text:
layout:     post
title:      "Do Not Believe What I Said"
subtitle:   ""
date:       2016-04-16 12:00:00
author:     "Supakorn Laohasongkram"
tags: ['true-happiness-essential']
---

My Goal

My goal is to offer you truth. I am not telling you to believe me. I am merely telling you the path and hoping that you try to walk it so that you could see for yourself if what I have to say actually true or helps to transforms your happiness and everything around you. That is all.

https://www.youtube.com/watch?v=YvOoKHFwqfw


text:
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.Dialog;

namespace Verses.iOS
{
	public class StyledTranslationRootElement : RootElement, IElementSizing
	{
		UIBarButtonItem BackButton;
		UILabel NavigationBarLabel;

		public StyledTranslationRootElement (string caption) : base (caption)
		{

		}

		public StyledTranslationRootElement (string caption, Group group) : base (caption, group)
		{

		}

		static NSString key = new NSString ("StyledTranslationRootElement");

		protected override NSString CellKey
		{
			get
			{
				return key;
			}
		}

		protected override void PrepareDialogViewController (UIViewController dvc)
		{
			base.PrepareDialogViewController (dvc);

			NavigationBarLabel = InterfaceHelper.LabelForTitle (Caption.ToUpper());
			dvc.NavigationItem.TitleView = NavigationBarLabel;

			var backButton = new UIButton (new RectangleF (0, 0, 25, 25));
			backButton.SetBackgroundImage (UIImage.FromFile ("Images/General/BackButton.png"), UIControlState.Normal);
			backButton.SetBackgroundImage (UIImage.FromFile ("Images/General/BackButtonHighlighted.png"), UIControlState.Highlighted);
			backButton.AddTarget((object sender, EventArgs args) => GoBack(dvc),
				UIControlEvent.TouchUpInside);

			BackButton = new UIBarButtonItem (backButton);
			dvc.NavigationItem.LeftBarButtonItem = BackButton;
		}

		private void GoBack(UIViewController dvc)
		{
			switch (RadioSelected)
			{
			case 0:
				TranslationHelper.SetCurrentTranslation ("esv");
				break;
			case 1:
				TranslationHelper.SetCurrentTranslation ("kjv");
				break;
			case 2:
				TranslationHelper.SetCurrentTranslation ("msg");
				break;
			case 3:
				TranslationHelper.SetCurrentTranslation ("nasb");
				break;
			};

			dvc.NavigationController.PopViewControllerAnimated (true);
		}

		public float GetHeight (UITableView tableView, NSIndexPath indexPath)
		{
			return 35;
		}

		public override UITableViewCell GetCell (UITableView tv)
		{
			var cell = base.GetCell (tv);

			cell.SelectionStyle = UITableViewCellSelectionStyle.None;
			cell.BackgroundColor = UIColor.White;

			cell.TextLabel.BackgroundColor = UIColor.White;
			cell.TextLabel.Font = UIFont.FromName ("SourceSansPro-Regular", 15f);
			cell.TextLabel.TextColor = UIColor.Black;

			cell.DetailTextLabel.BackgroundColor = UIColor.White;
			cell.DetailTextLabel.Font = UIFont.FromName ("SourceSansPro-Regular", 13f);
			cell.DetailTextLabel.TextColor = UIColor.Black;

			return cell;
		}

