text:
package org.winterblade.minecraft.harmony.integration.roots.operations;

import elucent.roots.component.ComponentManager;
import elucent.roots.component.ComponentRecipe;
import org.winterblade.minecraft.harmony.api.BasicOperation;
import org.winterblade.minecraft.harmony.api.Operation;
import org.winterblade.minecraft.harmony.api.OperationException;
import org.winterblade.minecraft.harmony.common.utility.LogHelper;

/**
 * Created by Matt on 7/30/2016.
 */
@Operation(name = "Roots.removeDust", aliases = {"Roots.disableDust"}, dependsOn = "roots")
public class RemoveComponentOperation extends BasicOperation {
    /*
     * Serialized properties
     */
    private String what;

    /*
     * Computed properties
     */
    private transient ComponentRecipe component;

    /**
     * Called to initialize the set
     *
     * @throws OperationException If something went wrong
     */
    @Override
    public void init() throws OperationException {
        component = ComponentManager.getRecipe(what);
        if(component == null) throw new OperationException("Roots.removeDust cannot find dust matching '" + what + "'.");
    }

    /**
     * Called to apply the set (if not player-specific)
     */
    @Override
    public void apply() {
        LogHelper.info("Disabling Roots dust '{}'.", what);
        component.disabled = true;
    }

    /**
     * Called to remove the set (if not player-specific)
     */
    @Override
    public void undo() {
        component.disabled = false;
    }
}


text:
echo
echo "*********************************"
echo "*                               *"
echo "*     RUNNING SETUP COMMON      *"
echo "*                               *"
echo "*********************************"
echo
sleep 3

cd $HOME
if [ -d ./startup/ ]; then
    mv startup startup.old
fi
if [ -d .emacs.d/ ]; then
    mv .emacs.d .emacs.d~
fi

sudo apt-get install -q -y git-core
git clone https://github.com/mvkvl/bootstrap.git

# add 1Gb swap file
# http://www.rownet.co.uk/adding-swap-space-to-an-amazon-ec2-micro-instance/
echo "generating swap...."
sudo dd if=/dev/zero of=/swapfile bs=1M count=1024
sudo mkswap /swapfile
sudo swapon /swapfile
sudo su root
echo "/swapfile  swap      swap    defaults         0 0" >> /etc/fstab
exit

# secure an instance (if username is set)
if [ $EC_USERNAME != "ubuntu" ]; then
  bootstrap/secure.sh
else
# cd /home/ubuntu
# make links for dotfiles
  ln -sb bootstrap/.screenrc .
  ln -sb bootstrap/.bash_profile .
  ln -sb bootstrap/.bashrc .
  ln -sb bootstrap/.bashrc_custom .
  ln -sb bootstrap/.bash_colors .
  ln -sf bootstrap/.emacs.d .
fi

# Install neded packages
sudo apt-get -q -y install htop mc

# https://launchpad.net/~cassou/+archive/emacs
sudo apt-add-repository -y ppa:cassou/emacs
sudo apt-get update
sudo apt-get install -q -y emacs24 emacs24-el emacs24-common-non-dfsg

redpajama_set_name: RedPajamaGithub


text:
package org.robolectric.shadows;

import android.R;
import android.app.Activity;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.Shadows;
import org.robolectric.TestRunners;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(TestRunners.WithDefaults.class)
public class ShadowAnimationUtilsTest {

  @Test
  public void loadAnimation_shouldCreateAnimation() {
    assertThat(AnimationUtils.loadAnimation(Robolectric.setupActivity(Activity.class), R.anim.fade_in)).isNotNull();
  }

  @Test
  public void loadLayoutAnimation_shouldCreateAnimation() {
    assertThat(AnimationUtils.loadLayoutAnimation(Robolectric.setupActivity(Activity.class), 1)).isNotNull();
  }

  @Test
  public void getLoadedFromResourceId_forAnimationController_shouldReturnAnimationResourceId() {
    final LayoutAnimationController anim = AnimationUtils.loadLayoutAnimation(Robolectric.setupActivity(Activity.class), R.anim.fade_in);
    assertThat(Shadows.shadowOf(anim).getLoadedFromResourceId()).isEqualTo(R.anim.fade_in);
  }
}


text:
package Validate::Plugin::IMAGES;

# Called by modip_ipv4, modip_ipv6, modip_ds, and so forth.

use strict;

sub new {
    my $classname = shift;
    my $self      = {};
    bless( $self, $classname );
    $self->{validate}=shift;
    return $self;
}

sub header_to_hash {
  my $self = shift;
  my $s = shift;
  my @list = split(/[\r\n]+/,$s);
  my %hash;
  if ($list[0] !~ /:/) {
    $hash{"Status"} = shift @list;
  }
  foreach my $line (@list ){
    my($a,$b) = split(/: /,$line,2);
    $hash{$a}=$b;
  }
  return %hash;
}

sub comparable {
  my($self) = shift;
  my(%hash) = @_;
  my $s = $hash{"Status"} . "\n";
  if (! $hash{"Exit-Code"}) {
      delete $hash{"Exit-Code"};
          delete $hash{"Exit-Reason"};
            }
              foreach my $a (qw( Content-Type Expires Vary Exit-Code)) {
    $s .= "$a\: $hash{$a}\n" if (exists $hash{$a});
  }
  return $s;
}

sub check {
  my $self = shift;
  my $url = shift;
  my $expected_headers = shift;
       my $validate = $self->{validate};

  my ( $content, $headers ) = $self->{validate}->curl( $url, "--head");
  my($status) = split(/[\r\n]/,$headers);

$DB::single=1 ;
  my %results = $self->header_to_hash($headers);
  my $found = $self->comparable(%results);
  my $expect = $self->comparable($self->header_to_hash($expected_headers));

  my $found_i = $validate->indent($found);
  my $expect_i = $validate->indent($expect);

my $bignotes = <<"EOF";

URL: $url

Please make sure images are installed; are not mapped
to another location on your file system; and have the correct
expiration data.  Expires are handled using mod_expires
plus the apache configuration that came with the falling-sky projoect.

We recommend allowing this virtualhost to override options;
doing so, will allow the bundled .htaccess files to take effect.

https://github.com/falling-sky/source/wiki/InstallContent
https://github.com/falling-sky/source/wiki/InstallApacheVirtualHost
EOF

  if ($found ne $expect) {
    return(status=>"bad",url=>$url,expect=>$expect_i,found=>$found_i,notes=>"One or more headers is missing or wrong." . $bignotes);
  }

  return(status=>"ok",url=>$url,  expect=>$expect_i,found=>$found_i);

}

1;


text:
namespace Moses
{

class KenDsgBase
{
public:
  virtual ~KenDsgBase() {}

  virtual float Score(const lm::ngram::State&, StringPiece,
                      lm::ngram::State&) const = 0;

  virtual const lm::ngram::State &BeginSentenceState() const = 0;

  virtual const lm::ngram::State &NullContextState() const = 0;

  virtual float ScoreEndSentence(const lm::ngram::State &in_state, lm::ngram::State &out_state) const = 0;
};

template <class KenModel>
class KenDsg : public KenDsgBase
{
public:
  KenDsg(const char *file, const lm::ngram::Config &config)
    : m_kenlm(file, config) {}

  float Score(const lm::ngram::State &in_state,
              StringPiece word,
              lm::ngram::State &out_state) const {
    return m_kenlm.Score(in_state, m_kenlm.GetVocabulary().Index(word),
                         out_state);
  }

  const lm::ngram::State &BeginSentenceState() const {
    return m_kenlm.BeginSentenceState();
  }

  const lm::ngram::State &NullContextState() const {
    return m_kenlm.NullContextState();
  }

  float ScoreEndSentence(const lm::ngram::State &in_state, lm::ngram::State &out_state) const {
    return m_kenlm.Score(in_state, m_kenlm.GetVocabulary().EndSentence(), out_state);
  }

private:
  KenModel m_kenlm;
};

typedef KenDsgBase DsgLM;

DsgLM* ConstructDsgLM(const char *file);

} // namespace


text:
typedef struct TICK_COUNTER_INSTANCE_TAG
{
    time_t init_time_value;
    tickcounter_ms_t current_ms;
} TICK_COUNTER_INSTANCE;

TICK_COUNTER_HANDLE tickcounter_create(void)
{
    TICK_COUNTER_INSTANCE* result = (TICK_COUNTER_INSTANCE*)malloc(sizeof(TICK_COUNTER_INSTANCE));
    if (result != NULL)
    {
        result->init_time_value = time(NULL);
        if (result->init_time_value == INVALID_TIME_VALUE)
        {
            LogError("tickcounter failed: time return INVALID_TIME.");
            free(result);
            result = NULL;
        }
        else
        {
            result->current_ms = 0;
        }
    }
    return result;
}

void tickcounter_destroy(TICK_COUNTER_HANDLE tick_counter)
{
    if (tick_counter != NULL)
    {
        free(tick_counter);
    }
}

int tickcounter_get_current_ms(TICK_COUNTER_HANDLE tick_counter, tickcounter_ms_t * current_ms)
{
    int result;

    if (tick_counter == NULL || current_ms == NULL)
    {
        LogError("tickcounter failed: Invalid Arguments.");
        result = __FAILURE__;
    }
    else
    {
        time_t time_value = time(NULL);
        if (time_value == INVALID_TIME_VALUE)
        {
            result = __FAILURE__;
        }
        else
        {
            TICK_COUNTER_INSTANCE* tick_counter_instance = (TICK_COUNTER_INSTANCE*)tick_counter;
            tick_counter_instance->current_ms = (tickcounter_ms_t)(difftime(time_value, tick_counter_instance->init_time_value) * 1000);
            *current_ms = tick_counter_instance->current_ms;
            result = 0;
        }
    }

    return result;
}


text:
package org.switchyard.component.bpm.annotation;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/** WorkItemHandler.
 *
 * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. */
@Target(TYPE)
@Retention(RUNTIME)
@Documented
public @interface WorkItemHandler {

    /** Impl class. */
    public Class<? extends org.kie.api.runtime.process.WorkItemHandler> value();

    /** Name. */
    public String name() default "";

}


text:
import re
import csv
import click
import getpass
import pathlib
import gmusicapi

