repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
camillepaviot/TP-Jobeet-IMIE
src/Ens/JobeetBundle/Entity/User.php
1681
<?php namespace Ens\JobeetBundle\Entity; use Symfony\Component\Security\Core\User\UserInterface; use Doctrine\ORM\Mapping as ORM; /** * User */ class User implements UserInterface { /** * @var integer */ private $id; /** * @var string */ private $username; /** * @var string */ private $password; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set username * * @param string $username * @return User */ public function setUsername($username) { $this->username = $username; } /** * Get username * * @return string */ public function getUsername() { return $this->username; } /** * Set password * * @param string $password * @return User */ public function setPassword($password) { $this->password = $password; } /** * Get password * * @return string */ public function getPassword() { return $this->password; } /** * * @return type */ public function getRoles() { return array('ROLE_ADMIN'); } /** * * @return type */ public function getSalt() { return null; } public function eraseCredentials() { } /** * * @param \Ens\JobeetBundle\Entity\User $user * @return type */ public function equals(User $user) { return $user->getUsername() == $this->getUsername(); } }
mit
pixel-stuff/ld_dare_32
Unity/ludum-dare-32-PixelStuff/Assets/Scripts/Beavers/Beaver.cs
5143
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public enum BeaverState{ Spawning, Running, HangOnTree, Smashed, Flying } public class Beaver : MonoBehaviour { [SerializeField] private GameObject m_idleSprite; [SerializeField] private GameObject m_eatSprite; [SerializeField] private GameObject m_ejectSprite; [SerializeField] private GameObject m_smashSprite; public Action<Beaver> destroyListener; [SerializeField] private BeaverState m_currentState = BeaverState.Spawning; [SerializeField] private int m_life = 100; [SerializeField] private Animation m_BeaversAnimations; [SerializeField] private EndFlyingAnimation m_endAnimationScript; private treeManager m_treeManager; float m_timeBetweenDamage = 1; Vector3 m_beaverSpeedRunning = new Vector3 (); Vector3 m_decalageHangOnTree = new Vector3 (); GameObject m_treeToHang; public void Initialize(treeManager treeManager){ m_treeManager = treeManager; m_currentState= BeaverState.Running; m_beaverSpeedRunning = new Vector3(UnityEngine.Random.Range(this.transform.lossyScale.x/40,this.transform.lossyScale.x/20)*1.6f,0f,0f); m_decalageHangOnTree = new Vector3 (UnityEngine.Random.Range (-1.0f, 0.5f), UnityEngine.Random.Range (-0.3f, 0.3f), 0f); m_endAnimationScript.endFlyingAnimationAction += endFlyingAnimationListener; } void Start(){ AudioManager audioMan = GameObject.FindGameObjectWithTag("AudioManager").GetComponent<AudioManager>(); // TODO : Changer l'audio à la création du castor //audioMan.Play("Bwaaa"); } private float m_timeFlyStateBegin; private float m_timeSmashStateBegin; // Update is called once per frame void Update () { AudioManager audioMan = GameObject.FindGameObjectWithTag("AudioManager").GetComponent<AudioManager>(); switch (m_currentState) { case BeaverState.Running: this.transform.localPosition -= m_beaverSpeedRunning; if (this.transform.localPosition.x <= -20f) { Destroy (this.gameObject); } break; case BeaverState.HangOnTree: m_timeBetweenDamage += Time.deltaTime; if(m_timeBetweenDamage >= 1.0f){ //m_life = m_life - 15; m_timeBetweenDamage = Time.deltaTime; m_treeManager.currentWeapon.GetComponent<weaponTree>().isNomNom(); //audioMan.Play("beaver_eat"); } if(m_treeToHang != null){ Vector3 newpos = m_treeToHang.transform.position + m_decalageHangOnTree; this.gameObject.transform.position = newpos; } if(m_life <= 0){ Destroy(this.gameObject); //changeState (BeaverState.Flying); } break; case BeaverState.Smashed: //TO DO: Afficher Anim écrasé //Debug.Log ("Ecrasé"); if (this.transform.position.x <= -20f) { //audioMan.Play("beaver_death"); Destroy (this.gameObject); } if(Time.time - m_timeSmashStateBegin >= 5){ //audioMan.Play("beaver_death"); Destroy (this.gameObject); } break; case BeaverState.Flying: //TO DO: Lancer anim d'envole du beaver <3 if(Time.time - m_timeFlyStateBegin >= 5){ Destroy (this.gameObject); } break; default: break; } } void OnDestroy(){ if (destroyListener != null) { destroyListener(this); } } void OnTriggerEnter2D(Collider2D collider){ if ((collider.gameObject.tag == "Trunk" || collider.gameObject.tag == "SmashTree") && m_currentState != BeaverState.HangOnTree) { changeState(BeaverState.Smashed); m_life = 0; this.gameObject.GetComponent<FollowingGroundSpeed>().enabled = true; return; } if (collider.gameObject.tag == "WeaponTree") { if( UnityEngine.Random.Range(0.0f,1.0f) <= 0.1f){ changeState(BeaverState.Smashed); m_life = 0; this.gameObject.GetComponent<FollowingGroundSpeed>().enabled = true; }else{ changeState(BeaverState.HangOnTree); m_treeToHang = collider.gameObject; Vector3 newpos = m_treeToHang.transform.position + m_decalageHangOnTree; this.gameObject.transform.position = newpos; } return; } } private void endFlyingAnimationListener(){ Destroy (this.gameObject); } public void changeState(BeaverState state){ m_currentState = state; resetImage (); switch (m_currentState) { case BeaverState.Running: m_idleSprite.SetActive (true); break; case BeaverState.HangOnTree: m_eatSprite.SetActive (true); break; case BeaverState.Smashed: m_smashSprite.SetActive (true); //Debug.Log("ISSAMSH"); m_smashSprite.GetComponentInChildren<ParticleSystem>().Play(); m_timeSmashStateBegin = Time.time; this.gameObject.GetComponent<BoxCollider2D>().enabled = false; break; case BeaverState.Flying: m_ejectSprite.SetActive (true); m_BeaversAnimations.Play(); m_timeFlyStateBegin = Time.time; this.gameObject.GetComponent<BoxCollider2D>().enabled = false; break; default: m_idleSprite.SetActive(true); break; } } private void resetImage(){ m_idleSprite.SetActive (false); m_eatSprite.SetActive (false); m_ejectSprite.SetActive (false); } public BeaverState getCurrentState(){ return m_currentState; } }
mit
eric-appeagle/appeagle-redoc-demo
node_modules/redoc/dist/utils/browser-adapter.d.ts
739
export declare class BrowserDomAdapter { static query(selector: string): any; static querySelector(el: any, selector: string): HTMLElement; static onAndCancel(el: any, evt: any, listener: any): Function; static attributeMap(element: any): Map<string, string>; static setStyle(element: any, styleName: string, styleValue: string): void; static removeStyle(element: any, stylename: string): void; static getStyle(element: any, stylename: string): string; static hasStyle(element: any, styleName: string, styleValue?: string): boolean; static hasAttribute(element: any, attribute: string): boolean; static getAttribute(element: any, attribute: string): string; static defaultDoc(): HTMLDocument; }
mit
asukakenji/pokemon-go
eff/internal/zh-CN/effectiveness_string.go
440
// Code generated by "stringer -type=Effectiveness"; DO NOT EDIT package zhCN import "fmt" const _Effectiveness_name = "无效不佳普通超群" var _Effectiveness_index = [...]uint8{0, 6, 12, 18, 24} func (i Effectiveness) String() string { if i < 0 || i >= Effectiveness(len(_Effectiveness_index)-1) { return fmt.Sprintf("Effectiveness(%d)", i) } return _Effectiveness_name[_Effectiveness_index[i]:_Effectiveness_index[i+1]] }
mit
chikara-chan/full-stack-javascript
manager/server/routes/order.js
480
import Router from 'koa-router' import order from '../controllers/order' import checkLogin from '../middlewares/checkLogin' const router = new Router({prefix: '/order'}) router.use(checkLogin) router.post('/sendOrder', order.sendOrder) router.post('/setOrder', order.setOrder) router.post('/rejectOrder', order.rejectOrder) router.post('/receiveOrder', order.receiveOrder) router.get('/getOrders', order.getOrders) router.get('/getOrder', order.getOrder) export default router
mit
SquidDev/luaj.luajc
src/test/resources/org/squiddev/luaj/luajc/fragment/LoadedNilUpvalue.lua
163
local function execute() local a = print() local b = c and { d = e } local f local function g() return f end return g() end assertEquals(nil, execute())
mit
amjacobowitz/classroom-library
classroom-library/db/schema.rb
3764
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20150729155709) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "authors", force: true do |t| t.string "first_name" t.string "last_name" t.datetime "created_at" t.datetime "updated_at" end create_table "favorite_authors", force: true do |t| t.integer "student_id" t.integer "author_id" t.boolean "favorite", default: false t.datetime "created_at" t.datetime "updated_at" end create_table "favorite_genres", force: true do |t| t.integer "student_id" t.integer "genre_id" t.boolean "favorite", default: false t.datetime "created_at" t.datetime "updated_at" end create_table "genres", force: true do |t| t.string "category" t.datetime "created_at" t.datetime "updated_at" end create_table "groups", force: true do |t| t.string "name" t.string "grouping" t.integer "teacher_id" t.datetime "created_at" t.datetime "updated_at" end create_table "klasses", force: true do |t| t.integer "teacher_id" t.integer "klass_number" t.integer "school_year" t.integer "grade" t.datetime "created_at" t.datetime "updated_at" end create_table "quotes", force: true do |t| t.string "content" t.string "source" t.datetime "created_at" t.datetime "updated_at" end create_table "schools", force: true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end create_table "student_texts", force: true do |t| t.integer "student_id" t.integer "text_id" t.integer "rating" t.boolean "favorite", default: false t.boolean "checked_out", default: false t.boolean "completed", default: false t.boolean "abandoned", default: false t.string "reason_for_abandoning", default: "" t.string "review_title", default: "" t.string "review_content", default: "" t.datetime "created_at" t.datetime "updated_at" end create_table "students", force: true do |t| t.string "first_name" t.string "last_name" t.string "password" t.string "handle" t.integer "klass_number" t.integer "lexile_level" t.integer "klass_id" t.datetime "created_at" t.datetime "updated_at" end create_table "teachers", force: true do |t| t.string "prefix" t.string "first_name" t.string "last_name" t.string "email" t.string "password_digest" t.boolean "admin" t.integer "school_id" t.datetime "created_at" t.datetime "updated_at" end create_table "texts", force: true do |t| t.integer "isbn" t.integer "lexile_level" t.integer "pages" t.string "title" t.string "author" t.string "genre" t.string "classroom" t.datetime "created_at" t.datetime "updated_at" end end
mit
danbraik/cachalot2
MusicPlayer.cpp
5493
#include <iostream> #include <string> #include <stdio.h> #include "MusicPlayer.hpp" #include "AnimatedLabel.hpp" #include "Button.hpp" #include "Slider.hpp" #include "Label.hpp" #include <libgen.h> std::string basename(std::string path) { int pos = path.find_last_of('/'); return path.substr(pos+1); } MusicPlayer::MusicPlayer(const std::string & guiTexturePath, const std::string & fontPath) : mGuiTexture(), mClock(), mMusic(0), mIsMusicValid(), mOffset(0), mOut_offset(&mOffset), mLabelFont(), mThreadChangeOffset(), mThreadParameter(0), mIsChangingOffset(false), mAnimatedLabel(0), mButtonPlay(0), mButtonPause(0), mSlider(0), mLabel(0) { // Construct GUI mGuiTexture.loadFromFile(guiTexturePath); mLabelFont.loadFromFile(fontPath); mAnimatedLabel = new gui::AnimatedLabel(mLabelFont); mAnimatedLabel->setLayout(sf::IntRect(64,0,256-8,64)); mAnimatedLabel->setString("Loading ..."); mButtonPlay = new gui::Button(mGuiTexture, sf::IntRect(0,0,64,64), sf::IntRect(0,64,64,64), sf::IntRect(0,128,64,64) ); mButtonPlay->setEnable(false); mButtonPause = new gui::Button (mGuiTexture, sf::IntRect(64,0,64,64), sf::IntRect(64,64,64,64), sf::IntRect(64,128,64,64) ); mSlider = new gui::Slider(); mSlider->setLayout(sf::IntRect(8,64+4,256-16-8,16)); mSlider->setEnable(false); mLabel = new gui::Label(mLabelFont, sf::IntRect(256-16+16-8,64-16+4+4,64,16)); mLabel->setString("...?"); } sf::Vector2u MusicPlayer::getSize() const { return sf::Vector2u(256+64, 64+16+8+8); } bool MusicPlayer::play(const std::string &filepath, float & io_offset) { // Load music mMusic = new sf::Music(); mIsMusicValid = mMusic->openFromFile(filepath); if (!mIsMusicValid) { delete mMusic; mAnimatedLabel->setString(sf::String("Loading music error ! File : " + filepath)); return false; } float musicDuration = mMusic->getDuration().asSeconds(); // Set playing offset if (io_offset < 0 || io_offset >= musicDuration) io_offset = 0; mOut_offset = &io_offset; //mMusic.setPlayingOffset(sf::seconds(io_offset)); mSlider->setEnable(true); mButtonPlay->setEnable(true); // Update GUI mAnimatedLabel->setString(sf::String( basename(filepath) )); mAnimatedLabel->setLoop(true); // max should be inferior at real duration mSlider->setMax(musicDuration - 1); mClock.restart(); // Play music mMusic->play(); changeMusicOffset(io_offset); return true; } void MusicPlayer::toggle() { if (mIsMusicValid && !mIsChangingOffset) { if (mMusic->getStatus() == sf::Music::Playing) mMusic->pause(); else mMusic->play(); } } void MusicPlayer::changeMusicOffset(float sliderUserValue) { if (!mIsChangingOffset) { mIsChangingOffset = true; mThreadParameter = sliderUserValue; if (mThreadChangeOffset) delete mThreadChangeOffset; // will wait mThreadChangeOffset = new sf::Thread(&MusicPlayer::innerChangeMusicOffset, this); mThreadChangeOffset->launch(); //mThreadChangeOffset->wait(); } } void MusicPlayer::innerChangeMusicOffset() { //std::cout << "!!!!!" << std::endl; mMusic->setPlayingOffset(sf::seconds(mThreadParameter)); mIsChangingOffset = false; } std::string MusicPlayer::getReadableMusicOffset(const sf::Time & offset) { int time_s = static_cast<int>(offset.asSeconds()); int hours = time_s / 3600; time_s -= 3600 * hours; int minutes = time_s / 60; time_s -= 60 * minutes; int seconds = time_s; char * c_str = new char[64]; if (hours > 0) sprintf(c_str, "%d:%02d:%02d", hours, minutes, seconds); else sprintf(c_str, "%d:%02d", minutes, seconds); return std::string(c_str); } void MusicPlayer::update(const sf::Vector2f & mousePosition, bool leftMouseButtonPressed) { const sf::Time elapsed = mClock.restart(); /// TITLE MUSIC LABEL mAnimatedLabel->update(elapsed); /// PLAY BUTTON if (mButtonPlay->update(mousePosition, leftMouseButtonPressed)) { if (mMusic->getStatus() != sf::Music::Playing && !mIsChangingOffset) mMusic->play(); } /// PAUSE BUTTON if (mButtonPause->update(mousePosition, leftMouseButtonPressed)) { mMusic->pause(); } /// MUSIC TIME SLIDER float sliderUserValue = *mOut_offset = mMusic->getPlayingOffset().asSeconds(); if (mSlider->update(mousePosition, leftMouseButtonPressed, sliderUserValue)) { // std::cout << sliderUserValue << std::endl; changeMusicOffset(sliderUserValue); } if (!mIsChangingOffset) mSlider->setValue(sliderUserValue); /// MUSIC TIME LABEL if (mIsMusicValid) mLabel->setString(sf::String(getReadableMusicOffset( mMusic->getDuration() - mMusic->getPlayingOffset()))); /// OTHER UPDATES // Binding with music status mButtonPlay->setVisible(mMusic->getStatus() != sf::Music::Playing); mButtonPause->setVisible(mMusic->getStatus() == sf::Music::Playing); if (mIsMusicValid) mAnimatedLabel->setLoop(mMusic->getStatus() == sf::Music::Playing); } MusicPlayer::~MusicPlayer() { delete mAnimatedLabel; delete mButtonPlay; delete mButtonPause; delete mSlider; delete mLabel; if (mThreadChangeOffset) delete mThreadChangeOffset; // will wait if (mMusic) delete mMusic; } void MusicPlayer::draw(sf::RenderTarget &target, sf::RenderStates states) const { target.draw(*mAnimatedLabel); target.draw(*mButtonPlay); target.draw(*mButtonPause); target.draw(*mSlider); target.draw(*mLabel); }
mit
dylnslck/micrograph
test/helpers/models/Blog.js
799
import db from '../database'; import User from './User'; export default class Blog { constructor(data) { this.id = data.id; this.title = data.title; this.content = data.content; this.authorId = data.author; } static getall() { return db().getAll('blog') .then(({ data }) => data.map(blog => new Blog(blog))); } static get(args) { return db().get('blog', args.id) .then(res => new Blog(res)); } static create(args) { const id = `${Date.now()}`; const input = { ...args.input, id, }; return db().set('blog', id, input) .then(res => res.data) .then(blog => new Blog(blog)); } author() { return db().get('user', this.authorId) .then(res => res.data) .then(user => new User(user)); } }
mit
lukkos/vCard
src/Lukkos/VCardBundle/DependencyInjection/LukkosVCardExtension.php
881
<?php namespace Lukkos\VCardBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class LukkosVCardExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } }
mit
yogeshsaroya/new-cdnjs
ajax/libs/angular-i18n/1.0.7/angular-locale_es-ve.js
129
version https://git-lfs.github.com/spec/v1 oid sha256:598c0b5883d1fef82ebe72340224afa454e467141a6c76aa3aa1c83405333737 size 2176
mit
catarse/catarse
db/migrate/20170928160527_remove_address_fields.rb
1194
class RemoveAddressFields < ActiveRecord::Migration def change execute <<-SQL alter table contributions drop column address_city; alter table contributions drop column address_complement; alter table contributions drop column address_street; alter table contributions drop column address_number ; alter table contributions drop column address_state ; alter table contributions drop column address_phone_number ; alter table contributions drop column address_neighbourhood ; alter table contributions drop column address_zip_code ; alter table contributions drop column country_id ; alter table users drop column address_city; alter table users drop column address_street; alter table users drop column address_complement; alter table users drop column address_number ; alter table users drop column address_state ; alter table users drop column phone_number ; alter table users drop column address_neighbourhood ; alter table users drop column address_zip_code ; alter table users drop column country_id ; alter table users drop column address_country ; SQL end end
mit
codenothing/Nlint
lib/FileResult.js
1683
var Nlint = global.Nlint; function FileResult( path ) { var self = this; if ( ! ( this instanceof FileResult ) ) { return new FileResult( path ); } self.path = path; self.passed = false; self.errors = []; self.warnings = []; self.times = []; } FileResult.prototype = { addResults: function( errors, warnings, times, linter ) { var self = this; // Add timestamp results self.times.push( times ); // Validate all errors and warnings [ errors, warnings ].forEach(function( list ) { var type = list === errors ? 'errors' : 'warnings'; // Nothing returned if ( ! list ) { return; } // If an array isn't returned, block it else if ( ! Nlint.isArray( list ) ) { throw new Error( linter + " didn't return an array for " + type + " [" + self.path + "]" ); } // Validate each individual object list.forEach(function( value ) { self.validate( value, linter, type ); self[ type ].push( value ); }); }); // Mark passed state based on # of errors/warnings self.passed = self.errors.length === 0 && self.warnings.length === 0; }, // Error/Warning validation validate: function( value, linter, type ) { var self = this; if ( ! value.message ) { throw new Error( linter + " didn't return a message for " + type + " [" + self.path + "]" ); } else if ( ! Nlint.isNumber( value.line ) ) { throw new Error( linter + " didn't return a line number for " + type + " [" + self.path + "]" ); } else if ( ! Nlint.isNumber( value.character ) ) { throw new Error( linter + " didn't return a character number for " + type + " [" + self.path + "]" ); } } }; // Expose Nlint.FileResult = FileResult;
mit
jwagner/smartcrop.js
karma.conf.js
3149
// Karma configuration // Generated on Mon Jun 27 2016 18:36:52 GMT+0200 (CEST) module.exports = function(config) { var launchers = { sauceChromeLatest: { base: 'SauceLabs', browserName: 'chrome', platform: 'Windows 10', version: 'latest' }, sauceFirefoxLatest: { base: 'SauceLabs', browserName: 'firefox', platform: 'Windows 10', version: 'latest' }, sauceIE: { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 8.1', version: '11' }, sauceEdge: { base: 'SauceLabs', browserName: 'MicrosoftEdge', platform: 'Windows 10', version: 'latest' }, sauceSafari: { base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.11', version: 'latest' } // sl_firefox: { // base: 'SauceLabs', // browserName: 'firefox', // version: '30' // }, // sl_ios_safari: { // base: 'SauceLabs', // browserName: 'iphone', // platform: 'OS X 10.9', // version: '7.1' // }, // sl_ie_11: { // base: 'SauceLabs', // browserName: 'internet explorer', // platform: 'Windows 8.1', // version: '11' // } }; 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: ['mocha'], // list of files / patterns to load in the browser files: [ 'node_modules/promise-polyfill/dist/polyfill.js', 'node_modules/chai/chai.js', 'smartcrop.js', 'test/smartcrop.js', { pattern: 'examples/images/flickr/kitty.jpg', included: false, served: true } ], proxies: { '/examples/images/': '/base/examples/images/' }, // 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', 'saucelabs'], // 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: Object.keys(launchers), customLaunchers: launchers, // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }); };
mit
pmark/AspenOS
aspenos.org/app/aoscontentserver/src/xml/SaxERTParser.java
5144
package org.aspenos.app.aoscontentserver.xml; import java.io.*; import java.util.*; import org.xml.sax.*; import org.xml.sax.helpers.*; import org.aspenos.app.aoscontentserver.defs.*; import org.aspenos.xml.*; // The ERT (Event-Resource-Template) Def has all the // info needs to set up the relationships between // events, resources and templates. public class SaxERTParser extends GenericSaxParser { private String _curRegistryGroup; private WebEventDefs _wedefs; private WebEventDef _curEvent; private ERTDefs _ertDefs; private ERTDef _curERT; private ResourceDefs _rdefs; private ResourceDef _curResource; private TemplateDefs _tdefs; private TemplateDef _curTemplate; private RoleDefs _roledefs; private RoleDef _curRole; private int _curOrdinal; public SaxERTParser(File f) throws SAXException, IOException { super(f); } public SaxERTParser(String xml) throws SAXException, IOException { super(xml); } //////////////////////////////////////////////////////////////// public ERTDefs getERTDefs() { return _ertDefs; } //////////////////////////////////////////////////////////////// public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException { HashMap hash = new HashMap(); String id; if(attrs != null) { for(int i = 0; i < attrs.getLength(); i++) { String attrib = attrs.getLocalName(i); String value = attrs.getValue(i); hash.put(attrib, value); } } if (localName.equals("ERTDef")) { _curRegistryGroup = (String)hash.get("registry_group"); _curERT = new ERTDef(hash); // Create a new webevent defs for this ert's webevents _wedefs = new WebEventDefs(); } else if (localName.equals("WebEventDef")) { _curEvent = new WebEventDef(hash); id = (String)hash.get("id"); if (id != null) _curEvent.setId(id); _wedefs.add(_curEvent); // Reset the ordinal counter _curOrdinal = 1; // Reset the parent's defs _curERT.setProperty("webevent_defs", _wedefs); // Create a new resource defs for this event's resources _rdefs = new ResourceDefs(); } else if (localName.equals("ResourceDef")) { _curResource = new ResourceDef(hash); id = (String)hash.get("id"); if (id != null) _curResource.setId(id); // count the ordinal _curResource.setProperty("ordinal", Integer.toString(_curOrdinal)); _curOrdinal++; _rdefs.add(_curResource); // Reset the parent's defs _curEvent.setProperty("resource_defs", _rdefs); // Create a new template defs for this resource's templates _tdefs = new TemplateDefs(); } else if (localName.equals("TemplateDef")) { _curTemplate = new TemplateDef(hash); id = (String)hash.get("id"); if (id != null) _curTemplate.setId(id); _tdefs.add(_curTemplate); // Reset the parent's defs _curResource.setProperty("template_defs", _tdefs); // Create a new role defs for this template's roles _roledefs = new RoleDefs(); } else if (localName.equals("RoleDef")) { _curRole = new RoleDef(hash); id = (String)hash.get("id"); if (id != null) _curRole.setId(id); _roledefs.add(_curRole); // Reset the parent's defs _curTemplate.setProperty("role_defs", _roledefs); } } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (localName.equals("ERTDef")) { if (_ertDefs == null) _ertDefs = new ERTDefs(); _ertDefs.add(_curERT); } } //////////////////////////////////////////////////////////////// public static void main(String args []) throws IOException { if(args.length != 1) { System.err.println("Usage: <XML filename>"); System.exit(1); } try { // THIS IS CRUCIAL!! // You must set the XML parser class here. System.setProperty("sax.parser.class", "org.apache.xerces.parsers.SAXParser"); System.setProperty("sax.parser.validating", "false"); // Run it with a File /////////////////////////// //SaxERTParser ertParser = new SaxERTParser(new File(args[0])); ///////////////////////////////////////////////// // Run it with a plain xml String /////////////// BufferedReader is = new BufferedReader( new FileReader(args[0])); StringBuffer in = new StringBuffer(); String curLine; while((curLine=is.readLine()) != null) in.append(curLine+"\n"); is.close(); System.out.println("parsing this: " + in.toString()); SaxERTParser ertParser = new SaxERTParser(in.toString()); ///////////////////////////////////////////////// String xml = ertParser.getERTDefs().toXML(); System.out.println("Ready to send ERTs to the registry:\n\n" + xml); } catch(SAXParseException err) { System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage()); } catch(SAXException e) { Exception x = e; if(e.getException() != null) x = e.getException(); x.printStackTrace(); } catch(Throwable t) { t.printStackTrace(); } System.exit(0); } }
mit
akaSybe/Disqus.NET
src/Disqus.NET/Requests/DisqusBlacklistRemoveRequest.cs
2130
using System.Collections.Generic; using System.Linq; namespace Disqus.NET.Requests { public class DisqusBlacklistRemoveRequest : DisqusRequestBase { private DisqusBlacklistRemoveRequest(string forum) { Parameters.Add(new KeyValuePair<string, string>("forum", forum)); } public static DisqusBlacklistRemoveRequest New(string forum) { return new DisqusBlacklistRemoveRequest(forum); } public DisqusBlacklistRemoveRequest Domain(params string[] domains) { var parameters = domains.Select(domain => new KeyValuePair<string, string>("domain", domain)); Parameters.AddRange(parameters); return this; } public DisqusBlacklistRemoveRequest Word(params string[] words) { var parameters = words.Select(word => new KeyValuePair<string, string>("word", word)); Parameters.AddRange(parameters); return this; } public DisqusBlacklistRemoveRequest IpAddress(params string[] ipAddresses) { var parameters = ipAddresses.Select(ipAddress => new KeyValuePair<string, string>("ip", ipAddress)); Parameters.AddRange(parameters); return this; } public DisqusBlacklistRemoveRequest User(params int[] users) { var parameters = users.Select(user => new KeyValuePair<string, string>("user", user.ToString())); Parameters.AddRange(parameters); return this; } public DisqusBlacklistRemoveRequest User(params string[] usernames) { var parameters = usernames.Select(username => new KeyValuePair<string, string>("user:username", username)); Parameters.AddRange(parameters); return this; } public DisqusBlacklistRemoveRequest Email(params string[] emails) { var parameters = emails.Select(email => new KeyValuePair<string, string>("email", email)); Parameters.AddRange(parameters); return this; } } }
mit
Nitee/ViewNet
TestConsole/Program.cs
1219
using System; using ViewNet; using System.Net; using System.Threading; namespace TestConsole { class MainClass { [STAThread] public static void Main () { Thread.CurrentThread.Name = "Main Thread"; TestServiceManager (); } public static void TestServiceManager () { var selector = new IPEndPoint (IPAddress.Loopback, 3333); var server = new DomainManager (); server.StartHosting (selector.Address, selector.Port); var client = new DomainManager (); client.ConnectToHost (selector.Address, selector.Port); var checkSystem = new FullSystemMonitor (); client.AddServiceToNode (selector, checkSystem); var timer = new System.Timers.Timer (); timer.AutoReset = true; timer.Enabled = true; timer.Interval = 1000; timer.Elapsed += (sender, e) => { checkSystem.SendCPUInformation(); checkSystem.PingToRemoteComputer(); Console.WriteLine("Ping: {0}", checkSystem.RemoteComputerPing.PingRate); Console.WriteLine("CPU: {0}", checkSystem.RemoteComputerCPU.CpuTick); }; timer.Start (); bool isActive = true; while (isActive) { Console.CancelKeyPress += (sender, e) => isActive = false; Thread.Sleep (0); } timer.Stop (); } } }
mit
drazenzadravec/projects
nice/sdk/json/Skills/TSGetDeliveryPreferencesConfigurationSkillRequest.ts
89
export var GetDeliveryPreferencesConfigurationSkillRequest_Skills = { "fields": "" };
mit
fallfromgrace/More.Net
More.Net/Data/IRepositoryService.cs
466
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace More.Net.Data { ///// <summary> ///// ///// </summary> //public interface IRepositoryService //{ // /// <summary> // /// // /// </summary> // /// <typeparam name="TEntity"></typeparam> // /// <returns></returns> // IRepository<TEntity> GetRepository<TEntity>(); //} }
mit
dev1x-org/python-example
lib/config/factory.py
403
#coding:utf-8 class ConfigFactory(object): @staticmethod def createSystemConfig(): from system import SystemConfig return SystemConfig() @staticmethod def createViewConfig(): from view import ViewConfig return ViewConfig() @staticmethod def createTemplateConfig(): from template import TemplateConfig return TemplateConfig()
mit
HimariO/VideoSum
tasks/video/dataset/rename.py
431
import os import re feat_files = [re.match('features_(\d+)_(\d+)\\\.npy', f) for f in os.listdir(path='./')] feat_files_tup = [] for f in feat_files: if f is not None: feat_files_tup.append((f.string, int(f.group(1)), int(f.group(2)))) # (file_name, start_id, end_id) feat_files_tup.sort(key=lambda x: x[1]) # sort by start data id. for f in feat_files_tup: os.rename(f[0], 'features_%d_%d.npy' % (f[1], f[2]))
mit
htchepannou/academy-service
src/main/java/io/tchepannou/academy/dao/QuizTypeDao.java
221
package io.tchepannou.academy.dao; import io.tchepannou.academy.domain.QuizType; import org.springframework.stereotype.Repository; @Repository public interface QuizTypeDao extends PersistentEnumRepository<QuizType> { }
mit
ICShapy/shapy
client/js/notification.js
5566
// This file is part of the Shapy project. // Licensing information can be found in the LICENSE file. // (C) 2015 The Shapy Team. All rights reserved. goog.provide('shapy.notification.Service'); goog.provide('shapy.notification.notifyBar'); /** * Notification service, brokers messages between the display and clients. * * @constructor * * @param {!angular.$timeout} $timeout */ shapy.notification.Service = function($timeout) { /** * Angular timeout service. * @private {!angular.$timeout} @const */ this.timeout_ = $timeout; /** * List of notifications. */ this.notifications = []; }; /** * Adds a new notification. * * @private * * @param {!shapy.notification.Type_} type Type of the notification. * @param {Object} data * * @return {Function} */ shapy.notification.Service.prototype.add_ = function(type, data) { var item = new shapy.notification.Notification_(type, data); this.notifications.push(item); if (data.dismiss > 0) { this.timeout_(goog.bind(function() { item.fade = true; this.timeout_(goog.bind(function() { this.remove(item); }, this), 1000); }, this), data.dismiss); } return goog.bind(function() { item.fade = true; this.timeout_(goog.bind(function() { this.remove(item); }, this), 2000); }, this); }; /** * Removes a notification. * * @param {!shapy.notification.Notification} notif Notification to be removed. * * @return {Function} */ shapy.notification.Service.prototype.remove = function(notif) { return this.notifications.splice(this.notifications.indexOf(notif), 1); }; /** * Adds a new notice. * * @param {Object} data * * @return {Function} */ shapy.notification.Service.prototype.warning = function(data) { return this.add_(shapy.notification.Type_.WARNING, data); }; /** * Adds a new error. * * @param {Object} data * * @return {Function} */ shapy.notification.Service.prototype.error = function(data) { return this.add_(shapy.notification.Type_.ERROR, data); }; /** * Adds a new notice. * * @param {Object} data * * @return {Function} */ shapy.notification.Service.prototype.notice = function(data) { return this.add_(shapy.notification.Type_.NOTICE, data); }; /** * Object containing information about a notification. * * @constructor * @private * * @param {shapy.Notification.Type_} type Type of the notification. * @param {Object} data */ shapy.notification.Notification_ = function(type, data) { /** * Type of the notification. * @public {shapy.notification.Type_} @const */ this.type = type; /** * Link to show on the notification. * @public {string} @const */ this.link = data.link; /** * Text to display. * @public {string} @const */ this.text = data.text || 'Missing text'; /** * Callback on click. * @public {Function} @const */ this.click = data.click || null; /** * True if a cancel button is shown. * @public {boolean} @const */ this.dismiss = data.dismiss || false; /** * True if the animation is being removed, fading out. * @public {boolean} */ this.fade = false; }; /** * Enumeration of notification types. * * @private * @enum {string} */ shapy.notification.Type_ = { WARNING: 'warning', ERROR: 'error', NOTICE: 'notice' }; /** * Controller for the notification display. * * @constructor * * @private * * @param {shapy.notification.Service} shNotify Angular notification service. * @param {!angular.$location} $location Angular location service. */ shapy.notification.Controller_ = function(shNotify, $location) { /** * Angular location service. * @private {!angular.$location} * @const */ this.location_ = $location; /** * Notification service. * @private {!shapy.notification.Service} * @const */ this.shNotify_ = shNotify; /** * List of notifications to display. * @public {!Array<!shapy.notification.Notification_>} * @expose * @const */ this.notifications = shNotify.notifications; }; /** * Redirects to the notification link. * * @param {!shapy.notification.Notification_} notif Notification to follow. */ shapy.notification.Controller_.prototype.click = function(notif) { this.shNotify_.remove(notif); this.location_.path(notif.link); }; /** * Dismisses a notification. * * @param {!shapy.notification.Notification_} notif Notification to hide. */ shapy.notification.Controller_.prototype.dismiss = function(notif) { this.shNotify_.remove(notif); }; /** * Notification bar directive, displays stuff. * * @return {!angular.Directive} */ shapy.notification.notifyBar = function() { return { restrict: 'E', template: '<div ng-show="notifyCtrl.notifications">' + '<div '+ 'ng-repeat="notif in notifyCtrl.notifications" '+ 'class="notification">' + '<span class="{{ notif.type }}" ng-class="{ fade: notif.fade }" >' + '<a ' + 'class="content"' + 'ng-show="notif.link" ' + 'ng-click="notifyCtrl.click(notif)">' + '{{ notif.text }}' + '</a>' + '<span ' + 'class="content"' + 'ng-hide="notif.link" ' + 'ng-click="notifyCtrl.dismiss(notif)">' + '{{ notif.text }}' + '</span>' + '</span>' + '</div>' + '</div>', controllerAs: 'notifyCtrl', controller: shapy.notification.Controller_ }; };
mit
IowaComputerGurus/icg.dnn.quiz
ICGDNNQuiz/Components/InfoObjects/QuizNotificationInfo.cs
889
namespace ICG.Modules.DnnQuiz.Components.InfoObjects { /// <summary> /// Used for notifications /// </summary> public class QuizNotificationInfo : UserQuizDisplay { /// <summary> /// Gets or sets the user id. /// </summary> /// <value>The user id.</value> public int UserId { get; set; } /// <summary> /// Gets or sets the first name. /// </summary> /// <value>The first name.</value> public string FirstName { get; set; } /// <summary> /// Gets or sets the last name. /// </summary> /// <value>The last name.</value> public string LastName { get; set; } /// <summary> /// Gets or sets the email. /// </summary> /// <value>The email.</value> public string Email { get; set; } } }
mit
codedstructure/rpcpdb
rpcpdb/xmlrpc_client.py
247
#!/usr/bin/env python -u import xmlrpclib import time s = xmlrpclib.ServerProxy('http://localhost:8000') # Print list of available methods print(s.system.listMethods()) p = 0 while True: time.sleep(0.5) p = s.next_prime(p) print(p)
mit
kpnlora/LoRaClient
src/Kpn.LoRa.Api.Stub/src/Kpn.LoRa.Api.Stub/Models/Subscription.cs
167
using System; using System.Collections.Generic; using System.Linq; namespace Kpn.LoRa.Api.Stub.Models.Subscription { public class subscription { } }
mit
phuongdm1987/bds
config/entrust.php
3114
<?php /** * This file is part of Entrust, * a role & permission management solution for Laravel. * * @license MIT * @package Zizaco\Entrust */ return [ /* |-------------------------------------------------------------------------- | Entrust Role Model |-------------------------------------------------------------------------- | | This is the Role model used by Entrust to create correct relations. Update | the role if it is in a different namespace. | */ 'role' => 'Bds\Hocs\Roles\Role', /* |-------------------------------------------------------------------------- | Entrust Roles Table |-------------------------------------------------------------------------- | | This is the roles table used by Entrust to save roles to the database. | */ 'roles_table' => 'roles', /* |-------------------------------------------------------------------------- | Application User Model |-------------------------------------------------------------------------- | | This is the User model used by Entrust to create correct relations. | Update the User if it is in a different namespace. | */ 'user' => 'Bds\Hocs\Users\User', /* |-------------------------------------------------------------------------- | Application Users Table |-------------------------------------------------------------------------- | | This is the users table used by the application to save users to the | database. | */ 'users_table' => 'users', /* |-------------------------------------------------------------------------- | Entrust Permission Model |-------------------------------------------------------------------------- | | This is the Permission model used by Entrust to create correct relations. | Update the permission if it is in a different namespace. | */ 'permission' => 'Bds\Hocs\Permissions\Permission', /* |-------------------------------------------------------------------------- | Entrust Permissions Table |-------------------------------------------------------------------------- | | This is the permissions table used by Entrust to save permissions to the | database. | */ 'permissions_table' => 'permissions', /* |-------------------------------------------------------------------------- | Entrust permission_role Table |-------------------------------------------------------------------------- | | This is the permission_role table used by Entrust to save relationship | between permissions and roles to the database. | */ 'permission_role_table' => 'permission_role', /* |-------------------------------------------------------------------------- | Entrust role_user Table |-------------------------------------------------------------------------- | | This is the role_user table used by Entrust to save assigned roles to the | database. | */ 'role_user_table' => 'role_user', ];
mit
jstafford1992/snekTrakr
routes/weight.js
1167
'use strict'; const express = require('express'); const router = express.Router(); const knex = require('../db/knex'); //get weight by ID router.get('/:id', function(req, res, next){ knex('weight') .select('*') .where('snake_id', req.params.id) .then(function(data){ console.log(data); res.json(data); }) .catch(function(err){ console.log(err); res.status(500).json({ err:err }); }); }); //add new weight data router.post('/', function(req, res, next){ console.log(req.body); knex('weight') .insert({ snake_id: req.body.snake_id, weight: req.body.weight, date_weighed: req.body.date_weighed }) .then(function(data){ console.log(data); res.json(data); }) .catch(function(err){ console.log(err); res.status(500).json({ err:err }); }); }); //delete Weight data router.delete('/:id', function(req, res, next){ knex('weight') .where('id', req.params.id) .del() .then(function(data){ console.log(data); res.json(data); }) .catch(function(err){ console.log(err); res.status(500).json({ err:err }); }); }); module.exports = router;
mit
redelivre/qr-pdf
formats.php
10031
<?php $pageFormats = array( '10R' => array(254, 305), '4P' => array(254, 305), '11R' => array(279, 356), '12R' => array(305, 381), '12SHEET' => array(3048, 1524), '16SHEET' => array(2032, 3048), '2A0' => array(1189, 1682), '32SHEET' => array(4064, 3048), '3R' => array(89, 127), 'L' => array(89, 127), '48SHEET' => array(6096, 3048), '4A0' => array(1682, 2378), '4D' => array(120, 152), '4R' => array(102, 152), 'KG' => array(102, 152), '4SHEET' => array(1016, 1524), '5R' => array(127, 178), '2L' => array(127, 178), '64SHEET' => array(8128, 3048), '6R' => array(152, 203), '8P' => array(152, 203), '6SHEET' => array(1200, 1800), '8R' => array(203, 254), '6P' => array(203, 254), '96SHEET' => array(12192, 3048), 'A0' => array(841, 1189), 'A10' => array(26, 37), 'A11' => array(18, 26), 'A12' => array(13, 18), 'A1' => array(594, 841), 'A2' => array(420, 594), 'A2_EXTRA' => array(445, 619), 'A3' => array(297, 420), 'A3+' => array(329, 483), 'A3_EXTRA' => array(322, 445), 'A3_SUPER' => array(305, 508), 'A4' => array(210, 297), 'A4_EXTRA' => array(235, 322), 'A4_LONG' => array(210, 348), 'A4_SUPER' => array(229, 322), 'A5' => array(148, 210), 'A5_EXTRA' => array(173, 235), 'A6' => array(105, 148), 'A7' => array(74, 105), 'A8' => array(52, 74), 'A9' => array(37, 52), 'ANNENV_A10' => array(159, 244), 'ANNENV_A2' => array(111, 146), 'ANNENV_A6' => array(121, 165), 'ANNENV_A7' => array(133, 184), 'ANNENV_A8' => array(140, 206), 'ANNENV_SLIM' => array(98, 225), 'ANSI_A' => array(216, 279), 'ANSI_B' => array(279, 432), 'ANSI_C' => array(432, 559), 'ANSI_D' => array(559, 864), 'ANSI_E' => array(864, 1118), 'ARCH_A' => array(229, 305), 'ARCH_B' => array(305, 457), 'ARCH_C' => array(457, 610), 'BROADSHEET' => array(457, 610), 'ARCH_D' => array(610, 914), 'ARCH_E1' => array(762, 1067), 'ARCH_E' => array(914, 1219), 'B0' => array(1000, 1414), 'B10' => array(31, 44), 'B11' => array(22, 31), 'B12' => array(15, 22), 'B1' => array(707, 1000), 'B2' => array(500, 707), 'B3' => array(353, 500), 'B4' => array(250, 353), 'B5' => array(176, 250), 'B6' => array(125, 176), 'B7' => array(88, 125), 'B8' => array(62, 88), 'B9' => array(44, 62), 'BE_COLOMBIER' => array(620, 850), 'BE_COQUILLE' => array(430, 560), 'BE_DOUBLE_CARRE' => array(620, 920), 'BE_DOUBLE_POSTE' => array(435, 565), 'BE_ELEPHANT' => array(616, 770), 'BE_GRAND_AIGLE' => array(700, 1040), 'BE_GRAND_JESUS' => array(550, 730), 'BE_GRAND_MEDIAN' => array(460, 605), 'BE_JESUS' => array(540, 730), 'BE_LYS' => array(317, 397), 'BE_PETIT_AIGLE' => array(600, 840), 'BE_PETIT_MEDIAN' => array(415, 530), 'BE_POT' => array(307, 384), 'BE_PROPATRIA' => array(345, 430), 'BE_RAISIN' => array(500, 650), 'BE_ROSETTE' => array(270, 347), 'BE_RUCHE' => array(360, 460), 'BUSINESS_CARD_AU' => array(55, 90), 'BUSINESS_CARD_DK' => array(55, 90), 'BUSINESS_CARD_SE' => array(55, 90), 'BUSINESS_CARD_HK' => array(54, 90), 'BUSINESS_CARD_ISO216' => array(52, 74), 'BUSINESS_CARD_IT' => array(55, 85), 'BUSINESS_CARD_UK' => array(55, 85), 'BUSINESS_CARD_FR' => array(55, 85), 'BUSINESS_CARD_DE' => array(55, 85), 'BUSINESS_CARD_ES' => array(55, 85), 'BUSINESS_CARD_JP' => array(55, 91), 'BUSINESS_CARD_RU' => array(50, 90), 'BUSINESS_CARD_CZ' => array(50, 90), 'BUSINESS_CARD_FI' => array(50, 90), 'BUSINESS_CARD_HU' => array(50, 90), 'BUSINESS_CARD_IL' => array(50, 90), 'BUSINESS_CARD_US' => array(51, 89), 'BUSINESS_CARD_CA' => array(51, 89), 'C0' => array(917, 1297), 'C10' => array(28, 40), 'C11' => array(20, 28), 'C12' => array(14, 20), 'C1' => array(648, 917), 'C2' => array(458, 648), 'C3' => array(324, 458), 'C4' => array(229, 324), 'C5' => array(162, 229), 'C6' => array(114, 162), 'C76' => array(81, 162), 'C7' => array(81, 114), 'C8' => array(57, 81), 'C9' => array(40, 57), 'CATENV_N10_1/2' => array(229, 305), 'CATENV_N1' => array(152, 229), 'CATENV_N12_1/2' => array(241, 318), 'CATENV_N13_1/2' => array(254, 330), 'CATENV_N1_3/4' => array(165, 241), 'CATENV_N14_1/2' => array(292, 368), 'CATENV_N14_1/4' => array(286, 311), 'CATENV_N2' => array(165, 254), 'CATENV_N3' => array(178, 254), 'CATENV_N6' => array(191, 267), 'CATENV_N7' => array(203, 279), 'CATENV_N8' => array(210, 286), 'CATENV_N9_1/2' => array(216, 267), 'CATENV_N9_3/4' => array(222, 286), 'COMMENV_N10' => array(105, 241), 'COMMENV_N11' => array(114, 263), 'COMMENV_N12' => array(121, 279), 'COMMENV_N14' => array(127, 292), 'COMMENV_N6_1/4' => array(89, 152), 'COMMENV_N6_3/4' => array(92, 165), 'COMMENV_N8' => array(98, 191), 'COMMENV_N9' => array(98, 225), 'COMPACT' => array(108, 171), 'CREDIT_CARD' => array(54, 86), 'BUSINESS_CARD' => array(54, 86), 'BUSINESS_CARD_ISO7810' => array(54, 86), 'DL' => array(110, 220), 'E0' => array(879, 1241), 'E10' => array(27, 39), 'E11' => array(19, 27), 'E12' => array(13, 19), 'E1' => array(620, 879), 'E2' => array(440, 620), 'E3' => array(310, 440), 'E4' => array(220, 310), 'E5' => array(155, 220), 'E6' => array(110, 155), 'E7' => array(78, 110), 'E' => array(82, 120), 'E8' => array(55, 78), 'E9' => array(39, 55), 'EN_ANTIQUARIAN' => array(787, 1346), 'EN_ATLAS' => array(660, 864), 'EN_BRIEF' => array(343, 406), 'EN_CARTRIDGE' => array(533, 660), 'EN_COLOMBIER' => array(597, 876), 'EN_COPY_DRAUGHT' => array(406, 508), 'EN_CROWN' => array(381, 508), 'EN_DEMY' => array(445, 572), 'EN_DOUBLE_DEMY' => array(572, 902), 'EN_DOUBLE_ELEPHANT' => array(679, 1016), 'EN_DOUBLE_LARGE_POST' => array(533, 838), 'EN_DOUBLE_POST' => array(483, 775), 'EN_ELEPHANT' => array(584, 711), 'EN_EMPEROR' => array(1219, 1829), 'EN_FOOLSCAP' => array(343, 432), 'EN_GRAND_EAGLE' => array(730, 1067), 'EN_IMPERIAL' => array(559, 762), 'EN_LARGE_POST' => array(419, 533), 'EN_MEDIUM' => array(445, 584), 'EN_PINCHED_POST' => array(375, 470), 'EN_POST' => array(394, 489), 'EN_POTT' => array(318, 381), 'EN_PRINCESS' => array(546, 711), 'EN_ROYAL' => array(508, 635), 'EN_SHEET' => array(495, 597), 'EN_HALF_POST' => array(495, 597), 'EN_SMALL_FOOLSCAP' => array(337, 419), 'EN_SUPER_ROYAL' => array(483, 686), 'EXECUTIVE' => array(184, 267), 'MONARCH' => array(184, 267), 'F4' => array(210, 330), 'FOLIO' => array(216, 330), 'GOVERNMENTLEGAL' => array(216, 330), 'FOOLSCAP' => array(210, 330), 'FR_CARRE' => array(450, 560), 'FR_CAVALIER' => array(460, 620), 'FR_CLOCHE' => array(600, 800), 'FR_COLOMBIER_AFFICHE' => array(630, 900), 'FR_COQUILLE' => array(440, 560), 'FR_COURONNE' => array(360, 460), 'FR_DOUBLE_CARRE' => array(560, 900), 'FR_DOUBLE_CAVALIER' => array(620, 920), 'FR_DOUBLE_CLOCHE' => array(400, 600), 'FR_DOUBLE_COLOMBIER' => array(900, 1260), 'FR_DOUBLE_COQUILLE' => array(560, 880), 'FR_DOUBLE_COURONNE' => array(460, 720), 'FR_DOUBLE_JESUS' => array(760, 1120), 'FR_DOUBLE_POT' => array(400, 620), 'FR_DOUBLE_RAISIN' => array(650, 1000), 'FR_DOUBLE_SOLEIL' => array(800, 1200), 'FR_DOUBLE_TELLIERE' => array(440, 680), 'FR_ECU' => array(400, 520), 'FR_GRAND_AIGLE' => array(750, 1060), 'FR_GRANDE_MONDE' => array(900, 1260), 'FR_JESUS' => array(560, 760), 'FR_JOURNAL' => array(650, 940), 'FR_PETIT_AIGLE' => array(700, 940), 'FR_POT' => array(310, 400), 'FR_RAISIN' => array(500, 650), 'FR_SOLEIL' => array(600, 800), 'FR_TELLIERE' => array(340, 440), 'FR_UNIVERS' => array(1000, 1300), 'G0' => array(958, 1354), 'G10' => array(29, 42), 'G11' => array(21, 29), 'G12' => array(14, 21), 'G1' => array(677, 958), 'G2' => array(479, 677), 'G3' => array(338, 479), 'G4' => array(239, 338), 'G5' => array(169, 239), 'G6' => array(119, 169), 'G7' => array(84, 119), 'G8' => array(59, 84), 'G9' => array(42, 59), 'GLETTER' => array(203, 267), 'GOVERNMENTLETTER' => array(203, 267), 'JIS_B0' => array(1030, 1456), 'JIS_B10' => array(32, 45), 'JIS_B11' => array(22, 32), 'JIS_B12' => array(16, 22), 'JIS_B1' => array(728, 1030), 'JIS_B2' => array(515, 728), 'JIS_B3' => array(364, 515), 'JIS_B4' => array(257, 364), 'JIS_B5' => array(182, 257), 'JIS_B6' => array(128, 182), 'JIS_B7' => array(91, 128), 'JIS_B8' => array(64, 91), 'JIS_B9' => array(45, 64), 'JLEGAL' => array(203, 127), 'JUNIORLEGAL' => array(203, 127), 'LEDGER' => array(432, 279), 'USLEDGER' => array(432, 279), 'LEGAL' => array(216, 356), 'USLEGAL' => array(216, 356), 'LETTER' => array(216, 279), 'USLETTER' => array(216, 279), 'ORGANIZERM' => array(216, 279), 'MEMO' => array(140, 216), 'STATEMENT' => array(140, 216), 'ORGANIZERL' => array(140, 216), 'NEWSPAPER_BERLINER' => array(470, 315), 'NEWSPAPER_BROADSHEET' => array(750, 600), 'NEWSPAPER_COMPACT' => array(430, 280), 'NEWSPAPER_TABLOID' => array(430, 280), 'ORGANIZERJ' => array(70, 127), 'P1' => array(560, 860), 'P2' => array(430, 560), 'P3' => array(280, 430), 'P4' => array(215, 280), 'P5' => array(140, 215), 'P6' => array(107, 140), 'PA0' => array(840, 1120), 'PA10' => array(26, 35), 'PA1' => array(560, 840), 'PA2' => array(420, 560), 'PA3' => array(280, 420), 'PA4' => array(210, 280), 'PA5' => array(140, 210), 'PA6' => array(105, 140), 'PA7' => array(70, 105), 'PA8' => array(52, 70), 'PA9' => array(35, 52), 'PASSPORT_PHOTO' => array(35, 45), 'QUADDEMY' => array(889, 1143), 'QUARTO' => array(229, 279), 'RA0' => array(860, 1220), 'RA1' => array(610, 860), 'RA2' => array(430, 610), 'RA3' => array(305, 430), 'RA4' => array(215, 305), 'S10R' => array(254, 381), '4PW' => array(254, 381), 'S11R' => array(279, 432), 'S12R' => array(305, 456), 'S8R' => array(203, 305), '6PW' => array(203, 305), 'SO_B5_EXTRA' => array(202, 276), 'SRA0' => array(900, 1280), 'SRA1' => array(640, 900), 'SRA2' => array(450, 640), 'SRA3' => array(320, 450), 'SRA4' => array(225, 320), 'SUPER_A3' => array(305, 487), 'SUPER_A4' => array(227, 356), 'SUPER_B' => array(330, 483), 'TABLOID' => array(279, 432), 'USTABLOID' => array(279, 432), 'BIBLE' => array(279, 432), 'ORGANIZERK' => array(279, 432), ); ?>
mit
Azure/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/UpdateDomain.Serialization.cs
1144
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Compute.Models { public partial class UpdateDomain : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WriteEndObject(); } internal static UpdateDomain DeserializeUpdateDomain(JsonElement element) { Optional<string> id = default; Optional<string> name = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("id")) { id = property.Value.GetString(); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } } return new UpdateDomain(id.Value, name.Value); } } }
mit
bcvsolutions/CzechIdMng
Realization/backend/acc/src/main/java/eu/bcvsolutions/idm/acc/dto/filter/SysSystemGroupFilter.java
1257
package eu.bcvsolutions.idm.acc.dto.filter; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import eu.bcvsolutions.idm.acc.domain.SystemGroupType; import eu.bcvsolutions.idm.acc.dto.SysSystemGroupDto; import eu.bcvsolutions.idm.core.api.dto.filter.DataFilter; import eu.bcvsolutions.idm.core.api.dto.filter.DisableableFilter; import eu.bcvsolutions.idm.core.api.utils.ParameterConverter; /** * System groups (cross-domain) filter. * * @author Vít Švanda * @since 11.2.0 * */ public class SysSystemGroupFilter extends DataFilter implements DisableableFilter { public static final String PARAMETER_GROUP_TYPE = "groupType"; public SysSystemGroupFilter() { this(new LinkedMultiValueMap<>()); } public SysSystemGroupFilter(MultiValueMap<String, Object> data) { this(data, null); } public SysSystemGroupFilter(MultiValueMap<String, Object> data, ParameterConverter parameterConverter) { super(SysSystemGroupDto.class, data, parameterConverter); } public SystemGroupType getGroupType() { return getParameterConverter().toEnum(getData(), PARAMETER_GROUP_TYPE, SystemGroupType.class); } public void setGroupType(SystemGroupType type) { set(PARAMETER_GROUP_TYPE, type); } }
mit
eablack/code-corps-ember
app/helpers/highlight-substrings.js
2128
import Ember from 'ember'; export function highlightSubstrings([string, substring]) { let substrings = substring.split(" ").uniq(); var positionsToAdd = []; var newString = []; var count = 0; var strongTagLocations = []; _findPositionsToAdd(positionsToAdd, string, substrings, newString); _assembleArrayOfStrings(positionsToAdd, newString, count, strongTagLocations); return _assembleOutputString(newString); } function _findPositionsToAdd(positionsToAdd, string, substrings, newString) { for (var i = 0; i < string.length; i++) { newString.push(string.charAt(i)); for (var e = 0; e < substrings.length; e++) { let stringOfSize = string.substring(i, substrings[e].length + i).toLowerCase(); let substringToMatch = substrings[e].toLowerCase(); if(stringOfSize === substringToMatch) { positionsToAdd.push({ index: i, stringLength: substringToMatch.length }); } } } } function _assembleArrayOfStrings(positionsToAdd, newString, count, strongTagLocations) { for (var i = 0; i < positionsToAdd.length; i++) { var canProceed = true; let startIndex = positionsToAdd[i].index; let stringLength = positionsToAdd[i].stringLength; let firstLocation = startIndex + count; let lastLocation = firstLocation + (stringLength + 1); canProceed = _checkIfLocationInLocations(firstLocation, strongTagLocations); if (canProceed) { newString.splice(firstLocation, 0, "<strong>"); newString.splice(lastLocation, 0, "</strong>"); strongTagLocations.push({ start: firstLocation, end: lastLocation }); count += 2; } } } function _assembleOutputString(arrayOfStrings) { var outputString = ""; for (var i = 0; i < arrayOfStrings.length; i++) { outputString += arrayOfStrings[i]; } return outputString; } function _checkIfLocationInLocations(location, locations) { var result = true; locations.forEach((searchedLocation) => { if (location <= searchedLocation.end) { result = false; } }); return result; } export default Ember.Helper.helper(highlightSubstrings);
mit
bmocanu/tryouts
java/java-quickaffe/src/test/java/ro/quickaffe/tests/SimpleChip.java
245
package ro.quickaffe.tests; import ro.quickaffe.Chip; import ro.quickaffe.mech.api.Cup; /** * Created by bogdan on 6/21/15. */ public class SimpleChip implements Chip { @Override public Cup prepare() { return null; } }
mit
ptomaszek/simple-rest-scala
app/org/example/invitation/controller/InvitationController.scala
697
package org.example.invitation.controller import org.example.invitation.dao.InvitationFakeDao import org.example.invitation.model.Invitation.Invitee import play.api.libs.json._ import play.api.mvc._ object InvitationController extends Controller { val inviteeDao = InvitationFakeDao def list = Action { Ok(Json.toJson(inviteeDao.findAll())) } def save = Action(BodyParsers.parse.json) { request => request.body.validate[Invitee].fold( errors => { BadRequest(Json.obj("message" -> JsError.toFlatJson(errors))) }, invitee => { inviteeDao.add(invitee) Created } ) } }
mit
PeeHaa/AsyncTwitter
examples/users/lookup-by-screen-names-and-user-ids.php
412
<?php declare(strict_types=1); namespace PeeHaa\AsyncTwitter\Examples\Users; use PeeHaa\AsyncTwitter\Api\Request\User\LookupByScreenNamesAndUserIds; require_once __DIR__ . '/../../vendor/autoload.php'; $apiClient = require __DIR__ . '/../create-client.php'; $request = (new LookupByScreenNamesAndUserIds(['PHPeeHaa'], [12345])) ->excludeEntities() ; \Amp\wait($result = $apiClient->request($request));
mit
colevk/kitten-button
js/background.js
1217
var toggled_on = false; function truth(str) { return str == "true"; } function load_helper_scripts() { chrome.tabs.executeScript(null, {file: "js/jquery.min.js"}); chrome.tabs.executeScript(null, {code: "color_kittens = " + localStorage.color}); chrome.tabs.executeScript(null, {file: "js/toggle.js"}); } function apply_toggle() { if (toggled_on) { chrome.tabs.executeScript(null, {code: "toggle_on();"}); } else { chrome.tabs.executeScript(null, {code: "toggle_off();"}); } } function toggle() { toggled_on = !toggled_on; if (toggled_on) { chrome.browserAction.setIcon({"path": "icon_active.png"}); } else { chrome.browserAction.setIcon({"path": "icon.png"}); } } function hide() { if (toggled_on) { chrome.tabs.insertCSS(null, {code: "img { visibility: hidden !important; }"}); } else { chrome.tabs.insertCSS(null, {code: "img { visibility: visible !important; }"}); } } chrome.tabs.onUpdated.addListener(function(tab) { hide(); load_helper_scripts(); apply_toggle(); }); chrome.tabs.onActivated.addListener(function(tab) { hide(); load_helper_scripts(); apply_toggle(); }); chrome.browserAction.onClicked.addListener(function(tab) { toggle(); hide(); apply_toggle(); });
mit
nczeroshift/nctoolkit
source/network/nckHttpServer.cpp
24315
/** * NCtoolKit © 2007-2017 Luís F.Loureiro, under zlib software license. * https://github.com/nczeroshift/nctoolkit */ #define NCK_SERVERSTRING "Server: nctoolkit\r\n" #define NCK_DATABUFFERSIZE 1024 #include "nckHttpServer.h" #if defined (NCK_WINDOWS) #include <WinSock2.h> #include <ws2tcpip.h> typedef SOCKET nckSocket; #undef CreateMutex #else #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <strings.h> #include <sys/wait.h> #include <netdb.h> typedef int nckSocket; #endif #include <stdio.h> #include <sys/types.h> #include <ctype.h> #include <string.h> #include <sys/stat.h> #include <stdlib.h> #include <stdint.h> #include "nckException.h" #include "nckThread.h" #include "nckUtils.h" #include "nckDataIO.h" #include "nckUriCodec.h" #if defined (NCK_WINDOWS) #define CLOSE_SOCKET(s) closesocket(s) #else extern int errno; #define CLOSE_SOCKET(s) close(s) #endif _NETWORK_BEGIN class HttpDispatchedThreadContext { public: HttpDispatchedThreadContext(){ thread = NULL; context = NULL; clientSocket = 0; } Core::Thread * thread; HttpServerContext * context; int clientSocket; std::string clientAdress; }; class HttpRequestDispatcher{ public: HttpRequestDispatcher(HttpServerContext * context){ this->context = context; dispatchedMutex = Core::CreateMutex(); activeMutex = Core::CreateMutex(); } ~HttpRequestDispatcher(){ while(GetActiveThreadsCount()>0){ Core::Thread::Wait(1); } ClearUp(); SafeDelete(activeMutex); SafeDelete(dispatchedMutex); } // Dispatch a new thread to handle the request. void Dispatch(Core::Thread_Function function, int clientSocket, const std::string & clientAdress) { HttpDispatchedThreadContext * dContext = new HttpDispatchedThreadContext(); dContext->context = context; dContext->clientAdress = clientAdress; Core::Thread * thread = Core::CreateThread(function,dContext); dContext->thread = thread; dContext->clientSocket = clientSocket; activeMutex->Lock(); activeThreads.push_front(thread); activeMutex->Unlock(); thread->Start(); } // Clear old threads from memory. void ClearUp(){ dispatchedMutex->Lock(); ListFor(Core::Thread*,dispatchedThreads,i) { (*i)->Join(); // just for precaution. delete (*i); } dispatchedThreads.clear(); dispatchedMutex->Unlock(); } // Schedule thread class to be released from memory. void Dispose(Core::Thread* thread) { activeMutex->Lock(); activeThreads.remove(thread); activeMutex->Unlock(); dispatchedMutex->Lock(); dispatchedThreads.push_front(thread); dispatchedMutex->Unlock(); } int GetActiveThreadsCount(){ activeMutex->Lock(); int count = (int)activeThreads.size(); activeMutex->Unlock(); return count; } private: HttpServerContext * context; std::list<Core::Thread*> activeThreads; std::list<Core::Thread*> dispatchedThreads; Core::Mutex * dispatchedMutex; Core::Mutex * activeMutex; }; class HttpServerContext{ public: HttpServerContext(); ~HttpServerContext(); void Start(int port, int connections); void Stop(); nckSocket httpdSocket; int httpdPort; int maxConnections; bool connectionTearDown; Core::Thread * connectionThread; HttpCallbackHandler * callbackHandler; HttpRequestDispatcher * dispatcher; static void * ConnectionCallback(void * data); static void * HandleRequestCallback(void * data); static bool FetchLine(int socket, std::string * line); void SendData(int client, unsigned char * data, int64_t size, int flags); void SendUnimplemented(int client); void SendNotFound(int client); void SendRootDocument(int client); bool SendFile(int client, const std::string filename,MIMEType type); void SendJSONText(int client, const std::string text); void SendImageData(int client, Core::ImageType type,unsigned char * data, size_t size); void SendBadRequest(int client); void SendHeaders(int client, MIMEType type); MIMEType GetMIMEType(const std::string & filename); void SendPostCreated(int client); void SendPostCreated(int client,HttpResponse * r); void SendForbiddenRequest(int client); void SendGetCreated(int client, HttpResponse * r); }; HttpServerContext::HttpServerContext(){ callbackHandler = NULL; httpdSocket = 0; httpdPort = 0; maxConnections = 0; connectionThread = NULL; connectionTearDown = false; dispatcher = new HttpRequestDispatcher(this); } HttpServerContext::~HttpServerContext(){ connectionTearDown = true; if(connectionThread) connectionThread->Join(); SafeDelete(dispatcher); SafeDelete(connectionThread); connectionTearDown = false; if(httpdSocket){ CLOSE_SOCKET(httpdSocket); httpdSocket = 0; } } void HttpServerContext::Stop() { connectionTearDown = true; if(connectionThread) connectionThread->Join(); SafeDelete(connectionThread); connectionTearDown = false; if(httpdSocket){ CLOSE_SOCKET(httpdSocket); httpdSocket = 0; } } void HttpServerContext::Start(int port, int connections) { sockaddr_in name; #if defined(NCK_WINDOWS) WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); #else //http://stackoverflow.com/questions/6824265/sigpipe-broken-pipe signal(SIGPIPE, SIG_IGN); #endif httpdSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); httpdPort = port; if (httpdSocket == -1) THROW_EXCEPTION("Unable to create server socket"); #if defined(NCK_MACOSX) int yes=1; if (setsockopt(httpdSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) { perror("setsockopt"); exit(1); } #endif memset(&name, 0, sizeof(name)); name.sin_family = AF_INET; name.sin_port = htons(httpdPort); name.sin_addr = in4addr_any; if (bind(httpdSocket, (struct sockaddr *)&name, sizeof(name)) < 0){ THROW_EXCEPTION("Unable to bind address family to socket"); } if (httpdPort == 0) { int namelen = sizeof(name); if (getsockname(httpdSocket, (struct sockaddr *)&name,(socklen_t*) &namelen) == -1) THROW_EXCEPTION("Unable to get the bounded socket port"); httpdPort = ntohs(name.sin_port); } struct timeval socket_tv; socket_tv.tv_sec = 10; socket_tv.tv_usec = 0; setsockopt(httpdSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&socket_tv,sizeof(struct timeval)); maxConnections = connections; if (listen(httpdSocket, maxConnections) < 0) THROW_EXCEPTION("Unable to mark socket as listener"); connectionThread = Core::CreateThread(ConnectionCallback,this); connectionThread->Start(); } bool HttpServerContext::FetchLine(int socket, std::string * line) { int i = 0; char c = '\0'; int n; *line = ""; while (c != '\n') { n = (int)recv(socket, &c, 1, 0); /* DEBUG printf("%02X\n", c); */ if (n > 0) { if (c == '\r') { n = (int)recv(socket, &c, 1, MSG_PEEK); /* DEBUG printf("%02X\n", c); */ if ((n > 0) && (c == '\n')) recv(socket, &c, 1, 0); else c = '\n'; } (*line) += c; i++; } else c = '\n'; } return i>0?true:false; } void * HttpServerContext::ConnectionCallback(void * data) { HttpServerContext * context = (HttpServerContext*)data; fd_set master; FD_ZERO(&master); FD_SET(context->httpdSocket, &master); int fdmax = context->httpdSocket; while(!context->connectionTearDown) { fd_set read_fds = master; struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 1000; if(select(fdmax+1,&read_fds,NULL,NULL,&timeout)>0) { while(context->dispatcher->GetActiveThreadsCount()>5) Core::Thread::Wait(1); struct sockaddr_in clientAddr; int clientAddrLen = sizeof(clientAddr); int clientSocket = accept(context->httpdSocket, (struct sockaddr *)&clientAddr, (socklen_t*)&clientAddrLen); char addrStr[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(clientAddr.sin_addr), addrStr, INET_ADDRSTRLEN); struct timeval socket_tv; socket_tv.tv_sec = 10; socket_tv.tv_usec = 0; setsockopt(clientSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&socket_tv,sizeof(struct timeval)); context->dispatcher->Dispatch(HandleRequestCallback,clientSocket,std::string(addrStr)); } context->dispatcher->ClearUp(); } return NULL; } static std::map<std::string, std::string> mapHeader(const std::string & src){ std::map<std::string, std::string> ret; size_t index ; std::string tmp = src; do{ index = tmp.find_first_of("\n"); std::string param; if(index != std::string::npos) param = tmp.substr(0,index); else param = tmp; size_t split = param.find_first_of(":"); if(split!=std::string::npos){ std::string type = param.substr(0,split); std::string value = param.substr(split+1,param.length()); ret.insert(std::pair<std::string,std::string>(type,Core::ltrim(value))); } if(index != std::string::npos) tmp = tmp.substr(index+1,tmp.length()); }while(index); return ret; } static std::string ReadStream(HttpDispatchedThreadContext * dCtx){ HttpServerContext * context = dCtx->context; std::string ret = ""; while(true){ std::string temp; if(!context->FetchLine(dCtx->clientSocket,&temp)) break; ret += temp; if(temp=="\n") break; } return ret; } void * HttpServerContext::HandleRequestCallback(void * data) { HttpDispatchedThreadContext * dCtx = (HttpDispatchedThreadContext*)data; HttpServerContext * context = dCtx->context; std::string line; if (FetchLine(dCtx->clientSocket, &line)) { line = Core::ltrim(line); size_t firstSpace = line.find_first_of(" "); size_t endSpace = line.find_last_of(" "); std::string strType = line.substr(0, firstSpace); std::string strPath = Core::ltrim(line.substr(firstSpace, endSpace - firstSpace)); std::string strVersion = Core::rtrim(Core::ltrim(line.substr(endSpace, line.length() - endSpace))); MIMEType mType = context->GetMIMEType(strPath); std::string headerStr = ReadStream(dCtx); std::map<std::string, std::string> headerMap = mapHeader(headerStr); std::map<std::string, std::string> paramMap; if (strPath.find_first_of("?") != std::string::npos) { std::vector<std::pair<std::string, std::string>> p; UriParseParameters((char*)strPath.c_str(), strPath.size(), &p); for (size_t i = 0; i < p.size(); i++) { paramMap.insert(std::pair<std::string, std::string>(p[i].first,p[i].second)); } strPath = strPath.substr(0, strPath.find_first_of("?")); } HttpRequest request; request.SetPath(strPath); request.SetType(mType); request.SetAddress(dCtx->clientAdress); request.SetVersion(strVersion); MapFor(std::string, std::string, headerMap, i) { request.SetHeader(i->first, i->second); } MapFor(std::string, std::string, paramMap, i) { request.SetParameter(i->first, i->second); } request.SetMethod(strType); HttpResponse response; if (context->callbackHandler && !context->callbackHandler->AllowRequest(&request, &response)) { // Content not accessible context->SendForbiddenRequest(dCtx->clientSocket); } else { if (strType == "GET") { if (strPath == "/") { // Serve root document context->SendRootDocument(dCtx->clientSocket); } else if (strPath.find("/x/") != std::string::npos) { if (context->callbackHandler && context->callbackHandler->HandleRequest(&request, &response)) { context->SendGetCreated(dCtx->clientSocket, &response); } else context->SendBadRequest(dCtx->clientSocket); } else { context->SendFile(dCtx->clientSocket, strPath, mType); } } else if (strType == "POST") { if (strPath.find("/x/") != std::string::npos) { //std::string dataStr = ReadStream(dCtx); std::string dataStr,temp; while (context->FetchLine(dCtx->clientSocket, &temp)) { dataStr += temp; } request.GetBuffer()->Push(dataStr); if (context->callbackHandler && context->callbackHandler->HandleRequest(&request, &response)) context->SendPostCreated(dCtx->clientSocket, &response); else context->SendBadRequest(dCtx->clientSocket); } else context->SendBadRequest(dCtx->clientSocket); } else { if (context->callbackHandler) context->callbackHandler->UnsupportedRequest(&request); printf("Unsupported request method (%s)\n", strType.c_str()); } } } CLOSE_SOCKET(dCtx->clientSocket); context->dispatcher->Dispose(dCtx->thread); delete dCtx; return NULL; } void HttpServerContext::SendPostCreated(int client){ char buf[1024]; strcpy(buf, "HTTP/1.1 201 CREATED\r\n"); send(client, buf, strlen(buf), 0); //sprintf(buf,"Accept: application/json, text/javascript, */*; q=0.01\r\n"); sprintf(buf,"Accept: application/x-www-form-urlencoded; charset=UTF-8"); send(client, buf, strlen(buf), 0); sprintf(buf, "Content-Type: text/json\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf,"Accept-Encoding:\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf,"Cache-Control: max-age=0, no-cache, no-store\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf,"Pragma: no-cache\r\n"); send(client, buf, strlen(buf), 0); strcpy(buf, "Content-Length: 0\r\n"); send(client, buf, strlen(buf), 0); strcpy(buf, "\r\n"); send(client, buf, strlen(buf), 0); } void HttpServerContext::SendPostCreated(int client, HttpResponse * r) { char buf[1024]; sprintf(buf, "HTTP/1.1 %d CREATED\r\n",r->GetStatusCode()); send(client, buf, strlen(buf), 0); if (r->GetType() == MIME_JSON_TEXT) sprintf(buf, "Content-Type: application/json\r\n"); else if(r->GetType() == MIME_PLAIN_TEXT) sprintf(buf, "Content-Type: text/plain\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "Accept-Encoding:\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "Cache-Control: max-age=0, no-cache, no-store\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "Pragma: no-cache\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "Content-Length: %d\r\n",r->GetBuffer()->Size()); send(client, buf, strlen(buf), 0); strcpy(buf, "\r\n"); send(client, buf, strlen(buf), 0); SendData(client, (unsigned char*)r->GetBuffer()->GetData(), r->GetBuffer()->Size(), 0); } void HttpServerContext::SendGetCreated(int client, HttpResponse * r) { char buf[1024]; sprintf(buf, "HTTP/1.1 %d CREATED\r\n", r->GetStatusCode()); send(client, buf, strlen(buf), 0); if (!r->HasHeader("Content-Type")) { if (r->GetType() == MIME_JSON_TEXT) sprintf(buf, "Content-Type: application/json\r\n"); else if (r->GetType() == MIME_PLAIN_TEXT) sprintf(buf, "Content-Type: text/plain\r\n"); else if (r->GetType() == MIME_JPEG_IMAGE) sprintf(buf, "Content-Type: image/jpg\r\n"); send(client, buf, strlen(buf), 0); } MapFor(std::string, std::string, r->m_Headers, i) { sprintf(buf, "%s: %s\r\n",i->first.c_str(),i->second.c_str()); send(client, buf, strlen(buf), 0); } sprintf(buf, "Accept-Encoding:\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "Cache-Control: max-age=0, no-cache, no-store\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "Pragma: no-cache\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "Content-Length: %d\r\n", r->GetBuffer()->Size()); send(client, buf, strlen(buf), 0); strcpy(buf, "\r\n"); send(client, buf, strlen(buf), 0); SendData(client, (unsigned char*)r->GetBuffer()->GetData(), r->GetBuffer()->Size(), 0); } void HttpServerContext::SendNotFound(int client) { char buf[1024]; sprintf(buf, "HTTP/1.1 404 NOT FOUND\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, NCK_SERVERSTRING); send(client, buf, strlen(buf), 0); sprintf(buf, "Content-Type: text/html\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "<HTML><TITLE>Not Found</TITLE>\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "<BODY><P>The server could not fulfill\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "your request because the resource specified\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "is unavailable or nonexistent.\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "</BODY></HTML>\r\n"); send(client, buf, strlen(buf), 0); } void HttpServerContext::SendForbiddenRequest(int client) { char buf[1024]; sprintf(buf, "HTTP/1.1 403 BAD REQUEST\r\n"); send(client, buf, sizeof(buf), 0); sprintf(buf, "Content-type: text/html\r\n"); send(client, buf, sizeof(buf), 0); sprintf(buf, "\r\n"); send(client, buf, sizeof(buf), 0); } void HttpServerContext::SendBadRequest(int client) { char buf[1024]; sprintf(buf, "HTTP/1.1 400 BAD REQUEST\r\n"); send(client, buf, sizeof(buf), 0); sprintf(buf, "Content-type: text/html\r\n"); send(client, buf, sizeof(buf), 0); sprintf(buf, "\r\n"); send(client, buf, sizeof(buf), 0); sprintf(buf, "<P>Your browser sent a bad request, "); send(client, buf, sizeof(buf), 0); sprintf(buf, "such as a POST without a Content-Length.\r\n"); send(client, buf, sizeof(buf), 0); } void HttpServerContext::SendUnimplemented(int client) { char buf[1024]; sprintf(buf, "HTTP/1.1 501 Method Not Implemented\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, NCK_SERVERSTRING); send(client, buf, strlen(buf), 0); sprintf(buf, "Content-Type: text/html\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "<HTML><HEAD><TITLE>Method Not Implemented\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "</TITLE></HEAD>\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "<BODY><P>HTTP request method not supported.\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "</BODY></HTML>\r\n"); send(client, buf, strlen(buf), 0); } void HttpServerContext::SendData(int client, unsigned char * data, int64_t size, int flags) { if(size == 0){ send(client,NULL,0,flags); return; } int64_t currentSize = size; int64_t currentOffset = 0; while(currentOffset < size && currentSize > 0) { int retSize = (int)send(client,(const char*)(data+currentOffset),currentSize,flags); if(retSize<0) // Ops ... socket gone break; currentSize-=retSize; currentOffset += retSize; if(retSize==0) break; } } bool HttpServerContext::SendFile(int client,const std::string filename,MIMEType type) { std::string fullFilename = Core::GetDataFolder()+"httpd/" + filename; FILE * resource = fopen(fullFilename.c_str(),"rb"); if(!resource){ SendHeaders(client,MIME_HTML_TEXT); SendNotFound(client); return false; } SendHeaders(client,type); bool eof = false; char buf[NCK_DATABUFFERSIZE+1]; do{ memset(buf,0,NCK_DATABUFFERSIZE+1); size_t size = fread(buf,1,NCK_DATABUFFERSIZE,resource); if(!size) break; #if defined(NCK_WINDOWS) SendData(client,(unsigned char*)buf,size,0); if(feof(resource)){ eof = true; SendData(client,(unsigned char*)NULL,0,0); } #else if(feof(resource)){ eof = true; SendData(client,(unsigned char*)buf,size,0); } else{ #if defined(NCK_WINDOWS) || defined(NCK_APPLE) SendData(client,(unsigned char*)buf,size,0); #else SendData(client,(unsigned char*)buf,size,MSG_MORE); #endif } #endif }while(!eof); fclose(resource); return true; } void HttpServerContext::SendJSONText(int client, const std::string text){ SendHeaders(client,MIME_JSON_TEXT); SendData(client,(unsigned char * )text.c_str(),text.length(),0); } void HttpServerContext::SendImageData(int client, Core::ImageType type, unsigned char * data, size_t size){ if(type == Core::IMAGE_TYPE_JPEG) SendHeaders(client,MIME_JPEG_IMAGE); else if(type == Core::IMAGE_TYPE_BMP) SendHeaders(client,MIME_BMP_IMAGE); int p = 0; while(p<size){ size_t remSize = size - p; if(remSize > NCK_DATABUFFERSIZE){ remSize = NCK_DATABUFFERSIZE; #if defined(NCK_WINDOWS) || defined(NCK_APPLE) SendData(client,data+p,remSize,0); #else SendData(client,data+p,remSize,MSG_MORE); #endif } else{ SendData(client,data+p,remSize,0); } p+=remSize; } } void HttpServerContext::SendRootDocument(int client){ SendFile(client, "index.html", MIME_HTML_TEXT); } void HttpServerContext::SendHeaders(int client,MIMEType type) { char buf[1024]; strcpy(buf, "HTTP/1.1 200 OK\r\n"); send(client, buf, strlen(buf), 0); strcpy(buf, NCK_SERVERSTRING); send(client, buf, strlen(buf), 0); switch(type){ case MIME_HTML_TEXT: sprintf(buf, "Content-Type: text/html\r\n"); break; case MIME_JPEG_IMAGE: sprintf(buf, "Content-Type: image/jpeg\r\n"); break; case MIME_BMP_IMAGE: sprintf(buf, "Content-Type: image/bmp\r\n"); break; case MIME_PNG_IMAGE: sprintf(buf, "Content-Type: image/png\r\n"); break; case MIME_PLAIN_TEXT: sprintf(buf, "Content-Type: text/plain\r\n"); break; case MIME_XML_TEXT: sprintf(buf, "Content-Type: text/xml\r\n"); break; case MIME_JSON_TEXT: sprintf(buf, "Content-Type: text/json\r\n"); break; case MIME_JAVASCRIPT: sprintf(buf, "Content-Type: application/javascript\r\n"); break; case MIME_CSS_TEXT: sprintf(buf, "Content-Type: text/css\r\n"); break; } send(client, buf, strlen(buf), 0); sprintf(buf,"Cache-Control: max-age=0, no-cache, no-store\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf,"Pragma: no-cache\r\n"); send(client, buf, strlen(buf), 0); strcpy(buf, "\r\n"); send(client, buf, strlen(buf), 0); } MIMEType HttpServerContext::GetMIMEType(const std::string & filename){ size_t paramPos = filename.find_first_of("?"); MIMEType type = MIME_HTML_TEXT; std::string extensionName =""; if(paramPos == std::string::npos) { size_t extensionPos = filename.find_last_of("."); extensionName = filename.substr(extensionPos+1,filename.length()-extensionPos-1); } else{ std::string tempName = filename.substr(0,paramPos); size_t extensionPos = tempName.find_last_of("."); extensionName = filename.substr(extensionPos+1,tempName.length()-extensionPos-1); } if(extensionName == "jpg") type = MIME_JPEG_IMAGE; else if(extensionName == "bmp") type = MIME_BMP_IMAGE; else if(extensionName == "png") type = MIME_PNG_IMAGE; else if(extensionName == "txt") type = MIME_PLAIN_TEXT; else if(extensionName == "xml") type = MIME_XML_TEXT; else if(extensionName == "json") type = MIME_JSON_TEXT; else if(extensionName == "js") type = MIME_JAVASCRIPT; else if(extensionName == "css") type = MIME_CSS_TEXT; return type; } HttpServer * HttpServer::Create(int port){ HttpServer * ret = new HttpServer(); ret->context = new HttpServerContext(); ret->context->Start(port,30); return ret; } void HttpServer::SetCallback(HttpCallbackHandler * handler){ context->callbackHandler = handler; } HttpServer::HttpServer(){ context = NULL; } HttpServer::~HttpServer(){ SafeDelete(context); } int HttpServer::GetPort(){ if(context) return context->httpdPort; return 0; } _NETWORK_END
mit
openfact/openfact-temp
model/jpa/src/main/java/org/openfact/models/jpa/ubl/common/ItemInstanceAdapter.java
3768
package org.openfact.models.jpa.ubl.common; import java.time.LocalDate; import java.time.LocalTime; import java.util.List; import java.util.stream.Collectors; import javax.persistence.EntityManager; import org.jboss.logging.Logger; import org.openfact.models.OpenfactSession; import org.openfact.models.jpa.JpaModel; import org.openfact.models.jpa.entities.ubl.common.ItemInstanceEntity; import org.openfact.models.jpa.entities.ubl.common.ItemPropertyEntity; import org.openfact.models.ubl.common.ItemInstanceModel; import org.openfact.models.ubl.common.ItemPropertyModel; import org.openfact.models.ubl.common.LotIdentificationModel; public class ItemInstanceAdapter implements ItemInstanceModel, JpaModel<ItemInstanceEntity> { protected static final Logger logger = Logger.getLogger(ItemInstanceAdapter.class); protected ItemInstanceEntity itemInstance; protected EntityManager em; protected OpenfactSession session; public ItemInstanceAdapter(OpenfactSession session, EntityManager em, ItemInstanceEntity itemInstance) { this.session = session; this.em = em; this.itemInstance = itemInstance; } @Override public String getProductTraceID() { return this.itemInstance.getProductTraceID(); } @Override public void setProductTraceID(String value) { this.itemInstance.setProductTraceID(value); } @Override public LocalDate getManufactureDate() { return this.itemInstance.getManufactureDate(); } @Override public void setManufactureDate(LocalDate value) { this.itemInstance.setManufactureDate(value); } @Override public LocalTime getManufactureTime() { return this.itemInstance.getManufactureTime(); } @Override public void setManufactureTime(LocalTime value) { this.itemInstance.setManufactureTime(value); } @Override public String getRegistrationID() { return this.itemInstance.getRegistrationID(); } @Override public void setRegistrationID(String value) { this.itemInstance.setRegistrationID(value); } @Override public String getSerialID() { return this.itemInstance.getSerialID(); } @Override public void setSerialID(String value) { this.itemInstance.setSerialID(value); } @Override public List<ItemPropertyModel> getAdditionalItemProperty() { return itemInstance.getAdditionalItemProperty().stream() .map(f -> new ItemPropertyAdapter(session, em, f)).collect(Collectors.toList()); } @Override public void setAdditionalItemProperty(List<ItemPropertyModel> additionalItemProperty) { List<ItemPropertyEntity> entities = additionalItemProperty.stream() .map(f -> ItemPropertyAdapter.toEntity(f, em)).collect(Collectors.toList()); itemInstance.setAdditionalItemProperty(entities); } @Override public LotIdentificationModel getLotIdentification() { return new LotIdentificationAdapter(session, em, itemInstance.getLotIdentification()); } @Override public void setLotIdentification(LotIdentificationModel value) { this.itemInstance.setLotIdentification(LotIdentificationAdapter.toEntity(value, em)); } @Override public String getId() { return this.itemInstance.getId(); } @Override public ItemInstanceEntity getEntity() { return itemInstance; } public static ItemInstanceEntity toEntity(ItemInstanceModel model, EntityManager em) { if (model instanceof ItemInstanceAdapter) { return ((ItemInstanceAdapter) model).getEntity(); } return em.getReference(ItemInstanceEntity.class, model.getId()); } }
mit
miamor/8dot
apps/upload/assets/js/script.js
2231
$(function() { var dropbox = $('#dropbox'), message = $('.message', dropbox); dropbox.filedrop({ // The name of the $_FILES entry: paramname:'pic', maxfiles: 5, maxfilesize: 2, url: 'post_file.php', uploadFinished: function(i,file,response) { $.data(file).addClass('done'); // response is the JSON object that post_file.php returns }, error: function(err, file) { switch(err) { case 'BrowserNotSupported': showMessage('Your browser does not support HTML5 file uploads!'); break; case 'TooManyFiles': alert('Too many files! Please select 5 at most! (configurable)'); break; case 'FileTooLarge': alert(file.name+' is too large! Please upload files up to 2mb (configurable).'); break; default: break; } }, // Called before each upload is started beforeEach: function(file) { if (!file.type.match(/^image\//)) { alert('Unsupported files!'); // Returning false will cause the // file to be rejected return false; } }, uploadStarted:function(i, file, len) { createImage(file); }, progressUpdated: function(i, file, progress) { $.data(file).find('.progress').width(progress); } }); var template = '<div class="preview"><span class="imageHolder"><img /><span class="uploaded"></span></span><div class="progressHolder"><div class="progress"></div></div></div>'; function createImage(file) { var preview = $(template), image = $('img', preview); var reader = new FileReader(); image.width = 100; image.height = 100; reader.onload = function(e) { // e.target.result holds the DataURL which // can be used as a source of the image: image.attr('src', e.target.result); }; // Reading the file as a DataURL. When finished, // this will trigger the onload function above: reader.readAsDataURL(file); message.hide(); preview.appendTo(dropbox); // Associating a preview container // with the file, using jQuery's $.data(): $.data(file, preview); } function showMessage(msg) { message.html(msg); } });
mit
afreewill333/PAT-Basic-Level-PractiseCode
1016.java
382
import java.io.*; import java.util.*; public class 1016{ public static void main(String[] args){ Scanner sc = new Scanner(system.in); String A = sc.nextString(); String B = sc.nextString(); char Da = sc.nextChar(); char Db = sc.nextChar(); int cnt=0; for(int i=0;i!=A.length();++i) if(A[i]==Da)cnt++; A = new String(cnt,Da); } }
mit
outpunk/adaptive-evil-blocks
pkg/adaptive-evil-blocks.min.js
447
(function(){var t,n,i;n=window.evil,t=function(t){var n;return n=/^([-\w]+:)\s*\d\w+$/im,t.replace(n,function(t){return"("+t+")"})},i=function(n,i){var e,r,c,o;if(o=window.matchMedia(t(n)),"function"==typeof i&&o.matches)return void i();if("object"==typeof i){if(r=i.match,c=i.mismatch,!r)return;return e=function(t){return t.matches?r():c?c():void 0},o.addListener(e),e(o)}},n.block.filters.splice(0,0,function(t){return t.media=i})}).call(this);
mit
quintel/etmoses
spec/models/network/builders/heat_spec.rb
1987
require 'rails_helper' module Network::Builders RSpec.describe Heat do let(:techs) do { child1: [{ type: 'households_water_heater_district_heating_steam_hot_water', units: 10 }] } end let(:list) { TechnologyList.from_hash(techs) } let(:tree) do { name: :parent, children: [{ name: :child1 }, { name: :child2 }] } end let(:sources_hash) do [{ distance: 1, units: 1, key: 'households_collective_chp_biogas', heat_production: 0.0, priority: 0 }, { distance: 1, key: 'central_heat_network_dispatchable', units: 0.0, heat_capacity: 3.71, heat_production: 0.0, priority: 1 }] end let(:sources) { HeatSourceList.new(asset_list: sources_hash) } let(:park) { graph.head.get(:park) } # -------------------------------------------------------------------------- context 'with no explicit volume-per-connection value' do let(:graph) do Heat.build(tree, list, sources, {}) end it 'assigns a volume of 10kWh per connection' do # 10kWh * 4 (15 minute frames) * 10 (units) expect(park.buffer_tech.reserves.first.volume).to eql(400.0) end it 'assigns an amplified volume of 17.78kWh per connection' do expect(park.buffer_tech.reserves.first.high_volume).to eql(400.0 * 1.78) end end context 'an a volume-per-connection of 15kW' do let(:graph) do Heat.build(tree, list, sources, central_heat_buffer_capacity: 15.0) end it 'assigns a volume of 15kWh per connection' do # 15kWh * 4 (15 minute frames) * 10 (units) expect(park.buffer_tech.reserves.first.volume).to eql(600.0) end it 'assigns an amplified volume of 26.67kWh per connection' do expect(park.buffer_tech.reserves.first.high_volume).to eql(600.0 * 1.78) end end end # Heat end
mit
aitherios/rails_with_crystal
crystalreportviewers/js/MochiKit/DragAndDrop.js
25686
/*** MochiKit.DragAndDrop 1.4 See <http://mochikit.com/> for documentation, downloads, license, etc. Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) Mochi-ized By Thomas Herve ([email protected]) ***/ if (typeof(dojo) != 'undefined') { dojo.provide('MochiKit.DragAndDrop'); dojo.require('MochiKit.Base'); dojo.require('MochiKit.DOM'); dojo.require('MochiKit.Iter'); dojo.require('MochiKit.Visual'); dojo.require('MochiKit.Signal'); } if (typeof(JSAN) != 'undefined') { JSAN.use("MochiKit.Base", []); JSAN.use("MochiKit.DOM", []); JSAN.use("MochiKit.Visual", []); JSAN.use("MochiKit.Iter", []); JSAN.use("MochiKit.Signal", []); } try { if (typeof(MochiKit.Base) == 'undefined' || typeof(MochiKit.DOM) == 'undefined' || typeof(MochiKit.Visual) == 'undefined' || typeof(MochiKit.Signal) == 'undefined' || typeof(MochiKit.Iter) == 'undefined') { throw ""; } } catch (e) { throw "MochiKit.DragAndDrop depends on MochiKit.Base, MochiKit.DOM, MochiKit.Visual, MochiKit.Signal and MochiKit.Iter!"; } if (typeof(MochiKit.DragAndDrop) == 'undefined') { MochiKit.DragAndDrop = {}; } MochiKit.DragAndDrop.NAME = 'MochiKit.DragAndDrop'; MochiKit.DragAndDrop.VERSION = '1.4'; MochiKit.DragAndDrop.__repr__ = function () { return '[' + this.NAME + ' ' + this.VERSION + ']'; }; MochiKit.DragAndDrop.toString = function () { return this.__repr__(); }; MochiKit.DragAndDrop.EXPORT = [ "Droppable", "Draggable" ]; MochiKit.DragAndDrop.EXPORT_OK = [ "Droppables", "Draggables" ]; MochiKit.DragAndDrop.Droppables = { /*** Manage all droppables. Shouldn't be used, use the Droppable object instead. ***/ drops: [], remove: function (element) { this.drops = MochiKit.Base.filter(function (d) { return d.element != MochiKit.DOM.getElement(element) }, this.drops); }, register: function (drop) { this.drops.push(drop); }, unregister: function (drop) { this.drops = MochiKit.Base.filter(function (d) { return d != drop; }, this.drops); }, prepare: function (element) { MochiKit.Base.map(function (drop) { if (drop.isAccepted(element)) { if (drop.options.activeclass) { MochiKit.DOM.addElementClass(drop.element, drop.options.activeclass); } drop.options.onactive(drop.element, element); } }, this.drops); }, findDeepestChild: function (drops) { deepest = drops[0]; for (i = 1; i < drops.length; ++i) { if (MochiKit.DOM.isParent(drops[i].element, deepest.element)) { deepest = drops[i]; } } return deepest; }, show: function (point, element) { if (!this.drops.length) { return; } var affected = []; if (this.last_active) { this.last_active.deactivate(); } MochiKit.Iter.forEach(this.drops, function (drop) { if (drop.isAffected(point, element)) { affected.push(drop); } }); if (affected.length > 0) { drop = this.findDeepestChild(affected); MochiKit.Position.within(drop.element, point.page.x, point.page.y); drop.options.onhover(element, drop.element, MochiKit.Position.overlap(drop.options.overlap, drop.element)); drop.activate(); } }, fire: function (event, element) { if (!this.last_active) { return; } MochiKit.Position.prepare(); if (this.last_active.isAffected(event.mouse(), element)) { this.last_active.options.ondrop(element, this.last_active.element, event); } }, reset: function (element) { MochiKit.Base.map(function (drop) { if (drop.options.activeclass) { MochiKit.DOM.removeElementClass(drop.element, drop.options.activeclass); } drop.options.ondesactive(drop.element, element); }, this.drops); if (this.last_active) { this.last_active.deactivate(); } } }; MochiKit.DragAndDrop.Droppable = function (element, options) { this.__init__(element, options); }; MochiKit.DragAndDrop.Droppable.prototype = { /*** A droppable object. Simple use is to create giving an element: new MochiKit.DragAndDrop.Droppable('myelement'); Generally you'll want to define the 'ondrop' function and maybe the 'accept' option to filter draggables. ***/ __class__: MochiKit.DragAndDrop.Droppable, __init__: function (element, /* optional */options) { var d = MochiKit.DOM; var b = MochiKit.Base; this.element = d.getElement(element); this.options = b.update({ greedy: true, hoverclass: null, activeclass: null, hoverfunc: b.noop, accept: null, onactive: b.noop, ondesactive: b.noop, onhover: b.noop, ondrop: b.noop, containment: [], tree: false }, options || {}); // cache containers this.options._containers = []; b.map(MochiKit.Base.bind(function (c) { this.options._containers.push(d.getElement(c)); }, this), this.options.containment); d.makePositioned(this.element); // fix IE MochiKit.DragAndDrop.Droppables.register(this); }, isContained: function (element) { if (this._containers) { var containmentNode; if (this.options.tree) { containmentNode = element.treeNode; } else { containmentNode = element.parentNode; } return MochiKit.Iter.some(this._containers, function (c) { return containmentNode == c; }); } else { return true; } }, isAccepted: function (element) { return ((!this.options.accept) || MochiKit.Iter.some( this.options.accept, function (c) { return MochiKit.DOM.hasElementClass(element, c); })); }, isAffected: function (point, element) { return ((this.element != element) && this.isContained(element) && this.isAccepted(element) && MochiKit.Position.within(this.element, point.page.x, point.page.y)); }, deactivate: function () { /*** A droppable is deactivate when a draggable has been over it and left. ***/ if (this.options.hoverclass) { MochiKit.DOM.removeElementClass(this.element, this.options.hoverclass); } this.options.hoverfunc(this.element, false); MochiKit.DragAndDrop.Droppables.last_active = null; }, activate: function () { /*** A droppable is active when a draggable is over it. ***/ if (this.options.hoverclass) { MochiKit.DOM.addElementClass(this.element, this.options.hoverclass); } this.options.hoverfunc(this.element, true); MochiKit.DragAndDrop.Droppables.last_active = this; }, destroy: function () { /*** Delete this droppable. ***/ MochiKit.DragAndDrop.Droppables.unregister(this); }, repr: function () { return '[' + this.__class__.NAME + ", options:" + MochiKit.Base.repr(this.options) + "]"; } }; MochiKit.DragAndDrop.Draggables = { /*** Manage draggables elements. Not intended to direct use. ***/ drags: [], observers: [], register: function (draggable) { if (this.drags.length === 0) { var conn = MochiKit.Signal.connect; this.eventMouseUp = conn(document, 'onmouseup', this, this.endDrag); this.eventMouseMove = conn(document, 'onmousemove', this, this.updateDrag); this.eventKeypress = conn(document, 'onkeypress', this, this.keyPress); } this.drags.push(draggable); }, unregister: function (draggable) { this.drags = MochiKit.Base.filter(function (d) { return d != draggable; }, this.drags); if (this.drags.length === 0) { var disc = MochiKit.Signal.disconnect disc(this.eventMouseUp); disc(this.eventMouseMove); disc(this.eventKeypress); } }, activate: function (draggable) { // allows keypress events if window is not currently focused // fails for Safari window.focus(); this.activeDraggable = draggable; }, deactivate: function () { this.activeDraggable = null; }, updateDrag: function (event) { if (!this.activeDraggable) { return; } var pointer = event.mouse(); // Mozilla-based browsers fire successive mousemove events with // the same coordinates, prevent needless redrawing (moz bug?) if (this._lastPointer && (MochiKit.Base.repr(this._lastPointer.page) == MochiKit.Base.repr(pointer.page))) { return; } this._lastPointer = pointer; this.activeDraggable.updateDrag(event, pointer); }, endDrag: function (event) { if (!this.activeDraggable) { return; } this._lastPointer = null; this.activeDraggable.endDrag(event); this.activeDraggable = null; }, keyPress: function (event) { if (this.activeDraggable) { this.activeDraggable.keyPress(event); } }, addObserver: function (observer) { this.observers.push(observer); this._cacheObserverCallbacks(); }, removeObserver: function (element) { // element instead of observer fixes mem leaks this.observers = MochiKit.Base.filter(function (o) { return o.element != element; }, this.observers); this._cacheObserverCallbacks(); }, notify: function (eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag' if (this[eventName + 'Count'] > 0) { MochiKit.Base.map(function (o) { if (o[eventName]) { o[eventName](eventName, draggable, event); } }, this.observers); } }, _cacheObserverCallbacks: function () { var b = MochiKit.Base; var self = MochiKit.DragAndDrop.Draggables; b.map(function (eventName) { self[eventName + 'Count'] = b.filter(function (o) { return o[eventName]; }, self.observers).length; }, ['onStart', 'onEnd', 'onDrag']); } }; MochiKit.DragAndDrop.Draggable = function (element, options) { this.__init__(element, options); }; MochiKit.DragAndDrop.Draggable.prototype = { /*** A draggable object. Simple instantiate : new MochiKit.DragAndDrop.Draggable('myelement'); ***/ __class__ : MochiKit.DragAndDrop.Draggable, __init__: function (element, /* optional */options) { var v = MochiKit.Visual; var b = MochiKit.Base; options = b.update({ handle: false, starteffect: function (innerelement) { this._savedOpacity = MochiKit.DOM.getOpacity(innerelement) || 1.0; new v.Opacity(innerelement, {duration:0.2, from:this._savedOpacity, to:0.7}); }, reverteffect: function (innerelement, top_offset, left_offset) { var dur = Math.sqrt(Math.abs(top_offset^2) + Math.abs(left_offset^2))*0.02; return new v.Move(innerelement, {x: -left_offset, y: -top_offset, duration: dur}); }, endeffect: function (innerelement) { new v.Opacity(innerelement, {duration:0.2, from:0.7, to:this._savedOpacity}); }, onchange: b.noop, zindex: 1000, revert: false, scroll: false, scrollSensitivity: 20, scrollSpeed: 15, // false, or xy or [x, y] or function (x, y){return [x, y];} snap: false }, options || {}); var d = MochiKit.DOM; this.element = d.getElement(element); if (options.handle && (typeof(options.handle) == 'string')) { this.handle = d.getFirstElementByTagAndClassName(null, options.handle, this.element); } if (!this.handle) { this.handle = d.getElement(options.handle); } if (!this.handle) { this.handle = this.element; } if (options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) { options.scroll = d.getElement(options.scroll); } d.makePositioned(this.element); // fix IE this.delta = this.currentDelta(); this.options = options; this.dragging = false; this.eventMouseDown = MochiKit.Signal.connect(this.handle, 'onmousedown', this, this.initDrag); MochiKit.DragAndDrop.Draggables.register(this); }, destroy: function () { MochiKit.Signal.disconnect(this.eventMouseDown); MochiKit.DragAndDrop.Draggables.unregister(this); }, currentDelta: function () { var s = MochiKit.DOM.getStyle; return [ parseInt(s(this.element, 'left') || '0'), parseInt(s(this.element, 'top') || '0')]; }, initDrag: function (event) { if (!event.mouse().button.left) { return; } // abort on form elements, fixes a Firefox issue var src = event.target; if (src.tagName && ( src.tagName == 'INPUT' || src.tagName == 'SELECT' || src.tagName == 'OPTION' || src.tagName == 'BUTTON' || src.tagName == 'TEXTAREA')) { return; } if (this._revert) { this._revert.cancel(); this._revert = null; } var pointer = event.mouse(); var pos = MochiKit.Position.cumulativeOffset(this.element); this.offset = [pointer.page.x - pos.x, pointer.page.y - pos.y] MochiKit.DragAndDrop.Draggables.activate(this); event.stop(); }, startDrag: function (event) { this.dragging = true; if (this.options.selectclass) { MochiKit.DOM.addElementClass(this.element, this.options.selectclass); } if (this.options.zindex) { this.originalZ = parseInt(MochiKit.DOM.getStyle(this.element, 'z-index') || '0'); this.element.style.zIndex = this.options.zindex; } if (this.options.ghosting) { this._clone = this.element.cloneNode(true); this.ghostPosition = MochiKit.Position.absolutize(this.element); this.element.parentNode.insertBefore(this._clone, this.element); } if (this.options.scroll) { if (this.options.scroll == window) { var where = this._getWindowScroll(this.options.scroll); this.originalScrollLeft = where.left; this.originalScrollTop = where.top; } else { this.originalScrollLeft = this.options.scroll.scrollLeft; this.originalScrollTop = this.options.scroll.scrollTop; } } MochiKit.DragAndDrop.Droppables.prepare(this.element); MochiKit.DragAndDrop.Draggables.notify('onStart', this, event); if (this.options.starteffect) { this.options.starteffect(this.element); } }, updateDrag: function (event, pointer) { if (!this.dragging) { this.startDrag(event); } MochiKit.Position.prepare(); MochiKit.DragAndDrop.Droppables.show(pointer, this.element); MochiKit.DragAndDrop.Draggables.notify('onDrag', this, event); this.draw(pointer); this.options.onchange(this); if (this.options.scroll) { this.stopScrolling(); var p, q; if (this.options.scroll == window) { var s = this._getWindowScroll(this.options.scroll); p = new MochiKit.Style.Coordinates(s.left, s.top); q = new MochiKit.Style.Coordinates(s.left + s.width, s.top + s.height); } else { p = MochiKit.Position.page(this.options.scroll); p.x += this.options.scroll.scrollLeft; p.y += this.options.scroll.scrollTop; q = new MochiKit.Style.Coordinates(p.x + this.options.scroll.offsetWidth, p.y + this.options.scroll.offsetHeight); } var speed = [0, 0]; if (pointer.page.x > (q.x - this.options.scrollSensitivity)) { speed[0] = pointer.page.x - (q.x - this.options.scrollSensitivity); } else if (pointer.page.x < (p.x + this.options.scrollSensitivity)) { speed[0] = pointer.page.x - (p.x + this.options.scrollSensitivity); } if (pointer.page.y > (q.y - this.options.scrollSensitivity)) { speed[1] = pointer.page.y - (q.y - this.options.scrollSensitivity); } else if (pointer.page.y < (p.y + this.options.scrollSensitivity)) { speed[1] = pointer.page.y - (p.y + this.options.scrollSensitivity); } this.startScrolling(speed); } // fix AppleWebKit rendering if (MochiKit.Base.isSafari()) { window.scrollBy(0, 0); } event.stop(); }, finishDrag: function (event, success) { var dr = MochiKit.DragAndDrop; this.dragging = false; if (this.options.selectclass) { MochiKit.DOM.removeElementClass(this.element, this.options.selectclass); } if (this.options.ghosting) { // XXX: from a user point of view, it would be better to remove // the node only *after* the MochiKit.Visual.Move end when used // with revert. MochiKit.Position.relativize(this.element, this.ghostPosition); MochiKit.DOM.removeElement(this._clone); this._clone = null; } if (success) { dr.Droppables.fire(event, this.element); } dr.Draggables.notify('onEnd', this, event); var revert = this.options.revert; if (revert && typeof(revert) == 'function') { revert = revert(this.element); } var d = this.currentDelta(); if (revert && this.options.reverteffect) { this._revert = this.options.reverteffect(this.element, d[1] - this.delta[1], d[0] - this.delta[0]); } else { this.delta = d; } if (this.options.zindex) { this.element.style.zIndex = this.originalZ; } if (this.options.endeffect) { this.options.endeffect(this.element); } dr.Draggables.deactivate(); dr.Droppables.reset(this.element); }, keyPress: function (event) { if (event.keyString != "KEY_ESCAPE") { return; } this.finishDrag(event, false); event.stop(); }, endDrag: function (event) { if (!this.dragging) { return; } this.stopScrolling(); this.finishDrag(event, true); event.stop(); }, draw: function (point) { var pos = MochiKit.Position.cumulativeOffset(this.element); var d = this.currentDelta(); pos.x -= d[0]; pos.y -= d[1]; if (this.options.scroll && !this.options.scroll.scrollTo) { pos.x -= this.options.scroll.scrollLeft - this.originalScrollLeft; pos.y -= this.options.scroll.scrollTop - this.originalScrollTop; } var p = [point.page.x - pos.x - this.offset[0], point.page.y - pos.y - this.offset[1]] if (this.options.snap) { if (typeof(this.options.snap) == 'function') { p = this.options.snap(p[0], p[1]); } else { if (this.options.snap instanceof Array) { var i = -1; p = MochiKit.Base.map(MochiKit.Base.bind(function (v) { i += 1; return Math.round(v/this.options.snap[i]) * this.options.snap[i] }, this), p) } else { p = MochiKit.Base.map(MochiKit.Base.bind(function (v) { return Math.round(v/this.options.snap) * this.options.snap }, this), p) } } } var style = this.element.style; if ((!this.options.constraint) || (this.options.constraint == 'horizontal')) { style.left = p[0] + 'px'; } if ((!this.options.constraint) || (this.options.constraint == 'vertical')) { style.top = p[1] + 'px'; } if (style.visibility == 'hidden') { style.visibility = ''; // fix gecko rendering } }, stopScrolling: function () { if (this.scrollInterval) { clearInterval(this.scrollInterval); this.scrollInterval = null; } }, startScrolling: function (speed) { if (!speed[0] || !speed[1]) { return; } this.scrollSpeed = [speed[0] * this.options.scrollSpeed, speed[1] * this.options.scrollSpeed]; this.lastScrolled = new Date(); this.scrollInterval = setInterval(MochiKit.Base.bind(this.scroll, this), 10); }, scroll: function () { var current = new Date(); var delta = current - this.lastScrolled; this.lastScrolled = current; if (this.options.scroll == window) { var s = this._getWindowScroll(this.options.scroll); if (this.scrollSpeed[0] || this.scrollSpeed[1]) { var d = delta / 1000; this.options.scroll.scrollTo(s.left + d * this.scrollSpeed[0], s.top + d * this.scrollSpeed[1]); } } else { this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000; this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000; } var d = MochiKit.DragAndDrop; MochiKit.Position.prepare(); d.Droppables.show(d.Draggables._lastPointer, this.element); this.draw(d.Draggables._lastPointer); this.options.onchange(this); }, _getWindowScroll: function (w) { var T, L, W, H; with (w.document) { if (w.document.documentElement && documentElement.scrollTop) { T = documentElement.scrollTop; L = documentElement.scrollLeft; } else if (w.document.body) { T = body.scrollTop; L = body.scrollLeft; } if (w.innerWidth) { W = w.innerWidth; H = w.innerHeight; } else if (w.document.documentElement && documentElement.clientWidth) { W = documentElement.clientWidth; H = documentElement.clientHeight; } else { W = body.offsetWidth; H = body.offsetHeight } } return {top: T, left: L, width: W, height: H}; }, repr: function () { return '[' + this.__class__.NAME + ", options:" + MochiKit.Base.repr(this.options) + "]"; } }; MochiKit.DragAndDrop.__new__ = function () { MochiKit.Base.nameFunctions(this); this.EXPORT_TAGS = { ":common": this.EXPORT, ":all": MochiKit.Base.concat(this.EXPORT, this.EXPORT_OK) }; }; MochiKit.DragAndDrop.__new__(); MochiKit.Base._exportSymbols(this, MochiKit.DragAndDrop);
mit
Swastika-IO/Swastika-IO-ngx-admin
src/app/pages/articles/article.services.ts
2717
import { Component } from '@angular/core'; import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; import 'rxjs/add/observable/fromPromise'; import { ApiResult, ArticleBackend, ArticleListItem } from '../../@swastika-io/viewmodels/article.viewmodels'; import { environment } from '../../../environments/environment'; import { Ng4LoadingSpinnerService } from 'ng4-loading-spinner'; import { ServiceHelper } from 'app/@swastika-io/helpers/sw.service.helper'; @Injectable() export class ArticleService { domain = environment.domain; constructor(private http: Http , private serviceHelper: ServiceHelper // , private spinnerSerice: Ng4LoadingSpinnerService ) { } getArticlesWithPromise(culture: string, pageSize: number, pageIndex: number): Promise<ApiResult> { const getUrl = this.domain + 'api/' + culture + '/articles/' + pageSize + '/' + pageIndex; return this.serviceHelper.getWithPromise(getUrl); } getArticleWithPromise(culture: string, id: string): Promise<ApiResult> { const getUrl = this.domain + 'api/' + culture + '/articles/edit/' + id; return this.serviceHelper.getWithPromise(getUrl); } saveArticleWithPromise(culture: string, article: ArticleBackend): Promise<ApiResult> { const saveUrl = this.domain + 'api/' + culture + '/articles/save'; return this.serviceHelper.postWithPromise(saveUrl, article); } getDefaultArticleWithPromise(culture: string): Promise<ApiResult> { // const agetUrl = this.domain + 'api/' + culture + '/account/get'; // this.serviceHelper.getWithPromise(agetUrl) const getUrl = this.domain + 'api/' + culture + '/articles/create'; return this.serviceHelper.getWithPromise(getUrl); } deleteArticleWithPromise(culture: string, id: string): Promise<ApiResult> { const getUrl = this.domain + 'api/' + culture + '/articles/delete/' + id; return this.serviceHelper.getWithPromise(getUrl); } recycleArticleWithPromise(culture: string, id: string): Promise<ApiResult> { const getUrl = this.domain + 'api/' + culture + '/articles/recycle/' + id; return this.serviceHelper.getWithPromise(getUrl); } restoreArticleWithPromise(culture: string, id: string): Promise<ApiResult> { const getUrl = this.domain + 'api/' + culture + '/articles/restore/' + id; return this.serviceHelper.getWithPromise(getUrl); } }
mit
kratorius/ads
java/graphs/MatrixGraph.java
5984
package graphs; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import interviewquestions.TestCase; /** * Implementation of directed and weighted graph based on a "matrix" (array of array) */ public class MatrixGraph<T> extends TestCase implements Graph<T> { private Map<T, Integer> nodesToId = new HashMap<T, Integer>(); private Map<Integer, T> idToNodes = new HashMap<Integer, T>(); private int[][] graph; public MatrixGraph(int nodesCount) { graph = new int[nodesCount][nodesCount]; } @Override public void link(T n1, T n2, int weight) { int i1 = getId(n1); int i2 = getId(n2); graph[i1][i2] = weight; } @Override public void unlink(T n1, T n2) { int i1 = getId(n1); int i2 = getId(n2); graph[i1][i2] = 0; } @Override public int weight(T n1, T n2) { int i1 = getId(n1); int i2 = getId(n2); return graph[i1][i2]; } @Override public boolean isLinked(T n1, T n2) { return weight(n1, n2) > 0; } @Override public Set<T> neighbours(T node) { int id = getId(node); int[] neighbours = graph[id]; Set<T> list = new HashSet<T>(); for (int nid = 0; nid < neighbours.length; nid++) { if (neighbours[nid] > 0) { list.add(idToNodes.get(nid)); } } return list; } private int getId(T node) { if (!nodesToId.containsKey(node)) { if (nodesToId.size() > graph.length) { throw new ArrayIndexOutOfBoundsException( "number of nodes in the graph exceede maximum graph size" ); } nodesToId.put(node, nodesToId.size()); } int id = nodesToId.get(node); idToNodes.put(id, node); return id; } /************************************** * Specializations of the graph class * **************************************/ public static class UndirectedMatrixGraph<T> extends MatrixGraph<T> { public UndirectedMatrixGraph(int nodesCount) { super(nodesCount); } @Override public void link(T n1, T n2, int weight) { super.link(n1, n2, weight); super.link(n2, n1, weight); } @Override public void unlink(T n1, T n2) { super.unlink(n1, n2); super.unlink(n2, n1); } } public static class UnweightedMatrixGraph<T> extends MatrixGraph<T> { public UnweightedMatrixGraph(int nodesCount) { super(nodesCount); } public void link(T n1, T n2) { super.link(n1, n2, 1); super.link(n2, n1, 1); } } public static class UndirectedUnweightedMatrixGraph<T> extends UndirectedMatrixGraph<T> { public UndirectedUnweightedMatrixGraph(int nodesCount) { super(nodesCount); } public void link(T n1, T n2) { super.link(n1, n2, 1); super.link(n2, n1, 1); } } public static void main(String[] args) { MatrixGraph<String> graph = new MatrixGraph<String>(10); // node1 -> node2 -> node5 -> node7 // -> node3 -> node6 // -> node4 graph.link("node1", "node2", 1); graph.link("node1", "node3", 2); graph.link("node1", "node4", 3); graph.link("node2", "node5", 4); graph.link("node3", "node6", 3); graph.link("node5", "node7", 2); assertTrue(graph.isLinked("node1", "node2")); assertTrue(graph.isLinked("node1", "node3")); assertTrue(graph.isLinked("node1", "node4")); assertTrue(graph.isLinked("node2", "node5")); assertTrue(graph.isLinked("node3", "node6")); assertTrue(graph.isLinked("node5", "node7")); assertFalse(graph.isLinked("node2", "node1")); assertFalse(graph.isLinked("node1", "node7")); assertFalse(graph.isLinked("node1", "node6")); assertFalse(graph.isLinked("node2", "node7")); assertFalse(graph.isLinked("node2", "node6")); assertFalse(graph.isLinked("node4", "node5")); assertEquals(1, graph.weight("node1", "node2")); assertEquals(2, graph.weight("node1", "node3")); assertEquals(3, graph.weight("node1", "node4")); assertEquals(4, graph.weight("node2", "node5")); assertEquals(3, graph.weight("node3", "node6")); assertEquals(2, graph.weight("node5", "node7")); assertEquals(0, graph.weight("node1", "node7")); assertEquals(new HashSet<String>(Arrays.asList( "node2", "node3", "node4" )), graph.neighbours("node1")); UndirectedMatrixGraph<String> undGraph = new UndirectedMatrixGraph<String>(10); undGraph.link("node1", "node2", 1); undGraph.link("node1", "node3", 2); undGraph.link("node1", "node4", 3); undGraph.link("node2", "node5", 4); undGraph.link("node3", "node6", 3); undGraph.link("node5", "node7", 2); assertTrue(undGraph.isLinked("node1", "node2")); assertTrue(undGraph.isLinked("node1", "node3")); assertTrue(undGraph.isLinked("node1", "node4")); assertTrue(undGraph.isLinked("node2", "node5")); assertTrue(undGraph.isLinked("node3", "node6")); assertTrue(undGraph.isLinked("node5", "node7")); assertTrue(undGraph.isLinked("node2", "node1")); assertTrue(undGraph.isLinked("node3", "node1")); assertTrue(undGraph.isLinked("node4", "node1")); assertTrue(undGraph.isLinked("node5", "node2")); assertTrue(undGraph.isLinked("node6", "node3")); assertTrue(undGraph.isLinked("node7", "node5")); UnweightedMatrixGraph<String> unwGraph = new UnweightedMatrixGraph<String>(10); unwGraph.link("node1", "node2"); unwGraph.link("node1", "node3"); unwGraph.link("node1", "node4"); unwGraph.link("node2", "node5"); unwGraph.link("node3", "node6"); unwGraph.link("node5", "node7"); assertEquals(1, unwGraph.weight("node1", "node2")); assertEquals(1, unwGraph.weight("node1", "node3")); assertEquals(1, unwGraph.weight("node1", "node4")); assertEquals(1, unwGraph.weight("node2", "node5")); assertEquals(1, unwGraph.weight("node3", "node6")); assertEquals(1, unwGraph.weight("node5", "node7")); } }
mit
taquimon/rhc
application/controllers/Delegado.php
684
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of Delegado * * @author phantom */ class Delegado extends MY_Controller { public function __construct() { parent::__construct(); $this->load->model('delegado_model', 'delegadoModel'); } public function index() { $delegados = $this->delegadoModel->getDelegadoList(); $this->data = $delegados; $this->middle = 'delegados/delegadoList'; $this->layout(); } }
mit
powertomato/heuOpt_2017_G1
solvers/LocalSearch/SimpleLocalSearch.py
763
from solvers.neighborhoods.Neighborhood import * class SimpleLocalSearch(object): def __init__(self, neighborhood, evaluator): self.neighborhood = neighborhood self.evaluator = evaluator self.step = 0 def optimize(self, x): while not self.evaluator.criteriaReached(x): x_prim = self.neighborhood.step() if x_prim == None: #neighborhood exhausted! break if self.evaluator.compare(x_prim, x): self.step += 1 x = x_prim.graphUpdate() self.neighborhood.reset(x) print("local search steps: %d" % self.step) return x
mit
thefishlive/LudumDare35
Assets/Resources/Scripts/UI/UIManager.cs
333
using UnityEngine; using UnityEngine.UI; using System.Collections; public class UIManager : MonoBehaviour { public GameObject ShiftProcessBar = default(GameObject); public GameObject AttackTimeBar = default(GameObject); public GameObject HealthBar = default(GameObject); public Text ScoreText = default(Text); }
mit
stealjs/steal-tools
lib/stream/check_slim_support.js
368
var through = require("through2"); var checkAtSteal = require("../slim/checks/steal"); module.exports = function() { return through.obj(function(data, enc, done) { try { checkSupport(data); done(null, data); } catch (err) { done(err); } }); }; function checkSupport(data) { checkAtSteal(data.loader.configMain || "package.json!npm", data.graph); }
mit
cerana/cerana
zfs/nv/xdr_decoder.go
7276
package nv import ( "encoding/binary" "io" "reflect" "time" "github.com/cerana/cerana/pkg/errors" xdr "github.com/davecgh/go-xdr/xdr2" ) // XDRDecoder is a Decoder for XDR encoding. type XDRDecoder struct { *xdr.Decoder r io.ReadSeeker pair pair } // NewXDRDecoder creates a new XDRDecoder. func NewXDRDecoder(r io.ReadSeeker) *XDRDecoder { return &XDRDecoder{Decoder: xdr.NewDecoder(r), r: r} } // Decode decodes data into a supplied target. // Note: care should be taken when decoding into a `map[string]interface{}` as // bytes/uint8s (and their array forms) can not be distinguished and will be // treated as uint8/[]uint8. func (d *XDRDecoder) Decode(target interface{}) error { // Validate data encoding codec, endianness, err := decodePreamble(d.r, binary.BigEndian) if err != nil { return err } else if codec != xdrCodec { return errors.Newv("invalid encoding", map[string]interface{}{"codec": codec}) } else if endianness != littleEndian { return errors.Newv("invalid endianess", map[string]interface{}{"endianness": endianness}) } // Validate target targetV := reflect.ValueOf(target) if targetV.Kind() != reflect.Ptr { return errors.Newv("cannot decode into non-pointer", map[string]interface{}{"type": reflect.TypeOf(targetV).String()}) } if targetV.IsNil() { return errors.New("cannot decode into nil") } return decodeList(d, reflect.Indirect(targetV)) } func (d *XDRDecoder) header() (header, error) { var h header err := binary.Read(d.r, binary.BigEndian, &h) return h, errors.Wrap(err, "failed to decode header") } func (d *XDRDecoder) meta() (string, dataType, error) { _, err := xdr.Unmarshal(d.r, &d.pair) return d.pair.Name, d.pair.Type, errors.Wrap(err, "failed to decode nvpair metadata") } func (d *XDRDecoder) skip() error { _, err := d.r.Seek(int64(d.pair.EncodedSize-uint32(d.pair.headerSize())), 1) return errors.Wrap(err, "failed to skip") } func (d *XDRDecoder) isEnd() (bool, error) { var end uint64 err := binary.Read(d.r, binary.BigEndian, &end) if err != nil { return false, errors.Wrap(err, "failed to check for end") } if end == 0 { return true, nil } _, err = d.r.Seek(-8, 1) return false, errors.Wrap(err, "failed to seek back") } func (d *XDRDecoder) value(targetType reflect.Type) (reflect.Value, fieldSetFunc, error) { var val reflect.Value var fsf fieldSetFunc var err error var v interface{} switch d.pair.Type { case _boolean: v := Boolean(true) val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } case _booleanValue: v, err = d.decodeBool() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetBool(v.(bool)) } case _byte: v, err = d.decodeByte() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetUint(uint64(v.(uint8))) } case _int8: v, err = d.decodeInt8() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetInt(int64(v.(int8))) } case _int16: v, err = d.decodeInt16() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetInt(int64(v.(int16))) } case _int32: v, err = d.decodeInt32() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetInt(int64(v.(int32))) } case _int64: v, err = d.decodeInt64() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetInt(v.(int64)) } case _uint8: v, err = d.decodeUint8() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetUint(uint64(v.(uint8))) } case _uint16: v, err = d.decodeUint16() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetUint(uint64(v.(uint16))) } case _uint32: v, err = d.decodeUint32() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetUint(uint64(v.(uint32))) } case _uint64: v, err = d.decodeUint64() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetUint(uint64(v.(uint64))) } case _hrtime: v, err = d.decodeHRTime() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetInt(int64(v.(time.Duration))) } case _double: v, err = d.decodeFloat64() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetFloat(v.(float64)) } case _booleanArray: v, err = d.decodeBoolArray() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } case _byteArray: if _, err = d.r.Seek(-4, 1); err == nil { v, err = d.decodeByteArray() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetBytes(v.([]byte)) } } case _int8Array: v, err = d.decodeInt8Array() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } case _int16Array: v, err = d.decodeInt16Array() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } case _int32Array: v, err = d.decodeInt32Array() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } case _int64Array: v, err = d.decodeInt64Array() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } case _uint8Array: v, err = d.decodeUint8Array() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } case _uint16Array: v, err = d.decodeUint16Array() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } case _uint32Array: v, err = d.decodeUint32Array() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } case _uint64Array: v, err = d.decodeUint64Array() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } case _string: v, err = d.decodeString() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.SetString(v.(string)) } case _stringArray: if _, err = d.r.Seek(-4, 1); err == nil { v, err = d.decodeStringArray() val = reflect.ValueOf(v) fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } } case _nvlist: val = reflect.Indirect(reflect.New(targetType)) err = decodeList(d, val) fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } case _nvlistArray: if targetType.Kind() == reflect.Interface { targetType = reflect.TypeOf([]map[string]interface{}{}) } nelems := int(d.pair.NElements) val = reflect.MakeSlice(targetType, 0, nelems) for i := 0; i < nelems; i++ { elem := reflect.Indirect(reflect.New(targetType.Elem())) err = decodeList(d, elem) if err != nil { break } val = reflect.Append(val, elem) } fsf = func(field reflect.Value, val reflect.Value) { field.Set(val) } default: err = errors.Newv("unknown type", map[string]interface{}{"type": d.pair.Type}) } return val, fsf, err }
mit
stevie-mayhew/silverstripe-redux-example
themes/base/source/js/components/EventsApp.js
2531
/*eslint-disable */ import React, {Component, PropTypes} from 'react'; import {getCountries, getMonths, getEventTypes, getEvents} from '../actions/eventActions'; import Pagination from './Pagination'; import EventFilters from './EventFilters'; export default class EventsApp extends Component { handlePage(page) { this.props.dispatch( getEvents( page, this.props.events.term, this.props.events.country, this.props.events.month, this.props.events.eventType ) ); } componentDidMount() { this.props.dispatch(getEvents(1)); this.props.dispatch(getCountries()); this.props.dispatch(getMonths()); this.props.dispatch(getEventTypes()); } getEvents() { if (this.props.events.count) { return this.props.events.events.map(event => <article key={event.ID} className="postcard"> <a className="postcard-left no-padding" href="{event.Link}"> <div className="postcard-label">{event.StartTime}</div> <img src={event.ImageURL} alt={event.Title}/> </a> <div className="postcard-center"> <h2><a href={event.Link}>{event.Title}</a></h2> <p>{event.Content}</p> </div> <div className="postcard-right"> <div className="vcenter-parent"> <div className="vcenter"> <h3 className="text-center"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 39 39" width="30px" height="30px" className="svg-map-pin-circle"><circle cx="19.6" cy="15.7" r="3.1"></circle><path d="M19.6 0C8.8 0 .1 8.7.1 19.5S8.8 39 19.6 39s19.5-8.7 19.5-19.5S30.3 0 19.6 0zM23 24.6c-1.6 3-3.2 5.4-3.2 5.5 0 .1-.1.1-.2.1s-.1 0-.2-.1c0 0-1.7-2.2-3.3-5.1-2.2-3.9-3.3-7.1-3.3-9.5 0-3.7 3-6.7 6.7-6.7s6.7 3 6.7 6.7c.1 2-1 5.1-3.2 9.1z"></path></svg> Location</h3> <p className="text-center">{event.LocationAddress}</p> </div> </div> </div> </article> ); } else { return (<p>Sorry there are no events</p>); } } render() { const events = this.getEvents(); return ( <div className="App"> <EventFilters {...this.props} handlePage={this.handlePage.bind(this)} /> {events} <Pagination handlePage={this.handlePage.bind(this)} count={this.props.events.count} page={this.props.events.page} maxLinks={7} /> </div> ); } } /*eslint-enable */
mit
typeorm/typeorm
src/util/DepGraph.ts
7625
/** * This source code is from https://github.com/jriecken/dependency-graph * Just added "any" types here, wrapper everything into exported class. * We cant use a package itself because we want to package "everything-in-it" for the frontend users of TypeORM. */ /** * A simple dependency graph */ import { TypeORMError } from "../error"; /** * Helper for creating a Depth-First-Search on * a set of edges. * * Detects cycles and throws an Error if one is detected. * * @param edges The set of edges to DFS through * @param leavesOnly Whether to only return "leaf" nodes (ones who have no edges) * @param result An array in which the results will be populated */ function createDFS(edges: any, leavesOnly: any, result: any) { let currentPath: any[] = []; let visited: any = {}; return function DFS(currentNode: any) { visited[currentNode] = true; currentPath.push(currentNode); edges[currentNode].forEach(function (node: any) { if (!visited[node]) { DFS(node); } else if (currentPath.indexOf(node) >= 0) { currentPath.push(node); throw new TypeORMError(`Dependency Cycle Found: ${currentPath.join(" -> ")}`); } }); currentPath.pop(); if ((!leavesOnly || edges[currentNode].length === 0) && result.indexOf(currentNode) === -1) { result.push(currentNode); } }; } export class DepGraph { nodes: any = {}; outgoingEdges: any = {}; // Node -> [Dependency Node] incomingEdges: any = {}; // Node -> [Dependant Node] /** * Add a node to the dependency graph. If a node already exists, this method will do nothing. */ addNode(node: any, data?: any) { if (!this.hasNode(node)) { // Checking the arguments length allows the user to add a node with undefined data if (arguments.length === 2) { this.nodes[node] = data; } else { this.nodes[node] = node; } this.outgoingEdges[node] = []; this.incomingEdges[node] = []; } } /** * Remove a node from the dependency graph. If a node does not exist, this method will do nothing. */ removeNode(node: any) { if (this.hasNode(node)) { delete this.nodes[node]; delete this.outgoingEdges[node]; delete this.incomingEdges[node]; [this.incomingEdges, this.outgoingEdges].forEach(function (edgeList) { Object.keys(edgeList).forEach(function (key: any) { let idx = edgeList[key].indexOf(node); if (idx >= 0) { edgeList[key].splice(idx, 1); } }, this); }); } } /** * Check if a node exists in the graph */ hasNode(node: any) { return this.nodes.hasOwnProperty(node); } /** * Get the data associated with a node name */ getNodeData(node: any) { if (this.hasNode(node)) { return this.nodes[node]; } else { throw new TypeORMError(`Node does not exist: ${node}`); } } /** * Set the associated data for a given node name. If the node does not exist, this method will throw an error */ setNodeData(node: any, data: any) { if (this.hasNode(node)) { this.nodes[node] = data; } else { throw new TypeORMError(`Node does not exist: ${node}`); } } /** * Add a dependency between two nodes. If either of the nodes does not exist, * an Error will be thrown. */ addDependency(from: any, to: any) { if (!this.hasNode(from)) { throw new TypeORMError(`Node does not exist: ${from}`); } if (!this.hasNode(to)) { throw new TypeORMError(`Node does not exist: ${to}`); } if (this.outgoingEdges[from].indexOf(to) === -1) { this.outgoingEdges[from].push(to); } if (this.incomingEdges[to].indexOf(from) === -1) { this.incomingEdges[to].push(from); } return true; } /** * Remove a dependency between two nodes. */ removeDependency(from: any, to: any) { let idx: any; if (this.hasNode(from)) { idx = this.outgoingEdges[from].indexOf(to); if (idx >= 0) { this.outgoingEdges[from].splice(idx, 1); } } if (this.hasNode(to)) { idx = this.incomingEdges[to].indexOf(from); if (idx >= 0) { this.incomingEdges[to].splice(idx, 1); } } } /** * Get an array containing the nodes that the specified node depends on (transitively). * * Throws an Error if the graph has a cycle, or the specified node does not exist. * * If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned * in the array. */ dependenciesOf(node: any, leavesOnly: any) { if (this.hasNode(node)) { let result: any[] = []; let DFS = createDFS(this.outgoingEdges, leavesOnly, result); DFS(node); let idx = result.indexOf(node); if (idx >= 0) { result.splice(idx, 1); } return result; } else { throw new TypeORMError(`Node does not exist: ${node}`); } } /** * get an array containing the nodes that depend on the specified node (transitively). * * Throws an Error if the graph has a cycle, or the specified node does not exist. * * If `leavesOnly` is true, only nodes that do not have any dependants will be returned in the array. */ dependantsOf(node: any, leavesOnly: any) { if (this.hasNode(node)) { let result: any[] = []; let DFS = createDFS(this.incomingEdges, leavesOnly, result); DFS(node); let idx = result.indexOf(node); if (idx >= 0) { result.splice(idx, 1); } return result; } else { throw new TypeORMError(`Node does not exist: ${node}`); } } /** * Construct the overall processing order for the dependency graph. * * Throws an Error if the graph has a cycle. * * If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned. */ overallOrder(leavesOnly?: any) { let self = this; let result: any[] = []; let keys = Object.keys(this.nodes); if (keys.length === 0) { return result; // Empty graph } else { // Look for cycles - we run the DFS starting at all the nodes in case there // are several disconnected subgraphs inside this dependency graph. let CycleDFS = createDFS(this.outgoingEdges, false, []); keys.forEach(function (n: any) { CycleDFS(n); }); let DFS = createDFS(this.outgoingEdges, leavesOnly, result); // Find all potential starting points (nodes with nothing depending on them) an // run a DFS starting at these points to get the order keys.filter(function (node) { return self.incomingEdges[node].length === 0; }).forEach(function (n) { DFS(n); }); return result; } } }
mit
wizawu/1c
@types/jdk/java.time.Month.d.ts
2144
declare namespace java { namespace time { class Month extends java.lang.Enum<java.time.Month> implements java.time.temporal.TemporalAccessor, java.time.temporal.TemporalAdjuster { public static readonly JANUARY: java.time.Month public static readonly FEBRUARY: java.time.Month public static readonly MARCH: java.time.Month public static readonly APRIL: java.time.Month public static readonly MAY: java.time.Month public static readonly JUNE: java.time.Month public static readonly JULY: java.time.Month public static readonly AUGUST: java.time.Month public static readonly SEPTEMBER: java.time.Month public static readonly OCTOBER: java.time.Month public static readonly NOVEMBER: java.time.Month public static readonly DECEMBER: java.time.Month public static values(): java.time.Month[] public static valueOf(arg0: java.lang.String | string): java.time.Month public static of(arg0: number | java.lang.Integer): java.time.Month public static from(arg0: java.time.temporal.TemporalAccessor): java.time.Month public getValue(): number public getDisplayName(arg0: java.time.format.TextStyle, arg1: java.util.Locale): java.lang.String public isSupported(arg0: java.time.temporal.TemporalField): boolean public range(arg0: java.time.temporal.TemporalField): java.time.temporal.ValueRange public get(arg0: java.time.temporal.TemporalField): number public getLong(arg0: java.time.temporal.TemporalField): number public plus(arg0: number | java.lang.Long): java.time.Month public minus(arg0: number | java.lang.Long): java.time.Month public length(arg0: boolean | java.lang.Boolean): number public minLength(): number public maxLength(): number public firstDayOfYear(arg0: boolean | java.lang.Boolean): number public firstMonthOfQuarter(): java.time.Month public query<R>(arg0: java.time.temporal.TemporalQuery<R> | java.time.temporal.TemporalQuery$$lambda<R>): R public adjustInto(arg0: java.time.temporal.Temporal): java.time.temporal.Temporal } } }
mit
TheBrainTech/xwt
Xwt.WPF/Xwt.WPFBackend/MenuBackend.cs
6502
// // MenuBackend.cs // // Author: // Carlos Alberto Cortez <[email protected]> // Luís Reis <[email protected]> // Eric Maupin <[email protected]> // // Copyright (c) 2011 Carlos Alberto Cortez // Copyright (c) 2012 Luís Reis // Copyright (c) 2012 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; using Xwt.Backends; namespace Xwt.WPFBackend { public class MenuBackend : Backend, IMenuBackend { List<MenuItemBackend> items; FontData customFont; IMenuEventSink eventSink; public void Initialize(IMenuEventSink eventSink) { this.eventSink = eventSink; } public override void InitializeBackend (object frontend, ApplicationContext context) { base.InitializeBackend (frontend, context); items = new List<MenuItemBackend> (); } public IList<MenuItemBackend> Items { get { return items; } } public MenuItemBackend ParentItem { get; set; } public WindowBackend ParentWindow { get; set; } public ContextMenu NativeMenu => menu; public virtual object Font { get { if (customFont == null) return FontData.FromControl (Items.Count > 0 ? Items[0].MenuItem : new System.Windows.Controls.MenuItem()); return customFont; } set { customFont = (FontData)value; foreach (var item in Items) item.SetFont (customFont); } } public void InsertItem (int index, IMenuItemBackend item) { var itemBackend = (MenuItemBackend)item; if (customFont != null) itemBackend.SetFont(customFont); items.Insert (index, itemBackend); if (ParentItem != null && ParentItem.MenuItem != null) ParentItem.MenuItem.Items.Insert (index, itemBackend.Item); else if (ParentWindow != null) ParentWindow.mainMenu.Items.Insert (index, itemBackend.Item); else if (this.menu != null) this.menu.Items.Insert (index, itemBackend.Item); } public void RemoveItem (IMenuItemBackend item) { var itemBackend = (MenuItemBackend)item; items.Remove (itemBackend); if (ParentItem != null) ParentItem.MenuItem.Items.Remove (itemBackend.Item); else if (ParentWindow != null) ParentWindow.mainMenu.Items.Remove (itemBackend.Item); else if (this.menu != null) this.menu.Items.Remove (itemBackend.Item); } public void RemoveFromParentItem () { if (ParentItem == null) return; ParentItem.MenuItem.Items.Clear (); ParentItem = null; } public void Popup (IWidgetBackend widget) { var menu = CreateContextMenu (); var target = widget.NativeWidget as UIElement; if(target == null) throw new System.ArgumentException("Widget belongs to an unsupported Toolkit", nameof(widget)); menu.PlacementTarget = target; menu.Placement = PlacementMode.MousePoint; menu.IsOpen = true; } public void Popup (IWidgetBackend widget, double x, double y) { var menu = CreateContextMenu (); var target = widget.NativeWidget as UIElement; if (target == null) throw new System.ArgumentException ("Widget belongs to an unsupported Toolkit", nameof (widget)); menu.PlacementTarget = target; menu.Placement = PlacementMode.Relative; menu.HorizontalOffset = x; menu.VerticalOffset = y; menu.IsOpen = true; } private ContextMenu menu; internal ContextMenu CreateContextMenu() { if (this.menu == null) { this.menu = new ContextMenu (); foreach (var item in Items) this.menu.Items.Add (item.Item); menu.Opened += (object sender, RoutedEventArgs e) => { this.Context.InvokeUserCode(eventSink.OnOpening); }; menu.Closed += (object sender, RoutedEventArgs e) => { this.Context.InvokeUserCode(eventSink.OnClosed); }; } return menu; } public ContextMenu ContextMenu { get { return menu; } } public override void EnableEvent(object eventId) { if(eventId is MenuEvent) { switch((MenuEvent)eventId) { case MenuEvent.Opening: if(this.ParentItem != null) { this.ParentItem.MenuItem.SubmenuOpened += SubmenuOpenedHandler; } break; case MenuEvent.Closed: if(this.ParentItem != null) { this.ParentItem.MenuItem.SubmenuClosed += SubmenuClosedHandler; } break; } } } public override void DisableEvent(object eventId) { if(eventId is MenuEvent) { switch((MenuEvent)eventId) { case MenuEvent.Opening: if(this.ParentItem != null) { this.ParentItem.MenuItem.SubmenuOpened -= SubmenuOpenedHandler; } break; case MenuEvent.Closed: if(this.ParentItem != null) { this.ParentItem.MenuItem.SubmenuClosed -= SubmenuClosedHandler; } break; } } } private void SubmenuOpenedHandler(object sender, RoutedEventArgs e) { if((e.Source as System.Windows.Controls.MenuItem) == this.ParentItem.MenuItem) { Context.InvokeUserCode(eventSink.OnOpening); } } private void SubmenuClosedHandler(object sender, RoutedEventArgs e) { if((e.Source as System.Windows.Controls.MenuItem) == this.ParentItem.MenuItem) { Context.InvokeUserCode(eventSink.OnClosed); } } } }
mit
eismintkaffee/LocalCrowdTicketing
test/features/support/env.rb
334
require 'rbconfig' require 'cucumber/formatter/unicode' require 'capybara' require 'capybara/dsl' require "capybara/cucumber" Capybara.default_driver = :selenium Capybara.app_host = "http://127.0.0.1:8000/" Capybara.register_driver :selenium do |app| Capybara::Driver::Selenium.new(app, :browser => :firefox) end World(Capybara)
mit
donflopez/meteor-toMarkdown
package.js
488
Package.describe({ summary: "Conver html code into markdown", version: "1.0.0", git: "https://github.com/donflopez/meteor-toMarkdown" }); Package.onUse(function(api) { api.versionsFrom('[email protected]'); api.addFiles('donflopez:he.js'); api.addFiles('donflopez:tomarkdown.js'); api.export('toMarkdown', ['client', 'server']); }); Package.onTest(function(api) { api.use('tinytest'); api.use('donflopez:tomarkdown'); api.addFiles('donflopez:tomarkdown-tests.js'); });
mit
Montana-Studio/mujerypunto
app/wp-content/themes/myp-19102016/partials/loop-sidebar-one.php
2074
<?php // WP_Query arguments $args = array ( 'posts_per_page' => 5, 'meta_key' => 'popular_posts', 'orderby' => 'meta_value_num', 'order' => 'DESC' ); // The Query $sidebartwo = new WP_Query( $args ); // The Loop if ( $sidebartwo->have_posts() ) { while ( $sidebartwo->have_posts() ) { $sidebartwo->the_post(); ?> <div class="post-sidebar"> <div id="post-sidebar-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="imagen-contentpost"> <a href="<?php the_permalink(); ?>"> <div class="lazy imagen-post" data-original="<?php the_post_thumbnail_url(300,300); ?>" style="background-image: url('<?php echo get_bloginfo('template_directory');?>/img/grey.gif');"> <div class="bg-contentpost"></div> </div> </a> </div> <div class="content-post"> <div class="post-inside"> <a href="<?php the_permalink(); ?>"> <div class="title-post"> <?php $thetitle = $post->post_title; $getlength = strlen($thetitle); $thelength = 45; echo substr($thetitle, 0, $thelength); if ($getlength > $thelength) echo "..."; ?> </div> </a> <div class="btn-read-green"><a href="<?php the_permalink(); ?>">Seguir Leyendo</a></div> <div class="social-share"> <ul> <li> <a class="facebook_share_sidebar1"> <i class="fa fa-facebook"></i> </a> </li> <li> <a class="twitter_share_sidebar1"> <i class="fa fa-twitter"></i> </a> </li> <li> <a class="plus_share_sidebar1"> <i class="fa fa-google-plus"></i> </a> </li> <li class="whatsapp"> <?php $title = strtolower(str_replace(' ', '-', the_title('', '', false))) ?> <a href="whatsapp://send?text=<?php echo $title; ?>-<?php urlencode(the_permalink()); ?>" data-action="share/whatsapp/share" data-href="<?php echo the_permalink(); ?>"><i class="fa fa-whatsapp"></i></a> </li> </ul> </div> </div> </div> </div> </div> <?php } } else { // no posts found } // Restore original Post Data wp_reset_postdata(); ?>
mit
pku9104038/qshuttle_driver
src/com/qshuttle/car/ListAdapterAddress.java
1687
/** * */ package com.qshuttle.car; import java.util.ArrayList; import com.amap.mapapi.offlinemap.City; import com.qshuttle.car.PrefProxy.Address; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; /** * @author wangpeifeng * */ public class ListAdapterAddress extends BaseAdapter { private ArrayList<Address> listItems; private Context context; /** * @param listItems * @param context */ public ListAdapterAddress(ArrayList<Address> listItems, Context context) { super(); this.listItems = listItems; this.context = context; } public int getCount() { // TODO Auto-generated method stub return listItems.size(); } public Object getItem(int position) { // TODO Auto-generated method stub return listItems.get(position); } public long getItemId(int position) { // TODO Auto-generated method stub return position; } public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub try { convertView = LayoutInflater.from(context).inflate(R.layout.listitem_address, null); ((TextView)convertView.findViewById(R.id.textViewCity)).setText(listItems.get(position).address); //((TextView)convertView.findViewById(R.id.textViewCity)).setTextColor(Color.BLUE); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return convertView; } }
mit
bauhausjs/bauhausjs
asset/config.js
858
module.exports = function (bauhausConfig) { // Register document for CRUD generation bauhausConfig.addDocument('Assets', { name: 'Asset', model: 'Asset', collection: 'assets', useAsLabel: 'name', icon: 'picture-o', query: { conditions: {parentId: null} }, templates: { listItem: '<a href="#/document/{{ type }}/{{document._id}}"><img ng-src="/assets/{{document._id}}?transform=resize&width=80&height=80"/> {{ document.name }}</a>' }, fields: [ { name: 'name', type: 'text', label: 'Name'}, { name: 'data', type: 'asset-data', label: 'File'}, { name: 'metadata', type: 'asset-meta-data', label: 'MetaData'} ] }); };
mit
ggkovacs/rss-finder
lib/parser.js
2574
'use strict'; var htmlparser = require('htmlparser2'); var FeedParser = require('feedparser'); var Promise = require('pinkie-promise'); var rssTypes = [ 'application/rss+xml', 'application/atom+xml', 'application/rdf+xml', 'application/rss', 'application/atom', 'application/rdf', 'text/rss+xml', 'text/atom+xml', 'text/rdf+xml', 'text/rss', 'text/atom', 'text/rdf' ]; var iconRels = [ 'icon', 'shortcut icon' ]; function htmlParser(htmlBody, feedParserOptions) { return new Promise(function(resolve, reject) { var rs = {}; var feeds = []; var parser; var isFeeds; var favicon; var isSiteTitle; var siteTitle; var feedParser; parser = new htmlparser.Parser({ onopentag: function(name, attr) { if (/(feed)|(atom)|(rdf)|(rss)/.test(name)) { isFeeds = true; } if (name === 'link' && rssTypes.indexOf(attr.type) !== -1 && attr.href) { feeds.push({ title: attr.title || null, url: attr.href }); } if (name === 'link' && (iconRels.indexOf(attr.rel) !== -1 || attr.type === 'image/x-icon')) { favicon = attr.href; } if (name === 'title') { isSiteTitle = true; } }, ontext: function(text) { if (isSiteTitle) { siteTitle = text; } }, onclosetag: function(name) { if (name === 'title') { isSiteTitle = false; } } }, { recognizeCDATA: true }); parser.write(htmlBody); parser.end(); if (isFeeds) { feedParser = new FeedParser(feedParserOptions); feeds = []; feedParser.on('error', function(err) { reject(err); }); feedParser.on('readable', function() { var data; if (feeds.length === 0) { data = this.meta; feeds.push(data); } }); feedParser.write(htmlBody); feedParser.end(function() { if (feeds.length !== 0) { rs.site = { title: feeds[0].title || null, favicon: feeds[0].favicon || null, url: feeds[0].link || null }; rs.feedUrls = [{ title: feeds[0].title || null, url: feeds[0].xmlUrl || null }]; } resolve(rs); }); } else { rs.site = { title: siteTitle || null, favicon: favicon || null }; rs.feedUrls = feeds; resolve(rs); } }); } module.exports = htmlParser;
mit
ruma/ruma
crates/ruma-client-api/src/r0/profile/get_display_name.rs
1168
//! [GET /_matrix/client/r0/profile/{userId}/displayname](https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-profile-userid-displayname) use ruma_api::ruma_api; use ruma_identifiers::UserId; ruma_api! { metadata: { description: "Get the display name of a user.", method: GET, name: "get_display_name", path: "/_matrix/client/r0/profile/:user_id/displayname", rate_limited: false, authentication: None, } request: { /// The user whose display name will be retrieved. #[ruma_api(path)] pub user_id: &'a UserId, } #[derive(Default)] response: { /// The user's display name, if set. #[serde(skip_serializing_if = "Option::is_none")] pub displayname: Option<String>, } error: crate::Error } impl<'a> Request<'a> { /// Creates a new `Request` with the given user ID. pub fn new(user_id: &'a UserId) -> Self { Self { user_id } } } impl Response { /// Creates a new `Response` with the given display name. pub fn new(displayname: Option<String>) -> Self { Self { displayname } } }
mit
IIazertyuiopII/unicorn_swipe_plugin
v1.0/unicorn_swipe_nodiag.js
8809
/*jshint -W032 */ /*jshint -W004 */ // jquerymobile-unicorn_swipe // ---------------------------------- // Copyright (c)2012 Donnovan Lewis // Copyright (c)2014 Romain Le Bail // Distributed under MIT license (http://opensource.org/licenses/MIT) // //credits to Donnovan Lewis for the material taken from https://github.com/blackdynamo/jquerymobile-swipeupdown (function (global, document) { 'use strict'; // initializes touch events var supportTouch = "ontouchstart" in global, touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchMoveEvent = supportTouch ? "touchmove" : "mousemove", touchEndEvent = supportTouch ? "touchend" : "mouseup"; var path; //array of coordinates of the points where the touchMoveEvent was fired var derived_path; var segs; var seg_xhalf; var max_freqs; var start; var stop; var n; function getPosition(event) { return [event.pageX, event.pageY]; } function dispatch(eventProperties) { // Create the event. var event = document.createEvent("Event"); event.initEvent("unicorn", true, true); for (var p in eventProperties) { // useful in case we want to pass more than the route (future versions maybe?) if (eventProperties.hasOwnProperty(p)) { event[p] = eventProperties[p]; } } start.origin.dispatchEvent(event); } function handleTouchStart(event) { //init the Arrays, record starting position and time var position = event.touches ? getPosition(event.touches[0]) : getPosition(event); path = []; derived_path = []; segs = []; seg_xhalf = []; max_freqs = []; start = { time: +new Date(), origin: event.target }; n = 0; path[n] = position; } function handleTouchMove(event) { var position = event.touches ? getPosition(event.touches[0]) : getPosition(event); if (!start) { return; } stop = { time: +new Date() }; if (event.touches && event.touches.length > 1) { //if multitouch event abort everything removeEventListener(touchMoveEvent, handleTouchMove); start = stop = false; } n++; path[n] = position; } function handleTouchEnd(event) { if (!stop && !start) { addEventListener(touchMoveEvent, handleTouchMove); } if (!stop) { return; } var l = path.length; var touchrate = 1000 * l / (stop.time - start.time); var length_adj = Math.round(touchrate/20) - 1; var min_length = l > 7 + length_adj ? 7 + length_adj : 7; // min length is to have enough points to perform consistent recognition console.warn(l+'/'+min_length); if (l > min_length && stop.time - start.time < 10000) { // otherwise do nothing /*########## STEP 1 : Compute and smoothen the derived path ##########*/ var compute_derived_path = function () { for (var i = 0; i < l - 1; ++i) { var d_i = (path[i + 1][1] - path[i][1]) / (path[i + 1][0] - path[i][0]); var x_sig_i = path[i + 1][0] - path[i][0] < 0 ? -1 : 1; derived_path[i] = d_i == Infinity ? 1000 : d_i == -Infinity ? -1000 : d_i > 3 ? 1000 * x_sig_i : d_i < -3 ? -1000 * x_sig_i // vertical moves : Math.abs(d_i) < 0.5 ? 0 : d_i; // horizontal moves }; }; compute_derived_path(); /*########## STEP 2 : Create sub-paths(segments) and classify them in one of the two x halves ##########*/ var generate_segments = function () { for (var i = 0; i < l - min_length; ++i) { segs[i] = derived_path.slice(i, i + min_length); /* create sub-paths of min_length points (because of derivation) */ seg_xhalf[i] = [0]; if (path[i + min_length - 1][0] > path[i + 1][0]) { seg_xhalf[i] = 1; }; if (path[i + min_length - 1][0] <= path[i + 1][0]) { seg_xhalf[i] = -1; }; } }; generate_segments(); /*########## STEP 3 : Find the most frequent direction in every segment ##########*/ var diff = function (a, b) { return a - b; }; var find_popular = function () { for (var i = 0; i < l - min_length; ++i) { segs[i].sort(diff); // sorting to count duplicates more easily var previous = segs[i][0]; var popular = segs[i][0]; var count = 1; var max_count = 1; for (var j = 1; j < min_length; j++) { if (segs[i][j] == previous) { // if current = previous then increment occurrence count count++; } else { if (count > max_count) { // if occurrence count exceeds previous max save it popular = segs[i][j - 1]; max_count = count; }; previous = segs[i][j]; count = 1; }; var pop = count > max_count ? segs[i][min_length - 2] : popular; // handle case where the last element is the most frequent var cnt = count > max_count ? count : max_count; max_freqs[i] = [pop, cnt]; // max_freqs contains the popular segment direction and its number of occurrences } } }; find_popular(); /*########## STEP 4 : Eliminate segments with unclear overall direction ##########*/ var min_number_of_max = min_length - 3; // only segments where the most frequent value is present this many times or more are kept var eliminate_unclear = function () { for (var i = max_freqs.length - 1; i >= 0; i--) { // to ensure the segment has a clearly defined direction if (max_freqs[i][1] <= min_number_of_max) { max_freqs.splice(i, 1); seg_xhalf.splice(i, 1); }; } }; eliminate_unclear(); /*########## STEP 5 : Eliminate consecutive segments with same direction ##########*/ var eliminate_consecutive = function () { var previous = max_freqs[max_freqs.length - 1]; var previous_type = seg_xhalf[max_freqs.length - 1]; for (var i = max_freqs.length - 2; i >= 0; i--) { if (previous[0] === max_freqs[i][0]) { // same direction if (Math.abs(max_freqs[i][0]) > 500 /* same vertical */ || (max_freqs[i][0] === 0 && previous_type === seg_xhalf[i])) { // same horizontal if (previous[1] > max_freqs[i][1]) { // keep the duplicate with the greater max max_freqs.splice(i, 1); seg_xhalf.splice(i, 1); } else { max_freqs.splice(i + 1, 1); seg_xhalf.splice(i + 1, 1); }; } } previous = max_freqs[i]; previous_type = seg_xhalf[i]; } }; eliminate_consecutive(); /*########## STEP 6 : Parse the route and trigger the event ##########*/ var parse_route = function () { var route = []; for (var i = 0; i < max_freqs.length; ++i) { var p_i = max_freqs[i][0]; var t_x_i = seg_xhalf[i]; route[i] = p_i == -1000 ? "N" : p_i == 1000 ? "S" : (t_x_i > 0 ? "E" : "W"); } if (i !== 0) { dispatch({ route: route }); }; }; parse_route(); } start = stop = false; } addEventListener(touchStartEvent, handleTouchStart); addEventListener(touchMoveEvent, handleTouchMove); addEventListener(touchEndEvent, handleTouchEnd); })(this, document);
mit
bThink-BGU/BPjs
src/test/java/il/ac/bgu/cs/bp/bpjs/execution/BProgramRunnerTest.java
5807
/* * The MIT License * * Copyright 2017 michael. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package il.ac.bgu.cs.bp.bpjs.execution; import il.ac.bgu.cs.bp.bpjs.execution.listeners.BProgramRunnerListener; import il.ac.bgu.cs.bp.bpjs.execution.listeners.BProgramRunnerListenerAdapter; import il.ac.bgu.cs.bp.bpjs.execution.listeners.InMemoryEventLoggingListener; import il.ac.bgu.cs.bp.bpjs.model.BProgram; import il.ac.bgu.cs.bp.bpjs.model.FailedAssertionViolation; import il.ac.bgu.cs.bp.bpjs.model.ResourceBProgram; import il.ac.bgu.cs.bp.bpjs.model.StringBProgram; import il.ac.bgu.cs.bp.bpjs.execution.listeners.PrintBProgramRunnerListener; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * @author michael */ public class BProgramRunnerTest { public BProgramRunnerTest() { } /** * Test of start method, of class BProgramRunner. */ @Test public void testRun() { BProgram bprog = new ResourceBProgram("HotNCold.js"); BProgramRunner sut = new BProgramRunner(bprog); sut.addListener(new PrintBProgramRunnerListener()); sut.run(); } @Test public void testImmediateAssert() { BProgram bprog = new ResourceBProgram( "ImmediateAssert.js"); BProgramRunner runner = new BProgramRunner(bprog); InMemoryEventLoggingListener listener = new InMemoryEventLoggingListener(); runner.addListener(listener); runner.run(); FailedAssertionViolation expected = new FailedAssertionViolation("failRightAWay!", "forward"); assertEquals(expected, runner.getFailedAssertion()); assertEquals(0, listener.getEvents().size()); } @Test public void testExecutorName() { BProgram bprog = new StringBProgram( "var exName = 'initial value'\n" + "bp.registerBThread( function(){\n" + " exName = bp.getJavaThreadName();\n" + "});" ); new BProgramRunner(bprog).run(); String exName = bprog.getFromGlobalScope("exName", String.class).get(); assertTrue("Java executor name is wrong (got:'" + exName + "')", exName.startsWith("BProgramRunner-")); } @Test public void testErrorReport() { BProgram bprog = new StringBProgram( "bp.registerBThread( function(){\n" + " bp.sync({request:bp.Event(\"A\")});\n" + " bp.sync({request:bp.Event(\"A\")});\n" + " bp.sync({request:bp.Event(\"A\")});\n" + " var myNullVar;\n" + " myNullVar.isNullAndSoThisInvocationShouldCrash();\n" + " bp.sync({request:bp.Event(\"A\")});\n" + "});" ); BProgramRunner sut = new BProgramRunner(bprog); final AtomicBoolean errorCalled = new AtomicBoolean(); final AtomicBoolean errorMadeSense = new AtomicBoolean(); sut.addListener( new BProgramRunnerListenerAdapter() { @Override public void error(BProgram bp, Exception ex) { errorCalled.set(true); System.out.println(ex.getMessage()); System.out.println(ex.getCause().getMessage()); errorMadeSense.set(ex.getMessage().contains("isNullAndSoThisInvocationShouldCrash")); } }); sut.run(); assertTrue( errorCalled.get() ); assertTrue( errorMadeSense.get() ); } @Test(timeout=3000) public void testHalt() { BProgram bprog = new StringBProgram( "bp.registerBThread(function(){\n" + "while (true){\n" + "bp.sync({request:bp.Event(\"evt\")});"+ "}"+ "});" ); BProgramRunner rnr = new BProgramRunner(bprog); AtomicBoolean haltedCalled = new AtomicBoolean(); AtomicBoolean endedCalled = new AtomicBoolean(); rnr.addListener( new BProgramRunnerListenerAdapter() { @Override public void halted(BProgram bp) { haltedCalled.set(true); } @Override public void ended(BProgram bp) { endedCalled.set(true); } }); new Thread(()->{ try { Thread.sleep(1000); } catch (InterruptedException ex) {} rnr.halt(); }).start(); rnr.run(); assertTrue( haltedCalled.get() ); assertFalse( endedCalled.get() ); } }
mit
jsettlers/settlers-remake
go.graphics.swing/src/main/java/go/graphics/swing/contextcreator/AsyncContextCreator.java
4323
/******************************************************************************* * Copyright (c) 2018 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *******************************************************************************/ package go.graphics.swing.contextcreator; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.nio.IntBuffer; import javax.swing.JPanel; import javax.swing.SwingUtilities; import go.graphics.DrawmodeListener; import go.graphics.swing.GLContainer; import go.graphics.swing.event.swingInterpreter.GOSwingEventConverter; public abstract class AsyncContextCreator extends ContextCreator implements Runnable,DrawmodeListener { private boolean offscreen = true; private boolean clear_offscreen = true; private boolean continue_run = true; protected boolean ignore_resize = false; protected BufferedImage bi = null; protected IntBuffer pixels; private Thread render_thread; public AsyncContextCreator(GLContainer container, boolean debug) { super(container, debug); } @Override public void stop() { continue_run = false; } @Override public void initSpecific() { JPanel panel = new JPanel() { public void paintComponent(Graphics graphics) { super.paintComponent(graphics); if(first_draw) { SwingUtilities.windowForComponent(this).addKeyListener(new GOSwingEventConverter(parent, parent)); first_draw = false; } if(offscreen) { synchronized (wnd_lock) { graphics.drawImage(bi, 0, 0, null); graphics.dispose(); } } else { graphics.drawString("Press m to enable offscreen transfer", width/3, height/2); } } }; canvas = panel; render_thread = new Thread(this); render_thread.start(); } @Override public void repaint() { canvas.repaint(); } @Override public void requestFocus() { canvas.requestFocus(); } public abstract void async_init(); public abstract void async_set_size(int width, int height); public abstract void async_refresh(); public abstract void async_swapbuffers(); public abstract void async_stop(); @Override public void run() { async_init(); parent.wrapNewContext(); while(continue_run) { if (change_res) { if(!ignore_resize) { width = new_width; height = new_height; async_set_size(width, height); parent.resize_gl(width, height); bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); pixels = BufferUtils.createIntBuffer(width * height); } ignore_resize = false; change_res = false; } async_refresh(); parent.draw(); if (offscreen) { synchronized (wnd_lock) { GL11.glReadPixels(0, 0, width, height, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); for (int x = 0; x != width; x++) { for (int y = 0; y != height; y++) { bi.setRGB(x, height - y - 1, pixels.get(y * width + x)); } } } } if(!offscreen || clear_offscreen ){ if(clear_offscreen) { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); clear_offscreen = false; } async_swapbuffers(); } } async_stop(); } @Override public void changeDrawMode() { offscreen = !offscreen; clear_offscreen = true; } }
mit
Magnition/innova-partnerships
www/wordpress/wp-content/plugins/advanced-custom-fields-pro/assets/js/acf-input.js
189844
( function( window, undefined ) { "use strict"; /** * Handles managing all events for whatever you plug it into. Priorities for hooks are based on lowest to highest in * that, lowest priority hooks are fired first. */ var EventManager = function() { /** * Maintain a reference to the object scope so our public methods never get confusing. */ var MethodsAvailable = { removeFilter : removeFilter, applyFilters : applyFilters, addFilter : addFilter, removeAction : removeAction, doAction : doAction, addAction : addAction, storage : getStorage }; /** * Contains the hooks that get registered with this EventManager. The array for storage utilizes a "flat" * object literal such that looking up the hook utilizes the native object literal hash. */ var STORAGE = { actions : {}, filters : {} }; function getStorage() { return STORAGE; }; /** * Adds an action to the event manager. * * @param action Must contain namespace.identifier * @param callback Must be a valid callback function before this action is added * @param [priority=10] Used to control when the function is executed in relation to other callbacks bound to the same hook * @param [context] Supply a value to be used for this */ function addAction( action, callback, priority, context ) { if( typeof action === 'string' && typeof callback === 'function' ) { priority = parseInt( ( priority || 10 ), 10 ); _addHook( 'actions', action, callback, priority, context ); } return MethodsAvailable; } /** * Performs an action if it exists. You can pass as many arguments as you want to this function; the only rule is * that the first argument must always be the action. */ function doAction( /* action, arg1, arg2, ... */ ) { var args = Array.prototype.slice.call( arguments ); var action = args.shift(); if( typeof action === 'string' ) { _runHook( 'actions', action, args ); } return MethodsAvailable; } /** * Removes the specified action if it contains a namespace.identifier & exists. * * @param action The action to remove * @param [callback] Callback function to remove */ function removeAction( action, callback ) { if( typeof action === 'string' ) { _removeHook( 'actions', action, callback ); } return MethodsAvailable; } /** * Adds a filter to the event manager. * * @param filter Must contain namespace.identifier * @param callback Must be a valid callback function before this action is added * @param [priority=10] Used to control when the function is executed in relation to other callbacks bound to the same hook * @param [context] Supply a value to be used for this */ function addFilter( filter, callback, priority, context ) { if( typeof filter === 'string' && typeof callback === 'function' ) { priority = parseInt( ( priority || 10 ), 10 ); _addHook( 'filters', filter, callback, priority, context ); } return MethodsAvailable; } /** * Performs a filter if it exists. You should only ever pass 1 argument to be filtered. The only rule is that * the first argument must always be the filter. */ function applyFilters( /* filter, filtered arg, arg2, ... */ ) { var args = Array.prototype.slice.call( arguments ); var filter = args.shift(); if( typeof filter === 'string' ) { return _runHook( 'filters', filter, args ); } return MethodsAvailable; } /** * Removes the specified filter if it contains a namespace.identifier & exists. * * @param filter The action to remove * @param [callback] Callback function to remove */ function removeFilter( filter, callback ) { if( typeof filter === 'string') { _removeHook( 'filters', filter, callback ); } return MethodsAvailable; } /** * Removes the specified hook by resetting the value of it. * * @param type Type of hook, either 'actions' or 'filters' * @param hook The hook (namespace.identifier) to remove * @private */ function _removeHook( type, hook, callback, context ) { if ( !STORAGE[ type ][ hook ] ) { return; } if ( !callback ) { STORAGE[ type ][ hook ] = []; } else { var handlers = STORAGE[ type ][ hook ]; var i; if ( !context ) { for ( i = handlers.length; i--; ) { if ( handlers[i].callback === callback ) { handlers.splice( i, 1 ); } } } else { for ( i = handlers.length; i--; ) { var handler = handlers[i]; if ( handler.callback === callback && handler.context === context) { handlers.splice( i, 1 ); } } } } } /** * Adds the hook to the appropriate storage container * * @param type 'actions' or 'filters' * @param hook The hook (namespace.identifier) to add to our event manager * @param callback The function that will be called when the hook is executed. * @param priority The priority of this hook. Must be an integer. * @param [context] A value to be used for this * @private */ function _addHook( type, hook, callback, priority, context ) { var hookObject = { callback : callback, priority : priority, context : context }; // Utilize 'prop itself' : http://jsperf.com/hasownproperty-vs-in-vs-undefined/19 var hooks = STORAGE[ type ][ hook ]; if( hooks ) { hooks.push( hookObject ); hooks = _hookInsertSort( hooks ); } else { hooks = [ hookObject ]; } STORAGE[ type ][ hook ] = hooks; } /** * Use an insert sort for keeping our hooks organized based on priority. This function is ridiculously faster * than bubble sort, etc: http://jsperf.com/javascript-sort * * @param hooks The custom array containing all of the appropriate hooks to perform an insert sort on. * @private */ function _hookInsertSort( hooks ) { var tmpHook, j, prevHook; for( var i = 1, len = hooks.length; i < len; i++ ) { tmpHook = hooks[ i ]; j = i; while( ( prevHook = hooks[ j - 1 ] ) && prevHook.priority > tmpHook.priority ) { hooks[ j ] = hooks[ j - 1 ]; --j; } hooks[ j ] = tmpHook; } return hooks; } /** * Runs the specified hook. If it is an action, the value is not modified but if it is a filter, it is. * * @param type 'actions' or 'filters' * @param hook The hook ( namespace.identifier ) to be ran. * @param args Arguments to pass to the action/filter. If it's a filter, args is actually a single parameter. * @private */ function _runHook( type, hook, args ) { var handlers = STORAGE[ type ][ hook ]; if ( !handlers ) { return (type === 'filters') ? args[0] : false; } var i = 0, len = handlers.length; if ( type === 'filters' ) { for ( ; i < len; i++ ) { args[ 0 ] = handlers[ i ].callback.apply( handlers[ i ].context, args ); } } else { for ( ; i < len; i++ ) { handlers[ i ].callback.apply( handlers[ i ].context, args ); } } return ( type === 'filters' ) ? args[ 0 ] : true; } // return all of the publicly available methods return MethodsAvailable; }; window.wp = window.wp || {}; window.wp.hooks = new EventManager(); } )( window ); var acf; (function($){ /* * exists * * This function will return true if a jQuery selection exists * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param n/a * @return (boolean) */ $.fn.exists = function() { return $(this).length>0; }; /* * outerHTML * * This function will return a string containing the HTML of the selected element * * @type function * @date 19/11/2013 * @since 5.0.0 * * @param $.fn * @return (string) */ $.fn.outerHTML = function() { return $(this).get(0).outerHTML; }; acf = { // vars l10n: {}, o: {}, /* * update * * This function will update a value found in acf.o * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param k (string) the key * @param v (mixed) the value * @return n/a */ update: function( k, v ){ this.o[ k ] = v; }, /* * get * * This function will return a value found in acf.o * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param k (string) the key * @return v (mixed) the value */ get: function( k ){ if( typeof this.o[ k ] !== 'undefined' ) { return this.o[ k ]; } return null; }, /* * _e * * This functiln will return a string found in acf.l10n * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param k1 (string) the first key to look for * @param k2 (string) the second key to look for * @return string (string) */ _e: function( k1, k2 ){ // defaults k2 = k2 || false; // get context var string = this.l10n[ k1 ] || ''; // get string if( k2 ) { string = string[ k2 ] || ''; } // return return string; }, /* * add_action * * This function uses wp.hooks to mimics WP add_action * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param * @return */ add_action: function() { // vars var a = arguments[0].split(' '), l = a.length; // loop for( var i = 0; i < l; i++) { /* // allow for special actions if( a[i].indexOf('initialize') !== -1 ) { a.push( a[i].replace('initialize', 'ready') ); a.push( a[i].replace('initialize', 'append') ); l = a.length; continue; } */ // prefix action arguments[0] = 'acf/' + a[i]; // add wp.hooks.addAction.apply(this, arguments); } // return return this; }, /* * remove_action * * This function uses wp.hooks to mimics WP remove_action * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param * @return */ remove_action: function() { // prefix action arguments[0] = 'acf/' + arguments[0]; wp.hooks.removeAction.apply(this, arguments); return this; }, /* * do_action * * This function uses wp.hooks to mimics WP do_action * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param * @return */ do_action: function() { //console.log('acf.do_action(%o)', arguments); // prefix action arguments[0] = 'acf/' + arguments[0]; wp.hooks.doAction.apply(this, arguments); return this; }, /* * add_filter * * This function uses wp.hooks to mimics WP add_filter * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param * @return */ add_filter: function() { // prefix action arguments[0] = 'acf/' + arguments[0]; wp.hooks.addFilter.apply(this, arguments); return this; }, /* * remove_filter * * This function uses wp.hooks to mimics WP remove_filter * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param * @return */ remove_filter: function() { // prefix action arguments[0] = 'acf/' + arguments[0]; wp.hooks.removeFilter.apply(this, arguments); return this; }, /* * apply_filters * * This function uses wp.hooks to mimics WP apply_filters * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param * @return */ apply_filters: function() { //console.log('acf.apply_filters(%o)', arguments); // prefix action arguments[0] = 'acf/' + arguments[0]; return wp.hooks.applyFilters.apply(this, arguments); }, /* * get_selector * * This function will return a valid selector for finding a field object * * @type function * @date 15/01/2015 * @since 5.1.5 * * @param s (string) * @return (string) */ get_selector: function( s ) { // defaults s = s || ''; // vars var selector = '.acf-field'; // compatibility with object if( $.isPlainObject(s) ) { if( $.isEmptyObject(s) ) { s = ''; } else { for( k in s ) { s = s[k]; break; } } } // search if( s ) { // append selector += '-' + s; // replace underscores (split/join replaces all and is faster than regex!) selector = selector.split('_').join('-'); // remove potential double up selector = selector.split('field-field-').join('field-'); } // return return selector; }, /* * get_fields * * This function will return a jQuery selection of fields * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param args (object) * @param $el (jQuery) element to look within * @param all (boolean) return all fields or allow filtering (for repeater) * @return $fields (jQuery) */ get_fields: function( s, $el, all ){ // debug //console.log( 'acf.get_fields(%o, %o, %o)', args, $el, all ); //console.time("acf.get_fields"); // defaults s = s || ''; $el = $el || false; all = all || false; // vars var selector = this.get_selector(s); // get child fields var $fields = $( selector, $el ); // append context to fields if also matches selector. // * Required for field group 'change_filed_type' append $tr to work if( $el !== false ) { $el.each(function(){ if( $(this).is(selector) ) { $fields = $fields.add( $(this) ); } }); } // filter out fields if( !all ) { $fields = acf.apply_filters('get_fields', $fields); } //console.log('get_fields(%o, %o, %o) %o', s, $el, all, $fields); //console.log('acf.get_fields(%o):', this.get_selector(s) ); //console.timeEnd("acf.get_fields"); // return return $fields; }, /* * get_field * * This function will return a jQuery selection based on a field key * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param field_key (string) * @param $el (jQuery) element to look within * @return $field (jQuery) */ get_field: function( s, $el ){ // defaults s = s || ''; $el = $el || false; // get fields var $fields = this.get_fields(s, $el, true); // check if exists if( $fields.exists() ) { return $fields.first(); } // return return false; }, /* * get_closest_field * * This function will return the closest parent field * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param $el (jQuery) element to start from * @param args (object) * @return $field (jQuery) */ get_closest_field : function( $el, s ){ // defaults s = s || ''; // return return $el.closest( this.get_selector(s) ); }, /* * get_field_wrap * * This function will return the closest parent field * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param $el (jQuery) element to start from * @return $field (jQuery) */ get_field_wrap: function( $el ){ return $el.closest( this.get_selector() ); }, /* * get_field_key * * This function will return the field's key * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param $field (jQuery) * @return (string) */ get_field_key: function( $field ){ return $field.data('key'); }, /* * get_field_type * * This function will return the field's type * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param $field (jQuery) * @return (string) */ get_field_type: function( $field ){ return $field.data('type'); }, /* * get_data * * This function will return attribute data for a given elemnt * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param $el (jQuery) * @param name (mixed) * @return (mixed) */ get_data: function( $el, name ){ //console.log('get_data(%o, %o)', name, $el); // get all datas if( typeof name === 'undefined' ) { return $el.data(); } // return return $el.data(name); }, /* * get_uniqid * * This function will return a unique string ID * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param prefix (string) * @param more_entropy (boolean) * @return (string) */ get_uniqid : function( prefix, more_entropy ){ // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + revised by: Kankrelune (http://www.webfaktory.info/) // % note 1: Uses an internal counter (in php_js global) to avoid collision // * example 1: uniqid(); // * returns 1: 'a30285b160c14' // * example 2: uniqid('foo'); // * returns 2: 'fooa30285b1cd361' // * example 3: uniqid('bar', true); // * returns 3: 'bara20285b23dfd1.31879087' if (typeof prefix === 'undefined') { prefix = ""; } var retId; var formatSeed = function (seed, reqWidth) { seed = parseInt(seed, 10).toString(16); // to hex str if (reqWidth < seed.length) { // so long we split return seed.slice(seed.length - reqWidth); } if (reqWidth > seed.length) { // so short we pad return Array(1 + (reqWidth - seed.length)).join('0') + seed; } return seed; }; // BEGIN REDUNDANT if (!this.php_js) { this.php_js = {}; } // END REDUNDANT if (!this.php_js.uniqidSeed) { // init seed with big random int this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15); } this.php_js.uniqidSeed++; retId = prefix; // start with prefix, add current milliseconds hex string retId += formatSeed(parseInt(new Date().getTime() / 1000, 10), 8); retId += formatSeed(this.php_js.uniqidSeed, 5); // add seed hex string if (more_entropy) { // for more entropy we add a float lower to 10 retId += (Math.random() * 10).toFixed(8).toString(); } return retId; }, /* * serialize_form * * This function will create an object of data containing all form inputs within an element * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param $el (jQuery selection) * @return $post_id (int) */ serialize_form : function( $el ){ // vars var data = {}, names = {}; // selector $selector = $el.find('select, textarea, input'); // populate data $.each( $selector.serializeArray(), function( i, pair ) { // initiate name if( pair.name.slice(-2) === '[]' ) { // remove [] pair.name = pair.name.replace('[]', ''); // initiate counter if( typeof names[ pair.name ] === 'undefined'){ names[ pair.name ] = -1; } // increase counter names[ pair.name ]++; // add key pair.name += '[' + names[ pair.name ] +']'; } // append to data data[ pair.name ] = pair.value; }); // return return data; }, serialize: function( $el ){ return this.serialize_form( $el ); }, /* * remove_tr * * This function will remove a tr element with animation * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param $tr (jQuery selection) * @param callback (function) runs on complete * @return n/a */ remove_tr : function( $tr, callback ){ // vars var height = $tr.height(), children = $tr.children().length; // add class $tr.addClass('acf-remove-element'); // after animation setTimeout(function(){ // remove class $tr.removeClass('acf-remove-element'); // vars $tr.html('<td style="padding:0; height:' + height + 'px" colspan="' + children + '"></td>'); $tr.children('td').animate({ height : 0}, 250, function(){ $tr.remove(); if( typeof(callback) == 'function' ) { callback(); } }); }, 250); }, /* * remove_el * * This function will remove an element with animation * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param $el (jQuery selection) * @param callback (function) runs on complete * @param end_height (int) * @return n/a */ remove_el : function( $el, callback, end_height ){ // defaults end_height = end_height || 0; // set layout $el.css({ height : $el.height(), width : $el.width(), position : 'absolute', //padding : 0 }); // wrap field $el.wrap( '<div class="acf-temp-wrap" style="height:' + $el.outerHeight(true) + 'px"></div>' ); // fade $el $el.animate({ opacity : 0 }, 250); // remove $el.parent('.acf-temp-wrap').animate({ height : end_height }, 250, function(){ $(this).remove(); if( typeof(callback) == 'function' ) { callback(); } }); }, /* * isset * * This function will return true if an object key exists * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param (object) * @param key1 (string) * @param key2 (string) * @param ... * @return (boolean) */ isset : function(){ var a = arguments, l = a.length, c = null, undef; if (l === 0) { throw new Error('Empty isset'); } c = a[0]; for (i = 1; i < l; i++) { if (a[i] === undef || c[ a[i] ] === undef) { return false; } c = c[ a[i] ]; } return true; }, /* * maybe_get * * This function will attempt to return a value and return null if not possible * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param obj (object) the array to look within * @param key (key) the array key to look for. Nested values may be found using '/' * @param value (mixed) the value returned if not found * @return (mixed) */ maybe_get: function( obj, key, value ){ // default if( typeof value == 'undefined' ) value = null; // convert type to string and split keys = String(key).split('.'); // loop through keys for( var i in keys ) { // vars var key = keys[i]; // bail ealry if not set if( typeof obj[ key ] === 'undefined' ) { return value; } // update obj obj = obj[ key ]; } // return return obj; }, /* * open_popup * * This function will create and open a popup modal * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param args (object) * @return n/a */ open_popup : function( args ){ // vars $popup = $('body > #acf-popup'); // already exists? if( $popup.exists() ) { return update_popup(args); } // template var tmpl = [ '<div id="acf-popup">', '<div class="acf-popup-box acf-box">', '<div class="title"><h3></h3><a href="#" class="acf-icon -cancel grey acf-close-popup"></a></div>', '<div class="inner"></div>', '<div class="loading"><i class="acf-loading"></i></div>', '</div>', '<div class="bg"></div>', '</div>' ].join(''); // append $('body').append( tmpl ); $('#acf-popup').on('click', '.bg, .acf-close-popup', function( e ){ e.preventDefault(); acf.close_popup(); }); // update return this.update_popup(args); }, /* * update_popup * * This function will update the content within a popup modal * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param args (object) * @return n/a */ update_popup : function( args ){ // vars $popup = $('#acf-popup'); // validate if( !$popup.exists() ) { return false } // defaults args = $.extend({}, { title : '', content : '', width : 0, height : 0, loading : false }, args); if( args.title ) { $popup.find('.title h3').html( args.title ); } if( args.content ) { $inner = $popup.find('.inner:first'); $inner.html( args.content ); acf.do_action('append', $inner); // update height $inner.attr('style', 'position: relative;'); args.height = $inner.outerHeight(); $inner.removeAttr('style'); } if( args.width ) { $popup.find('.acf-popup-box').css({ 'width' : args.width, 'margin-left' : 0 - (args.width / 2), }); } if( args.height ) { // add h3 height (44) args.height += 44; $popup.find('.acf-popup-box').css({ 'height' : args.height, 'margin-top' : 0 - (args.height / 2), }); } if( args.loading ) { $popup.find('.loading').show(); } else { $popup.find('.loading').hide(); } return $popup; }, /* * close_popup * * This function will close and remove a popup modal * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param n/a * @return n/a */ close_popup : function(){ // vars $popup = $('#acf-popup'); // already exists? if( $popup.exists() ) { $popup.remove(); } }, /* * update_user_setting * * This function will send an AJAX request to update a user setting * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ update_user_setting : function( name, value ) { // ajax $.ajax({ url : acf.get('ajaxurl'), dataType : 'html', type : 'post', data : acf.prepare_for_ajax({ 'action' : 'acf/update_user_setting', 'name' : name, 'value' : value }) }); }, /* * prepare_for_ajax * * This function will prepare data for an AJAX request * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param args (object) * @return args */ prepare_for_ajax : function( args ) { // nonce args.nonce = acf.get('nonce'); // filter for 3rd party customization args = acf.apply_filters('prepare_for_ajax', args); // return return args; }, /* * is_ajax_success * * This function will return true for a successful WP AJAX response * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param json (object) * @return (boolean) */ is_ajax_success : function( json ) { if( json && json.success ) { return true; } return false; }, /* * get_ajax_message * * This function will return an object containing error/message information * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param json (object) * @return (boolean) */ get_ajax_message: function( json ) { // vars var message = { text: '', type: 'error' }; // bail early if no json if( !json ) { return message; } // PHP error (too may themes will have warnings / errors. Don't show these in ACF taxonomy popup) /* if( typeof json === 'string' ) { message.text = json; return message; } */ // success if( json.success ) { message.type = 'success'; } // message if( json.data && json.data.message ) { message.text = json.data.message; } // error if( json.data && json.data.error ) { message.text = json.data.error; } // return return message; }, /* * is_in_view * * This function will return true if a jQuery element is visible in browser * * @type function * @date 8/09/2014 * @since 5.0.0 * * @param $el (jQuery) * @return (boolean) */ is_in_view: function( $el ) { // vars var elemTop = $el.offset().top, elemBottom = elemTop + $el.height(); // bail early if hidden if( elemTop === elemBottom ) { return false; } // more vars var docViewTop = $(window).scrollTop(), docViewBottom = docViewTop + $(window).height(); // return return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); }, /* * val * * This function will update an elements value and trigger the change event if different * * @type function * @date 16/10/2014 * @since 5.0.9 * * @param $el (jQuery) * @param val (mixed) * @return n/a */ val: function( $el, val ){ // vars var orig = $el.val(); // update value $el.val( val ); // trigger change if( val != orig ) { $el.trigger('change'); } }, /* * str_replace * * This function will perform a str replace similar to php function str_replace * * @type function * @date 1/05/2015 * @since 5.2.3 * * @param $search (string) * @param $replace (string) * @param $subject (string) * @return (string) */ str_replace: function( search, replace, subject ) { return subject.split(search).join(replace); }, /* * str_sanitize * * description * * @type function * @date 4/06/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ str_sanitize: function( string ) { // vars var string2 = '', replace = { 'æ': 'a', 'å': 'a', 'á': 'a', 'ä': 'a', 'č': 'c', 'ď': 'd', 'è': 'e', 'é': 'e', 'ě': 'e', 'ë': 'e', 'í': 'i', 'ĺ': 'l', 'ľ': 'l', 'ň': 'n', 'ø': 'o', 'ó': 'o', 'ô': 'o', 'ő': 'o', 'ö': 'o', 'ŕ': 'r', 'š': 's', 'ť': 't', 'ú': 'u', 'ů': 'u', 'ű': 'u', 'ü': 'u', 'ý': 'y', 'ř': 'r', 'ž': 'z', ' ': '_', '\'': '', '?': '', '/': '', '\\': '', '.': '', ',': '', '>': '', '<': '', '"': '', '[': '', ']': '', '|': '', '{': '', '}': '', '(': '', ')': '' }; // lowercase string = string.toLowerCase(); // loop through characters for( i = 0; i < string.length; i++ ) { // character var c = string.charAt(i); // override c with replacement if( typeof replace[c] !== 'undefined' ) { c = replace[c]; } // append string2 += c; } // return return string2; }, /* * render_select * * This function will update a select field with new choices * * @type function * @date 8/04/2014 * @since 5.0.0 * * @param $select * @param choices * @return n/a */ render_select: function( $select, choices ){ // vars var value = $select.val(); // clear choices $select.html(''); // bail early if no choices if( !choices ) { return; } // populate choices $.each(choices, function( i, item ){ // vars var $optgroup = $select; // add group if( item.group ) { $optgroup = $select.find('optgroup[label="' + item.group + '"]'); if( !$optgroup.exists() ) { $optgroup = $('<optgroup label="' + item.group + '"></optgroup>'); $select.append( $optgroup ); } } // append select $optgroup.append( '<option value="' + item.value + '">' + item.label + '</option>' ); // selectedIndex if( value == item.value ) { $select.prop('selectedIndex', i); } }); }, /* * duplicate * * This function will duplicate and return an element * * @type function * @date 22/08/2015 * @since 5.2.3 * * @param $el (jQuery) object to be duplicated * @param attr (string) attrbute name where $el id can be found * @return $el2 (jQuery) */ duplicate: function( $el, attr ){ //console.time('duplicate'); // defaults attr = attr || 'data-id'; // vars find = $el.attr(attr); replace = acf.get_uniqid(); // allow acf to modify DOM // fixes bug where select field option is not selected acf.do_action('before_duplicate', $el); // clone var $el2 = $el.clone(); // remove acf-clone (may be a clone) $el2.removeClass('acf-clone'); // remove JS functionality acf.do_action('remove', $el2); // find / replace if( typeof find !== 'undefined' ) { // replcae data attribute $el2.attr(attr, replace); // replace ids $el2.find('[id*="' + find + '"]').each(function(){ $(this).attr('id', $(this).attr('id').replace(find, replace) ); }); // replace names $el2.find('[name*="' + find + '"]').each(function(){ $(this).attr('name', $(this).attr('name').replace(find, replace) ); }); // replace label for $el2.find('label[for*="' + find + '"]').each(function(){ $(this).attr('for', $(this).attr('for').replace(find, replace) ); }); } // remove ui-sortable $el2.find('.ui-sortable').removeClass('ui-sortable'); // allow acf to modify DOM acf.do_action('after_duplicate', $el, $el2 ); // append $el.after( $el2 ); // add JS functionality // - allow element to be moved into a visible position before fire action setTimeout(function(){ acf.do_action('append', $el2); }, 1); //console.timeEnd('duplicate'); // return return $el2; }, decode: function( string ){ return $('<div/>').html( string ).text(); }, /* * parse_args * * This function will merge together defaults and args much like the WP wp_parse_args function * * @type function * @date 11/04/2016 * @since 5.3.8 * * @param args (object) * @param defaults (object) * @return args */ parse_args: function( args, defaults ) { return $.extend({}, defaults, args); } }; /* * acf.model * * This model acts as a scafold for action.event driven modules * * @type object * @date 8/09/2014 * @since 5.0.0 * * @param (object) * @return (object) */ acf.model = { // vars actions: {}, filters: {}, events: {}, extend: function( args ){ // extend var model = $.extend( {}, this, args ); // setup actions $.each(model.actions, function( name, callback ){ model._add_action( name, callback ); }); // setup filters $.each(model.filters, function( name, callback ){ model._add_filter( name, callback ); }); // setup events $.each(model.events, function( name, callback ){ model._add_event( name, callback ); }); // return return model; }, _add_action: function( name, callback ) { // split var model = this, data = name.split(' '); // add missing priority var name = data[0] || '', priority = data[1] || 10; // add action acf.add_action(name, model[ callback ], priority, model); }, _add_filter: function( name, callback ) { // split var model = this, data = name.split(' '); // add missing priority var name = data[0] || '', priority = data[1] || 10; // add action acf.add_filter(name, model[ callback ], priority, model); }, _add_event: function( name, callback ) { // vars var model = this, event = name.substr(0,name.indexOf(' ')), selector = name.substr(name.indexOf(' ')+1); // add event $(document).on(event, selector, function( e ){ // append $el to event object e.$el = $(this); // event if( typeof model.event === 'function' ) { e = model.event( e ); } // callback model[ callback ].apply(model, [e]); }); }, get: function( name, value ){ // defaults value = value || null; // get if( typeof this[ name ] !== 'undefined' ) { value = this[ name ]; } // return return value; }, set: function( name, value ){ // set this[ name ] = value; // function for 3rd party if( typeof this[ '_set_' + name ] === 'function' ) { this[ '_set_' + name ].apply(this); } // return for chaining return this; } }; /* * field * * This model sets up many of the field's interactions * * @type function * @date 21/02/2014 * @since 3.5.1 * * @param n/a * @return n/a */ acf.field = acf.model.extend({ // vars type: '', o: {}, $field: null, _add_action: function( name, callback ) { // vars var model = this; // update name name = name + '_field/type=' + model.type; // add action acf.add_action(name, function( $field ){ // focus model.set('$field', $field); // callback model[ callback ].apply(model, arguments); }); }, _add_filter: function( name, callback ) { // vars var model = this; // update name name = name + '_field/type=' + model.type; // add action acf.add_filter(name, function( $field ){ // focus model.set('$field', $field); // callback model[ callback ].apply(model, arguments); }); }, _add_event: function( name, callback ) { // vars var model = this, event = name.substr(0,name.indexOf(' ')), selector = name.substr(name.indexOf(' ')+1), context = acf.get_selector(model.type); // add event $(document).on(event, context + ' ' + selector, function( e ){ // append $el to event object e.$el = $(this); e.$field = acf.get_closest_field(e.$el, model.type); // focus model.set('$field', e.$field); // callback model[ callback ].apply(model, [e]); }); }, _set_$field: function(){ // callback if( typeof this.focus === 'function' ) { this.focus(); } }, // depreciated doFocus: function( $field ){ return this.set('$field', $field); } }); /* * field * * This model fires actions and filters for registered fields * * @type function * @date 21/02/2014 * @since 3.5.1 * * @param n/a * @return n/a */ acf.fields = acf.model.extend({ actions: { 'prepare' : '_prepare', 'prepare_field' : '_prepare_field', 'ready' : '_ready', 'ready_field' : '_ready_field', 'append' : '_append', 'append_field' : '_append_field', 'load' : '_load', 'load_field' : '_load_field', 'remove' : '_remove', 'remove_field' : '_remove_field', 'sortstart' : '_sortstart', 'sortstart_field' : '_sortstart_field', 'sortstop' : '_sortstop', 'sortstop_field' : '_sortstop_field', 'show' : '_show', 'show_field' : '_show_field', 'hide' : '_hide', 'hide_field' : '_hide_field', }, // prepare _prepare: function( $el ){ acf.get_fields('', $el).each(function(){ acf.do_action('prepare_field', $(this)); }); }, _prepare_field: function( $el ){ acf.do_action('prepare_field/type=' + $el.data('type'), $el); }, // ready _ready: function( $el ){ acf.get_fields('', $el).each(function(){ acf.do_action('ready_field', $(this)); }); }, _ready_field: function( $el ){ acf.do_action('ready_field/type=' + $el.data('type'), $el); }, // append _append: function( $el ){ acf.get_fields('', $el).each(function(){ acf.do_action('append_field', $(this)); }); }, _append_field: function( $el ){ acf.do_action('append_field/type=' + $el.data('type'), $el); }, // load _load: function( $el ){ acf.get_fields('', $el).each(function(){ acf.do_action('load_field', $(this)); }); }, _load_field: function( $el ){ acf.do_action('load_field/type=' + $el.data('type'), $el); }, // remove _remove: function( $el ){ acf.get_fields('', $el).each(function(){ acf.do_action('remove_field', $(this)); }); }, _remove_field: function( $el ){ acf.do_action('remove_field/type=' + $el.data('type'), $el); }, // sortstart _sortstart: function( $el, $placeholder ){ acf.get_fields('', $el).each(function(){ acf.do_action('sortstart_field', $(this), $placeholder); }); }, _sortstart_field: function( $el, $placeholder ){ acf.do_action('sortstart_field/type=' + $el.data('type'), $el, $placeholder); }, // sortstop _sortstop: function( $el, $placeholder ){ acf.get_fields('', $el).each(function(){ acf.do_action('sortstop_field', $(this), $placeholder); }); }, _sortstop_field: function( $el, $placeholder ){ acf.do_action('sortstop_field/type=' + $el.data('type'), $el, $placeholder); }, // hide _hide: function( $el, context ){ acf.get_fields('', $el).each(function(){ acf.do_action('hide_field', $(this), context); }); }, _hide_field: function( $el, context ){ acf.do_action('hide_field/type=' + $el.data('type'), $el, context); }, // show _show: function( $el, context ){ acf.get_fields('', $el).each(function(){ acf.do_action('show_field', $(this), context); }); }, _show_field: function( $el, context ){ acf.do_action('show_field/type=' + $el.data('type'), $el, context); } }); /* * ready * * description * * @type function * @date 19/02/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ $(document).ready(function(){ // action for 3rd party customization acf.do_action('ready', $('body')); }); /* * load * * description * * @type function * @date 19/02/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ $(window).on('load', function(){ // action for 3rd party customization acf.do_action('load', $('body')); }); /* * layout * * This model handles the width layout for fields * * @type function * @date 21/02/2014 * @since 3.5.1 * * @param n/a * @return n/a */ acf.layout = acf.model.extend({ active: 0, actions: { 'refresh': 'refresh', }, refresh: function( $el ){ //console.time('acf.width.render'); // defaults $el = $el || false; // loop over visible fields $('.acf-fields:visible', $el).each(function(){ // vars var $els = $(), top = 0, height = 0, cell = -1; // get fields var $fields = $(this).children('.acf-field[data-width]:visible'); // bail early if no fields if( !$fields.exists() ) { return; } // reset fields $fields.removeClass('acf-r0 acf-c0').css({'min-height': 0}); $fields.each(function( i ){ // vars var $el = $(this), this_top = $el.position().top; // set top if( i == 0 ) { top = this_top; } // detect new row if( this_top != top ) { // set previous heights $els.css({'min-height': (height+1)+'px'}); // reset $els = $(); top = $el.position().top; // don't use variable as this value may have changed due to min-height css height = 0; cell = -1; } // increase cell++; // set height height = ($el.outerHeight() > height) ? $el.outerHeight() : height; // append $els = $els.add( $el ); // add classes if( this_top == 0 ) { $el.addClass('acf-r0'); } else if( cell == 0 ) { $el.addClass('acf-c0'); } }); // clean up if( $els.exists() ) { $els.css({'min-height': (height+1)+'px'}); } }); //console.timeEnd('acf.width.render'); } }); /* * Force revisions * * description * * @type function * @date 19/02/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ $(document).on('change', '.acf-field input, .acf-field textarea, .acf-field select', function(){ // preview hack if( $('#acf-form-data input[name="_acfchanged"]').exists() ) { $('#acf-form-data input[name="_acfchanged"]').val(1); } // action for 3rd party customization acf.do_action('change', $(this)); }); /* * preventDefault helper * * This function will prevent default of any link with an href of # * * @type function * @date 24/07/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ $(document).on('click', '.acf-field a[href="#"]', function( e ){ e.preventDefault(); }); /* * unload * * This model handles the unload prompt * * @type function * @date 21/02/2014 * @since 3.5.1 * * @param n/a * @return n/a */ acf.unload = acf.model.extend({ active: 1, changed: 0, filters: { 'validation_complete': 'validation_complete' }, actions: { 'change': 'on', 'submit': 'off' }, events: { 'submit form': 'off', }, validation_complete: function( json, $form ){ if( json && json.errors ) { this.on(); } // return return json; }, on: function(){ // bail ealry if already changed (or not active) if( this.changed || !this.active ) { return; } // update this.changed = 1; // add event $(window).on('beforeunload', this.unload); }, off: function(){ // update this.changed = 0; // remove event $(window).off('beforeunload', this.unload); }, unload: function(){ // alert string return acf._e('unload'); } }); acf.tooltip = acf.model.extend({ $el: null, events: { 'mouseenter .acf-js-tooltip': 'on', 'mouseleave .acf-js-tooltip': 'off', }, on: function( e ){ //console.log('on'); // vars var title = e.$el.attr('title'); // hide empty titles if( !title ) { return; } // $t this.$el = $('<div class="acf-tooltip">' + title + '</div>'); // append $('body').append( this.$el ); // position var tolerance = 10; target_w = e.$el.outerWidth(), target_h = e.$el.outerHeight(), target_t = e.$el.offset().top, target_l = e.$el.offset().left, tooltip_w = this.$el.outerWidth(), tooltip_h = this.$el.outerHeight(); // calculate top var top = target_t - tooltip_h, left = target_l + (target_w / 2) - (tooltip_w / 2); // too far left if( left < tolerance ) { this.$el.addClass('right'); left = target_l + target_w; top = target_t + (target_h / 2) - (tooltip_h / 2); // too far right } else if( (left + tooltip_w + tolerance) > $(window).width() ) { this.$el.addClass('left'); left = target_l - tooltip_w; top = target_t + (target_h / 2) - (tooltip_h / 2); // too far top } else if( top - $(window).scrollTop() < tolerance ) { this.$el.addClass('bottom'); top = target_t + target_h; } else { this.$el.addClass('top'); } // update css this.$el.css({ 'top': top, 'left': left }); // avoid double title e.$el.data('title', title); e.$el.attr('title', ''); }, off: function( e ){ //console.log('off'); // bail early if no $el if( !this.$el ) { return; } // replace title e.$el.attr('title', e.$el.data('title')); // remove tooltip this.$el.remove(); } }); acf.postbox = acf.model.extend({ events: { 'mouseenter .acf-postbox .handlediv': 'on', 'mouseleave .acf-postbox .handlediv': 'off', }, on: function( e ){ e.$el.siblings('.hndle').addClass('hover'); }, off: function( e ){ e.$el.siblings('.hndle').removeClass('hover'); }, render: function( args ){ // defaults args = $.extend({}, { id: '', key: '', style: 'default', label: 'top', edit_url: '', edit_title: '', visibility: true }, args); // vars var $postbox = $('#' + args.id), $toggle = $('#' + args.id + '-hide'), $label = $toggle.parent(); // add class $postbox.addClass('acf-postbox'); $label.addClass('acf-postbox-toggle'); // remove class $postbox.removeClass('hide-if-js'); $label.removeClass('hide-if-js'); // field group style if( args.style !== 'default' ) { $postbox.addClass( args.style ); } // .inside class $postbox.children('.inside').addClass('acf-fields').addClass('-' + args.label); // visibility if( args.visibility ) { $toggle.prop('checked', true); } else { $postbox.addClass('acf-hidden'); $label.addClass('acf-hidden'); } // edit_url if( args.edit_url ) { $postbox.children('.hndle').append('<a href="' + args.edit_url + '" class="dashicons dashicons-admin-generic acf-hndle-cog acf-js-tooltip" title="' + args.edit_title + '"></a>'); } } }); /* * Sortable * * These functions will hook into the start and stop of a jQuery sortable event and modify the item and placeholder * * @type function * @date 12/11/2013 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ acf.add_action('sortstart', function( $item, $placeholder ){ // if $item is a tr, apply some css to the elements if( $item.is('tr') ) { // temp set as relative to find widths $item.css('position', 'relative'); // set widths for td children $item.children().each(function(){ $(this).width($(this).width()); }); // revert position css $item.css('position', 'absolute'); // add markup to the placeholder $placeholder.html('<td style="height:' + $item.height() + 'px; padding:0;" colspan="' + $item.children('td').length + '"></td>'); } }); /* * before & after duplicate * * This function will modify the DOM before it is cloned. Primarily fixes a cloning issue with select elements * * @type function * @date 16/05/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ acf.add_action('before_duplicate', function( $orig ){ // save select values $orig.find('select option:selected').addClass('selected'); }); acf.add_action('after_duplicate', function( $orig, $duplicate ){ // restore select values $orig.find('select option.selected').removeClass('selected'); // set select values $duplicate.find('select').each(function(){ // vars var val = []; // loop $(this).find('option.selected').each(function(){ // append val.push( $(this).val() ); // remove class $(this).removeClass('selected'); }); // set val $(this).val( val ); }); }); /* console.time("acf_test_ready"); console.time("acf_test_load"); acf.add_action('ready', function(){ console.timeEnd("acf_test_ready"); }, 999); acf.add_action('load', function(){ console.timeEnd("acf_test_load"); }, 999); */ })(jQuery); (function($){ acf.ajax = acf.model.extend({ actions: { 'ready': 'ready' }, events: { 'change #page_template': '_change_template', 'change #parent_id': '_change_parent', 'change #post-formats-select input': '_change_format', 'change .categorychecklist input': '_change_term', 'change .acf-taxonomy-field[data-save="1"] input': '_change_term', 'change .acf-taxonomy-field[data-save="1"] select': '_change_term' }, o: { //'post_id': 0, //'page_template': 0, //'page_parent': 0, //'page_type': 0, //'post_format': 0, //'post_taxonomy': 0, }, xhr: null, //timeout: null, update: function( k, v ){ this.o[ k ] = v; return this; }, get: function( k ){ return this.o[ k ] || null; }, ready: function(){ // update post_id this.update('post_id', acf.get('post_id')); }, /* maybe_fetch: function(){ // reference var self = this; // abort timeout if( this.timeout ) { clearTimeout( this.timeout ); } // fetch this.timeout = setTimeout(function(){ self.fetch(); }, 100); }, */ fetch: function(){ // bail early if no ajax if( !acf.get('ajax') ) return; // abort XHR if is already loading AJAX data if( this.xhr ) { this.xhr.abort(); } // vars var self = this, data = this.o; // add action url data.action = 'acf/post/get_field_groups'; // add ignore data.exists = []; $('.acf-postbox').not('.acf-hidden').each(function(){ data.exists.push( $(this).attr('id').substr(4) ); }); // ajax this.xhr = $.ajax({ url: acf.get('ajaxurl'), data: acf.prepare_for_ajax( data ), type: 'post', dataType: 'json', success: function( json ){ if( acf.is_ajax_success( json ) ) { self.render( json.data ); } } }); }, render: function( json ){ // hide $('.acf-postbox').addClass('acf-hidden'); $('.acf-postbox-toggle').addClass('acf-hidden'); // show the new postboxes $.each(json, function( k, field_group ){ // vars var $postbox = $('#acf-' + field_group.key), $toggle = $('#acf-' + field_group.key + '-hide'), $label = $toggle.parent(); // show // use show() to force display when postbox has been hidden by 'Show on screen' toggle $postbox.removeClass('acf-hidden hide-if-js').show(); $label.removeClass('acf-hidden hide-if-js').show(); $toggle.prop('checked', true); // replace HTML if needed var $replace = $postbox.find('.acf-replace-with-fields'); if( $replace.exists() ) { $replace.replaceWith( field_group.html ); acf.do_action('append', $postbox); } // update style if needed if( k === 0 ) { $('#acf-style').html( field_group.style ); } // enable inputs $postbox.find('.acf-hidden-by-postbox').prop('disabled', false); }); // disable inputs $('.acf-postbox.acf-hidden').find('select, textarea, input').not(':disabled').each(function(){ $(this).addClass('acf-hidden-by-postbox').prop('disabled', true); }); }, sync_taxonomy_terms: function(){ // vars var values = ['']; // loop over term lists $('.categorychecklist, .acf-taxonomy-field').each(function(){ // vars var $el = $(this), $checkbox = $el.find('input[type="checkbox"]').not(':disabled'), $radio = $el.find('input[type="radio"]').not(':disabled'), $select = $el.find('select').not(':disabled'), $hidden = $el.find('input[type="hidden"]').not(':disabled'); // bail early if not a field which saves taxonomy terms to post if( $el.is('.acf-taxonomy-field') && $el.attr('data-save') != '1' ) { return; } // bail early if in attachment if( $el.closest('.media-frame').exists() ) { return; } // checkbox if( $checkbox.exists() ) { $checkbox.filter(':checked').each(function(){ values.push( $(this).val() ); }); } else if( $radio.exists() ) { $radio.filter(':checked').each(function(){ values.push( $(this).val() ); }); } else if( $select.exists() ) { $select.find('option:selected').each(function(){ values.push( $(this).val() ); }); } else if( $hidden.exists() ) { $hidden.each(function(){ // ignor blank values if( ! $(this).val() ) { return; } values.push( $(this).val() ); }); } }); // filter duplicates values = values.filter (function (v, i, a) { return a.indexOf (v) == i }); // update screen this.update( 'post_taxonomy', values ).fetch(); }, /* * events * * description * * @type function * @date 29/09/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ _change_template: function( e ){ // vars var page_template = e.$el.val(); // update & fetch this.update('page_template', page_template).fetch(); }, _change_parent: function( e ){ // vars var page_type = 'parent', page_parent = 0; // if is child if( e.$el.val() != "" ) { page_type = 'child'; page_parent = e.$el.val(); } // update & fetch this.update('page_type', page_type).update('page_parent', page_parent).fetch(); }, _change_format: function( e ){ // vars var post_format = e.$el.val(); // default if( post_format == '0' ) { post_format = 'standard'; } // update & fetch this.update('post_format', post_format).fetch(); }, _change_term: function( e ){ // reference var self = this; // bail early if within media popup if( e.$el.closest('.media-frame').exists() ) { return; } // set timeout to fix issue with chrome which does not register the change has yet happened setTimeout(function(){ self.sync_taxonomy_terms(); }, 1); } }); })(jQuery); (function($){ acf.fields.checkbox = acf.field.extend({ type: 'checkbox', events: { 'change input': 'change' }, change: function( e ){ // vars var $ul = e.$el.closest('ul'), $inputs = $ul.find('input[name]'), checked = e.$el.is(':checked'); // is toggle? if( e.$el.hasClass('acf-checkbox-toggle') ) { // toggle all $inputs.prop('checked', checked); // return return; } // bail early if no toggle if( !$ul.find('.acf-checkbox-toggle').exists() ) { return; } // determine if all inputs are checked var checked = ( $inputs.not(':checked').length == 0 ); // update toggle $ul.find('.acf-checkbox-toggle').prop('checked', checked); } }); })(jQuery); (function($){ acf.fields.color_picker = acf.field.extend({ type: 'color_picker', $input: null, $hidden: null, actions: { 'ready': 'initialize', 'append': 'initialize' }, focus: function(){ this.$input = this.$field.find('input[type="text"]'); this.$hidden = this.$field.find('input[type="hidden"]'); }, initialize: function(){ // reference var $input = this.$input, $hidden = this.$hidden; // trigger change function var change_hidden = function(){ // timeout is required to ensure the $input val is correct setTimeout(function(){ acf.val( $hidden, $input.val() ); }, 1); } // args var args = { defaultColor: false, palettes: true, hide: true, change: change_hidden, clear: change_hidden } // filter var args = acf.apply_filters('color_picker_args', args, this.$field); // iris this.$input.wpColorPicker(args); } }); })(jQuery); (function($){ acf.conditional_logic = acf.model.extend({ actions: { 'prepare 20': 'render', 'append 20': 'render' }, events: { 'change .acf-field input': 'change', 'change .acf-field textarea': 'change', 'change .acf-field select': 'change' }, items: {}, triggers: {}, /* * add * * This function will add a set of conditional logic rules * * @type function * @date 22/05/2015 * @since 5.2.3 * * @param target (string) target field key * @param groups (array) rule groups * @return $post_id (int) */ add: function( target, groups ){ // debug //console.log( 'conditional_logic.add(%o, %o)', target, groups ); // populate triggers for( var i in groups ) { // vars var group = groups[i]; for( var k in group ) { // vars var rule = group[k], trigger = rule.field, triggers = this.triggers[ trigger ] || {}; // append trigger (sub field will simply override) triggers[ target ] = target; // update this.triggers[ trigger ] = triggers; } } // append items this.items[ target ] = groups; }, /* * render * * This function will render all fields * * @type function * @date 22/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ render: function( $el ){ // debug //console.log('conditional_logic.render(%o)', $el); // defaults $el = $el || false; // get targets var $targets = acf.get_fields( '', $el, true ); // render fields this.render_fields( $targets ); // action for 3rd party customization acf.do_action('refresh', $el); }, /* * change * * This function is called when an input is changed and will render any fields which are considered targets of this trigger * * @type function * @date 22/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ change: function( e ){ // debug //console.log( 'conditional_logic.change(%o)', $input ); // vars var $input = e.$el, $field = acf.get_field_wrap( $input ), key = $field.data('key'); // bail early if this field does not trigger any actions if( typeof this.triggers[key] === 'undefined' ) { return false; } // vars $parent = $field.parent(); // update visibility for( var i in this.triggers[ key ] ) { // get the target key var target_key = this.triggers[ key ][ i ]; // get targets var $targets = acf.get_fields(target_key, $parent, true); // render this.render_fields( $targets ); } // action for 3rd party customization acf.do_action('refresh', $parent); }, /* * render_fields * * This function will render a selection of fields * * @type function * @date 22/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ render_fields: function( $targets ) { // reference var self = this; // loop over targets and render them $targets.each(function(){ self.render_field( $(this) ); }); }, /* * render_field * * This function will render a field * * @type function * @date 22/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ render_field : function( $target ){ // vars var key = $target.data('key'); // bail early if this field does not contain any conditional logic if( typeof this.items[ key ] === 'undefined' ) { return false; } // vars var visibility = false; // debug //console.log( 'conditional_logic.render_field(%o)', $field ); // get conditional logic var groups = this.items[ key ]; // calculate visibility for( var i in groups ) { // vars var group = groups[i], match_group = true; for( var k in group ) { // vars var rule = group[k]; // get trigger for rule var $trigger = this.get_trigger( $target, rule.field ); // break if rule did not validate if( !this.calculate(rule, $trigger, $target) ) { match_group = false; break; } } // set visibility if rule group did validate if( match_group ) { visibility = true; break; } } // hide / show field if( visibility ) { this.show_field( $target ); } else { this.hide_field( $target ); } }, /* * show_field * * This function will show a field * * @type function * @date 22/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ show_field: function( $field ){ // debug //console.log('show_field(%o)', $field); // bail early if field is already visible // Note: Do not bail early! Instead, allow show_field to run on already visible fields. // This fixes an issue where showing a repeater field would enable sub field inputs which // should remain hidden due to another conditiona logic rule /* if( !$field.hasClass('hidden-by-conditional-logic') ) { return; } */ // remove class $field.removeClass( 'hidden-by-conditional-logic' ); // remove "disabled" // ignore inputs which have a class of 'acf-disabled'. These inputs are disabled for life // ignore inputs which are hidden by conditiona logic of a sub field $field.find('.acf-clhi').not('.hidden-by-conditional-logic .acf-clhi').removeClass('acf-clhi').prop('disabled', false); // action for 3rd party customization acf.do_action('show_field', $field, 'conditional_logic' ); }, /* * hide_field * * This function will hide a field * * @type function * @date 22/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ hide_field : function( $field ){ // debug //console.log('hide_field(%o)', $field); // bail early if field is already hidden /* if( $field.hasClass('hidden-by-conditional-logic') ) { return; } */ // add class $field.addClass( 'hidden-by-conditional-logic' ); // add "disabled" $field.find('input, textarea, select').not('.acf-disabled').addClass('acf-clhi').prop('disabled', true); // action for 3rd party customization acf.do_action('hide_field', $field, 'conditional_logic' ); }, /* * get_trigger * * This function will return the relevant $trigger for a $target * * @type function * @date 22/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ get_trigger: function( $target, key ){ // vars var selector = acf.get_selector( key ); // find sibling $trigger var $trigger = $target.siblings( selector ); // parent trigger if( !$trigger.exists() ) { // vars var parent = acf.get_selector(); // loop through parent fields and review their siblings too $target.parents( parent ).each(function(){ // find sibling $trigger $trigger = $(this).siblings( selector ); // bail early if $trigger is found if( $trigger.exists() ) { return false; } }); } // bail early if no $trigger is found if( !$trigger.exists() ) { return false; } // return return $trigger; }, /* * calculate * * This function will calculate if a rule matches based on the $trigger * * @type function * @date 22/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ calculate : function( rule, $trigger, $target ){ // bail early if $trigger could not be found if( !$trigger || !$target ) return false; // debug //console.log( 'calculate(%o, %o, %o)', rule, $trigger, $target); // vars var match = false, type = $trigger.data('type'); // input with :checked if( type == 'true_false' || type == 'checkbox' || type == 'radio' ) { match = this.calculate_checkbox( rule, $trigger ); } else if( type == 'select' ) { match = this.calculate_select( rule, $trigger ); } // reverse if 'not equal to' if( rule.operator === "!=" ) { match = !match; } // return return match; }, calculate_checkbox: function( rule, $trigger ){ // look for selected input var match = $trigger.find('input[value="' + rule.value + '"]:checked').exists(); // override for "allow null" if( rule.value === '' && !$trigger.find('input:checked').exists() ) { match = true; } // return return match; }, calculate_select: function( rule, $trigger ){ // vars var $select = $trigger.find('select'), val = $select.val(); // check for no value if( !val && !$.isNumeric(val) ) { val = ''; } // convert to array if( !$.isArray(val) ) { val = [ val ]; } // calc match = ($.inArray(rule.value, val) > -1); // return return match; } }); })(jQuery); (function($){ acf.fields.date_picker = acf.field.extend({ type: 'date_picker', $el: null, $input: null, $hidden: null, o : {}, actions: { 'ready': 'initialize', 'append': 'initialize' }, events: { 'blur input[type="text"]': 'blur', }, focus: function(){ // get elements this.$el = this.$field.find('.acf-date_picker'); this.$input = this.$el.find('input[type="text"]'); this.$hidden = this.$el.find('input[type="hidden"]'); // get options this.o = acf.get_data( this.$el ); }, initialize: function(){ // get and set value from alt field this.$input.val( this.$hidden.val() ); // create options var args = $.extend( {}, acf.l10n.date_picker, { dateFormat : 'yymmdd', altField : this.$hidden, altFormat : 'yymmdd', changeYear : true, yearRange : "-100:+100", changeMonth : true, showButtonPanel : true, firstDay : this.o.first_day }); // filter for 3rd party customization args = acf.apply_filters('date_picker_args', args, this.$field); // add date picker this.$input.addClass('active').datepicker( args ); // now change the format back to how it should be. this.$input.datepicker( "option", "dateFormat", this.o.display_format ); // wrap the datepicker (only if it hasn't already been wrapped) if( $('body > #ui-datepicker-div').exists() ) { $('body > #ui-datepicker-div').wrap('<div class="acf-ui-datepicker" />'); } }, blur : function(){ if( !this.$input.val() ) { this.$hidden.val(''); } } }); })(jQuery); (function($){ acf.fields.file = acf.field.extend({ type: 'file', $el: null, $input: null, actions: { 'ready': 'initialize', 'append': 'initialize' }, events: { 'click a[data-name="add"]': 'add', 'click a[data-name="edit"]': 'edit', 'click a[data-name="remove"]': 'remove', 'change input[type="file"]': 'change' }, /* * focus * * This function will setup variables when focused on a field * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param n/a * @return n/a */ focus: function(){ // get elements this.$el = this.$field.find('.acf-file-uploader'); this.$input = this.$el.find('input[type="hidden"]'); // get options this.o = acf.get_data( this.$el ); }, /* * initialize * * This function is used to setup basic upload form attributes * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param n/a * @return n/a */ initialize: function(){ // add attribute to form if( this.o.uploader == 'basic' ) { this.$el.closest('form').attr('enctype', 'multipart/form-data'); } }, /* * prepare * * This function will prepare an object of attachment data * selecting a library image vs embed an image via url return different data * this function will keep the 2 consistent * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param attachment (object) * @return data (object) */ prepare: function( attachment ) { // defaults attachment = attachment || {}; // bail ealry if already valid if( attachment._valid ) return attachment; // vars var data = { url: '', alt: '', title: '', filename: '', filesize: '', icon: '/wp-includes/images/media/default.png' }; // wp image if( attachment.id ) { // update data data = attachment.attributes; } // valid data._valid = true; // return return data; }, /* * render * * This function will render the UI * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param attachment (obj) * @return n/a */ render: function( data ){ // prepare data = this.prepare(data); // update els this.$el.find('img').attr({ src: data.icon, alt: data.alt, title: data.title }); this.$el.find('[data-name="title"]').text( data.title ); this.$el.find('[data-name="filename"]').text( data.filename ).attr( 'href', data.url ); this.$el.find('[data-name="filesize"]').text( data.filesize ); // vars var val = ''; // WP attachment if( data.id ) { val = data.id; } // update val acf.val( this.$input, val ); // update class if( val ) { this.$el.addClass('has-value'); } else { this.$el.removeClass('has-value'); } }, /* * add * * event listener * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param e (event) * @return n/a */ add: function() { // reference var self = this, $field = this.$field; // get repeater var $repeater = acf.get_closest_field( $field, 'repeater' ); // popup var frame = acf.media.popup({ title: acf._e('file', 'select'), mode: 'select', type: '', field: $field.data('key'), multiple: $repeater.exists(), library: this.o.library, mime_types: this.o.mime_types, select: function( attachment, i ) { // select / add another image field? if( i > 0 ) { // vars var key = $field.data('key'), $tr = $field.closest('.acf-row'); // reset field $field = false; // find next image field $tr.nextAll('.acf-row:visible').each(function(){ // get next $field $field = acf.get_field( key, $(this) ); // bail early if $next was not found if( !$field ) return; // bail early if next file uploader has value if( $field.find('.acf-file-uploader.has-value').exists() ) { $field = false; return; } // end loop if $next is found return false; }); // add extra row if next is not found if( !$field ) { $tr = acf.fields.repeater.doFocus( $repeater ).add(); // bail early if no $tr (maximum rows hit) if( !$tr ) return false; // get next $field $field = acf.get_field( key, $tr ); } } // render self.set('$field', $field).render( attachment ); } }); }, /* * edit * * event listener * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param e (event) * @return n/a */ edit: function() { // reference var self = this, $field = this.$field; // vars var val = this.$input.val(); // bail early if no val if( !val ) return; // popup var frame = acf.media.popup({ title: acf._e('file', 'edit'), button: acf._e('file', 'update'), mode: 'edit', attachment: val, select: function( attachment, i ) { // render self.set('$field', $field).render( attachment ); } }); }, /* * remove * * event listener * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param e (event) * @return n/a */ remove: function() { // vars var attachment = {}; // add file to field this.render( attachment ); }, /* * change * * This function will update the hidden input when selecting a basic file to clear validation errors * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param e (event) * @return n/a */ change: function( e ){ this.$input.val( e.$el.val() ); } }); })(jQuery); (function($){ acf.fields.google_map = acf.field.extend({ type: 'google_map', $el: null, $search: null, timeout: null, status : '', // '', 'loading', 'ready' geocoder : false, map : false, maps : {}, $pending: $(), actions: { 'ready': 'initialize', 'append': 'initialize', 'show': 'show' }, events: { 'click a[data-name="clear"]': '_clear', 'click a[data-name="locate"]': '_locate', 'click a[data-name="search"]': '_search', 'keydown .search': '_keydown', 'keyup .search': '_keyup', 'focus .search': '_focus', 'blur .search': '_blur', //'paste .search': '_paste', 'mousedown .acf-google-map': '_mousedown', }, focus: function(){ // get elements this.$el = this.$field.find('.acf-google-map'); this.$search = this.$el.find('.search'); // get options this.o = acf.get_data( this.$el ); // get map if( this.maps[ this.o.id ] ) { this.map = this.maps[ this.o.id ]; } }, /* * is_ready * * This function will ensure google API is available and return a boolean for the current status * * @type function * @date 19/11/2014 * @since 5.0.9 * * @param n/a * @return (boolean) */ is_ready: function(){ // reference var self = this; // ready if( this.status == 'ready' ) { return true; } // loading if( this.status == 'loading' ) { return false; } // no google if( !acf.isset(window, 'google', 'load') ) { // set status self.status = 'loading'; // load API $.getScript('https://www.google.com/jsapi', function(){ // load maps google.load('maps', '3', { other_params: 'sensor=false&libraries=places', callback: function(){ // set status self.status = 'ready'; // initialize pending self.initialize_pending(); }}); }); return false; } // no maps or places if( !acf.isset(window, 'google', 'maps', 'places') ) { // set status self.status = 'loading'; // load maps google.load('maps', '3', { other_params: 'sensor=false&libraries=places', callback: function(){ // set status self.status = 'ready'; // initialize pending self.initialize_pending(); }}); return false; } // google must exist already this.status = 'ready'; // return return true; }, initialize_pending: function(){ // reference var self = this; this.$pending.each(function(){ self.doFocus( $(this) ).initialize(); }); // reset this.$pending = $(); }, /* * actions * * these functions are fired for this fields actions * * @type function * @date 17/09/2015 * @since 5.2.3 * * @param (mixed) * @return n/a */ initialize: function(){ // add to pending if( !this.is_ready() ) { this.$pending = this.$pending.add( this.$field ); return false; } // load geocode if( !this.geocoder ) { this.geocoder = new google.maps.Geocoder(); } // reference var self = this, $field = this.$field, $el = this.$el, $search = this.$search; // input value may be cached by browser, so update the search input to match $search.val( this.$el.find('.input-address').val() ); // map var map_args = acf.apply_filters('google_map_args', { zoom: parseInt(this.o.zoom), center: new google.maps.LatLng(this.o.lat, this.o.lng), mapTypeId: google.maps.MapTypeId.ROADMAP }, this.$field); // create map this.map = new google.maps.Map( this.$el.find('.canvas')[0], map_args); // add search var autocomplete = new google.maps.places.Autocomplete( this.$search[0] ); autocomplete.bindTo('bounds', this.map); this.map.autocomplete = autocomplete; // marker var marker_args = acf.apply_filters('google_map_marker_args', { draggable: true, raiseOnDrag: true, map: this.map }, this.$field); // add marker this.map.marker = new google.maps.Marker( marker_args ); // add references this.map.$el = $el; this.map.$field = $field; // value exists? var lat = $el.find('.input-lat').val(), lng = $el.find('.input-lng').val(); if( lat && lng ) { this.update(lat, lng).center(); } // events google.maps.event.addListener(autocomplete, 'place_changed', function( e ) { // vars var place = this.getPlace(); // search self.search( place ); }); google.maps.event.addListener( this.map.marker, 'dragend', function(){ // vars var position = this.map.marker.getPosition(), lat = position.lat(), lng = position.lng(); self.update( lat, lng ).sync(); }); google.maps.event.addListener( this.map, 'click', function( e ) { // vars var lat = e.latLng.lat(), lng = e.latLng.lng(); self.update( lat, lng ).sync(); }); // add to maps this.maps[ this.o.id ] = this.map; }, search: function( place ){ // reference var self = this; // vars var address = this.$search.val(); // bail ealry if no address if( !address ) { return false; } // update input this.$el.find('.input-address').val( address ); // is lat lng? var latLng = address.split(','); if( latLng.length == 2 ) { var lat = latLng[0], lng = latLng[1]; if( $.isNumeric(lat) && $.isNumeric(lng) ) { // parse lat = parseFloat(lat); lng = parseFloat(lng); self.update( lat, lng ).center(); return; } } // if place exists if( place && place.geometry ) { var lat = place.geometry.location.lat(), lng = place.geometry.location.lng(); // update self.update( lat, lng ).center(); // bail early return; } // add class this.$el.addClass('-loading'); self.geocoder.geocode({ 'address' : address }, function( results, status ){ // remove class self.$el.removeClass('-loading'); // validate if( status != google.maps.GeocoderStatus.OK ) { console.log('Geocoder failed due to: ' + status); return; } else if( !results[0] ) { console.log('No results found'); return; } // get place place = results[0]; var lat = place.geometry.location.lat(), lng = place.geometry.location.lng(); self.update( lat, lng ).center(); }); }, update: function( lat, lng ){ // vars var latlng = new google.maps.LatLng( lat, lng ); // update inputs acf.val( this.$el.find('.input-lat'), lat ); acf.val( this.$el.find('.input-lng'), lng ); // update marker this.map.marker.setPosition( latlng ); // show marker this.map.marker.setVisible( true ); // update class this.$el.addClass('-value'); // validation this.$field.removeClass('error'); // action acf.do_action('google_map_change', latlng, this.map, this.$field); // blur input this.$search.blur(); // return for chaining return this; }, center: function(){ // vars var position = this.map.marker.getPosition(), lat = this.o.lat, lng = this.o.lng; // if marker exists, center on the marker if( position ) { lat = position.lat(); lng = position.lng(); } var latlng = new google.maps.LatLng( lat, lng ); // set center of map this.map.setCenter( latlng ); }, sync: function(){ // reference var self = this; // vars var position = this.map.marker.getPosition(), latlng = new google.maps.LatLng( position.lat(), position.lng() ); // add class this.$el.addClass('-loading'); // load this.geocoder.geocode({ 'latLng' : latlng }, function( results, status ){ // remove class self.$el.removeClass('-loading'); // validate if( status != google.maps.GeocoderStatus.OK ) { console.log('Geocoder failed due to: ' + status); return; } else if( !results[0] ) { console.log('No results found'); return; } // get location var location = results[0]; // update title self.$search.val( location.formatted_address ); // update input acf.val( self.$el.find('.input-address'), location.formatted_address ); }); // return for chaining return this; }, refresh: function(){ // bail early if not ready if( !this.is_ready() ) { return false; } // trigger resize on map google.maps.event.trigger(this.map, 'resize'); // center map this.center(); }, show: function(){ // vars var self = this, $field = this.$field; // center map when it is shown (by a tab / collapsed row) // - use delay to avoid rendering issues with browsers (ensures div is visible) setTimeout(function(){ self.set('$field', $field).refresh(); }, 10); }, /* * events * * these functions are fired for this fields events * * @type function * @date 17/09/2015 * @since 5.2.3 * * @param e * @return n/a */ _clear: function( e ){ // console.log('_clear'); // remove Class this.$el.removeClass('-value -loading -search'); // clear search this.$search.val(''); // clear inputs acf.val( this.$el.find('.input-address'), '' ); acf.val( this.$el.find('.input-lat'), '' ); acf.val( this.$el.find('.input-lng'), '' ); // hide marker this.map.marker.setVisible( false ); }, _locate: function( e ){ // console.log('_locate'); // reference var self = this; // Try HTML5 geolocation if( !navigator.geolocation ) { alert( acf._e('google_map', 'browser_support') ); return this; } // add class this.$el.addClass('-loading'); // load navigator.geolocation.getCurrentPosition(function(position){ // remove class self.$el.removeClass('-loading'); // vars var lat = position.coords.latitude, lng = position.coords.longitude; self.update( lat, lng ).sync().center(); }); }, _search: function( e ){ // console.log('_search'); this.search(); }, _focus: function( e ){ // console.log('_focus'); // remove class this.$el.removeClass('-value'); // toggle -search class this._keyup(); }, _blur: function( e ){ // console.log('_blur'); // reference var self = this; // vars var val = this.$el.find('.input-address').val(); // bail early if no val if( !val ) { return; } // revert search to hidden input value this.timeout = setTimeout(function(){ self.$el.addClass('-value'); self.$search.val( val ); }, 100); }, /* _paste: function( e ){ console.log('_paste'); // reference var $search = this.$search; // blur search $search.blur(); // clear timeout this._mousedown(e); // focus on input setTimeout(function(){ $search.focus(); }, 1); }, */ _keydown: function( e ){ // console.log('_keydown'); // prevent form from submitting if( e.which == 13 ) { e.preventDefault(); } }, _keyup: function( e ){ // console.log('_keyup'); // vars var val = this.$search.val(); // toggle class if( val ) { this.$el.addClass('-search'); } else { this.$el.removeClass('-search'); } }, _mousedown: function( e ){ // console.log('_mousedown'); // reference var self = this; // clear timeout in 1ms (_mousedown will run before _blur) setTimeout(function(){ clearTimeout( self.timeout ); }, 1); } }); })(jQuery); (function($){ acf.fields.image = acf.field.extend({ type: 'image', $el: null, $input: null, $img: null, actions: { 'ready': 'initialize', 'append': 'initialize' }, events: { 'click a[data-name="add"]': 'add', 'click a[data-name="edit"]': 'edit', 'click a[data-name="remove"]': 'remove', 'change input[type="file"]': 'change' }, /* * focus * * This function will setup variables when focused on a field * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param n/a * @return n/a */ focus: function(){ // vars this.$el = this.$field.find('.acf-image-uploader'); this.$input = this.$el.find('input[type="hidden"]'); this.$img = this.$el.find('img'); // options this.o = acf.get_data( this.$el ); }, /* * initialize * * This function is used to setup basic upload form attributes * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param n/a * @return n/a */ initialize: function(){ // add attribute to form if( this.o.uploader == 'basic' ) { this.$el.closest('form').attr('enctype', 'multipart/form-data'); } }, /* * prepare * * This function will prepare an object of attachment data * selecting a library image vs embed an image via url return different data * this function will keep the 2 consistent * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param attachment (object) * @return data (object) */ prepare: function( attachment ) { // defaults attachment = attachment || {}; // bail ealry if already valid if( attachment._valid ) return attachment; // vars var data = { url: '', alt: '', title: '', caption: '', description: '', width: 0, height: 0 }; // wp image if( attachment.id ) { // update data data = attachment.attributes; // maybe get preview size data.url = acf.maybe_get(data, 'sizes.'+this.o.preview_size+'.url', data.url); } // valid data._valid = true; // return return data; }, /* * render * * This function will render the UI * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param attachment (obj) * @return n/a */ render: function( data ){ // prepare data = this.prepare(data); // update image this.$img.attr({ src: data.url, alt: data.alt, title: data.title }); // vars var val = ''; // WP attachment if( data.id ) { val = data.id; } // update val acf.val( this.$input, val ); // update class if( val ) { this.$el.addClass('has-value'); } else { this.$el.removeClass('has-value'); } }, /* * add * * event listener * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param e (event) * @return n/a */ add: function() { // reference var self = this, $field = this.$field; // get repeater var $repeater = acf.get_closest_field( this.$field, 'repeater' ); // popup var frame = acf.media.popup({ title: acf._e('image', 'select'), mode: 'select', type: 'image', field: $field.data('key'), multiple: $repeater.exists(), library: this.o.library, mime_types: this.o.mime_types, select: function( attachment, i ) { // select / add another image field? if( i > 0 ) { // vars var key = $field.data('key'), $tr = $field.closest('.acf-row'); // reset field $field = false; // find next image field $tr.nextAll('.acf-row:visible').each(function(){ // get next $field $field = acf.get_field( key, $(this) ); // bail early if $next was not found if( !$field ) return; // bail early if next file uploader has value if( $field.find('.acf-image-uploader.has-value').exists() ) { $field = false; return; } // end loop if $next is found return false; }); // add extra row if next is not found if( !$field ) { $tr = acf.fields.repeater.doFocus( $repeater ).add(); // bail early if no $tr (maximum rows hit) if( !$tr ) return false; // get next $field $field = acf.get_field( key, $tr ); } } // render self.set('$field', $field).render( attachment ); } }); }, /* * edit * * event listener * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param e (event) * @return n/a */ edit: function() { // reference var self = this, $field = this.$field; // vars var val = this.$input.val(); // bail early if no val if( !val ) return; // popup var frame = acf.media.popup({ title: acf._e('image', 'edit'), button: acf._e('image', 'update'), mode: 'edit', attachment: val, select: function( attachment, i ) { // render self.set('$field', $field).render( attachment ); } }); }, /* * remove * * event listener * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param e (event) * @return n/a */ remove: function() { // vars var attachment = {}; // add file to field this.render( attachment ); }, /* * change * * This function will update the hidden input when selecting a basic file to clear validation errors * * @type function * @date 12/04/2016 * @since 5.3.8 * * @param e (event) * @return n/a */ change: function( e ){ this.$input.val( e.$el.val() ); } }); })(jQuery); (function($){ acf.media = acf.model.extend({ frames: [], mime_types: {}, actions: { 'ready': 'ready' }, /* * frame * * This function will return the current frame * * @type function * @date 11/04/2016 * @since 5.3.2 * * @param n/a * @return frame (object) */ frame: function(){ // vars var i = this.frames.length - 1; // bail early if no index if( i < 0 ) return false; // return return this.frames[ i ]; }, /* * destroy * * this function will destroy a frame * * @type function * @date 11/04/2016 * @since 5.3.8 * * @return frame (object) * @return n/a */ destroy: function( frame ) { // detach frame.detach(); frame.dispose(); // remove frame frame = null; this.frames.pop(); }, /* * popup * * This function will create a wp media popup frame * * @type function * @date 11/04/2016 * @since 5.3.8 * * @param args (object) * @return frame (object) */ popup: function( args ) { // vars var post_id = acf.get('post_id'), frame = false; // validate post_id if( !$.isNumeric(post_id) ) post_id = 0; // settings var settings = acf.parse_args( args, { mode: 'select', // 'select', 'edit' title: '', // 'Upload Image' button: '', // 'Select Image' type: '', // 'image', '' field: '', // 'field_123' mime_types: '', // 'pdf, etc' library: 'all', // 'all', 'uploadedTo' multiple: false, // false, true, 'add' attachment: 0, // the attachment to edit post_id: post_id, // the post being edited select: function(){} }); // id changed to attributes if( settings.id ) settings.attachment = settings.id; // create frame var frame = this.new_media_frame( settings ); // append this.frames.push( frame ); // open popup (allow frame customization before opening) setTimeout(function(){ frame.open(); }, 1); // return return frame; }, /* * _get_media_frame_settings * * This function will return an object containing frame settings * * @type function * @date 11/04/2016 * @since 5.3.8 * * @param frame (object) * @param settings (object) * @return frame (object) */ _get_media_frame_settings: function( frame, settings ){ // select if( settings.mode === 'select' ) { frame = this._get_select_frame_settings( frame, settings ); // edit } else if( settings.mode === 'edit' ) { frame = this._get_edit_frame_settings( frame, settings ); } // return return frame; }, _get_select_frame_settings: function( frame, settings ){ // type if( settings.type ) { frame.library.type = settings.type; } // library if( settings.library === 'uploadedTo' ) { frame.library.uploadedTo = settings.post_id; } // button frame._button = acf._e('media', 'select'); // return return frame; }, _get_edit_frame_settings: function( frame, settings ){ // post__in frame.library.post__in = [ settings.attachment ]; // button frame._button = acf._e('media', 'update'); // return return frame; }, /* * _add_media_frame_events * * This function will add events to the frame object * * @type function * @date 11/04/2016 * @since 5.3.8 * * @param $post_id (int) * @return $post_id (int) */ _add_media_frame_events: function( frame, settings ){ // log events /* frame.on('all', function( e ) { console.log( 'frame all: %o', e ); }); */ // add class frame.on('open',function() { // add class this.$el.closest('.media-modal').addClass('acf-media-modal -' +settings.mode ); }, frame); // edit image view // source: media-views.js:2410 editImageContent() frame.on('content:render:edit-image', function(){ var image = this.state().get('image'), view = new wp.media.view.EditImage( { model: image, controller: this } ).render(); this.content.set( view ); // after creating the wrapper view, load the actual editor via an ajax call view.loadEditor(); }, frame); // update toolbar button frame.on( 'toolbar:create:select', function( toolbar ) { toolbar.view = new wp.media.view.Toolbar.Select({ text: frame.options._button, controller: this }); }, frame ); // select image frame.on('select', function() { // get selected images var state = frame.state(), image = state.get('image'), selection = state.get('selection'); // if editing image if( image ) { settings.select.apply( frame, [image, 0] ); return; } // if selecting images if( selection ) { // vars var i = 0; // loop selection.each(function( attachment ){ settings.select.apply( frame, [attachment, i] ); i++; }); return; } }); // close popup frame.on('close',function(){ setTimeout(function(){ acf.media.destroy( frame ); }, 500); }); // select if( settings.mode === 'select' ) { frame = this._add_select_frame_events( frame, settings ); // edit } else if( settings.mode === 'edit' ) { frame = this._add_edit_frame_events( frame, settings ); } // return return frame; }, _add_select_frame_events: function( frame, settings ){ // reference var self = this; // plupload // adds _acfuploader param to validate uploads if( acf.isset(_wpPluploadSettings, 'defaults', 'multipart_params') ) { // add _acfuploader so that Uploader will inherit _wpPluploadSettings.defaults.multipart_params._acfuploader = settings.field; // remove acf_field so future Uploaders won't inherit frame.on('open', function(){ delete _wpPluploadSettings.defaults.multipart_params._acfuploader; }); } // modify DOM frame.on('content:activate:browse', function(){ // populate above vars making sure to allow for failure try { var toolbar = frame.content.get().toolbar, filters = toolbar.get('filters'), search = toolbar.get('search'); } catch(e) { // one of the objects was 'undefined'... perhaps the frame open is Upload Files // console.log( 'error %o', e ); return; } // image if( settings.type == 'image' ) { // update all filters.filters.all.text = acf._e('image', 'all'); // remove some filters delete filters.filters.audio; delete filters.filters.video; // update all filters to show images $.each( filters.filters, function( k, filter ){ if( filter.props.type === null ) { filter.props.type = 'image'; } }); } // custom mime types if( settings.mime_types ) { // explode var extra_types = settings.mime_types.split(' ').join('').split('.').join('').split(','); // loop through mime_types $.each( extra_types, function( i, type ){ // find mime $.each( self.mime_types, function( t, mime ){ // continue if key does not match if( t.indexOf(type) === -1 ) { return; } // create new filter var filter = { text: type, props: { status: null, type: mime, uploadedTo: null, orderby: 'date', order: 'DESC' }, priority: 20 }; // append filter filters.filters[ mime ] = filter; }); }); } // uploaded to post if( settings.library == 'uploadedTo' ) { // remove some filters delete filters.filters.unattached; delete filters.filters.uploaded; // add 'uploadedTo' text filters.$el.parent().append('<span class="acf-uploadedTo">' + acf._e('image', 'uploadedTo') + '</span>'); // add uploadedTo to filters $.each( filters.filters, function( k, filter ){ filter.props.uploadedTo = post_id; }); } // add _acfuploader to filters $.each( filters.filters, function( k, filter ){ filter.props._acfuploader = settings.field; }); // add _acfuplaoder to search search.model.attributes._acfuploader = settings.field; // render if( typeof filters.refresh === 'function' ) { filters.refresh(); } }); // return return frame; }, _add_edit_frame_events: function( frame, settings ){ // add class frame.on('open',function() { // add class this.$el.closest('.media-modal').addClass('acf-expanded'); // set to browse if( this.content.mode() != 'browse' ) { this.content.mode('browse'); } // set selection var state = this.state(), selection = state.get('selection'), attachment = wp.media.attachment( settings.attachment ); selection.add( attachment ); }, frame); // return return frame; }, /* * new_media_frame * * this function will create a new media frame * * @type function * @date 11/04/2016 * @since 5.3.8 * * @param settings (object) * @return frame (object) */ new_media_frame: function( settings ){ // vars var attributes = { title: settings.title, multiple: settings.multiple, library: {}, states: [], }; // get options attributes = this._get_media_frame_settings( attributes, settings ); // create query var Query = wp.media.query( attributes.library ); // add _acfuploader // this is super wack! // if you add _acfuploader to the options.library args, new uploads will not be added to the library view. // this has been traced back to the wp.media.model.Query initialize function (which can't be overriden) // Adding any custom args will cause the Attahcments to not observe the uploader queue // To bypass this security issue, we add in the args AFTER the Query has been initialized // options.library._acfuploader = settings.field; if( acf.isset(Query, 'mirroring', 'args') ) { Query.mirroring.args._acfuploader = settings.field; } // add states attributes.states = [ // main state new wp.media.controller.Library({ library: Query, multiple: attributes.multiple, title: attributes.title, priority: 20, filterable: 'all', editable: true, // If the user isn't allowed to edit fields, // can they still edit it locally? allowLocalEdits: true, }) ]; // edit image functionality (added in WP 3.9) if( acf.isset(wp, 'media', 'controller', 'EditImage') ) { attributes.states.push( new wp.media.controller.EditImage() ); } // create frame var frame = wp.media( attributes ); // add args reference frame.acf = settings; // add events frame = this._add_media_frame_events( frame, settings ); // return return frame; }, ready: function(){ // vars var version = acf.get('wp_version'), post_id = acf.get('post_id'); // update wp.media if( acf.isset(window,'wp','media','view','settings','post') && $.isNumeric(post_id) ) { wp.media.view.settings.post.id = post_id; } // update version if( version ) { // use only major version if( typeof version == 'string' ) { version = version.substr(0,1); } // add body class $('body').addClass('acf-wp-' + version); } // customize wp.media views if( acf.isset(window, 'wp', 'media', 'view') ) { //this.customize_Attachments(); //this.customize_Query(); //this.add_AcfEmbed(); this.customize_Attachment(); this.customize_AttachmentFiltersAll(); this.customize_AttachmentCompat(); } }, /* add_AcfEmbed: function(){ //test urls //(image) jpg: http://www.ml24.net/img/ml24_design_process_scion_frs_3d_rendering.jpg //(image) svg: http://kompozer.net/images/svg/Mozilla_Firefox.svg //(file) pdf: http://martinfowler.com/ieeeSoftware/whenType.pdf //(video) mp4: https://videos.files.wordpress.com/kUJmAcSf/bbb_sunflower_1080p_30fps_normal_hd.mp4 // add view wp.media.view.AcfEmbed = wp.media.view.Embed.extend({ initialize: function() { // set attachments this.model.props.attributes = this.controller.acf.attachment || {}; // refresh wp.media.view.Embed.prototype.initialize.apply( this, arguments ); }, refresh: function() { // vars var attachment = acf.parse_args(this.model.props.attributes, { url: '', filename: '', title: '', caption: '', alt: '', description: '', type: '', ext: '' }); // update attachment if( attachment.url ) { // filename attachment.filename = attachment.url.split('/').pop().split('?')[0]; // update attachment.ext = attachment.filename.split('.').pop(); attachment.type = /(jpe?g|png|gif|svg)/i.test(attachment.ext) ? 'image': 'file'; } // auto generate title if( attachment.filename && !attachment.title ) { // replace attachment.title = attachment.filename.split('-').join(' ').split('_').join(' '); // uppercase first word attachment.title = attachment.title.charAt(0).toUpperCase() + attachment.title.slice(1); // remove extension attachment.title = attachment.title.replace('.'+attachment.ext, ''); // update model this.model.props.attributes.title = attachment.title; } // save somee extra data this.model.props.attributes.filename = attachment.filename; this.model.props.attributes.type = attachment.type; // always show image view // avoid this.model.set() to prevent listeners updating view this.model.attributes.type = 'image'; // refresh wp.media.view.Embed.prototype.refresh.apply( this, arguments ); // append title this.$el.find('.setting.caption').before([ '<label class="setting title">', '<span>Title</span>', '<input type="text" data-setting="title" value="' + attachment.title + '">', '</label>' ].join('')); // append description this.$el.find('.setting.alt-text').after([ '<label class="setting description">', '<span>Description</span>', '<textarea type="text" data-setting="description">' + attachment.description + '</textarea>', '</label>' ].join('')); // hide alt if( attachment.type !== 'image' ) { this.$el.find('.setting.alt-text').hide(); } } }); }, */ /* customize_Attachments: function(){ // vars var Attachments = wp.media.model.Attachments; wp.media.model.Attachments = Attachments.extend({ initialize: function( models, options ){ // console.log('My Attachments initialize: %o %o %o', this, models, options); // return return Attachments.prototype.initialize.apply( this, arguments ); }, sync: function( method, model, options ) { // console.log('My Attachments sync: %o %o %o %o', this, method, model, options); // return return Attachments.prototype.sync.apply( this, arguments ); } }); }, customize_Query: function(){ // console.log('customize Query!'); // vars var Query = wp.media.model.Query; wp.media.model.Query = {}; }, */ customize_Attachment: function(){ // vars var AttachmentLibrary = wp.media.view.Attachment.Library; // extend wp.media.view.Attachment.Library = AttachmentLibrary.extend({ render: function() { // vars var frame = acf.media.frame(), errors = acf.maybe_get(this, 'model.attributes.acf_errors'); // add class // also make sure frame exists to prevent this logic running on a WP popup (such as feature image) if( frame && errors ) { this.$el.addClass('acf-disabled'); } // return return AttachmentLibrary.prototype.render.apply( this, arguments ); }, toggleSelection: function( options ) { // vars var frame = acf.media.frame(), errors = acf.maybe_get(this, 'model.attributes.acf_errors'), $sidebar = this.controller.$el.find('.media-frame-content .media-sidebar'); // remove previous error $sidebar.children('.acf-selection-error').remove(); // show attachment details $sidebar.children().removeClass('acf-hidden'); // add message if( frame && errors ) { // vars var filename = acf.maybe_get(this, 'model.attributes.filename', ''); // hide attachment details // Gallery field continues to show previously selected attachment... $sidebar.children().addClass('acf-hidden'); // append message $sidebar.prepend([ '<div class="acf-selection-error">', '<span class="selection-error-label">' + acf._e('restricted') +'</span>', '<span class="selection-error-filename">' + filename + '</span>', '<span class="selection-error-message">' + errors + '</span>', '</div>' ].join('')); } // return AttachmentLibrary.prototype.toggleSelection.apply( this, arguments ); }, select: function( model, collection ) { // vars var frame = acf.media.frame(), state = this.controller.state(), selection = state.get('selection'), errors = acf.maybe_get(this, 'model.attributes.acf_errors'); // prevent selection if( frame && errors ) { return selection.remove( model ); } //return return AttachmentLibrary.prototype.select.apply( this, arguments ); } }); }, customize_AttachmentFiltersAll: function(){ // add function refresh wp.media.view.AttachmentFilters.All.prototype.refresh = function(){ // Build `<option>` elements. this.$el.html( _.chain( this.filters ).map( function( filter, value ) { return { el: $( '<option></option>' ).val( value ).html( filter.text )[0], priority: filter.priority || 50 }; }, this ).sortBy('priority').pluck('el').value() ); }; }, customize_AttachmentCompat: function(){ // vars var AttachmentCompat = wp.media.view.AttachmentCompat; // extend wp.media.view.AttachmentCompat = AttachmentCompat.extend({ render: function() { //console.log('AttachmentCompat.render', this); // reference var self = this; // validate if( this.ignore_render ) return this; // add button setTimeout(function(){ // vars var $media_model = self.$el.closest('.media-modal'); // does button already exist? if( $media_model.find('.media-frame-router .acf-expand-details').exists() ) { return; } // create button var $a = $([ '<a href="#" class="acf-expand-details">', '<span class="is-closed"><span class="acf-icon -left small grey"></span>' + acf._e('expand_details') + '</span>', '<span class="is-open"><span class="acf-icon -right small grey"></span>' + acf._e('collapse_details') + '</span>', '</a>' ].join('')); // add events $a.on('click', function( e ){ e.preventDefault(); if( $media_model.hasClass('acf-expanded') ) { $media_model.removeClass('acf-expanded'); } else { $media_model.addClass('acf-expanded'); } }); // append $media_model.find('.media-frame-router').append( $a ); }, 0); // setup fields // The clearTimout is needed to prevent many setup functions from running at the same time clearTimeout( acf.media.render_timout ); acf.media.render_timout = setTimeout(function(){ acf.do_action('append', self.$el); }, 50); // return return AttachmentCompat.prototype.render.apply( this, arguments ); }, dispose: function() { //console.log('AttachmentCompat.dispose', this); // remove acf.do_action('remove', this.$el); // return return AttachmentCompat.prototype.dispose.apply( this, arguments ); }, save: function( e ) { //console.log('AttachmentCompat.save', this); if( e ) { e.preventDefault(); } // serialize form var data = acf.serialize_form(this.$el); // ignore render this.ignore_render = true; // save this.model.saveCompat( data ); } }); } }); })(jQuery); (function($){ acf.fields.oembed = { search : function( $el ){ // vars var s = $el.find('[data-name="search-input"]').val(); // fix missing 'http://' - causes the oembed code to error and fail if( s.substr(0, 4) != 'http' ) { s = 'http://' + s; $el.find('[data-name="search-input"]').val( s ); } // show loading $el.addClass('is-loading'); // AJAX data var ajax_data = { 'action' : 'acf/fields/oembed/search', 'nonce' : acf.get('nonce'), 's' : s, 'width' : acf.get_data($el, 'width'), 'height' : acf.get_data($el, 'height') }; // abort XHR if this field is already loading AJAX data if( $el.data('xhr') ) { $el.data('xhr').abort(); } // get HTML var xhr = $.ajax({ url: acf.get('ajaxurl'), data: ajax_data, type: 'post', dataType: 'html', success: function( html ){ $el.removeClass('is-loading'); // update from json acf.fields.oembed.search_success( $el, s, html ); // no results? if( !html ) { acf.fields.oembed.search_error( $el ); } } }); // update el data $el.data('xhr', xhr); }, search_success : function( $el, s, html ){ $el.removeClass('has-error').addClass('has-value'); $el.find('[data-name="value-input"]').val( s ); $el.find('[data-name="value-title"]').html( s ); $el.find('[data-name="value-embed"]').html( html ); }, search_error : function( $el ){ // update class $el.removeClass('has-value').addClass('has-error'); }, clear : function( $el ){ // update class $el.removeClass('has-error has-value'); // clear search $el.find('[data-name="search-input"]').val(''); // clear inputs $el.find('[data-name="value-input"]').val( '' ); $el.find('[data-name="value-title"]').html( '' ); $el.find('[data-name="value-embed"]').html( '' ); }, edit : function( $el ){ // update class $el.addClass('is-editing'); // set url and focus var url = $el.find('[data-name="value-title"]').text(); $el.find('[data-name="search-input"]').val( url ).focus() }, blur : function( $el ){ $el.removeClass('is-editing'); // set url and focus var old_url = $el.find('[data-name="value-title"]').text(), new_url = $el.find('[data-name="search-input"]').val(), embed = $el.find('[data-name="value-embed"]').html(); // bail early if no valu if( !new_url ) { this.clear( $el ); return; } // bail early if no change if( new_url == old_url ) { return; } this.search( $el ); } }; /* * Events * * jQuery events for this field * * @type function * @date 1/03/2011 * * @param N/A * @return N/A */ $(document).on('click', '.acf-oembed [data-name="search-button"]', function( e ){ e.preventDefault(); acf.fields.oembed.search( $(this).closest('.acf-oembed') ); $(this).blur(); }); $(document).on('click', '.acf-oembed [data-name="clear-button"]', function( e ){ e.preventDefault(); acf.fields.oembed.clear( $(this).closest('.acf-oembed') ); $(this).blur(); }); $(document).on('click', '.acf-oembed [data-name="value-title"]', function( e ){ e.preventDefault(); acf.fields.oembed.edit( $(this).closest('.acf-oembed') ); }); $(document).on('keypress', '.acf-oembed [data-name="search-input"]', function( e ){ // don't submit form if( e.which == 13 ) { e.preventDefault(); } }); $(document).on('keyup', '.acf-oembed [data-name="search-input"]', function( e ){ // bail early if no value if( ! $(this).val() ) { return; } // bail early for directional controls if( ! e.which ) { return; } acf.fields.oembed.search( $(this).closest('.acf-oembed') ); }); $(document).on('blur', '.acf-oembed [data-name="search-input"]', function(e){ acf.fields.oembed.blur( $(this).closest('.acf-oembed') ); }); })(jQuery); (function($){ acf.fields.radio = acf.field.extend({ type: 'radio', $ul: null, events: { 'click input[type="radio"]': 'click', }, focus: function(){ // focus on $select this.$ul = this.$field.find('ul'); // get options this.o = acf.get_data( this.$ul ); }, click: function(e){ // vars var $radio = e.$el, $label = $radio.parent('label'), selected = $label.hasClass('selected'), val = $radio.val(); // remove previous selected this.$ul.find('.selected').removeClass('selected'); // add active class $label.addClass('selected'); // allow null if( this.o.allow_null && selected ) { // unselect e.$el.prop('checked', false); $label.removeClass('selected'); val = false; // trigger change e.$el.trigger('change'); } // other if( this.o.other_choice ) { // vars var $other = this.$ul.find('input[type="text"]'); // show if( val === 'other' ) { $other.prop('disabled', false).attr('name', $radio.attr('name')); // hide } else { $other.prop('disabled', true).attr('name', ''); } } } }); })(jQuery); (function($){ acf.fields.relationship = acf.field.extend({ type: 'relationship', $el: null, $input: null, $filters: null, $choices: null, $values: null, actions: { 'ready': 'initialize', 'append': 'initialize', //'show': 'show' }, events: { 'keypress [data-filter]': 'submit_filter', 'change [data-filter]': 'change_filter', 'keyup [data-filter]': 'change_filter', 'click .choices .acf-rel-item': 'add_item', 'click [data-name="remove_item"]': 'remove_item' }, focus: function(){ // get elements this.$el = this.$field.find('.acf-relationship'); this.$input = this.$el.find('.acf-hidden input'); this.$choices = this.$el.find('.choices'), this.$values = this.$el.find('.values'); // get options this.o = acf.get_data( this.$el ); }, initialize: function(){ // reference var self = this, $field = this.$field, $el = this.$el, $input = this.$input; // right sortable this.$values.children('.list').sortable({ items: 'li', forceHelperSize: true, forcePlaceholderSize: true, scroll: true, update: function(){ $input.trigger('change'); } }); this.$choices.children('.list').scrollTop(0).on('scroll', function(e){ // bail early if no more results if( $el.hasClass('is-loading') || $el.hasClass('is-empty') ) { return; } // Scrolled to bottom if( Math.ceil( $(this).scrollTop() ) + $(this).innerHeight() >= $(this).get(0).scrollHeight ) { // get paged var paged = $el.data('paged') || 1; // update paged $el.data('paged', (paged+1) ); // fetch self.doFocus($field); self.fetch(); } }); /* // scroll event var maybe_fetch = function( e ){ console.log('scroll'); // remove listener $(window).off('scroll', maybe_fetch); // is field in view if( acf.is_in_view($field) ) { // fetch self.doFocus($field); self.fetch(); // return return; } // add listener setTimeout(function(){ $(window).on('scroll', maybe_fetch); }, 500); }; */ // fetch this.fetch(); }, /* show: function(){ console.log('show field: %o', this.o.xhr); // bail ealry if already loaded if( typeof this.o.xhr !== 'undefined' ) { return; } // is field in view if( acf.is_in_view(this.$field) ) { // fetch this.fetch(); } }, */ maybe_fetch: function(){ // reference var self = this, $field = this.$field; // abort timeout if( this.o.timeout ) { clearTimeout( this.o.timeout ); } // fetch var timeout = setTimeout(function(){ self.doFocus($field); self.fetch(); }, 400); this.$el.data('timeout', timeout); }, fetch: function(){ // reference var self = this, $field = this.$field; // add class this.$el.addClass('is-loading'); // abort XHR if this field is already loading AJAX data if( this.o.xhr ) { this.o.xhr.abort(); this.o.xhr = false; } // add to this.o this.o.action = 'acf/fields/relationship/query'; this.o.field_key = $field.data('key'); this.o.post_id = acf.get('post_id'); // ready for ajax var ajax_data = acf.prepare_for_ajax( this.o ); // clear html if is new query if( ajax_data.paged == 1 ) { this.$choices.children('.list').html('') } // add message this.$choices.find('ul:last').append('<p><i class="acf-loading"></i> ' + acf._e('relationship', 'loading') + '</p>'); // get results var xhr = $.ajax({ url: acf.get('ajaxurl'), dataType: 'json', type: 'post', data: ajax_data, success: function( json ){ // render self.doFocus($field); self.render(json); } }); // update el data this.$el.data('xhr', xhr); }, render: function( json ){ // remove loading class this.$el.removeClass('is-loading is-empty'); // remove p tag this.$choices.find('p').remove(); // no results? if( !json || !json.length ) { // add class this.$el.addClass('is-empty'); // add message if( this.o.paged == 1 ) { this.$choices.children('.list').append('<p>' + acf._e('relationship', 'empty') + '</p>'); } // return return; } // get new results var $new = $( this.walker(json) ); // apply .disabled to left li's this.$values.find('.acf-rel-item').each(function(){ $new.find('.acf-rel-item[data-id="' + $(this).data('id') + '"]').addClass('disabled'); }); // underline search match if( this.o.s ) { var s = this.o.s; $new.find('.acf-rel-item').each(function(){ // vars var find = $(this).text(), replace = find.replace( new RegExp('(' + s + ')', 'gi'), '<b>$1</b>'); $(this).html( $(this).html().replace(find, replace) ); }); } // append this.$choices.children('.list').append( $new ); // merge together groups var label = '', $list = null; this.$choices.find('.acf-rel-label').each(function(){ if( $(this).text() == label ) { $list.append( $(this).siblings('ul').html() ); $(this).parent().remove(); return; } // update vars label = $(this).text(); $list = $(this).siblings('ul'); }); }, walker: function( data ){ // vars var s = ''; // loop through data if( $.isArray(data) ) { for( var k in data ) { s += this.walker( data[ k ] ); } } else if( $.isPlainObject(data) ) { // optgroup if( data.children !== undefined ) { s += '<li><span class="acf-rel-label">' + data.text + '</span><ul class="acf-bl">'; s += this.walker( data.children ); s += '</ul></li>'; } else { s += '<li><span class="acf-rel-item" data-id="' + data.id + '">' + data.text + '</span></li>'; } } // return return s; }, submit_filter: function( e ){ // don't submit form if( e.which == 13 ) { e.preventDefault(); } }, change_filter: function( e ){ // vars var val = e.$el.val(), filter = e.$el.data('filter'); // Bail early if filter has not changed if( this.$el.data(filter) == val ) { return; } // update attr this.$el.data(filter, val); // reset paged this.$el.data('paged', 1); // fetch if( e.$el.is('select') ) { this.fetch(); // search must go through timeout } else { this.maybe_fetch(); } }, add_item: function( e ){ // max posts if( this.o.max > 0 ) { if( this.$values.find('.acf-rel-item').length >= this.o.max ) { alert( acf._e('relationship', 'max').replace('{max}', this.o.max) ); return; } } // can be added? if( e.$el.hasClass('disabled') ) { return false; } // disable e.$el.addClass('disabled'); // template var html = [ '<li>', '<input type="hidden" name="' + this.$input.attr('name') + '[]" value="' + e.$el.data('id') + '" />', '<span data-id="' + e.$el.data('id') + '" class="acf-rel-item">' + e.$el.html(), '<a href="#" class="acf-icon -minus small dark" data-name="remove_item"></a>', '</span>', '</li>'].join(''); // add new li this.$values.children('.list').append( html ) // trigger change on new_li this.$input.trigger('change'); // validation acf.validation.remove_error( this.$field ); }, remove_item : function( e ){ // vars var $span = e.$el.parent(), id = $span.data('id'); // remove $span.parent('li').remove(); // show this.$choices.find('.acf-rel-item[data-id="' + id + '"]').removeClass('disabled'); // trigger change on new_li this.$input.trigger('change'); } }); })(jQuery); (function($){ /* * acf.select2 * * description * * @type function * @date 16/12/2015 * @since 5.3.2 * * @param $post_id (int) * @return $post_id (int) */ acf.select2 = acf.model.extend({ init: function( $select, args ){ // vars var version = this.version(); // bail early if no version found if( !version ) return; // defaults args = $.extend({ allow_null: false, placeholder: '', multiple: false, ajax: false, action: '', pagination: false }, args); // v3 if( version == 3 ) { return this.init_v3( $select, args ); } // v4 return this.init_v4( $select, args ); }, /* * version * * This function will return the Select2 version number * * @type function * @date 24/12/2015 * @since 5.3.2 * * @param n/a * @return (int) */ version: function(){ // v3 if( acf.maybe_get(window, 'Select2') ) return 3; // v4 if( acf.maybe_get(window, 'jQuery.fn.select2.amd') ) return 4; // return return 0; }, /* * get_data * * This function will look at a $select element and return an object choices * * @type function * @date 24/12/2015 * @since 5.3.2 * * @param $select (jQuery) * @return (array) */ get_data: function( $select, data ){ // reference var self = this; // defaults data = data || []; // loop over children $select.children().each(function(){ // vars var $el = $(this); // optgroup if( $el.is('optgroup') ) { data.push({ 'text': $el.attr('label'), 'children': self.get_data( $el ) }); // option } else { data.push({ 'id': $el.attr('value'), 'text': $el.text() }); } }); // return return data; }, /* * decode_data * * This function will take an array of choices and decode the text * Changes '&amp;' to '&' which fixes a bug (in Select2 v3 )when searching for '&' * * @type function * @date 24/12/2015 * @since 5.3.2 * * @param $select (jQuery) * @return (array) */ decode_data: function( data ) { // bail ealry if no data if( !data ) return []; //loop $.each(data, function(k, v){ // text data[ k ].text = acf.decode( v.text ); // children if( typeof v.children !== 'undefined' ) { data[ k ].children = acf.select2.decode_data(v.children); } }); // return return data; }, /* * count_data * * This function will take an array of choices and return the count * * @type function * @date 24/12/2015 * @since 5.3.2 * * @param data (array) * @return (int) */ count_data: function( data ) { // vars var i = 0; // bail ealry if no data if( !data ) return i; //loop $.each(data, function(k, v){ // increase i++; // children if( typeof v.children !== 'undefined' ) { i += v.children.length; } }); // return return i; }, /* * get_value * * This function will return the selected options in a Select2 format * * @type function * @date 5/01/2016 * @since 5.3.2 * * @param $post_id (int) * @return $post_id (int) */ get_value: function( $select ){ // vars var val = [], $selected = $select.find('option:selected'); // bail early if no selected if( !$selected.exists() ) return val; // sort $selected = $selected.sort(function(a, b) { return +a.getAttribute('data-i') - +b.getAttribute('data-i'); }); // loop $selected.each(function(){ // vars var $el = $(this); // append val.push({ 'id': $el.attr('value'), 'text': $el.text() }); }); // return return val; }, /* * init_v3 * * This function will create a new Select2 for v3 * * @type function * @date 24/12/2015 * @since 5.3.2 * * @param $select (jQuery) * @return args (object) */ init_v3: function( $select, args ){ // vars var $input = $select.siblings('input'); // bail early if no input if( !$input.exists() ) return; // select2 args var select2_args = { width: '100%', containerCssClass: '-acf', allowClear: args.allow_null, placeholder: args.placeholder, multiple: args.multiple, separator: '||', data: [], escapeMarkup: function( m ){ return m; } }; // value var value = this.get_value( $select ); // multiple if( args.multiple ) { // vars var name = $select.attr('name'); // add hidden input to each multiple selection select2_args.formatSelection = function( object, $div ){ // append input $div.parent().append('<input type="hidden" class="select2-search-choice-hidden" name="' + name + '" value="' + object.id + '" />'); // return return object.text; } } else { // change array to single object value = acf.maybe_get(value, 0, ''); } // remove the blank option as we have a clear all button! if( args.allow_null ) { $select.find('option[value=""]').remove(); } // get data select2_args.data = this.get_data( $select ); // initial selection select2_args.initSelection = function( element, callback ) { callback( value ); }; // ajax if( args.ajax ) { select2_args.ajax = { url: acf.get('ajaxurl'), dataType: 'json', type: 'post', cache: false, data: function (term, page) { // vars var data = acf.prepare_for_ajax({ action: args.action, field_key: args.key, post_id: acf.get('post_id'), s: term, paged: page }); // return return data; }, results: function(data, page){ return { results: acf.select2.decode_data(data) }; } }; if( args.pagination ) { select2_args.ajax.results = function( data, page ) { return { results: acf.select2.decode_data(data), more: (acf.select2.count_data(data) >= 20) }; }; $input.on("select2-loaded", function(e) { // merge together groups var label = '', $list = null; $('#select2-drop .select2-result-with-children').each(function(){ // vars var $label = $(this).children('.select2-result-label'), $ul = $(this).children('.select2-result-sub'); // append group to previous if( $label.text() == label ) { $list.append( $ul.children() ); $(this).remove(); return; } // update vars label = $label.text(); $list = $ul; }); }); } } // attachment z-index fix select2_args.dropdownCss = { 'z-index' : '999999999' }; // filter for 3rd party customization select2_args = acf.apply_filters( 'select2_args', select2_args, $select, args ); // add select2 $input.select2( select2_args ); // vars var $container = $input.select2('container'); // reorder DOM // - this order is very important so don't change it // - $select goes first so the input can override it. Fixes issue where conditional logic will enable the select // - $input goes second to reset the input data // - container goes last to allow multiple hidden inputs to override $input $container.before( $select ); $container.before( $input ); // multiple if( args.multiple ) { // sortable $container.find('ul.select2-choices').sortable({ start: function() { $input.select2("onSortStart"); }, stop: function() { $input.select2("onSortEnd"); } }); } // disbale select $select.prop('disabled', true).addClass('acf-disabled acf-hidden'); // update select value // this fixes a bug where select2 appears blank after duplicating a post_object field (field settings). // the $select is disabled, so setting the value won't cause any issues (this is what select2 v4 does anyway). $input.on('change', function(e) { $select.val( e.val ); }); }, init_v4: function( $select, args ){ // vars var $input = $select.siblings('input'); // bail early if no input if( !$input.exists() ) return; // select2 args var select2_args = { width: '100%', containerCssClass: '-acf', allowClear: args.allow_null, placeholder: args.placeholder, multiple: args.multiple, separator: '||', data: [], escapeMarkup: function( m ){ return m; }, /* sorter: function (data) { console.log('sorter %o', data); return data; }, */ }; // value var value = this.get_value( $select ); // multiple if( args.multiple ) { /* // vars var name = $select.attr('name'); // add hidden input to each multiple selection select2_args.templateSelection = function( selection ){ return selection.text + '<input type="hidden" class="select2-search-choice-hidden" name="' + name + '" value="' + selection.id + '" />'; } */ } else { // change array to single object value = acf.maybe_get(value, 0, ''); } // remove the blank option as we have a clear all button! if( args.allow_null ) { $select.find('option[value=""]').remove(); } // get data select2_args.data = this.get_data( $select ); // initial selection select2_args.initSelection = function( element, callback ) { callback( value ); }; // remove conflicting atts if( !args.ajax ) { $select.removeData('ajax'); $select.removeAttr('data-ajax'); } else { select2_args.ajax = { url: acf.get('ajaxurl'), delay: 250, dataType: 'json', type: 'post', cache: false, data: function( params ) { //console.log('ajax data %o', params); // vars var data = acf.prepare_for_ajax({ action: args.action, field_key: args.key, post_id: acf.get('post_id'), s: params.term, paged: params.page }); // return return data; }, processResults: function(data, params){ //console.log('processResults %o', data); return { results: acf.select2.decode_data(data) }; } }; if( args.pagination ) { select2_args.ajax.processResults = function(data, params){ //console.log('processResults %o %o', data, params); setTimeout(function(){ // merge together groups var $prev_options = null, $prev_group = null; $('.select2-results__option[role="group"]').each(function(){ // vars var $options = $(this).children('ul'), $group = $(this).children('strong'); // compare to previous if( $prev_group !== null && $group.text() == $prev_group.text() ) { $prev_options.append( $options.children() ); $(this).remove(); return; } // update vars $prev_options = $options; $prev_group = $group; }); }, 1); return { results: acf.select2.decode_data(data), pagination: { more: (acf.select2.count_data(data) >= 20) } }; }; } } // multiple /* if( args.multiple ) { $select.on('select2:select', function( e ){ console.log( 'select2:select %o &o', $(this), e ); // vars var $option = $(e.params.data.element); // move option to begining of select //$(this).prepend( $option ); }); } */ // attachment z-index fix select2_args.dropdownCss = { 'z-index' : '999999999' }; // reorder DOM // - no need to reorder, the select field is needed to $_POST values // filter for 3rd party customization select2_args = acf.apply_filters( 'select2_args', select2_args, $select, args ); // add select2 //console.log( '%o %o ', $select, select2_args ); var container = $select.select2( select2_args ); }, /* * destroy * * This function will destroy a Select2 * * @type function * @date 24/12/2015 * @since 5.3.2 * * @param $post_id (int) * @return $post_id (int) */ destroy: function( $select ){ // remove select2 container $select.siblings('.select2-container').remove(); // show input so that select2 can correctly render visible select2 container $select.siblings('input').show(); // enable select $select.prop('disabled', false).removeClass('acf-disabled acf-hidden'); } }); /* * depreciated * * These functions have moved since v5.3.3 * * @type function * @date 11/12/2015 * @since 5.3.2 * * @param n/a * @return n/a */ acf.add_select2 = function( $select, args ) { acf.select2.init( $select, args ); } acf.remove_select2 = function( $select ) { acf.select2.destroy( $select ); } // select acf.fields.select = acf.field.extend({ type: 'select', pagination: false, $select: null, actions: { 'ready': 'render', 'append': 'render', 'remove': 'remove' }, focus: function(){ // focus on $select this.$select = this.$field.find('select'); // bail early if no select field if( !this.$select.exists() ) { return; } // get options this.o = acf.get_data( this.$select ); // customize o this.o.pagination = this.pagination; this.o.key = this.$field.data('key'); this.o.action = 'acf/fields/' + this.type + '/query'; }, render: function(){ // validate ui if( !this.$select.exists() || !this.o.ui ) { return false; } acf.select2.init( this.$select, this.o ); }, remove: function(){ // validate ui if( !this.$select.exists() || !this.o.ui ) { return false; } // remove select2 acf.select2.destroy( this.$select ); } }); // user acf.fields.user = acf.fields.select.extend({ type: 'user', pagination: true }); // post_object acf.fields.post_object = acf.fields.select.extend({ type: 'post_object', pagination: true }); // page_link acf.fields.page_link = acf.fields.select.extend({ type: 'page_link', pagination: true }); })(jQuery); (function($){ acf.fields.tab = acf.field.extend({ type: 'tab', $el: null, $wrap: null, actions: { 'prepare': 'initialize', 'append': 'initialize', 'hide': 'hide', 'show': 'show' }, focus: function(){ // get elements this.$el = this.$field.find('.acf-tab'); // get options this.o = this.$el.data(); this.o.key = this.$field.data('key'); this.o.text = this.$el.text(); }, initialize: function(){ // bail early if is td if( this.$field.is('td') ) return; // add tab tab_manager.add_tab( this.$field, this.o ); }, hide: function( $field, context ){ // bail early if not conditional logic if( context != 'conditional_logic' ) return; // vars var key = $field.data('key'), $group = $field.prevAll('.acf-tab-wrap'), $a = $group.find('a[data-key="' + key + '"]'), $li = $a.parent(); // bail early if $group does not exist (clone field) if( !$group.exists() ) return; // hide li $li.addClass('hidden-by-conditional-logic'); // set timout to allow proceeding fields to hide first // without this, the tab field will hide all fields, regarless of if that field has it's own conditional logic rules setTimeout(function(){ // if this tab field was hidden by conditional_logic, disable it's children to prevent validation $field.nextUntil('.acf-field-tab', '.acf-field').each(function(){ // bail ealry if already hidden if( $(this).hasClass('hidden-by-conditional-logic') ) return; // hide field acf.conditional_logic.hide_field( $(this) ); // add parent reference $(this).addClass('-hbcl-' + key); }); // select other tab if active if( $li.hasClass('active') ) { $group.find('li:not(.hidden-by-conditional-logic):first a').trigger('click'); } }, 0); }, show: function( $field, context ){ // bail early if not conditional logic if( context != 'conditional_logic' ) return; // vars var key = $field.data('key'), $group = $field.prevAll('.acf-tab-wrap'), $a = $group.find('a[data-key="' + key + '"]'), $li = $a.parent(); // bail early if $group does not exist (clone field) if( !$group.exists() ) return; // show li $li.removeClass('hidden-by-conditional-logic'); // set timout to allow proceeding fields to hide first // without this, the tab field will hide all fields, regarless of if that field has it's own conditional logic rules setTimeout(function(){ // if this tab field was shown by conditional_logic, enable it's children to allow validation $field.siblings('.acf-field.-hbcl-' + key).each(function(){ // show field acf.conditional_logic.show_field( $(this) ); // remove parent reference $(this).removeClass('-hbcl-' + key); }); // select tab if no other active var $active = $li.siblings('.active'); if( !$active.exists() || $active.hasClass('hidden-by-conditional-logic') ) { $a.trigger('click'); } }, 0); } }); /* * tab_manager * * This model will handle adding tabs and groups * * @type function * @date 25/11/2015 * @since 5.3.2 * * @param $post_id (int) * @return $post_id (int) */ var tab_manager = acf.model.extend({ actions: { 'prepare 15': 'render', 'append 15': 'render', 'refresh 15': 'render' }, events: { 'click .acf-tab-button': '_click' }, render: function( $el ){ // find visible tab wraps $('.acf-tab-wrap', $el).each(function(){ // vars var $group = $(this), $wrap = $group.parent(); // trigger click if( !$group.find('li.active').exists() ) { $group.find('li:not(.hidden-by-conditional-logic):first a').trigger('click'); } if( $wrap.hasClass('-sidebar') ) { // vars var attribute = $wrap.is('td') ? 'height' : 'min-height'; // find height (minus 1 for border-bottom) var height = $group.position().top + $group.children('ul').outerHeight(true) - 1; // add css $wrap.css(attribute, height); } }); }, add_group: function( $field, settings ){ // vars var $wrap = $field.parent(), html = ''; // add sidebar to wrap if( $wrap.hasClass('acf-fields') && settings.placement == 'left' ) { $wrap.addClass('-sidebar'); // can't have side tab without sidebar } else { settings.placement = 'top'; } // generate html if( $wrap.is('tbody') ) { html = '<tr class="acf-tab-wrap"><td colspan="2"><ul class="acf-hl acf-tab-group"></ul></td></tr>'; } else { html = '<div class="acf-tab-wrap -' + settings.placement + '"><ul class="acf-hl acf-tab-group"></ul></div>'; } // save $group = $(html); // append $field.before( $group ); // return return $group; }, add_tab: function( $field, settings ){ //console.log('add_tab(%o, %o)', $field, settings); // vars var $group = $field.siblings('.acf-tab-wrap').last(); // add tab group if no group exists if( !$group.exists() ) { $group = this.add_group( $field, settings ); // add tab group if is endpoint } else if( settings.endpoint ) { $group = this.add_group( $field, settings ); } // vars var $li = $('<li><a class="acf-tab-button" href="#" data-key="' + settings.key + '">' + settings.text + '</a></li>'); // hide li if( settings.text === '' ) $li.hide(); // add tab $group.find('ul').append( $li ); // conditional logic if( $field.hasClass('hidden-by-conditional-logic') ) { $li.addClass('hidden-by-conditional-logic'); } }, _click: function( e ){ // prevent default e.preventDefault(); // reference var self = this; // vars var $a = e.$el, $group = $a.closest('.acf-tab-wrap'), show = $a.data('key'), current = ''; // add and remove classes $a.parent().addClass('active').siblings().removeClass('active'); // loop over all fields until you hit another group $group.nextUntil('.acf-tab-wrap', '.acf-field').each(function(){ // vars var $field = $(this); // set current if( $field.data('type') == 'tab' ) { current = $field.data('key'); // bail early if endpoint is found if( $field.hasClass('endpoint') ) { // stop loop - current tab group is complete return false; } } // show if( current === show ) { // only show if hidden if( $field.hasClass('hidden-by-tab') ) { $field.removeClass('hidden-by-tab'); acf.do_action('show_field', $(this), 'tab'); } // hide } else { // only hide if not hidden if( !$field.hasClass('hidden-by-tab') ) { $field.addClass('hidden-by-tab'); acf.do_action('hide_field', $(this), 'tab'); } } }); // action for 3rd party customization acf.do_action('refresh', $group.parent() ); // blur $a.trigger('blur'); } }); /* * tab_validation * * This model will handle validation of fields within a tab group * * @type function * @date 25/11/2015 * @since 5.3.2 * * @param $post_id (int) * @return $post_id (int) */ var tab_validation = acf.model.extend({ active: 1, actions: { 'add_field_error': 'add_field_error' }, add_field_error: function( $field ){ // bail early if already focused if( !this.active ) { return; } // bail early if not hidden by tab if( !$field.hasClass('hidden-by-tab') ) { return; } // reference var self = this; // vars var $tab = $field.prevAll('.acf-field-tab:first'), $group = $field.prevAll('.acf-tab-wrap:first'); // focus $group.find('a[data-key="' + $tab.data('key') + '"]').trigger('click'); // disable functionality for 1sec (allow next validation to work) this.active = 0; setTimeout(function(){ self.active = 1; }, 1000); } }); })(jQuery); (function($){ // taxonomy acf.fields.taxonomy = acf.field.extend({ type: 'taxonomy', $el: null, actions: { 'ready': 'render', 'append': 'render', 'remove': 'remove' }, events: { 'click a[data-name="add"]': 'add_term', }, focus: function(){ // $el this.$el = this.$field.find('.acf-taxonomy-field'); // get options this.o = acf.get_data( this.$el ); // extra this.o.key = this.$field.data('key'); }, render: function(){ // attempt select2 var $select = this.$field.find('select'); // bail early if no select if( !$select.exists() ) { return false; } // select2 options var args = acf.get_data( $select ); // customize args args.pagination = true; args.key = this.o.key; args.action = 'acf/fields/taxonomy/query'; // add select2 acf.select2.init( $select, args ); }, remove: function(){ // attempt select2 var $select = this.$field.find('select'); // validate ui if( !$select.exists() ) { return false; } // remove select2 acf.select2.destroy( $select ); }, add_term: function( e ){ // reference var self = this; // open popup acf.open_popup({ title: e.$el.attr('title') || e.$el.data('title'), loading: true, height: 220 }); // AJAX data var ajax_data = acf.prepare_for_ajax({ action: 'acf/fields/taxonomy/add_term', field_key: this.o.key }); // get HTML $.ajax({ url: acf.get('ajaxurl'), data: ajax_data, type: 'post', dataType: 'html', success: function(html){ self.add_term_confirm( html ); } }); }, add_term_confirm: function( html ){ // reference var self = this; // update popup acf.update_popup({ content : html }); // focus $('#acf-popup input[name="term_name"]').focus(); // events $('#acf-popup form').on('submit', function( e ){ // prevent default e.preventDefault(); // submit self.add_term_submit( $(this )); }); }, add_term_submit: function( $form ){ // reference var self = this; // vars var $submit = $form.find('.acf-submit'), $name = $form.find('input[name="term_name"]'), $parent = $form.find('select[name="term_parent"]'); // basic validation if( $name.val() === '' ) { $name.focus(); return false; } // show loading $submit.find('button').attr('disabled', 'disabled'); $submit.find('.acf-spinner').addClass('is-active'); // vars var ajax_data = acf.prepare_for_ajax({ action: 'acf/fields/taxonomy/add_term', field_key: this.o.key, term_name: $name.val(), term_parent: $parent.exists() ? $parent.val() : 0 }); // save term $.ajax({ url: acf.get('ajaxurl'), data: ajax_data, type: 'post', dataType: 'json', success: function( json ){ // vars var message = acf.get_ajax_message(json); // success if( acf.is_ajax_success(json) ) { // clear name $name.val(''); // update term lists self.append_new_term( json.data ); } // message if( message.text ) { $submit.find('span').html( message.text ); } }, complete: function(){ // reset button $submit.find('button').removeAttr('disabled'); // hide loading $submit.find('.acf-spinner').removeClass('is-active'); // remove message $submit.find('span').delay(1500).fadeOut(250, function(){ $(this).html(''); $(this).show(); }); // focus $name.focus(); } }); }, append_new_term: function( term ){ // vars var item = { id: term.term_id, text: term.term_label }; // append to all taxonomy lists $('.acf-taxonomy-field[data-taxonomy="' + this.o.taxonomy + '"]').each(function(){ // vars var type = $(this).data('type'); // bail early if not checkbox/radio if( type == 'radio' || type == 'checkbox' ) { // allow } else { return; } // vars var $hidden = $(this).children('input[type="hidden"]'), $ul = $(this).find('ul:first'), name = $hidden.attr('name'); // allow multiple selection if( type == 'checkbox' ) { name += '[]'; } // create new li var $li = $([ '<li data-id="' + term.term_id + '">', '<label>', '<input type="' + type + '" value="' + term.term_id + '" name="' + name + '" /> ', '<span>' + term.term_label + '</span>', '</label>', '</li>' ].join('')); // find parent if( term.term_parent ) { // vars var $parent = $ul.find('li[data-id="' + term.term_parent + '"]'); // update vars $ul = $parent.children('ul'); // create ul if( !$ul.exists() ) { $ul = $('<ul class="children acf-bl"></ul>'); $parent.append( $ul ); } } // append $ul.append( $li ); }); // append to select $('#acf-popup #term_parent').each(function(){ // vars var $option = $('<option value="' + term.term_id + '">' + term.term_label + '</option>'); if( term.term_parent ) { $(this).children('option[value="' + term.term_parent + '"]').after( $option ); } else { $(this).append( $option ); } }); // set value switch( this.o.type ) { // select case 'select': this.$el.children('input').select2('data', item); break; case 'multi_select': // vars var $input = this.$el.children('input'), value = $input.select2('data') || []; // append value.push( item ); // update $input.select2('data', value); break; case 'checkbox': case 'radio': // scroll to view var $holder = this.$el.find('.categorychecklist-holder'), $li = $holder.find('li[data-id="' + term.term_id + '"]'), offet = $holder.get(0).scrollTop + ( $li.offset().top - $holder.offset().top ); // check input $li.find('input').prop('checked', true); // scroll to bottom $holder.animate({scrollTop: offet}, '250'); break; } } }); })(jQuery); (function($){ acf.fields.url = acf.field.extend({ type: 'url', $input: null, actions: { 'ready': 'render', 'append': 'render' }, events: { 'keyup input[type="url"]': 'render' }, focus: function(){ this.$input = this.$field.find('input[type="url"]'); }, is_valid: function(){ // vars var val = this.$input.val(); if( val.indexOf('://') !== -1 ) { // url } else if( val.indexOf('//') === 0 ) { // protocol relative url } else { return false; } // return return true; }, render: function(){ // add class if( this.is_valid() ) { this.$input.parent().addClass('valid'); // remove class } else { this.$input.parent().removeClass('valid'); } } }); })(jQuery); (function($){ acf.validation = acf.model.extend({ actions: { 'ready': 'ready', 'append': 'ready' }, filters: { 'validation_complete': 'validation_complete' }, events: { 'click #save-post': 'click_ignore', 'click [type="submit"]': 'click_publish', 'submit form': 'submit_form', 'click .acf-error-message a': 'click_message' }, // vars active: 1, ignore: 0, busy: 0, valid: true, errors: [], // classes error_class: 'acf-error', message_class: 'acf-error-message', // el $trigger: null, /* * ready * * This function will add 'non bubbling' events * * @type function * @date 26/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ ready: function( $el ){ // reference $el.find('.acf-field input').filter('[type="number"], [type="email"], [type="url"]').on('invalid', function( e ){ // prvent defual // fixes chrome bug where 'hidden-by-tab' field throws focus error e.preventDefault(); // append to errors acf.validation.errors.push({ input: $(this).attr('name'), message: e.target.validationMessage }); // run validation acf.validation.fetch( $(this).closest('form') ); }); }, /* * validation_complete * * This function will modify the JSON response and add local 'invalid' errors * * @type function * @date 26/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ validation_complete: function( json, $form ) { // bail early if no local errors if( !this.errors.length ) return json; // set valid json.valid = 0; // require array json.errors = json.errors || []; // vars var inputs = []; // populate inputs for( i in json.errors ) { inputs.push( json.errors[ i ].input ); } // append for( i in this.errors ) { // vars var error = this.errors[ i ]; // bail ealry if alreay exists if( $.inArray(error.input, inputs) !== false ) continue; // append json.errors.push( error ); } // reset this.errors = []; // return return json; }, /* * click_message * * This function will dismiss the validation message * * @type function * @date 26/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ click_message: function( e ) { e.preventDefault(); acf.remove_el( e.$el.parent() ); }, /* * click_ignore * * This event is trigered via submit butons which ignore validation * * @type function * @date 4/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ click_ignore: function( e ) { this.ignore = 1; this.$trigger = e.$el; }, /* * click_publish * * This event is trigered via submit butons which trigger validation * * @type function * @date 4/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ click_publish: function( e ) { this.$trigger = e.$el; }, /* * submit_form * * description * * @type function * @date 4/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ submit_form: function( e ){ // bail early if not active if( !this.active ) { return true; } // ignore validation (only ignore once) if( this.ignore ) { this.ignore = 0; return true; } // bail early if this form does not contain ACF data if( !e.$el.find('#acf-form-data').exists() ) { return true; } // bail early if is preview var $preview = e.$el.find('#wp-preview'); if( $preview.exists() && $preview.val() ) { // WP will lock form, unlock it this.toggle( e.$el, 'unlock' ); return true; } // prevent default e.preventDefault(); // run validation this.fetch( e.$el ); }, /* * lock * * description * * @type function * @date 7/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ toggle: function( $form, state ){ // defaults state = state || 'unlock'; // debug //console.log('toggle %o, %o %o', this.$trigger, $form, state); // vars var $submit = null, $spinner = null, $parent = $('#submitdiv'); // 3rd party publish box if( !$parent.exists() ) { $parent = $('#submitpost'); } // term, user if( !$parent.exists() ) { $parent = $form.find('p.submit').last(); } // front end form if( !$parent.exists() ) { $parent = $form.find('.acf-form-submit'); } // default if( !$parent.exists() ) { $parent = $form; } // find elements // note: media edit page does not use .button, this is why we need to look for generic input[type="submit"] $submit = $parent.find('input[type="submit"], .button'); $spinner = $parent.find('.spinner, .acf-spinner'); // hide all spinners (hides the preview spinner) this.hide_spinner( $spinner ); // unlock if( state == 'unlock' ) { this.enable_submit( $submit ); // lock } else if( state == 'lock' ) { // show only last spinner (allow all spinners to be hidden - preview spinner + submit spinner) this.disable_submit( $submit ); this.show_spinner( $spinner.last() ); } }, /* * fetch * * description * * @type function * @date 4/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ fetch: function( $form ){ // bail aelry if already busy if( this.busy ) return false; // reference var self = this; // vars var data = acf.serialize_form($form); // append AJAX action data.action = 'acf/validate_save_post'; // set busy this.busy = 1; // lock form this.toggle( $form, 'lock' ); // ajax $.ajax({ url: acf.get('ajaxurl'), data: data, type: 'post', dataType: 'json', success: function( json ){ // bail early if not json success if( !acf.is_ajax_success(json) ) { return; } self.fetch_success( $form, json.data ); }, complete: function(){ self.fetch_complete( $form ); } }); }, /* * fetch_complete * * description * * @type function * @date 4/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ fetch_complete: function( $form ){ // set busy this.busy = 0; // unlock so WP can publish form this.toggle( $form, 'unlock' ); // bail early if validationw as not valid if( !this.valid ) { return; } // update ignore (allow form submit to not run validation) this.ignore = 1; // remove previous error message var $message = $form.children('.acf-error-message'); if( $message.exists() ) { $message.addClass('-success'); $message.children('p').html( acf._e('validation_successful') ); // remove message setTimeout(function(){ acf.remove_el( $message ); }, 2000); } // remove hidden postboxes (this will stop them from being posted to save) $form.find('.acf-postbox.acf-hidden').remove(); // action for 3rd party customization acf.do_action('submit', $form); // submit form again if( this.$trigger ) { this.$trigger.click(); } else { $form.submit(); } // lock form this.toggle( $form, 'lock' ); }, /* * fetch_success * * description * * @type function * @date 4/05/2015 * @since 5.2.3 * * @param $post_id (int) * @return $post_id (int) */ fetch_success: function( $form, json ){ // filter for 3rd party customization json = acf.apply_filters('validation_complete', json, $form); // validate json if( !json || json.valid || !json.errors ) { // set valid (allows fetch_complete to run) this.valid = true; // end function return; } // set valid (prevents fetch_complete from runing) this.valid = false; // reset trigger this.$trigger = null; // vars var $scrollTo = null, count = 0, message = acf._e('validation_failed'); // show field error messages if( json.errors && json.errors.length > 0 ) { for( var i in json.errors ) { // get error var error = json.errors[ i ]; // is error for a specific field? if( !error.input ) { // update message message += '. ' + error.message; // ignore following functionality continue; } // get input var $input = $form.find('[name="' + error.input + '"]').first(); // if $_POST value was an array, this $input may not exist if( !$input.exists() ) { $input = $form.find('[name^="' + error.input + '"]').first(); } // bail early if input doesn't exist if( !$input.exists() ) continue; // increase count++; // now get field var $field = acf.get_field_wrap( $input ); // add error this.add_error( $field, error.message ); // set $scrollTo if( $scrollTo === null ) { $scrollTo = $field; } } // message if( count == 1 ) { message += '. ' + acf._e('validation_failed_1'); } else if( count > 1 ) { message += '. ' + acf._e('validation_failed_2').replace('%d', count); } } // get $message var $message = $form.children('.acf-error-message'); if( !$message.exists() ) { $message = $('<div class="acf-error-message"><p></p><a href="#" class="acf-icon -cancel small"></a></div>'); $form.prepend( $message ); } // update message $message.children('p').html( message ); // if no $scrollTo, set to message if( $scrollTo === null ) { $scrollTo = $message; } // timeout avoids flicker jump setTimeout(function(){ $("html, body").animate({ scrollTop: $scrollTo.offset().top - ( $(window).height() / 2 ) }, 500); }, 1); }, /* * add_error * * This function will add error markup to a field * * @type function * @date 4/05/2015 * @since 5.2.3 * * @param $field (jQuery) * @param message (string) * @return n/a */ add_error: function( $field, message ){ // reference var self = this; // add class $field.addClass(this.error_class); // add message if( message !== undefined ) { $field.children('.acf-input').children('.' + this.message_class).remove(); $field.children('.acf-input').prepend('<div class="' + this.message_class + '"><p>' + message + '</p></div>'); } // add event var event = function(){ // remove error self.remove_error( $field ); // remove self $field.off('focus change', 'input, textarea, select', event); } $field.on('focus change', 'input, textarea, select', event); // hook for 3rd party customization acf.do_action('add_field_error', $field); }, /* * remove_error * * This function will remove error markup from a field * * @type function * @date 4/05/2015 * @since 5.2.3 * * @param $field (jQuery) * @return n/a */ remove_error: function( $field ){ // var $message = $field.children('.acf-input').children('.' + this.message_class); // remove class $field.removeClass(this.error_class); // remove message setTimeout(function(){ acf.remove_el( $message ); }, 250); // hook for 3rd party customization acf.do_action('remove_field_error', $field); }, /* * add_warning * * This functino will add and auto remove an error message to a field * * @type function * @date 4/05/2015 * @since 5.2.3 * * @param $field (jQuery) * @param message (string) * @return n/a */ add_warning: function( $field, message ){ this.add_error( $field, message ); setTimeout(function(){ acf.validation.remove_error( $field ) }, 1000); }, /* * show_spinner * * This function will show a spinner element. Logic changed in WP 4.2 * * @type function * @date 3/05/2015 * @since 5.2.3 * * @param $spinner (jQuery) * @return n/a */ show_spinner: function( $spinner ){ // bail early if no spinner if( !$spinner.exists() ) { return; } // vars var wp_version = acf.get('wp_version'); // show if( parseFloat(wp_version) >= 4.2 ) { $spinner.addClass('is-active'); } else { $spinner.css('display', 'inline-block'); } }, /* * hide_spinner * * This function will hide a spinner element. Logic changed in WP 4.2 * * @type function * @date 3/05/2015 * @since 5.2.3 * * @param $spinner (jQuery) * @return n/a */ hide_spinner: function( $spinner ){ // bail early if no spinner if( !$spinner.exists() ) { return; } // vars var wp_version = acf.get('wp_version'); // hide if( parseFloat(wp_version) >= 4.2 ) { $spinner.removeClass('is-active'); } else { $spinner.css('display', 'none'); } }, /* * disable_submit * * This function will disable the $trigger is possible * * @type function * @date 3/05/2015 * @since 5.2.3 * * @param $spinner (jQuery) * @return n/a */ disable_submit: function( $submit ){ // bail early if no submit if( !$submit.exists() ) { return; } // add class $submit.addClass('disabled button-disabled button-primary-disabled'); }, /* * enable_submit * * This function will enable the $trigger is possible * * @type function * @date 3/05/2015 * @since 5.2.3 * * @param $spinner (jQuery) * @return n/a */ enable_submit: function( $submit ){ // bail early if no submit if( !$submit.exists() ) { return; } // remove class $submit.removeClass('disabled button-disabled button-primary-disabled'); } }); })(jQuery); (function($){ acf.fields.wysiwyg = acf.field.extend({ type: 'wysiwyg', $el: null, $textarea: null, toolbars: {}, actions: { 'load': 'initialize', 'append': 'initialize', 'remove': 'disable', 'sortstart': 'disable', 'sortstop': 'enable' }, focus: function(){ // get elements this.$el = this.$field.find('.wp-editor-wrap').last(); this.$textarea = this.$el.find('textarea'); // get options this.o = acf.get_data( this.$el ); this.o.id = this.$textarea.attr('id'); }, initialize: function(){ // bail early if no tinymce if( typeof tinyMCEPreInit === 'undefined' || typeof tinymce === 'undefined' ) { return false; } // generate new id var old_id = this.o.id, new_id = acf.get_uniqid('acf-editor-'), html = this.$el.outerHTML(); // replace html = acf.str_replace( old_id, new_id, html ); // swap this.$el.replaceWith( html ); // update id this.o.id = new_id // vars var mceInit = this.get_mceInit(), qtInit = this.get_qtInit(); // append settings tinyMCEPreInit.mceInit[ mceInit.id ] = mceInit; tinyMCEPreInit.qtInit[ qtInit.id ] = qtInit; // initialize mceInit if( this.$el.hasClass('tmce-active') ) { try { tinymce.init( mceInit ); } catch(e){} } // initialize qtInit try { var qtag = quicktags( qtInit ); this._buttonsInit( qtag ); } catch(e){} }, get_mceInit : function(){ // reference var $field = this.$field; // vars var toolbar = this.get_toolbar( this.o.toolbar ), mceInit = $.extend({}, tinyMCEPreInit.mceInit.acf_content); // selector mceInit.selector = '#' + this.o.id; // id mceInit.id = this.o.id; // tinymce v4 mceInit.elements = this.o.id; // tinymce v3 // toolbar if( toolbar ) { var k = (tinymce.majorVersion < 4) ? 'theme_advanced_buttons' : 'toolbar'; for( var i = 1; i < 5; i++ ) { mceInit[ k + i ] = acf.isset(toolbar, i) ? toolbar[i] : ''; } } // events if( tinymce.majorVersion < 4 ) { mceInit.setup = function( ed ){ ed.onInit.add(function(ed, event) { // focus $(ed.getBody()).on('focus', function(){ acf.validation.remove_error( $field ); }); $(ed.getBody()).on('blur', function(){ // update the hidden textarea // - This fixes a bug when adding a taxonomy term as the form is not posted and the hidden textarea is never populated! // save to textarea ed.save(); // trigger change on textarea $field.find('textarea').trigger('change'); }); }); }; } else { mceInit.setup = function( ed ){ ed.on('focus', function(e) { acf.validation.remove_error( $field ); }); ed.on('change', function(e) { // save to textarea ed.save(); $field.find('textarea').trigger('change'); }); /* ed.on('blur', function(e) { // update the hidden textarea // - This fixes a but when adding a taxonomy term as the form is not posted and the hidden textarea is never populated! // save to textarea ed.save(); // trigger change on textarea $field.find('textarea').trigger('change'); }); */ /* ed.on('ResizeEditor', function(e) { // console.log(e); }); */ }; } // disable wp_autoresize_on (no solution yet for fixed toolbar) mceInit.wp_autoresize_on = false; // hook for 3rd party customization mceInit = acf.apply_filters('wysiwyg_tinymce_settings', mceInit, mceInit.id); // return return mceInit; }, get_qtInit : function(){ // vars var qtInit = $.extend({}, tinyMCEPreInit.qtInit.acf_content); // id qtInit.id = this.o.id; // hook for 3rd party customization qtInit = acf.apply_filters('wysiwyg_quicktags_settings', qtInit, qtInit.id); // return return qtInit; }, /* * disable * * This function will disable the tinymce for a given field * Note: txtarea_el is different from $textarea.val() and is the value that you see, not the value that you save. * this allows text like <--more--> to wok instead of showing as an image when the tinymce is removed * * @type function * @date 1/08/2014 * @since 5.0.0 * * @param n/a * @return n/a */ disable: function(){ try { // vars var ed = tinyMCE.get( this.o.id ) // save ed.save(); // destroy editor ed.destroy(); } catch(e) {} }, enable: function(){ // bail early if html mode if( this.$el.hasClass('tmce-active') && acf.isset(window,'switchEditors') ) { switchEditors.go( this.o.id, 'tmce'); } }, get_toolbar : function( name ){ // bail early if toolbar doesn't exist if( typeof this.toolbars[ name ] !== 'undefined' ) { return this.toolbars[ name ]; } // return return false; }, /* * _buttonsInit * * This function will add the quicktags HTML to a WYSIWYG field. Normaly, this is added via quicktags on document ready, * however, there is no support for 'append'. Source: wp-includes/js/quicktags.js:245 * * @type function * @date 1/08/2014 * @since 5.0.0 * * @param ed (object) quicktag object * @return n/a */ _buttonsInit: function( ed ) { var defaults = ',strong,em,link,block,del,ins,img,ul,ol,li,code,more,close,'; canvas = ed.canvas; name = ed.name; settings = ed.settings; html = ''; theButtons = {}; use = ''; // set buttons if ( settings.buttons ) { use = ','+settings.buttons+','; } for ( i in edButtons ) { if ( !edButtons[i] ) { continue; } id = edButtons[i].id; if ( use && defaults.indexOf( ',' + id + ',' ) !== -1 && use.indexOf( ',' + id + ',' ) === -1 ) { continue; } if ( !edButtons[i].instance || edButtons[i].instance === inst ) { theButtons[id] = edButtons[i]; if ( edButtons[i].html ) { html += edButtons[i].html(name + '_'); } } } if ( use && use.indexOf(',fullscreen,') !== -1 ) { theButtons.fullscreen = new qt.FullscreenButton(); html += theButtons.fullscreen.html(name + '_'); } if ( 'rtl' === document.getElementsByTagName('html')[0].dir ) { theButtons.textdirection = new qt.TextDirectionButton(); html += theButtons.textdirection.html(name + '_'); } ed.toolbar.innerHTML = html; ed.theButtons = theButtons; }, }); $(document).ready(function(){ // move acf_content wysiwyg if( $('#wp-acf_content-wrap').exists() ) { $('#wp-acf_content-wrap').parent().appendTo('body'); } }); })(jQuery); // @codekit-prepend "../js/event-manager.js"; // @codekit-prepend "../js/acf.js"; // @codekit-prepend "../js/acf-ajax.js"; // @codekit-prepend "../js/acf-checkbox.js"; // @codekit-prepend "../js/acf-color-picker.js"; // @codekit-prepend "../js/acf-conditional-logic.js"; // @codekit-prepend "../js/acf-date-picker.js"; // @codekit-prepend "../js/acf-file.js"; // @codekit-prepend "../js/acf-google-map.js"; // @codekit-prepend "../js/acf-image.js"; // @codekit-prepend "../js/acf-media.js"; // @codekit-prepend "../js/acf-oembed.js"; // @codekit-prepend "../js/acf-radio.js"; // @codekit-prepend "../js/acf-relationship.js"; // @codekit-prepend "../js/acf-select.js"; // @codekit-prepend "../js/acf-tab.js"; // @codekit-prepend "../js/acf-taxonomy.js"; // @codekit-prepend "../js/acf-url.js"; // @codekit-prepend "../js/acf-validation.js"; // @codekit-prepend "../js/acf-wysiwyg.js";
mit
rightscale/right_aws_api
lib/cloud/aws/route53/routines/request_signer.rb
2954
#-- # Copyright (c) 2013 RightScale, Inc. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # 'Software'), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ module RightScale module CloudApi module AWS module Route53 # Route 53 request signer class RequestSigner < CloudApi::Routine # Route53 RequestSigner Error class Error < CloudApi::Error end # Authenticates a Route53 request # # @return [void] # # @example # # no example # def process # Fix body unless @data[:request][:body]._blank? # Make sure 'content-type' is set if we have a body @data[:request][:headers].set_if_blank('content-type', 'application/xml' ) # Fix body if it is a Hash instance if @data[:request][:body].is_a?(Hash) @data[:request][:body] = Utils::contentify_body(@data[:request][:body], @data[:request][:headers]['content-type']) end # Calculate 'content-md5' when possible (some API calls wanna have it set) if @data[:request][:body].is_a?(String) @data[:request][:headers]['content-md5'] = Base64::encode64(Digest::MD5::digest(@data[:request][:body])).strip end end # Set date @data[:request][:headers].set_if_blank('x-amz-date', Time::now.utc.httpdate) # Set path @data[:request][:path] = Utils::join_urn(@data[:connection][:uri].path, @data[:options][:api_version], @data[:request][:relative_path], @data[:request][:params]) # Sign a request Utils::AWS::sign_v4_signature( @data[:credentials][:aws_access_key_id], @data[:credentials][:aws_secret_access_key], @data[:connection][:uri].host, @data[:request] ) end end end end end end
mit
rkrauskopf/chai-exec
lib/util.js
1285
"use strict"; const chai = require("chai"); const flag = chai.util.flag; const util = module.exports = { /** * Determines whether the given value is a CLI object */ isCLI (cli) { return cli && typeof cli === "object" && typeof cli.command === "string" && Array.isArray(cli.args); }, /** * Sets multiple assertion flags at once, and returns commonly-used flags * * @param {chai.Assertion} assertion - The Assertion to get/set flags for * @param {object} [flags] - A map of flag names and values to set * @returns {object} - A map of flag names and values, including commonly-used flags */ flags (assertion, flags = {}) { // Set all the flags for (let key of Object.keys(flags)) { flag(assertion, key, flags[key]); } // Always return these flags flags.object = flags.object || flag(assertion, "object"); flags.cli = flags.cli || flag(assertion, "cli"); flags.message = flags.message || flag(assertion, "message"); // If the "cli" flag isn't set, and the "object" flag is a CLI object, // then go ahead and set the "cli" flag if (!flags.cli && util.isCLI(flags.object)) { flag(assertion, "cli", flags.object); flags.cli = flags.object; } return flags; }, };
mit
DarkIrata/WinCommandPalette
WinCommandPalette/Enums/ModifierKey.cs
317
using WinCommandPalette.Helper; using System; namespace WinCommandPalette.Enums { [Flags] public enum ModifierKey { None = 0, ALT = HotKeyHelper.MOD_ALT, LeftCTRL = HotKeyHelper.MOD_CONTROL, LeftShift = HotKeyHelper.MOD_SHIFT, Win = HotKeyHelper.MOD_WIN } }
mit
cuckata23/wurfl-data
data/verykool_s353_ver1.php
409
<?php return array ( 'id' => 'verykool_s353_ver1', 'fallback' => 'generic_android_ver4_2', 'capabilities' => array ( 'model_name' => 'S353', 'brand_name' => 'verykool', 'marketing_name' => 'Jasper', 'release_date' => '2013_november', 'physical_screen_height' => '77', 'physical_screen_width' => '46', 'resolution_width' => '480', 'resolution_height' => '800', ), );
mit
ellipsesynergie/jquery-google-piechart
lib/piechart.min.js
708
(function($){function Piechart(element,options){this.element=element,this.options=$.extend({},defaults,options),this._defaults=defaults,this._name=pluginName,this.data=$(this.element).data("data"),this.init()}var pluginName="piechart",defaults={backgroundColor:"transparent",colors:["#468851","#C24A48"],legend:{position:"none"}};Piechart.prototype={init:function(){var chartData=google.visualization.arrayToDataTable(this.data),chart=new google.visualization.PieChart(this.element);chart.draw(chartData,this.options)}},$.fn[pluginName]=function(options){return this.each(function(){$.data(this,"plugin_"+pluginName)||$.data(this,"plugin_"+pluginName,new Piechart(this,options))})}})(jQuery,window,document);
mit
dkrock24/lapizzeria
pages/d.php
1514
session_start(); include_once("../class_db/class_menus.php"); <!-- *** HOMEPAGE CAROUSEL *** --> <div class="home-carousel"> <div class="dark-mask"></div> <div class="container"> <div class="homepage owl-carousel"> <?php foreach ($carrusel as $item) { ?> <div class="item"> <div class="row"> <div class="col-sm-5 right"> <p> <img src="../../../../asset_/img/<?php echo $item->imagen; ?>.png" alt=""> </p> <h1><?php echo $item->titulo; ?></h1> <p><?php echo $item->descripcion; ?></p> </div> <div class="col-sm-7"> <img class="img-responsive" src="../../../../asset_/img/<?php echo $item->pie; ?>.png" alt=""> </div> </div> </div> <?php } ?> </div> <!-- /.project owl-slider --> </div> </div> <!-- *** HOMEPAGE CAROUSEL END *** -->
mit
sebastienros/yessql
src/YesSql.Abstractions/Commands/IAddColumnCommand.cs
109
namespace YesSql.Sql.Schema { public interface IAddColumnCommand : ICreateColumnCommand { } }
mit
feltnerm/whatcd-search
index.js
1418
#!/usr/bin/env node var util = require('util'), _ = require('underscore'), minimist = require('minimist'); var Client = require('./lib/search'); // set default params var params = { searchstr: 'Pure Guava' }; function filter_torrents(torrents){ return torrents.map(function (torrent) { var info = _.extend( _.omit(torrent.group, 'wikiBody', 'vanityHouse', 'isBookmarked'), _.omit(torrent.torrent, 'description', 'seeders', 'leechers', 'snatched', 'freeTorrent', 'reported', 'time', 'description', 'fileList') ); return info; }); } if (process.argv.length > 2) { var args = process.argv.slice(2), argv = minimist(args); params = _.extend(params, argv); var client = Client(process.env.WHAT_USERNAME, process.env.WHAT_PASSWORD); client.search(params).then(function(result){ console.dir(filter_torrents(result)); }, function(error){ debug(error); }); } else { console.log("Usage: \n" + "\n" + "--artistname ['Ween',...]\n" + "--searchstr ['White Pepper',...]\n" + "--media [WEB,CD,...]\n" + "--encoding [lossless,...]\n" + "--format [FLAC,...]\n" + "\n" + " .. and so forth ...\n"); process.exit(1) }
mit
obivandamme/MSTest.Fluent
MSTest.Fluent/Not/NotObject.cs
3077
namespace MSTest.Fluent.Not { using System; using MSTest.Fluent.Expect; using MSTest.Fluent.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; public class NotObject { private readonly ExpectObject expect; public NotObject(ExpectObject expect) { this.expect = expect; } public AndConstraint<ExpectObject> ToEqual(object notExpected) { return this.AssertFluent(() => Assert.AreNotEqual(notExpected, this.expect.Actual)); } public AndConstraint<ExpectObject> ToEqual(object notExpected, string message) { return this.AssertFluent(() => Assert.AreNotEqual(notExpected, this.expect.Actual, message)); } public AndConstraint<ExpectObject> ToEqual(object notExpected, string message, params object[] parameters) { return this.AssertFluent(() => Assert.AreNotEqual(notExpected, this.expect.Actual, message, parameters)); } public AndConstraint<ExpectObject> ToBeNull() { return this.AssertFluent(() => Assert.IsNotNull(this.expect.Actual)); } public AndConstraint<ExpectObject> ToBeNull(string message) { return this.AssertFluent(() => Assert.IsNotNull(this.expect.Actual, message)); } public AndConstraint<ExpectObject> ToBeNull(string message, params object[] parameters) { return this.AssertFluent(()=> Assert.IsNotNull(this.expect, message, parameters)); } public AndConstraint<ExpectObject> ToBe(object notExpected) { return this.AssertFluent(() => Assert.AreNotSame(notExpected, this.expect.Actual)); } public AndConstraint<ExpectObject> ToBe(object notExpected, string message) { return this.AssertFluent(() => Assert.AreNotSame(notExpected, this.expect.Actual, message)); } public AndConstraint<ExpectObject> ToBe(object notExpected, string message, params object[] parameters) { return this.AssertFluent(() => Assert.AreNotSame(notExpected, this.expect, message, parameters)); } public AndConstraint<ExpectObject> ToBeInstanceOfType(Type wrongType) { return this.AssertFluent(() => Assert.IsNotInstanceOfType(this.expect.Actual, wrongType)); } public AndConstraint<ExpectObject> ToBeInstanceOfType(Type wrongType, string message) { return this.AssertFluent(() => Assert.IsNotInstanceOfType(this.expect, wrongType, message)); } public AndConstraint<ExpectObject> ToBeInstanceOfType(Type wrongType, string message, params object[] parameters) { return this.AssertFluent(() => Assert.IsNotInstanceOfType(this.expect, wrongType, message, parameters)); } private AndConstraint<ExpectObject> AssertFluent(Action assert) { assert.Invoke(); return new AndConstraint<ExpectObject>(this.expect); } } }
mit
frederic3476/compte
src/Applisun/GraphicBundle/Graphic/Flot/Type/AbstractType.php
598
<?php namespace Applisun\GraphicBundle\Graphic\Flot\Type; abstract class AbstractType { protected $domSelector; protected $data; public $options = array(); public function __construct($domSelector, $data, $options = array()) { $this->domSelector = $domSelector; $this->data = $data; if (is_array($options)) { $this->options = $this->options + $options; } } public function getView() { return array("domSelector" => $this->domSelector, "data" => $this->data, "options" => $this->options); } }
mit
ShoukriKattan/ForgedUI-Eclipse
com.forgedui.editor/src/com/forgedui/editor/edit/SliderEditPart.java
1576
package com.forgedui.editor.edit; import com.forgedui.editor.figures.SliderFigure; import com.forgedui.model.titanium.Slider; import com.forgedui.util.Utils; /** * Edit part for the slider component. * * @author Tareq Doufish * */ public class SliderEditPart extends TitaniumElementEditPart<Slider> { @Override protected void refreshVisuals() { SliderFigure figure = (SliderFigure)getFigure(); Slider model = getModel(); double value = getDefaultValue(); if (model.getMin() != null && model.getMax() != null){ if (model.getMax() > model.getMin()){ if (model.getValue() != null){ value = (model.getValue() - model.getMin())/(model.getMax() - model.getMin()); } else if (model.getMinRange() != null){ value = (model.getMinRange() - model.getMin())/(model.getMax() - model.getMin()); } } } figure.setValue(value); super.refreshVisuals(); } protected float getDefaultValue(){ return getModel().getPlatform().isAndroid() ? 0 : 1; } @Override protected String getBackgroundColor() { return Utils.getBoolean(getModel().getEnabled(), true) ? getModel().getBackgroundColor() : Utils.getString( getModel().getBackgroundDisabledColor(), getModel().getBackgroundColor()); } @Override protected String getBackgroundImage() { return Utils.getBoolean(getModel().getEnabled(), true) ? getModel().getBackgroundImage() : Utils.getString( getModel().getBackgroundDisabledImage(), getModel().getBackgroundImage()); } }
mit
danylaporte/asyncplify
src/flatMapLatest.js
1427
Asyncplify.prototype.flatMapLatest = function (options) { return new Asyncplify(FlatMapLatest, options, this); }; function FlatMapLatest(options, sink, source) { this.mapper = options || identity; this.sink = sink; this.sink.source = this; this.source = null; this.subscription = null; source._subscribe(this); } FlatMapLatest.prototype = { childEnd: function (err, item) { this.subscription = null; if (err && this.source) { this.source.setState(Asyncplify.states.CLOSED); this.source = null; this.mapper = noop; } if (err || !this.source) this.sink.end(err); }, emit: function (v) { var item = this.mapper(v); if (item) { if (this.subscription) this.subscription.setState(Asyncplify.states.CLOSED); this.subscription = new FlatMapItem(this); item._subscribe(this.subscription); } }, end: function (err) { this.mapper = noop; this.source = null; if (err && this.subscription) { this.subscription.setState(Asyncplify.states.CLOSED); this.subscription = null; } if (err || !this.subscription) this.sink.end(err); }, setState: function (state) { if (this.source) this.source.setState(state); if (this.subscription) this.subscription.setState(state); } };
mit
oxyno-zeta/crash-reporter-electron
src/webDev/crash-reporter/views/projects/list/js/list.controller.js
781
/* * Author: Alexandre Havrileck (Oxyno-zeta) * Date: 22/07/16 * Licence: See Readme */ (function () { 'use strict'; angular .module('crash-reporter.views.projects.list') .controller('ProjectsController', ProjectsController); /** @ngInject */ function ProjectsController(projectList) { var vm = this; // Variables vm.projectList = projectList; // Functions //////////////// /* ************************************* */ /* ******** PRIVATE FUNCTIONS ******** */ /* ************************************* */ /* ************************************* */ /* ******** PUBLIC FUNCTIONS ******** */ /* ************************************* */ } })();
mit
jcmuller/build_status_server
spec/lib/build_status_server/http_server_spec.rb
2702
require 'spec_helper' describe BuildStatusServer::HTTPServer do let(:tcp_server) { { "address" => "address", "port" => "port" }} let(:config) { double(tcp_server: tcp_server, verbose: false) } let(:store) { double } subject { described_class.new(config, store, false) } before do TCPServer.stub(:new) end describe "#setup" do after { subject.setup } it { TCPServer.should_receive(:new).with("address", "port") } it "should let us all know about it if verbose" do config.should_receive(:verbose).and_return(true) STDOUT.should_receive(:puts).with("Listening on TCP address:port") end it "should report error on address in use" do subject.should_receive(:address_in_use_error) TCPServer.should_receive(:new).and_raise(Errno::EADDRINUSE) end it "should report error on address not available" do subject.should_receive(:address_not_available_error) TCPServer.should_receive(:new).and_raise(Errno::EADDRNOTAVAIL) end end describe "#process" do it "should start thread and process request" do request = double server = double(accept: request) subject.should_receive(:server).and_return(server) Thread.should_receive(:start).with(request).and_yield(request) subject.should_receive(:process_request).with(request) subject.process end end describe "#process_request" do let(:request) { double } before do request.stub(:print) request.stub(:close) subject.stub(:headers).and_return("headers") subject.stub(:body).and_return("body") end it { request.should_receive(:print).with("headers") } it { request.should_receive(:print).with("body") } it { request.should_receive(:close) } after { subject.send(:process_request, request) } end describe "#headers" do it { subject.send(:headers).should == "HTTP/1.1 200/OK\r\nContent-type:text/html\r\n\r\n" } end describe "#body" do it "should print body" do subject.should_receive(:build_status).and_return("build_status") subject.send(:body).should == <<-EOB <html> <head> <meta http-equiv="refresh" content="5; url=http://address:port/"> </head> <body> Build is build_status </body> </html> EOB end end describe "#build_status" do it "should return passing if builds are passing" do store.should_receive(:passing_builds?).and_return(true) subject.send(:build_status).should == "passing" end it "should return failing if builds are failing" do store.should_receive(:passing_builds?).and_return(false) subject.send(:build_status).should == "failing" end end end
mit
yojimbo87/ArangoDB-NET
src/Arango/Arango.Tests/Issues/IssueTests.cs
10676
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Arango.Client; namespace Arango.Tests { [TestFixture()] public class IssueTests : IDisposable { public IssueTests() { Database.CreateTestDatabase(Database.TestDatabaseGeneral); } [Test()] public void Issue_No8_Guid_conversion() { Database.CreateTestCollection(Database.TestDocumentCollectionName, ACollectionType.Document); var db = new ADatabase(Database.Alias); var demo = new IssueNo8Entity(); demo.SomeOtherId = Guid.NewGuid(); demo.Name = "My name"; var createResult = db.Document.Create(Database.TestDocumentCollectionName, demo); Assert.IsTrue(createResult.Success); var getresult = db.Document.Get<IssueNo8Entity>(createResult.Value.ID()); Assert.IsTrue(getresult.Success); Assert.AreEqual(demo.SomeOtherId.ToString(), getresult.Value.SomeOtherId.ToString()); } [Test()] public void Issue_No9_Enum_type_handling() { Database.CreateTestCollection(Database.TestDocumentCollectionName, ACollectionType.Document); var db = new ADatabase(Database.Alias); var demo = new IssueNo9Entity(); demo.SomeOtherId = Guid.NewGuid(); demo.Name = "My name"; demo.MyFavoriteColor = IssueNo9Entity.Color.Blue; var createResult = db.Document.Create(Database.TestDocumentCollectionName, demo); Assert.IsTrue(createResult.Success); var getResult = db.Document.Get<IssueNo9Entity>(createResult.Value.ID()); Assert.IsTrue(getResult.Success); Assert.AreEqual(demo.MyFavoriteColor, getResult.Value.MyFavoriteColor); var getDocResult = db.Document.Get(createResult.Value.ID()); Assert.IsTrue(getDocResult.Success); Assert.IsTrue(getDocResult.Value.IsString("MyFavoriteColor")); Assert.AreEqual(demo.MyFavoriteColor.ToString(), getDocResult.Value.String("MyFavoriteColor")); // change JSON serialization options to serialize enum types as values (integers and not strings) ASettings.JsonParameters.UseValuesOfEnums = true; var createResult2 = db.Document.Create(Database.TestDocumentCollectionName, demo); Assert.IsTrue(createResult2.Success); var getDocResult2 = db.Document.Get(createResult2.Value.ID()); Assert.IsTrue(getDocResult2.Success); Assert.IsTrue(getDocResult2.Value.IsLong("MyFavoriteColor")); Assert.AreEqual((int)demo.MyFavoriteColor, getDocResult2.Value.Int("MyFavoriteColor")); } [Test()] public void Issue_No15_List_save_and_retrieve() { Database.CreateTestCollection(Database.TestDocumentCollectionName, ACollectionType.Document); var db = new ADatabase(Database.Alias); var entity = new IssueNo15Entity(); entity.ListNumbers = new List<int> { 1, 2, 3 }; entity.ArrayNumbers = new int[] { 4, 5, 6}; var createResult = db.Document.Create(Database.TestDocumentCollectionName, entity); Assert.IsTrue(createResult.Success); var getresult = db.Document.Get<IssueNo15Entity>(createResult.Value.ID()); Assert.IsTrue(getresult.Success); Assert.IsTrue(getresult.HasValue); for (int i = 0; i < getresult.Value.ListNumbers.Count; i++) { Assert.AreEqual(entity.ListNumbers[i], getresult.Value.ListNumbers[i]); } for (int i = 0; i < getresult.Value.ArrayNumbers.Length; i++) { Assert.AreEqual(entity.ArrayNumbers[i], getresult.Value.ArrayNumbers[i]); } } [Test()] public void Issue_No16_SortedList() { Database.CreateTestCollection(Database.TestDocumentCollectionName, ACollectionType.Document); var db = new ADatabase(Database.Alias); var entity = new IssueNo16Entity(); entity.SortedList = new SortedList<int, bool>(); entity.SortedList.Add(1, true); entity.SortedList.Add(2, false); entity.SortedList.Add(3, false); entity.SortedList.Add(4, false); var createResult = db.Document.Create(Database.TestDocumentCollectionName, entity); Assert.IsTrue(createResult.Success); var getResult = db.Document.Get<IssueNo16Entity>(createResult.Value.ID()); Assert.IsTrue(getResult.Success); Assert.IsTrue(getResult.HasValue); for (int i = 0; i < getResult.Value.SortedList.Count; i++) { Assert.AreEqual(entity.SortedList.ElementAt(i).Key, getResult.Value.SortedList.ElementAt(i).Key); Assert.AreEqual(entity.SortedList.ElementAt(i).Value, getResult.Value.SortedList.ElementAt(i).Value); } } [Test()] public void Issue_No34_MapAttributesToProperties() { Database.CreateTestCollection(Database.TestDocumentCollectionName, ACollectionType.Document); Database.CreateTestCollection(Database.TestEdgeCollectionName, ACollectionType.Edge); var db = new ADatabase(Database.Alias); var vertex1 = new IssueNo34Entity { Key = "5", Foo = "some string value", Bar = 12345 }; var createResult1 = db.Document.Create(Database.TestDocumentCollectionName, vertex1); Assert.IsTrue(createResult1.Success); Assert.IsTrue(createResult1.HasValue); Assert.AreEqual(vertex1.Key, createResult1.Value.Key()); var getResult1 = db.Document.Get<IssueNo34Entity>(createResult1.Value.ID()); Assert.IsTrue(getResult1.Success); Assert.IsTrue(getResult1.HasValue); Assert.AreEqual(vertex1.Key, getResult1.Value.Key); Assert.AreEqual(vertex1.Foo, getResult1.Value.Foo); Assert.AreEqual(vertex1.Bar, getResult1.Value.Bar); var vertex2 = new IssueNo34Entity { Key = "8", Foo = "some other string value", Bar = 67890 }; var createResult2 = db.Document.Create(Database.TestDocumentCollectionName, vertex2); Assert.IsTrue(createResult2.Success); Assert.IsTrue(createResult2.HasValue); Assert.AreEqual(vertex2.Key, createResult2.Value.Key()); var getResult2 = db.Document.Get<IssueNo34Entity>(createResult2.Value.ID()); Assert.IsTrue(getResult2.Success); Assert.IsTrue(getResult2.HasValue); Assert.AreEqual(vertex2.Key, getResult2.Value.Key); Assert.AreEqual(vertex2.Foo, getResult2.Value.Foo); Assert.AreEqual(vertex2.Bar, getResult2.Value.Bar); var edge = new IssueNo34Entity { From = createResult1.Value.ID(), To = createResult2.Value.ID(), Key = "10", Foo = "edge string value", Bar = 13579 }; var createEdge = db .Document .ReturnNew() .CreateEdge(Database.TestEdgeCollectionName, edge.From, edge.To, edge); Assert.IsTrue(createEdge.Success); Assert.IsTrue(createEdge.HasValue); Assert.AreEqual(edge.Key, createEdge.Value.Key()); var getEdge = db.Document.Get<IssueNo34Entity>(createEdge.Value.ID()); Assert.IsTrue(getEdge.Success); Assert.IsTrue(getEdge.HasValue); Assert.AreEqual(edge.From, getEdge.Value.From); Assert.AreEqual(edge.To, getEdge.Value.To); Assert.AreEqual(edge.Key, getEdge.Value.Key); Assert.AreEqual(edge.Foo, getEdge.Value.Foo); Assert.AreEqual(edge.Bar, getEdge.Value.Bar); var queryVertex1Result = db.Query .Aql($"FOR item IN {Database.TestDocumentCollectionName} FILTER item._key == \"{vertex1.Key}\" RETURN item") .ToObject<IssueNo34Entity>(); Assert.IsTrue(queryVertex1Result.Success); Assert.IsTrue(queryVertex1Result.HasValue); Assert.AreEqual(vertex1.Key, queryVertex1Result.Value.Key); Assert.AreEqual(vertex1.Foo, queryVertex1Result.Value.Foo); Assert.AreEqual(vertex1.Bar, queryVertex1Result.Value.Bar); var queryVertex2Result = db.Query .Aql($"FOR item IN {Database.TestDocumentCollectionName} FILTER item._key == \"{vertex2.Key}\" RETURN item") .ToObject<IssueNo34Entity>(); Assert.IsTrue(queryVertex2Result.Success); Assert.IsTrue(queryVertex2Result.HasValue); Assert.AreEqual(vertex2.Key, queryVertex2Result.Value.Key); Assert.AreEqual(vertex2.Foo, queryVertex2Result.Value.Foo); Assert.AreEqual(vertex2.Bar, queryVertex2Result.Value.Bar); var queryEdgeResult = db.Query .Aql($"FOR item IN {Database.TestEdgeCollectionName} FILTER item._key == \"{edge.Key}\" RETURN item") .ToObject<IssueNo34Entity>(); Assert.IsTrue(queryEdgeResult.Success); Assert.IsTrue(queryEdgeResult.HasValue); Assert.AreEqual(edge.From, queryEdgeResult.Value.From); Assert.AreEqual(edge.To, queryEdgeResult.Value.To); Assert.AreEqual(edge.Key, queryEdgeResult.Value.Key); Assert.AreEqual(edge.Foo, queryEdgeResult.Value.Foo); Assert.AreEqual(edge.Bar, queryEdgeResult.Value.Bar); } public void Dispose() { Database.DeleteTestDatabase(Database.TestDatabaseGeneral); } } }
mit
lcristianiim/caesar-crypter
example/index.js
332
const caesarCrypter = require("../lib"); // Encrypt the 'ab' message using base string 'abcdefgh', step 1, direction -1 console.log(caesarCrypter.encrypt(1,-1,"abcdefgh","ab")); // 'ha' // Decrypt the 'ha' message using base string 'abcdefgh', step 1, direction -1 console.log(caesarCrypter.decrypt(1,-1,"abcdefgh","ha")); // 'ab'
mit
surendrary/CMPE-202-GU
TestGuessIt/src/com/GuessDatabaseResource.java
4903
package com; import java.io.IOException; import java.util.HashMap; import java.util.Random; import java.util.UUID; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.JSONException; import org.json.JSONObject; import org.restlet.representation.Representation; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.WriteResult; @Path("/guessit/database") public class GuessDatabaseResource { @GET @Produces("application/json") public Response represent() throws JSONException { String dbURI = "mongodb://guessitadmin:[email protected]:51137/guessit"; MongoClient mongoClient = new MongoClient(new MongoClientURI(dbURI)); DB db = mongoClient.getDB("guessit"); DBObject query = BasicDBObjectBuilder.start().add("_id", 123).get(); JSONObject gameObject = new JSONObject(); DBCollection gameCollection = db.getCollection("gameTable"); DBCursor cursor = gameCollection.find(query); DBObject gameDetails = null; if (cursor != null && cursor.hasNext()) { gameDetails = cursor.next(); gameObject.put("game", gameDetails); } else { gameObject.put("message", "No game with this id exists. Please check!"); } return Response.status(200).entity(gameObject).build(); } @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.TEXT_PLAIN }) public String hostGame(Game entity) throws IOException, JSONException { Representation result = null; String dbURI = "mongodb://guessitadmin:[email protected]:51137/guessit"; MongoClient mongoClient = new MongoClient(new MongoClientURI(dbURI)); DB db = mongoClient.getDB("guessit"); DBCollection gameCollection = db.getCollection("gameTable"); String host = entity.getHost(); String gameLevel = entity.getLevel(); String gameName = entity.getGameName(); UUID id = UUID.randomUUID(); DBObject foundGame = findGame(gameName); if (foundGame == null) { int computerGuess = 70; if (gameLevel.equalsIgnoreCase("easy")) computerGuess = new Random().nextInt(100) + 2; else computerGuess = new Random().nextInt(1000) + 2; BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start(); BasicDBList asList1 = new BasicDBList(); BasicDBList asList2 = new BasicDBList(); docBuilder.append("_id", id); docBuilder.append("host", host); docBuilder.append("level", gameLevel); docBuilder.append("gameName", gameName); docBuilder.append("computerGuess", computerGuess); docBuilder.append("players", asList1); docBuilder.append("score", asList2); DBObject gameObject = docBuilder.get(); gameCollection.insert(gameObject); mongoClient.close(); return String.valueOf(computerGuess); } else return "Error! Game already Exists"; } @PUT @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.TEXT_PLAIN }) public String joinGame(Game entity) throws JSONException { String dbURI = "mongodb://guessitadmin:[email protected]:51137/guessit"; MongoClient mongoClient = new MongoClient(new MongoClientURI(dbURI)); DB db = mongoClient.getDB("guessit"); DBCollection gameCollection = db.getCollection("gameTable"); DBObject foundGame = findGame(entity.getGameName()); if (foundGame == null) { return "Game Does Not Exists"; } else { BasicDBObject updateQuery = new BasicDBObject(); updateQuery.put("gameName", entity.getGameName()); BasicDBObject updateCommand = new BasicDBObject(); HashMap<String, String> map = new HashMap<String, String>(); map.put("playerName", entity.getPlayerName()); updateCommand.put("$push", new BasicDBObject("players", map)); WriteResult result = gameCollection.update(updateQuery, updateCommand, true, true); mongoClient.close(); } return foundGame.get("computerGuess").toString(); } private DBObject findGame(String gameName) throws JSONException { String dbURI = "mongodb://guessitadmin:[email protected]:51137/guessit"; MongoClient mongoClient = new MongoClient(new MongoClientURI(dbURI)); DB db = mongoClient.getDB("guessit"); DBObject query = BasicDBObjectBuilder.start().add("gameName", gameName).get(); JSONObject gameObject = new JSONObject(); DBCollection gameCollection = db.getCollection("gameTable"); DBCursor cursor = gameCollection.find(query); DBObject gameDetails = null; if (cursor != null && cursor.hasNext()) { gameDetails = cursor.next(); gameObject.put("game", gameDetails); mongoClient.close(); } return gameDetails; } }
mit
WaveEngine/Extensions
WaveEngine.Networking/Shared/Connection/EventArgs/HostDiscoveredEventArgs.cs
922
// Copyright © 2018 Wave Engine S.L. All rights reserved. Use is subject to license terms. #region Using Statements using System; #endregion namespace WaveEngine.Networking.Connection { /// <summary> /// Represents the arguments of the host discovered event. /// </summary> public class HostDiscoveredEventArgs : EventArgs { #region Properties /// <summary> /// Gets the discovered host endpoint. /// </summary> public NetworkEndpoint Host { get; private set; } #endregion #region Initialize /// <summary> /// Initializes a new instance of the <see cref="HostDiscoveredEventArgs" /> class. /// </summary> /// <param name="host">The discovered host endpoint</param> public HostDiscoveredEventArgs(NetworkEndpoint host) { this.Host = host; } #endregion } }
mit
Telerik-Pomegranate/Announcement
lib/scripts/bower_components/system.js/bench/config-example/pkg-configs.js
17984
System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "mocha", "meta": { "mocha.js": { "deps": [ "./mocha.css!" ], "exports": "mocha" } } }; }); System.registerDynamic("github:angular/[email protected]", [], false, function() { return { "main": "angular", "meta": { "angular.js": { "exports": "angular" } } }; }); System.registerDynamic("github:systemjs/[email protected]", [], false, function() { return { "main": "css" }; }); System.registerDynamic("github:twbs/[email protected]", [], false, function() { return { "main": "dist/js/bootstrap.js", "meta": { "dist/js/bootstrap.js": { "deps": [ "jquery" ], "exports": "$" } } }; }); System.registerDynamic("github:systemjs/[email protected]", [], false, function() { return { "main": "text" }; }); System.registerDynamic("github:components/[email protected]", [], false, function() { return { "main": "jquery" }; }); System.registerDynamic("github:mbostock/[email protected]", [], false, function() { return { "main": "d3", "meta": { "d3.js": { "exports": "d3", "format": "global" } } }; }); System.registerDynamic("github:jspm/[email protected]", [], false, function() { return { "main": "./util.js", "map": { "./isBuffer.js": { "~node": "./isBufferBrowser.js" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "ready.js", "format": "cjs", "meta": { "*.json": { "format": "json" } }, "map": { "domready": "." } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "invert.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "lb.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "iota.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "shell.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "fft.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "scratch.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "downsample.js", "format": "cjs", "meta": { "*": { "globals": { "process": "process" } }, "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "mipmap.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "texture.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "tilemap.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "buffer.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "webglew.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "vao.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "dist/gl-matrix.js", "format": "cjs", "meta": { "*.json": { "format": "json" }, "dist/gl-matrix-min.js": { "format": "amd" }, "src/gl-matrix.js.erb": { "format": "amd" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "esprima.js", "format": "cjs", "meta": { "*": { "globals": { "process": "process" } }, "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "cwise.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "compiler.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "ndarray-ops.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" }, "test/*": { "globals": { "Buffer": "buffer/global" } } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "ndarray.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "compiler.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "twiddle.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "dup.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "pool.js", "format": "cjs", "meta": { "*.json": { "format": "json" }, "pool.js": { "globals": { "Buffer": "buffer/global" } }, "test/*": { "globals": { "Buffer": "buffer/global" } } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "uniq.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "iota.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "greedy.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "twiddle.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "dup.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "pool.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "mesh.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("github:jspm/[email protected]", [], false, function() { return { "main": "./fs.js" }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*": { "globals": { "process": "process" } }, "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*": { "globals": { "process": "process" } }, "*.json": { "format": "json" } }, "map": { "./test.js": "./test/index.js" } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" } }, "map": { "./lib.js": "./lib/index.js", "./test.js": "./test/index.js" } }; }); System.registerDynamic("github:jspm/[email protected]", [], false, function() { return { "main": "./stream.js", "map": { "./stream.js": { "browser": "stream-browserify" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" }, "index.js": { "globals": { "Buffer": "buffer/global" } } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*": { "globals": { "process": "process" } }, "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "node.js", "format": "cjs", "meta": { "*.json": { "format": "json" } }, "map": { "./node.js": { "browser": "./browser.js" } } }; }); System.registerDynamic("github:jspm/[email protected]", [], false, function() { return { "main": "./events.js" }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "lib/b64.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" }, "test/*": { "globals": { "Buffer": "buffer/global" } } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*": { "globals": { "process": "process" } }, "*.json": { "format": "json" }, "test/constructor.js": { "globals": { "Buffer": "buffer/global" } }, "test/node-es6/test-buffer-arraybuffer.js": { "globals": { "Buffer": "buffer/global" } }, "test/node-es6/test-buffer-iterator.js": { "globals": { "Buffer": "buffer/global" } }, "test/node/test-buffer-ascii.js": { "globals": { "Buffer": "buffer/global" } }, "test/node/test-buffer-bytelength.js": { "globals": { "Buffer": "buffer/global" } }, "test/node/test-buffer-concat.js": { "globals": { "Buffer": "buffer/global" } }, "test/node/test-buffer-indexof.js": { "globals": { "Buffer": "buffer/global" } }, "test/node/test-buffer-inspect.js": { "globals": { "Buffer": "buffer/global" } }, "test/node/test-buffer.js": { "globals": { "Buffer": "buffer/global" } } } }; }); System.registerDynamic("github:jspm/[email protected]", [], false, function() { return { "main": "buffer.js", "map": { "./buffer.js": { "browser": "buffer-browserify" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "lib/util.js", "format": "cjs", "meta": { "*.json": { "format": "json" }, "lib/*": { "globals": { "Buffer": "buffer/global" } }, "test.js": { "globals": { "Buffer": "buffer/global" } } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "inherits.js", "format": "cjs", "meta": { "*.json": { "format": "json" } }, "map": { "./inherits.js": { "browser": "./inherits_browser.js" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "readable.js", "format": "cjs", "meta": { "*": { "globals": { "process": "process" } }, "*.json": { "format": "json" }, "lib/_stream_readable.js": { "globals": { "Buffer": "buffer/global" } }, "lib/_stream_writable.js": { "globals": { "Buffer": "buffer/global" } } }, "map": { "util": { "browser": "@empty" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" }, "test/*": { "globals": { "Buffer": "buffer/global" } } } }; }); System.registerDynamic("github:jspm/[email protected]", [], false, function() { return { "main": "./process.js" }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*": { "globals": { "process": "process" } }, "*.json": { "format": "json" } }, "map": { "./test.js": "./test/index.js" } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "uniq.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "index.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "aoshader.js", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; }); System.registerDynamic("npm:[email protected]", [], false, function() { return { "main": "shader", "format": "cjs", "meta": { "*.json": { "format": "json" } } }; });
mit
Ceasar/twosheds
tests/alias.py
527
def test_alias_substitution1(alias_transform): """Alias substitution should expand aliases.""" text = "ls" assert alias_transform(text) == "ls -G" def test_alias_substitution2(alias_transform): """Alias substitution should not expand arguments.""" text = "echo ls" assert alias_transform(text) == text def test_alias_substitution_inverse(alias_transform): """Alias substitution should have an inverse.""" text = "ls" assert alias_transform(alias_transform(text), inverse=True) == text
mit
HasanSa/hackathon
node_modules/redux-form/es/actions.js
7348
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import { ARRAY_INSERT, ARRAY_MOVE, ARRAY_POP, ARRAY_PUSH, ARRAY_REMOVE, ARRAY_REMOVE_ALL, ARRAY_SHIFT, ARRAY_SPLICE, ARRAY_SWAP, ARRAY_UNSHIFT, AUTOFILL, BLUR, CHANGE, CLEAR_SUBMIT, CLEAR_ASYNC_ERROR, DESTROY, FOCUS, INITIALIZE, REGISTER_FIELD, RESET, SET_SUBMIT_FAILED, SET_SUBMIT_SUCCEEDED, START_ASYNC_VALIDATION, START_SUBMIT, STOP_ASYNC_VALIDATION, STOP_SUBMIT, SUBMIT, TOUCH, UNREGISTER_FIELD, UNTOUCH, UPDATE_SYNC_ERRORS, UPDATE_SYNC_WARNINGS } from './actionTypes'; export var arrayInsert = function arrayInsert(form, field, index, value) { return { type: ARRAY_INSERT, meta: { form: form, field: field, index: index }, payload: value }; }; export var arrayMove = function arrayMove(form, field, from, to) { return { type: ARRAY_MOVE, meta: { form: form, field: field, from: from, to: to } }; }; export var arrayPop = function arrayPop(form, field) { return { type: ARRAY_POP, meta: { form: form, field: field } }; }; export var arrayPush = function arrayPush(form, field, value) { return { type: ARRAY_PUSH, meta: { form: form, field: field }, payload: value }; }; export var arrayRemove = function arrayRemove(form, field, index) { return { type: ARRAY_REMOVE, meta: { form: form, field: field, index: index } }; }; export var arrayRemoveAll = function arrayRemoveAll(form, field) { return { type: ARRAY_REMOVE_ALL, meta: { form: form, field: field } }; }; export var arrayShift = function arrayShift(form, field) { return { type: ARRAY_SHIFT, meta: { form: form, field: field } }; }; export var arraySplice = function arraySplice(form, field, index, removeNum, value) { var action = { type: ARRAY_SPLICE, meta: { form: form, field: field, index: index, removeNum: removeNum } }; if (value !== undefined) { action.payload = value; } return action; }; export var arraySwap = function arraySwap(form, field, indexA, indexB) { if (indexA === indexB) { throw new Error('Swap indices cannot be equal'); } if (indexA < 0 || indexB < 0) { throw new Error('Swap indices cannot be negative'); } return { type: ARRAY_SWAP, meta: { form: form, field: field, indexA: indexA, indexB: indexB } }; }; export var arrayUnshift = function arrayUnshift(form, field, value) { return { type: ARRAY_UNSHIFT, meta: { form: form, field: field }, payload: value }; }; export var autofill = function autofill(form, field, value) { return { type: AUTOFILL, meta: { form: form, field: field }, payload: value }; }; export var blur = function blur(form, field, value, touch) { return { type: BLUR, meta: { form: form, field: field, touch: touch }, payload: value }; }; export var change = function change(form, field, value, touch, persistentSubmitErrors) { return { type: CHANGE, meta: { form: form, field: field, touch: touch, persistentSubmitErrors: persistentSubmitErrors }, payload: value }; }; export var clearSubmit = function clearSubmit(form) { return { type: CLEAR_SUBMIT, meta: { form: form } }; }; export var clearAsyncError = function clearAsyncError(form, field) { return { type: CLEAR_ASYNC_ERROR, meta: { form: form, field: field } }; }; export var destroy = function destroy() { for (var _len = arguments.length, form = Array(_len), _key = 0; _key < _len; _key++) { form[_key] = arguments[_key]; } return { type: DESTROY, meta: { form: form } }; }; export var focus = function focus(form, field) { return { type: FOCUS, meta: { form: form, field: field } }; }; export var initialize = function initialize(form, values, keepDirty) { var otherMeta = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; if (keepDirty instanceof Object) { otherMeta = keepDirty; keepDirty = false; } return { type: INITIALIZE, meta: _extends({ form: form, keepDirty: keepDirty }, otherMeta), payload: values }; }; export var registerField = function registerField(form, name, type) { return { type: REGISTER_FIELD, meta: { form: form }, payload: { name: name, type: type } }; }; export var reset = function reset(form) { return { type: RESET, meta: { form: form } }; }; export var startAsyncValidation = function startAsyncValidation(form, field) { return { type: START_ASYNC_VALIDATION, meta: { form: form, field: field } }; }; export var startSubmit = function startSubmit(form) { return { type: START_SUBMIT, meta: { form: form } }; }; export var stopAsyncValidation = function stopAsyncValidation(form, errors) { var action = { type: STOP_ASYNC_VALIDATION, meta: { form: form }, payload: errors }; if (errors && Object.keys(errors).length) { action.error = true; } return action; }; export var stopSubmit = function stopSubmit(form, errors) { var action = { type: STOP_SUBMIT, meta: { form: form }, payload: errors }; if (errors && Object.keys(errors).length) { action.error = true; } return action; }; export var submit = function submit(form) { return { type: SUBMIT, meta: { form: form } }; }; export var setSubmitFailed = function setSubmitFailed(form) { for (var _len2 = arguments.length, fields = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { fields[_key2 - 1] = arguments[_key2]; } return { type: SET_SUBMIT_FAILED, meta: { form: form, fields: fields }, error: true }; }; export var setSubmitSucceeded = function setSubmitSucceeded(form) { for (var _len3 = arguments.length, fields = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { fields[_key3 - 1] = arguments[_key3]; } return { type: SET_SUBMIT_SUCCEEDED, meta: { form: form, fields: fields }, error: false }; }; export var touch = function touch(form) { for (var _len4 = arguments.length, fields = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { fields[_key4 - 1] = arguments[_key4]; } return { type: TOUCH, meta: { form: form, fields: fields } }; }; export var unregisterField = function unregisterField(form, name) { var destroyOnUnmount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; return { type: UNREGISTER_FIELD, meta: { form: form }, payload: { name: name, destroyOnUnmount: destroyOnUnmount } }; }; export var untouch = function untouch(form) { for (var _len5 = arguments.length, fields = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { fields[_key5 - 1] = arguments[_key5]; } return { type: UNTOUCH, meta: { form: form, fields: fields } }; }; export var updateSyncErrors = function updateSyncErrors(form) { var syncErrors = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var error = arguments[2]; return { type: UPDATE_SYNC_ERRORS, meta: { form: form }, payload: { syncErrors: syncErrors, error: error } }; }; export var updateSyncWarnings = function updateSyncWarnings(form) { var syncWarnings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var warning = arguments[2]; return { type: UPDATE_SYNC_WARNINGS, meta: { form: form }, payload: { syncWarnings: syncWarnings, warning: warning } }; };
mit
logithr/django-htpayway
htpayway/urls.py
407
from htpayway.views import begin, failure, success try: from django.conf.urls.defaults import patterns, url except ImportError: from django.conf.urls import patterns, url urlpatterns = patterns( '', url(r'^begin/(?P<transaction_id>\d+)/$', begin, name='htpayway_begin'), url(r'^success/$', success, name='htpayway_success'), url(r'^failure/$', failure, name='htpayway_failure'), )
mit
boy-jer/santhathi-appointment
config/initializers/accounting_initializers.rb
1078
# COMPANY_NAME = 'Kaiga Thrift Society' BRANCH_NAME = 'Main' #Asset accounts BANK_AC = {:name => 'State Bank of India S.B. A/c.', :group => 'Bank Accounts'} CASH_AC = {:name => 'Cash A/c.', :group => 'Cash-in Hand'} #Liabitiies accounts #Expenses accounts PURCHASE_AC = {:name => 'Purchases A/c.', :group => 'Purchases Account'} #Income accounts MEDICINES_INCOME_AC = {:name => 'Medicines Income A/c.', :group => 'Direct Income'} SERVICES_INCOME_AC = {:name => 'Services Incone A/c.', :group => 'Direct Income'} TESTS_INCOME_AC = {:name => 'Tests Incone A/c.', :group => 'Direct Income'} ##Inventory #Unit of measurements STRIPS_UNIT = {:unit_name => 'Strip', :unit_symbol => 'strips', :sub_unit_name => 'Pieces', :sub_unit_symbol => 'pcs', :unit_value => 10} DOZENS_UNIT = {:unit_name => 'Dozen', :unit_symbol => 'dozen', :sub_unit_name => 'Pieces', :sub_unit_symbol => 'pcs', :unit_value => 12} #Inventory Groups MEDICINES_INV_GRP = {:name => 'Medicines', :description => 'Medicines'} LAB_EQUIPMENTS_INV_GRP = {:name => 'Laboratory Items', :description => 'Medicines'}
mit
snorkpete/everycent
app/models/concerns/transfers.rb
3377
module Transfers extend ActiveSupport::Concern module ClassMethods def transfer(params) from_account = find_by(id: params[:from]) return { success: false, reason: "From account doesn't exist" } unless from_account from_account.transfer(params) end end def transfer(params) return { success: false, reason: "Amount must be greater than 0" } unless params[:amount] > 0 return { success: false, reason: "Description can't be blank" } if params[:description].blank? return { success: false, reason: "Can only transfer from EITHER an allocation OR a sink fund allocation, not both" } if params[:from_allocation] && params[:from_sink_fund_allocation] return { success: false, reason: "Can only transfer to EITHER an allocation OR a sink fund allocation, not both" } if params[:to_allocation] && params[:to_sink_fund_allocation] to_account = BankAccount.find_by(id: params[:to]) return { success: false, reason: "To account doesn't exist" } unless to_account budget = Budget.find_by(id: params[:budget_id]) return { success: false, reason: "Budget doesn't exist" } unless budget transaction_date = params[:date].respond_to?(:strftime) ? params[:date] : Date.parse(params[:date]) if transaction_date > budget.end_date || transaction_date < budget.start_date return { success: false, reason: "Transaction date is outside the budget period" } end from_transaction = Transaction.new( description: "Withdrawal - " + params[:description], withdrawal_amount: params[:amount], deposit_amount: 0, transaction_date: params[:date] || Date.today, status: 'paid', allocation_id: params[:from_allocation], sink_fund_allocation_id: params[:from_sink_fund_allocation], ) transactions << from_transaction to_transaction = Transaction.new( description: "Deposit - " + params[:description], withdrawal_amount: 0, deposit_amount: params[:amount], transaction_date: params[:date] || Date.today, status: 'paid', allocation_id: params[:to_allocation], sink_fund_allocation_id: params[:to_sink_fund_allocation], ) to_account.transactions << to_transaction { success: true } end def transfer_to_old(existing_allocation_id, new_allocation_id, amount, date=Date.today) return if existing_allocation_id == 0 and new_allocation_id == 0 # remove the amount from the existing allocation transaction_from = transaction_for_transfer(existing_allocation_id, date) transaction_from.withdrawal_amount = amount self.transactions << transaction_from transaction_to = transaction_for_transfer(new_allocation_id, date) transaction_to.deposit_amount = amount self.transactions << transaction_to #self.save end def transaction_for_transfer_2(sink_fund_allocation_id, date) new_transaction = Transaction.new(sink_fund_allocation_id: sink_fund_allocation_id) new_transaction.description = "Internal Allocation Transfer" new_transaction.withdrawal_amount = 0 new_transaction.deposit_amount = 0 new_transaction.transaction_date = date new_transaction.status = 'paid' new_transaction end ############################## # end sink fund functions ############################## end
mit
frozzare/wp-admin-menu-tabs
tests/bootstrap.php
215
<?php // Load Composer autoload. require __DIR__ . '/../vendor/autoload.php'; // Load the plugin. WP_Test_Suite::load_plugins( __DIR__ . '/../plugin.php' ); // Run the WordPress test suite. WP_Test_Suite::run();
mit
sethjuarez/numl
Src/numl/Math/Metrics/CosineDistance.cs
598
// file: Math\Metrics\CosineDistance.cs // // summary: Implements the cosine distance class using numl.Math.LinearAlgebra; namespace numl.Math.Metrics { /// <summary>A cosine distance.</summary> public sealed class CosineDistance : IDistance { /// <summary>Computes.</summary> /// <param name="x">The Vector to process.</param> /// <param name="y">The Vector to process.</param> /// <returns>A double.</returns> public double Compute(Vector x, Vector y) { return 1d - (x.Dot(y) / (x.Norm() * y.Norm())); } } }
mit
pegurnee/2013-01-111
Labs/02 - Weekend Trip/WeekendTripProj.java
2451
/** 1/16/13 * This is used to compute the time taken for a weekend trip, * provided the trip is not too long or too short * Coding provided by Eddie Gurnee */ import java.util.Scanner; // imports the Scanner object public class WeekendTripProj { public static void main (String [ ] args) { Scanner keyboard = new Scanner(System.in); //create the variable keyboard of the scanner type double distance, travelTime, averageSpeed; //declares variable for distance, time, and average speed System.out.println("So you want to go on a weekend trip, huh?"); System.out.println(); System.out.print("How far is your destination? "); distance = keyboard.nextDouble(); //reads the distance inputed if (distance > 300) //check distance greater than 300 { if (distance > 600) //check distance greater than 600 { System.out.println("YOU HAVE GOT TO BE KIDDING ME!! THAT'S WAY TOO FAR!!"); } else { System.out.println("Sorry, but that distance is too long for a simple weekend trip") ; } } else if (distance < 19) { System.out.println("Sorry, but that distance is too close for a weekend trip"); } else { System.out.println("That's sounds delightful!"); System.out.println("What do you think your average speed will be (in miles per hour)? "); averageSpeed = keyboard.nextDouble(); //reads the average speed if (averageSpeed > 80) //check speed greater than 80 { if (averageSpeed > 100) //check speed greater than 100 { System.out.println("Cannot compute time considering amout of times you will be pulled over."); } else { System.out.println("You probably shouldn't be driving that fast.") ; } } else if (averageSpeed < 35) { System.out.println("Take public transportation, you drive too slow."); } else { travelTime = distance / averageSpeed; System.out.println("With an average speed of " + averageSpeed + "mph, you should get there in " + travelTime + " hours."); System.out.println(); System.out.println("Enjoy your weekend!"); } } } }
mit
totocheku/ImgSkraper
ImgSkraper.meta.js
503
// ==UserScript== // @name ImgSkraper // @namespace https://github.com/totocheku/ImgSkraper/ // @version 0.1 // @description Scrap all the <img> on the web page and show them in side bar for easy viewing // @author totocheku // @match http://www.xossip.com/* // @grant none // @updateURL https://github.com/totocheku/ImgSkraper/raw/master/ImgSkraper.meta.js // @downloadURL https://github.com/totocheku/ImgSkraper/raw/master/ImgSkraper.user.js // ==/UserScript==
mit
benlangfeld/specinfra
lib/specinfra/backend.rb
304
require 'specinfra/backend/base' require 'specinfra/backend/exec' require 'specinfra/backend/ssh' require 'specinfra/backend/powershell/script_helper' require 'specinfra/backend/powershell/command' require 'specinfra/backend/cmd' require 'specinfra/backend/winrm' require 'specinfra/backend/shellscript'
mit
mickaelandrieu/bamboo
src/Elcodi/Store/MetricBundle/StoreMetricBundle.php
950
<?php /* * This file is part of the Elcodi package. * * Copyright (c) 2014 Elcodi.com * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <[email protected]> * @author Aldo Chiecchia <[email protected]> * @author Elcodi Team <[email protected]> */ namespace Elcodi\Store\MetricBundle; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; use Symfony\Component\HttpKernel\Bundle\Bundle; use Elcodi\Store\MetricBundle\DependencyInjection\StoreMetricExtension; /** * Class StoreMetricBundle */ class StoreMetricBundle extends Bundle { /** * Returns the bundle's container extension. * * @return ExtensionInterface The container extension */ public function getContainerExtension() { return new StoreMetricExtension(); } }
mit
Chormon/EloPVPRanking
src/main/java/pl/chormon/elopvpranking/Config.java
3489
/* * The MIT License * * Copyright 2014 Chormon. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package pl.chormon.elopvpranking; import java.text.MessageFormat; import java.util.List; import org.bukkit.ChatColor; /** * * @author Chormon */ public class Config { public static void initConfig() { EloPVPRanking.get().reloadConfig(); EloPVPRanking.get().saveDefaultConfig(); } public static String getMessage(String path) { return EloPVPRanking.get().getConfig().getString("messages." + path); } @Deprecated public static String getMessage(String path, Object... params) { String message = ""; try { message = ChatColor.translateAlternateColorCodes('&', EloPVPRanking.get().getConfig().getString("messages." + path)); } catch (Exception e) { return ""; } if (params != null) { return MessageFormat.format(message, params); } else { return message; } } public static int getStartingPoints() { return EloPVPRanking.get().getConfig().getInt("settings.startingPoints"); } public static int getConstantValue() { return EloPVPRanking.get().getConfig().getInt("settings.constantValue"); } public static int getPlayersTop() { return EloPVPRanking.get().getConfig().getInt("settings.playersTop"); } public static int getPlayersPerPage() { return EloPVPRanking.get().getConfig().getInt("settings.playersPerPage"); } public static boolean getLogPointsChange() { return EloPVPRanking.get().getConfig().getBoolean("settings.logPointsChange"); } public static int getMaxPoints() { return EloPVPRanking.get().getConfig().getInt("settings.maxPoints"); } public static int getMinPoints() { return EloPVPRanking.get().getConfig().getInt("settings.minPoints"); } public static List<String> getWorlds() { return EloPVPRanking.get().getConfig().getStringList("settings.worlds"); } public static int getKillsHistory() { return EloPVPRanking.get().getConfig().getInt("settings.killsHistory"); } public static int getDeathsHistory() { return EloPVPRanking.get().getConfig().getInt("settings.deathsHistory"); } public static long getRemoveAfter() { return EloPVPRanking.get().getConfig().getLong("settings.removeAfter"); } }
mit
tools4j/unix4j
unix4j-core/unix4j-base/src/main/java/org/unix4j/util/sort/MonthStringComparator.java
2837
package org.unix4j.util.sort; import org.unix4j.util.StringUtil; import java.text.DateFormatSymbols; import java.util.Comparator; import java.util.Locale; /** * A comparator Months: (unknown) < 'JAN' < ... < 'DEC'. The current locale * determines the month spellings. */ public class MonthStringComparator implements Comparator<CharSequence> { /** * The instance for the default locale returned by {@link #getInstance()}. */ private static final MonthStringComparator DEFAULT_INSTANCE = new MonthStringComparator(); /** * Returns the instance for the default locale. * * @see Locale#getDefault() */ public static MonthStringComparator getInstance() { return DEFAULT_INSTANCE; } /** * Returns an instance for the specified locale. */ public static MonthStringComparator getInstance(Locale locale) { return new MonthStringComparator(locale); } private final String[] months; private final String[] shortMonths; /** * Private constructor used to create the {@link #DEFAULT_INSTANCE}. */ private MonthStringComparator() { this(DateFormatSymbols.getInstance()); } /** * Private constructor used by {@link #getInstance(Locale)}. */ private MonthStringComparator(Locale locale) { this(DateFormatSymbols.getInstance(locale)); } /** * Constructor with date symbols. * * @param symbols * the date symbols */ public MonthStringComparator(DateFormatSymbols symbols) { this.months = symbols.getMonths(); this.shortMonths = symbols.getShortMonths(); } @Override public int compare(CharSequence s1, CharSequence s2) { final int start1 = StringUtil.findStartTrimWhitespace(s1); final int end1 = StringUtil.findEndTrimWhitespace(s1); final int start2 = StringUtil.findStartTrimWhitespace(s2); final int end2 = StringUtil.findEndTrimWhitespace(s2); final int month1 = month(s1, start1, end1); final int month2 = month(s2, start2, end2); return Integer.compare(month1, month2); } private final int month(CharSequence s, int start, int end) { int m = month(months, s, start, end); return m >= 0 ? m : month(shortMonths, s, start, end); } private static int month(String[] months, CharSequence s, int start, int end) { for (int i = 0; i < months.length; i++) { final String month = months[i]; if (!equalsIgnoreCase(month, s, start, end)) { continue; } return i; } return -1; } private static final boolean equalsIgnoreCase(String s1, CharSequence s2, int start, int end) { if (end - start != s1.length()) { return false; } for (int i = start; i < end; i++) { if (!equalsIgnoreCase(s1.charAt(i - start), s2.charAt(i))) { return false; } } return true; } private static final boolean equalsIgnoreCase(char ch1, char ch2) { return Character.toUpperCase(ch1) == Character.toUpperCase(ch2); } }
mit
mtwilliams/mojo
dependencies/assimp-2.0.863/code/LWOBLoader.cpp
11204
/* --------------------------------------------------------------------------- Open Asset Import Library (ASSIMP) --------------------------------------------------------------------------- Copyright (c) 2006-2010, ASSIMP Development Team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the ASSIMP team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the ASSIMP Development Team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ /** @file Implementation of the LWO importer class for the older LWOB file formats, including materials */ #include "AssimpPCH.h" #ifndef ASSIMP_BUILD_NO_LWO_IMPORTER // Internal headers #include "LWOLoader.h" using namespace Assimp; // ------------------------------------------------------------------------------------------------ void LWOImporter::LoadLWOBFile() { LE_NCONST uint8_t* const end = mFileBuffer + fileSize; bool running = true; while (running) { if (mFileBuffer + sizeof(IFF::ChunkHeader) > end)break; LE_NCONST IFF::ChunkHeader* const head = IFF::LoadChunk(mFileBuffer); if (mFileBuffer + head->length > end) { throw DeadlyImportError("LWOB: Invalid chunk length"); break; } uint8_t* const next = mFileBuffer+head->length; switch (head->type) { // vertex list case AI_LWO_PNTS: { if (!mCurLayer->mTempPoints.empty()) DefaultLogger::get()->warn("LWO: PNTS chunk encountered twice"); else LoadLWOPoints(head->length); break; } // face list case AI_LWO_POLS: { if (!mCurLayer->mFaces.empty()) DefaultLogger::get()->warn("LWO: POLS chunk encountered twice"); else LoadLWOBPolygons(head->length); break; } // list of tags case AI_LWO_SRFS: { if (!mTags->empty()) DefaultLogger::get()->warn("LWO: SRFS chunk encountered twice"); else LoadLWOTags(head->length); break; } // surface chunk case AI_LWO_SURF: { LoadLWOBSurface(head->length); break; } } mFileBuffer = next; } } // ------------------------------------------------------------------------------------------------ void LWOImporter::LoadLWOBPolygons(unsigned int length) { // first find out how many faces and vertices we'll finally need LE_NCONST uint16_t* const end = (LE_NCONST uint16_t*)(mFileBuffer+length); LE_NCONST uint16_t* cursor = (LE_NCONST uint16_t*)mFileBuffer; // perform endianess conversions #ifndef AI_BUILD_BIG_ENDIAN while (cursor < end)ByteSwap::Swap2(cursor++); cursor = (LE_NCONST uint16_t*)mFileBuffer; #endif unsigned int iNumFaces = 0,iNumVertices = 0; CountVertsAndFacesLWOB(iNumVertices,iNumFaces,cursor,end); // allocate the output array and copy face indices if (iNumFaces) { cursor = (LE_NCONST uint16_t*)mFileBuffer; mCurLayer->mFaces.resize(iNumFaces); FaceList::iterator it = mCurLayer->mFaces.begin(); CopyFaceIndicesLWOB(it,cursor,end); } } // ------------------------------------------------------------------------------------------------ void LWOImporter::CountVertsAndFacesLWOB(unsigned int& verts, unsigned int& faces, LE_NCONST uint16_t*& cursor, const uint16_t* const end, unsigned int max) { while (cursor < end && max--) { uint16_t numIndices = *cursor++; verts += numIndices;faces++; cursor += numIndices; int16_t surface = *cursor++; if (surface < 0) { // there are detail polygons numIndices = *cursor++; CountVertsAndFacesLWOB(verts,faces,cursor,end,numIndices); } } } // ------------------------------------------------------------------------------------------------ void LWOImporter::CopyFaceIndicesLWOB(FaceList::iterator& it, LE_NCONST uint16_t*& cursor, const uint16_t* const end, unsigned int max) { while (cursor < end && max--) { LWO::Face& face = *it;++it; if((face.mNumIndices = *cursor++)) { if (cursor + face.mNumIndices >= end)break; face.mIndices = new unsigned int[face.mNumIndices]; for (unsigned int i = 0; i < face.mNumIndices;++i) { unsigned int & mi = face.mIndices[i] = *cursor++; if (mi > mCurLayer->mTempPoints.size()) { DefaultLogger::get()->warn("LWOB: face index is out of range"); mi = (unsigned int)mCurLayer->mTempPoints.size()-1; } } } else DefaultLogger::get()->warn("LWOB: Face has 0 indices"); int16_t surface = *cursor++; if (surface < 0) { surface = -surface; // there are detail polygons. const uint16_t numPolygons = *cursor++; if (cursor < end)CopyFaceIndicesLWOB(it,cursor,end,numPolygons); } face.surfaceIndex = surface-1; } } // ------------------------------------------------------------------------------------------------ LWO::Texture* LWOImporter::SetupNewTextureLWOB(LWO::TextureList& list,unsigned int size) { list.push_back(LWO::Texture()); LWO::Texture* tex = &list.back(); std::string type; GetS0(type,size); const char* s = type.c_str(); if(strstr(s, "Image Map")) { // Determine mapping type if(strstr(s, "Planar")) tex->mapMode = LWO::Texture::Planar; else if(strstr(s, "Cylindrical")) tex->mapMode = LWO::Texture::Cylindrical; else if(strstr(s, "Spherical")) tex->mapMode = LWO::Texture::Spherical; else if(strstr(s, "Cubic")) tex->mapMode = LWO::Texture::Cubic; else if(strstr(s, "Front")) tex->mapMode = LWO::Texture::FrontProjection; } else { // procedural or gradient, not supported DefaultLogger::get()->error("LWOB: Unsupported legacy texture: " + type); } return tex; } // ------------------------------------------------------------------------------------------------ void LWOImporter::LoadLWOBSurface(unsigned int size) { LE_NCONST uint8_t* const end = mFileBuffer + size; mSurfaces->push_back( LWO::Surface () ); LWO::Surface& surf = mSurfaces->back(); LWO::Texture* pTex = NULL; GetS0(surf.mName,size); bool runnning = true; while (runnning) { if (mFileBuffer + 6 >= end) break; IFF::SubChunkHeader* const head = IFF::LoadSubChunk(mFileBuffer); /* A single test file (sonycam.lwo) seems to have invalid surface chunks. * I'm assuming it's the fault of a single, unknown exporter so there are * probably THOUSANDS of them. Here's a dirty workaround: * * We don't break if the chunk limit is exceeded. Instead, we're computing * how much storage is actually left and work with this value from now on. */ if (mFileBuffer + head->length > end) { DefaultLogger::get()->error("LWOB: Invalid surface chunk length. Trying to continue."); head->length = (uint16_t) (end - mFileBuffer); } uint8_t* const next = mFileBuffer+head->length; switch (head->type) { // diffuse color case AI_LWO_COLR: { AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,COLR,3); surf.mColor.r = GetU1() / 255.0f; surf.mColor.g = GetU1() / 255.0f; surf.mColor.b = GetU1() / 255.0f; break; } // diffuse strength ... case AI_LWO_DIFF: { AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,DIFF,2); surf.mDiffuseValue = GetU2() / 255.0f; break; } // specular strength ... case AI_LWO_SPEC: { AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,SPEC,2); surf.mSpecularValue = GetU2() / 255.0f; break; } // luminosity ... case AI_LWO_LUMI: { AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,LUMI,2); surf.mLuminosity = GetU2() / 255.0f; break; } // transparency case AI_LWO_TRAN: { AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,TRAN,2); surf.mTransparency = GetU2() / 255.0f; break; } // surface flags case AI_LWO_FLAG: { AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,FLAG,2); uint16_t flag = GetU2(); if (flag & 0x4 ) surf.mMaximumSmoothAngle = 1.56207f; if (flag & 0x8 ) surf.mColorHighlights = 1.f; if (flag & 0x100) surf.bDoubleSided = true; break; } // maximum smoothing angle case AI_LWO_SMAN: { AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,SMAN,4); surf.mMaximumSmoothAngle = fabs( GetF4() ); break; } // glossiness case AI_LWO_GLOS: { AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,GLOS,2); surf.mGlossiness = (float)GetU2(); break; } // color texture case AI_LWO_CTEX: { pTex = SetupNewTextureLWOB(surf.mColorTextures, head->length); break; } // diffuse texture case AI_LWO_DTEX: { pTex = SetupNewTextureLWOB(surf.mDiffuseTextures, head->length); break; } // specular texture case AI_LWO_STEX: { pTex = SetupNewTextureLWOB(surf.mSpecularTextures, head->length); break; } // bump texture case AI_LWO_BTEX: { pTex = SetupNewTextureLWOB(surf.mBumpTextures, head->length); break; } // transparency texture case AI_LWO_TTEX: { pTex = SetupNewTextureLWOB(surf.mOpacityTextures, head->length); break; } // texture path case AI_LWO_TIMG: { if (pTex) { GetS0(pTex->mFileName,head->length); } else DefaultLogger::get()->warn("LWOB: Unexpected TIMG chunk"); break; } // texture strength case AI_LWO_TVAL: { AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,TVAL,1); if (pTex) { pTex->mStrength = (float)GetU1()/ 255.f; } else DefaultLogger::get()->warn("LWOB: Unexpected TVAL chunk"); break; } // texture flags case AI_LWO_TFLG: { AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,TFLG,2); if (pTex) { const uint16_t s = GetU2(); if (s & 1) pTex->majorAxis = LWO::Texture::AXIS_X; else if (s & 2) pTex->majorAxis = LWO::Texture::AXIS_Y; else if (s & 4) pTex->majorAxis = LWO::Texture::AXIS_Z; if (s & 16) DefaultLogger::get()->warn("LWOB: Ignoring \'negate\' flag on texture"); } else DefaultLogger::get()->warn("LWOB: Unexpected TFLG chunk"); break; } } mFileBuffer = next; } } #endif // !! ASSIMP_BUILD_NO_LWO_IMPORTER
mit
ThotAlion/Phoenix
WIFI-FPV/thrustmaster.py
1103
import pygame import zmq import time IP = '10.0.0.2' c = zmq.Context() s = c.socket(zmq.REQ) s.connect('tcp://'+IP+':8080') pygame.init() pygame.joystick.init() goon = True req = {} req["pad"] = {} while goon: t0 = time.clock() pygame.event.get() j = pygame.joystick.Joystick(0) j.init() req["pad"]["stickPitch"] = j.get_axis(1) req["pad"]["stickRoll"] = j.get_axis(0) req["pad"]["stickYaw"] = j.get_axis(3) req["pad"]["thrust"] = j.get_axis(2) req["pad"]["stickPal"] = j.get_axis(3) req["pad"]["stickTrim"] = j.get_hat(0) req["pad"]["Fire"] = j.get_button(0) req["pad"]["L1"] = j.get_button(1) req["pad"]["L3"] = j.get_button(3) req["pad"]["R3"] = j.get_button(2) req["pad"]["T5"] = j.get_button(4) req["pad"]["T6"] = j.get_button(5) req["pad"]["T7"] = j.get_button(6) req["pad"]["T8"] = j.get_button(7) req["pad"]["T9"] = j.get_button(8) req["pad"]["T10"] = j.get_button(9) req["pad"]["SE"] = j.get_button(10) req["pad"]["ST"] = j.get_button(11) s.send_json(req) a = s.recv_json() time.sleep(0.01)
mit
otoukebri/java-samples
java8-samples/src/main/java/tn/zelda/projects/java8/samples/LambdaScope.java
487
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tn.zelda.projects.java8.samples; /** * * @author o.TOUKEBRI */ public class LambdaScope { public static void main(String[] args) { final int num = 1; Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num); stringConverter.convert(2); } }
mit