		protected override void Dispose (bool disposing)
		{
			base.Dispose (disposing);

			if (BackButton != null) {
				BackButton.Dispose ();
				BackButton = null;
			}

			if (NavigationBarLabel != null) {
				NavigationBarLabel.Dispose ();
				NavigationBarLabel = null;
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


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

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum InsightStatus {

    ONGOING("ONGOING"),
    CLOSED("CLOSED");

    private String value;

    private InsightStatus(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return InsightStatus corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static InsightStatus fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (InsightStatus enumEntry : InsightStatus.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="cpp_skywell.androcal.androcal.example.EventActivity"
    tools:showIn="@layout/activity_event">

</android.support.constraint.ConstraintLayout>


text:
#ifndef JSDOMWindowCustom_h
#define JSDOMWindowCustom_h

#include "JSDOMWindow.h"
#include "JSDOMWindowShell.h"
#include <wtf/AlwaysInline.h>

namespace WebCore {

inline JSDOMWindow* asJSDOMWindow(JSC::JSGlobalObject* globalObject)
{
    return static_cast<JSDOMWindow*>(globalObject);
}

inline const JSDOMWindow* asJSDOMWindow(const JSC::JSGlobalObject* globalObject)
{
    return static_cast<const JSDOMWindow*>(globalObject);
}

inline bool JSDOMWindowBase::allowsAccessFrom(const JSGlobalObject* other) const
{
    if (allowsAccessFromPrivate(other))
        return true;
    printErrorMessage(crossDomainAccessErrorMessage(other));
    return false;
}

inline bool JSDOMWindowBase::allowsAccessFrom(JSC::ExecState* exec) const
{
    if (allowsAccessFromPrivate(exec->lexicalGlobalObject()))
        return true;
    printErrorMessage(crossDomainAccessErrorMessage(exec->lexicalGlobalObject()));
    return false;
}

inline bool JSDOMWindowBase::allowsAccessFromNoErrorMessage(JSC::ExecState* exec) const
{
    return allowsAccessFromPrivate(exec->lexicalGlobalObject());
}

inline bool JSDOMWindowBase::allowsAccessFrom(JSC::ExecState* exec, String& message) const
{
    if (allowsAccessFromPrivate(exec->lexicalGlobalObject()))
        return true;
    message = crossDomainAccessErrorMessage(exec->lexicalGlobalObject());
    return false;
}

ALWAYS_INLINE bool JSDOMWindowBase::allowsAccessFromPrivate(const JSGlobalObject* other) const
{
    const JSDOMWindow* originWindow = asJSDOMWindow(other);
    const JSDOMWindow* targetWindow = m_shell->window();

    if (originWindow == targetWindow)
        return true;

    const SecurityOrigin* originSecurityOrigin = originWindow->impl()->securityOrigin();
    const SecurityOrigin* targetSecurityOrigin = targetWindow->impl()->securityOrigin();

    return originSecurityOrigin->canAccess(targetSecurityOrigin);
}

}

#endif // JSDOMWindowCustom_h


text:
package uk.org.ngo.squeezer.util;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;

import java.util.Hashtable;
import java.util.Map;

/**
 * Provides a fragment that will be retained across the lifecycle of the activity that hosts it.
 * <p>
 * Get an instance of this class by calling {@link #getInstance(String, FragmentManager)}, and place
 * objects that should be persisted across the activity lifecycle using {@link #put(String,
 * Object)}. Retrieve persisted objects with {@link #get(String)}.
 */
public class RetainFragment extends Fragment {

    private static final String TAG = RetainFragment.class.getName();

    private final Map<String, Object> mHash = new Hashtable<String, Object>();

    /**
     * Empty constructor as per the Fragment documentation
     */
    public RetainFragment() {
    }

    public static RetainFragment getInstance(String tag, FragmentManager fm) {
        Log.d(TAG, "getInstance() for " + tag);
        RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(tag);
        if (fragment == null) {
            Log.d(TAG, "  Creating new instance");
            fragment = new RetainFragment();
            fm.beginTransaction().add(fragment, tag).commitAllowingStateLoss();
        }
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Make sure this Fragment is retained over a configuration change
        setRetainInstance(true);
    }

    public Object put(String key, Object value) {
        mHash.put(key, value);
        return value;
    }

    public Object get(String key) {
        return mHash.get(key);
    }
}


text:
This is playground for Angular2 rc.1 built with webpack.

- using rc.4 component router (`@angular/router`)
- using sass loader
- using firebase as a data source

# Prerequisities

- last npm!, node

# First run

`npm install` - this will install dependencies

`npm start` - this will start a dev server on port 8080

# Scripts

`npm run build` - builds project in dist directory

`npm run dev` - starts webpack dev server: (http://localhost:8080/webpack-dev-server/)

`npm start` - alias for `npm run dev`

`npm run watch` - build triggered on change


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28614_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans258.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans268.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Beetle 3H Injection Skid

Coronet — Strom —- I """""" ' ", Site "171    Ranchero - Beetle Oil CT B : "44* : °°"°"'.T "13"" "W53"   e L  *: i : I MNCHER01918«2H um: anal-an . Resources |
Process Flow Diagram
MJY m3" "IV-mp Smlhm

mun-u mum mun-u M..."

; _ _ _ _ _ _ _ _ _ _ _._| Gu \ Allocatlon ' Meter
M ' 1 V Men! .7  1  Ir BeetIeB a" h," Beetle3
1----

    <p class="styleSans198.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">lemp

Gas Allocation Mater

Strom 8 Perm
' anchero < Temp

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
'use strict';

defineParticle(({UiParticle, html}) => {

  const template = html`

{{arrival}}

  `;

  const daysToMs = 24*60*60*1000;

  return class extends UiParticle {
    get template() {
      return template;
    }
    shouldRender(props) {
      return !!props && !!props.product;
    }
    render(props) {
      const {product} = props;
      const needed = new Date();
      needed.setDate(needed.getDate() + 12);

      let style = null;
      let arrival = '';
      if (product.shipDays) {
        // create a Date-only Date (with a time of 00:00:00etc)
        const estimated = new Date(new Date().toDateString());
        estimated.setDate(estimated.getDate() + product.shipDays);
        arrival = `Arrives ${estimated.toDateString()}`;
        if (estimated > needed) {
          arrival += ` which may be too late.`;
          style = {color: 'darkred', /*fontWeight: 'bold',*/ fontStyle: 'normal'};
        } else {
          style = {color: 'green'};
        }
      } else {
        arrival = `No shipping info.`;
      }
      return {
        arrival,
        style
      };
    }
  };
});


text:
<?php

namespace Php\Form\Builder\Element;

abstract class Input extends Control
{
    const NAME = 'input';

    public function __construct($type, array $attributes = [])
    {
        $attributes['type'] = $type;
        parent::__construct(self::NAME, parent::INNER_EMPTY, $attributes);
    }

    public function get_value()
    {
        return $this->value;
    }

    public function set_submitted_value($value)
    {
        if (is_scalar($value)) {
            $this->value = $value;
        }
    }
}


text:
Sequel.migration do
  up do
    create_table(migration_schema_for_table(:boofs)) do
      primary_key :id
      String :name, :null=>false
    end
  end

  down do
    drop_table(:boofs)
  end
end


text:
using UnityEngine;
using System.Collections;

/// <summary>
/// Centers the object horizontally with respects to screen width
/// </summary>
public class CenterHorizontally : MonoBehaviour
{

	// Use this for initialization
	void Start ()
	{
		transform.position = new Vector3(Screen.width / 2, transform.position.y, transform.position.z);
	}

	void Update()
	{

	}
}


text:
package org.apache.ojb.broker.core;

import org.apache.ojb.broker.OJBRuntimeException;
import org.apache.ojb.broker.util.ClassHelper;
import org.apache.ojb.broker.util.configuration.Configuration;
import org.apache.ojb.broker.util.configuration.Configurator;
import org.apache.ojb.broker.util.configuration.impl.OjbConfigurator;
import org.apache.ojb.broker.util.logging.Logger;
import org.apache.ojb.broker.util.logging.LoggerFactory;

/**
 *
 * @author Thomas Mahler
 * @version $Id: PersistenceBrokerFactoryFactory.java,v 1.1 2007-08-24 22:17:35 ewestfal Exp $
 */
public class PersistenceBrokerFactoryFactory
{
    private static Logger log = LoggerFactory.getBootLogger();

    private static final String PBF_KEY = "PersistenceBrokerFactoryClass";
    private static PersistenceBrokerFactoryIF singleton = init();

    /**
     * Returns an {@link PersistenceBrokerFactoryIF} instance.
     */
    public static PersistenceBrokerFactoryIF instance()
    {
        return singleton;
    }

    private static PersistenceBrokerFactoryIF init()
    {
        if (log.isDebugEnabled()) log.debug("Instantiate PersistenceBrokerFactory");
        Class pbfClass = null;
        try
        {
            Configurator configurator = OjbConfigurator.getInstance();
            Configuration config = configurator.getConfigurationFor(null);
            pbfClass = config.getClass(PBF_KEY, null);
            if(pbfClass == null)
            {
                log.error("Creation of PersistenceBrokerFactory (PBF) instance failed, can't get PBF class object");
                throw new OJBRuntimeException("Property for key '" + PBF_KEY + "' can not be found in properties file");
            }
            PersistenceBrokerFactoryIF result = (PersistenceBrokerFactoryIF) ClassHelper.newInstance(pbfClass);
            configurator.configure(result);
            log.info("PersistencebrokerFactory class instantiated: " + result);
            return result;
        }
        catch (Exception e)
        {
            if(e instanceof OJBRuntimeException)
            {
                throw (OJBRuntimeException) e;
            }
            else
            {
                throw new OJBRuntimeException("Error while instantiation of PersistenceBrokerFactory class", e);
            }
        }
    }
}


text:
static void usage(CmdOptionsCtx* ctx)
{
    printf(
        "Decodes INPUT and optionally writes OUTPUT.\n"
        "Decide if the input stream is HEVC 10bit, run 'ffprobe' or other tool to confirm 'HEVC Main 10' profile\n"
        "Usage: %s [options] INPUT [OUTPUT]\n", ctx->program);
}

int main(int argc, char** argv)
{
    mfxStatus sts = MFX_ERR_NONE;
    bool bEnableOutput; // if true, removes all YUV file writing
    CmdOptions options;

    // =====================================================================
    // Intel Media SDK decode pipeline setup
    // - In this example we are decoding an HEVC (H.265) stream
    // - For simplistic memory management, system memory surfaces are used to store the decoded frames
    //   (Note that when using HW acceleration video surfaces are prefered, for better performance)
    // - Before run the program, check if the input stream is HEVC 10bit, run "ffprobe" or other tool
    //   to confirm if the stream has the "HEVC Main 10" profile

    // 1. Read options from the command line (if any is given)
    memset(&options, 0, sizeof(CmdOptions));
    options.ctx.options = OPTIONS_DECODE;
    options.ctx.usage = usage;
    // Set default values:
    options.values.impl = MFX_IMPL_AUTO_ANY;

    // here we parse options
    ParseOptions(argc, argv, &options);

    if (!options.values.SourceName[0]) {
        printf("error: source file name not set (mandatory)\n");
        return -1;
    }

    bEnableOutput = (options.values.SinkName[0] != '\0');
    // Open input H.265 elementary stream (ES) file
    fileUniPtr fSource(OpenFile(options.values.SourceName, "rb"), &CloseFile);
    MSDK_CHECK_POINTER(fSource, MFX_ERR_NULL_PTR);
    // Create output YUV file
    fileUniPtr fSink(nullptr, &CloseFile);
    if (bEnableOutput) {
        fSink.reset(OpenFile(options.values.SinkName, "wb"));
        MSDK_CHECK_POINTER(fSink, MFX_ERR_NULL_PTR);
    }

    // 2. Initialize Intel Media SDK session
    // - MFX_IMPL_AUTO_ANY selects HW acceleration if available (on any adapter)
    // - Version 1.0 is selected for greatest backwards compatibility.
    // OS specific notes
    // - On Windows both SW and HW libraries may present
    // - On Linux only HW library only is available
    //   If more recent API features are needed, change the version accordingly
    mfxIMPL impl = options.values.impl;
    mfxVersion ver = { {0, 1} };
    MFXVideoSession session;

    sts = Initialize(impl, ver, &session, NULL);
    MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);

    // Create Media SDK decoder
    MFXVideoDECODE mfxDEC(session);

    // 3. Set required video parameters for decode
    mfxVideoParam mfxVideoParams;
    memset(&mfxVideoParams, 0, sizeof(mfxVideoParams));
    mfxVideoParams.mfx.CodecId = MFX_CODEC_HEVC; //The codecId must be set to HEVC in order to load the plugin
    mfxVideoParams.IOPattern = MFX_IOPATTERN_OUT_SYSTEM_MEMORY;

    // 4. Load the HEVC plugin
    mfxPluginUID codecUID;
    bool success = true;
    codecUID = msdkGetPluginUID(impl, MSDK_VDECODE, mfxVideoParams.mfx.CodecId);

    if (AreGuidsEqual(codecUID, MSDK_PLUGINGUID_NULL)) {
        printf("Get Plugin UID for HEVC is failed.\n");
        success = false;
    }

    printf("Loading HEVC plugin: %s\n", ConvertGuidToString(codecUID));

    //On the success of get the UID, load the plugin
    if (success) {
        sts = MFXVideoUSER_Load(session, &codecUID, ver.Major);
        if (sts < MFX_ERR_NONE) {
            printf("Loading HEVC plugin failed\n");
            success = false;
        }
    }

    // 5. Prepare Media SDK bit stream buffer
    // - Arbitrary buffer size for this example
    mfxBitstream mfxBS;
    memset(&mfxBS, 0, sizeof(mfxBS));
    mfxBS.MaxLength = 8 * 1024 * 1024;
    std::vector<mfxU8> bstData(mfxBS.MaxLength);
    mfxBS.Data = bstData.data();

    // Read a chunk of data from stream file into bit stream buffer
    // - Parse bit stream, searching for header and fill video parameters structure
    // - Abort if bit stream header is not found in the first bit stream buffer chunk
    sts = ReadBitStreamData(&mfxBS, fSource.get());
    MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);

    sts = mfxDEC.DecodeHeader(&mfxBS, &mfxVideoParams);
    MSDK_IGNORE_MFX_STS(sts, MFX_WRN_PARTIAL_ACCELERATION);
    MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);

    // Validate video decode parameters (optional)
     sts = mfxDEC.Query(&mfxVideoParams, &mfxVideoParams);

    // Query number of required surfaces for decoder
    mfxFrameAllocRequest Request;
    memset(&Request, 0, sizeof(Request));
    sts = mfxDEC.QueryIOSurf(&mfxVideoParams, &Request);
    MSDK_IGNORE_MFX_STS(sts, MFX_WRN_PARTIAL_ACCELERATION);
    MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);

    mfxU16 numSurfaces = Request.NumFrameSuggested;

    // 6. Allocate surfaces for decoder
    // - Width and height of buffer must be aligned, a multiple of 32
    // - Frame surface array keeps pointers all surface planes and general frame info
    // - For HEVC 10 bit, the bytes per pixel is doubled, so the width is multiplied by 2.
    mfxU16 width = (mfxU16) MSDK_ALIGN32(Request.Info.Width * 2);
    mfxU16 height = (mfxU16) MSDK_ALIGN32(Request.Info.Height);
    mfxU8 bitsPerPixel = 12; // Note: YUV P010 format is a 24 bits per pixel format, but we have doubled the width
    mfxU32 surfaceSize = width * height * bitsPerPixel / 8;
    std::vector<mfxU8> surfaceBuffersData(surfaceSize * numSurfaces);
    mfxU8* surfaceBuffers = surfaceBuffersData.data();

    // Allocate surface headers (mfxFrameSurface1) for decoder, noticed the width has been doubled for P010.
    std::vector<mfxFrameSurface1> pmfxSurfaces(numSurfaces);
    for (int i = 0; i < numSurfaces; i++) {
        memset(&pmfxSurfaces[i], 0, sizeof(mfxFrameSurface1));
        pmfxSurfaces[i].Info = mfxVideoParams.mfx.FrameInfo;
        pmfxSurfaces[i].Data.Y = &surfaceBuffers[surfaceSize * i];
        pmfxSurfaces[i].Data.U = pmfxSurfaces[i].Data.Y + width * height;
        pmfxSurfaces[i].Data.V = pmfxSurfaces[i].Data.U + 1;
        pmfxSurfaces[i].Data.Pitch = width;
    }

    // 7. Initialize the Media SDK decoder
    sts = mfxDEC.Init(&mfxVideoParams);
    MSDK_IGNORE_MFX_STS(sts, MFX_WRN_PARTIAL_ACCELERATION);
    MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);

    // ===============================================================
    // 8. Start decoding the frames
    //

    mfxTime tStart, tEnd;
    mfxGetTime(&tStart);

    mfxSyncPoint syncp;
    mfxFrameSurface1* pmfxOutSurface = NULL;
    int nIndex = 0;
    mfxU32 nFrame = 0;

    //
    // Stage 1: Main decoding loop
    //
    while (MFX_ERR_NONE <= sts || MFX_ERR_MORE_DATA == sts || MFX_ERR_MORE_SURFACE == sts) {
        if (MFX_WRN_DEVICE_BUSY == sts)
            MSDK_SLEEP(1);  // Wait if device is busy, then repeat the same call to DecodeFrameAsync

        if (MFX_ERR_MORE_DATA == sts) {
            sts = ReadBitStreamData(&mfxBS, fSource.get());       // Read more data into input bit stream
            MSDK_BREAK_ON_ERROR(sts);
        }

        if (MFX_ERR_MORE_SURFACE == sts || MFX_ERR_NONE == sts) {
            nIndex = GetFreeSurfaceIndex(pmfxSurfaces);        // Find free frame surface
            MSDK_CHECK_ERROR(MFX_ERR_NOT_FOUND, nIndex, MFX_ERR_MEMORY_ALLOC);
        }
        // Decode a frame asychronously (returns immediately)
        //  - If input bitstream contains multiple frames DecodeFrameAsync will start decoding multiple frames, and remove them from bitstream
        sts = mfxDEC.DecodeFrameAsync(&mfxBS, &pmfxSurfaces[nIndex], &pmfxOutSurface, &syncp);

        // Ignore warnings if output is available,
        // if no output and no action required just repeat the DecodeFrameAsync call
        if (MFX_ERR_NONE < sts && syncp)
            sts = MFX_ERR_NONE;

        if (MFX_ERR_NONE == sts)
            sts = session.SyncOperation(syncp, 60000);      // Synchronize. Wait until decoded frame is ready

        if (MFX_ERR_NONE == sts) {
            ++nFrame;
            if (bEnableOutput) {
                sts = WriteRaw10BitFrame(pmfxOutSurface, fSink.get());
                MSDK_BREAK_ON_ERROR(sts);

                printf("Frame number: %d\r", nFrame);
                fflush(stdout);
            }
        }
    }

    // MFX_ERR_MORE_DATA means that file has ended, need to go to buffering loop, exit in case of other errors
    MSDK_IGNORE_MFX_STS(sts, MFX_ERR_MORE_DATA);
    MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);

    //
    // Stage 2: Retrieve the buffered decoded frames
    //
    while (MFX_ERR_NONE <= sts || MFX_ERR_MORE_SURFACE == sts) {
        if (MFX_WRN_DEVICE_BUSY == sts)
            MSDK_SLEEP(1);  // Wait if device is busy, then repeat the same call to DecodeFrameAsync

        nIndex = GetFreeSurfaceIndex(pmfxSurfaces);        // Find free frame surface
        MSDK_CHECK_ERROR(MFX_ERR_NOT_FOUND, nIndex, MFX_ERR_MEMORY_ALLOC);

        // Decode a frame asychronously (returns immediately)
        sts = mfxDEC.DecodeFrameAsync(NULL, &pmfxSurfaces[nIndex], &pmfxOutSurface, &syncp);

        // Ignore warnings if output is available,
        // if no output and no action required just repeat the DecodeFrameAsync call
        if (MFX_ERR_NONE < sts && syncp)
            sts = MFX_ERR_NONE;

        if (MFX_ERR_NONE == sts)
            sts = session.SyncOperation(syncp, 60000);      // Synchronize. Waits until decoded frame is ready

        if (MFX_ERR_NONE == sts) {
            ++nFrame;
            if (bEnableOutput) {
                sts = WriteRaw10BitFrame(pmfxOutSurface, fSink.get());
                MSDK_BREAK_ON_ERROR(sts);

                printf("Frame number: %d\r", nFrame);
                fflush(stdout);
            }
        }
    }

    // MFX_ERR_MORE_DATA indicates that all buffers has been fetched, exit in case of other errors
    MSDK_IGNORE_MFX_STS(sts, MFX_ERR_MORE_DATA);
    MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);