@click.command()
@click.option('--username', prompt='Google username (usually, email)')
@click.option('--password', prompt='Google password', hide_input=True)
@click.option('--public/--private', default=True)
@click.argument('playlist', type=click.Path(exists=True))
def import_playlist(username, password, public, playlist):
    gmusic = gmusicapi.Mobileclient()
    gmusic.login(username, password, gmusicapi.Mobileclient.FROM_MAC_ADDRESS)

    # Delete an existing playlist if it already exists. This is a bit easier
    # than trying to de-dup tracks.
    playlist_name = pathlib.Path(playlist).stem.replace('_', ' ')
    existing_playlists = {p['name']: p['id'] for p in gmusic.get_all_playlists()}
    if playlist_name in existing_playlists:
        click.confirm('Playlist already exists; continuing will delete it and start over. OK?', abort=True)
        gmusic.delete_playlist(existing_playlists[playlist_name])

    playlist_track_ids = []

    # Technique for finding tracks:
    #   1. search for "{artist} {track}"
    #   2. for each song hit, calcuate a "score" based on how many fields
    #      (track name, artist name, album name, track number) match.
    #   3. choose the highest score

    with click.progressbar(list(csv.DictReader(open(playlist))), label="Finding tracks") as tracks:
        for track in tracks:
            search_results = gmusic.search_all_access('{Artist} {Name}'.format(**track))['song_hits']
            candidates = [r['track'] for r in search_results]
            scored_candidates = []
            for candidate in candidates:
                score = sum([
                    normalize(candidate['album']) == normalize(track['Album']),
                    normalize(candidate['artist']) == normalize(track['Artist']),
                    normalize(candidate['title']) == normalize(track['Name']),
                    str(candidate['trackNumber']) == track['Track Number'],
                ])
                # Don't include tracks with a score of 0.
                if score:
                    scored_candidates.append((score, candidate))

            if not scored_candidates:
                click.secho("Can't find: {Artist} - {Name}".format(**track), fg='yellow')
                continue

            match = max(scored_candidates)[1]
            playlist_track_ids.append(match['storeId'])

        playlist_id = gmusic.create_playlist(playlist_name, public=public)
        gmusic.add_songs_to_playlist(playlist_id, playlist_track_ids)

def normalize(s):
    return re.sub(r'\(.*?\)', '', s.lower()).strip()

if __name__ == '__main__':
    import_playlist()


text:
Although both categories and extensions are used to add new methods and properties to an existing class. But, Swift extension and Objective-C category are a little different.

- You can't create an instance of a category in Objective C. But in swift, we can create an instance of an extension.
- In Objective-C, we wrote **only declarations** of methods in ```.h``` file. They were by-default **public**.
- To have more methods into already existing class, we used to write the **definition** (not declaration) of those new methods directly into the ```.m``` file. They were by-default **private**.
- To have declaration of these new methods, we can't add them to ```.h``` or ```.m``` file. We have to create a ```category``` above the ```.m``` file itself, and then add the **declaration** of the new methods in the category.
- The main difference is that with an extension, the compiler will expect you to implement the methods within your `main @implementation`, whereas with a category you have a `separate @implementation` block. So you should pretty much only use an extension at the `top of your main .m` file (the only place you should care about ivars, incidentally) - it's meant to be just that, an extension.

----

**Class Category VS Class Extension**

`Class Category of Obj C` is same as `Extension of Swift` - We define additional methods in a file, and can use it anywhere in the project.

But `Class Extension of Obj C` means the file where I am declaring the extension, it remains private to that file. We can only use the additional methods in that file, and no where else on the project.

----

1. **Class Category:**
	- In objective c, when you want to add some more functionality to a class without inheritance, you simply use category for it.
	- It come with its own .h and .m file
	- Category is used to add new methods not properties.

2. **Class Extension**
	- In objective c, when you want to make behavior of some property private, you use class extension.
	- It comes with .m file only.
	- It is used mainly for properties.

----

**Note:**

Ques: Can we create an instance of category?
Ans: No. We can't create an instance of a category.

Ques: Can we access the category method in subclasses?
Ans: Yes. We can access the category method in subclasses.

Ques: Can Extensions in Swift be used to add stored properties?
Ans: No. We can only add methods to an extension, not stored properties.


text:
ALTER TABLE {$NAMESPACE}_project.project
  ADD isMembershipLocked TINYINT(1) NOT NULL DEFAULT 0 AFTER joinPolicy;


text:
package com.thinkgem.jeesite.modules.prho.dao;

import java.util.List;

import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.modules.prho.entity.PrhoProjectDevelopSpeed;

/**
 * 项目开发速度分析DAO接口
 * @author zhl
 * @version 2017-06-01
 */
@MyBatisDao
public interface PrhoProjectDevelopSpeedDao extends CrudDao<PrhoProjectDevelopSpeed> {
	public List<PrhoProjectDevelopSpeed> findPageBy(PrhoProjectDevelopSpeed prhoProjectDevelopSpeed);
}


text:
package me.alert.resources;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;

import me.alert.dao.AlertDataDao;
import me.alert.dto.AlertDataDto;

@Path("/alert")
public class AlertResource {
	private AlertDataDao alertDao;

	public AlertResource(AlertDataDao alertDao) {
		this.alertDao = alertDao;
	}

	@POST
	@Path("/add")
	@Consumes(MediaType.APPLICATION_JSON)
	public void addNewAlert(AlertDataDto alertData) {
		alertDao.addNewAlert(alertData);
	}
}


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))

require 'mocha'
require 'rulebook'

# Require all files within /support
Dir[File.expand_path('../support/**/*.rb', __FILE__)].each { |f| require f }


text:
var Instance, chainable, helpers, _,
  __hasProp = {}.hasOwnProperty;

_ = require('./lodash.js');

chainable = (helpers = require('./helpers')).chainable;

module.exports = Instance = (function() {
  function Instance(template, Transparency) {
    this.Transparency = Transparency;
    this.queryCache = {};
    this.childNodes = _.toArray(template.childNodes);
    this.elements = helpers.getElements(template);
  }

  Instance.prototype.remove = chainable(function() {
    var node, _i, _len, _ref, _results;
    _ref = this.childNodes;
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      node = _ref[_i];
      _results.push(node.parentNode.removeChild(node));
    }
    return _results;
  });

  Instance.prototype.appendTo = chainable(function(parent) {
    var node, _i, _len, _ref, _results;
    _ref = this.childNodes;
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      node = _ref[_i];
      _results.push(parent.appendChild(node));
    }
    return _results;
  });

  Instance.prototype.prepare = chainable(function(model) {
    var element, _i, _len, _ref, _results;
    _ref = this.elements;
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      element = _ref[_i];
      element.reset();
      _results.push(helpers.data(element.el).model = model);
    }
    return _results;
  });

  Instance.prototype.renderValues = chainable(function(model, children) {
    var element, key, value, _results;
    if (_.isElement(model) && (element = this.elements[0])) {
      return element.empty().el.appendChild(model);
    } else if (typeof model === 'object') {
      _results = [];
      for (key in model) {
        if (!__hasProp.call(model, key)) continue;
        value = model[key];
        if (value != null) {
          if (_.isString(value) || _.isNumber(value) || _.isBoolean(value) || _.isDate(value)) {
            _results.push((function() {
              var _i, _len, _ref, _results1;
              _ref = this.matchingElements(key);
              _results1 = [];
              for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                element = _ref[_i];
                _results1.push(element.render(value));
              }
              return _results1;
            }).call(this));
          } else if (typeof value === 'object') {
            _results.push(children.push(key));
          } else {
            _results.push(void 0);
          }
        }
      }
      return _results;
    }
  });

  Instance.prototype.renderDirectives = chainable(function(model, index, directives) {
    var attributes, element, key, _results;
    _results = [];
    for (key in directives) {
      if (!__hasProp.call(directives, key)) continue;
      attributes = directives[key];
      if (!(typeof attributes === 'object')) {
        continue;
      }
      if (typeof model !== 'object') {
        model = {
          value: model
        };
      }
      _results.push((function() {
        var _i, _len, _ref, _results1;
        _ref = this.matchingElements(key);
        _results1 = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          element = _ref[_i];
          _results1.push(element.renderDirectives(model, index, attributes));
        }
        return _results1;
      }).call(this));
    }
    return _results;
  });

  Instance.prototype.renderChildren = chainable(function(model, children, directives, options) {
    var element, key, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = children.length; _i < _len; _i++) {
      key = children[_i];
      _results.push((function() {
        var _j, _len1, _ref, _results1;
        _ref = this.matchingElements(key);
        _results1 = [];
        for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
          element = _ref[_j];
          _results1.push(this.Transparency.render(element.el, model[key], directives[key], options));
        }
        return _results1;
      }).call(this));
    }
    return _results;
  });

  Instance.prototype.matchingElements = function(key) {
    var el, elements, _base;
    elements = (_base = this.queryCache)[key] || (_base[key] = (function() {
      var _i, _len, _ref, _results;
      _ref = this.elements;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        el = _ref[_i];
        if (this.Transparency.matcher(el, key)) {
          _results.push(el);
        }
      }
      return _results;
    }).call(this));
    helpers.log("Matching elements for '" + key + "':", elements);
    return elements;
  };

  return Instance;

})();


text:
package org.apache.asterix.algebra.base;

public interface OperatorAnnotation {
    String FIELD_ACCESS = "FIELD_ACCESS";
    String PUSHED_FIELD_ACCESS = "PUSHED_FIELD_ACCESS";
    String PUSHED_RUNNABLE_FIELD_ACCESS = "PUSHED_RUNNABLE_FIELD_ACCESS";
    String FIELD_TYPE = "FIELD_TYPE";
}


text:
/* jshint node: true */
/* jshint jquery: true */
/* jshint sub: true */
/* global window,document, $,alert,history */
'use strict';

var log = function(msg)
{
  console.log('map:', msg);
};

//----------

var _ = require('lodash');

var map = function(f)
{
  log('--spacetimeline-map-');
  var W = this.W;

  var preObj = this;
  var newObj = _.cloneDeep(preObj);

  W.watch(preObj, 'beacon', function()
  {
    newObj.val = f(preObj.val);
    newObj.beacon = preObj.beacon;
  });

  return newObj;
};

module.exports = map;


text:
package project.addmoto.model;

import java.awt.Image;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import project.addmoto.custom.ExceptionDialog;
import project.addmoto.data.ProductLine;
import project.addmoto.data.Products;
import project.addmoto.data.Supplier;
import project.addmoto.database.Database;

/**
 *
 * @author Kim Howel delos Reyes
 */
public class InventoryModel {

    private final Connection connection;
    private String query;
    private Statement statement;
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;

    public InventoryModel(final Connection connection) {
        this.connection = connection;

        System.out.println("Inventory model is called.");
    }

    public ArrayList<ProductLine> getProductLines() {
        ArrayList<ProductLine> productLines = new ArrayList<>();

        try {
            query = "SELECT * FROM " + Database.PRODUCT_LINE_TABLE + ";";

            statement = connection.createStatement();
            resultSet = statement.executeQuery(query);
            while(resultSet.next()) {
                int productLineID = resultSet.getInt(Database.PRODUCT_LINE_ID);
                String productLineName = resultSet.getString(Database.PRODUCT_LINE_NAME);

                productLines.add(
                        new ProductLine(productLineID, productLineName));
            }
        } catch(Exception e) {
            e.printStackTrace();
        }

        return productLines;
    }

