text:
from models.keyword import Keyword
from models.document import Document
from models.collection import Collection
from bitmessage.bitmessage import Bitmessage
from models.fj_message import FJMessage
from models.signature import Signature
from cache.cache import Cache
from config import DOCUMENT_DIRECTORY_PATH, MAIN_CHANNEL_ADDRESS
from freenet.FreenetConnection import FreenetConnection
from jsonschema import *
from models.json_schemas import *
from sqlalchemy.exc import IntegrityError
from random import randint
from async import run_as_thread
import json
import time
import base64
import datetime
import hashlib
import sys
import os

class Controller:

    def __init__(self):
        self.connection = Bitmessage()
        self.cache = Cache()
        self.download_threads = set()

    def _check_signature(self, fj_message):
        """
        Checks that the signature is the correct sha256 hash of the address's public keys and payload
        :param fj_message: the message containing the collection and signature
        :return: True if the signatures match, False otherwise
        """
        h = hashlib.sha256(fj_message["pubkey"] + fj_message['payload']).hexdigest()

        if h == fj_message["signature"]:
            print "Signature Verified"
            return True
        else:
            print "Signature Not Verified"
            return False

    def _save_document(self, data, file_name, testing_mode=False):
        """
        Private helper function for writing file data to disk.
        Creates the file to the directory specified in config.py.

        :param data: the file data
        :param file_name: the name of the file
        :return: a boolean indicating success
        """

        try:
            if testing_mode:
                file_path = file_name
            else:
                file_path = os.path.expanduser(DOCUMENT_DIRECTORY_PATH) + file_name

            open(file_path, 'w').write(data)
            return True
        except Exception as e:
            return False

    def _get_document(self, hash):
        """
        Private helper function for getting document data
        from freenet.

        :param hash: the Content Hash Key for a document
        :return: the file data if successful, None otherwise
        """

        data = None

        #Try obtaining a freenet connection
        try:
            freenet_connection = FreenetConnection()
        except Exception as e:
            print("Couldn't connect to freenet")
            return data

        try:
            data = freenet_connection.get(hash)
        except Exception as e:
            pass

        return data

    def _hash_document_filenames(self, documents, collection):
        """
        Private helper function for hashing a collection of
        documents file names so that file name conflicts will be
        rare.

        :param documents: a list of document objects
        """

        for document in documents:
            #Create a new file name out of a hash to deal with possible naming conflicts
            file_name = document.filename
            if not document.filename:
                file_name = document.title + str(randint(0, 100))
            name, extension = os.path.splitext(file_name)
            hash_name = document.hash
            new_file_name = hash_name + extension
            #Save the new file name to the cache so it can be viewed later
            document.filename = new_file_name
            self.cache.insert_new_document_in_collection(document, collection)

    @run_as_thread
    def _download_documents(self, collection_title, documents):
        """
        A function that downloads documents from a collection in a new thread.

        :param collection_title: the title of the collection
        :param documents: the list of document objects to download
        """

        print("Downloading documents for " + collection_title)
        print("Number of Documents to download: " + str(len(documents)))

        doc_counter = 0
        for document in documents:
            # Store and validate that the document has a file name
            file_name = document.filename
            if not file_name:
                file_name = collection_title + str(doc_counter) + document.title
                doc_counter += 1
            # Try obtaining the file data from freenet
            data = self._get_document(document.hash)
            if not data:
                print("Couldn't download " + file_name + " from freenet")
                continue

            # If the file data was successfully downloaded, save the data to disk
            success = self._save_document(data, file_name)
            if success:
                print("Successfully downloaded " + file_name + " from freenet")
            else:
                print("Couldn't save document data to disk (check that the document"
                      + " directory path exists and appropriate permissions are set")

    def _build_docs_keywords(self, payload, collection):
        """
        Builds a list of Keyword objects and a list of Document objects from the received json.

        :param payload: The payload of the FJ Message including the documents and keywords
        :return: Two lists representing the documents and keywords of the FJ Message
        """
        for key in payload["keywords"]:
            db_key = self.cache.get_keyword_by_id(key["id"])
            if db_key is not None:
                collection.keywords.append(db_key)
            else:
                collection.keywords.append(Keyword(name=key["name"]))

        for doc in payload["documents"]:
            db_doc = self.cache.get_document_by_hash(doc["hash"])
            if db_doc is not None:
                collection.documents.append(db_doc)
            else:
                collection.documents.append(Document(collection_address=doc["address"], description=doc["description"],
                                     hash=doc["hash"], title=doc["title"], filename=doc["filename"], accesses=doc["accesses"]))

    def _cache_collection(self, payload, message):
        """
        Checks to see if this collection is already in the cache. If it is we update the collection with the new data.
        Otherwise a new collection is made and cached.
        :param message: the Bitmessage message containing an FJ_message
        :param payload: the contents of the FJ_message
        """
        # Grabbing the text representations of the documents and keywords and rebuilding them
        #docs, keywords = self._build_docs_keywords(payload)
        cached_collection = self.cache.get_collection_with_address(payload["address"])

        if cached_collection is None:
            collection_model = Collection(
                title=payload["title"],
                description=payload["description"],
                address=payload["address"],
                btc=payload["btc"],
                creation_date=datetime.datetime.strptime(payload["creation_date"], "%A, %d. %B %Y %I:%M%p"),
                oldest_date=datetime.datetime.strptime(payload["oldest_date"], "%A, %d. %B %Y %I:%M%p"),
                latest_broadcast_date=datetime.datetime.strptime(payload["latest_broadcast_date"], "%A, %d. %B %Y %I:%M%p"),
                votes=payload['votes'],
                votes_last_checked=datetime.datetime.strptime(payload["votes_last_checked"], "%A, %d. %B %Y %I:%M%p"),
            )

            self._build_docs_keywords(payload, collection_model)
            signature = Signature(pubkey=message["pubkey"], signature=message["signature"], address=payload["address"])
            try:
                self.cache.insert_new_collection(collection_model)
                self.cache.insert_new_collection(signature)
                self._hash_document_filenames(collection_model.documents, collection_model)
                self.download_threads.add(self._download_documents(collection_model.title, collection_model.documents))
                print "Cached New Collection"
                return True
            except IntegrityError as m:
                print m.message
                return False
        else:
            cached_collection.keywords = []
            cached_sig = self.cache.get_signature_by_address(payload["address"])
            cached_sig.pubkey = message["pubkey"]
            cached_sig.signature = message["signature"]
            cached_collection.title = payload["title"]
            cached_collection.description = payload["description"]
            cached_collection.address = payload["address"]
            cached_collection.btc = payload["btc"]
            cached_collection.documents = []
            cached_collection.creation_date = datetime.datetime.strptime(payload["creation_date"],
                                                                         "%A, %d. %B %Y %I:%M%p")
            cached_collection.oldest_date = datetime.datetime.strptime(payload["oldest_date"], "%A, %d. %B %Y %I:%M%p")
            cached_collection.latest_broadcast_date = datetime.datetime.strptime(payload["latest_broadcast_date"],
                                                                                "%A, %d. %B %Y %I:%M%p")
            cached_collection.votes = payload['votes']
            cached_collection.votes_last_checked = datetime.datetime.strptime(payload["votes_last_checked"], "%A, %d. %B %Y %I:%M%p")
            self._build_docs_keywords(payload, cached_collection)
            try:
                self.cache.insert_new_collection(cached_collection)
                self.cache.insert_new_collection(cached_sig)
                self._hash_document_filenames(cached_collection.documents, cached_collection)
                self.download_threads.add(self._download_documents(cached_collection.title, cached_collection.documents))
                print "Cached Updated Collection"
                return True
            except IntegrityError as m:
                print m.message
                return False

    def _find_address_in_keysdat(self, address):
        """
        Checks if this bitmessage address is in our keys.dat
        :param address: The address to look for
        :return: True if the address is in keys.dat, false otherwise
        """
        f = open(os.path.expanduser('~/.config/PyBitmessage/keys.dat'), 'r')
        keys = f.read()
        keys_list = keys.split('\n\n')

        for key_info in keys_list[1:]:
            if address in key_info:
                return True
        return False

    def import_collection(self, address):
        """
        Imports a Collection from the given Bit Message address and checks if its signature is valid.
        If it is valid then it is cached locally.
        :param address: the address to import the collection from
        :return: True if the collection was imported and cached successfully, False otherwise
        """

        # buffer time to make sure to get messages
        messages = self.connection.check_inbox()
        for message in messages["inboxMessages"]:
            if message["toAddress"] == address:
                # decoded_message is a FJMessage
                base64_decode = base64.b64decode(message["message"])
                try:
                    json_decode = json.loads(base64_decode)
                    validate(json_decode, fj_schema)
                except (ValueError, TypeError, ValidationError) as m:
                    #print m.message
                    print "Not a FJ Message or Invalid FJ Message"
                    self.connection.delete_message(message['msgid'])
                    continue

                # Trying to filter out non collection messages
                # TODO Change this?
                if "payload" in json_decode:
                    payload = json_decode["payload"]
                    try:
                        payload = json.loads(payload)
                        validate(payload, coll_schema)
                    except (ValueError, TypeError, ValidationError) as m:
                        print "Contents of FJ Message invalid or corrupted"
                        self.connection.delete_message(message['msgid'])
                        continue

                    if self._check_signature(json_decode):
                        if self._cache_collection(payload, json_decode):
                            self.connection.delete_message(message['msgid'])
                            return True

        #print "Could not import collection"
        return False

    def publish_collection(self, collection, to_address, from_address=None):
        """
        Publishes the given to collection to the bitmessage network
        :param collection: the collection to be published
        :param to_address: the address to send the collection to,  always MAIN_CHANNEL_ADDRESS except in unittests
        :param from_address: the address to send the collection from
        :return: True if the collection is published successfully, False otherwise
        """

        if from_address is None:
            from_address = self.connection.create_address("new address", True)
            print "created address: ", from_address
        if not self._find_address_in_keysdat(from_address):
            print "This address is not in keys.dat, can not send message"
            return False

        collection_payload = collection.to_json()
        if collection_payload is None:
            return False
        new_fj_message = FJMessage(1, collection.address, collection_payload)
        sendable_fj_message = new_fj_message.to_json()
        if sendable_fj_message is None:
            return False
        self.connection.send_message(to_address, from_address, "subject", sendable_fj_message)
        return True

    def rebroadcast(self, collection, to_address=MAIN_CHANNEL_ADDRESS, from_address=MAIN_CHANNEL_ADDRESS):
        """
        Rebroadcasts a collection that is stored locally to the bitmessage network
        :param collection: The collection to rebroadcast
        :param to_address: the address to send the collection to, only used for testing
        :param from_address: the address to send the collection from, only used for testing
        :return: True if the collection is sent successfully, false otherwise
        """
        collection_payload = collection.to_json()
        if collection_payload is None:
            return False
        cached_signature = self.cache.get_signature_by_address(collection.address)
        h = hashlib.sha256(cached_signature.pubkey + collection_payload).hexdigest()

        if h == cached_signature.signature:
            new_fj_message = FJMessage(3, collection.address, collection_payload)
            sendable_fj_message = new_fj_message.to_json(cached_signature.signature)
            if sendable_fj_message is None:
                return False
            self.connection.send_message(to_address, from_address, "subject", sendable_fj_message)
            return True
        else:
            print "Signature Not Verified"
            return False

    def alive_downloads(self):
        """
        Checks if there are any downloads in progress
        :return: True if there is a running download
        """
        self.download_threads = {t for t in self.download_threads if t.is_alive()}
        return len(self.download_threads) > 0

    def join_downloads(self):
        """
        Joins all of the in-progress download threads
        """
        for dl_thread in self.download_threads:
            dl_thread.join()
        self.download_threads = set()

redpajama_set_name: RedPajamaGithub


text:
<form class="form-horizontal" role="form" action="Setting_submit/group_setting" method="post" id="group_form">

			Group Name

			<input type="text" name="group" class="form-control"  onkeypress="return only_chareter(this.value)" placeholder="Enter Group Name" required/>

			<button type="submit" name="submit" id="group_submit" class="btn btn-primary" data-toggle="tooltip" title="Save"> Save</button>