    mfxGetTime(&tEnd);
    double elapsed = TimeDiffMsec(tEnd, tStart) / 1000;
    double fps = ((double)nFrame / elapsed);
    printf("\nExecution time: %3.2f s (%3.2f fps)\n", elapsed, fps);

    // ===================================================================
    // 8. Clean up resources
    //  - It is recommended to close Media SDK components first, before releasing allocated surfaces, since
    //    some surfaces may still be locked by internal Media SDK resources.

    mfxDEC.Close();
    // session closed automatically on destruction

    Release();

    return 0;
}


text:
/**
 * @author Anton Sukhonosenko
 */

exports.EventView = function(data, friends) {

	// TODO: request additional info via graph API request
	// TODO: add ability to checkin using Facebook Places
	// TODO: rsvp and ban events
	// TODO: event image and scroll view

	var _ = require('underscore')._;
	require('date');  // This adds Date.js library, extending standard Date() object

	var self = Ti.UI.createView({
		top : "0dp",
		height : "100%",
		backgroundColor : "#fff",
		zIndex: 103
	});

	self.friends = friends;

	var headerLabel = Ti.UI.createLabel({
		text: "Event Details",
		top: "0dp",
		height: "44dp",
		width: "100%",
		textAlign:'center',
		color:"#fff",
		font: {
			fontSize: 18,
			fontWeight: "bold"
		},
		zIndex: 100,
		backgroundImage: "/images/iphone_title_bar_blue.png" // FIXME: strange <Error>: CGContextConcatCTM: invalid context 0x0 etc etc. yet it works
	});

	self.add(headerLabel);

	var scrollView = Titanium.UI.createScrollView({
		contentWidth : Titanium.Platform.osname==='iphone'?"320dp":"768dp",
		contentHeight : 'auto',
		top : "45dp",
		showVerticalScrollIndicator : true
	});

	var backButton = Ti.UI.createButton({
		title : "Back",
		top : "8dp",
		left : "5dp",
		width : "50dp",
		height : "29dp",
		color: "white",
		selectedColor: "gray",
		font: {
			fontSize: 12,
			fontWeight: "bold"
		},
		backgroundImage: "/images/iphone_title_button_blue.png",
		backgroundFocusedImage: "/images/iphone_title_button_blue_focused.png",
		backgroundSelectedImage: "/images/iphone_title_button_blue_focused.png",
		zIndex: 102
	});

	backButton.addEventListener('click', function(e) {

		// TODO: beware memory issues!!
		// TODO: are we creating new eventView each time when we click on tableView?
		// TODO: does this affect memory?

		self.hide();

		// TODO: following is a humble attempt to manage memory issues

		// self.remove();
		// self = null;
	});

	var nameLabel = Ti.UI.createLabel({
		top: "5dp",
		left: "5dp",
		right: "5dp",
		height: "44dp",
		width: Titanium.Platform.osname==='iphone'?"320dp":"768dp",
		textAlign: "center",
		text: data.name,
		font: {
			fontSize: 18,
			fontWeight: "bold"
		}
	});

	var imageView = Ti.UI.createImageView({
		image: "https://graph.facebook.com/" + (data.id || 0) + "/picture?type=large&access_token=" + Ti.Facebook.accessToken,
		top: "50dp",
		right: "5dp",
		width: Titanium.Platform.osname==='iphone'?"320dp":"768dp",
		height: "120dp"
	});

	imageView.touchEnabled = true;

	imageView.addEventListener('click', function(e) {

		var largeImageView = Ti.UI.createImageView({
			image: "https://graph.facebook.com/" + (data.id || 0) + "/picture?type=large&access_token=" + Ti.Facebook.accessToken,
			top: "0dp",
			height: "100%",
			width: "100%",
			zIndex: 200,
			backgroundColor: "#000",
			opacity: 0.0
		});

		self.add(largeImageView);

		var animation = Titanium.UI.createAnimation();
		animation.opacity = 1.0;
		animation.duration = 300;

		largeImageView.animate(animation);

		largeImageView.addEventListener('click', function(e){
			animation.opacity = 0.0;
			animation.duration = 300;
			animation.addEventListener('complete', function(e){
				self.remove(largeImageView);
				largeImageView = null;
			});
			largeImageView.animate(animation);
		});

	});

	var locationLabel = Ti.UI.createLabel({
		top : "180dp",
		left: "5dp",
		right: "5dp",
		height : "40dp",
		width: Titanium.Platform.osname==='iphone'?"320dp":"768dp",
		textAlign: "center",
		text : data.location,
		font: {
			fontSize: 12
		}
	});

	var dateLabel = Ti.UI.createLabel({
		top: "230dp",
		left: "5dp",
		right: "5dp",
		height : "40dp",
		width: Titanium.Platform.osname==='iphone'?"320dp":"768dp",
		textAlign: "center",
		text : Date.parse(data.start_time).toString("HH:mm, dd-MMM-yyyy"),
		font: {
			fontSize: 12
		}
	});

	// RSVP buttons
	// TODO: if this event is in user's me/events, highlight button accordingly

	var attend = Ti.UI.createButton({
		top: "280dp",
		left: "5dp",
		height: "30dp",
		width: "100dp",
		title: "I'm attending"
	})

	var maybe = Ti.UI.createButton({
		top: "280dp",
		left: "110dp",
		height: "30dp",
		width: "100dp",
		title: "Don't know"
	})

	var reject = Ti.UI.createButton({
		top: "280dp",
		left: "215dp",
		height: "30dp",
		width: "100dp",
		title: "No"
	})

	attend.addEventListener('click', function(e) {
		Ti.API.info(data.id);
		Titanium.Facebook.requestWithGraphPath('/' + data.id + '/attending', {}, 'POST', function(e) {
			if(e.success) {
				Ti.API.info(e.result);
			} else {
				if(e.error) {
					Ti.API.info(e.error);
				} else {
					Ti.API.info("Unknown result");
				}
			}
		});
	});

	maybe.addEventListener('click', function(e) {
		Ti.API.info(data.id);
		Titanium.Facebook.requestWithGraphPath('/' + data.id + '/maybe', {}, 'POST', function(e) {
			if(e.success) {
				Ti.API.info(e.result);
			} else {
				if(e.error) {
					Ti.API.info(e.error);
				} else {
					Ti.API.info("Unknown result");
				}
			}
		});
	});

	reject.addEventListener('click', function(e) {
		Ti.API.info(data.id);
		Titanium.Facebook.requestWithGraphPath('/' + data.id + '/declined', {}, 'POST', function(e) {
			if(e.success) {
				Ti.API.info(e.result);
			} else {
				if(e.error) {
					Ti.API.info(e.error);
				} else {
					Ti.API.info("Unknown result");
				}
			}
		});
	});

	scrollView.add(nameLabel);
	scrollView.add(locationLabel);
	scrollView.add(dateLabel);

	scrollView.add(attend);
	scrollView.add(maybe);
	scrollView.add(reject);

	scrollView.add(imageView);

	self.add(backButton);
	self.add(scrollView);

	Titanium.Facebook.requestWithGraphPath('/' + data.id, {"limit": 0}, 'GET', function(e) {
		if(e.success) {
			var current_event = JSON.parse(e.result);

			var descriptionLabel = Ti.UI.createLabel({
				text: current_event.description,
				top: "390dp",
				height: "auto",
				width: "auto",
				left: "5dp",
				width: Titanium.Platform.osname==='iphone'?"320dp":"768dp",
				font: {
					fontSize: 12
				}
			});

			scrollView.add(descriptionLabel);

			Ti.API.info(e.result);

			// TODO: get event image from https://graph.facebook.com/331218348435/picture request to show in events list tile view
			// TODO: maybe get owner with another request (/#{current_event.owner.id})
			// TODO: cache all in json-based local storage

		} else {
			if(e.error) {
				Ti.API.info(e.error);
			} else {
				Ti.API.info("Unknown result");
			}
		}
	});

	// get all users who will attend
	// TODO: add list of friends who RSVP that
	// for this, check returned list against list of your friends (with underscore)
	// AVOID dozens of get requests to /attending/user_id!!

	Titanium.Facebook.requestWithGraphPath('/' + data.id + '/attending', {"limit": 0}, 'GET', function(e) {
		if(e.success) {
			Ti.API.info("Invited users: " + e.result);
			Ti.API.info("Friends: " + JSON.stringify(self.friends));

			var attending_ids = _.pluck(JSON.parse(e.result).data, 'id');
			var friends_ids = _.pluck(self.friends, 'id');
			var attending_friends_ids = _.intersect(attending_ids, friends_ids);

			Ti.API.info("Attending friends: "+ attending_friends_ids.length);

			var i = -1;
			_(attending_friends_ids).each(function (friend_id) {
				// http://graph.facebook.com/{friendId}/picture
				var userpic = Ti.UI.createImageView({
					image: "https://graph.facebook.com/" + (friend_id || 0) + "/picture?type=large&access_token=" + Ti.Facebook.accessToken,
					top: "320dp",
					left: (++i*64+2),
					height: "64dp",
					width: "64dp",
				});

				scrollView.add(userpic);
			});

		} else {
			if(e.error) {
				Ti.API.info(e.error);
			} else {
				Ti.API.info("Unknown result");
			}
		}
	});

	return self;
};


text:
using System;
using System.Collections;
using System.Drawing;
using System.Reactive.Linq;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
using System.Windows.Forms;
using RxMouseService;

namespace RxMouseClient
{
    partial class Program
    {
        const string SERVICENAME = "MouseService";

        static IObservable<Point> Remoting(string srv, int port)
        {
            ConfigureRemoting();

            var ms = (IMouseService)Activator.GetObject(typeof(IMouseService), string.Format("tcp://{0}:{1}/{2}", srv, port, SERVICENAME));

            return ms.GetPoints();
        }