    public int insertNewProductLine(String productLine) {
        try {
            query = "INSERT INTO " + Database.PRODUCT_LINE_TABLE +
                    " (" + Database.PRODUCT_LINE_NAME + ") VALUES(?);";

            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setString(1, productLine);

            return preparedStatement.executeUpdate();
        } catch(Exception e) {
            return 0;
        }
    }

    public ArrayList<Supplier> getSuppliers() {
        ArrayList<Supplier> suppliers = new ArrayList<>();

        try {
            query = "SELECT * FROM " + Database.SUPPLIER_TABLE + ";";

            statement = connection.createStatement();
            resultSet = statement.executeQuery(query);
            while(resultSet.next()) {
                int supplierID = resultSet.getInt(Database.SUPPLIER_ID);
                String supplierName = resultSet.getString(Database.SUPPLIER_NAME);
                String supplierCity = resultSet.getString(Database.SUPPLIER_CITY);
                String supplierCountry = resultSet.getString(Database.SUPPLIER_COUNTRY);
                String supplierAddress = resultSet.getString(Database.SUPPLIER_ADDRESS);
                int supplierPostal = resultSet.getInt(Database.SUPPLIER_POSTAL);

                suppliers.add(
                        new Supplier(supplierID, supplierName, supplierCity,
                                supplierCountry, supplierAddress, supplierPostal));
            }
        } catch(Exception e) {
            e.printStackTrace();
        }

        return suppliers;
    }

    public ArrayList<Products> getProducts() {
        ArrayList<Products> products = new ArrayList<>();

        try {
            query = "SELECT * FROM " + Database.PRODUCTS_TABLE + ";";

            statement = connection.createStatement();
            resultSet = statement.executeQuery(query);
            while(resultSet.next()) {
                int productID = resultSet.getInt(Database.PRODUCT_ID);
                String addMotoCode = resultSet.getString(Database.PRODUCT_ADDMOTO_CODE);
                String supplierCode = resultSet.getString(Database.PRODUCT_SUPPLIER_CODE);
                int quantity = resultSet.getInt(Database.PRODUCT_CURRENT_QUANTITY);
                double unitPrice = resultSet.getDouble(Database.PRODUCT_UNIT_PRICE);
                double sellingPrice = resultSet.getDouble(Database.PRODUCT_SELLING_PRICE);
                double profitMargin = resultSet.getDouble(Database.PRODUCT_PROFIT_MARGIN);
                int threshold = resultSet.getInt(Database.PRODUCT_THRESHOLD_COUNT);
                Image image = null;
                String description = resultSet.getString(Database.PRODUCT_DESCRIPTION);
                String characteristics = resultSet.getString(Database.PRODUCT_CHARACTERISTICS);
                String models = resultSet.getString(Database.PRODUCT_MOTORS);
                int productLineID = resultSet.getInt(Database.PRODUCT_LINE_ID_FK);
                int supplierID = resultSet.getInt(Database.SUPPLIER_SUPPLIER_ID_FK);

                products.add(
                        new Products(productID, addMotoCode, supplierCode,
                                quantity, unitPrice, sellingPrice,
                                profitMargin, threshold, image,
                                description, characteristics, models,
                                productLineID, supplierID));
            }
        } catch(Exception e) {
            e.printStackTrace();
        }

        return products;
    }

    public int addNewProduct(Products product) {
        try {
            query = "INSERT INTO " + Database.PRODUCTS_TABLE + " ("
                    + Database.PRODUCT_ADDMOTO_CODE + ", " + Database.PRODUCT_SUPPLIER_CODE + ", "+ Database.PRODUCT_CURRENT_QUANTITY + ", "
                    + Database.PRODUCT_UNIT_PRICE + ", " + Database.PRODUCT_SELLING_PRICE + ", " + Database.PRODUCT_PROFIT_MARGIN + ", "
                    + Database.PRODUCT_THRESHOLD_COUNT + ", " +  Database.PRODUCT_DESCRIPTION + ", " +  Database.PRODUCT_CHARACTERISTICS + ", "
                    + Database.PRODUCT_MOTORS + ", " + Database.PRODUCT_LINE_ID_FK + ", " + Database.PRODUCT_SUPPLIER_ID_FK
                    + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setString(1, product.getAddmotoCode());
            preparedStatement.setString(2, product.getSupplierCode());
            preparedStatement.setInt(3, product.getCurrentQuantity());
            preparedStatement.setDouble(4, product.getUnitPrice());
            preparedStatement.setDouble(5, product.getSellingPrice());
            preparedStatement.setDouble(6, product.getProfitMargin());
            preparedStatement.setInt(7, product.getThresholdCount());
            preparedStatement.setString(8, product.getDescription());
            preparedStatement.setString(9, product.getCharacteristics());
            preparedStatement.setString(10, product.getMotors());
            preparedStatement.setInt(11, product.getProductLineID());
            preparedStatement.setInt(12, product.getSupplierID());
            return preparedStatement.executeUpdate();
        } catch(Exception exc) {
            exc.printStackTrace();
        }
        return 0;
    }

    public int updateSellingPrice(int itemID, double sellingPrice) {
        try {
            query = "UPDATE " + Database.PRODUCTS_TABLE + " SET " + Database.PRODUCT_SELLING_PRICE +
                    " = ? WHERE " + Database.PRODUCT_ID + " = ?;";

            preparedStatement = connection.prepareCall(query);
            preparedStatement.setDouble(1, sellingPrice);
            preparedStatement.setInt(2, itemID);

            return preparedStatement.executeUpdate();
        } catch(Exception exc) {
            return 0;
        }
    }

    public int updateUnitPrice(int itemID, double unitPrice) {
        try {
            query = "UPDATE " + Database.PRODUCTS_TABLE + " SET " + Database.PRODUCT_UNIT_PRICE +
                    " = ? WHERE " + Database.PRODUCT_ID + " = ?;";

            preparedStatement = connection.prepareCall(query);
            preparedStatement.setDouble(1, unitPrice);
            preparedStatement.setInt(2, itemID);

            return preparedStatement.executeUpdate();
        } catch(Exception exc) {
            return 0;
        }
    }

    public int updateThreshold(int itemID, int threshold) {
        try {
            query = "UPDATE " + Database.PRODUCTS_TABLE + " SET " + Database.PRODUCT_THRESHOLD_COUNT +
                    " = ? WHERE " + Database.PRODUCT_ID + " = ?;";

            preparedStatement = connection.prepareCall(query);
            preparedStatement.setDouble(1, threshold);
            preparedStatement.setInt(2, itemID);

            return preparedStatement.executeUpdate();
        } catch(Exception exc) {
            return 0;
        }
    }
}


text:
<?php

class jigoshop_product_meta
{
	public function __construct() {
		add_action( 'jigoshop_process_product_meta', array(&$this, 'save'), 1, 2 );
	}

	public function save($post_id)
	{
		// Set the product type
		wp_set_object_terms($post_id, sanitize_title($_POST['product-type']), 'product_type');

		// Process general product data
		$regular_price = 0.0;
		if(isset($_POST['regular_price'])){
			if($_POST['regular_price'] != ''){
				$regular_price = jigoshop_sanitize_num($_POST['regular_price']);
			} else {
				$regular_price = '';
			}
		}
		update_post_meta($post_id, 'regular_price', $regular_price);

		$sale_price = !empty($_POST['sale_price'])
			? (!strstr($_POST['sale_price'], '%') ? jigoshop_sanitize_num($_POST['sale_price']) : $_POST['sale_price'])
			: '';

		if (strstr($_POST['sale_price'], '%')) {
			update_post_meta($post_id, 'sale_price', $sale_price);
		} else if (!empty($sale_price) && $sale_price < $regular_price) {
			update_post_meta($post_id, 'sale_price', $sale_price);
		} else {
			// silently fail if entered sale price > regular price (or nothing entered)
			update_post_meta($post_id, 'sale_price', '');
		}
		// finally, if this product is a 'variable' or 'grouped', then there should never be a sale_price here
		// perhaps it was a 'simple' product once and was changed (see rhr #437)
		$terms = wp_get_object_terms($post_id, 'product_type');
		if (!empty($terms)) {
			if (!is_wp_error($terms)) {
				if (sizeof($terms) == 1) {
					if (in_array($terms[0]->slug, array('variable', 'grouped'))) {
						delete_post_meta($post_id, 'sale_price');
					}
				}
			}
		}

		if (isset($_POST['weight'])) {
			update_post_meta($post_id, 'weight', (float)$_POST['weight']);
		}
		if (isset($_POST['length'])) {
			update_post_meta($post_id, 'length', (float)$_POST['length']);
		}
		if (isset($_POST['width'])) {
			update_post_meta($post_id, 'width', (float)$_POST['width']);
		}
		if (isset($_POST['height'])) {
			update_post_meta($post_id, 'height', (float)$_POST['height']);
		}

		update_post_meta($post_id, 'tax_status', $_POST['tax_status']);
		update_post_meta($post_id, 'tax_classes', isset($_POST['tax_classes']) ? $_POST['tax_classes'] : array());

		update_post_meta($post_id, 'visibility', $_POST['product_visibility']);
		update_post_meta($post_id, 'featured', isset($_POST['featured']));
		update_post_meta($post_id, 'customizable', $_POST['product_customize']);
		update_post_meta($post_id, 'customized_length', $_POST['customized_length']);

		// Downloadable Only
		if ($_POST['product-type'] == 'downloadable') {
			update_post_meta($post_id, 'file_path', $_POST['file_path']);
			update_post_meta($post_id, 'download_limit', $_POST['download_limit']);
		}

		// Process the SKU
		if (Jigoshop_Base::get_options()->get('jigoshop_enable_sku') !== 'no') {
			($this->is_unique_sku($post_id, $_POST['sku']))
				? update_post_meta($post_id, 'sku', $_POST['sku'])
				: delete_post_meta($post_id, 'sku');
		}
		// Process the Brand
		if (Jigoshop_Base::get_options()->get('jigoshop_enable_brand') !== 'no') {
			($this->is_unique_sku($post_id, $_POST['brand']))
				? update_post_meta($post_id, 'brand', $_POST['brand'])
				: delete_post_meta($post_id, 'brand');
		}
		// Process the GTIN
		if (Jigoshop_Base::get_options()->get('jigoshop_enable_gtin') !== 'no') {
			($this->is_unique_sku($post_id, $_POST['gtin']))
				? update_post_meta($post_id, 'gtin', $_POST['gtin'])
				: delete_post_meta($post_id, 'gtin');
		}
		// Process the MPN
		if (Jigoshop_Base::get_options()->get('jigoshop_enable_mpn') !== 'no') {
			($this->is_unique_sku($post_id, $_POST['mpn']))
				? update_post_meta($post_id, 'mpn', $_POST['mpn'])
				: delete_post_meta($post_id, 'mpn');
		}

		// Process the attributes
		update_post_meta($post_id, 'product_attributes', $this->process_attributes($_POST, $post_id));

		// Process the stock information
		$stockresult = $this->process_stock($_POST);
		if (is_array($stockresult)) {
			foreach ($stockresult as $key => $value) {
				update_post_meta($post_id, $key, $value);
			}
		}

		if ($_POST['product-type'] == 'external') {
			update_post_meta($post_id, 'external_url', $_POST['external_url']);
			update_post_meta($post_id, 'stock_status', 'instock');
			update_post_meta($post_id, 'manage_stock', false);
		}

		// Process the sale dates
		foreach ($this->process_sale_dates($_POST, $post_id) as $key => $value) {
			update_post_meta($post_id, $key, $value);
		}

		// Do action for product type
		do_action('jigoshop_process_product_meta_'.$_POST['product-type'], $post_id);
	}