</form>

	<?php if($t_srow!=0){ ?>

						Group List

						Sl.No
						Group Name
						Action

					<?php $sfid=1;
					foreach($all_group as $value){
					$test=$this->bsetting->group_delete_test($value->groupid);
					if($test>0) { $disable="disabled"; } else { echo $disable=""; }
					?>

						<?php echo $sfid++; ?>
						<?php echo $value->group_name ?>
						<a href="basic_setting/group_edit?id=<?php echo $value->groupid; ?>"><button type="button" class="btn btn-primary" data-toggle="tooltip" title="Edit" ></button>

						<a onclick="return delete_confirm();" href="setting_submit/group_delete?id=<?php echo $value->groupid; ?>"><button  type="button" class="btn btn-danger" <?php echo $disable; ?> data-toggle="tooltip" title="Delete" ></button>

					<?php } ?>

	<?php } ?>


text:
package de.hshannover.operation_muehle.utils;

import de.hshannover.operation_muehle.logic.Logger;

public abstract class TimeObserver {
	private boolean hasFinishedInTime;
	private Thread thread;

	public TimeObserver(int thinkTime) {
		thread = new Thread() {
			public void run() {
				doRun();
			}
		};
		thread.start();

		waitForThread(thinkTime);
		this.hasFinishedInTime = !thread.isAlive();
	}

	private void waitForThread(long thinkTime) {
		long startSysTime = System.currentTimeMillis();
		try {
			synchronized (thread) {
				thread.join(thinkTime);
			}
		} catch (InterruptedException e) {
			long elapsedTime = System.currentTimeMillis() - startSysTime;
			Logger.logDebugf("waited %d", elapsedTime);
			if ( elapsedTime < thinkTime) {
				waitForThread(thinkTime - elapsedTime);
			}
		}

	}

	private void doRun() {
		run();
		synchronized (thread) {
			thread.notifyAll();
		}
	}

	public boolean hasFinishedInTime() {
		return this.hasFinishedInTime;
	}

	public abstract void run();
}


text:
a collection of useful tools, ideas, and occasional tangents.

Create a new post in `_posts`.

To serve locally:
1. `jekyll build` to detect new posts
2. `jekyll serve --baseurl '' --watch --incremental`

To serve a draft:
`jekyll serve --drafts --baseurl '' --watch --incremental`


text:
using Orchard.MediaProcessing.Descriptors.Filter;

namespace Orchard.MediaProcessing.ViewModels {
    public class FilterEditViewModel {
        public int Id { get; set; }
        public string Description { get; set; }
        public FilterDescriptor Filter { get; set; }
        public dynamic Form { get; set; }
    }
}


text:
require 'spec_helper'
require 'lazy_files/dirs/dir'
require 'lazy_files/utils/utils'

describe Lazy do
  init()
  it { should respond_to :pwd }
  it { should respond_to :wd}
  describe "#wd" do
    subject(:wd) { Lazy.wd }
    it { should be_an_instance_of Lazy::Dir }
    it "should be the current directory" do
      wd.path.should == Dir.pwd
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="<?php echo base_url('bootstrap/css/bootstrap.min.css'); ?>">
    <link rel="stylesheet" href="<?php echo base_url('assets/css/login.css'); ?>">

		<a href="<?php echo base_url('home');?>"><img src="<?php echo base_url('assets/img/Temp.png')?>" id="logo1" class="logo"/>

ORGANIZE STAFF

Organize your staff with ease by adding staff menu and just input the details in your desired way.

TIME MANAGEMENT

Manage your time with ease by using Tempus. List your important appointments, meetings in our calendar, and can also check your availability.

					<?php echo validation_errors(); ?>
						<form action="<?php echo base_url('login')?>" method='post'>
						Username:
						<input class="form-control" type="email" required="" placeholder="Email address" autofocus="" id="inputEmail" name="email">
						Password:
						<input class="form-control" type="password" required="" placeholder="Password" id="inputPassword" name="password">
						<button id="login1" class="btn btn-default" type="submit">Login</button>
						</form>

Don't have an account? <a href="<?php echo base_url('registration');?>" >Signup now!


text:
using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Majstic.Models
{
    public class ExternalLoginConfirmationViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }
    }

    public class ManageUserViewModel
    {
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Current password")]
        public string OldPassword { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "New password")]
        public string NewPassword { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm new password")]
        [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

    public class LoginViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }

    public class RegisterViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required]
        [Display(Name = "Full Name")]
        public string Name { get; set; }

        [Required]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [Display(Name = "Phone Number")]
        public int PhoneNumber { get; set; }

        // Return a pre-poulated instance of AppliationUser:
        public ApplicationUser GetUser()
        {
            var user = new ApplicationUser()
            {
                UserName = this.UserName,
                Email = this.Email,
                PhoneNumber = this.PhoneNumber,
                Name = this.Name,
            };
            return user;
        }

    }

    public class EditUserViewModel
    {
        public EditUserViewModel() { }

        // Allow Initialization with an instance of ApplicationUser:
        public EditUserViewModel(ApplicationUser user)
        {
            this.UserName = user.UserName;
            this.Name = user.Name;
            this.PhoneNumber = user.PhoneNumber;
            this.Email = user.Email;
        }

        [Required]
        [Display(Name = "User Name")]
        public string UserName { get; set; }

        [Required]
        [Display(Name = "First Name")]
        public string Name { get; set; }

        [Required]
        [Display(Name = "Last Name")]
        public string Email { get; set; }

        [Required]
        public int PhoneNumber { get; set; }
    }

    // Used to display a single role with a checkbox, within a list structure:
    public class SelectRoleEditorViewModel
    {
        public SelectRoleEditorViewModel() { }
        public SelectRoleEditorViewModel(IdentityRole role)
        {
            this.RoleName = role.Name;
        }

        public bool Selected { get; set; }

        [Required]
        public string RoleName { get; set; }
    }

    public class SelectUserRolesViewModel
    {
        public SelectUserRolesViewModel()
        {
            this.Roles = new List<SelectRoleEditorViewModel>();
        }

        // Enable initialization with an instance of ApplicationUser:
        public SelectUserRolesViewModel(ApplicationUser user)
            : this()
        {
            this.UserName = user.UserName;
            this.Name = user.Name;
            this.PhoneNumber = user.PhoneNumber;
            this.Email = user.Email;

            var Db = new ApplicationDbContext();

            // Add all available roles to the list of EditorViewModels:
            var allRoles = Db.Roles;
            foreach (var role in allRoles)
            {
                // An EditorViewModel will be used by Editor Template:
                var rvm = new SelectRoleEditorViewModel(role);
                this.Roles.Add(rvm);
            }

            // Set the Selected property to true for those roles for
            // which the current user is a member:
            foreach (var userRole in user.Roles)
            {
                var checkUserRole =
                    this.Roles.Find(r => r.RoleName == userRole.Role.Name);
                checkUserRole.Selected = true;
            }
        }
        public string UserName { get; set; }
        public string Name { get; set; }
        public int PhoneNumber { get; set; }
        public string Email { get; set; }
        public List<SelectRoleEditorViewModel> Roles { get; set; }
    }

}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of SolidInvoice project.
 *
 * (c) Pierre du Plessis <open-source@solidworx.co>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace SolidInvoice\CoreBundle\Test\Traits;

use SolidInvoice\Kernel;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\KernelInterface;

/**
 * @codeCoverageIgnore
 */
trait SymfonyKernelTrait
{
    /**
     * @var KernelInterface
     */
    protected $kernel;

    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @before
     */
    protected function setUpSymfonyKernel(): void
    {
        if (null === $this->kernel) {
            $this->kernel = $this->createKernel();
            $this->kernel->boot();
            $this->container = $this->kernel->getContainer();
        }
    }

    protected function createKernel(): KernelInterface
    {
        $class = $this->getKernelClass();
        $options = $this->getKernelOptions();

        return new $class(
            $options['environment'] ?? 'test',
            $options['debug'] ?? true
        );
    }

    protected function getKernelClass(): string
    {
        return Kernel::class;
    }

    protected function getKernelOptions(): array
    {
        return ['environment' => 'test', 'debug' => true];
    }

    /**
     * @after
     */
    protected function tearDownSymfonyKernel(): void
    {
        if (null !== $this->kernel) {
            $this->kernel->shutdown();
        }
    }
}


text:
<?php

namespace Tests\Homie\IFTTT;

use Homie\IFTTT\Event\TriggerEvent;
use Homie\IFTTT\Trigger;
use Homie\IFTTT\Listener;
use PHPUnit\Framework\TestCase;
use PHPUnit_Framework_MockObject_MockObject as MockObject;

class ListenerTest extends TestCase
{

    /**
     * @var Listener
     */
    private $subject;

    /**
     * @var Trigger|MockObject
     */
    private $action;

    public function setUp()
    {
        $this->action  = $this->createMock(Trigger::class);
        $this->subject = new Listener($this->action);
    }

    public function testHandleEvent()
    {
        $eventName = 'my-test';
        $event = new TriggerEvent($eventName);

        $this->action
            ->expects($this->once())
            ->method('trigger')
            ->with($eventName);

        $this->subject->callTrigger($event);
    }
}


text:
package com.swip.rest.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.swip.api.lang.workspace.Workspace;
import com.swip.api.repository.Repository;
import com.swip.core.workspace.TemplateConfigurableWorkspace;

@RestController
@RequestMapping("/workspace")
public class WorkspaceService extends ElementService<TemplateConfigurableWorkspace> {

	@Autowired
	private Repository<TemplateConfigurableWorkspace> repository;

	@RequestMapping(value = "/new/{category}/{label}", method = RequestMethod.PUT)
	public Workspace create(@PathVariable final String category, @PathVariable final String label) {

		final TemplateConfigurableWorkspace workspace = new TemplateConfigurableWorkspace(category, label);

		this.getRepository().store(workspace);

		return workspace;
	}

	@Override
	protected Class<TemplateConfigurableWorkspace> getElementClass() {

		return TemplateConfigurableWorkspace.class;
	}

	@Override
	protected Repository<TemplateConfigurableWorkspace> getRepository() {

		return this.repository;
	}

}


text:
/**
 * WPGlobus for YoastSeo 4.1.0
 * Interface JS functions
 *
 * @since 1.7.7
 *
 * @package WPGlobus
 */
/*jslint browser: true*/
/*global jQuery, console, wpseoReplaceVarsL10n, YoastSEO, WPGlobusVendor, WPGlobusCore, WPGlobusCoreData*/

var WPGlobusYoastSeo;
/**
 * @see wpglobus-yoastseo-premium-{{version}}.js
 */