        private static void ConfigureRemoting()
        {
            var server = new BinaryServerFormatterSinkProvider();
            server.TypeFilterLevel = TypeFilterLevel.Full;

            var client = new BinaryClientFormatterSinkProvider();

            IDictionary props = new Hashtable();
            props["port"] = 0;
            props["name"] = SERVICENAME;
            props["typeFilterLevel"] = TypeFilterLevel.Full;

            ChannelServices.RegisterChannel(new TcpChannel(props, client, null), false);
        }
    }
}


text:
package jitd.spec

case class Transform(
  name: String,
  from: MatchNode,
  to: ConstructorPattern
) {

  def invertAs(newName: String): Transform =
    Transform(newName, to.asInstanceOf[ConstructNode].toMatchPattern, from.toConstructorPattern)

  def enumName = "JITD_TRANSFORM_"+name

  override def toString =
    s"transform $name matches $from\n{\n${to.toString("  ")}\n}"
}


text:
if(navigator.userAgent.toLowerCase().indexOf('iphone') > -1){
  console.log("go iphone")
  document.body.addEventListener('touchstart', function(evt) {
  if(!evt._isScroller) {
    evt.preventDefault();
  }
   var overscroll = function(el) {
              el.addEventListener('touchstart', function() {
                var top = el.scrollTop
                  , totalScroll = el.scrollHeight
                  , currentScroll = top + el.offsetHeight;
                //If we're at the top or the bottom of the containers
                //scroll, push up or down one pixel.
                //
                //this prevents the scroll from "passing through" to
                //the body.
                if(top === 0) {
                  el.scrollTop = 1;
                } else if(currentScroll === totalScroll) {
                  el.scrollTop = top - 1;
                }
              });
              el.addEventListener('touchmove', function(evt) {
                //if the content is actually scrollable, i.e. the content is long enough
                //that scrolling can occur
                if(el.offsetHeight < el.scrollHeight)
                  evt._isScroller = true;
              });
    }
  overscroll(document.querySelector('.scroll'));
  });
 }


text:
package redis

import (
	"log"
	"os"
	"time"

	redigo "github.com/garyburd/redigo/redis"
)

// GetRedisPool returns a new redis pool
func GetRedisPool() *redigo.Pool {
	return &redigo.Pool{
		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redigo.Conn, error) {
			c, err := redigo.Dial("tcp", os.Getenv("REDIS_URL"))
			if err != nil {
				log.Fatalln("eden: failed to connect to redis at", os.Getenv("REDIS_URL"))
				return nil, err
			}
			return c, err
		},
		TestOnBorrow: func(c redigo.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}


text:
package com.capitalone.dashboard.collector;

import java.util.List;

import com.capitalone.dashboard.model.SplunkEvent;

public interface SplunkClient {
	 List<SplunkEvent> getSplunkEventList() throws Exception;
}


text:
package org.poorzerg.weixin.bean;

import org.apache.commons.lang.builder.ToStringBuilder;

/**
 * 群组信息
 *
 * @author Poorzerg
 *
 */
public class GroupInfo {
	private int id;
	private String name;
	private int count;

	public int getCount() {
		return count;
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

}


text:
class VivaldiDocumentLoader : protected content::WebContentsDelegate,
                              protected content::WebContentsObserver {
 public:
  VivaldiDocumentLoader(Profile* profile,
                        const extensions::Extension* extension);
  ~VivaldiDocumentLoader() override;

 private:
  // content::WebContentsDelegate overrides.
  bool ShouldSuppressDialogs(content::WebContents* source) override;
  bool IsNeverComposited(content::WebContents* web_contents) override;

  // content::WebContentsObserver overrides.
  void DidStartNavigation(
      content::NavigationHandle* navigation_handle) override;
  void DidFinishNavigation(
      content::NavigationHandle* navigation_handle) override;

  std::unique_ptr<content::WebContents> vivaldi_web_contents_;

  // Timers.
  base::TimeTicks start_time_;
  base::TimeTicks end_time_;
};

#endif  // VIVALDI_DOCUMENT_LOADER_DOCUMENT_H_


text:
import re
import hashlib
import sys

pattern = re.compile(r"\*\n(Builtin protocol feature: (.*)(?:\*[^/]|[^\*])*)\*/")

def main():
    with open(sys.argv[1], "r") as f:
        contents = f.read()
        print('#include <eosio/chain/protocol_feature_manager.hpp>')
        print('#include <map>')

        print('#include <boost/test/unit_test.hpp>')

        print('using namespace eosio::chain;')

        print('BOOST_AUTO_TEST_CASE(protocol_feature_digest_tests) {')
        print('   std::map<std::string, std::string> digests;')
        for match in re.finditer(pattern, contents):
            print('   digests.emplace("%s", "%s");' % (match.group(2),  hashlib.sha256(match.group(1).encode('utf8')).hexdigest()))
        print('   for(const auto& [id, spec] : builtin_protocol_feature_codenames) {')
        print('      BOOST_TEST(digests[spec.codename] == fc::variant(spec.description_digest).as<std::string>());')
        print('   }')
        print('}')

if __name__ == "__main__":
    main()


text:
package VMOMI::VirtualApp;
use parent 'VMOMI::ResourcePool';

use strict;
use warnings;

our @class_ancestors = (
    'ResourcePool',
    'ManagedEntity',
    'ExtensibleManagedObject',
    'ManagedObject',
);

our @class_members = (
    ['childLink', 'VirtualAppLinkInfo', 1, 0],
    ['datastore', 'ManagedObjectReference', 1, 0],
    ['network', 'ManagedObjectReference', 1, 0],
    ['parentFolder', 'ManagedObjectReference', 0, 0],
    ['parentVApp', 'ManagedObjectReference', 0, 0],
    ['vAppConfig', 'VAppConfigInfo', 0, 0],
);

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;


text:
use quote::quote;

/// A helper derive proc macro to flatten multiple subcommand enums into one
/// Note that it is unable to check for duplicate commands and they will be
/// tried in order of declaration
#[proc_macro_derive(FlattenSubcommand)]
pub fn flatten_subcommand(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let ast = syn::parse_macro_input!(input as syn::DeriveInput);
    let de = match ast.data {
        syn::Data::Enum(v) => v,
        _ => unreachable!(),
    };
    let name = &ast.ident;

    // An enum variant like `<name>(<ty>)`
    struct SubCommandVariant<'a> {
        name: &'a syn::Ident,
        ty: &'a syn::Type,
    }

    let variants: Vec<SubCommandVariant<'_>> = de
        .variants
        .iter()
        .map(|variant| {
            let name = &variant.ident;
            let ty = match &variant.fields {
                syn::Fields::Unnamed(field) => {
                    if field.unnamed.len() != 1 {
                        unreachable!()
                    }

                    &field.unnamed.first().unwrap().ty
                }
                _ => unreachable!(),
            };
            SubCommandVariant { name, ty }
        })
        .collect();

    let variant_ty = variants.iter().map(|x| x.ty).collect::<Vec<_>>();
    let variant_names = variants.iter().map(|x| x.name).collect::<Vec<_>>();

    (quote! {
        impl argh::FromArgs for #name {
            fn from_args(command_name: &[&str], args: &[&str])
                -> std::result::Result<Self, argh::EarlyExit>
            {
                let subcommand_name = if let Some(subcommand_name) = command_name.last() {
                    *subcommand_name
                } else {
                    return Err(argh::EarlyExit::from("no subcommand name".to_owned()));
                };

                #(
                    if <#variant_ty as argh::SubCommands>::COMMANDS
                    .iter()
                    .find(|ci| ci.name.eq(subcommand_name))
                    .is_some()
                    {
                        return <#variant_ty as argh::FromArgs>::from_args(command_name, args)
                            .map(|v| Self::#variant_names(v));
                    }
                )*

                Err(argh::EarlyExit::from("no subcommand matched".to_owned()))
            }

            fn redact_arg_values(command_name: &[&str], args: &[&str]) -> std::result::Result<Vec<String>, argh::EarlyExit> {
                let subcommand_name = if let Some(subcommand_name) = command_name.last() {
                    *subcommand_name
                } else {
                    return Err(argh::EarlyExit::from("no subcommand name".to_owned()));
                };

                #(
                    if <#variant_ty as argh::SubCommands>::COMMANDS
                    .iter()
                    .find(|ci| ci.name.eq(subcommand_name))
                    .is_some()
                    {
                        return <#variant_ty as argh::FromArgs>::redact_arg_values(
                            command_name,
                            args,
                        );
                    }

                )*

                Err(argh::EarlyExit::from("no subcommand matched".to_owned()))
            }
        }

        impl argh::SubCommands for #name {
            const COMMANDS: &'static [&'static argh::CommandInfo] = {
                const TOTAL_LEN: usize = #(<#variant_ty as argh::SubCommands>::COMMANDS.len())+*;
                const COMMANDS: [&'static argh::CommandInfo; TOTAL_LEN] = {
                    let slices = &[#(<#variant_ty as argh::SubCommands>::COMMANDS,)*];
                    // Its not possible for slices[0][0] to be invalid
                    let mut output = [slices[0][0]; TOTAL_LEN];

                    let mut output_index = 0;
                    let mut which_slice = 0;
                    while which_slice < slices.len() {
                        let slice = &slices[which_slice];
                        let mut index_in_slice = 0;
                        while index_in_slice < slice.len() {
                            output[output_index] = slice[index_in_slice];
                            output_index += 1;
                            index_in_slice += 1;
                        }
                        which_slice += 1;
                    }
                    output
                };
                &COMMANDS
            };
        }
    })
    .into()
}