	/**
	 * Processes the sale dates
	 *
	 * @param   array $post The postback
	 * @return  array
	 **/
	private function process_sale_dates( array $post, $post_id ) {

		// Set the default values
		$array = array(
			'sale_price_dates_from'  => false,
			'sale_price_dates_to'    => false,
		);

		// If our product is grouped remove the dates
		if( $post['product-type'] !== 'grouped' ) {

			// Only set sale dates if we have an end
			// Set start as current time if null
			if( $sale_end = strtotime($post['sale_price_dates_to']) ) {
				$sale_start	= ($post['sale_price_dates_from'])
					? strtotime($post['sale_price_dates_from'])
					: current_time('timestamp');

				$array['sale_price_dates_from'] = $sale_start;
				$array['sale_price_dates_to']   = $sale_end;
				$this->grouped_sale_dates($array, $post_id);
			}
		}

		return $array;
	}

	/**
	 * Check if product is in group and update sale dates meta of group
	 *
	 * @param array $dates Sale Dates
	 * @param $post_id Post ID
	 */
	private function grouped_sale_dates (array $dates, $post_id)
	{
		$post = get_post($post_id);

		//Process only if product has parent
		if ($post->post_parent != '0') {
			$parent = get_post($post->post_parent);

			//Check if parent is grouped
			if ($parent->post_name == 'grouped') {
				$meta = get_post_meta($parent->ID);

				//Update if current 'sale date from' is earlier than stored or is null
				if ($dates['sale_price_dates_from'] < $meta['sale_price_dates_from'][0] || $meta['sale_price_dates_from'][0] == null) {
					update_post_meta($parent->ID, 'sale_price_dates_from', $dates['sale_price_dates_from']);
				}

				//Update if current 'sale date to' is later than stored or is null
				if ($dates['sale_price_dates_to'] > $meta['sale_price_dates_to'][0] || $meta['sale_price_dates_to'][0] == null) {
					update_post_meta($parent->ID, 'sale_price_dates_to', $dates['sale_price_dates_to']);
				}
			}
		}
	}

	/**
	 * Processes the stock options
	 *
	 * @param   array   The postback
	 * @return  array
	 **/
	private function process_stock( array $post ) {

        $jigoshop_options = Jigoshop_Base::get_options();

		// If the global stock switch is off
		if ( !$jigoshop_options->get('jigoshop_manage_stock') )
			return false;

		// Don't hold stock info for external & grouped products
		if( $post['product-type'] === 'external' || $post['product-type'] === 'grouped' )
			return false;

		// Always return the stock switch
		$array = array(
			'manage_stock' 	=> isset($post['manage_stock']),
			'stock_status'  => isset($post['stock_status']) ? $post['stock_status'] : 0
		);

		// Store suitable stock data
		if( $array['manage_stock'] ) {
			$array['stock']        = absint( $post['stock'] );
			$array['backorders']   = $post['backorders']; // should have a space
			$array['stock_status'] = -1; // Discount if stock is managed
			if ( $jigoshop_options->get( 'jigoshop_hide_no_stock_product' ) == 'yes' ) {
				if ( $array['stock'] <= $jigoshop_options->get( 'jigoshop_notify_no_stock_amount' ) ) {
					if ( $post['product-type'] <> 'grouped' && $post['product-type'] <> 'variable' ) {
						update_post_meta( $post['ID'], 'visibility', 'hidden' );
					} else {
						// how to handle grouped and variable?  for now, ensure they are visible
						update_post_meta( $post['ID'], 'visibility', $_POST['product_visibility'] );
					}
				}
			}
		}

		return $array;
	}

	/**
	 * Check if an SKU is unique to both the posts & post_meta tables
	 *
	 * @param   $post_id   Post ID
	 * @param   $new_sku   The SKU to be checked
	 * @return  boolean
	 **/
	private function is_unique_sku( $post_id, $new_sku ) {
		global $wpdb;

		// Check for an SKU value
		if ( ! $new_sku )
			return false;

		// Skip check if sku is the same
		if( $new_sku === get_post_meta( $post_id, 'sku', true ) )
			return true;

		// Check that the new sku does not already exist as a meta value or a post ID
		$_unique_meta    = $wpdb->prepare("SELECT COUNT(1) FROM $wpdb->postmeta WHERE meta_key = 'sku' AND meta_value = %s", $new_sku);
		$_unique_post_id = $wpdb->prepare("SELECT COUNT(1) FROM $wpdb->posts WHERE ID = %s AND ID != %s AND post_type = 'product'", $new_sku, $post_id);

		if ( $wpdb->get_var($_unique_meta) || $wpdb->get_var($_unique_post_id) )
			return new WP_Error( 'jigoshop_unique_sku', __('Product SKU must be unique', 'jigoshop') );

		return true;
	}

	/**
	 * Processes the attribute data from postback into an array
	 *
	 * TODO: increase efficiency of this function
	 *
	 * @param   $post      the postback
	 * @param   $post_id   Post ID
	 * @return  array
	 **/
	private function process_attributes( array $post, $post_id ) {

		if ( ! isset($_POST['attribute_values']) )
			return false;

		$attr_names      = $post['attribute_names'];
		$attr_values     = $post['attribute_values'];
		$attr_visibility = isset($post['attribute_visibility']) ? $post['attribute_visibility'] : null;
		$attr_variation  = isset($post['attribute_variation']) ? $post['attribute_variation'] : null;
		$attr_is_tax     = $post['attribute_is_taxonomy'];
		$attr_position   = $post['attribute_position'];

		// Create empty attributes array
		$attributes = array();

		foreach( $attr_values as $key => $value ) {

			// Skip if no value
			if ( empty( $value )) continue;

			$has_tax = false;

			if ( ! is_array( $value ) && isset( $attr_variation[$key] ) && $attr_variation[$key] ) {
			 	$value = explode( ',', $value );
			 	$value = array_map( 'trim', $value );
			 	$value = implode( ', ', $value );
			} else if ( ! is_array( $value ) ) {
				$value = trim( $value );
			}

			// If attribute is standard then create the relationship
			if ( $attr_is_tax[$key] && taxonomy_exists('pa_'.sanitize_title($attr_names[$key])) ) {
				wp_set_object_terms( $post_id, $value, 'pa_'.sanitize_title($attr_names[$key]) );
				$has_tax = true;
			}

			$attributes[ sanitize_title($attr_names[$key]) ] = array(
				'name'        => $attr_names[$key],
				'value'       => $value,
				'position'    => $attr_position[$key],
				'visible'     => isset( $attr_visibility[$key] ),
				'variation'   => isset( $attr_variation[$key] ) ? $attr_variation[$key] : null,
				'is_taxonomy' => $has_tax
			);
		}

		// Sort by position & return
		uasort($attributes, array($this, 'sort_attributes'));
		return $attributes;
	}

	/**
	 * Callback function to help sort the attributes array by position
	 *
	 * @param   $a   Master comparable
	 * @param   $b   Slave comparable
	 * @return  int
	 **/
	private function sort_attributes( $a, $b ) {
		if ($a['position'] == $b['position'])
			return 0;
		return ($a['position'] < $b['position']) ? -1 : 1;
	}
} new jigoshop_product_meta();


text:
using namespace std;

void TestCodeLinkedList(){
	CLinkedList linkedList;
	linkedList.InsertItemOnLast(0);
	linkedList.InsertItemOnLast(3);
	linkedList.InsertItemOnLast(5);
	linkedList.InsertItemOnLast(7);
	linkedList.InsertItemOnLast(9);
	linkedList.PrintItemList();
	linkedList.InsertItem(1);
	linkedList.PrintItemList();
	linkedList.DeleteItem(0);
	linkedList.PrintItemList();
}

void TestCodeStack(){
	CStack<int> stack;
	stack.Push(1);
	stack.Push(2);
	stack.Push(3);
	stack.Push(4);
	stack.Push(5);
	stack.Push(6);
	stack.PrintItemList();
	stack.Pop();
	stack.PrintItemList();
}

int main(int argc, char* argv[]) {
	cout << "Hello, goorm!" << endl;

	//TestCodeLinkedList();
	TestCodeStack();

	return 0;
}


text:
package ch.raffael.util.common.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Raffael Herzog
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
@Documented
public @interface Singleton {

}


text:
    Bundle is not maintained anymore, but mostly works because of its simplicity.