var WPGlobusYoastSeoPremium = false;
jQuery(document).ready( function ($) {
	'use strict';

	if ( typeof wpseoReplaceVarsL10n === 'undefined' ) {
		return;
	}

	if ( typeof WPGlobusCoreData === 'undefined' ) {
		return;
	}

	if ( typeof WPGlobusVendor === 'undefined' ) {
		return;
	}

	var api;

	if ( 'edit-tags.php' == WPGlobusVendor.pagenow || 'term.php' == WPGlobusVendor.pagenow ) {

		api = WPGlobusYoastSeo = {
			editorIDs: [ 'description' ],
			editor: {},
			submitId: '#submit',
			preventChangeEditor: false,
			observer: null,
			init: function() {

				api.attachListeners();
				_.delay( api.start, 1500 );

			},
			submit: function( event ) {

				if ( 'mouseenter' === event.type ) {

					$.each( api.editor, function( id, d ) {

						if ( ! api.editor[ id ][ 'contentEditor' ] || api.editor[ id ][ 'contentEditor' ].isHidden() ) {

							$( '#'+id ).val( api.editor[ id ].content );

						} else {

							tinymce.get( id ).setContent( api.editor[ id ].content	);
						}

					} );

				} else if ( 'mouseleave' === event.type ) {

					if ( ! api.preventChangeEditor ) {
						/** restore data for current language when submit button wasn't clicked */
						$.each( api.editor, function( id, d ) {

							if ( ! api.editor[ id ].contentEditor || api.editor[ id ].contentEditor.isHidden() ) {

								$( '#'+id ).val(
									WPGlobusCore.TextFilter( d.content, api.getCurrentTab(), 'RETURN_EMPTY' )
								);

							} else {

								tinymce.get( id ).setContent(
									WPGlobusCore.TextFilter( d.content, api.getCurrentTab(), 'RETURN_EMPTY' )
								);

							}

						} );
						api.preventChangeEditor = false;
					}

				} else if ( 'click' === event.type ) {

					api.preventChangeEditor = true;
					if ( 'tinymce' != getUserSetting( 'editor' ) ) {
						setUserSetting( 'editor', 'tinymce' );
					}

				}

			},
			attachListeners: function() {

				/**
				 * Switch language.
				 */
				$( '.wrap' ).on( 'tabsactivate', function( event, ui ) {

					$.each( api.editor, function( ID, ed ) {

						if ( ! api.editor[ ID ][ 'contentEditor' ] || api.editor[ ID ][ 'contentEditor' ].isHidden() ) {

							$( '#'+ID ).val( WPGlobusCore.TextFilter( ed.content, ui.newTab[0].dataset.language, 'RETURN_EMPTY' ) );

						} else {

							tinymce.get( ID ).setContent(
								WPGlobusCore.TextFilter(
									ed.content,
									ui.newTab[0].dataset.language,
									'RETURN_EMPTY'
								)
							);

						}

					} );

				} );

				/**
				 * Submit action.
				 */
				$(document).on( 'mouseenter', api.submitId, api.submit )
					.on( 'mouseleave', api.submitId, api.submit )
					.on( 'click', api.submitId, api.submit );

				/**
				 * Yoast tinymce editors init.
S				 */
				$(document).on( 'tinymce-editor-init', function( event, editor ) {

					if ( _.indexOf( api.editorIDs, editor.id ) != -1 ) {

						var $ed = $( '#' + editor.id );

						api.editor[ editor.id ] = {};
						api.editor[ editor.id ][ 'contentEditor' ] = editor;
						api.editor[ editor.id ][ 'content' ] = $ed.val();

						editor.setContent(
							WPGlobusCore.TextFilter(
								api.editor[ editor.id ][ 'content' ],
								WPGlobusCoreData.default_language,
								'RETURN_EMPTY'
							)
						);

						$( '#' + editor.getContainer().id ).find( 'iframe' ).addClass( 'wpglobus-translatable' );
						$ed.removeClass( 'hidden' );

						/** tinymce */
						editor.on( 'nodechange keyup', _.debounce( api.update, 500 ) );

						/** textarea */
						$ed.on( 'input keyup', _.debounce( api.update, 500 ) );
					}

				} );

			},
			update: function( event ) {

				var id, text;

				if ( typeof event.target !== 'undefined' ) {
					id = event.target.id;
				} else {
					return;
				}

				if ( id == 'tinymce' ) {
					id = event.target.dataset.id;
				}

				if ( typeof api.editor[ id ][ 'contentEditor' ] === 'undefined' ) {
					return;
				}

				if ( ! api.editor[ id ][ 'contentEditor' ] || api.editor[ id ][ 'contentEditor' ].isHidden() ) {
					text = $( '#' + id ).val();
				} else {
					text = api.editor[ id ][ 'contentEditor' ].getContent( { format: 'raw' } );
				}

				api.editor[ id ][ 'content' ] = WPGlobusCore.getString( api.editor[ id ][ 'content' ], text, api.getCurrentTab() );

			},
			getCurrentTab: function() {
				return $( '.wpglobus-taxonomy-tabs-list .ui-tabs-active' ).data( 'language' );
			},
			start: function() {

				/** hide all wpglobus description field */
				$( '.wpglobus-element_description' ).css({ 'display':'none' });

			}

		}

		WPGlobusYoastSeo.init();

		var WPGlobusYoastSeoPlugin = function() {

			/**
			 * Switch language.
			 */
			$( '.wrap' ).on( 'tabsactivate', function( event, ui ) {

				if ( ui.newTab[0].dataset.language == WPGlobusCoreData.default_language ) {
					$( '#poststuff .inside' ).css({ 'display':'block' });
				} else {
					$( '#poststuff .inside' ).css({ 'display':'none' });
				}

			} );

			/**
			 * Translate strings.
			 */
			$.each(
				[
					'category_description',
					'sitedesc',
					'sitename',
					'tag_description',
					'term_description',
					'term_title'
				],
				function( i, e ) {
					wpseoReplaceVarsL10n.replace_vars[ e ] = WPGlobusCore.TextFilter(
						wpseoReplaceVarsL10n.replace_vars[ e ],
						WPGlobusCoreData.default_language
					);
				}
			);

			/**
			 * Mutation observer.
			 */
			WPGlobusYoastSeo.observer = new MutationObserver( function( mutations ) {
				mutations.forEach( function( mutation ) {
					if ( 'placeholder' == mutation.attributeName ) {
						WPGlobusYoastSeo.observer.disconnect();
						/**
						 * Update focus keyword.
						 */
						var kw = $( '#wpseo_focuskw' );
						if ( '' == kw.val() ) {
							kw.attr(
								'placeholder',
								WPGlobusCore.TextFilter(
									kw.attr( 'placeholder' ),
									WPGlobusCoreData.default_language
								)
							);
						}
						WPGlobusYoastSeo.observer.observe(
							document.querySelector('#wpseo_focuskw'),
							{ attributes: true, childList: true, characterData: true }
						);

					}
				} );
			} );

			WPGlobusYoastSeo.observer.observe(
				document.querySelector('#wpseo_focuskw'),
				{ attributes: true, childList: true, characterData: true }
			);

		}

		window.WPGlobusYoastSeoPlugin = new WPGlobusYoastSeoPlugin();

	} else {
		/**
		 * pagenow is in [ 'post.php', 'post-new.php' ]
		 */
		/**
		 * WPGlobusYoastSeo.
		 */
		api = WPGlobusYoastSeo = {
			wpseoTabSelector: '#wpglobus-wpseo-tabs',
			url		  :   '',
			attrs	  : 	$('#wpglobus-wpseo-attr'),
			iB		  : 	$('#wpseo-meta-section-content'), // insert before element
			t	      :	$('#wpseo-meta-section-content'), // source
			ids		  : 	'',
			names	  :   '',
			wpseoTab  :   WPGlobusCoreData.default_language,
			editSnippetButtonClass 	: 'wpglobus-snippet-editor__edit-button',
			editSnippetFormClass 	: 'wpglobus-snippet-editor__form',
			editSnippetSubmitClass 	: 'wpglobus-snippet-editor__submit',
			editSnippetHeadingClass : 'wpglobus-snippet-editor__heading-editor',
			yoastTitleProgress		: 'wpglobus-yoast-title-progress',
			yoastMetadescProgress	: 'wpglobus-yoast-metadesc-progress',
			/**
			 * @since 1.7.2
			 */
			yoastPremium			: WPGlobusVendor.vendor.WPSEO_PREMIUM,
			/**
			 * Index of current keywords for each language.
			 * @since 1.7.2
			 */
			keywordIndex			: {},
			init: function() {
				/**
				 * @see wpglobus-admin.js for init point.
				 */
				$.each( WPGlobusCoreData.enabled_languages, function(i,lang){
					api.keywordIndex[lang] = 0;
				});
				api.start();
			},
			initAddKeywordPopup: function() {
				/** @see wp-seo-metabox-302.js */
				/**
				 * Adds keyword popup if the template for it is found.
				 * If add keyword popup exists then bind it to the add keyword button.
				 */
				if ( 1 == $( '#wpseo-add-keyword-popup' ).length ) {
					$( '.wpseo-add-keyword' ).on( 'click', api.addKeywordPopup );
				} else {
					if ( WPGlobusYoastSeoPremium ) {
						WPGlobusYoastSeoPremium.addKeywordButton();
					}
				}
			},
			addKeywordPopup: function() {
				/**
				 * Shows an informational popup if someone click the add keyword button.
				 * @see wp-seo-metabox-302.js
				 */
				var title = $( '#wpseo-add-keyword-popup-button' ).text();
				tb_show( title, '#TB_inline?width=650&height=350&inlineId=wpseo-add-keyword-popup', 'group' );

				/**
				 * The container window isn't the correct size, rectify this.
				 */
				$( '#TB_window' ).css( 'height', 235 );
				$( '#TB_window' ).css( 'width', 680 );
			},
			qtip: function() {
				/** @see jQuery( '.yoast_help' ).qtip() */
				/** obsolete since yoastseo 3.2 */
				$( '.yoast_help' ).qtip(
					{
						content: {
							attr: 'alt'
						},
						position: {
							my: 'bottom left',
							at: 'top center'
						},
						style   : {
							tip: {
								corner: true
							},
							classes : 'yoast-qtip qtip-rounded qtip-blue'
						},
						show    : 'click',
						hide    : {
							fixed: true,
							delay: 500
						}
					}
				);
			},
			removeClasses: function( element, classes ) {
				_.each( classes, function( cl ){
					element.removeClass( cl );
				} );
			},
			updateProgressBar: function( element, lang ) {

				if ( typeof element === 'undefined' ) {
					return;
				}
				if ( typeof lang === 'undefined' ) {

					if ( element.data( 'language' ) !== 'undefined' ) {
						lang = element.data( 'language' );
					}

					if ( typeof lang === 'undefined' ) {
						return;
					}
				}

				var allClasses = [
					"snippet-editor__progress--bad",
					"snippet-editor__progress--ok",
					"snippet-editor__progress--good"
				];
				var text, progress, score = 0, cl = '', max = 0, warningText = false;

				text = element.val();
				score = text.length;

				if ( element.hasClass( 'wpglobus-snippet-editor-title' ) ) {
					/**
					 * "snippet-editor__progress--ok" - score 0-34
					 * "snippet-editor__progress--good" - score 35-65
					 * "snippet-editor__progress--ok" score >=66, red text
					 */
					progress = $( 'progress.' + api.yoastTitleProgress + '_' + lang );
					max = progress.attr( 'max' );
					cl = allClasses[2];
					if ( score == 0 ) {
						cl = allClasses[1];
					} else if ( score > max ) {
						cl = allClasses[1];
						warningText = true;
					} else if ( score > 0 && score < 35 ) {
						cl = allClasses[1];
					}

				} else if ( element.hasClass( 'wpglobus-snippet-editor-meta-description' ) ) {
					/**
					 * "snippet-editor__progress--ok" - score 0-120
					 * "snippet-editor__progress--good" - score 121-156
					 * "snippet-editor__progress--ok" score >=157, red text
					 */
					progress = $( 'progress.' + api.yoastMetadescProgress + '_' + lang );
					max = progress.attr( 'max' );
					cl = allClasses[2];
					if ( score == 0 ) {
						cl = allClasses[1];
					} else if ( score > max ) {
						cl = allClasses[1];
						warningText = true;
					} else if ( score > 0 && score < 121 ) {
						cl = allClasses[1];
					}
				}
				api.removeClasses( progress, allClasses );
				progress.attr( 'value', score ).addClass( cl );
				if ( warningText ) {
					element.css( 'color', '#f00' );
				} else {
					element.css( 'color', '#000' );
				}

			},
			updateWpseoKeyword: function( kw, l ) {
				/**
				 * Update focus keyword during init time.
				 */
				$( '#wpseo-meta-section-content_' + l + ' .wpseo-keyword'  ).text( kw );
			},
			start: function() {
				/**
				 * Tabs on.
				 */
				$( api.wpseoTabSelector ).tabs();

				api.ids 	= api.attrs.data('ids');
				api.names 	= api.attrs.data('names');

				api.ids 	= api.ids + ',' + api.attrs.data('qtip');
				api.ids 	= api.ids.split(',');
				api.names 	= api.names.split(',');

				$('#wpglobus-wpseo-tabs').insertBefore( api.iB );
				$('.wpseo-metabox-tabs').css({'height':'26px'});

				$('.wpglobus-wpseo-general').each(function(i,e){
					var $e = $(e);
					var l  = $e.data('language');
					var sectionID = 'wpseo-meta-section-content_'+l;

					$e.html('
' + api.t.html() + '
');
					$('#'+sectionID+' .wpseo-metabox-tabs').attr( 'id', 'wpseo-metabox-tabs_'+l ).attr( 'data-language', l );
					$('#'+sectionID+' .wpseotab').attr( 'id', 'wpseo_content_'+l );
					/** added since yoastseo 3.2 */
					$('#wpseo_content_'+l).css({'float':'left'});
					$('#'+sectionID).css({'display':'block'});
					$('#wpseo_meta').css({'overflow':'hidden'});

					$('#'+sectionID+' .snippet_container').addClass('wpglobus-snippet_container');

					if ( l !== WPGlobusCoreData.default_language ) {
						/**
						 * Hide plus sign.
						 */
						$('#'+sectionID+' .wpseo-add-keyword').addClass('hidden');
					}

					$.each( api.names, function(i,name) {
						$( '#'+name ).attr( 'name', name+'_'+l );
					});

					$.each( api.ids, function(i,id) {
						var $id = $('#'+id);
						if ( 'wpseosnippet' == id ) {
							$id.addClass('wpglobus-wpseosnippet');
						}
						if ( 'snippet_title' == id ) {
							$id.addClass('wpglobus-snippet_title');
						}
						if ( 'snippet_meta' == id ) {
							$id.addClass('wpglobus-snippet_meta');
						}
						/** url */
						if ( 'snippet_cite' == id ) {
							$id.addClass('wpglobus-snippet_cite');
						}
						if ( 'snippet_citeBase' == id ) {
							$id.addClass('wpglobus-snippet_citeBase');
						}
						/** @since 1.5.6 */
						if ( 'url_container' == id ) {
							$id.css( { 'height':'16px'} );
						}
						/** focuskw */
						if ( 'yoast_wpseo_focuskw_text_input' == id ) {
							$id.addClass('wpglobus-yoast_wpseo_focuskw_text_input');
							/**
							 * Add attribute to store first keyword.
							 * @since 1.7.2
							 */
							$id.attr('data-value', '');
							$id.parents( 'div#wpseofocuskeyword' ).attr( 'id', 'wpseofocuskeyword_' + l );
							/**
							 * @todo check for '#wpseo-focuskeyword-section', '#help-yoast-focuskeyword', label for="yoast_wpseo_focuskw_text_input".
							 */
						}
						/** @since 1.7.2 */
						if ( 'yoast_wpseo_focuskeywords' == id ) {
							$id.addClass('wpglobus-yoast_wpseo_focuskeywords');
						}
						/** wpseo-pageanalysis */
						if ( 'wpseo-pageanalysis' == id ) {
							$id.addClass( 'wpglobus-wpseo-pageanalysis' );
						}
						/**
						 * yoast-seo-content-analysis
						 * @since 1.5.8
						 */
						if ( 'yoast-seo-content-analysis' == id ) {
							$id.addClass( 'wpglobus-yoast-seo-content-analysis' );
						}
						/** #snippet_preview */
						if ( 'snippet_preview' == id ) {
							$id.addClass('wpglobus-snippet_preview');
						}
						/** #snippet-editor-title */
						if ( 'snippet-editor-title' == id ) {
							$id.addClass( 'wpglobus-snippet-editor-title' );
							$id.parent( 'label' ).attr( 'for', $id.parent( 'label' ).attr( 'for' ) + '_' + l );
							$id.val( $( '#wpseo-tab-' + l ).data( 'wpseotitle' ) );

							//$id.parent( 'label' ).find( 'progress' ).addClass( api.yoastTitleProgress ).addClass( api.yoastTitleProgress + '_' + l );
							/** @since yoastseo 3.3.1 */
							$id.parent( 'label' ).next( 'progress' ).addClass( api.yoastTitleProgress ).addClass( api.yoastTitleProgress + '_' + l );
							_.debounce( api.updateProgressBar( $id,	l ), 500 );
						}
						/** #snippet-editor-slug */
						if ( 'snippet-editor-slug' == id ) {
							$id.addClass('wpglobus-snippet-editor-slug');
							$id.parent( 'label' ).attr( 'for', $id.parent( 'label' ).attr( 'for' ) + '_' + l );
							if ( WPGlobusCoreData.default_language != l ) {
								/** disable slug field by default */
								$id.attr( 'disabled', 'disabled' );
							}
						}
						/** #snippet-editor-meta-description */
						if ( 'snippet-editor-meta-description' == id ) {
							$id.addClass( 'wpglobus-snippet-editor-meta-description' );
							$id.parent( 'label' ).attr( 'for', $id.parent( 'label' ).attr( 'for' ) + '_' + l );
							$id.val( $( '#wpseo-tab-' + l ).data( 'metadesc' ) );

							//$id.parent( 'label' ).find( 'progress' ).addClass( api.yoastMetadescProgress ).addClass( api.yoastMetadescProgress + '_' + l );
							// @since yoastseo 3.3.1
							$id.parent( 'label' ).next( 'progress' ).addClass( api.yoastMetadescProgress ).addClass( api.yoastMetadescProgress + '_' + l );
							_.debounce( api.updateProgressBar( $id,	l ), 500 );
						}
						/** #snippetpreview-help-toggle */
						if ( 'snippetpreview-help-toggle' == id ) {
							$id.addClass( 'wpglobus-snippetpreview-help-toggle_'+l );
							$(document).on( 'click', '.wpglobus-snippetpreview-help-toggle_'+l, function(ev){
								var $t = $(this);
								if ( $( '#snippetpreview-help_'+$t.data( 'language' ) ).css('display') === 'none' ) {
									$( '#snippetpreview-help_'+$t.data( 'language' ) ).css({'display':'block'});
								} else {
									$( '#snippetpreview-help_'+$t.data( 'language' ) ).css({'display':'none'});
								}
							});
						}
						/** #focuskw_text_input-help-toggle	*/
						if ( 'focuskw_text_input-help-toggle' == id ) {
							$id.addClass( 'wpglobus-focuskw_text_input-help-toggle_'+l );
							$(document).on( 'click', '.wpglobus-focuskw_text_input-help-toggle_'+l, function(ev){
								var $t = $(this);
								if ( $( '#focuskw_text_input-help_'+$t.data( 'language' ) ).css('display') === 'none' ) {
									$( '#focuskw_text_input-help_'+$t.data( 'language' ) ).css({'display':'block'});
								} else {
									$( '#focuskw_text_input-help_'+$t.data( 'language' ) ).css({'display':'none'});
								}
							});
						}
						/** #snippetpreview-help	*/
						if ( 'pageanalysis-help-toggle' == id ) {
							$id.addClass( 'wpglobus-pageanalysis-help-toggle_'+l );
							$(document).on( 'click', '.wpglobus-pageanalysis-help-toggle_'+l, function(ev){
								var $t = $(this);
								if ( $( '#pageanalysis-help_'+$t.data( 'language' ) ).css('display') === 'none' ) {
									$( '#pageanalysis-help_'+$t.data( 'language' ) ).css({'display':'block'});
								} else {
									$( '#pageanalysis-help_'+$t.data( 'language' ) ).css({'display':'none'});
								}
							});
						}
						/**
						 * Generate unique id.
						 */
						$id.attr( 'id', id+'_'+l );
						$( '#'+id+'_'+l ).attr( 'data-language', l );

					});

					/**
					 * Set focus keywords for every language.
					 */
					var focuskw = WPGlobusCore.TextFilter( $('#yoast_wpseo_focuskw_text_input').val(), l, 'RETURN_EMPTY' );
					$( '#yoast_wpseo_focuskw_text_input_'+l ).val( focuskw ).data( 'value', focuskw );
					/** since yoastseo 3.2 */

					$( '#yoast_wpseo_focuskw_'+l ).val( focuskw );

					/**
					 * Set data-keyword for yoast seo.
					 * @since 1.7.9
					 */
					if ( ! WPGlobusYoastSeoPremium ) {
						$('#wpseo-metabox-tabs_'+l+' .wpseo_keyword_tab .wpseo_tablink').data('keyword', focuskw);
					}

					/** since yoastseo 3.2 */
					api.updateWpseoKeyword( focuskw, l );

					if ( l !== WPGlobusCoreData.default_language ) {
						$('#'+sectionID+' #yoast_wpseo_focuskw_text_input_'+l)
							.addClass('hidden')
							.after('
'+WPGlobusVendor.i18n.yoastseo_plus_access+'
');

						$('#'+sectionID+' #wpseo-pageanalysis_'+l).addClass('hidden').css({'display':'none'});
					}

					if ( WPGlobusYoastSeoPremium ) {
						/**
						 * @since 1.7.2
						 */
						if ( l == WPGlobusCoreData.default_language ) {
							/**
							 * Do nothing.
							 */
						} else {
							$( '#wpseo-metabox-tabs_'+l+' .wpseo_keyword_tab' ).removeClass('wpseo_keyword_tab').addClass('wpglobus-wpseo_keyword_tab');
							/**
							 * Hide keywords tabs with extra keywords for extra language after page was loaded.
							 */
							$( '#wpseo-meta-section-content_'+l+' .wpseo_keyword_tab_hideable' ).css({'display':'none'}).attr('data-language',l);
						}

					}

				}); /** end each .wpglobus-wpseo-general */

				/** add wpglobus classes to 'Edit snippet' button and hidden form */
				$( '.wpglobus-wpseosnippet' ).each( function(i,e) {
					var $e = $(e);
					var l  = $e.data( 'language' );
					$e.find( 'button.snippet-editor__button.snippet-editor__edit-button' )
						.addClass( api.editSnippetButtonClass ).addClass( api.editSnippetButtonClass+'_'+l ).attr( 'data-language', l );
					$e.find( '.snippet-editor__form' ).addClass( api.editSnippetFormClass ).addClass( api.editSnippetFormClass+'_'+l );
					$e.find( '.snippet-editor__heading-editor' ).addClass( api.editSnippetHeadingClass ).addClass( api.editSnippetHeadingClass+'_'+l );
					$e.find( '.snippet-editor__submit' )
						.addClass( api.editSnippetSubmitClass ).addClass( api.editSnippetSubmitClass+'_'+l ).attr( 'data-language', l );
				});

				/**
				 * Hide original section content.
				 */
				api.iB.addClass( 'hidden' );
				api.iB.css({'height':0,'overflow':'hidden','display':'none'});

				if ( WPGlobusYoastSeoPremium ) {
					/**
					 * Class wpseo_keyword_tab using for counting of keywords in WPSEO_PREMIUM.
					 * So we need to change original .wpseo_keyword_tab class to something else.
					 * @since 1.7.2
					 */
					$('#wpseo-meta-section-content .wpseo_keyword_tab').removeClass('wpseo_keyword_tab').addClass('wpseo_keyword_tab_original');
				}

				/**
				 * Set focuskw to default language.
				 */
				var focuskw_d = WPGlobusCore.TextFilter( $('#yoast_wpseo_focuskw_text_input').val(), WPGlobusCoreData.default_language, 'RETURN_EMPTY' );
				$( '#yoast_wpseo_focuskw_text_input' ).val( focuskw_d );
				$( '#yoast_wpseo_focuskw' ).val( focuskw_d );

				/**
				 * Make switchable wpseo_generic_tab & (wpseo_keyword_tab or wpglobus-wpseo_keyword_tab).
				 * @see element #yoast-seo-content-analysis
				 * @since 1.5.10
				 */
				$(document).on( 'click', '.wpglobus-wpseo-general .wpseo_tablink', function(ev) {
					ev.preventDefault();
					var $t = $(this),
						l = $t.parents( 'ul' ).data( 'language' ),
						tab = $t.parent( 'li' );

					if ( l != WPGlobusCoreData.default_language ) {
						/**
						 * Trigger handler.
						 */
						if ( 'undefined' === typeof $(document).triggerHandler( 'wpglobus_yoast_analysis', {language:l} ) ) {
							return;
						}
					}

					if ( tab.hasClass( 'wpseo_generic_tab' ) ) {
						/**
						 * Readability tab.
						 */
						$( '#wpseo-pageanalysis_' + l ).css({'display':'none'});
						$( '#yoast-seo-content-analysis_' + l ).css({'display':'block'});
						$( '#wpseo_content_' + l + ' table tr' ).eq(0).css({'display':'none'});
						$( '#wpseo_content_' + l + ' table tr' ).eq(1).css({'display':'none'});
						$( '#yoast-seo-content-analysis_' + l + ' li a' ).css({'float':'none'});
					} else if ( tab.hasClass( 'wpseo_keyword_tab' ) ) {
						/**
						 * Keyword tab with default language.
						 */
						if ( WPGlobusYoastSeoPremium ) {
							/**
							 * Reset active status before activate tab.
							 */
							$('#wpseo-meta-section-content_'+l+' .wpseo_keyword_tab').removeClass('active');

							$t.parent('.wpseo_keyword_tab').addClass('active');

							/**
							 * @since 1.7.9
							 */
							$( '#wpseo-pageanalysis_' + l ).css({'display':'block'});
							$( '#yoast-seo-content-analysis_' + l ).css({'display':'none'});
							$( '#wpseo_content_' + l + ' table tr' ).eq(0).css('display','');
							$( '#wpseo_content_' + l + ' table tr' ).eq(1).css('display','');

							/**
							 * Update keyword index.
							 * @since 1.7.2
							 */
							$( '#wpseo-metabox-tabs_'+l+ ' .wpseo_keyword_tab' ).each( function(i,e){
								if ( $(e).hasClass( 'active' ) ) {
									api.keywordIndex[l] = i;
									return false;
								}
							});
						}

						/**
						 * Correct switching Readability/Keyword tabs for extra languages in yoast seo.
						 * @since 1.7.9
						 */
						if ( ! WPGlobusYoastSeoPremium && l != WPGlobusCoreData.default_language ) {
							$( '#wpseo-pageanalysis_' + l ).css({'display':'block'});
							$( '#yoast-seo-content-analysis_' + l ).css({'display':'none'});
							$( '#wpseo_content_' + l + ' table tr' ).eq(0).css('display','');
							$( '#wpseo_content_' + l + ' table tr' ).eq(1).css('display','');
							return;
						}

						var keywords = api.getKeywordsOrig();
						var keyword  = keywords[api.keywordIndex[l]]['keyword'];

						YoastSEO.app.rawData.keyword = keyword;
						$('#yoast_wpseo_focuskw_text_input').val( keyword );
						$('#yoast_wpseo_focuskw_text_input_'+l ).val( keyword );
						$('input[name="yoast_wpseo_focuskw"]').val( keyword );
						WPGlobusYoastSeoPlugin.prototype.analyze();

						$( '#wpseo-pageanalysis_' + l ).css({'display':'block'});
						$( '#yoast-seo-content-analysis_' + l ).css({'display':'none'});
						$( '#wpseo_content_' + l + ' table tr' ).eq(0).css('display','');
						$( '#wpseo_content_' + l + ' table tr' ).eq(1).css('display','');

					} else if ( tab.hasClass( 'wpglobus-wpseo_keyword_tab' ) ) {
						/**
						 * @since 1.7.9
						 */
						$( '#wpseo-pageanalysis_' + l ).css({'display':'block'});
						$( '#yoast-seo-content-analysis_' + l ).css({'display':'none'});
						$( '#wpseo_content_' + l + ' table tr' ).eq(0).css('display','');
						$( '#wpseo_content_' + l + ' table tr' ).eq(1).css('display','');
					}

				});

				/**
				 * wpseo-metabox-sidebar.
				 */
				$('.wpseo-metabox-sidebar .wpseo-meta-section-link').on( 'click',function(ev){
					if ( $(this).attr('href') == '#wpseo-meta-section-content' ) {
						$('#wpglobus-wpseo-tabs').css({'display':'block'});
					} else {
						$('#wpglobus-wpseo-tabs').css({'display':'none'});
					}
				});

				/**
				 * Open form to edit snippet.
				 */
				$(document).on( 'click', '.'+api.editSnippetButtonClass, function(event){
					var $t = $(this);
					var l  = $t.data( 'language' );
					var sform   = $( '.' + api.editSnippetFormClass + '_' + l );
					var sbutton = $( '.' + api.editSnippetSubmitClass + '_' + l );
					var heading = $( '.' + api.editSnippetHeadingClass+'_'+l );

					if ( sform.hasClass( 'snippet-editor--hidden' ) )  {
						sform.removeClass( 'snippet-editor--hidden' );
						heading.removeClass( 'snippet-editor--hidden' );
						sbutton.removeClass( 'snippet-editor--hidden' );
					} else {
						sform.addClass( 'snippet-editor--hidden' );
						heading.addClass( 'snippet-editor--hidden' );
					}
					$t.addClass( 'snippet-editor--hidden' );
				});

				/**
				 * To close snippet editor.
				 */
				$(document).on( 'click', '.'+api.editSnippetSubmitClass, function(event){
					var $t = $(this);
					var l  = $t.data( 'language' );
					var button  = $( '.' + api.editSnippetButtonClass + '_' + l );
					var sform  	= $( '.' + api.editSnippetFormClass + '_' + l );
					var sbutton = $( '.' + api.editSnippetSubmitClass + '_' + l );
					var heading = $( '.' + api.editSnippetHeadingClass+'_'+l );

					button.removeClass( 'snippet-editor--hidden' );
					sform.addClass( 'snippet-editor--hidden' );
					sbutton.addClass( 'snippet-editor--hidden' );
					heading.addClass( 'snippet-editor--hidden' );
				});

				/**
				 * Make title.
				 */
				$(document).on( 'keyup', 'input.wpglobus-snippet-editor-title', function(event){
					var $t = $(this),
						l = $t.data( 'language' ),
						s = WPGlobusCore.getString( $( 'input[name="yoast_wpseo_title"]' ).val(), $t.val(), l );

					$( '#snippet_title_'+l ).html( _this.replaceVariablesPlugin( $t.val() ) );

					YoastSEO.app.rawData.pageTitle = s;  /** @todo maybe set at start js ? */

					/** $('#yoast_wpseo_title').val( s );  @todo don't work with id */
					$( 'input[name="yoast_wpseo_title"]' ).val( s );
					$( '#snippet_title' ).text( s );
					_.debounce( api.updateProgressBar( $t,	l ), 500 );
				});

				/**
				 * Make slug.
				 */
				$(document).on( 'keyup', 'input.wpglobus-snippet-editor-slug', function(event){
					var $t = $(this), l = $t.data( 'language' );

					$( '#snippet_cite_' + l ).text( $t.val() + '/' );
					$( '#editable-post-name' ).text( $t.val() );
					$( '#editable-post-name-full' ).text( $t.val() );
				});

				/**
				 * @todo add doc.
				 */
				$(document).on( 'change', 'input.wpglobus-snippet-editor-slug', function(event){
					var $t = $(this);
					/**
					 * @see editPermalink() in /wp-admin/js/post.js
					 */
					$.post(ajaxurl, {
						action: 'sample-permalink',
						post_id: $('#post_ID').val() || 0,
						new_slug: $t.val(),
						new_title: $('#title').val(),
						samplepermalinknonce: $('#samplepermalinknonce').val()
					});

				});

				/**
				 * Make meta description.
				 */
				$(document).on( 'keyup', 'textarea.wpglobus-snippet-editor-meta-description', function(event){
					var $t = $(this),
						l = $t.data( 'language' );
					$( '#snippet_meta_'+l ).text( $t.val() );

					var s = WPGlobusCore.getString( $('#yoast_wpseo_metadesc').val(), $t.val(), $t.data('language') );
					$( '#yoast_wpseo_metadesc' ).val( s );
					$( '#snippet_meta' ).text( s );
					_.debounce( api.updateProgressBar( $t,	l ), 500 );
				});

				/**
				 * Make synchronization click on "Post tab" with seo tab.
				 */
				$(document).on( 'click', '.wpglobus-post-body-tabs-list li', function(event){
					var $t = $(this);
					if ( $t.hasClass('wpglobus-post-tab') ) {
						/**
						 * @see 'tabsactivate' action.
						 */
						$('#wpglobus-wpseo-tabs').tabs( 'option', 'active', $t.data('order') );

						/**
						 * Set keyword.
						 */
						var k = $( '#yoast_wpseo_focuskw_text_input_' + $t.data('language') ).val();
						YoastSEO.app.rawData.keyword = k ;
						$('#yoast_wpseo_focuskw_text_input').val( k );
						$('input[name="yoast_wpseo_focuskw"]').val( k );

						WPGlobusYoastSeoPlugin.prototype.analyze();
					}
				});
				api.initAddKeywordPopup();
			},
			getKeywordsOrig: function(){
				/**
				 * Retrieves the current keywords.
				 * @see YoastMultiKeyword.prototype.getKeywords
				 */
				return $(".wpseo_keyword_tab").map(function (i, keywordTab) {
					keywordTab = $(keywordTab).find(".wpseo_tablink");

					return {
						// Convert to string to prevent errors if the keyword is "null".
						keyword: keywordTab.data("keyword") + "",
						score: keywordTab.data("score")
					};
				}).get();
			}
		} /** end WPGlobusYoastSeo */

		/********/
		var _this;
		var WPGlobusYoastSeoPlugin = function() {

			this.replaceVars 	= wpseoReplaceVarsL10n.replace_vars;
			this.language 	 	= WPGlobusCoreData.default_language;
			this.tab 	 	 	= WPGlobusCoreData.default_language;
			this.wpseoTab 	 	= WPGlobusCoreData.default_language;

			this.title_template = wpseoPostScraperL10n.title_template;

			this.focuskw		= $('#yoast_wpseo_focuskw_text_input');
			this.focuskw_hidden	= $('input[name="yoast_wpseo_focuskw"]');
			this.focuskwKeep	= false;

			this.post_slug 		= '#editable-post-name-full';

			YoastSEO.app.registerPlugin( 'wpglobusYoastSeoPlugin', {status: 'ready'} );

			/**
			* @param modification    {string}    The name of the filter
			* @param callable        {function}  The callable
			* @param pluginName      {string}    The plugin that is registering the modification.
			* @param priority        {number}    (optional) Used to specify the order in which the callables
			*                                    associated with a particular filter are called. Lower numbers
			*                                    correspond with earlier execution.
			*
			* @see wp-seo-replacevar-plugin-320.js
			*/
			YoastSEO.app.registerModification( 'content', this.contentModification, 'wpglobusYoastSeoPlugin', 0 );
			YoastSEO.app.registerModification( 'title', this.titleModification, 'wpglobusYoastSeoPlugin', 0 );

			YoastSEO.app.registerModification( 'snippet_title', this.snippetModification, 'wpglobusYoastSeoPlugin', 0 );
			YoastSEO.app.registerModification( 'snippet_meta', this.snippetModification, 'wpglobusYoastSeoPlugin', 0 );

			YoastSEO.app.registerModification( 'data_page_title', this.pageTitleModification, 'wpglobusYoastSeoPlugin', 0 );
			YoastSEO.app.registerModification( 'data_meta_desc', this.metaDescModification, 'wpglobusYoastSeoPlugin', 0 );

			WPGlobusYoastSeoPlugin.prototype.setScoreIcon();

			$(document).on( 'blur', '.wpglobus-snippet_title', function(ev){
				var $t = $(this);
				var s = WPGlobusCore.getString( $('#yoast_wpseo_title').val(), $t.text(), $t.data('language') );

				YoastSEO.app.rawData.pageTitle = s;  // @todo maybe set at start js ?

				//$('#yoast_wpseo_title').val( s );  // @todo don't work with id
				$('input[name="yoast_wpseo_title"]').val( s );
				$('#snippet_title').text( s );
			});

			$(document).on( 'blur', '.wpglobus-snippet_meta', function(ev){
				var $t = $(this);
				var s = WPGlobusCore.getString( $('#yoast_wpseo_metadesc').val(), $t.text(), $t.data('language') );
				$( '#yoast_wpseo_metadesc' ).val( s );
				$( '#snippet_meta' ).text( s );

			});

			/**
			 * Handle event of keyword's change.
			 */
			$(document).on( 'keyup', '.wpglobus-yoast_wpseo_focuskw_text_input', function(ev){
				var $t 	 = $(this);
				var s 	 = $t.val(), lang = $t.data('language');
				_this.focuskw.val( s );
				_this.focuskw_hidden.val( s );

				/**
				 * Set data-keyword for yoast seo.
				 * @since 1.7.9
				 */
				if ( ! WPGlobusYoastSeoPremium ) {
					$('#wpseo-metabox-tabs_'+lang+' .wpseo_keyword_tab .wpseo_tablink').data('keyword', s);
				}

				_this.updateWpseoKeyword( s, lang );
				/**
				 * @since 1.7.2
				 */
				if ( 0 == WPGlobusYoastSeo.keywordIndex[lang] ) {
					/**
					 * Save first keyword in 'data-value' attribute.
					 */
					$( '#yoast_wpseo_focuskw_text_input_'+lang ).data('value', s);
				} else {
					if ( WPGlobusYoastSeoPremium ) {
						WPGlobusYoastSeoPremium.setFocuskeyword( lang );
					}

				}
				/**
				 * @since yoastseo 3.2.
				 */
				WPGlobusYoastSeoPlugin.prototype.analyze();
			});

			/**
			 * Pre-save action.
			 */
			$( '#publish,#save-post' ).on( 'mouseenter', function(event){
				/**
				 * Save first keywords for all languages.
				 */
				var $t, s = '';
				$('.wpglobus-yoast_wpseo_focuskw_text_input').each( function(i,e){
					$t = $(this);
					if ( $t.data('language') == WPGlobusCoreData.default_language ) {
						if ( WPGlobusYoastSeoPremium ) {
							var keywords = WPGlobusYoastSeo.getKeywordsOrig();
							s = WPGlobusCore.getString( s, keywords[0]['keyword'], $t.data('language') );
						} else {
							s = WPGlobusCore.getString( s, $t.val(), $t.data('language') );
						}
					} else {
						s = WPGlobusCore.getString( s, $t.val(), $t.data('language') );
					}
				});
				_this.focuskw.val( s );
				_this.focuskw_hidden.val( s );
			}).on( 'mouseleave', function(event) {
				if ( ! _this.focuskwKeep ) {
					_this.wpseoTab = $('.wpglobus-wpseo-tabs-list .ui-tabs-active').data('language');
					var $t = $(this);
					_this.focuskw.val( $('#yoast_wpseo_focuskw_text_input_'+_this.wpseoTab ).val() );
					_this.focuskw_hidden.val( $('#yoast_wpseo_focuskw_text_input_'+_this.wpseoTab ).val() );
				}
			}).on( 'click', function(event){
				_this.focuskwKeep = true;
			});

			/**
			 * The action when language's tab was activated in Yoast SEO or Yoast SEO Premium metabox
			 * or synchronization was fired from "Post tab".
			 * It is fired when user come from other language tab.
			 * @see action ['click', '.wpglobus-post-body-tabs-list li']
			 */
			$(document).on( 'tabsactivate', WPGlobusYoastSeo.wpseoTabSelector, function(event, ui){
				_this.language = ui.newPanel.attr( 'data-language' );
				WPGlobusYoastSeo.wpseoTab = _this.language;
				if ( ui.newPanel.attr( 'data-language' ) === WPGlobusCoreData.default_language ) {
					/**
					 * Set keyword.
					 */
					var k;
					if ( WPGlobusYoastSeoPremium ) {
						/**
						 * @todo To use wpglobus-wpseo_keyword_tab class instead of wpseo_keyword_tab for extra languages.
						 * @since 1.7.2
						 */
						$('#wpseo-meta-section-content_'+WPGlobusYoastSeoPremium.dLang+' .wpseo_keyword_tab').removeClass('active');
						var tab = $('#wpseo-meta-section-content_'+WPGlobusYoastSeoPremium.dLang+' .wpseo_keyword_tab').eq(WPGlobusYoastSeo.keywordIndex[WPGlobusYoastSeoPremium.dLang]);
						tab.addClass('active');
						/**
						 * We could loose keyword for default language.
						 * Let's restore it.
						 */
						k = $( '#yoast_wpseo_focuskw_text_input_' + WPGlobusYoastSeoPremium.dLang ).val();
					} else {
						k = $( '#yoast_wpseo_focuskw_text_input_' + WPGlobusCoreData.default_language ).val();
					}
					YoastSEO.app.rawData.keyword = k ;
					_this.focuskw.val( k );
					_this.focuskw_hidden.val( k );
				}

				/**
				 * Update keyword index.
				 * @since 1.7.2
				 */
				$( '#wpseo-metabox-tabs_'+_this.language+ ' .wpseo_keyword_tab' ).each( function(i,e){
					if ( $(e).hasClass( 'active' ) ) {
						WPGlobusYoastSeo.keywordIndex[_this.language] = i;
						return false;
					}
				});
				WPGlobusYoastSeoPlugin.prototype.analyze();
			});

			/**
			 * An alias.
			 */
			_this = this;

		}

		WPGlobusYoastSeoPlugin.prototype.analyze = function() {

			var tab = $('.wpglobus-wpseo-tabs-list .ui-tabs-active').data('language');
			if (  tab == WPGlobusCoreData.default_language ) {
				YoastSEO.app.snippetPreview.data.urlPath = $( '#editable-post-name-full' ).text();
			} else {
				if ( $( '#editable-post-name-full-' + tab ).length != 0 ) {
					YoastSEO.app.snippetPreview.data.urlPath = $( '#editable-post-name-full-' + tab ).text();
				} else {
					YoastSEO.app.snippetPreview.data.urlPath = $( '#editable-post-name-full' ).text();
				}
			}

			YoastSEO.app.analyzeTimer( YoastSEO.app );
			WPGlobusYoastSeoPlugin.prototype.setScoreIcon();

		}

		WPGlobusYoastSeoPlugin.prototype.setScoreIcon = function() {
			var iID;
			var timer = function() {
				var l = $('.wpglobus-wpseo-tabs-list .ui-tabs-active').data('language');
				/**
				 * Get calculated scores from source ...
				 * @since 1.6.8
				 */
				var generic_tab_score = $('#wpseo-meta-section-content .wpseo_generic_tab a').data('score');
				var keyword_tab_score = $('#wpseo-meta-section-content .wpseo_keyword_tab a').data('score');

				/**
				 * ... and place them to the appropriate language.
				 * @since 1.6.8
				 */
				if ( generic_tab_score != '' ) {
					$( '#wpseo-metabox-tabs_'+l+' .wpseo_generic_tab .wpseo-score-icon' ).removeClass( 'bad ok good 100 na' );
					$( '#wpseo-metabox-tabs_'+l+' .wpseo_generic_tab .wpseo-score-icon' ).addClass( generic_tab_score );
				}

				/**
				 * WPGlobusYoastSeoPremium has undefined keyword_tab_score.
				 * @todo need to check class 'wpseo_keyword_tab_original'.
				 */
				if ( 'undefined' !== typeof keyword_tab_score ) {
					if ( '' != keyword_tab_score ) {
						if ( WPGlobusYoastSeoPremium && l != WPGlobusYoastSeoPremium.dLang ) {
							$( '#wpseo-metabox-tabs_'+l+' .wpglobus-wpseo_keyword_tab .wpseo-score-icon' ).removeClass( 'bad ok good 100 na' );
							$( '#wpseo-metabox-tabs_'+l+' .wpglobus-wpseo_keyword_tab .wpseo-score-icon' ).addClass( keyword_tab_score );
						} else {
							$( '#wpseo-metabox-tabs_'+l+' .wpseo_keyword_tab .wpseo-score-icon' ).removeClass( 'bad ok good 100 na' );
							$( '#wpseo-metabox-tabs_'+l+' .wpseo_keyword_tab .wpseo-score-icon' ).addClass( keyword_tab_score );
						}
					}
				}
				clearInterval(iID);
			}
			iID = setInterval( timer, 1500 );
		}

		WPGlobusYoastSeoPlugin.prototype.getWPseoTab = function() {
			return $('.wpglobus-wpseo-tabs-list .ui-tabs-active').data('language');
		}

		WPGlobusYoastSeoPlugin.prototype.citeModification = function(l) {
			var citeBase = '#snippet_citeBase_' + l,
				cite 	 = '#snippet_cite_' + l,
				cb 		 = $( '#wpseo-tab-' + l ).data( 'yoast-cite-base' ),
				e  		 = $( '#wpseo-tab-' + l ).data( 'cite-contenteditable' );

			if ( e === false ) {
				$(cite).attr( 'contenteditable', 'false' );
			}
			$(citeBase).text( cb );
		}

		/**
		 * Page title modification for backend
		 */
		WPGlobusYoastSeoPlugin.prototype.pageTitleModification = function(data) {
			//console.log( '1. pageTitleModification: ' + _this.getWPseoTab() + ' ->' + data);

			var id = '#snippet_title_',
				text = '', tr, return_text = '', set, temp;

			if ( _this.title_template == data ) {
				/**
				 * meta key _yoast_wpseo_title is empty or doesn't exists
				 */
				$.each( WPGlobusCoreData.enabled_languages, function(i,l) {
					set = $( '#snippet-editor-title_' + l ).val();
					if ( set.length == 0 ) {
						temp = _this.title_template;
					} else {
						temp = set;
					}
					//_this.language = l;
					text = _this.replaceVariablesPlugin( temp );
					$( id+l ).text( text );
					if ( l == _this.getWPseoTab() ) {
						return_text = text;
					}
				});

			} else {

				tr = WPGlobusCore.getTranslations( data );

				if ( _this.getWPseoTab() !== WPGlobusCoreData.default_language ) {
					/**
					 * Case when we get data with extra language only ( without language marks )
					 */
					if ( tr[ WPGlobusCoreData.default_language ] == data ) {

						var l = _this.getWPseoTab();

						set = $( '#snippet-editor-title_' + l ).val();
						if ( set.length > 0 ) {
							temp = set;
						} else {
							temp = _this.title_template;
						}
						temp = _this.replaceVariablesPlugin( temp );

						$( id+l ).text( temp );

						return temp;
					}

				}

				$.each( WPGlobusCoreData.enabled_languages, function(i,l) {
					//_this.language = l;
					if ( '' === tr[l] ) {
						text = _this.replaceVariablesPlugin( _this.title_template );
					} else {
						text = _this.replaceVariablesPlugin( tr[l] );
					}
					if ( l == _this.getWPseoTab() ) {
						return_text = text;
						set = $( '#snippet-editor-title_' + l ).val();
						if ( set.length != 0 ) {
							if ( set != return_text ) {
								return_text	= _this.replaceVariablesPlugin( set );
							}
						} else {
							return_text	= _this.replaceVariablesPlugin( _this.title_template );
						}
					}
					$( id+l ).html( return_text );
				});
			}

			return return_text;
		}

		/**
		 * Page description modification for backend
		 */
		WPGlobusYoastSeoPlugin.prototype.metaDescModification = function(data) {
			//console.log( '2. metaDescModification: ' + _this.getWPseoTab() + ': ' + data );

			var id = '#snippet_meta_'; // span element
			var metaDesc = '#snippet-editor-meta-description_';
			var metaDescText = '';
			var tr = WPGlobusCore.getTranslations( data );
			var return_text = '';

			metaDescText = $( metaDesc + _this.getWPseoTab() ).val();

			if ( _this.getWPseoTab() !== WPGlobusCoreData.default_language ) {
				/**
				 * Case when we get data with extra language only (without language marks).
				 */
				if ( tr[ WPGlobusCoreData.default_language ] == data ) {
					var l = _this.getWPseoTab();
					_this.citeModification( l );

					if ( metaDescText.length == 0 ) {
						//$( id+l ).text( data );
						$( id+l ).text( '' );
					} else if ( metaDescText != data ) {
						$( id+l ).text( metaDescText );
					}

					return data;
				}

			}

			$.each( WPGlobusCoreData.enabled_languages, function(i,l) {
				$( id+l ).text( WPGlobusCore.TextFilter( data, l, 'RETURN_EMPTY' ) );
				_this.citeModification( l );
			});

			if ( metaDescText == tr[ _this.getWPseoTab() ]  ) {
				return_text = tr[ _this.getWPseoTab() ];
				if ( return_text.length == 0 ) {
					$( id + _this.getWPseoTab() ).text(
						WPGlobusCore.TextFilter(
							YoastSEO.app.snippetPreview.data.metaDesc,
							WPGlobusCoreData.default_language,
							'RETURN_EMPTY'
						)
					);
				}
			} else {
				return_text = metaDescText;
				if ( return_text.length == 0 ) {
					$( id + _this.getWPseoTab() ).text(
						WPGlobusCore.TextFilter(
							YoastSEO.app.snippetPreview.data.metaDesc,
							WPGlobusCoreData.default_language,
							'RETURN_EMPTY'
						)
					);
				} else {
					$( id + _this.getWPseoTab() ).text( return_text );
				}
			}

			$( id + _this.getWPseoTab() ).text( return_text );
			return return_text;

		}

		WPGlobusYoastSeoPlugin.prototype.snippetModification = function(data) {
			//console.log( '3. snippetModification: ' + _this.getWPseoTab() );
			return WPGlobusCore.TextFilter( data, _this.getWPseoTab(), 'RETURN_EMPTY' );
		}

		/**
		 * Adds some text to the data...
		 *
		 * @param data The data to modify
		 */
		WPGlobusYoastSeoPlugin.prototype.contentModification = function(data) {
			//console.log( '4. contentModification: ' + _this.getWPseoTab() );

			if ( _this.getWPseoTab() == WPGlobusCoreData.default_language ) {
				return data;
			}
			return $( '#content_' + _this.getWPseoTab() ).val();
		};

		WPGlobusYoastSeoPlugin.prototype.titleModification = function(data) {
			//console.log( '5. titleModification: ' + _this.getWPseoTab() );

			setTimeout( _this.updatePageAnalysis, 1000 );

			if ( _this.getWPseoTab() == WPGlobusCoreData.default_language ) {
				return data;
			}

			return $( '#title_' + _this.getWPseoTab() ).val();

		};

		/**
		 * Replace default variables with the values stored in the wpseoMetaboxL10n object.
		 *
		 * @see YoastReplaceVarPlugin.prototype.defaultReplace
		 * @since 1.4.7
		 *
		 * @param {String} textString
		 * @return {String}
		 */
		WPGlobusYoastSeoPlugin.prototype.defaultReplace = function( textString ) {
			var focusKeyword = YoastSEO.app.rawData.keyword;

			return textString.replace( /%%sitedesc%%/g, this.replaceVars.sitedesc )
				.replace( /%%sitename%%/g, WPGlobusCore.TextFilter( this.replaceVars.sitename, _this.getWPseoTab() ) )
				.replace( /%%term_title%%/g, this.replaceVars.term_title )
				.replace( /%%term_description%%/g, this.replaceVars.term_description )
				.replace( /%%category_description%%/g, this.replaceVars.category_description )
				.replace( /%%tag_description%%/g, this.replaceVars.tag_description )
				.replace( /%%searchphrase%%/g, this.replaceVars.searchphrase )
				.replace( /%%date%%/g, this.replaceVars.date )
				.replace( /%%id%%/g, this.replaceVars.id )
				.replace( /%%page%%/g, this.replaceVars.page )
				.replace( /%%currenttime%%/g, this.replaceVars.currenttime )
				.replace( /%%currentdate%%/g, this.replaceVars.currentdate )
				.replace( /%%currentday%%/g, this.replaceVars.currentday )
				.replace( /%%currentmonth%%/g, this.replaceVars.currentmonth )
				.replace( /%%currentyear%%/g, this.replaceVars.currentyear )
				.replace( /%%focuskw%%/g, focusKeyword );
		};

		/**
		 * runs the different replacements on the data-string
		 *
		 * @see YoastReplaceVarPlugin.prototype.replaceVariablesPlugin
		 *
		 * @param {String} data
		 * @returns {string}
		 */
		/*
		WPGlobusYoastSeoPlugin.prototype.replaceVariablesPlugin = function( data ) {
			if( typeof data !== 'undefined' ) {
				data = this.titleReplace( data );
				data = this.defaultReplace( data );
				//data = this.parentReplace( data );
				data = this.doubleSepReplace( data );
				//data = this.excerptReplace( data );
			}
			return data;
		};	// */

		/**
		 * runs the different replacements on the data-string
		 *
		 * @see YoastReplaceVarPlugin.prototype.replaceVariablesPlugin
		 * @since 1.4.7
		 *
		 * @param {String} data
		 * @returns {string}
		 */
		WPGlobusYoastSeoPlugin.prototype.replaceVariablesPlugin = function( data ) {
			if( typeof data !== 'undefined' ) {
				data = this.titleReplace( data );
				//data = this.termtitleReplace( data );
				data = this.defaultReplace( data );
				//data = this.parentReplace( data );
				data = this.replaceSeparators( data );
				//data = this.excerptReplace( data );
			}
			return data;
		};

		/**
		 * Replaces separators in the string.
		 *
		 * @since 1.4.7
		 * @see YoastReplaceVarPlugin.prototype.replaceSeparators
		 *
		 * @param {String} data
		 * @returns {String}
		 */
		WPGlobusYoastSeoPlugin.prototype.replaceSeparators = function( data ) {
			return data.replace( /%%sep%%(\s+%%sep%%)*/g, this.replaceVars.sep );
		};

		/**
		 * Replaces %%title%% with the title
		 *
		 * @see YoastReplaceVarPlugin.prototype.titleReplace
		 *
		 * @param {String} data
		 * @returns {string}
		 */
		WPGlobusYoastSeoPlugin.prototype.titleReplace = function( data ) {
			var title = '', t = '';
			if ( this.language == WPGlobusCoreData.default_language ) {
				title = $('#title').val();
			} else {
				title = $('#title_'+this.language).val();
			}
			if ( typeof title === 'undefined' ) {
				title = YoastSEO.app.rawData.pageTitle;
			}
			if ( this.language != WPGlobusCoreData.default_language && title.length == 0 ) {
				title = $('#title').val();
			}
			data = data.replace( /%%title%%/g, title );

			return data;
		};

		/**
		 * Removes double seperators and replaces them with a single seperator.
		 *
		 * @see YoastReplaceVarPlugin.prototype.doubleSepReplace
		 *
		 * @param {String} data
		 * @returns {String}
		 */
		WPGlobusYoastSeoPlugin.prototype.doubleSepReplace = function( data ) {
			var escaped_seperator = YoastSEO.app.stringHelper.addEscapeChars( this.replaceVars.sep );
			var pattern = new RegExp( escaped_seperator + ' ' + escaped_seperator, 'g' );
			data = data.replace( pattern, this.replaceVars.sep );
			return data;
		};

		WPGlobusYoastSeoPlugin.prototype.updateWpseoKeyword = function(kw,l) {
			if ( $( '#wpseo-meta-section-content_'+l+' .wpseo-keyword' ).length > 0 ) {
				$( '#wpseo-meta-section-content_'+l+' .wpseo-keyword' ).removeClass( 'wpseo-keyword' ).addClass( 'wpglobus-wpseo_keyword_'+l );
			}
			$( '.wpglobus-wpseo_keyword_'+l ).text( kw );
		}

		WPGlobusYoastSeoPlugin.prototype.updatePageAnalysis = function() {
			$( '#wpseo-pageanalysis_' + _this.getWPseoTab() ).html( $('#wpseo-pageanalysis').html() );
			$( '#yoast-seo-content-analysis_' + _this.getWPseoTab() ).html( $( '#yoast-seo-content-analysis' ).html() );
			$( '#yoast-seo-content-analysis_' + _this.getWPseoTab() + ' li a' ).css({'float':'none'});
		};

		window.WPGlobusYoastSeoPlugin = new WPGlobusYoastSeoPlugin();

	} /** endif WPGlobusVendor.pagenow */

});


text:
<?php

class ConfigTest extends PHPUnit_Framework_TestCase
{
    public function test()
    {
        $versions = PhpBrew\Config::getInstalledPhpVersions();
        // ok( $versions );
        // var_dump( $versions );
    }
}


text:
declare module "archy" {
    function archy(obj: archy.Data, prefix?: string, opts?: archy.Options): string;
    function archy(obj: string, prefix?: string, opts?: archy.Options): string;

    module archy {
        interface Data {
            label: string;
            nodes?: (Data | string)[];
        }
        interface Options {
            unicode?: boolean;
        }
    }

    export = archy;
}


text:
package com.airhacks.enhydrator.transform;

import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author airhacks.com
 */
@XmlRootElement(name = "datatype")
public enum Datatype {

    DOUBLE, INTEGER, BOOLEAN;

}


text:
'use strict';

/* Controllers */
define(['angular', 'angular-file-upload'], function(angular) {
angular.module('lecture.controller', ['security', 'ui.bootstrap' , 'angularFileUpload'])
//app
.controller('LectureListCtrl',
['$rootScope', '$scope', 'Lecture','$stateParams', function($rootScope, $scope, Lecture,$stateParams) {
	console.log($stateParams);

	$scope.course = { _id: $stateParams.courseId };
	$scope.lectures = Lecture.query({courseId: $stateParams.courseId});

	$scope.open = function($event) {
  	    $event.preventDefault();
    	$event.stopPropagation();

    	$scope.opened = true;
    };

}]);

//app
angular.module('lecture.controller')
.controller('LectureItemCtrl',
['$scope', '$q', '$location','$stateParams','Lecture','User','lectureId', '$modalInstance', '$modal','lectureService', function($scope, $q, $location, $stateParams,Lecture,User,lectureId, $modalInstance, $modal,lectureService) {

	$scope.lecture = Lecture.get({lectureId: lectureId});

	$scope.lecture.$promise.then(function() {
		lectureService.setLecture($scope.lecture);
		$scope.lecture.presentationFile = $scope.lecture.presentation_url.replace(/^.*[\\\/]/, '');
		$scope.lecture.materialFiles = {};

		for( var i in $scope.lecture.material_url) {
			$scope.lecture.materialFiles[i] = {
					fileName : $scope.lecture.material_url[i].url.replace(/^.*[\\\/]/, ''),
					url : $scope.lecture.material_url[i].url,

			};

		}

	});

	$scope.launchEdit = function() {
		//$modalInstance.close();

		var dlg = null;
		dlg = $modal.open({
				templateUrl: '/partials/lecture/edit',
				controller: 'LectureEditCtrl',
				backdrop: 'static',
				resolve: {
					lecture: function() {
						return $scope.lecture;
					}
				}
			});

		dlg.result.then(function () {
			console.log($scope.courseId);
			$scope.lectures = Lecture.query({course: $scope.course._id});

		}, function() {
			console.log("Dismissed");
		});

	};

	$scope.view = function() {

		$modalInstance.close();
		$location.path("/lapp/"+$scope.lecture._id);
   		//$scope.$apply();

	}

	$scope.deleteLecture = function() {
		$scope.lecture.$delete( {id: $scope.lecture._id} , function(p,resp){

			if(!p.error) {
				// If there is no error, redirect to the main view
				console.log("delete Success!");
				//$location.path('/lectures/');
				$modalInstance.close();
			} else {
				alert('Could not delete lecture');
			}
		});
	};

}]);

//app
angular.module('lecture.controller')
.controller('LectureNewCtrl',
['$scope', '$modalInstance', '$location','$stateParams','Lecture', 'course', 'FileUploader','XSRF_TOKEN', '$http',  function($scope, $modalInstance, $location, $stateParams, Lecture, course, FileUploader, csrf_token, $http) {
	//var user = $scope.user;

	$scope.fileUploadFlag = 0;
	$scope.updateFlag = function(flag){
		$scope.fileUploadFlag = flag;
	}
	$scope.course = course;
	$scope.lecture = {
		title: '',
		description: '',
		status: 0,
		duration: 0,
		ppt_page: 0,
		ppt_event_log: "",
		course: course._id,
		vod_url: '',
		material_url: [],
		presentation_url: ''
	};
	console.info("fileupload: debug");

	$scope.open = function($event) {

  	    $event.preventDefault();
    	$event.stopPropagation();

    	$scope.opened = true;
    };

	// VoD upload
	var uploader = $scope.uploader = new FileUploader({
        scope: $scope,                          // to automatically update the html. Default: $rootScope
        url: '/fileUpload',
        formData: [
            { key: 'value' }
        ],
        headers:
                  {'X-CSRF-TOKEN': csrf_token
        },

    });

	console.log(uploader);

	uploader.filters.push({
		name: "videoExtensionFilter",
		fn: function (item) {                    // first user filter

        	if(item.type.indexOf("video/mp4")> -1 || item.type.indexOf("video/webm")> -1 || item.type.indexOf("video/ogg")> -1)
        		return true;
        	else
        		return false;
        }
	});

	uploader.filters.push({
		name: "pptExtensionFilter",
		fn: function (item) {                    // first user filter

        	if(item.type.indexOf("presentation")> -1 || item.type.indexOf("pdf") > -1)
        		return true;
        	else
        		return false;
        }
	});
	uploader.filters.push({
		name: "etcExtensionFilter",
		fn: function (item) {                    // first user filter
           return true;
        }
	});

	uploader.onAfterAddingFile = function(item) {
		$("#sBtn").attr("disabled",true);

	};

    uploader.onWhenAddingFileFailed = function (item,filter,option) {
        if ($scope.fileUploadFlag == 1)
        	alert("Video Files Only!");
        else if($scope.fileUploadFlag == 2)
        	alert("Presentation Files Only!");
    };

    uploader.onCompleteItem = function (item, response, status, headers) {
        var base_url = $location.$$absUrl.replace($location.$$url, "") + "/uploads/temp/";
        //$scope.lecture.vod_url = $location.$$absUrl.replace($location.$$url, "") + "/uploads/temp/" + item.file.name;
        //console.log($location.$$absUrl + " " + $loca
        ;

        var vod = "";
        if ($scope.lecture.status == 0){
        	vod = $("#lectureVoDFile").val().replace(/^.*[\\\/]/, '');
        }

        var presentation = "";
        try{
        	presentation = $("#lecturePresentationFile").val().replace(/^.*[\\\/]/, '');
        }catch(err){

        }

        if (vod == item.file.name){
        	$scope.lecture.vod_url = base_url + item.file.name.replace(new RegExp(" ", 'g'), "_");
	        var videoPreview = $('#videoPreview');
	        videoPreview.attr("src",$scope.lecture.vod_url);
	        videoPreview.get(0).load();
	        videoPreview.get(0).play();
	        videoPreview.show();

	        videoPreview.bind('loadeddata', function(e) {
	        	console.log(e.target.duration);
	        	$scope.lecture.duration = e.target.duration;
	        });
        }
        else if (presentation == item.file.name){
        	$scope.lecture.presentation_url = base_url + item.file.name.replace(new RegExp(" ", 'g'), "_");
        }
        else {
        	var supply_url = base_url + item.file.name.replace(new RegExp(" ", 'g'), "_");
        	$scope.lecture.material_url.push({url: supply_url});
        }
        console.log($scope.lecture);
    };

    uploader.onCompleteAll = function() {
    	$("#sBtn").attr("disabled",false);
    };

	$scope.createLecture = function() {
		var lecture = $scope.lecture;

		//uploader

		if(lecture.title.length > 0) {

			var newLecture = new Lecture(lecture);

			newLecture.$save(function(p, resp) {
				if(!p.error) {
					// If there is no error, redirect to the main view
					console.log("p");
					console.log(p);
					var url_data = {_id: p._id, status: p.status, vod_url: p.vod_url, presentation_url: p.presentation_url, material_url: p.material_url};

					$http.post('/createLecture', url_data).success(function(resp){
						try{
							var base_url = $location.$$absUrl.replace($location.$$url, "") + "/uploads/" + p._id + "/";
							if (p.status == 0)
								p.vod_url = base_url + p.vod_url.replace(/^.*[\\\/]/, '');
							p.presentation_url = base_url + p.presentation_url.replace(/^.*[\\\/]/, '');
							for (var i in p.material_url){
								p.material_url[i].url = base_url + p.material_url[i].url.replace(/^.*[\\\/]/, '');
							}
							p.$save(function(q, resp){
								if(!q.error){
									console.log("q");
									$modalInstance.close();
								}
								else{
									alert('Could not create course');
								}
							});
						}catch(err){
							$modalInstance.close();
						}
					});

				} else {
					alert('Could not create course');
				}
			});
		} else {
			alert('You must enter a title');
		}

	};

	$scope.cancel = function() {
		$modalInstance.dismiss('cancel');
	};

}]);

angular.module('lecture.controller')
.controller('LectureEditCtrl',
['$scope', '$modalInstance', '$location','$stateParams','Lecture', 'Course', 'lecture', function($scope, $modalInstance, $location, $stateParams,Lecture, Course, lecture) {

	$scope.lecture = lecture;
	$scope.course = Course.get({courseId: lecture.course});

	$scope.updateLecture = function() {

		var lecture = $scope.lecture;

		if(lecture.title.length > 0) {

			lecture.$save(function(p, resp) {
				if(!p.error) {
					// If there is no error, redirect to the main view
					$modalInstance.close();
				} else {
					alert('Could not update course');
				}
			});
		} else {
			alert('You must enter a title');
		}
	};

	$scope.cancel = function() {
		$modalInstance.dismiss('cancel');
	};

}]);

});


text:
import PropTypes from 'prop-types';

import Element from './Element';

export default class Line extends Element {

  static displayName = 'Line';

  static propTypes = {
    x1: PropTypes.oneOfType([PropTypes.func, PropTypes.number]).isRequired,
    x2: PropTypes.oneOfType([PropTypes.func, PropTypes.number]).isRequired,
    y1: PropTypes.oneOfType([PropTypes.func, PropTypes.number]).isRequired,
    y2: PropTypes.oneOfType([PropTypes.func, PropTypes.number]).isRequired,
  };

  static defaultProps = {
    ...Element.defaultProps,
  };

  defaultComponent='line'

}


text:
<?php namespace UrlShortener\Links;

use Laracasts\Commander\Events\EventGenerator;
use UrlShortener\Events\LinkWasGenerated;
use UrlShortener\Presenters\PresentableTrait;

class Link extends \Eloquent {

	use EventGenerator, PresentableTrait;

	protected $fillable = ['user_id', 'url', 'hash'];

	/**
	 * Link presenter class location
	 * @var string
	 */
	protected $presenter = 'UrlShortener\Presenters\LinkPresenter';

	/**
	 * Generate a new link
	 * @param $user_id
	 * @param $url
	 * @param $hash
	 * @return static
	 */
	public function generate($user_id, $url, $hash)
	{
		$link = new static(compact('user_id', 'url', 'hash'));

		$link->raise(new LinkWasGenerated($user_id, $url, $hash));

		return $link;
	}

	/**
	 * Link belongs to a user
	 */
	public function user()
	{
		return $this->belongsTo('UrlShortener\Users\User');
	}

}


text:
module Vimpack
  module Models
    autoload :Base,    'vimpack/models/base'
    autoload :ApiBase, 'vimpack/models/apibase'
    autoload :Script,  'vimpack/models/script'
    autoload :Repo,    'vimpack/models/repo'
  end
end


text:
var conf = require('../enode.config.js').config;

var lowIdClients = {

  _min: 1,
  _max: 0xffffff,
  _count: 0,
  _next: 1,
  _clients: {},

  _nextId: function() {
    if (!conf.tcp.allowLowIDs) return false;
    if (lowIdClients._count >= lowIdClients._max - lowIdClients._min + 1) {
      return false;
    }
    var r = lowIdClients._next;
    lowIdClients._next++;
    while (lowIdClients._clients.hasOwnProperty[lowIdClients._next]) {
      lowIdClients._next++;
      if (lowIdClients._next > lowIdClients._max) {
        lowIdClients._next = lowIdClients._min;
      }
    }
    return r;
  },

  count: function() {
    return lowIdClients._count;
  },

  add: function(client) {
    var id = lowIdClients._nextId();
    if (id) { lowIdClients._clients[id] = client; }
    return id;
  },

  get: function(id) {
    if (lowIdClients._clients.hasOwnProperty(id)) {
      return lowIdClients.clients[id];
    }
    else {
      return false;
    }
  },

  remove: function(id) {
    lowIdClients._count--;
    delete lowIdClients._clients[id];
  }

};

exports.lowIdClients = lowIdClients;


text:
{% extends "siteTemplate.html" %} {% load staticfiles %}

{% block content %}

        Add new video

        {% for video in videos %}

{{ video.title }}

        {% endfor %}

{% endblock %}


text:
package pl.itrack.client.local.view.widgets.modals;

import gwt.material.design.client.constants.ModalType;
import org.apache.commons.lang3.StringUtils;

import javax.inject.Inject;

public class SimpleAsyncDialog {

    private static final String DIALOG_CSS_CLASS_NAME = "simple-dialog";

    private final BaseDialog<SimpleDialogBody> dialog;

    private final SimpleDialogBody body;

    @Inject
    public SimpleAsyncDialog(BaseDialog<SimpleDialogBody> dialog, SimpleDialogBody body) {
        this.dialog = dialog;
        this.body = body;
    }

    public void show() {
        dialog.init(StringUtils.EMPTY, body, DIALOG_CSS_CLASS_NAME);
        dialog.setType(ModalType.FIXED_FOOTER);
        dialog.showWithLoader();
    }

    public void update(String title, String description) {
        dialog.setTitle(title);
        dialog.getDialogBody().setInnerHtml(description);
    }

    public void hideLoader() {
        dialog.hideLoader();
    }
}


text:
<?php
namespace Chamilo\Core\Repository\ContentObject\Survey\Storage\DataClass;

use Chamilo\Core\Repository\ContentObject\Survey\Display\Interfaces\SurveyDisplayItem;
use Chamilo\Core\Repository\Storage\DataClass\ComplexContentObjectItem;

/**
 * $Id: complex_survey.class.php 200 2009-11-13 12:30:04Z kariboe $
 *
 * @package repository.lib.content_object.survey
 */
class ComplexSurvey extends ComplexContentObjectItem implements SurveyDisplayItem
{
    const PROPERTY_VISIBLE = 'visible';

    static function get_additional_property_names()
    {
        return array(self::PROPERTY_VISIBLE);
    }

    function get_visible()
    {
        return $this->get_additional_property(self::PROPERTY_VISIBLE);
    }

    function set_visible($value)
    {
        $this->set_additional_property(self::PROPERTY_VISIBLE, $value);
    }

    function is_visible()
    {
        return $this->get_visible() == 1;
    }

    function toggle_visibility()
    {
        $this->set_visible(! $this->get_visible());
    }

    function getDataAttributes()
    {
        return null;
    }
}
?>


text:
<?php

namespace Bitpay;

use Bitpay\Math\Math;
use Bitpay\Util\Secp256k1;
use Bitpay\Util\Util;

/**
 * @package Bitcore
 */
class PublicKey extends Key
{
    /**
     * @var SinKey
     */
    protected $sin;

    /**
     * @var PrivateKey
     */
    protected $privateKey;

    /**
     * Returns the compressed public key value
     *
     * @return string
     */
    public function __toString()
    {
        if (is_null($this->x)) {
            return '';
        }

        if (Math::mod('0x'.$this->y, '0x02') == '1') {
            return sprintf('03%s', $this->x);
        } else {
            return sprintf('02%s', $this->x);
        }
    }

    /**
     * @param PrivateKey
     */
    public static function createFromPrivateKey(PrivateKey $private)
    {
        $public = new self();
        $public->setPrivateKey($private);

        return $public;
    }

    /**
     * @return KeyInterface
     */
    public function setPrivateKey(PrivateKey $privateKey)
    {
        $this->privateKey = $privateKey;

        return $this;
    }

    /**
     * Generates an uncompressed and compressed EC public key.
     *
     * @param \Bitpay\PrivateKey $privateKey
     *
     * @return Bitpay\PublicKey
     */
    public function generate(PrivateKey $privateKey = null)
    {
        if ($privateKey instanceof PrivateKey) {
            $this->setPrivateKey($privateKey);
        }

        if (!empty($this->hex)) {
            return $this;
        }

        if (is_null($this->privateKey)) {
            throw new \Exception('Please `setPrivateKey` before you generate a public key');
        }

        if (!$this->privateKey->isGenerated()) {
            $this->privateKey->generate();
        }

        if (!$this->privateKey->isValid()) {
            throw new \Exception('Private Key is invalid and cannot be used to generate a public key');
        }

        $point = new Point(
            '0x'.substr(Secp256k1::G, 2, 64),
            '0x'.substr(Secp256k1::G, 66, 64)
        );

        $R = Util::doubleAndAdd(
            '0x'.$this->privateKey->getHex(),
            $point
        );

        $RxHex = Util::encodeHex($R->getX());
        $RyHex = Util::encodeHex($R->getY());

        $RxHex = str_pad($RxHex, 64, '0', STR_PAD_LEFT);
        $RyHex = str_pad($RyHex, 64, '0', STR_PAD_LEFT);

        $this->x   = $RxHex;
        $this->y   = $RyHex;
        $this->hex = sprintf('%s%s', $RxHex, $RyHex);
        $this->dec = Util::decodeHex($this->hex);

        return $this;
    }

    /**
     * Checks to see if the public key is not blank and contains
     * valid decimal and hex valules for this->hex & this->dec
     *
     * @return boolean
     */
    public function isValid()
    {
        return ((!empty($this->hex) && ctype_xdigit($this->hex)) && (!empty($this->dec) && ctype_digit($this->dec)));
    }

    /**
     * @return SinKey
     */
    public function getSin()
    {
        if (empty($this->hex)) {
            $this->generate();
        }

        if (null === $this->sin) {
            $this->sin = new SinKey();
            $this->sin->setPublicKey($this);
            $this->sin->generate();
        }

        return $this->sin;
    }
}


text:
<?php

namespace spec\PhpSpec\Process\ReRunner;

use PhpSpec\ObjectBehavior;
use PhpSpec\Process\Context\ExecutionContextInterface;
use Prophecy\Argument;
use Symfony\Component\Process\PhpExecutableFinder;

class PassthruRerunnerSpec extends ObjectBehavior
{
    function let(PhpExecutableFinder $executableFinder, ExecutionContextInterface $executionContext)
    {
        $this->beConstructedThrough('withExecutionContext', array($executableFinder, $executionContext));
    }

    function it_is_a_rerunner()
    {
        $this->shouldHaveType('PhpSpec\Process\ReRunner');
    }

    function it_is_not_supported_when_php_process_is_not_found(PhpExecutableFinder $executableFinder)
    {
        $executableFinder->find()->willReturn(false);

        $this->isSupported()->shouldReturn(false);
    }
}