/// A helper proc macro to pad strings so that argh would break them at intended points
#[proc_macro_attribute]
pub fn pad_description_for_argh(
    _attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let mut item = syn::parse_macro_input!(item as syn::Item);
    if let syn::Item::Struct(s) = &mut item {
        if let syn::Fields::Named(fields) = &mut s.fields {
            for f in fields.named.iter_mut() {
                for a in f.attrs.iter_mut() {
                    if a.path
                        .get_ident()
                        .map(|i| i.to_string())
                        .unwrap_or_default()
                        == *"doc"
                    {
                        if let Ok(syn::Meta::NameValue(nv)) = a.parse_meta() {
                            if let syn::Lit::Str(s) = nv.lit {
                                let doc = s
                                    .value()
                                    .lines()
                                    .map(|s| format!("{: <61}", s))
                                    .collect::<String>();
                                *a = syn::parse_quote! { #[doc= #doc] };
                            }
                        }
                    }
                }
            }
        } else {
            unreachable!()
        }
    } else {
        unreachable!()
    }
    quote! {
        #item
    }
    .into()
}


text:
var defaultLocation = {
	"city": null,
    "country": null,
    "location": "Easter Island",
    "region": null
};

var Artist = function () {

	this.name;

	this.id;

	this.spotId;

	this.genres;

	this.popularity;

	this.albums = [];

	this.images;

	this.terms;

	this.location;

	this.popularityOverTime;

	this.minActivityYear;

	this.maxActivityYear;

};

Artist.prototype.artistFromEchoJSON = function ( json ) {

	var art = json[ 'artist' ];

	this.name = art[ 'name' ];
	this.id = art[ 'id' ];
	this.spotId = art[ 'foreign_ids'] ? art[ 'foreign_ids' ][ 0 ][ 'foreign_id' ].split( ':' )[2] : null;
	this.genres = art[ 'genres' ];
	this.location = art[ 'artist_location' ] ? art[ 'artist_location' ] : defaultLocation;
	this.terms = art[ 'terms' ];
};

Artist.prototype.artistFromSpotifyJSON = function ( json ) {

	this.images = json[ "images" ];
};

Artist.prototype.albumsFromSpotifyJSON = function ( json ) {

	var albumPerYear = {};

	for ( var a in json[ 'albums' ] ) {
		var album = new Album();
		album.albumFromSpotifyJSON( json[ 'albums' ][ a ] );

		// Add only the more popular album for year
		if ( !albumPerYear[ album.year ] || album.popularity > albumPerYear[ album.year ].popularity ) {
			albumPerYear[ album.year ] = album;
		}
	}

	for ( var k in albumPerYear ) {
		this.albums.push( albumPerYear[ k ] );
	}

};

Artist.prototype.getPopularityOverTime = function () {

	if ( this.popularityOverTime ) {
		return this.popularityOverTime;
	}
	return this.popularityOverTime = this.computePopularity();
};

Artist.prototype.computePopularity = function () {

	var startingYear = 1940;
	var currentYear = 2015;

	var top = startingYear;
	var bot = currentYear;

	var popularity = [];
	var yearToPop = {};

	function weight( x ) {
		if ( x > currentYear ) {
			x = currentYear;
		}
		// Linear weight, to enhance older artists:
		// when x = currentYear y = 1
		// when x = startingYear y = 10
		var m = ( 1 - 5 ) / ( currentYear - startingYear );
		return m * ( x - currentYear ) + 1;
	}

	function smooth ( x ) {
		var sdsq = .5;
		// Change smoothing function for different shapes
		return Math.exp( -x * x / sdsq );
		// return Math.pow( x, alpha ) * Math.exp( -x * beta );
	}

	if ( allArtistsStatic[ this.name ] ) {
		// Static data available
		var staticData = allArtistsStatic[ this.name ];

		for ( var i in staticData ) {
			yearToPop[ staticData[ i ][ "year" ] ] = staticData[ i ][ "value" ]
			if ( +staticData[ i ][ "year" ] > top ) {
				top = +staticData[ i ][ "year" ];
			}
			if ( +staticData[ i ][ "year" ] < bot ) {
				bot = +staticData[ i ][ "year" ];
			}
		}

	} else {

		for ( var i = 0, len = this.albums.length; i < len; ++i ) {
			yearToPop[ this.albums[ i ].year ] = this.albums[ i ].popularity;
			if ( this.albums[ i ].year > top ) {
				top = this.albums[ i ].year;
			}
			if ( this.albums[ i ].year < bot ) {
				bot = this.albums[ i ].year;
			}
		}

	}
	// Smooth popularity
	var smoothedPopularity = {};
	for ( var i = startingYear; i <= currentYear; ++i  ) {
		smoothedPopularity[ i ] = 0;
		for ( var j = startingYear; j <= currentYear; ++j ) {
			smoothedPopularity[ i ] += ( yearToPop[ j ] || 0 ) * smooth( i - j );
		}
		// Weight popularity
		//smoothedPopularity[ i ] *= weight( i );
	}
	// Format popularity
	for ( var i = startingYear; i <= currentYear; ++i) {
		popularity.push( { "name": this.name, "date": i.toString(), "value": smoothedPopularity[ i ] || 0 } );
	}
	// Set min and max activity year
	var delta = 3;
	bot = +bot;
	top = +top;
	this.minActivityYear = _.max( [ bot - delta, startingYear ] );
	this.maxActivityYear = _.min( [ top + delta, currentYear ]  );

	return popularity;

};


text:
Simple ping6 application for testing purpose.
=============================================

The user should wait for the prompt and input the ping6 command followed by the
destination IPv6 address. The address should not use any abbreviated form (the
application does very little input format check).

E.g. of a correct command:

    > ping6 fe80:0000:0000:0000:02bd:07ff:fee2:1c00

The ping6 application will then send PING6_NB = 5 ping request packets.


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

<title>ca.ualberta.cs.xpertsapp.views Class Hierarchy</title>
<meta name="date" content="2015-12-11">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package ca.ualberta.cs.xpertsapp.views

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

android.content.Context

android.content.ContextWrapper

android.view.ContextThemeWrapper

android.app.Activity (implements android.content.ComponentCallbacks2, android.view.KeyEvent.Callback, android.view.LayoutInflater.Factory2, android.view.View.OnCreateContextMenuListener, android.view.Window.Callback)

ca.ualberta.cs.xpertsapp.views.AddServiceActivity

ca.ualberta.cs.xpertsapp.views.BrowseServiceDetailsActivity

ca.ualberta.cs.xpertsapp.views.BrowseServicesActivity (implements android.widget.AdapterView.OnItemSelectedListener)

ca.ualberta.cs.xpertsapp.views.EditProfileActivity

ca.ualberta.cs.xpertsapp.views.FriendProfileActivity

ca.ualberta.cs.xpertsapp.views.FriendsActivity

ca.ualberta.cs.xpertsapp.views.FriendServiceDetailsActivity

ca.ualberta.cs.xpertsapp.views.IncomingOfferActivity

ca.ualberta.cs.xpertsapp.views.LoginActivity

ca.ualberta.cs.xpertsapp.views.MainActivity

ca.ualberta.cs.xpertsapp.views.OfferCounterTradeActivity

ca.ualberta.cs.xpertsapp.views.OfferTradeActivity

ca.ualberta.cs.xpertsapp.views.OutgoingOfferActivity

ca.ualberta.cs.xpertsapp.views.ServiceDetailsActivity

ca.ualberta.cs.xpertsapp.views.TopTradersActivity

ca.ualberta.cs.xpertsapp.views.TradeListActivity

ca.ualberta.cs.xpertsapp.views.ViewProfileActivity

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

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

/**
 * API System
 *
 * The API System uses xml-rpc to communicate.
 *
 * @package		API
 * @subpackage	API
 * @category	API
 * @author		68kb Dev Team
 * @link		http://68kb.com/user_guide/developer/api.html
 * @version 	$Id: api.php 112 2009-11-10 01:08:48Z suzkaw68 $
 */
class Api extends controller
{

	/**
	* Constructor
	*
	* Requires needed models and helpers.
	*
	* @access	public
	*/
	function __construct()
	{
		parent::__construct();
		$this->load->model('init_model');
		$this->load->model('category_model');
		$this->load->model('article_model');
	}

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

	/**
	 * Route the function
	 *
	 * @access	public
	 */
	function index()
	{
		$this->load->library('xmlrpc');
		$this->load->library('xmlrpcs');

		// Users
		$config['functions']['add_user'] = array('function' => 'Api.add_user');
		$config['functions']['edit_user'] = array('function' => 'Api.edit_user');
		$config['functions']['get_user'] = array('function' => 'Api.get_user');

		// Articles
		$config['functions']['add_article'] = array('function' => 'Api.add_article');
		$config['functions']['edit_article'] = array('function' => 'Api.edit_article');
		$config['functions']['add_article_to_cats'] = array('function' => 'Api.add_article_to_cats');

		// Comments
		$config['functions']['add_comment'] = array('function' => 'Api.add_comment');
		$config['functions']['edit_comment'] = array('function' => 'Api.edit_comment');

		$this->xmlrpcs->initialize($config);
		$this->xmlrpcs->serve();
	}

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

	/**
	 * Check for a valid user account
	 *
	 * @access	public
	 */
	private function check_access($username, $password)
	{
		$this->db->where('username', $username);
		$this->db->where('password', md5($password));
		$query = $this->db->get('users');

		if ($query->num_rows() == 1)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

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

	/**
	* Username check
	*
	* Checks to see if a username is in use.
	*
	* @access	public
	*/
	private function _username_check($str)
	{
		$this->db->select('id')->from('users')->where('username', $str);
		$query = $this->db->get();
		//echo $this->db->last_query();
		if ($query->num_rows() > 0)
		{
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}

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

	/**
	 * Add a new users
	 *
	 * Parameters:
	 * <code>
	 * 	$request = array(
	 *		array(array('username'=>'demo', 'password' => 'demo'),'struct'),
	 *		array(array('firstname'=>'John','lastname'=>'Smith','email'=>'john@smith.com','username'=>'john','password'=>'john'),'struct')
	 *	);
	 * </code>
	 *
	 * @access	public
	 */
	function add_user($request)
	{
		$parameters = $request->output_parameters();

		$username = $parameters['0']['username'];
		$password = $parameters['0']['password'];

		if( ! $this->check_access($username, $password))
		{
			return $this->xmlrpc->send_error_message('100', 'Invalid Access');
		}

		$error = '';
		//check errors
		$user_firstname = $parameters['1']['firstname'];
		$user_lastname = $parameters['1']['lastname'];
		$user_email = $parameters['1']['email'];
		$user_username = $parameters['1']['username'];
		$user_password = $parameters['1']['password'];
		if($user_username == '')
		{
			$error .= 'Username required'."\n";
		}
		if($user_password == '')
		{
			$error .= 'Password required'."\n";
		}
		if( ! $this->_username_check($user_username))
		{
			$error .= 'Username already exists'."\n";
		}
		if($error <> '')
		{
			return $this->xmlrpc->send_error_message('101', $error);
		}

		$user_password = md5($user_password);

		$data = array(
			    'firstname' => $user_firstname,
			    'lastname' => $user_lastname,
			    'email' => $user_email,
			    'username' => $user_username,
			    'password' => $user_password,
			    'joindate' => time()
			);
		if ($this->db->insert('users', $data))
		{
			$id = $this->db->insert_id();
			$response = array(array('id'  => $id), 'struct');
	        return $this->xmlrpc->send_response($response);
		}
		else
		{
			$response = array(false, 'boolean');
			return $this->xmlrpc->send_response($response);
		}
	}

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

	/**
	 * Edit a users
	 *
	 * @access	public
	 */
	function edit_user($request)
	{
		$parameters = $request->output_parameters();

		$username = $parameters['0']['username'];
		$password = $parameters['0']['password'];

		if( ! $this->check_access($username, $password))
		{
			return $this->xmlrpc->send_error_message('100', 'Invalid Access');
		}

		$error = '';
		//check errors
		$user_id = $parameters['1']['id'];
		$user_firstname = $parameters['1']['firstname'];
		$user_lastname = $parameters['1']['lastname'];
		$user_email = $parameters['1']['email'];
		$user_username = $parameters['1']['username'];
		$user_password = $parameters['1']['password'];
		if($user_username == '')
		{
			$error .= 'Username required'."\n";
		}
		if($user_password == '')
		{
			$error .= 'Password required'."\n";
		}
		if($error <> '')
		{
			return $this->xmlrpc->send_error_message('101', $error);
		}

		$user_password = md5($user_password);
		$data = array(
			    'firstname' => $user_firstname,
			    'lastname' => $user_lastname,
			    'email' => $user_email,
			    'username' => $user_username,
			    'password' => $user_password
			);
		$this->db->where('id', $user_id);
		if ($this->db->update('users', $data))
		{
			$response = array(true, 'boolean');
	        return $this->xmlrpc->send_response($response);
		}
		else
		{
			$response = array(false, 'boolean');
	        return $this->xmlrpc->send_response($response);
		}
	}

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

	/**
	 * Get User
	 *
	 * @access	public
	 */
	function get_user($request)
	{
		$parameters = $request->output_parameters();

		$username = $parameters['0']['username'];
		$password = $parameters['0']['password'];

		if( ! $this->check_access($username, $password))
		{
			return $this->xmlrpc->send_error_message('100', 'Invalid Access');
		}
		$user_username = $parameters['1']['username'];

		$this->db->from('users')->where('username', $user_username);
		$query = $this->db->get();
		if ($query->num_rows() > 0)
		{
			$row = $query->row();

			$response = array(array('id'    => array($row->id,'string'),
									'username'  => array($row->username,'string'),
	                                'firstname' => array($row->firstname,'string'),
	                                'lastname'  => array($row->lastname,'string'),
	                                'email'  => array($row->email,'string'),
	                                'joindate' => array($row->joindate,'string')
	                                ),
	                         'struct');

	        return $this->xmlrpc->send_response($response);
		}
		else
		{
			$response = array(false, 'boolean');
			return $this->xmlrpc->send_response($response);
		}
	}

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

	/**
	 * Add a new article
	 *
	 * @access	public
	 */
	function add_article($request)
	{
		$parameters = $request->output_parameters();

		$username = $parameters['0']['username'];
		$password = $parameters['0']['password'];

		if( ! $this->check_access($username, $password))
		{
			return $this->xmlrpc->send_error_message('100', 'Invalid Access');
		}
		$error = '';
		//check errors
		$article_author = $parameters['1']['article_author'];
		$article_title = $parameters['1']['article_title'];
		$article_keywords = $parameters['1']['article_keywords'];
		$article_short_desc = $parameters['1']['article_short_desc'];
		$article_description = $parameters['1']['article_description'];
		$article_display = $parameters['1']['article_display'];
		if($article_author == '')
		{
			$error .= 'Author required'."\n";
		}
		if($article_title == '')
		{
			$error .= 'Title required'."\n";
		}
		if($article_description == '')
		{
			$error .= 'Description required'."\n";
		}
		if($error <> '')
		{
			return $this->xmlrpc->send_error_message('101', $error);
		}
		$data = array(
			'article_author' => $article_author,
			'article_title' => $article_title,
			'article_keywords' => $article_keywords,
			'article_short_desc' => $article_short_desc,
			'article_description' => $article_description,
			'article_display' => $article_display
		);
		$id = $this->article_model->add_article($data);
		if(is_int($id))
		{
			$response = array(array('id'  => $id), 'struct');
	        return $this->xmlrpc->send_response($response);
		}
		else
		{
			$response = array(false, 'boolean');
			return $this->xmlrpc->send_response($response);
		}
	}

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

	/**
	 * Edit an article
	 *
	 * @access	public
	 */
	function edit_article($request)
	{
		$parameters = $request->output_parameters();

		$username = $parameters['0']['username'];
		$password = $parameters['0']['password'];

		if( ! $this->check_access($username, $password))
		{
			return $this->xmlrpc->send_error_message('100', 'Invalid Access');
		}
		$error = '';
		//check errors
		$article_id = $parameters['1']['article_id'];
		$article_author = $parameters['1']['article_author'];
		$article_title = $parameters['1']['article_title'];
		$article_keywords = $parameters['1']['article_keywords'];
		$article_short_desc = $parameters['1']['article_short_desc'];
		$article_description = $parameters['1']['article_description'];
		$article_display = $parameters['1']['article_display'];
		if($article_author == '')
		{
			$error .= 'Author required'."\n";
		}
		if($article_title == '')
		{
			$error .= 'Title required'."\n";
		}
		if($article_description == '')
		{
			$error .= 'Description required'."\n";
		}
		if($error <> '')
		{
			return $this->xmlrpc->send_error_message('101', $error);
		}
		$data = array(
			'article_author' => $article_author,
			'article_title' => $article_title,
			'article_keywords' => $article_keywords,
			'article_short_desc' => $article_short_desc,
			'article_description' => $article_description,
			'article_display' => $article_display
		);
		$this->db->where('article_id', $article_id);
		if ($this->db->update('articles', $data))
		{
			$response = array(true, 'boolean');
	        return $this->xmlrpc->send_response($response);
		}
		else
		{
			$response = array(false, 'boolean');
	        return $this->xmlrpc->send_response($response);
		}
	}

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

	/**
	 * Add article to category
	 *
	 * @todo Get this working. :)
	 * @access	public
	 */
	function add_article_to_cats($request)
	{
		$parameters = $request->output_parameters();

		$username = $parameters['0']['username'];
		$password = $parameters['0']['password'];

		if( ! $this->check_access($username, $password))
		{
			return $this->xmlrpc->send_error_message('100', 'Invalid Access');
		}
		$error = '';
		//check errors
		$article_id = $parameters['1']['article_id'];
		$cats = $parameters['1']['cats'];
		if($article_id == '')
		{
			$error .= 'Article ID required'."\n";
		}
		if($cats == '')
		{
			$error .= 'Category array is required'."\n";
		}
		if($error <> '')
		{
			return $this->xmlrpc->send_error_message('101', $error);
		}
		if($this->category_model->insert_cats($article_id, $cats))
		{
			//$response = array(array('response'  => TRUE), 'boolean');
			$response = array(true, 'boolean');
	        return $this->xmlrpc->send_response($response);
		}
		else
		{
			$response = array(false, 'boolean');
	        return $this->xmlrpc->send_response($response);
		}
	}

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

	/**
	 * Add a comment
	 *
	 * @access	public
	 */
	function add_comment($request)
	{
		$parameters = $request->output_parameters();

		$username = $parameters['0']['username'];
		$password = $parameters['0']['password'];

		if( ! $this->check_access($username, $password))
		{
			return $this->xmlrpc->send_error_message('100', 'Invalid Access');
		}

		//check errors
		$error = '';
		$comment_author = $parameters['1']['comment_author'];
		$comment_article_ID = $parameters['1']['comment_article_ID'];
		$comment_author_email = $parameters['1']['comment_author_email'];
		$comment_content = $parameters['1']['comment_content'];

		if($comment_author == '')
		{
			$error .= 'Author required'."\n";
		}
		if($comment_article_ID == '')
		{
			$error .= 'Article ID is required'."\n";
		}
		if($comment_author_email == '')
		{
			$error .= 'Author Email required'."\n";
		}
		if($comment_content == '')
		{
			$error .= 'Description required'."\n";
		}
		if($error <> '')
		{
			return $this->xmlrpc->send_error_message('101', $error);
		}

		$data = array(
			'comment_article_ID' => $comment_article_ID,
			'comment_author' => $comment_author,
			'comment_author_email' => $comment_author_email,
			'comment_content' => $comment_content,
			'comment_approved' => 1
		);
		$this->db->insert('comments', $data);
		$id = $this->db->insert_id();
		if(is_int($id))
		{
			$response = array(array('id'  => $id), 'struct');
	        return $this->xmlrpc->send_response($response);
		}
		else
		{
			$response = array(false, 'boolean');
			return $this->xmlrpc->send_response($response);
		}
	}

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

	/**
	 * Edit a comment
	 *
	 * @access	public
	 */
	function edit_comment($request)
	{
		$parameters = $request->output_parameters();

		$username = $parameters['0']['username'];
		$password = $parameters['0']['password'];

		if( ! $this->check_access($username, $password))
		{
			return $this->xmlrpc->send_error_message('100', 'Invalid Access');
		}

		//check errors
		$error = '';
		$comment_ID = $parameters['1']['comment_ID'];
		$comment_author = $parameters['1']['comment_author'];
		$comment_article_ID = $parameters['1']['comment_article_ID'];
		$comment_author_email = $parameters['1']['comment_author_email'];
		$comment_content = $parameters['1']['comment_content'];
		$comment_approved = $parameters['1']['comment_approved'];

		if($comment_ID == '')
		{
			$error .= 'Comment id required'."\n";
		}
		if($comment_author == '')
		{
			$error .= 'Author required'."\n";
		}
		if($comment_article_ID == '')
		{
			$error .= 'Article ID is required'."\n";
		}
		if($comment_author_email == '')
		{
			$error .= 'Author Email required'."\n";
		}
		if($comment_content == '')
		{
			$error .= 'Description required'."\n";
		}
		if($error <> '')
		{
			return $this->xmlrpc->send_error_message('101', $error);
		}

		$data = array(
			'comment_article_ID' => $comment_article_ID,
			'comment_author' => $comment_author,
			'comment_author_email' => $comment_author_email,
			'comment_content' => $comment_content,
			'comment_approved' => $comment_approved
		);
		$this->db->where('comment_ID', $comment_ID);
		$this->db->update('comments', $data);
		if($this->db->affected_rows() > 0)
		{
			$response = array(true, 'boolean');
	        return $this->xmlrpc->send_response($response);
		}
		else
		{
			$response = array(false, 'boolean');
			return $this->xmlrpc->send_response($response);
		}
	}
}


text:
export { default as RedBlock } from './RedBlock/RedBlock';
export { default as BlueBlock } from './BlueBlock/BlueBlock';


text:
package com.tapglue.model.queries;

public enum TGQueryType {

    EQUALS("eq"),IN("in");

    private String stringRepresentation;

    TGQueryType(String representation) {
        stringRepresentation = representation;
    }

    public String getStringRepresentation() {
        return stringRepresentation;
    }

    /**
     * Get object by representing string
     * @param rep String name
     * @return Object or null when not correct
     */
    public static TGQueryType fromString(String rep) {
        if (rep == null)
            return null;
        for (TGQueryType val : values()) {
            if (val.getStringRepresentation().equalsIgnoreCase(rep))
                return val;
        }
        return null;
    }
}


text:
package org.xmlactions.pager.actions.form.templates;

import org.xmlactions.common.theme.Theme;
import org.xmlactions.pager.actions.form.ThemeConst;

public class HtmlTextArea extends Html
{

	public HtmlTextArea()
	{
		super(HtmlEnum.label_textarea.getAttributeName());
	}

	public HtmlTextArea(Theme theme)
	{
		super(HtmlEnum.label_textarea.getAttributeName());
		setClazz(theme.getValue(ThemeConst.INPUT_TEXTAREA.toString()));
	}

	public void setName(String value)
	{
		put(HtmlEnum.name.getAttributeName(), value);
	}

	/** Specifies the height of the textarea based on the number of visible lines of text. If there's more text than this allows, users can scroll using the textarea's scrollbars. */
	public void setRows(String value)
	{
		put(HtmlEnum.rows.getAttributeName(), value);
	}

	/** Specifies the width of the textarea based on the number of visible character widths.  */
	public void setCols(String value)
	{
		put(HtmlEnum.cols.getAttributeName(), value);
	}

}


text:
package vspk

import "github.com/nuagenetworks/go-bambou/bambou"

// NSGUpgradeProfileIdentity represents the Identity of the object
var NSGUpgradeProfileIdentity = bambou.Identity{
	Name:     "nsgupgradeprofile",
	Category: "nsgupgradeprofiles",
}

// NSGUpgradeProfilesList represents a list of NSGUpgradeProfiles
type NSGUpgradeProfilesList []*NSGUpgradeProfile

// NSGUpgradeProfilesAncestor is the interface that an ancestor of a NSGUpgradeProfile must implement.
// An Ancestor is defined as an entity that has NSGUpgradeProfile as a descendant.
// An Ancestor can get a list of its child NSGUpgradeProfiles, but not necessarily create one.
type NSGUpgradeProfilesAncestor interface {
	NSGUpgradeProfiles(*bambou.FetchingInfo) (NSGUpgradeProfilesList, *bambou.Error)
}

// NSGUpgradeProfilesParent is the interface that a parent of a NSGUpgradeProfile must implement.
// A Parent is defined as an entity that has NSGUpgradeProfile as a child.
// A Parent is an Ancestor which can create a NSGUpgradeProfile.
type NSGUpgradeProfilesParent interface {
	NSGUpgradeProfilesAncestor
	CreateNSGUpgradeProfile(*NSGUpgradeProfile) *bambou.Error
}

// NSGUpgradeProfile represents the model of a nsgupgradeprofile
type NSGUpgradeProfile struct {
	ID                  string `json:"ID,omitempty"`
	ParentID            string `json:"parentID,omitempty"`
	ParentType          string `json:"parentType,omitempty"`
	Owner               string `json:"owner,omitempty"`
	Name                string `json:"name,omitempty"`
	LastUpdatedBy       string `json:"lastUpdatedBy,omitempty"`
	Description         string `json:"description,omitempty"`
	MetadataUpgradePath string `json:"metadataUpgradePath,omitempty"`
	EnterpriseID        string `json:"enterpriseID,omitempty"`
	EntityScope         string `json:"entityScope,omitempty"`
	DownloadRateLimit   int    `json:"downloadRateLimit,omitempty"`
	ExternalID          string `json:"externalID,omitempty"`
}

// NewNSGUpgradeProfile returns a new *NSGUpgradeProfile
func NewNSGUpgradeProfile() *NSGUpgradeProfile {

	return &NSGUpgradeProfile{
		DownloadRateLimit: 10000,
	}
}

// Identity returns the Identity of the object.
func (o *NSGUpgradeProfile) Identity() bambou.Identity {

	return NSGUpgradeProfileIdentity
}

// Identifier returns the value of the object's unique identifier.
func (o *NSGUpgradeProfile) Identifier() string {

	return o.ID
}

// SetIdentifier sets the value of the object's unique identifier.
func (o *NSGUpgradeProfile) SetIdentifier(ID string) {

	o.ID = ID
}

// Fetch retrieves the NSGUpgradeProfile from the server
func (o *NSGUpgradeProfile) Fetch() *bambou.Error {

	return bambou.CurrentSession().FetchEntity(o)
}

// Save saves the NSGUpgradeProfile into the server
func (o *NSGUpgradeProfile) Save() *bambou.Error {

	return bambou.CurrentSession().SaveEntity(o)
}

// Delete deletes the NSGUpgradeProfile from the server
func (o *NSGUpgradeProfile) Delete() *bambou.Error {

	return bambou.CurrentSession().DeleteEntity(o)
}


text:
Full Screen Photo Tour

https://alucidwolf.github.io/lenspt/


text:
using NPoco;
using Umbraco.Cms.Core;
using Umbraco.Cms.Infrastructure.Persistence.DatabaseAnnotations;
using Umbraco.Cms.Infrastructure.Persistence.DatabaseModelDefinitions;
using Umbraco.Cms.Infrastructure.Persistence.Dtos;

namespace Umbraco.Cms.Infrastructure.Migrations.Upgrade.V_8_0_0.Models;

/// <summary>
///     Snapshot of the <see cref="PropertyTypeDto" /> as it was at version 8.0
/// </summary>
/// <remarks>
///     This is required during migrations before 8.6 since the schema has changed and running SQL against the new table
///     would result in errors
/// </remarks>
[TableName(Constants.DatabaseSchema.Tables.PropertyType)]
[PrimaryKey("id")]
[ExplicitColumns]
internal class PropertyTypeDto80
{
    [Column("id")]
    [PrimaryKeyColumn(IdentitySeed = 50)]
    public int Id { get; set; }

    [Column("dataTypeId")]
    [ForeignKey(typeof(DataTypeDto), Column = "nodeId")]
    public int DataTypeId { get; set; }

    [Column("contentTypeId")]
    [ForeignKey(typeof(ContentTypeDto), Column = "nodeId")]
    public int ContentTypeId { get; set; }

    [Column("propertyTypeGroupId")]
    [NullSetting(NullSetting = NullSettings.Null)]
    [ForeignKey(typeof(PropertyTypeGroupDto))]
    public int? PropertyTypeGroupId { get; set; }

    [Index(IndexTypes.NonClustered, Name = "IX_cmsPropertyTypeAlias")]
    [Column("Alias")]
    public string Alias { get; set; } = null!;

    [Column("Name")]
    [NullSetting(NullSetting = NullSettings.Null)]
    public string? Name { get; set; }

    [Column("sortOrder")]
    [Constraint(Default = "0")]
    public int SortOrder { get; set; }

    [Column("mandatory")]
    [Constraint(Default = "0")]
    public bool Mandatory { get; set; }

    [Column("validationRegExp")]
    [NullSetting(NullSetting = NullSettings.Null)]
    public string? ValidationRegExp { get; set; }

    [Column("Description")]
    [NullSetting(NullSetting = NullSettings.Null)]
    [Length(2000)]
    public string? Description { get; set; }

    [Column("variations")]
    [Constraint(Default = "1" /*ContentVariation.InvariantNeutral*/)]
    public byte Variations { get; set; }

    [ResultColumn]
    [Reference(ReferenceType.OneToOne, ColumnName = "DataTypeId")]
    public DataTypeDto? DataTypeDto { get; set; }

    [Column("UniqueID")]
    [NullSetting(NullSetting = NullSettings.NotNull)]
    [Constraint(Default = SystemMethods.NewGuid)]
    [Index(IndexTypes.UniqueNonClustered, Name = "IX_cmsPropertyTypeUniqueID")]
    public Guid UniqueId { get; set; }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft">
//   Copyright (c) 2013 Microsoft Corporation
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System.Collections.Generic;
using Microsoft.Research.DataOnboarding.DomainModel;
using Microsoft.Research.DataOnboarding.Utilities.Model;

namespace Microsoft.Research.DataOnboarding.RepositoriesService.Interface
{
    public interface IRepositoryService
    {
        /// <summary>
        ///  Method to retrieve all the available repositories.
        /// </summary>
        /// <param name="includeAdminRepositories">bool indicates if repositories marked as AdminOnly should be returned or not</param>
        /// <returns></returns>
        IEnumerable<RepositoryDataModel> RetrieveRepositories(bool includeAdminRepositories);

        /// <summary>
        /// Method to retrieve all the repository types.
        /// </summary>
        /// <returns>list of repository types.</returns>
        IEnumerable<BaseRepository> RetrieveRepositoryTypes();

        /// <summary>
        /// Method to get the repository for the specific repository id.
        /// </summary>
        /// <param name="repositoryId">Repository id.</param>
        /// <returns>Repository object.</returns>
        Repository GetRepositoryById(int repositoryId);

        /// <summary>
        /// Method to get the repository for the specific repository name.
        /// </summary>
        /// <param name="name">Repository name.</param>
        /// <returns>Repository object.</returns>
        Repository GetRepositoryByName(string name);

        /// <summary>
        /// Method to  add\update the repository details.
        /// </summary>
        /// <param name="repositoryDetails">Repository details.</param>
        /// <returns>Returns true if success else false.</returns>
        bool AddUpdateRepository(Repository repositoryDetails);

        /// <summary>
        /// Method to delete the specific repository.
        /// </summary>
        /// <param name="repositoryId">Repository id.</param>
        /// <returns>Returns true if success else false.</returns>
        bool DeleteRepository(int repositoryId);

        /// <summary>
        /// Method to delete the specific repository metadata fields.
        /// </summary>
        /// <param name="repositoryId">Repository id.</param>
        /// <param name="repositoryMetaDataFields">repositoryMetaDataFields seperated  by commas</param>
        /// <returns>Returns true if success else false.</returns>
        bool DeleteRepositoryMetaDataFields(int repositoryId, string repositoryMetaDataFields);

        /// <summary>
        /// Method to check the duplicate repository name.
        /// </summary>
        /// <param name="repositoryName">Repository name.</param>
        /// <returns>Repository id if exists else 0.</returns>
        int CheckRepositoryExists(string repositoryName);

        /// <summary>
        /// Returns the Metadata Types.
        /// </summary>
        /// <returns>Metadata Types.</returns>
        IEnumerable<MetadataType> GetMetadataTypes();

        /// <summary>
        /// Gets all the repositories that allows a file extension.
        /// </summary>
        /// <param name="isAdmin">Is administrator</param>
        /// <param name="fileExtension">File extension.</param>
        /// <returns></returns>
        IEnumerable<Repository> GetRepositoriesByRoleAndFileExtension(bool isAdmin, string fileExtension);
    }
}


text:
module.exports = function(options) {

    var RequestValidator = require('./request-validator'),
        jsonParser = require('body-parser').json(),
        app = options.express,
        route = options.route || "/",
        appId = options.applicationId || "",
        launchCallback = null,
        endedCallback = null,
        intents = {};

    app.post(route, jsonParser, RequestValidator, function(req, res) {

        if(req.body.session.application.applicationId == appId || !appId.length) {

            switch(req.body.request.type) {

                case "LaunchRequest":
                    if(launchCallback)
                        launchCallback(req, res);
                    else
                        throw ("LaunchRequest not handled")
                    break;
                case "IntentRequest":

                    if(!req.body.session.attributes)
                        req.body.session.attributes = {};

                    if(intents[req.body.request.intent.name])
                        intents[req.body.request.intent.name](req, res, req.body.request.intent.slots, req.body.session.attributes);
                    else
                        throw ("IntentRequest for `" + req.body.request.intent.name + "` not handled")
                    break;
                case "SessionEndedRequest":
                    if(endedCallback)
                        endedCallback(req, res, req.body.request.reason);
                    res.json({});
                    break;
            }
        }
    });

    this.launch = function(callback) {
        launchCallback = callback;
    };

    this.intent = function(name, callback) {
        intents[name] = callback;
    };

    this.ended = function(callback) {
        endedCallback = callback;
    };

    this.send = function(req, res, options, sessionAttributes) {

        if(!("shouldEndSession" in options))
            options.shouldEndSession = true;

        var response = {
            version: req.body.version,
            sessionAttributes: (sessionAttributes || req.body.session.attributes),
            response: {
                shouldEndSession: options.shouldEndSession
            }
        }

        if(options.outputSpeech && options.outputSpeech.length) {
            response.response.outputSpeech = {
                type: "PlainText",
                text: options.outputSpeech
            };
        } else if(options.outputSSML && options.outputSSML.length) {
            response.response.outputSpeech = {
                type: "SSML",
                ssml: options.outputSSML
            };
        }

        if(options.reprompt && options.reprompt.length) {
            response.response.reprompt = {
                outputSpeech: {
                    type: "PlainText",
                    text: options.reprompt
                }
            };
        } else if(options.repromptSSML && options.repromptSSML.length) {
            response.response.reprompt = {
                outputSpeech: {
                    type: "SSML",
                    ssml: options.repromptSSML
                }
            };
        }

        if(options.card) {
            response.response.card = options.card;
        }

        res.header("Content-Type", "application/json; charset=utf-8");
        res.json(response);

    };

    this.buildCard = function(title, content) {
        return this.buildSimpleCard(title, content);
    };

    this.buildSimpleCard = function(title, content) {
        var card = {};
        card.type = "Simple";
        card.title = title;
        card.content = content;
        return card;
    }

    this.buildStandardCard = function(title, text, smallImageUrl,largeImageUrl)
    {
        var card = {};
        card.type = "Standard";
        card.title = title;
        card.text = text;
        card.image = {};
        card.image.smallImageUrl = smallImageUrl;
        card.image.largeImageUrl = largeImageUrl;
        return card;
    }

    this.buildLinkAccountCard = function(text)
    {
        var card = {};
        card.type = "LinkAccount";
        card.text = text;
        return card;
    }

};


text:
Services

We offer a quite place to write at Industrious Brooklyn, an elagant, professional coworking space.

Quiet Desk Space

We offer 24/7 shared desk space with wifi.

Community

Be a part of a larger community with weekly happy hour and events.

Free Printing+

Free printing, conference room, food and refreshments!


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

'use strict';

const globalCacheStore = new Map<string, { expiry: number; data: any }>();

/**
 * Gets a cache store to be used to store return values of methods or any other.
 *
 * @returns
 */
export function getGlobalCacheStore() {
    return globalCacheStore;
}

export function getCacheKeyFromFunctionArgs(keyPrefix: string, fnArgs: any[]): string {
    const argsKey = fnArgs.map((arg) => `${JSON.stringify(arg)}`).join('-Arg-Separator-');
    return `KeyPrefix=${keyPrefix}-Args=${argsKey}`;
}

export function clearCache() {
    globalCacheStore.clear();
}

type CacheData<T> = {
    value: T;
    expiry: number;
};

/**
 * InMemoryCache caches a single value up until its expiry.
 */
export class InMemoryCache<T> {
    private cacheData?: CacheData<T>;

    constructor(protected readonly expiryDurationMs: number) {}
    public get hasData() {
        if (!this.cacheData || this.hasExpired(this.cacheData.expiry)) {
            this.cacheData = undefined;
            return false;
        }
        return true;
    }
    /**
     * Returns undefined if there is no data.
     * Uses `hasData` to determine whether any cached data exists.
     *
     * @readonly
     * @type {(T | undefined)}
     * @memberof InMemoryCache
     */
    public get data(): T | undefined {
        if (!this.hasData) {
            return;
        }
        return this.cacheData?.value;
    }
    public set data(value: T | undefined) {
        if (value !== undefined) {
            this.cacheData = {
                expiry: this.calculateExpiry(),
                value,
            };
        } else {
            this.cacheData = undefined;
        }
    }
    public clear() {
        this.cacheData = undefined;
    }

    /**
     * Has this data expired?
     * (protected class member to allow for reliable non-data-time-based testing)
     *
     * @param expiry The date to be tested for expiry.
     * @returns true if the data expired, false otherwise.
     */
    protected hasExpired(expiry: number): boolean {
        return expiry <= Date.now();
    }

    /**
     * When should this data item expire?
     * (protected class method to allow for reliable non-data-time-based testing)
     *
     * @returns number representing the expiry time for this item.
     */
    protected calculateExpiry(): number {
        return Date.now() + this.expiryDurationMs;
    }
}


text:
layout: post
title: "Blog created"
ref: created
comments: True
lang: en
tags: github github-pages jekyll
---

I created a blog for the notes which helped me and maybe will help you.

I am using Github Pages as blog platform

Why Github Pages?

- Free, no ads, no registration and SMS
- Quick installation, does not require learning additional programming languages
- Hosted by great [corporation](http://github.com){:target="_blank"} for developers
- Git
- Dont care about updates, security and server configuring
- Flexibility

There are tons of articles how to install Jekyll. But many articles are written for linux users which generating blog with Ruby on Linux desktop.
I didn't want to waste time with Virtualbox and etc, I want to install Ruby, Python, Jekyll on [Windows](http://jekyll-windows.juthilo.com/){:target="_blank"}.
Recommendations for Windows install:

>Install Ruby and Ruby DevKit with same bit
>You may need install [certificate](https://gist.github.com/fnichol/867550){:target="_blank"} if Jekyll will complain about SSL

I installed the blog in [subfolder](http://stackoverflow.com/a/29423406/2409592){:target="_blank"}.
I recommended this article by [Joshua Lande](http://joshualande.com/jekyll-github-pages-poole/){:target="_blank"} if you want install same blog


text:
export const SET_RAW = 'SET_RAW';
export const SET_FILTER = 'SET_FILTER';
export const CREATE_HEXBIN = 'CREATE_HEXBIN';
export const SET_OBJECT = 'SET_OBJECT';
export const SET_REGEXP = 'SET_REGEXP';


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29337_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">19400 — 19500
19500 — 19600
19600 — 19700

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">DOLOMITE: Light cream tan, light cream, light brown, light gray, silty, microcrystalline, very fine, microsucrosic, mottled, calcareous, carbonaceous, soft to firm, argillaceous, moderate pyrite, poor intergranular porosity, dull even orange fluorescence, instant streaming cut.
DOLOMITE: Light cream, light tan, light brown, very light gray, cream tan, silty, microcrystalline, very fine, microsucrosic, mottled, calcareous, carbonaceous, soft to firm, argillaceous, moderate pyrite, poor intergranular porosity, very faint orange to yellow fluorescence, very weak cloudy cut.
DOLOMITE: Light brown, cream, light blue gray, light tan, light gray, brown, gray,

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">cream tan, suty, m1crocrysta1une, very rme, rmcrosucros1c, mottled, calcareous, carbonaceous, soft to firm, argillaceous, moderate pyrite, poor intergranular porosity, dull scattered yellow fluorescence, weak cloudy cut.

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">19700 — 19760 DOLOMITE: Light brown, cream, light tan, light gray, brown, gray, cream tan, silty, microcrystalline, very fine, microsucrosic, mottled, calcareous, carbonaceous, soft to
firm, argillaceous, trace pyrite, poor intergranular porosity, dull scattered yellow fluorescence, weak cloudy cut.
Reached TD of 19, 760' MD at 9:30 am CST on February 23, 2015.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">38


text:
using NBatch.Main.Core;
using System;
using System.Collections.Generic;

namespace NBatch.ConsoleDemo
{
    public class ConsoleWriter<TInput> : IWriter<TInput>
    {
        public bool Write(IEnumerable<TInput> items)
        {
            foreach (var item in items)
                Console.WriteLine(item);

            return true;
        }
    }
}


text:
class Entry < ApplicationRecord
  # include Elasticsearch::Model
  include HasOwner

  PER_PAGE = 10

  # index_name Rails.configuration.entry_index_name

  belongs_to :agent, optional: true
  belongs_to :user, optional: true, counter_cache: true, touch: false
  belongs_to :community, optional: true, counter_cache: true, touch: false
  has_many :comments, as: :commentable, dependent: :destroy
  has_many :posts, dependent: :destroy
  has_many :news, dependent: :destroy

  enum privacy: [:generally_accessible, :visible_to_community, :visible_to_followees, :personal]

  mount_uploader :image, PostImageUploader

  before_validation :normalize_title, :sanitize_body

  validates_presence_of :body, :privacy

  scope :not_deleted, -> { where(deleted: false) }
  scope :with_privacy, -> (value) { where(privacy: value) unless value.blank? }
  scope :public_entries, -> { where(privacy: Entry.privacies[:generally_accessible]) }
  scope :recent, -> { order 'id desc' }
  scope :archive, -> (year, month) { where "date_trunc('month', created_at) = ?", '%04d-%02d-01' % [year, month] }
  scope :since, -> (time) { where('created_at > ?', time) }
  scope :popular, -> { order('view_count desc') }

  # @param [Integer] page
  def self.page_for_administration(page)
    not_deleted.with_privacy(Entry.community_privacies).recent.page(page).per(PER_PAGE)
  end

  # @param [User] user
  # @param [Integer] page
  def self.page_for_visitors(user, page)
    not_deleted.with_privacy(Entry.privacy_for_user(user)).recent.page(page).per(PER_PAGE)
  end

  # @param [User] user
  # @param [Integer] page
  def self.page_for_owner(user, page)
    owned_by(user).not_deleted.recent.page(page).per(PER_PAGE)
  end

  def self.community_privacies
    [Entry.privacies[:generally_accessible], Entry.privacies[:visible_to_community]]
  end

  def self.entity_parameters
    for_image = %i(image image_name image_author_name image_author_link)
    for_image + %i(lead title body slug privacy show_name source source_link)
  end

  def self.creation_parameters
    entity_parameters # + %i(community_id)
  end

  # @param [User] user
  def self.privacy_for_user(user)
    user.is_a?(User) ? Entry.community_privacies : Entry.privacies[:generally_accessible]
  end

  # @param [User] user
  def can_be_reposted_by?(user)
    false
  end

  # Is entry visible to user?
  #
  # @param [User|nil] user who tries to see the entry
  # @return [Boolean]
  def visible_to?(user)
    method = "#{self.privacy}_to?".to_sym
    respond_to?(method) ? send(method, user) : owned_by?(user)
  end

  # Is entry visible to user as generally accessible entry?
  #
  # @param [User|nil] user who tries to see the entry
  # @return [Boolean]
  def generally_accessible_to?(user)
    user.nil? || user.is_a?(User)
  end

  # Is entry visible to user as entry for community?
  #
  # @param [User|nil] user who tries to see the entry
  # @return [Boolean]
  def visible_to_community_to?(user)
    user.is_a? User
  end

  # Is entry visible to user as entry for followees?
  #
  # @param [User|nil] user who tries to see the entry
  # @return [Boolean]
  def visible_to_followees_to?(user)
    owned_by?(user) || (self.user.is_a?(User) && self.user.follows?(user))
  end

  def editable_by?(user)
    false
  end

  # @param [User] user
  def commentable_by?(user)
    user.is_a? User
  end

  private

  def sanitize_body
    self.body = body.gsub(/<\s*(?:no)?script/, '')
  end

  def normalize_title
    if title.blank?
      self.title, self.slug = nil, nil
    else
      self.title = title.strip[0..200]
      self.slug  = Canonizer.transliterate title
    end
  end
end


text:
package org.systemsbiology.hadoop;

import org.apache.hadoop.fs.*;
import org.apache.hadoop.fs.permission.*;
import org.systemsbiology.common.*;

import java.io.*;

/**
 * org.systemsbiology.hadoop.IHDFSFileSystem
 *
 * @author Steve Lewis
 * @date 18/05/13
 */
public interface IHDFSFileSystem extends IFileSystem {
    public static IHDFSFileSystem[] EMPTY_ARRAY = {};
    public static Class THIS_CLASS = IHDFSFileSystem.class;

    public static final FsPermission FULL_ACCESS = new FsPermission(  FsAction.ALL,FsAction.READ_EXECUTE,FsAction.READ_EXECUTE);
    public static final FsPermission FULL_FILE_ACCESS = new FsPermission(  FsAction.READ_WRITE,FsAction.READ_WRITE,FsAction.READ_WRITE);

    /**
     * there are issues with hdfs and running as a remote user
     * InputFormats should be running in the cluster and should alerday be the
     * right user
     * @return  true is you are running on the cluster
     */
    public boolean isRunningAsUser();

    /**
     * if you are running as the user - i.e. on the cluster
     * this should work
     * @param path
     * @return
     */
    public InputStream openFileForRead(Path path);

    /**
     * if you are running as the user - i.e. on the cluster
     * this should work
     * @param path
     * @return
     */
    public OutputStream openFileForWrite(Path path);

}


text:
namespace SharableTypes.Interface
{
    public interface IModel
    {
        string GlobalId { get; set; }
        bool SavedOffline { get; set; }
        int SyncAction { get; set; }
        int ResponseCode { get; set; }
        string ErrorMessage { get; set; }
        bool Active { get; set; }
    }
}


text:
<?xml version="1.0" encoding='utf-8' standalone='no'?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<!-- blaze-out/gcc-4.X.Y-crosstool-v18-hybrid-grtev4-k8-opt/genfiles/java/com/google/android/gmscore/integ/client/common/res/values-uk/strings.xml -->
<eat-comment/>
<string name="common_google_play_services_unknown_issue" msgid="2518680582564677258">"У додатку <xliff:g id="APP_NAME">%1$s</xliff:g> виникла проблема із сервісами Google Play. Повторіть спробу."</string>
</resources>


text:
var _ = require('lodash');
var replacer = require('../util').replacer;

var teencode = require('./model/teencode.json');
var abbr = require('./model/abbr.json');

var conversionTables = _.merge({}, teencode, abbr);
var normalizer = replacer(conversionTables);

exports.normalize = function (str) {
    return normalizer(str);
}


text:
def get_status(file_name):
	f = open(file_name, "r")
	get_status_result =  f.read()
	f.close()
	return get_status_result


text:
dmesg

##### Used to find kernel & hardware information for the system.

logread

##### replaces syslogd on the OpenWRT operating system. Can be used to find lots of useful log information

## Examples -

##### Find pineapple type

dmesg | grep machine

##### See all ssh logins

logread | grep "auth.info ssh"