[Loggly](http://loggly.com/) handler for [Monolog](https://github.com/Seldaek/monolog) as a Symfony bundle.

The bundle is inspired from [Monologgly](https://github.com/pradador/Monologgly)

## Installation

Deps

    [WhitewashingLogglyBundle]
        git=https://github.com/beberlei/WhitewashingLogglyBundle.git
        target=/bundles/Whitewashing/Bundle/LogglyBundle

Kernel

    $bundles = array(
        //..
        new Whitewashing\Bundle\LogglyBundle\WhitewashingLogglyBundle(),
    );

Autoload:

    $loader->registerNamespaces(array(
        //..
        'Whitewashing' => __DIR__.'/../vendor/bundles',
    ));

## Configuration

Configure Monolog

    monolog:
        handlers:
            main:
                type:         fingers_crossed
                action_level: error
                handler:      loggly
            loggly:
                type: service
                id: whitewashing_loggly.monolog_handler

Configure Loggly:

    whitewashing_loggly:
        # Loggly input key
        key: abcdefg

        # Loggly API host
        host: logs.loggly.com

        # Loggly API port (443 for HTTPS, 80 for HTTP)
        port: 443

        # Level to be logged (defaults to DEBUG)
        level: DEBUG

        bubble: true


text:
'use strict';

import fetch from 'node-fetch';
import {parseString} from 'xml2js';

const counties = {};
const townships = {
  ToufenTownship: '頭份鎮',
  TaoyuanDistrict: '桃園區'
};

export default fetch('http://download.post.gov.tw/post/download/county_h_10603.xml')
  .then(res => res.text())
  .then(body => new Promise((resolve, reject) => parseString(
    body,
    (err, {dataroot}) => {
      /* istanbul ignore if */
      if(err)
        return reject(err);

      const {county_h_10508} = dataroot;

      county_h_10508.forEach(data => {
        const chi = data['欄位2'][0];
        const eng = data['欄位3'][0].split(', ');
        const countyChiName = chi.slice(0, 3);
        const townshipChiName = chi.slice(3);
        const countyEngName = eng[eng[1] ? 1: 0].replace(/ /g, '');
        const townshipEngName = eng[0].replace(/\.| |'/g, '');

        counties[countyEngName] = countyChiName;
        townships[townshipEngName] = townshipChiName;
      });

      resolve({
        counties,
        townships
      });
    }
  )));


text:
package fi.nls.oskari.control.feature;

import fi.nls.oskari.annotation.Oskari;
import fi.nls.oskari.cache.CacheManager;
import fi.nls.oskari.cache.ComputeOnceCache;
import fi.nls.oskari.domain.User;
import fi.nls.oskari.domain.map.OskariLayer;
import fi.nls.oskari.domain.map.analysis.Analysis;
import fi.nls.oskari.map.analysis.service.AnalysisDataService;
import fi.nls.oskari.map.analysis.service.AnalysisDbService;
import fi.nls.oskari.service.OskariComponentManager;
import fi.nls.oskari.util.PropertyUtil;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory;
import org.opengis.filter.expression.Expression;
import org.oskari.geojson.GeoJSONFeatureCollection;
import org.oskari.permissions.PermissionService;
import org.oskari.permissions.model.PermissionType;
import org.oskari.permissions.model.ResourceType;
import org.oskari.service.user.UserLayerService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Oskari
public class AnalysisWFSHelper extends UserLayerService {

    public static final String PROP_ANALYSIS_BASELAYER_ID = "analysis.baselayer.id";
    public static final String PREFIX_ANALYSIS = "analysis_";

    protected static final String ATTR_GEOMETRY = "geometry";
    private static final String ATTR_LAYER_ID = "analysis_id";

    private static final List<String> HIDDEN_PROPERTIES = Arrays.asList(ATTR_LAYER_ID, "created", "bbox", "uuid");

    private FilterFactory ff;
    private int analysisLayerId;
    private AnalysisDbService service;
    private ComputeOnceCache<Set<String>> permissionsCache;

    public AnalysisWFSHelper() {
        init();
    }

    public void init() {
        this.ff = CommonFactoryFinder.getFilterFactory();
        this.analysisLayerId = PropertyUtil.getOptional(PROP_ANALYSIS_BASELAYER_ID, -2);

        // One minute cache to get most of the requests from going to db but also a workaround the issue that:
        // FIXME: this is not the right place to cache permissions.
        long expireInOneMinute = 60L * 1000L;
        permissionsCache = CacheManager.getCache(getClass().getName(),() -> new ComputeOnceCache<>(100, expireInOneMinute));
    }

    public int getBaselayerId() {
        return analysisLayerId;
    }

    public boolean isUserContentLayer(String layerId) {
        return layerId.startsWith(PREFIX_ANALYSIS);
    }

    public int parseId(String layerId) {
        return Integer.parseInt(layerId.substring(layerId.lastIndexOf('_') + 1));
    }

    public Filter getWFSFilter(String analysisLayerId, ReferencedEnvelope bbox) {
        int layerId = parseId(analysisLayerId);
        Expression _layerId = ff.property(ATTR_LAYER_ID);

        Filter userlayerIdEquals = ff.equals(_layerId, ff.literal(layerId));

        Filter bboxFilter = ff.bbox(ATTR_GEOMETRY,
                bbox.getMinX(), bbox.getMinY(),
                bbox.getMaxX(), bbox.getMaxY(),
                CRS.toSRS(bbox.getCoordinateReferenceSystem()));

        return ff.and(Arrays.asList(userlayerIdEquals, bboxFilter));
    }

    public boolean hasViewPermission(String id, User user) {
        int layerId = parseId(id);
        final Analysis layer = getLayer(layerId);
        if (layer == null) {
            return false;
        }
        if (layer.isOwnedBy(user.getUuid())) {
            return true;
        }

        // caching for permissions
        final Set<String> permissions = getPermissionsForUser(user);
        return permissions.contains("analysis+" + layerId);
    }

    private Set<String> getPermissionsForUser(User user) {
        return permissionsCache.get(Long.toString(user.getId()),
                __ ->
                        OskariComponentManager.getComponentOfType(PermissionService.class).getResourcesWithGrantedPermissions(
                                ResourceType.analysislayer, user, PermissionType.VIEW_PUBLISHED));
    }

    protected Analysis getLayer(int id) {
        if (service == null) {
            // might cause problems with timing of components being initialized if done in init/constructor
            service = OskariComponentManager.getComponentOfType(AnalysisDbService.class);
        }
        return service.getAnalysisById(id);
    }
    protected OskariLayer getBaseLayer() {
        return AnalysisDataService.getBaseLayer();
    }

    public SimpleFeatureCollection postProcess(SimpleFeatureCollection sfc) throws Exception {
        List<SimpleFeature> fc = new ArrayList<>();
        SimpleFeatureType schema;

        try (SimpleFeatureIterator it = sfc.features()) {
            if (!it.hasNext()) {
                return sfc;
            }
            SimpleFeature ftr = it.next();
            schema = createType(sfc.getSchema(), ftr);
            SimpleFeatureBuilder builder = new SimpleFeatureBuilder(schema);
            List<AttributeDescriptor> attributes = schema.getAttributeDescriptors();
            attributes.stream().forEach(attr ->
                    builder.set(attr.getLocalName(), ftr.getAttribute(attr.getLocalName())));
            fc.add(builder.buildFeature(ftr.getID()));

            while (it.hasNext()) {
                SimpleFeature f = it.next();
                attributes.stream().forEach(attr ->
                        builder.set(attr.getLocalName(), f.getAttribute(attr.getLocalName())));
                fc.add(builder.buildFeature(f.getID()));
            }
        }

        return new GeoJSONFeatureCollection(fc, schema);
    }

    private SimpleFeatureType createType(SimpleFeatureType schema, SimpleFeature f) {
        SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
        typeBuilder.setName(schema.getName());
        typeBuilder.setDefaultGeometry(schema.getGeometryDescriptor().getLocalName());
        f.getFeatureType().getAttributeDescriptors().stream()
                .filter(attr -> isVisibleProperty(attr.getLocalName()))
                .forEach(attr -> typeBuilder.add(attr));
        return typeBuilder.buildFeatureType();
    }

    private boolean isVisibleProperty(String name) {
        return HIDDEN_PROPERTIES.stream().noneMatch(propName -> propName.equals(name));
    }
}


text:
<?xml version="1.0"?>

<!DOCTYPE suppressions PUBLIC
    "-//Puppy Crawl//DTD Suppressions 1.1//EN"
    "http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">

<!-- IMPORTANT ECLIPSE NOTE: If you change this file, you must restart Eclipse
 for your changes to take effect in its Checkstyle integration. -->
<suppressions>
    <!-- Suppress test classes -->
    <suppress files="[/\\]src[/\\].*[Tt]est[/\\](java|groovy)[/\\]" checks="Javadoc*" />
    <suppress files="[/\\]src[/\\].*[Tt]est[/\\](java|groovy)[/\\]" checks="VariableDeclarationUsageDistance" />

    <!-- JavadocStyle enforces existence of package-info.java package-level Javadoc; we consider this a bug. -->
    <suppress files="package-info.java" checks="JavadocStyle" />

    <!-- non-code classes -->
    <suppress files="\.(bdr|eot|gif|gzip|jar|json|otf|png|svg|ttf|woff|zip)$" checks="FileTabCharacter" />
    <suppress files="\.(bdr|eot|gif|gzip|jar|json|otf|png|svg|ttf|woff|zip)$" checks="NewlineAtEndOfFile" />

    <!-- Generated code should not be subjected to checkstyle. -->
    <suppress files="[/\\].*[/\\]generated_src[/\\]" checks="." />
    <suppress files="[/\\].*[/\\]generated_testSrc[/\\]" checks="." />
</suppressions>


text:
guid: 007b6e5d-bd7b-4b01-9a6c-99b332701dc7
type: Live
reformat: True
shortenReferences: True
categories: mnemonics
scopes: InCSharpTypeMember(minimumLanguageVersion=2.0); InCSharpTypeAndNamespace(minimumLanguageVersion=2.0)
parameterOrder: type, fieldname
type-expression: constant("type")
fieldname-expression: constant("fieldname")
---

# vrf

A readonly field of type $typename$

```
private readonly $type$ $fieldname$;
```


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Oesterr. Bot. Z. 70:13. 1921

#### Original name
null

### Remarks
null


text:
package hulo.localization.beacon;

import hulo.localization.Beacon;
import hulo.localization.BLEBeacon;
import hulo.localization.State;
import hulo.localization.utils.ClassUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.apache.wink.json4j.JSONException;
import org.apache.wink.json4j.JSONObject;

public class ClosestBeaconFilter extends AbstractBeaconFilter implements BeaconFilter{

	static final String RANGE2D_KEY = "range2D";
	static final String RANGE_FLOOR_KEY = "rangeFloor";

	boolean isActive = true;

	double range2D= 10.0; //m
	double rangeFloor = 0.5; // floor

	List<BLEBeacon> bleBeacons;

	public ClosestBeaconFilter(){}

	@Override
	public void settingFromJSON(JSONObject params){
		try {
			double range2D = params.getDouble(RANGE2D_KEY);
			double rangeFloor = params.getDouble(RANGE_FLOOR_KEY);
			this.range2D = range2D;
			this.rangeFloor = rangeFloor;

			System.out.println(this.summary());

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public ClosestBeaconFilter setBLEBeacon(List<BLEBeacon> bleBeacons){
		this.bleBeacons = bleBeacons;
		return this;
	}

	@Override
	public List<Beacon> filter(List<Beacon> beacons, State[] states){
		if( isActive){
			int n = beacons.size();

			Set<Integer> closeMinorSet = new TreeSet<Integer>();
			for(BLEBeacon ib: bleBeacons){
				int minor = ib.getMinor();
				for(State st: states){
					double dist = st.getDistance(ib);
					double floorDiff = st.getFloorDifference(ib);
					if(dist<range2D && floorDiff<rangeFloor){
						closeMinorSet.add(minor);
						break;
					}
				}
			}

			List<Beacon> beaconsNew = new ArrayList<Beacon>();
			for(Beacon b: beacons){
				int minor = b.getMinor();
				if(closeMinorSet.contains(minor)){
					beaconsNew.add(b);
				}
			}

			int m = beaconsNew.size();

			if(n!=m){
				System.out.println("closest beacon filter reduced no. beacons "+n+">>"+m);
			}

			return beaconsNew;
		}else{
			return beacons;
		}
	}

	public String summary(){
		return ClassUtils.summary(this);
	}

}


text:
package org.wso2.developerstudio.eclipse.platform.core.project.export;

import java.io.File;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.osgi.storagemanager.StorageManager;
import org.wso2.developerstudio.eclipse.platform.core.utils.Constants;
import org.wso2.developerstudio.eclipse.utils.file.TempFileUtils;

public abstract class ProjectArtifactHandler {
	private NullProgressMonitor nullProgressMonitor = new NullProgressMonitor();

	public abstract List<IResource> exportArtifact(IProject projecmessaget) throws Exception;

	protected  NullProgressMonitor getProgressMonitor() {
		return nullProgressMonitor;
	}

	protected File createTempProject() throws Exception {
//		IProject tempProject = ResourcesPlugin.getWorkspace().getRoot()
//				.getProject(".temp" + System.currentTimeMillis());
		File tempProject=TempFileUtils.createTempFile("temp", Long.toString(System.currentTimeMillis()), null);
		tempProject.delete();
		tempProject.mkdir();
//		tempProject.create(getProgressMonitor());
//		tempProject.open(getProgressMonitor());
//		tempProject.setHidden(true);
		return tempProject;
	}

	protected IPath getOutputPath(IJavaProject project) throws Exception{
		return ResourcesPlugin.getWorkspace().getRoot()
		.getFolder(project.getOutputLocation()).getLocation();
	}

	protected IPath getResourcePath(IProject project) throws Exception{
		return project.getFolder(
				"src" + File.separator + "main" + File.separator
						+ "resources").getLocation();
	}

	protected IFile getTargetArchive(IProject project,String ext) throws Exception{
		String finalName = String.format("%s.%s", project.getName(), ext);
		IFolder binaries = project.getFolder("target");
		if (!binaries.exists()) {
			binaries.create(true, true, getProgressMonitor());
			binaries.setHidden(true);
		}
		IFile archive = project.getFile("target" + File.separator + finalName);
		return archive;
	}

	protected IFile getTargetArchive(IProject project,String version,String ext) throws Exception{
		String finalName = String.format("%s.%s", project.getName()+"_"+version, ext);
		IFolder binaries = project.getFolder("target");
		if (!binaries.exists()) {
			binaries.create(true, true, getProgressMonitor());
			binaries.setHidden(true);
		}
		IFile archive = project.getFile("target" + File.separator + finalName);
		return archive;
	}

	protected void clearTarget(IProject project) {
		try {
			project.build(IncrementalProjectBuilder.CLEAN_BUILD,
							getProgressMonitor());
			File target = project.getFolder("target").getLocation().toFile();
			FileUtils.cleanDirectory(target);
		} catch (Exception e) {
			// TODO: log error
		}
	}

	protected IFolder getTempDirInWorksapce(String projectName, String dirName){
		String dir = String.format("%s_%s", projectName,dirName);
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(".tmp");
		if(project.exists()){
			IFolder tmpDir = project.getFolder(dir);
			if(!tmpDir.exists()){
				try {
					tmpDir.create(false, true, null);
					return tmpDir;
				} catch (CoreException e) {
					return null;
				}
			} else {
				return tmpDir ;
			}

		} else{
			try {
				project.create(null);
				return getTempDirInWorksapce(projectName,dir);
			} catch (Exception e) {
				return null;
			}
		}
	}

	protected void clearTempDirInWorksapce(String projectName, String dirName){
		String dir = String.format("%s_%s", projectName,dirName);
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(".tmp");
		if(project.exists()){
			IFolder tmpDir = project.getFolder(dir);
			if(tmpDir.exists()){
				try {
					tmpDir.delete(true, null);
				} catch (CoreException e) {
					//ignore
				}
			}
		}
	}

	/**
	 * create new StorageManager
	 * @param project
	 * @return new StorageManager
	 */
	protected StorageManager createStorageManager(IProject project){
		return new StorageManager(project.getLocation().toFile(), "false");
	}

	protected File createTempDir(File project, String name)
			throws Exception {
//		StorageManager manager = createStorageManager(project);
//		File dir = manager.createTempFile(name);
		File dir = TempFileUtils.createTempFile(name, null, project);
		dir.delete();
		dir.mkdir();
//		dir.delete();
		return dir;
	}
	/**
	 *
	 * @param project
	 * @return
	 * @throws Exception
	 */
	protected IPath buildJavaProject(IProject project) throws Exception {
		project.build(IncrementalProjectBuilder.CLEAN_BUILD,
						getProgressMonitor());
		project.build(IncrementalProjectBuilder.FULL_BUILD,
				getProgressMonitor());
		IJavaProject javaProject = JavaCore.create(project);;
		return getOutputPath(javaProject);
	}

	protected void clearProject(IProject project){
		try {
			project.delete(true, nullProgressMonitor);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}

}


text:
$(document).ready(function() {

  var Table = {};

  Table.applyNavbarPositions = function() {
    $.get('/cms/navbar_content_nodes/positions', function(data) {
      $('.navbar-table tbody tr').css('opacity', '0.5');
      $('.navbar-table tr td[data-content=position]').text('');
      $('.navbar-table tr td[data-content=shown]').text('Nein');
      for (let id in data) {
        $('.navbar-table tbody tr[data-node-id=' + id + ']').css('opacity', '1');
        $('.navbar-table tr[data-node-id=' + id + '] td[data-content=position]').text(data[id]);
        $('.navbar-table tr[data-node-id=' + id + '] td[data-content=shown]').text('Ja');
      }
    });
  };

  Table.applyNavbarPositions();

  Table.preserveCellWidth = function (event, ui) {
    ui.children().each(function() {
      $(this).width($(this).width());
    });
    return ui;
  };

  Table.bind_sortable = function () {
    $('table.content-nodes tbody').sortable({
      helper: Table.preserveCellWidth,
      stop: function(event, ui) {
        var url = ui.item.attr('data-sort-url'),
            position = $('tr').index(ui.item);
        $.post(url, { position: position }, function() {
          Table.applyNavbarPositions();
        });
      }
    });
  };

  window.CmsTable = {
    bind_sortable: Table.bind_sortable
  };
});


text:
// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';
// import 'rxjs/add/operator/toPromise';

import { SignInCredential } from '../shared/sign-in-credential';
import {HTTP_FORM_OPTIONS} from "../shared/shared.utils";
import { map, catchError } from "rxjs/operators";
import { Observable, throwError as observableThrowError } from "rxjs";
const signInUrl = '/c/login';
/**
 *
 * Define a service to provide sign in methods
 *
 **
 * class SignInService
 */
@Injectable()
export class SignInService {

    constructor(private http: Http) {}

    // Handle the related exceptions
    handleError(error: any): Observable<any> {
        return observableThrowError(error.message || error);
    }

    // Submit signin form to backend (NOT restful service)
    signIn(signInCredential: SignInCredential): Observable<any> {
        // Build the form package
        const body = new URLSearchParams();
        body.set('principal', signInCredential.principal);
        body.set('password', signInCredential.password);

        // Trigger Http
        return this.http.post(signInUrl, body.toString(), HTTP_FORM_OPTIONS)
        .pipe(map(() => null)
        , catchError(error => observableThrowError(error)));

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _02.Rectangle_Area
{
    class RectangleArea
    {
        static void Main(string[] args)
        {
            double a = double.Parse(Console.ReadLine());
            double b = double.Parse(Console.ReadLine());

            Console.WriteLine("{0:f2}", a * b);
        }
    }
}


text:
package de.tum.in.niedermr.ta.extensions.testing.frameworks.junit.collector;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({})
public class JUnit4TestSuite {
	// NOP
}


text:
. $CORE_PATH/hw/scripts/jlink.sh

FILE_NAME=$BIN_BASENAME.elf
JLINK_DEV="nrf5340_xxaa_app"

jlink_debug


text:
<?php

final class PhabricatorInfrastructureTestCase extends PhabricatorTestCase {

  protected function getPhabricatorTestCaseConfiguration() {
    return array(
      self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true,
    );
  }

  public function testApplicationsInstalled() {
    $all = PhabricatorApplication::getAllApplications();
    $installed = PhabricatorApplication::getAllInstalledApplications();

    $this->assertEqual(
      count($all),
      count($installed),
      pht('In test cases, all applications should default to installed.'));
  }

  public function testRejectMySQLNonUTF8Queries() {
    $table = new HarbormasterScratchTable();
    $conn_r = $table->establishConnection('w');

    $snowman = "\xE2\x98\x83";
    $invalid = "\xE6\x9D";

    qsprintf($conn_r, 'SELECT %B', $snowman);
    qsprintf($conn_r, 'SELECT %s', $snowman);
    qsprintf($conn_r, 'SELECT %B', $invalid);

    $caught = null;
    try {
      qsprintf($conn_r, 'SELECT %s', $invalid);
    } catch (AphrontCharacterSetQueryException $ex) {
      $caught = $ex;
    }

    $this->assertTrue($caught instanceof AphrontCharacterSetQueryException);
  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
com.google.flightmap.android.db (Flight Map android)
</TITLE>

<META NAME="date" CONTENT="2011-02-02">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

com.google.flightmap.android.db

Classes

AndroidAviationDbAdapter

GetAirportsInRectangleTask

GetAirportsInRectangleTask.QueryParams

GetAirspacesInRectangleTask

QueryTask


text:
namespace performance_manager {

namespace {

using PageState = PageNode::PageState;

bool IsValidInitialPageState(PageState page_state) {
  switch (page_state) {
    case PageState::kActive:
    case PageState::kPrerendering:
      return true;

    case PageState::kBackForwardCache:
      return false;
  }
  NOTREACHED();
  return false;
}

bool IsValidPageStateTransition(PageState old_state, PageState new_state) {
  switch (old_state) {
    case PageState::kActive:
      return new_state == PageState::kBackForwardCache;

    case PageState::kPrerendering:
    case PageState::kBackForwardCache:
      return new_state == PageState::kActive;
  }
  NOTREACHED();
  return false;
}

}  // namespace

PageNodeImpl::PageNodeImpl(const WebContentsProxy& contents_proxy,
                           const std::string& browser_context_id,
                           const GURL& visible_url,
                           bool is_visible,
                           bool is_audible,
                           base::TimeTicks visibility_change_time,
                           PageState page_state)
    : contents_proxy_(contents_proxy),
      visibility_change_time_(visibility_change_time),
      main_frame_url_(visible_url),
      browser_context_id_(browser_context_id),
      is_visible_(is_visible),
      is_audible_(is_audible),
      page_state_(page_state) {
  DCHECK(IsValidInitialPageState(page_state));
  weak_this_ = weak_factory_.GetWeakPtr();

  DETACH_FROM_SEQUENCE(sequence_checker_);
}

PageNodeImpl::~PageNodeImpl() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_EQ(nullptr, opener_frame_node_);
  DCHECK_EQ(nullptr, embedder_frame_node_);
  DCHECK_EQ(EmbeddingType::kInvalid, embedding_type_);
  DCHECK(!page_load_tracker_data_);
  DCHECK(!site_data_);
  DCHECK(!frozen_frame_data_);
  DCHECK(!page_aggregator_data_);
}

const WebContentsProxy& PageNodeImpl::contents_proxy() const {
  return contents_proxy_;
}

void PageNodeImpl::AddFrame(base::PassKey<FrameNodeImpl>,
                            FrameNodeImpl* frame_node) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(frame_node);
  DCHECK_EQ(this, frame_node->page_node());
  DCHECK(graph()->NodeInGraph(frame_node));

  ++frame_node_count_;
  if (frame_node->parent_frame_node() == nullptr)
    main_frame_nodes_.insert(frame_node);
}

void PageNodeImpl::RemoveFrame(base::PassKey<FrameNodeImpl>,
                               FrameNodeImpl* frame_node) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(frame_node);
  DCHECK_EQ(this, frame_node->page_node());
  DCHECK(graph()->NodeInGraph(frame_node));

  --frame_node_count_;
  if (frame_node->parent_frame_node() == nullptr) {
    size_t removed = main_frame_nodes_.erase(frame_node);
    DCHECK_EQ(1u, removed);
  }
}

void PageNodeImpl::SetLoadingState(LoadingState loading_state) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  loading_state_.SetAndMaybeNotify(this, loading_state);
}

void PageNodeImpl::SetType(PageType type) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  type_.SetAndMaybeNotify(this, type);
}

void PageNodeImpl::SetIsVisible(bool is_visible) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (is_visible_.SetAndMaybeNotify(this, is_visible)) {
    // The change time needs to be updated after observers are notified, as they
    // use this to determine time passed since the *previous* visibility state
    // change. They can infer the current state change time themselves via
    // NowTicks.
    visibility_change_time_ = base::TimeTicks::Now();
  }
}

void PageNodeImpl::SetIsAudible(bool is_audible) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  is_audible_.SetAndMaybeNotify(this, is_audible);
}

void PageNodeImpl::SetUkmSourceId(ukm::SourceId ukm_source_id) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  ukm_source_id_.SetAndMaybeNotify(this, ukm_source_id);
}

void PageNodeImpl::OnFaviconUpdated() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  for (auto* observer : GetObservers())
    observer->OnFaviconUpdated(this);
}

void PageNodeImpl::OnTitleUpdated() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  for (auto* observer : GetObservers())
    observer->OnTitleUpdated(this);
}

void PageNodeImpl::OnMainFrameNavigationCommitted(
    bool same_document,
    base::TimeTicks navigation_committed_time,
    int64_t navigation_id,
    const GURL& url,
    const std::string& contents_mime_type) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // This should never be invoked with a null navigation, nor should it be
  // called twice for the same navigation.
  DCHECK_NE(0, navigation_id);
  DCHECK_NE(navigation_id_, navigation_id);
  navigation_committed_time_ = navigation_committed_time;
  navigation_id_ = navigation_id;
  contents_mime_type_ = contents_mime_type;
  main_frame_url_.SetAndMaybeNotify(this, url);

  // No mainframe document change notification on same-document navigations.
  if (same_document)
    return;

  for (auto* observer : GetObservers())
    observer->OnMainFrameDocumentChanged(this);
}

base::TimeDelta PageNodeImpl::TimeSinceLastNavigation() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (navigation_committed_time_.is_null())
    return base::TimeDelta();
  return base::TimeTicks::Now() - navigation_committed_time_;
}

base::TimeDelta PageNodeImpl::TimeSinceLastVisibilityChange() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return base::TimeTicks::Now() - visibility_change_time_;
}

FrameNodeImpl* PageNodeImpl::GetMainFrameNodeImpl() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (main_frame_nodes_.empty())
    return nullptr;

  // Return the current frame node if there is one. Iterating over this set is
  // fine because it is almost always of length 1 or 2.
  for (auto* frame : main_frame_nodes_) {
    if (frame->is_current())
      return frame;
  }

  // Otherwise, return any old main frame node.
  return *main_frame_nodes_.begin();
}

FrameNodeImpl* PageNodeImpl::opener_frame_node() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return opener_frame_node_;
}

FrameNodeImpl* PageNodeImpl::embedder_frame_node() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(embedder_frame_node_ || embedding_type_ == EmbeddingType::kInvalid);
  return embedder_frame_node_;
}

PageNodeImpl::EmbeddingType PageNodeImpl::embedding_type() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(embedder_frame_node_ || embedding_type_ == EmbeddingType::kInvalid);
  return embedding_type_;
}

PageType PageNodeImpl::type() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return type_.value();
}

bool PageNodeImpl::is_visible() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return is_visible_.value();
}

bool PageNodeImpl::is_audible() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return is_audible_.value();
}

PageNode::LoadingState PageNodeImpl::loading_state() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return loading_state_.value();
}

ukm::SourceId PageNodeImpl::ukm_source_id() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return ukm_source_id_.value();
}

PageNodeImpl::LifecycleState PageNodeImpl::lifecycle_state() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return lifecycle_state_.value();
}

bool PageNodeImpl::is_holding_weblock() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return is_holding_weblock_.value();
}

bool PageNodeImpl::is_holding_indexeddb_lock() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return is_holding_indexeddb_lock_.value();
}

const base::flat_set<FrameNodeImpl*>& PageNodeImpl::main_frame_nodes() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return main_frame_nodes_;
}

base::TimeTicks PageNodeImpl::usage_estimate_time() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return usage_estimate_time_;
}

uint64_t PageNodeImpl::private_footprint_kb_estimate() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return private_footprint_kb_estimate_;
}

const std::string& PageNodeImpl::browser_context_id() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return browser_context_id_;
}

const GURL& PageNodeImpl::main_frame_url() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return main_frame_url_.value();
}

int64_t PageNodeImpl::navigation_id() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return navigation_id_;
}

const std::string& PageNodeImpl::contents_mime_type() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return contents_mime_type_;
}

bool PageNodeImpl::had_form_interaction() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return had_form_interaction_.value();
}

const absl::optional<freezing::FreezingVote>& PageNodeImpl::freezing_vote()
    const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return freezing_vote_.value();
}

PageNode::PageState PageNodeImpl::page_state() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return page_state_.value();
}

void PageNodeImpl::SetOpenerFrameNode(FrameNodeImpl* opener) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(opener);
  DCHECK(graph()->NodeInGraph(opener));
  DCHECK_NE(this, opener->page_node());

  auto* previous_opener = opener_frame_node_.get();
  if (previous_opener)
    previous_opener->RemoveOpenedPage(PassKey(), this);
  opener_frame_node_ = opener;
  opener->AddOpenedPage(PassKey(), this);

  for (auto* observer : GetObservers())
    observer->OnOpenerFrameNodeChanged(this, previous_opener);
}

void PageNodeImpl::ClearOpenerFrameNode() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_NE(nullptr, opener_frame_node_);

  auto* previous_opener = opener_frame_node_.get();

  opener_frame_node_->RemoveOpenedPage(PassKey(), this);
  opener_frame_node_ = nullptr;

  for (auto* observer : GetObservers())
    observer->OnOpenerFrameNodeChanged(this, previous_opener);
}

void PageNodeImpl::SetEmbedderFrameNodeAndEmbeddingType(
    FrameNodeImpl* embedder,
    EmbeddingType embedding_type) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(embedder);
  DCHECK(graph()->NodeInGraph(embedder));
  DCHECK_NE(this, embedder->page_node());
  DCHECK_NE(EmbeddingType::kInvalid, embedding_type);

  auto* previous_embedder = embedder_frame_node_.get();
  auto previous_type = embedding_type_;

  if (previous_embedder)
    previous_embedder->RemoveEmbeddedPage(PassKey(), this);
  embedder_frame_node_ = embedder;
  embedding_type_ = embedding_type;
  embedder->AddEmbeddedPage(PassKey(), this);

  for (auto* observer : GetObservers())
    observer->OnEmbedderFrameNodeChanged(this, previous_embedder,
                                         previous_type);
}

void PageNodeImpl::ClearEmbedderFrameNodeAndEmbeddingType() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_NE(nullptr, embedder_frame_node_);
  DCHECK_NE(EmbeddingType::kInvalid, embedding_type_);

  auto* previous_embedder = embedder_frame_node_.get();
  auto previous_type = embedding_type_;

  embedder_frame_node_->RemoveEmbeddedPage(PassKey(), this);
  embedder_frame_node_ = nullptr;
  embedding_type_ = EmbeddingType::kInvalid;

  for (auto* observer : GetObservers())
    observer->OnEmbedderFrameNodeChanged(this, previous_embedder,
                                         previous_type);
}

void PageNodeImpl::set_usage_estimate_time(
    base::TimeTicks usage_estimate_time) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  usage_estimate_time_ = usage_estimate_time;
}

void PageNodeImpl::set_private_footprint_kb_estimate(
    uint64_t private_footprint_kb_estimate) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  private_footprint_kb_estimate_ = private_footprint_kb_estimate;
}

void PageNodeImpl::set_has_nonempty_beforeunload(
    bool has_nonempty_beforeunload) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  has_nonempty_beforeunload_ = has_nonempty_beforeunload;
}

void PageNodeImpl::set_freezing_vote(
    absl::optional<freezing::FreezingVote> freezing_vote) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  freezing_vote_.SetAndMaybeNotify(this, freezing_vote);
}

void PageNodeImpl::set_page_state(PageState page_state) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(IsValidPageStateTransition(page_state_.value(), page_state));
  page_state_.SetAndMaybeNotify(this, page_state);
}

void PageNodeImpl::OnJoiningGraph() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
#if DCHECK_IS_ON()
  // Dereferencing the WeakPtr associated with this node will bind it to the
  // current sequence (all subsequent calls to |GetWeakPtr| will return the
  // same WeakPtr).
  GetWeakPtr()->GetImpl();
#endif
}

void PageNodeImpl::OnBeforeLeavingGraph() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Sever opener relationships.
  if (opener_frame_node_)
    ClearOpenerFrameNode();

  // Sever embedder relationships.
  if (embedder_frame_node_)
    ClearEmbedderFrameNodeAndEmbeddingType();

  DCHECK_EQ(0u, frame_node_count_);
}

void PageNodeImpl::RemoveNodeAttachedData() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  page_load_tracker_data_.reset();
  site_data_.reset();
  frozen_frame_data_.Reset();
  page_aggregator_data_.Reset();
}

const std::string& PageNodeImpl::GetBrowserContextID() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return browser_context_id();
}

const FrameNode* PageNodeImpl::GetOpenerFrameNode() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return opener_frame_node();
}

const FrameNode* PageNodeImpl::GetEmbedderFrameNode() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return embedder_frame_node();
}

PageNodeImpl::EmbeddingType PageNodeImpl::GetEmbeddingType() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return embedding_type();
}

PageType PageNodeImpl::GetType() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return type();
}

bool PageNodeImpl::IsVisible() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return is_visible();
}

base::TimeDelta PageNodeImpl::GetTimeSinceLastVisibilityChange() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return TimeSinceLastVisibilityChange();
}

bool PageNodeImpl::IsAudible() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return is_audible();
}

PageNode::LoadingState PageNodeImpl::GetLoadingState() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return loading_state();
}

ukm::SourceId PageNodeImpl::GetUkmSourceID() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return ukm_source_id();
}

PageNodeImpl::LifecycleState PageNodeImpl::GetLifecycleState() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return lifecycle_state();
}

bool PageNodeImpl::IsHoldingWebLock() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return is_holding_weblock();
}

bool PageNodeImpl::IsHoldingIndexedDBLock() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return is_holding_indexeddb_lock();
}

int64_t PageNodeImpl::GetNavigationID() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return navigation_id();
}

const std::string& PageNodeImpl::GetContentsMimeType() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return contents_mime_type();
}

base::TimeDelta PageNodeImpl::GetTimeSinceLastNavigation() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return TimeSinceLastNavigation();
}

const FrameNode* PageNodeImpl::GetMainFrameNode() const {
  return GetMainFrameNodeImpl();
}

bool PageNodeImpl::VisitMainFrameNodes(const FrameNodeVisitor& visitor) const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  for (auto* frame_impl : main_frame_nodes_) {
    const FrameNode* frame = frame_impl;
    if (!visitor.Run(frame))
      return false;
  }
  return true;
}

const base::flat_set<const FrameNode*> PageNodeImpl::GetMainFrameNodes() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  base::flat_set<const FrameNode*> main_frame_nodes(main_frame_nodes_.begin(),
                                                    main_frame_nodes_.end());
  return main_frame_nodes;
}

const GURL& PageNodeImpl::GetMainFrameUrl() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return main_frame_url();
}

bool PageNodeImpl::HadFormInteraction() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return had_form_interaction();
}

const WebContentsProxy& PageNodeImpl::GetContentsProxy() const {
  return contents_proxy();
}

const absl::optional<freezing::FreezingVote>& PageNodeImpl::GetFreezingVote()
    const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return freezing_vote();
}

PageState PageNodeImpl::GetPageState() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return page_state();
}

uint64_t PageNodeImpl::EstimateResidentSetSize() const {
  uint64_t total = 0;
  performance_manager::GraphOperations::VisitFrameTreePreOrder(
      this, base::BindRepeating(
                [](uint64_t* total, const FrameNode* frame_node) {
                  *total += frame_node->GetResidentSetKbEstimate();
                  return true;
                },
                &total));
  return total;
}

void PageNodeImpl::SetLifecycleState(LifecycleState lifecycle_state) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  lifecycle_state_.SetAndMaybeNotify(this, lifecycle_state);
}

void PageNodeImpl::SetIsHoldingWebLock(bool is_holding_weblock) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  is_holding_weblock_.SetAndMaybeNotify(this, is_holding_weblock);
}

void PageNodeImpl::SetIsHoldingIndexedDBLock(bool is_holding_indexeddb_lock) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  is_holding_indexeddb_lock_.SetAndMaybeNotify(this, is_holding_indexeddb_lock);
}

void PageNodeImpl::SetHadFormInteraction(bool had_form_interaction) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  had_form_interaction_.SetAndMaybeNotify(this, had_form_interaction);
}

}  // namespace performance_manager


text:
package com.amazonaws.services.appmesh.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * An object that represents the client's certificate.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ClientTlsCertificate implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * An object that represents a local file certificate. The certificate must meet specific requirements and you must
     * have proxy authorization enabled. For more information, see Transport Layer Security (TLS).
     *

     */
    private ListenerTlsFileCertificate file;
    /**
     *

     * A reference to an object that represents a client's TLS Secret Discovery Service certificate.
     *

     */
    private ListenerTlsSdsCertificate sds;

    /**
     *

     * An object that represents a local file certificate. The certificate must meet specific requirements and you must
     * have proxy authorization enabled. For more information, see Transport Layer Security (TLS).
     *

     *
     * @param file
     *        An object that represents a local file certificate. The certificate must meet specific requirements and
     *        you must have proxy authorization enabled. For more information, see Transport Layer Security (TLS).
     */

    public void setFile(ListenerTlsFileCertificate file) {
        this.file = file;
    }

    /**
     *

     * An object that represents a local file certificate. The certificate must meet specific requirements and you must
     * have proxy authorization enabled. For more information, see Transport Layer Security (TLS).
     *

     *
     * @return An object that represents a local file certificate. The certificate must meet specific requirements and
     *         you must have proxy authorization enabled. For more information, see Transport Layer Security (TLS).
     */

    public ListenerTlsFileCertificate getFile() {
        return this.file;
    }

    /**
     *

     * An object that represents a local file certificate. The certificate must meet specific requirements and you must
     * have proxy authorization enabled. For more information, see Transport Layer Security (TLS).
     *

     *
     * @param file
     *        An object that represents a local file certificate. The certificate must meet specific requirements and
     *        you must have proxy authorization enabled. For more information, see Transport Layer Security (TLS).
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ClientTlsCertificate withFile(ListenerTlsFileCertificate file) {
        setFile(file);
        return this;
    }

    /**
     *

     * A reference to an object that represents a client's TLS Secret Discovery Service certificate.
     *

     *
     * @param sds
     *        A reference to an object that represents a client's TLS Secret Discovery Service certificate.
     */

    public void setSds(ListenerTlsSdsCertificate sds) {
        this.sds = sds;
    }

    /**
     *

     * A reference to an object that represents a client's TLS Secret Discovery Service certificate.
     *

     *
     * @return A reference to an object that represents a client's TLS Secret Discovery Service certificate.
     */

    public ListenerTlsSdsCertificate getSds() {
        return this.sds;
    }

    /**
     *

     * A reference to an object that represents a client's TLS Secret Discovery Service certificate.
     *

     *
     * @param sds
     *        A reference to an object that represents a client's TLS Secret Discovery Service certificate.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ClientTlsCertificate withSds(ListenerTlsSdsCertificate sds) {
        setSds(sds);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getFile() != null)
            sb.append("File: ").append(getFile()).append(",");
        if (getSds() != null)
            sb.append("Sds: ").append(getSds());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ClientTlsCertificate == false)
            return false;
        ClientTlsCertificate other = (ClientTlsCertificate) obj;
        if (other.getFile() == null ^ this.getFile() == null)
            return false;
        if (other.getFile() != null && other.getFile().equals(this.getFile()) == false)
            return false;
        if (other.getSds() == null ^ this.getSds() == null)
            return false;
        if (other.getSds() != null && other.getSds().equals(this.getSds()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getFile() == null) ? 0 : getFile().hashCode());
        hashCode = prime * hashCode + ((getSds() == null) ? 0 : getSds().hashCode());
        return hashCode;
    }

    @Override
    public ClientTlsCertificate clone() {
        try {
            return (ClientTlsCertificate) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.appmesh.model.transform.ClientTlsCertificateMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
NodeJS + ExpressJS wrapper for Mandrill

_Currently only being used to route requests and responses to/from
Mandrill. If it makes sense to add more functionality in the future, I will_.


text:
Modules and Libraries
=====================

.. toctree::
   :maxdepth: 2

   blobstore
   convert
   jobs
   native_api
   stream
   web_data


text:
<?php

/* FOSUserBundle::layout.html.twig */
class __TwigTemplate_8fa89e9944e0c25c5583cc08009eb7551d50e15bee18d934bd85fd372df66956 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        try {
            $this->parent = $this->env->loadTemplate("::layout/layout.html.twig");
        } catch (Twig_Error_Loader $e) {
            $e->setTemplateFile($this->getTemplateName());
            $e->setTemplateLine(1);

            throw $e;
        }

        $this->blocks = array(
            'body' => array($this, 'block_body'),
            'fos_user_content' => array($this, 'block_fos_user_content'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::layout/layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        // line 4
        echo "

            ";
        // line 5
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : null), "session", array()), "flashbag", array()), "all", array(), "method"));
        foreach ($context['_seq'] as $context["type"] => $context["messages"]) {
            // line 6
            echo "            ";
            $context['_parent'] = (array) $context;
            $context['_seq'] = twig_ensure_traversable($context["messages"]);
            foreach ($context['_seq'] as $context["_key"] => $context["message"]) {
                // line 7
                echo "
env, $context["type"], "html", null, true);
                echo "\">
                    ";
                // line 8
                echo twig_escape_filter($this->env, $context["message"], "html", null, true);
                echo "

            ";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['message'], $context['_parent'], $context['loop']);
            $context = array_intersect_key($context, $_parent) + $_parent;
            // line 11
            echo "        ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['type'], $context['messages'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 12
        echo "
            ";
        // line 13
        $this->displayBlock('fos_user_content', $context, $blocks);
        // line 15
        echo "

";
    }

    // line 13
    public function block_fos_user_content($context, array $blocks = array())
    {
        // line 14
        echo "            ";
    }

    public function getTemplateName()
    {
        return "FOSUserBundle::layout.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  85 => 14,  82 => 13,  77 => 15,  75 => 13,  72 => 12,  66 => 11,  57 => 8,  52 => 7,  47 => 6,  43 => 5,  40 => 4,  37 => 3,  11 => 1,);
    }
}


text:
$(document).ready(function(){
$(".scroll").click(function(event){
//prevent the default action for the click event
event.preventDefault();

//get the full url - like mysitecom/index.htm#home
var full_url = this.href;

//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
var parts = full_url.split("#");
var trgt = parts[1];

//get the top offset of the target anchor
var target_offset = $("#"+trgt).offset();
var target_top = target_offset.top;

//goto that anchor by setting the body scroll top to anchor top
$('html, body').animate({scrollTop:target_top}, 500);
});
});