text:
static const QString kStreamURL = "http://www.facebook.com/connect/prompt_feed.php";

///////////////////////////////////////////////////////////////////////////////////////////////////

FBStreamDialog::FBStreamDialog(FBSession* aSession) : FBDialog(aSession)
{}

void FBStreamDialog::load ()
{
    Dictionary getParams, postParams;
    getParams["display"] = "touch";

    postParams["api_key"] = iSession->apiKey();
    postParams["session_key"] = iSession->sessionKey();
    postParams["preview"] = "1";
    postParams["callback"] = "fbconnect:success";
    postParams["cancel"] = "fbconnect:cancel";
    postParams["attachment"] = iAttachment;
    postParams["action_links"] = iActionLinks;
    postParams["target_id"] = iTargetId;
    postParams["user_message_prompt"] = iUserMessagePrompt;

    loadURL(kStreamURL, QNetworkAccessManager::PostOperation, getParams, postParams );

}


text:
package com.capricorn.example;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.capricorn.ArcMenu;
import com.capricorn.RayMenu;

/**
 *
 * @author Capricorn
 *
 */
public class MainActivity extends Activity {
	private static final int[] ITEM_DRAWABLES = { R.drawable.composer_camera, R.drawable.composer_music,
			R.drawable.composer_place, R.drawable.composer_sleep, R.drawable.composer_thought, R.drawable.composer_with };

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// ArcMenu arcMenu = (ArcMenu) findViewById(R.id.arc_menu);
		// ArcMenu arcMenu2 = (ArcMenu) findViewById(R.id.arc_menu_2);

		// initArcMenu(arcMenu, ITEM_DRAWABLES);
		// initArcMenu(arcMenu2, ITEM_DRAWABLES);

		RayMenu rayMenu = (RayMenu) findViewById(R.id.ray_menu);
		int mm[] = {R.drawable.navi48, R.drawable.near48};
		final int itemCount = mm.length;
		for (int i = 0; i < itemCount; i++) {
			ImageView item = new ImageView(this);
			item.setImageResource(mm[i]);

			final int position = i;
			rayMenu.addItem(item, new OnClickListener() {

				@Override
				public void onClick(View v) {
					Toast.makeText(MainActivity.this, "position:" + position, Toast.LENGTH_SHORT).show();
				}
			});// Add a menu item
		}
	}

	private void initArcMenu(ArcMenu menu, int[] itemDrawables) {
		final int itemCount = itemDrawables.length;
		for (int i = 0; i < itemCount; i++) {
			ImageView item = new ImageView(this);
			item.setImageResource(itemDrawables[i]);

			final int position = i;
			menu.addItem(item, new OnClickListener() {

				@Override
				public void onClick(View v) {
					Toast.makeText(MainActivity.this, "position:" + position, Toast.LENGTH_SHORT).show();
				}
			});
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
import json
import threading

import os
import re
import tornado.autoreload
import tornado.ioloop
import tornado.web

from api_python_library.tools import config, api

class ItemsHandler(tornado.web.RequestHandler):
    def data_received(self, chunk):
        pass

    def get(self, *args, **kwargs):
        # items GET /items(.:format) items#index
        items = {'items': [{1: {'title': 'first item'}, 2: {'title': 'second time'}}]}
        self.write(json.dumps(items))
        self.finish()

    def post(self, *args, **kwargs):
        # POST /items(.:format) items#create
        result = {'result': 'ok'}
        self.write(json.dumps(result))
        self.finish()

class ItemHandler(tornado.web.RequestHandler):
    def data_received(self, chunk):
        pass

    def get(self, *args, **kwargs):
        # new_item GET /items/new(.:format) items#new
        # item GET /items/:id(.:format) items#show
        # edit_item GET /items/:id/edit(.:format) items#edit
        if re.match(r'/items/new', self.request.path):
            self.write('..nothing to print..')
        elif re.match(r'/items/[0-9]+(/edit)?', self.request.path):
            item = {'title': 'first item'}
            self.write(json.dumps(item))
        self.finish()

    def patch(self, *args, **kwargs):
        # PATCH or PUT /items/:id(.:format) items#update
        result = {'result': 'ok'}
        self.write(json.dumps(result))
        self.finish()

    def put(self, *args, **kwargs):
        # PATCH or PUT /items/:id(.:format) items#update
        result = {'result': 'ok'}
        self.write(json.dumps(result))
        self.finish()

    def delete(self, *args, **kwargs):
        # DELETE /items/:id(.:format) items#destroy
        result = {'result': 'ok'}
        self.write(json.dumps(result))
        self.finish()

pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/main.ini' % pwd)
api.add_api_config('%s/api.ini' % pwd)

application = tornado.web.Application(
        handlers=[
            (r"/items", ItemsHandler),
            (r"/items/(.*)", ItemHandler),
        ])

if __name__ == '__main__':
    application.listen(config.port, config.host)
    tornado_ioloop = tornado.ioloop.IOLoop.instance()
    threading.Thread(target=tornado_ioloop.start).start()

    authorization_header = api.get_basic_authorization_header(config.user, config.password)
    host = '%s:%s' % (config.host, config.port)

    try:
        print api.index_items(host, headers=authorization_header)
        print api.create_item(host, headers=authorization_header)
        print api.new_item(host, headers=authorization_header)
        print api.edit_item(host, arguments={'id': 1}, headers=authorization_header)
        print api.show_item(host, arguments={'id': 1}, headers=authorization_header)
        print api.update_item(host, arguments={'id': 1}, headers=authorization_header)
        print api.destroy_item(host, arguments={'id': 1}, headers=authorization_header)
    finally:
        tornado_ioloop.stop()


text:
/*
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
package com.codeup.auth.infrastructure.jdbc;

import com.codeup.auth.domain.identity.User;
import com.dbal.jdbc.RowMapper;
import com.dbal.jdbc.Table;

import java.sql.Connection;

class UsersTable extends Table<User> {
    UsersTable(Connection connection) {
        super(connection);
    }

    User insert(String username, String password) {
        return this
            .createInsert("username", "password")
            .execute(username, password)
            .fetch()
        ;
    }

    User findBy(String username) {
        return this
            .select("*")
            .where("username = ?")
            .execute(username)
            .fetch()
        ;
    }

    @Override
    protected String table() {
        return "users";
    }

    @Override
    protected RowMapper<User> mapper() {
        return new UsersMapper();
    }
}


text:
import Ember from 'ember';
import { test, moduleForComponent } from 'ember-qunit';
import PagedArray from 'ember-cli-pagination/local/paged-array';

moduleForComponent("page-numbers");

var paramTest = function(name,ops,f) {
  test(name, function(assert) {
    var subject = this.subject();

    Ember.run(function() {
      Object.keys(ops).forEach(function (key) {
          var value = ops[key];
          subject.set(key,value);
      });
    });

    f.call(this,subject,assert,ops);
  });
};

test('hasPages', function(assert) {
  assert.expect(2);
  var s = this.subject();

  Ember.run(function() {
    s.set('totalPages', 1);
  });
  assert.equal(s.get('hasPages'),false);

  Ember.run(function() {
    s.set('totalPages', 2);
  });
  assert.equal(s.get('hasPages'),true);
});

test("canStepBackward", function(assert) {
  var s = this.subject();
  Ember.run(function() {
    s.set("currentPage",1);
  });
  assert.equal(s.get('canStepBackward'),false);
});

paramTest("first page", {currentPage: 1, totalPages: 10}, function(s,assert) {
  assert.equal(s.get('canStepBackward'),false);
  assert.equal(s.get('canStepForward'),true);
});

paramTest("last page page", {currentPage: 10, totalPages: 10}, function(s,assert) {
  assert.equal(s.get('canStepBackward'),true);
  assert.equal(s.get('canStepForward'),false);
});

paramTest("middle page", {currentPage: 5, totalPages: 10}, function(s,assert) {
  assert.equal(s.get('canStepBackward'),true);
  assert.equal(s.get('canStepForward'),true);
});

paramTest("only one page", {currentPage: 1, totalPages: 1}, function(s,assert) {
  assert.equal(s.get('canStepBackward'),false);
  assert.equal(s.get('canStepForward'),false);
});

var makePagedArray = function(list) {
  return PagedArray.create({content: list, perPage: 2, page: 1});
};

paramTest("create with content", {content: makePagedArray([1,2,3,4,5])}, function(s,assert,ops) {
  assert.equal(s.get('totalPages'),3);
  assert.equal(ops.content.get('totalPages'),3);
});

paramTest("create with content - changing array.content changes component", {content: makePagedArray([1,2,3,4,5])}, function(s,assert,ops) {
  assert.equal(s.get('totalPages'),3);
  Ember.run(function() {
    ops.content.pushObjects([6,7]);
  });
  assert.equal(s.get('totalPages'),4);
});

paramTest("create with content - changing page changes content value", {content: makePagedArray([1,2,3,4,5])}, function(s,assert,ops) {
  assert.equal(s.get('totalPages'),3);
  Ember.run(function() {
    ops.content.set("page",2);
  });
  assert.equal(s.get('currentPage'),2);
});

paramTest("template smoke", {content: makePagedArray([1,2,3,4,5])}, function(s,assert) {
  assert.equal(this.$().find(".page-number").length,3);
  assert.equal(this.$().find(".prev.disabled").length,1);
  assert.equal(this.$().find(".next.enabled-arrow").length,1);
});

// COMMENTEDOUTTEST
// paramTest("template smoke 2", {content: makePagedArray([1,2,3,4,5])}, function(s,assert) {
//   this.append();

//   hasPages(3);
//   hasActivePage(1);

//   clickPage(2);
//   andThen(function() {
//     hasActivePage(2);
//   });
// });

paramTest("arrows and pages in right order", {content: makePagedArray([1,2,3,4,5])}, function(s,assert) {
  var pageItems = this.$().find("ul.pagination li");
  assert.equal(pageItems.length,5);

  assert.equal(pageItems.eq(0).hasClass("prev"),true);
  assert.equal(pageItems.eq(1).text(),1);
  assert.equal(pageItems.eq(2).text(),2);
  assert.equal(pageItems.eq(3).text(),3);
  assert.equal(pageItems.eq(4).hasClass("next"),true);
});

paramTest("truncation", {currentPage: 2, totalPages: 10, numPagesToShow: 5}, function(s,assert) {
  var pages = s.get('pageItems').map(function(obj) {
    return obj.page;
  });

  assert.deepEqual(pages,[1,2,3,4,5]);
});

paramTest("truncation with showFL = true", {currentPage: 2, totalPages: 10, numPagesToShow: 5, showFL: true}, function(s,assert) {
  var pages = s.get('pageItems').map(function(obj) {
    return obj.page;
  });

  assert.deepEqual(pages,[1,2,3,4,5,6,10]);
});

paramTest("pageClicked sends default event", {content: makePagedArray([1,2,3,4,5])}, function(s,assert,ops) {
  var actionCounter = 0;
  var clickedPage = null;
  var containingObject = {
    doThing: function(n) {
      actionCounter++;
      clickedPage = n;
    }
  };

  s.set('targetObject',containingObject);
  s.set('action','doThing');

  assert.equal(s.get('totalPages'),3);
  Ember.run(function() {
    s.send('pageClicked',2);
  });
  assert.equal(s.get('currentPage'),2);
  assert.equal(actionCounter,1);
  assert.equal(clickedPage,2);
});

paramTest("incrementPage sends default event", {content: makePagedArray([1,2,3,4,5])}, function(s,assert,ops) {
  var actionCounter = 0;
  var clickedPage = null;
  var containingObject = {
    doThing: function(n) {
      actionCounter++;
      clickedPage = n;
    }
  };

  s.set('targetObject',containingObject);
  s.set('action','doThing');

  assert.equal(s.get('totalPages'),3);
  Ember.run(function() {
    s.send('incrementPage',1);
  });
  assert.equal(s.get('currentPage'),2);
  assert.equal(actionCounter,1);
  assert.equal(clickedPage,2);
});

paramTest("invalid incrementPage does not send default event", {content: makePagedArray([1,2,3,4,5])}, function(s,assert,ops) {
  var actionCounter = 0;
  var clickedPage = null;
  var containingObject = {
    doThing: function(n) {
      actionCounter++;
      clickedPage = n;
    }
  };

  s.set('targetObject',containingObject);
  s.set('action','doThing');

  assert.equal(s.get('totalPages'),3);
  Ember.run(function() {
    s.send('incrementPage',-1);
  });
  assert.equal(s.get('currentPage'),1);
  assert.equal(actionCounter,0);
});

paramTest("invalid page send invalidPage component action", {content: makePagedArray([1,2,3,4,5])}, function(s,assert,ops) {
  var actionCounter = 0;
  var pageEvent = null;
  var containingObject = {
    doThing: function(n) {
      actionCounter++;
      pageEvent = n;
    }
  };

  s.set('targetObject',containingObject);
  s.set('invalidPageAction','doThing');

  assert.equal(s.get('totalPages'),3);
  Ember.run(function() {
    s.get('content').set('page',99);
  });
  assert.equal(pageEvent.page,99);
  assert.equal(actionCounter,1);
});
/*
*/


text:
<?php

final class PhabricatorMacroTransaction
  extends PhabricatorApplicationTransaction {

  public function getApplicationName() {
    return 'file';
  }

  public function getTableName() {
    return 'macro_transaction';
  }

  public function getApplicationTransactionType() {
    return PhabricatorMacroMacroPHIDType::TYPECONST;
  }

  public function getApplicationTransactionCommentObject() {
    return new PhabricatorMacroTransactionComment();
  }

  public function getRequiredHandlePHIDs() {
    $phids = parent::getRequiredHandlePHIDs();

    $old = $this->getOldValue();
    $new = $this->getNewValue();

    switch ($this->getTransactionType()) {
      case PhabricatorMacroTransactionType::TYPE_FILE:
      case PhabricatorMacroTransactionType::TYPE_AUDIO:
        if ($old !== null) {
          $phids[] = $old;
        }
        $phids[] = $new;
        break;
    }

    return $phids;
  }

  public function shouldHide() {
    $old = $this->getOldValue();
    $new = $this->getNewValue();

    switch ($this->getTransactionType()) {
      case PhabricatorMacroTransactionType::TYPE_NAME:
        return ($old === null);
    }

    return parent::shouldHide();
  }

  public function getTitle() {
    $author_phid = $this->getAuthorPHID();

    $old = $this->getOldValue();
    $new = $this->getNewValue();

    switch ($this->getTransactionType()) {
      case PhabricatorMacroTransactionType::TYPE_NAME:
        return pht(
          '%s renamed this macro from "%s" to "%s".',
          $this->renderHandleLink($author_phid),
          $old,
          $new);
        break;
      case PhabricatorMacroTransactionType::TYPE_DISABLED:
        if ($new) {
          return pht(
            '%s disabled this macro.',
            $this->renderHandleLink($author_phid));
        } else {
          return pht(
            '%s restored this macro.',
            $this->renderHandleLink($author_phid));
        }
        break;

      case PhabricatorMacroTransactionType::TYPE_AUDIO:
        if (!$old) {
          return pht(
            '%s attached audio: %s.',
            $this->renderHandleLink($author_phid),
            $this->renderHandleLink($new));
        } else {
          return pht(
            '%s changed the audio for this macro from %s to %s.',
            $this->renderHandleLink($author_phid),
            $this->renderHandleLink($old),
            $this->renderHandleLink($new));
        }

      case PhabricatorMacroTransactionType::TYPE_AUDIO_BEHAVIOR:
        switch ($new) {
          case PhabricatorFileImageMacro::AUDIO_BEHAVIOR_ONCE:
            return pht(
              '%s set the audio to play once.',
              $this->renderHandleLink($author_phid));
          case PhabricatorFileImageMacro::AUDIO_BEHAVIOR_LOOP:
            return pht(
              '%s set the audio to loop.',
              $this->renderHandleLink($author_phid));
          default:
            return pht(
              '%s disabled the audio for this macro.',
              $this->renderHandleLink($author_phid));
        }

      case PhabricatorMacroTransactionType::TYPE_FILE:
        if ($old === null) {
          return pht(
            '%s created this macro.',
            $this->renderHandleLink($author_phid));
        } else {
          return pht(
            '%s changed the image for this macro from %s to %s.',
            $this->renderHandleLink($author_phid),
            $this->renderHandleLink($old),
            $this->renderHandleLink($new));
        }
        break;
    }

    return parent::getTitle();
  }

  public function getTitleForFeed(PhabricatorFeedStory $story) {
    $author_phid = $this->getAuthorPHID();
    $object_phid = $this->getObjectPHID();

    $old = $this->getOldValue();
    $new = $this->getNewValue();

    switch ($this->getTransactionType()) {
      case PhabricatorMacroTransactionType::TYPE_NAME:
        return pht(
          '%s renamed %s from "%s" to "%s".',
          $this->renderHandleLink($author_phid),
          $this->renderHandleLink($object_phid),
          $old,
          $new);
      case PhabricatorMacroTransactionType::TYPE_DISABLED:
        if ($new) {
          return pht(
            '%s disabled %s.',
            $this->renderHandleLink($author_phid),
            $this->renderHandleLink($object_phid));
        } else {
          return pht(
            '%s restored %s.',
            $this->renderHandleLink($author_phid),
            $this->renderHandleLink($object_phid));
        }
      case PhabricatorMacroTransactionType::TYPE_FILE:
        if ($old === null) {
          return pht(
            '%s created %s.',
            $this->renderHandleLink($author_phid),
            $this->renderHandleLink($object_phid));
        } else {
          return pht(
            '%s updated the image for %s.',
            $this->renderHandleLink($author_phid),
            $this->renderHandleLink($object_phid));
        }

      case PhabricatorMacroTransactionType::TYPE_AUDIO:
        if (!$old) {
          return pht(
            '%s attached audio to %s: %s.',
            $this->renderHandleLink($author_phid),
            $this->renderHandleLink($object_phid),
            $this->renderHandleLink($new));
        } else {
          return pht(
            '%s changed the audio for %s from %s to %s.',
            $this->renderHandleLink($author_phid),
            $this->renderHandleLink($object_phid),
            $this->renderHandleLink($old),
            $this->renderHandleLink($new));
        }

      case PhabricatorMacroTransactionType::TYPE_AUDIO_BEHAVIOR:
        switch ($new) {
          case PhabricatorFileImageMacro::AUDIO_BEHAVIOR_ONCE:
            return pht(
              '%s set the audio for %s to play once.',
              $this->renderHandleLink($author_phid),
              $this->renderHandleLink($object_phid));
          case PhabricatorFileImageMacro::AUDIO_BEHAVIOR_LOOP:
            return pht(
              '%s set the audio for %s to loop.',
              $this->renderHandleLink($author_phid),
              $this->renderHandleLink($object_phid));
          default:
            return pht(
              '%s disabled the audio for %s.',
              $this->renderHandleLink($author_phid),
              $this->renderHandleLink($object_phid));
        }

    }

    return parent::getTitleForFeed($story);
  }

  public function getActionName() {
    $old = $this->getOldValue();
    $new = $this->getNewValue();

    switch ($this->getTransactionType()) {
      case PhabricatorMacroTransactionType::TYPE_NAME:
        if ($old === null) {
          return pht('Created');
        } else {
          return pht('Renamed');
        }
      case PhabricatorMacroTransactionType::TYPE_DISABLED:
        if ($new) {
          return pht('Disabled');
        } else {
          return pht('Restored');
        }
      case PhabricatorMacroTransactionType::TYPE_FILE:
        if ($old === null) {
          return pht('Created');
        } else {
          return pht('Edited Image');
        }

      case PhabricatorMacroTransactionType::TYPE_AUDIO:
        return pht('Audio');

      case PhabricatorMacroTransactionType::TYPE_AUDIO_BEHAVIOR:
        return pht('Audio Behavior');

    }

    return parent::getActionName();
  }

  public function getActionStrength() {
    switch ($this->getTransactionType()) {
      case PhabricatorMacroTransactionType::TYPE_DISABLED:
        return 2.0;
      case PhabricatorMacroTransactionType::TYPE_FILE:
        return 1.5;
    }
    return parent::getActionStrength();
  }

  public function getIcon() {
    $old = $this->getOldValue();
    $new = $this->getNewValue();

    switch ($this->getTransactionType()) {
      case PhabricatorMacroTransactionType::TYPE_NAME:
        return 'fa-pencil';
      case PhabricatorMacroTransactionType::TYPE_FILE:
        if ($old === null) {
          return 'fa-plus';
        } else {
          return 'fa-pencil';
        }
      case PhabricatorMacroTransactionType::TYPE_DISABLED:
        if ($new) {
          return 'fa-times';
        } else {
          return 'fa-undo';
        }
      case PhabricatorMacroTransactionType::TYPE_AUDIO:
        return 'fa-headphones';
    }

    return parent::getIcon();
  }

  public function getColor() {
    $old = $this->getOldValue();
    $new = $this->getNewValue();

    switch ($this->getTransactionType()) {
      case PhabricatorMacroTransactionType::TYPE_NAME:
        return PhabricatorTransactions::COLOR_BLUE;
      case PhabricatorMacroTransactionType::TYPE_FILE:
        if ($old === null) {
          return PhabricatorTransactions::COLOR_GREEN;
        } else {
          return PhabricatorTransactions::COLOR_BLUE;
        }
      case PhabricatorMacroTransactionType::TYPE_DISABLED:
        if ($new) {
          return PhabricatorTransactions::COLOR_BLACK;
        } else {
          return PhabricatorTransactions::COLOR_SKY;
        }
    }

    return parent::getColor();
  }

}


text:
#
# = Apache Log Regex
#
# Ruby parser for Apache log files based on regular expressions.
#
# Category::
# Package::     ApacheLogRegex
# Author::      Simone Carletti <weppos@weppos.net>
# License::
#
#--
# SVN: $Id$
#++

require 'test_helper'

Dir.glob(File.dirname(__FILE__) + '/**/*_test.rb').sort.each { |unit| require unit }


text:
package de.techjava.mqtt.camunda.config;

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

import javax.enterprise.util.Nonbinding;
import javax.inject.Qualifier;

/**
 * Annotates an element that represents a configuration property, which is injected from the environment property provider.
 *
 * @author Simon Zambrovski
 *
Inspired by Nazar Annagurban
 */
@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER, TYPE })
@Documented
public @interface Property {
    @Nonbinding
    String value() default "";
}


text:
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace System.ComponentModel.DataAnnotations
{
    [AttributeUsage(
        AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter,
        AllowMultiple = false)]
    public sealed class EnumDataTypeAttribute : DataTypeAttribute
    {
        public EnumDataTypeAttribute(Type enumType)
            : base("Enumeration")
        {
            EnumType = enumType;
        }

        public Type EnumType { get; private set; }

        public override bool IsValid(object value)
        {
            if (EnumType == null)
            {
                throw new InvalidOperationException(SR.EnumDataTypeAttribute_TypeCannotBeNull);
            }
            if (!EnumType.GetTypeInfo().IsEnum)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
                    SR.EnumDataTypeAttribute_TypeNeedsToBeAnEnum, EnumType.FullName));
            }

            if (value == null)
            {
                return true;
            }
            var stringValue = value as string;
            if (stringValue != null && string.IsNullOrEmpty(stringValue))
            {
                return true;
            }

            Type valueType = value.GetType();
            if (valueType.GetTypeInfo().IsEnum && EnumType != valueType)
            {
                // don't match a different enum that might map to the same underlying integer
                return false;
            }

            if (!valueType.GetTypeInfo().IsValueType && valueType != typeof(string))
            {
                // non-value types cannot be converted
                return false;
            }

            if (valueType == typeof(bool) ||
                valueType == typeof(float) ||
                valueType == typeof(double) ||
                valueType == typeof(decimal) ||
                valueType == typeof(char))
            {
                // non-integral types cannot be converted
                return false;
            }

            object convertedValue;
            if (valueType.GetTypeInfo().IsEnum)
            {
                Debug.Assert(valueType == value.GetType(), "The valueType should equal the Type of the value");
                convertedValue = value;
            }
            else
            {
                try
                {
                    if (stringValue != null)
                    {
                        convertedValue = Enum.Parse(EnumType, stringValue, false);
                    }
                    else
                    {
                        convertedValue = Enum.ToObject(EnumType, value);
                    }
                }
                catch (ArgumentException)
                {
                    // REVIEW: is there a better way to detect this
                    return false;
                }
            }

            if (IsEnumTypeInFlagsMode(EnumType))
            {
                // REVIEW: this seems to be the easiest way to ensure that the value is a valid flag combination
                // If it is, the string representation of the enum value will be something like "A, B", while
                // the string representation of the underlying value will be "3". If the enum value does not
                // match a valid flag combination, then it would also be something like "3".
                string underlying = GetUnderlyingTypeValueString(EnumType, convertedValue);
                string converted = convertedValue.ToString();
                return !underlying.Equals(converted);
            }

            return Enum.IsDefined(EnumType, convertedValue);
        }

        private static bool IsEnumTypeInFlagsMode(Type enumType)
        {
            return enumType.GetTypeInfo().GetCustomAttributes(typeof(FlagsAttribute), false).Any();
        }

        private static string GetUnderlyingTypeValueString(Type enumType, object enumValue)
        {
            return
                Convert.ChangeType(enumValue, Enum.GetUnderlyingType(enumType), CultureInfo.InvariantCulture).ToString();
        }
    }
}


text:
<?php

    namespace Slashworks\AppBundle\Model;

    use Slashworks\AppBundle\Model\om\BaseRemoteApp;

    /**
     * Class RemoteApp
     *
     * @package Slashworks\AppBundle\Model
     */
    class RemoteApp extends BaseRemoteApp
    {

        public function checkNotificationSetting($sValue){
            if(!method_exists($this,"get".ucfirst($sValue))){
                throw new \Exception("Notificationsettings for "."get".ucfirst($sValue)." not found");
            }

            return $this->{"get".ucfirst($sValue)}();
        }

        /**
         * @return string
         */
        public function generateFileName(){
            $sName = $this->getName();
            $sName = strtolower($sName);
            $arrSearch = array('/[^a-zA-Z0-9 \.\&\/_-]+/', '/[ \.\&\/-]+/');
            $arrReplace = array('', '-');
            $sName = preg_replace($arrSearch, $arrReplace, $sName);

            return trim($sName, '-');
        }

        /**
         * @return string
         */
        public function getUpdateUrl(){
            $sUrl = $this->getDomain().$this->getApiUrl()."public/update.php";
            return $sUrl;
        }

        /**
         * @return string
         */
        public function getFullApiUrl(){
            $sUrl = $this->getDomain().$this->getApiUrl()."server/public/api.php";
            return $sUrl;
        }

        public function saveApiCallResult($aResult){

        }

        public function getRemoteHistoryContao(){
            $aReturn = parent::getRemoteHistoryContaos();
            if($aReturn instanceof \PropelCollection) {
                if($aReturn->count() > 0) {
                    return $aReturn[0];
                }
            }
            $o = new RemoteHistoryContao();
            $a = new \ArrayObject(array());
            $o->setExtensions($a);
            return $o;
        }

        public function getRemoteHistoryContaoAsArray(){
            $oReturn = $this->getRemoteHistoryContao();
            if($oReturn === false){
                return json_encode(array());
            }
            $aReturn               = $oReturn->toArray();
            $aReturn['Extensions'] = $aReturn['Extensions']->getArrayCopy();

            $sMaintenance = $aReturn['ConfigMaintenancemode'];
            $aReturn['ConfigMaintenancemode'] = "getId()."\">";
            if($sMaintenance === 'On') {
                $aReturn['ConfigMaintenancemode'] .= "";
            }else{
                $aReturn['ConfigMaintenancemode'] .= "";
            }

            $aReturn['ConfigMaintenancemode'] .= "";

            return $aReturn;
        }

        public function getRemoteHistoryContaoAsJson(){
            $aReturn = $this->getRemoteHistoryContaoAsArray();
            return json_encode($aReturn);
        }

    }


text:
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
//
// Rmath.h: Rcpp R/C++ interface class library -- Wrappers for R's Rmath API
//
// Copyright (C) 2012 Dirk Eddelbuettel and Romain Francois
//
// This file is part of Rcpp.
//
// Rcpp is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Rcpp is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Rcpp.  If not, see <http://www.gnu.org/licenses/>.

#ifndef Rcpp_Rmath_h
#define Rcpp_Rmath_h

namespace R {

    // see R's Rmath.h as well as Writing R Extension

    /* Random Number Generators */
    inline double norm_rand(void) 	{ return ::norm_rand(); }
    inline double unif_rand(void)	{ return ::unif_rand(); }
    inline double exp_rand(void)	{ return ::exp_rand(); }

    /* Normal Distribution */
    inline double dnorm(double x, double mu, double sigma, int lg)              { return ::Rf_dnorm4(x, mu, sigma, lg); }
    inline double pnorm(double x, double mu, double sigma, int lt, int lg)      { return ::Rf_pnorm5(x, mu, sigma, lt, lg); }
    inline double qnorm(double p, double mu, double sigma, int lt, int lg)      { return ::Rf_qnorm5(p, mu, sigma, lt, lg); }
    inline double rnorm(double mu, double sigma)                                { return ::Rf_rnorm(mu, sigma); }
    inline void	pnorm_both(double x, double *cum, double *ccum, int lt, int lg) { return ::Rf_pnorm_both(x, cum, ccum, lt, lg); }

    /* Uniform Distribution */
    inline double dunif(double x, double a, double b, int lg)		{ return ::Rf_dunif(x, a, b, lg); }
    inline double punif(double x, double a, double b, int lt, int lg)   { return ::Rf_punif(x, a, b, lt, lg); }
    inline double qunif(double p, double a, double b, int lt, int lg)   { return ::Rf_qunif(p, a, b, lt, lg); }
    inline double runif(double a, double b)                             { return ::Rf_runif(a, b); }

    /* Gamma Distribution */
    inline double dgamma(double x, double shp, double scl, int lg)	   { return ::Rf_dgamma(x, shp, scl, lg); }
    inline double pgamma(double x, double alp, double scl, int lt, int lg) { return ::Rf_pgamma(x, alp, scl, lt, lg); }
    inline double qgamma(double p, double alp, double scl, int lt, int lg) { return ::Rf_qgamma(p, alp, scl, lt, lg); }
    inline double rgamma(double a, double scl)                             { return ::Rf_rgamma(a, scl); }

    inline double log1pmx(double x)                  { return ::Rf_log1pmx(x); }
    inline double log1pexp(double x)                 { return ::log1pexp(x); }  // <-- ../nmath/plogis.c
    inline double lgamma1p(double a)                 { return ::Rf_lgamma1p(a); }
    inline double logspace_add(double lx, double ly) { return ::Rf_logspace_add(lx, ly); }
    inline double logspace_sub(double lx, double ly) { return ::Rf_logspace_sub(lx, ly); }

    /* Beta Distribution */
    inline double dbeta(double x, double a, double b, int lg)         { return ::Rf_dbeta(x, a, b, lg); }
    inline double pbeta(double x, double p, double q, int lt, int lg) { return ::Rf_pbeta(x, p, q, lt, lg); }
    inline double qbeta(double a, double p, double q, int lt, int lg) { return ::Rf_qbeta(a, p, q, lt, lg); }
    inline double rbeta(double a, double b)                           { return ::Rf_rbeta(a, b); }

    /* Lognormal Distribution */
    inline double dlnorm(double x, double ml, double sl, int lg)	 { return ::Rf_dlnorm(x, ml, sl, lg); }
    inline double plnorm(double x, double ml, double sl, int lt, int lg) { return ::Rf_plnorm(x, ml, sl, lt, lg); }
    inline double qlnorm(double p, double ml, double sl, int lt, int lg) { return ::Rf_qlnorm(p, ml, sl, lt, lg); }
    inline double rlnorm(double ml, double sl)                           { return ::Rf_rlnorm(ml, sl); }

    /* Chi-squared Distribution */
    inline double dchisq(double x, double df, int lg)          { return ::Rf_dchisq(x, df, lg); }
    inline double pchisq(double x, double df, int lt, int lg)  { return ::Rf_pchisq(x, df, lt, lg); }
    inline double qchisq(double p, double df, int lt, int lg)  { return ::Rf_qchisq(p, df, lt, lg); }
    inline double rchisq(double df)                            { return ::Rf_rchisq(df); }

    /* Non-central Chi-squared Distribution */
    inline double dnchisq(double x, double df, double ncp, int lg)          { return ::Rf_dnchisq(x, df, ncp, lg); }
    inline double pnchisq(double x, double df, double ncp, int lt, int lg)  { return ::Rf_pnchisq(x, df, ncp, lt, lg); }
    inline double qnchisq(double p, double df, double ncp, int lt, int lg)  { return ::Rf_qnchisq(p, df, ncp, lt, lg); }
    inline double rnchisq(double df, double lb)                             { return ::Rf_rnchisq(df, lb); }

    /* F Distibution */
    inline double df(double x, double df1, double df2, int lg)		{ return ::Rf_df(x, df1, df2, lg); }
    inline double pf(double x, double df1, double df2, int lt, int lg)	{ return ::Rf_pf(x, df1, df2, lt, lg); }
    inline double qf(double p, double df1, double df2, int lt, int lg)	{ return ::Rf_qf(p, df1, df2, lt, lg); }
    inline double rf(double df1, double df2)				{ return ::Rf_rf(df1, df2); }

    /* Student t Distibution */
    inline double dt(double x, double n, int lg)			{ return ::Rf_dt(x, n, lg); }
    inline double pt(double x, double n, int lt, int lg)		{ return ::Rf_pt(x, n, lt, lg); }
    inline double qt(double p, double n, int lt, int lg)		{ return ::Rf_qt(p, n, lt, lg); }
    inline double rt(double n)						{ return ::Rf_rt(n); }

    /* Binomial Distribution */
    inline double dbinom(double x, double n, double p, int lg)	  	{ return ::Rf_dbinom(x, n, p, lg); }
    inline double pbinom(double x, double n, double p, int lt, int lg)  { return ::Rf_pbinom(x, n, p, lt, lg); }
    inline double qbinom(double p, double n, double m, int lt, int lg)  { return ::Rf_qbinom(p, n, m, lt, lg); }
    inline double rbinom(double n, double p)				{ return ::Rf_rbinom(n, p); }

    /* Multnomial Distribution */
    inline void rmultinom(int n, double* prob, int k, int* rn)		{ return ::rmultinom(n, prob, k, rn); }

    /* Cauchy Distribution */
    inline double dcauchy(double x, double lc, double sl, int lg)		{ return ::Rf_dcauchy(x, lc, sl, lg); }
    inline double pcauchy(double x, double lc, double sl, int lt, int lg)	{ return ::Rf_pcauchy(x, lc, sl, lt, lg); }
    inline double qcauchy(double p, double lc, double sl, int lt, int lg)	{ return ::Rf_qcauchy(p, lc, sl, lt, lg); }
    inline double rcauchy(double lc, double sl)					{ return ::Rf_rcauchy(lc, sl); }

    /* Exponential Distribution */
    inline double dexp(double x, double sl, int lg)		{ return ::Rf_dexp(x, sl, lg); }
    inline double pexp(double x, double sl, int lt, int lg)	{ return ::Rf_pexp(x, sl, lt, lg); }
    inline double qexp(double p, double sl, int lt, int lg)	{ return ::Rf_qexp(p, sl, lt, lg); }
    inline double rexp(double sl)				{ return ::Rf_rexp(sl); }

    /* Geometric Distribution */
    inline double dgeom(double x, double p, int lg)		{ return ::Rf_dgeom(x, p, lg); }
    inline double pgeom(double x, double p, int lt, int lg)	{ return ::Rf_pgeom(x, p, lt, lg); }
    inline double qgeom(double p, double pb, int lt, int lg)	{ return ::Rf_qgeom(p, pb, lt, lg); }
    inline double rgeom(double p)				{ return ::Rf_rgeom(p); }

    /* Hypergeometric Distibution */
    inline double dhyper(double x, double r, double b, double n, int lg)		{ return ::Rf_dhyper(x, r, b, n, lg); }
    inline double phyper(double x, double r, double b, double n, int lt, int lg)	{ return ::Rf_phyper(x, r, b, n, lt, lg); }
    inline double qhyper(double p, double r, double b, double n, int lt, int lg)	{ return ::Rf_qhyper(p, r, b, n, lt, lg); }
    inline double rhyper(double r, double b, double n)					{ return ::Rf_rhyper(r, b, n); }

    /* Negative Binomial Distribution */
    inline double dnbinom(double x, double sz, double pb, int lg)		{ return ::Rf_dnbinom(x, sz, pb, lg); }
    inline double pnbinom(double x, double sz, double pb, int lt, int lg)	{ return ::Rf_pnbinom(x, sz, pb, lt, lg); }
    inline double qnbinom(double p, double sz, double pb, int lt, int lg)	{ return ::Rf_qnbinom(p, sz, pb, lt, lg); }
    inline double rnbinom(double sz, double pb)					{ return ::Rf_rnbinom(sz, pb); }

#if R_VERSION >= R_Version(3, 1, 2)
    inline double dnbinom_mu(double x, double sz, double mu, int lg)		{ return ::Rf_dnbinom_mu(x, sz, mu, lg); }
    inline double pnbinom_mu(double x, double sz, double mu, int lt, int lg)	{ return ::Rf_pnbinom_mu(x, sz, mu, lt, lg); }
    inline double qnbinom_mu(double x, double sz, double mu, int lt, int lg)	{ return ::Rf_qnbinom_mu(x, sz, mu, lt, lg); }
    //inline double rnbinom_mu(double sz, double mu)				{ return ::Rf_rnbinom_mu(sz, mu); }
#endif

    /* Poisson Distribution */
    inline double dpois(double x, double lb, int lg)		{ return ::Rf_dpois(x, lb, lg); }
    inline double ppois(double x, double lb, int lt, int lg)	{ return ::Rf_ppois(x, lb, lt, lg); }
    inline double qpois(double p, double lb, int lt, int lg)	{ return ::Rf_qpois(p, lb, lt, lg); }
    inline double rpois(double mu)				{ return ::Rf_rpois(mu); }

    /* Weibull Distribution */
    inline double dweibull(double x, double sh, double sl, int lg)		{ return ::Rf_dweibull(x, sh, sl, lg); }
    inline double pweibull(double x, double sh, double sl, int lt, int lg)	{ return ::Rf_pweibull(x, sh, sl, lt, lg); }
    inline double qweibull(double p, double sh, double sl, int lt, int lg)	{ return ::Rf_qweibull(p, sh, sl, lt, lg); }
    inline double rweibull(double sh, double sl)				{ return ::Rf_rweibull(sh, sl); }

    /* Logistic Distribution */
    inline double dlogis(double x, double lc, double sl, int lg)		{ return ::Rf_dlogis(x, lc, sl, lg); }
    inline double plogis(double x, double lc, double sl, int lt, int lg)	{ return ::Rf_plogis(x, lc, sl, lt, lg); }
    inline double qlogis(double p, double lc, double sl, int lt, int lg)	{ return ::Rf_qlogis(p, lc, sl, lt, lg); }
    inline double rlogis(double lc, double sl)					{ return ::Rf_rlogis(lc, sl); }

    /* Non-central Beta Distribution */
    inline double dnbeta(double x, double a, double b, double ncp, int lg)		{ return ::Rf_dnbeta(x, a, b, ncp, lg); }
    inline double pnbeta(double x, double a, double b, double ncp, int lt, int lg)	{ return ::Rf_pnbeta(x, a, b, ncp, lt, lg); }
    inline double qnbeta(double p, double a, double b, double ncp, int lt, int lg)	{ return ::Rf_qnbeta(p, a, b, ncp, lt, lg); }
    inline double rnbeta(double a, double b, double np)					{ return ::Rf_rnbeta(a, b, np); }

    /* Non-central F Distribution */
    inline double dnf(double x, double df1, double df2, double ncp, int lg)		{ return ::Rf_dnf(x, df1, df2, ncp, lg); }
    inline double pnf(double x, double df1, double df2, double ncp, int lt, int lg)	{ return ::Rf_pnf(x, df1, df2, ncp, lt, lg); }
    inline double qnf(double p, double df1, double df2, double ncp, int lt, int lg)	{ return ::Rf_qnf(p, df1, df2, ncp, lt, lg); }

    /* Non-central Student t Distribution */
    inline double dnt(double x, double df, double ncp, int lg)		{ return ::Rf_dnt(x, df, ncp, lg); }
    inline double pnt(double x, double df, double ncp, int lt, int lg)	{ return ::Rf_pnt(x, df, ncp, lt, lg); }
    inline double qnt(double p, double df, double ncp, int lt, int lg)	{ return ::Rf_qnt(p, df, ncp, lt, lg); }

    /* Studentized Range Distribution */
    inline double ptukey(double q, double rr, double cc, double df, int lt, int lg)	{ return ::Rf_ptukey(q, rr, cc, df, lt, lg); }
    inline double qtukey(double p, double rr, double cc, double df, int lt, int lg)	{ return ::Rf_qtukey(p, rr, cc, df, lt, lg); }

    /* Wilcoxon Rank Sum Distribution */
    inline double dwilcox(double x, double m, double n, int lg)		{ return ::Rf_dwilcox(x, m, n, lg); }
    inline double pwilcox(double q, double m, double n, int lt, int lg)	{ return ::Rf_pwilcox(q, m, n, lt, lg); }
    inline double qwilcox(double x, double m, double n, int lt, int lg)	{ return ::Rf_qwilcox(x, m, n, lt, lg); }
    inline double rwilcox(double m, double n)				{ return ::Rf_rwilcox(m, n); }

    /* Wilcoxon Signed Rank Distribution */
    inline double dsignrank(double x, double n, int lg)			{ return ::Rf_dsignrank(x, n, lg); }
    inline double psignrank(double x, double n, int lt, int lg)		{ return ::Rf_psignrank(x, n, lt, lg); }
    inline double qsignrank(double x, double n, int lt, int lg)		{ return ::Rf_qsignrank(x, n, lt, lg); }
    inline double rsignrank(double n)					{ return ::Rf_rsignrank(n); }

    /* Gamma and Related Functions */
    inline double gammafn(double x)			{ return ::Rf_gammafn(x); }
    inline double lgammafn(double x)			{ return ::Rf_lgammafn(x); }
    inline double lgammafn_sign(double x, int *sgn)	{ return ::Rf_lgammafn_sign(x, sgn); }
    inline void   dpsifn(double x, int n, int kode, int m, double *ans, int *nz, int *ierr)	{ return ::Rf_dpsifn(x, n, kode, m, ans, nz, ierr); }
    inline double psigamma(double x, double deriv)	{ return ::Rf_psigamma(x, deriv); }
    inline double digamma(double x)	{ return ::Rf_digamma(x); }
    inline double trigamma(double x)	{ return ::Rf_trigamma(x); }
    inline double tetragamma(double x)	{ return ::Rf_tetragamma(x); }
    inline double pentagamma(double x)	{ return ::Rf_pentagamma(x); }

    inline double beta(double a, double b)	{ return ::Rf_beta(a, b); }
    inline double lbeta(double a, double b)	{ return ::Rf_lbeta(a, b); }

    inline double choose(double n, double k)	{ return ::Rf_choose(n, k); }
    inline double lchoose(double n, double k)	{ return ::Rf_lchoose(n, k); }

    /* Bessel Functions */
    inline double bessel_i(double x, double al, double ex)	{ return ::Rf_bessel_i(x, al, ex); }
    inline double bessel_j(double x, double al)			{ return ::Rf_bessel_j(x, al); }
    inline double bessel_k(double x, double al, double ex)	{ return ::Rf_bessel_k(x, al, ex); }
    inline double bessel_y(double x, double al)			{ return ::Rf_bessel_y(x, al); }
    inline double bessel_i_ex(double x, double al, double ex, double *bi)	{ return ::Rf_bessel_i_ex(x, al, ex, bi); }
    inline double bessel_j_ex(double x, double al, double *bj)			{ return ::Rf_bessel_j_ex(x, al, bj); }
    inline double bessel_k_ex(double x, double al, double ex, double *bk)	{ return ::Rf_bessel_k_ex(x, al, ex, bk); }
    inline double bessel_y_ex(double x, double al, double *by)			{ return ::Rf_bessel_y_ex(x, al, by); }

    /* General Support Functions */
#ifndef HAVE_HYPOT
    inline double hypot(double a, double b)	{ return ::Rf_hypot(a, b); }
#endif
    inline double pythag(double a, double b)	{ return ::Rf_pythag(a, b); }
#ifndef HAVE_EXPM1
    inline double expm1(double x); /* = exp(x)-1 {care for small x} */	{ return ::Rf_expm1(x); }
#endif
#ifndef HAVE_LOG1P
    inline double log1p(double x); /* = log(1+x) {care for small x} */ { return ::Rf_log1p(x); }
#endif
    inline int imax2(int x, int y)		{ return ::Rf_imax2(x, y); }
    inline int imin2(int x, int y)		{ return ::Rf_imin2(x, y); }
    inline double fmax2(double x, double y)	{ return ::Rf_fmax2(x, y); }
    inline double fmin2(double x, double y)	{ return ::Rf_fmin2(x, y); }
    inline double sign(double x)		{ return ::Rf_sign(x); }
    inline double fprec(double x, double dg)	{ return ::Rf_fprec(x, dg); }
    inline double fround(double x, double dg)	{ return ::Rf_fround(x, dg); }
    inline double fsign(double x, double y)	{ return ::Rf_fsign(x, y); }
    inline double ftrunc(double x)		{ return ::Rf_ftrunc(x); }

}

#endif


text:
{% include base_path %}

<!-- start custom head snippets -->

<link rel="apple-touch-icon" sizes="57x57" href="{{ base_path }}/images/logo/apple-touch-icon-57x57.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="60x60" href="{{ base_path }}/images/logo/apple-touch-icon-60x60.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="72x72" href="{{ base_path }}/images/logo/apple-touch-icon-72x72.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="76x76" href="{{ base_path }}/images/logo/apple-touch-icon-76x76.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="114x114" href="{{ base_path }}/images/logo/apple-touch-icon-114x114.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="120x120" href="{{ base_path }}/images/logo/apple-touch-icon-120x120.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="144x144" href="{{ base_path }}/images/logo/apple-touch-icon-144x144.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="152x152" href="{{ base_path }}/images/logo/apple-touch-icon-152x152.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="180x180" href="{{ base_path }}/images/logo/apple-touch-icon-180x180.png?v=M44lzPylqQ">
<link rel="icon" type="image/png" href="{{ base_path }}/images/logo/favicon-32x32.png?v=M44lzPylqQ" sizes="32x32">
<link rel="icon" type="image/png" href="{{ base_path }}/images/logo/android-chrome-192x192.png?v=M44lzPylqQ" sizes="192x192">
<link rel="icon" type="image/png" href="{{ base_path }}/images/logo/favicon-96x96.png?v=M44lzPylqQ" sizes="96x96">
<link rel="icon" type="image/png" href="{{ base_path }}/images/logo/favicon-16x16.png?v=M44lzPylqQ" sizes="16x16">
<link rel="manifest" href="{{ base_path }}/images/logo/manifest.json?v=M44lzPylqQ">
<link rel="mask-icon" href="{{ base_path }}/images/logo/safari-pinned-tab.svg?v=M44lzPylqQ" color="#000000">
<link rel="shortcut icon" href="/images/logo/favicon.ico?v=M44lzPylqQ">
<meta name="msapplication-TileColor" content="#000000">
<meta name="msapplication-TileImage" content="{{ base_path }}/images/logo/mstile-144x144.png?v=M44lzPylqQ">
<meta name="msapplication-config" content="{{ base_path }}/images/logo/browserconfig.xml?v=M44lzPylqQ">
<meta name="theme-color" content="#ffffff">

<!-- end custom head snippets -->


text:
//
//  RoleOracle.java
//  blogwt
//
//  Created by William Shakour (billy1380) on 3 Oct 2015.
//  Copyright © 2015 WillShex Limited. All rights reserved.
//
package com.willshex.blogwt.client.oracle;

import java.util.Collections;

import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.willshex.blogwt.client.controller.SessionController;
import com.willshex.blogwt.client.helper.ApiHelper;
import com.willshex.blogwt.shared.api.datatype.Role;
import com.willshex.blogwt.shared.api.user.call.GetRolesRequest;
import com.willshex.blogwt.shared.api.user.call.GetRolesResponse;
import com.willshex.blogwt.shared.helper.PagerHelper;
import com.willshex.gson.web.service.shared.StatusType;

/**
 * @author William Shakour (billy1380)
 *
 */
public class RoleOracle extends SuggestOracle<Role> {

	public interface NameDescriptionTemplates extends SafeHtmlTemplates {

		NameDescriptionTemplates INSTANCE = GWT
				.create(NameDescriptionTemplates.class);

		@Template("{0}
{1}
")
		SafeHtml description (String name, String description);
	}

	private com.google.gwt.http.client.Request getRolesRequest;

	/* (non-Javadoc)
	 *
	 * @see
	 * com.willshex.blogwt.client.oracle.SuggestOracle#lookup(com.google.gwt
	 * .user.client.ui.SuggestOracle.Request,
	 * com.google.gwt.user.client.ui.SuggestOracle.Callback) */
	@Override
	protected void lookup (final Request request, final Callback callback) {
		final GetRolesRequest input = ApiHelper
				.setAccessCode(new GetRolesRequest());
		input.session = SessionController.get().sessionForApiCall();
		input.query = request.getQuery();
		input.pager = PagerHelper.createDefaultPager();
		input.pager.count = Integer.valueOf(request.getLimit());

		if (getRolesRequest != null) {
			getRolesRequest.cancel();
		}

		getRolesRequest = ApiHelper.createUserClient().getRoles(input,
				new AsyncCallback<GetRolesResponse>() {

					@Override
					public void onSuccess (GetRolesResponse output) {
						if (output.status == StatusType.StatusTypeSuccess
								&& output.pager != null) {
							foundItems(request, callback, output.roles);
						} else {
							foundItems(request, callback,
									Collections.<Role> emptyList());
						}
					}

					@Override
					public void onFailure (Throwable caught) {
						GWT.log("Error getting roles with query " + input.query,
								caught);

						foundItems(request, callback,
								Collections.<Role> emptyList());
					}
				});
	}

	/* (non-Javadoc)
	 *
	 * @see
	 * com.willshex.blogwt.client.oracle.SuggestOracle#getDisplayString(java
	 * .lang.Object) */
	@Override
	protected String getDisplayString (Role item) {
		return NameDescriptionTemplates.INSTANCE.description(item.name,
				item.description).asString();
	}

	/* (non-Javadoc)
	 *
	 * @see
	 * com.willshex.blogwt.client.oracle.SuggestOracle#getReplacementString
	 * (java.lang.Object) */
	@Override
	protected String getReplacementString (Role item) {
		return item.code;
	}

	/* (non-Javadoc)
	 *
	 * @see com.google.gwt.user.client.ui.SuggestOracle#isDisplayStringHTML() */
	@Override
	public boolean isDisplayStringHTML () {
		return true;
	}

	/* (non-Javadoc)
	 *
	 * @see com.willshex.blogwt.client.oracle.SuggestOracle#getQueryMinLength() */
	@Override
	protected int getQueryMinLength () {
		return 0;
	}

}


text:
import { ReactElement } from 'react';
import { Route, RouterOnContext } from 'react-router';
import { Store } from 'redux';
import { ThunkAction, ActionCreator } from 'redux';
import { Reducer } from 'redux';
import { namespace as createPollNamespace } from 'features/editPoll';
import { namespace as viewPollsNamespace } from 'features/viewPolls';
import Api from '../api/Api';

interface IModule<S> {
  router: RouterOnContext | null;
  store: Store<IReduxState> | null;
  getRoutes?: () => ReactElement<Route.RouteProps> | Array<ReactElement<Route.RouteProps>>;
  getReducer?: () => { name: string; reducer: Reducer<S> };
}

interface IExtraArguments {
  api: Api;
}

interface IAction {
  payload?: { [key: string]: any } | number | string | null;
  type: string;
}

interface IReduxState {
  createPoll: createPollNamespace.IReduxState;
  viewPolls: viewPollsNamespace.IReduxState;
}

interface ICommunication {
  isRequesting: boolean;
  error: string;
}

type AsyncActionCreatorResult = ThunkAction<Promise<void>, IReduxState, IExtraArguments>;
type AsyncActionCreator = ActionCreator<AsyncActionCreatorResult>;
type QuestionType = 'YesNo' | 'SingleChoice';

/* Main app entities */
interface IEditablePoll {
  id?: string;
  isActive: boolean;
  title: string;
  description: string;
  startTime: string;
  endTime: string;
  questions: IEditableQuestion[];
}

interface IEditableQuestion {
  type: 'YesNo' | 'SingleChoice';
  text: string;
  answers: IEditableAnswer[];
}

interface IEditableAnswer {
  id?: string;
  text: string;
}

interface IPoll {
  id: string | number;
  isActive: boolean;
  title: string;
  description: string;
  startTime: string;
  endTime: string;
  questions: IQuestion[];
}

interface IQuestion {
  type: 'YesNo' | 'SingleChoice';
  text: string;
  answers: IAnswer[];
}

interface IAnswer {
  id: string;
  text: string;
  isSelected: boolean;
}

interface IPollResult {
  id?: string;
  pollId: string;
  questions: IQuestionResult[];
}

interface IQuestionResult {
  answerId: string;
  text: string;
  answer: string;
}

export {
  IQuestionResult,
  IPollResult,
  ICommunication,
  IQuestion,
  IAnswer,
  IPoll,
  QuestionType,
  IEditablePoll,
  IEditableQuestion,
  IEditableAnswer,
  IModule,
  IAction,
  IExtraArguments,
  IReduxState,
  AsyncActionCreator,
  AsyncActionCreatorResult
};


text:
import webapp2

class MainHandler(webapp2.RequestHandler):
    def dispatch(self):
    	self.response.headers['Cache-Control'] = 'no-store'
    	self.response.headers['Content-Type'] = 'text/plain'
        self.response.write(self.request)

    def get(self):
    	self.dispatch()

	def post(self):
		self.dispatch()

	def put(self):
		self.dispatch()

	def delete(self):
		self.dispatch()

app = webapp2.WSGIApplication([
    (r'/', MainHandler),
    (r'/.*', MainHandler)
], debug=True)


text:
/* import Vector */ var Vector = require('./../../../../app/js/model/geometry/Vector');
/* import Box */ var Box = require('./../../../../app/js/model/geometry/shape/Box');
/* import Meta */ var Meta = window.Meta;

var box = new Box({
    position: Vector.fromArray([1, 1]),
    size: Vector.fromArray([1, 1]),
    speed: Vector.fromArray([2, 1])
});

describe('PhysicalObject', function () {

    it('make a small movement', function () {
        var movedObject = box.applyTime(1);
        expect(movedObject.position.coords).toEqual([3, 2]);
    });
});


text:
package rosa.core;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import rosa.core.util.XMLUtil;

// TODO move

public class SceneMapping {
	/**
	 * Divide into blocks. Each block (except possibly the last) ends with a
	 * known lecoy number. If there is a difference between guess for the end
	 * block and the correct value, spread that difference evenly through the
	 * block.
	 *
	 * Returns array of start (inclusive), end (exlusive) lecoy numbers parallel
	 * to cols.
	 */

	private static int[] guessLecoy(List<BookStructure.Column> cols,
			boolean usesyncpoints) {
		int[] guess = new int[cols.size() + 1];

		int total_poetry_lines = 0;

		for (BookStructure.Column col : cols) {
			total_poetry_lines += col.linesOfPoetry();
		}

		int avg_col_poetry_lines = Math.round((float) total_poetry_lines
				/ cols.size());

		int start = 0; // start of block inclusive
		int end = cols.size(); // end of block inclusive
		guess[0] = 1;

		for (;;) {
			for (end = start; end < cols.size(); end++) {
				BookStructure.Column col = cols.get(end);

				guess[end + 1] = guess[end] + col.linesOfPoetry();

				if (col.firstLineLecoy() != -1) {
					break;
				}
			}

			if (end == cols.size()) {
				break;
			}

			// TODO spread more uniformly?

			if (usesyncpoints) {
				BookStructure.Column startcol = cols.get(start);
				BookStructure.Column endcol = cols.get(end);

				int diff = guess[end] - endcol.firstLineLecoy();

				// System.err.println(endcol + " " + diff);

				guess[end] = endcol.firstLineLecoy();
				guess[end + 1] = guess[end] + endcol.linesOfPoetry();

				if (diff < 0) {
					diff = -diff;
					// Missing lines, possibly whole leaves
					// Assume missing leaves are in middle of block

					if (diff > avg_col_poetry_lines * 2) {
						System.err
								.println("Probably at least one leaf missing between "
										+ startcol + " and " + endcol);
					}

					int middle = (start + end) / 2;

					for (int i = middle; i < end; i++) {
						guess[i] += diff;
					}
				} else if (diff > 0) {
					// More non-lecoy itmes than expected
					// Assume additional stuff is in middle of block

					int middle = (start + end) / 2;

					for (int i = middle; i < end; i++) {
						guess[i] -= diff;
					}
				}
			}

			start = end + 1;
		}

		// for (int i = 0; i < cols.size(); i++) {
		// BookStructure.Column col = cols.get(i);
		//
		// System.err.println(col
		// + " "
		// + guess[i]
		// + (col.firstLineLecoy() == -1 ? "" : " [lecoy: "
		// + col.firstLineLecoy() + "]"));
		// }

		return guess;
	}

	/**
	 * Guess narrative mapping. If transcription file not null, add lines from
	 * this transcription. The string trans_prefix will be prepended to each transcription line.
	 */
	public static NarrativeMapping guessNarrativeScenes(NarrativeSections nar,
			BookStructure struct, boolean usesyncpoints, File transcription, String trans_prefix)
			throws IOException, SAXException {
		// Turn guess of column start/end lecoy into guess of scene start/end
		// columns

		List<BookStructure.Column> cols = struct.columns();
		int[] lecoyguess = guessLecoy(cols, usesyncpoints);

		NarrativeSections.Scene[] scenes = nar.asScenes();
		BookStructure.Column[] sceneguess = new BookStructure.Column[scenes.length * 2];

		// line offset into scene, starts at 1, inclusive
		int[] scenelineguess = new int[scenes.length * 2];

		for (int i = 0; i < lecoyguess.length - 1; i++) {
			int start = lecoyguess[i];
			int end = lecoyguess[i + 1];
			BookStructure.Column col = cols.get(i);

			for (int j = 0; j < scenes.length; j++) {
				NarrativeSections.Scene scene = scenes[j];

				if (!scene.isLecoy()) {
					continue;
				}

				if (start <= scene.lecoy_start && end > scene.lecoy_start) {
					sceneguess[j * 2] = col;
					scenelineguess[j * 2] = scene.lecoy_start - start + 1;
				}

				if (start <= scene.lecoy_end && end > scene.lecoy_end) {
					sceneguess[(j * 2) + 1] = col;
					scenelineguess[(j * 2) + 1] = scene.lecoy_end - start + 1;
				}
			}
		}

		NodeList milestones = null;

		if (transcription != null) {
			Document doc = XMLUtil.createDocument(transcription);
			milestones = doc.getElementsByTagName("milestone");
		}

		// Turn scene start/end columns into narrative tagging
		NarrativeMapping guess = new NarrativeMapping();

		for (int j = 0; j < scenes.length; j++) {
			NarrativeSections.Scene scene = scenes[j];
			BookStructure.Column start = sceneguess[j * 2];
			BookStructure.Column end = sceneguess[(j * 2) + 1];
			int startline = scenelineguess[j * 2];
			int endline = scenelineguess[(j * 2) + 1];

			if (start == null || end == null) {
				// System.err.println("Bad error, start or end null for scene "
				// + scene.id);
				continue;
			}

			String start_trans = null;

			if (milestones != null) {
				String s = "" + scene.lecoy_start;

				for (int i = 0; i < milestones.getLength(); i++) {
					Element m = (Element) milestones.item(i);

					if (m.getAttribute("n").equals(s)) {
						// TODO not accurate for all transcriptions
						start_trans = trans_prefix + " " + XMLUtil.extractText(m.getParentNode()).trim();
						break;
					}
				}
			}

			//System.out.println(scene.id + " " + scene.lecoy_start);

			guess.scenes().add(
					new NarrativeMapping.Scene(scene.id,
							start.parent().folio(), "" + start.columnLetter(),
							startline, end.parent().folio(), ""
									+ end.columnLetter(), endline, start_trans,
							false, scene.lecoy_start));
		}

		return guess;
	}

	private static int numColumns(String folio, String col) {
		int n = Integer.parseInt(folio.substring(0, folio.length() - 1)) - 1;
		int s = folio.endsWith("r") ? 0 : 1;
		int c = (col.equals("a") || col.equals("c")) ? 0 : 1;

		return (n * 4) + (s * 2) + c;
	}

	public static void printComparison(NarrativeMapping truthnar,
			NarrativeMapping guessnar) {
		int count = 0;
		int columncorrect = 0;
		int pagecorrect = 0;
		int totalcoldiff = 0;
		int withinoncolumn = 0;

		System.out
				.println("Scene,Location,GuessColumn,CorrectColumn,ColumnDiff");

		next: for (NarrativeMapping.Scene truth : truthnar.scenes()) {
			for (NarrativeMapping.Scene guess : guessnar.scenes()) {
				if (guess.id().equals(truth.id())) {
					if (guess.startFolio().equals(truth.startFolio())) {
						pagecorrect++;

						if (guess.startFolioCol().equals(truth.startFolioCol())) {
							columncorrect++;
						}
					}

					int coldiff = numColumns(guess.startFolio(), guess
							.startFolioCol())
							- numColumns(truth.startFolio(), truth
									.startFolioCol());

					totalcoldiff += Math.abs(coldiff);

					if (Math.abs(coldiff) <= 1) {
						withinoncolumn++;
					}

					System.out.println(guess.id()
							+ ", "
							+ guess.startFolio()
							+ "."
							+ guess.startFolioCol()
							+ ", "
							+ truth.startFolio()
							+ "."
							+ truth.startFolioCol()
							+ ", "
							+ numColumns(guess.startFolio(), guess
									.startFolioCol()) + ", " + coldiff);

					count++;
					continue next;
				}
			}

			System.err.println("No guess for " + truth.id());
		}

		System.err.println("Total " + count);
		System.err.println("Correct column: " + columncorrect + " ("
				+ ((float) columncorrect / count) + "%)");
		System.err.println("Correct within one column: " + withinoncolumn
				+ " (" + ((float) withinoncolumn / count) + "%)");
		System.err.println("Correct page: " + pagecorrect + " ("
				+ ((float) pagecorrect / count) + "%)");
		System.err.println("Column diff avg: "
				+ +((float) totalcoldiff / count));
	}
}


text:
**The Character Sheet / Map Visibility**

The biggest problem with playing Heroclix on Roll20 is the lack of visibilty into the figures on map. You can have the dials open on HCRealms and check, but that current method makes it easy to miss changes in click on figures and hard to keep track of which of multiple of the same figure is on which click. The goal of this extension is to allow the dials to displayed on map in Roll20 to prevent those kinds of mistakes from happening and to make Roll20 play a little smoother. Once it's set up your character will look like this:

![First Image](Documentation/Final%20product.PNG)

The dial is above the figure and can be clicked by changing the value in the green bubble that appears when the figure is clicked.

**Creating A New Figure**

In order to use this character sheet you must first have access to a game using this character sheet. In order to gain acces to a roll20 game that uses this you must either have Roll20 Pro which allows you to use custom sheets and put the HTMl and CSS for this sheet into the settings page or contact me for an invite to game that uses the sheet. Once you are in a game that uses the sheet you must first add a character in the journal:

![First Image](Documentation/Create%20Character.png)

One the character has been created click save changes and go to the character sheet tab, it should look like this:

![First Image](Documentation/Character%20Sheet.png)

To fill in the character sheet manually just click the add button to add a new click and then enter the character's stats on that click. In order to load a character intro the sheet automatically go to hcrealms, and find the character you want to load in in the units section. click the dial button on the top right of the chracter dial, as shown below:

![First Image](Documentation/HCRealms%20DialCode%20Link.png)

Once on the Inline dial page copy the contents of the BBcode box, as shown below, and return to the character sheet:

![First Image](Documentation/HCRealms%20BBCode.png)

Paste the BBcode into the dial box on the character sheet and click the populate button

![First Image](Documentation/Character%20Sheet%20BBCode.png)

![First Image](Documentation/Character%20Sheet%20Populate.png)

The result should look like this:

![First Image](Documentation/Populated%20Character%20Sheet.png)

**Adding the Token and Dial to the Map**

Once your character sheet is populated, whether manually or automatically you have to add the image to the map and relate it to the character sheet so that the dial can appear on map. To get started click the settings button that appears when you click on the image, as shown below:

![First Image](Documentation/Token%20Settings.png)

Then relate the first bar to Clicks, the second to attack_current and the third to damage_current. If you aren't using an image of the actual character I reccomend using an image of a black square so that the bars show better on map and moving the bars to bottom overlapping in the advanced tab. Also check show nameplate if not using an actual image of the character. When you are done filling in the setting spage it should look like this:

![First Image](Documentation/Filled%20Token%20Settings.png)

To change clicks change the value in the green bubble when clicking on the character as shown below. Your final result should look like this:

![First Image](Documentation/Filled%20Token%20On%20Map.png)


text:
package cz.afrosoft.whattoeat.core.gui.component;

import cz.afrosoft.whattoeat.cookbook.ingredient.logic.service.IngredientQuantityService;
import javafx.scene.control.TableCell;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

/**
 * Cell for displaying quantity of ingredient. Use {@link IngredientQuantityService} for intelligent formatting which use
 * {@link cz.afrosoft.whattoeat.cookbook.ingredient.logic.model.UnitConversion} if possible to provide suitable unit and conversion.
 * <p>
 * This cell does not support editing.
 *
 * @author Tomas Rejent
 */
public class IngredientQuantityCell extends TableCell<IngredientQuantity, Float> {

    private final IngredientQuantityService quantityService;

    public IngredientQuantityCell(final IngredientQuantityService quantityService) {
        Validate.notNull(quantityService);
        this.quantityService = quantityService;
    }

    @Override
    protected void updateItem(final Float quantity, final boolean empty) {
        super.updateItem(quantity, empty);

        if (quantity == null || empty) {
            setText(StringUtils.EMPTY);
        } else {
            IngredientQuantity ingredientQuantity = getTableView().getItems().get(getIndex());
            setText(quantityService.getFormattedQuantity(ingredientQuantity.getIngredient(), quantity));
        }
    }
}


text:
id: 53
title: Backup con rsync
author: Stefano Marzorati
layout: post
guid: http://ubbunti.wordpress.com/2011/03/05/backup-con-rsync
permalink: /backup-con-rsync/
blogger_blog:
  - ubbunti.blogspot.com
  - ubbunti.blogspot.com
  - ubbunti.blogspot.com
blogger_author:
  - m@il_of_d@y
  - m@il_of_d@y
  - m@il_of_d@y
blogger_e466c7156e8bac77e64f63e8bad92c92_permalink:
  - 413232360335717170
  - 413232360335717170
  - 413232360335717170
dsq_thread_id:
  - 2066525498
categories:
  - Linux
tags:
  - backup
  - rsync
---
Backup (controlla i cambiamenti tra sorgente e destinazione e cancella dalla destinazione i file che sono stati cancellati nella sorgente)

Esempio backup locale/locale:

`rsync -av --delete --progress /home/utente/ /home/utente/Desktop/backup`

Se invece non voglio mai cancellare dalla destinazione, togli –delete

Esempio backup locale/remoto:

`rsync -avz --progress --exclude /cache/ /var/www/html/prova/ root@172.16.1.1:/var/www/html/prova/`


text:
package datamanagement;

import java.io.FileInputStream;
import java.io.IOException;

import java.util.Properties;

public class ApplicationProperties
{
  //===========================================================================
  // Variables
  //===========================================================================

  private static ApplicationProperties instance_ = null;

  private Properties properties_;

  //===========================================================================
  // Constructors
  //===========================================================================

  private ApplicationProperties()
  {
    properties_ = new Properties();
    try {
      properties_.load(new FileInputStream("Properties.prop"));
    }
    catch (IOException exception) {
      throw new RuntimeException("ApplicationProperties : " +
                                 "ApplicationProperties : " +
                                 "Could not read property file");
    }
  }

  //===========================================================================
  // Getters and Setters
  //===========================================================================

  public static ApplicationProperties getInstance()
  {
    if (instance_ == null) {
      instance_ = new ApplicationProperties();
    }
    return instance_;
  }

  public Properties getProperties()
  {
    return properties_;
  }

  //===========================================================================
  // Methods
  //===========================================================================

  public String xmlFileName()
  {
    return getProperties().getProperty("XMLFILE");
  }

}


text:
(function(w) {
	w.hereAtHelp = w.hereAtHelp || {};
	w.hereAtHelp.app = w.angular.module('hereathelp', [
		'hereathelp.services',
		'hereathelp.controllers',
		'pascalprecht.translate',

		'ui.bootstrap',
		'ui.router'
	]);

	w.hereAtHelp.app
		.config(function($stateProvider, $urlRouterProvider) {
			$stateProvider
				.state('items', {
					url: '/items'
				})
				.state('items.view', {
					url: '/:id',
                    parent: 'items'
				})
                .state('dashboard', {
                    url: '/dashboard'
                })
			// TODO more states here...
			;

			$urlRouterProvider
				.otherwise('/items');
		})
		.config(function($translateProvider) {
			$translateProvider
				.translations('en-PH', {
					APP_ID: 'Here@Help',
					LANG_ID: 'en-PH',
					LANG_NAME_LONG: 'English (Philippines)',
					LANG_NAME_SHORT: 'English',
					LANG_VARIANT: 'Philippines',

					LANG_NAME_LONG_LOCAL: 'English (Philippines)',
					LANG_NAME_SHORT_LOCAL: 'English',
					LANG_VARIANT_LOCAL: 'Philippines'
					// TODO more translation strings here...
				})
				.translations('tl-PH', {
					APP_ID: 'Here@Help',
					LANG_ID: 'tl-PH',
					LANG_NAME_LONG: 'Tagalog (Philippines)',
					LANG_NAME_SHORT: 'Tagalog',
					LANG_VARIANT: 'Philippines',

					LANG_NAME_LONG_LOCAL: 'Tagalog (Pilipinas)',
					LANG_NAME_SHORT_LOCAL: 'Tagalog',
					LANG_VARIANT_LOCAL: 'Pilipinas'
					// TODO more translation strings here...
				})
				// TODO more languages here ...
				.preferredLanguage('en-PH')
			;
		})
		.run(function($translate, $rootScope, $state, ItemService) {
			$rootScope.setLanguage = function(lang) {
				$translate.use(lang);
			};

            $rootScope.filter = {};
			$rootScope.title = "Here@Help";

            $rootScope.isState = function(state) {
                return $state.includes(state);
            };

            $rootScope.dashboardMap = null;
            $rootScope.areaMaps = {
                'large': {
                    id: 'area-map',
                    map: null,
                    marker: null,
                    bounds: null
                },
                'mobile': {
                    id: 'area-map-mobile',
                    map: null,
                    marker: null,
                    bounds: null
                }
            };
            $rootScope.currentItem = null;

            $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
            });

            function parseJson(obj) {
                obj = JSON.parse(obj);
            }

            $rootScope.showItem = function(id) {
                $rootScope.currentItem = ItemService.get(parseInt(id));

                _.each($rootScope.areaMaps, function(x, i) {
                    if($rootScope.areaMaps[i].bounds == null) {
                        $rootScope.areaMaps[i].bounds = w.L.polygon($rootScope.currentItem.geobounds, { color: '#0000FF', weight: 8, fill: false });
                        $rootScope.areaMaps[i].map.addLayer($rootScope.areaMaps[i].bounds);
                    }
                    else
                        $rootScope.areaMaps[i].bounds.setLatLngs($rootScope.currentItem.geobounds);

                    $rootScope.areaMaps[i].map.panTo($rootScope.currentItem.location.coords.split(','));

                    if($rootScope.areaMaps[i].marker == null)
                        $rootScope.areaMaps[i].marker = w.L.marker($rootScope.currentItem.location.coords.split(','))
                            .addTo($rootScope.areaMaps[i].map);
                    else
                        $rootScope.areaMaps[i].marker.setLatLng($rootScope.currentItem.location.coords.split(','));

                });
            };

            $rootScope.hideItem = function() {
                $rootScope.currentItem = null;
            };

            ItemService.loadItems()
                .then(function() {
                    $rootScope.items = ItemService.getAll();

                    _.each($rootScope.items, function(x, i) {
                        var location = {
                            coords: '',
                            name: {},
                            nameString : ''
                        };

                        location.coords = $rootScope.items[i]['location'];
                        location.name = JSON.parse($rootScope.items[i]['parse_location_name']);
                        location.nameString = [
                            location.name.properties.county,
                            location.name.properties.region,
                            location.name.properties.country
                        ].join(', ');

                        $rootScope.items[i].id = parseInt($rootScope.items[i].id);
                        $rootScope.items[i]['location'] = location;

                        var geobounds = $rootScope.items[i]['geobounds'].split(';');
                        _.each(geobounds, function(y, j) {
                            geobounds[j] = geobounds[j].split(',');
                            geobounds[j] = { lat: geobounds[j][0], lng: geobounds[j][1] }
                        });
                        $rootScope.items[i]['geobounds'] = geobounds;

                        _.each($rootScope.items[i].needs, function(y, j) {
                            var json = JSON.parse($rootScope.items[i].needs[j].provision.content);

                            $rootScope.items[i].needs[j].provision = json.priorities;
                        });

                        w.angular.element(document).ready(function() {
                            if($rootScope.dashboardMap == null) {
                                $rootScope.dashboardMap = w.L.map('dashboard-map').setView([0, 0], 2);

                                w.L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                                    attribution: '© OpenStreetMap contributors'
                                }).addTo($rootScope.dashboardMap);
                            }

                            $rootScope.items[i]['marker'] = w.L.marker($rootScope.items[i]['location'].coords.split(','))
                                .addTo($rootScope.dashboardMap)
                                .bindPopup(
                                    "" + "Disaster" + "" +
                                    "" + $rootScope.items[i]['location'].nameString + "
" +
                                        "Affected: " + (parseInt($rootScope.items[i]['est_alive']) + parseInt($rootScope.items[i]['est_dead'])) + "
" +
                                        'View');

                            _.each($rootScope.areaMaps, function(y, j) {
                                if($rootScope.areaMaps[j].map == null) {
                                    $rootScope.areaMaps[j].map = w.L.map($rootScope.areaMaps[j].id).setView([0, 0], 14);

                                $rootScope.areaMaps[j].map.on('moveend', function(e) {
                                    _.each($rootScope.areaMaps, function(z, k) {
                                        if(j == k)
                                            return;
                                        var center = e.target.getCenter();
                                        $rootScope.areaMaps[k].map.panTo([center.lat, center.lng], { animate: false });
                                    });
                                });

                                $rootScope.areaMaps[j].map.on('zoomend', function(e) {
                                    _.each($rootScope.areaMaps, function(z, k) {
                                        if(j == k)
                                            return;
                                        $rootScope.areaMaps[k].map.setZoom(e.target.getZoom(), { animate: false });
                                    });
                                });

                                w.L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                                    attribution: '© OpenStreetMap contributors'
                                })
                                    .addTo($rootScope.areaMaps[j].map);
                                }
                            });
                        });
                    });
                });
		})
	;
})(window);


text:
import os
import sys
sys.path.append(os.getcwd())
sys.path.append(os.path.dirname(os.getcwd()))
os.environ['DJANGO_SETTINGS_MODULE']='opentrain.settings'
import analysis.models
import numpy as np
from scipy import spatial
try:
    import matplotlib.pyplot as plt
except ImportError:
    pass
import simplekml
import config
import itertools
import datetime

def enum(**enums):
    return type('Enum', (), enums)

def get_XY_pos(relativeNullPoint, p):
    """ Calculates X and Y distances in meters.
    """
    deltaLatitude = p.latitude - relativeNullPoint.latitude
    deltaLongitude = p.longitude - relativeNullPoint.longitude
    latitudeCircumference = 40075160 * cos(relativeNullPoint.latitude * pi / 180)
    resultX = deltaLongitude * latitudeCircumference / 360
    resultY = deltaLatitude * 40008000 / 360
    return resultX, resultY

def query_coords(point_tree, query_coords, query_accuracies):
    if isinstance( query_accuracies, ( int, long, float ) ):
        res = list(point_tree.query_ball_point(query_coords, query_accuracies))
    else:
        res = [point_tree.query_ball_point(query_coords[i], query_accuracies[i]) for i in xrange(len(query_accuracies))]
    return res

def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    return type('Enum', (), enums)

def is_strictly_increasing(L):
    return all(x<y for x, y in zip(L, L[1:]))

def is_increasing(L):
    return all(x<=y for x, y in zip(L, L[1:]))

def find_index_of_first_consecutive_value(values, start_index):
    res = None
    for i in reversed(range(start_index)):
        if values[i] != values[start_index]:
            res = i+1
            break
        elif i == 0:
            res = 0
            break

    return res

def get_report_counts_and_dates(do_print=False):
    result = []
    device_ids = analysis.models.Report.objects.values_list('device_id', flat=True).distinct()
    for device_id in device_ids:
        count = analysis.models.Report.objects.filter(device_id=device_id).count()
        report = analysis.models.Report.objects.filter(device_id=device_id).order_by('timestamp')[:1].get()
        result.append((report.timestamp.date(), count, device_id))
    result = sorted(result)
    if do_print:
        for x in result:
            print x
    return result

if __name__ == '__main__':
    pass
    get_report_counts_and_dates(True)


text:
<?php

namespace SilverStripe\Widgets\Model;

use SilverStripe\Admin\LeftAndMain;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Core\ClassInfo;

/**
 * Optional controller for every widget which has its own logic, e.g. in forms.
 *
 * It always handles a single widget, usually passed in as a database
 * identifier through the controller URL. Needs to be constructed as a nested
 * controller within a {@link ContentController}.
 *
 * ## Forms
 * You can add forms like in any other SilverStripe controller. If you need
 * access to the widget from within a form, you can use
 * `$this->controller->getWidget()` inside the form logic.
 *
 * Note: Widget controllers currently only work on {@link Page} objects,
 * because the logic is implemented in {@link ContentController->handleWidget()}.
 * Copy this logic and the URL rules to enable it for other controllers.
 *
 * @package widgets
 */
class WidgetController extends Controller
{
    /**
     * @var Widget
     */
    protected $widget;

    /**
     * @var array
     */
    private static $allowed_actions = array(
        'editablesegment'
    );

    /**
     * @param Widget $widget
     */
    public function __construct($widget = null)
    {
        if ($widget) {
            $this->widget = $widget;
            $this->failover = $widget;
        }

        parent::__construct();
    }

    /**
     * @param string $action
     * @return string
     */
    public function Link($action = null)
    {
        $id = ($this->widget) ? $this->widget->ID : null;
        $segment = Controller::join_links('widget', $id, $action);

        $page = Director::get_current_page();
        if ($page && !($page instanceof WidgetController)) {
            return $page->Link($segment);
        }

        if ($controller = $this->getParentController()) {
            return $controller->Link($segment);
        }

        return $segment;
    }

    /**
     * Cycles up the controller stack until it finds a non-widget controller
     * This is needed becauseController::currreturns the widget controller,
     * which means anyLinkfunction turns into endless loop.
     *
     * @return Controller
     */
    public function getParentController()
    {
        foreach (Controller::$controller_stack as $controller) {
            if (!($controller instanceof WidgetController)) {
                return $controller;
            }
        }
        return false;
    }

    /**
     * @return Widget
     */
    public function getWidget()
    {
        return $this->widget;
    }

    /**
     * Overloaded from {@link Widget->Content()} to allow for controller / form
     * linking.
     *
     * @return string HTML
     */
    public function Content()
    {
        return $this->renderWith(array_reverse(ClassInfo::ancestry(get_class($this->widget)) ?? []));
    }

    /**
     * Overloaded from {@link Widget->WidgetHolder()} to allow for controller/
     * form linking.
     *
     * @return string HTML
     */
    public function WidgetHolder()
    {
        return $this->renderWith("WidgetHolder");
    }

    /**
     * Uses the `WidgetEditor.ss` template and {@link Widget->editablesegment()}
     * to render a administrator-view of the widget. It is assumed that this
     * view contains form elements which are submitted and saved through
     * {@link WidgetAreaEditor} within the CMS interface.
     *
     * @return string HTML
     */
    public function editablesegment()
    {
        // use left and main to set the html config
        $leftandmain = LeftAndMain::create();
        $leftandmain->setRequest($this->getRequest());
        $leftandmain->doInit();

        // Decode if fully qualified - @see Widget::ClassName
        $className = str_replace('_', '\\', $this->urlParams['ID'] ?? '');
        if (class_exists($className ?? '') && is_subclass_of($className, Widget::class)) {
            $obj = new $className();
            return $obj->EditableSegment();
        } else {
            user_error("Bad widget class: $className", E_USER_WARNING);
            return "Bad widget class name given";
        }
    }
}


text:
package cobracmd

import (
	"fmt"

	"github.com/spf13/cobra"
)

var ServeCmd = &cobra.Command{
	Use:   "start <config>",
	Short: "`start` start registry service",
	Long:  "`serve` start registry services.",

	Run: func(cmd *cobra.Command, args []string) {
		fmt.Printf("running registry service\n")
	},
}


text:
package org.apache.hc.client5.http.impl.async;

import java.io.InterruptedIOException;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.hc.client5.http.HttpRoute;
import org.apache.hc.client5.http.async.AsyncExecRuntime;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.config.TlsConfig;
import org.apache.hc.client5.http.impl.ConnPoolSupport;
import org.apache.hc.client5.http.impl.Operations;
import org.apache.hc.client5.http.nio.AsyncClientConnectionManager;
import org.apache.hc.client5.http.nio.AsyncConnectionEndpoint;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.concurrent.CallbackContribution;
import org.apache.hc.core5.concurrent.Cancellable;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.nio.AsyncClientExchangeHandler;
import org.apache.hc.core5.http.nio.AsyncPushConsumer;
import org.apache.hc.core5.http.nio.HandlerFactory;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.reactor.ConnectionInitiator;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.slf4j.Logger;

class InternalHttpAsyncExecRuntime implements AsyncExecRuntime {

    private final Logger log;
    private final AsyncClientConnectionManager manager;
    private final ConnectionInitiator connectionInitiator;
    private final HandlerFactory<AsyncPushConsumer> pushHandlerFactory;
    /**
     * @deprecated TLS should be configured by the connection manager
     */
    @Deprecated
    private final TlsConfig tlsConfig;
    private final AtomicReference<AsyncConnectionEndpoint> endpointRef;
    private volatile boolean reusable;
    private volatile Object state;
    private volatile TimeValue validDuration;

    InternalHttpAsyncExecRuntime(
            final Logger log,
            final AsyncClientConnectionManager manager,
            final ConnectionInitiator connectionInitiator,
            final HandlerFactory<AsyncPushConsumer> pushHandlerFactory,
            final TlsConfig tlsConfig) {
        super();
        this.log = log;
        this.manager = manager;
        this.connectionInitiator = connectionInitiator;
        this.pushHandlerFactory = pushHandlerFactory;
        this.tlsConfig = tlsConfig;
        this.endpointRef = new AtomicReference<>();
        this.validDuration = TimeValue.NEG_ONE_MILLISECOND;
    }

    @Override
    public boolean isEndpointAcquired() {
        return endpointRef.get() != null;
    }

    @Override
    public Cancellable acquireEndpoint(
            final String id,
            final HttpRoute route,
            final Object object,
            final HttpClientContext context,
            final FutureCallback<AsyncExecRuntime> callback) {
        if (endpointRef.get() == null) {
            state = object;
            final RequestConfig requestConfig = context.getRequestConfig();
            final Timeout connectionRequestTimeout = requestConfig.getConnectionRequestTimeout();
            if (log.isDebugEnabled()) {
                log.debug("{} acquiring endpoint ({})", id, connectionRequestTimeout);
            }
            return Operations.cancellable(manager.lease(
                    id,
                    route,
                    object,
                    connectionRequestTimeout,
                    new FutureCallback<AsyncConnectionEndpoint>() {

                        @Override
                        public void completed(final AsyncConnectionEndpoint connectionEndpoint) {
                            endpointRef.set(connectionEndpoint);
                            reusable = connectionEndpoint.isConnected();
                            if (log.isDebugEnabled()) {
                                log.debug("{} acquired endpoint {}", id, ConnPoolSupport.getId(connectionEndpoint));
                            }
                            callback.completed(InternalHttpAsyncExecRuntime.this);
                        }

                        @Override
                        public void failed(final Exception ex) {
                            callback.failed(ex);
                        }

                        @Override
                        public void cancelled() {
                            callback.cancelled();
                        }
                    }));
        }
        callback.completed(this);
        return Operations.nonCancellable();
    }

    private void discardEndpoint(final AsyncConnectionEndpoint endpoint) {
        try {
            endpoint.close(CloseMode.IMMEDIATE);
            if (log.isDebugEnabled()) {
                log.debug("{} endpoint closed", ConnPoolSupport.getId(endpoint));
            }
        } finally {
            if (log.isDebugEnabled()) {
                log.debug("{} discarding endpoint", ConnPoolSupport.getId(endpoint));
            }
            manager.release(endpoint, null, TimeValue.ZERO_MILLISECONDS);
        }
    }

    @Override
    public void releaseEndpoint() {
        final AsyncConnectionEndpoint endpoint = endpointRef.getAndSet(null);
        if (endpoint != null) {
            if (reusable) {
                if (log.isDebugEnabled()) {
                    log.debug("{} releasing valid endpoint", ConnPoolSupport.getId(endpoint));
                }
                manager.release(endpoint, state, validDuration);
            } else {
                discardEndpoint(endpoint);
            }
        }
    }

    @Override
    public void discardEndpoint() {
        final AsyncConnectionEndpoint endpoint = endpointRef.getAndSet(null);
        if (endpoint != null) {
            discardEndpoint(endpoint);
        }
    }

    @Override
    public boolean validateConnection() {
        if (reusable) {
            final AsyncConnectionEndpoint endpoint = endpointRef.get();
            return endpoint != null && endpoint.isConnected();
        }
        final AsyncConnectionEndpoint endpoint = endpointRef.getAndSet(null);
        if (endpoint != null) {
            discardEndpoint(endpoint);
        }
        return false;
    }

    AsyncConnectionEndpoint ensureValid() {
        final AsyncConnectionEndpoint endpoint = endpointRef.get();
        if (endpoint == null) {
            throw new IllegalStateException("Endpoint not acquired / already released");
        }
        return endpoint;
    }

    @Override
    public boolean isEndpointConnected() {
        final AsyncConnectionEndpoint endpoint = endpointRef.get();
        return endpoint != null && endpoint.isConnected();
    }

    @Override
    public Cancellable connectEndpoint(
            final HttpClientContext context,
            final FutureCallback<AsyncExecRuntime> callback) {
        final AsyncConnectionEndpoint endpoint = ensureValid();
        if (endpoint.isConnected()) {
            callback.completed(this);
            return Operations.nonCancellable();
        }
        final RequestConfig requestConfig = context.getRequestConfig();
        @SuppressWarnings("deprecation")
        final Timeout connectTimeout = requestConfig.getConnectTimeout();
        if (log.isDebugEnabled()) {
            log.debug("{} connecting endpoint ({})", ConnPoolSupport.getId(endpoint), connectTimeout);
        }
        return Operations.cancellable(manager.connect(
                endpoint,
                connectionInitiator,
                connectTimeout,
                tlsConfig,
                context,
                new CallbackContribution<AsyncConnectionEndpoint>(callback) {

                    @Override
                    public void completed(final AsyncConnectionEndpoint endpoint) {
                        if (log.isDebugEnabled()) {
                            log.debug("{} endpoint connected", ConnPoolSupport.getId(endpoint));
                        }
                        if (callback != null) {
                            callback.completed(InternalHttpAsyncExecRuntime.this);
                        }
                    }

        }));

    }

    @Override
    public void upgradeTls(final HttpClientContext context) {
        upgradeTls(context, null);
    }

    @Override
    public void upgradeTls(final HttpClientContext context, final FutureCallback<AsyncExecRuntime> callback) {
        final AsyncConnectionEndpoint endpoint = ensureValid();
        if (log.isDebugEnabled()) {
            log.debug("{} upgrading endpoint", ConnPoolSupport.getId(endpoint));
        }
        manager.upgrade(endpoint, tlsConfig, context, new CallbackContribution<AsyncConnectionEndpoint>(callback) {

            @Override
            public void completed(final AsyncConnectionEndpoint endpoint) {
                if (callback != null) {
                    callback.completed(InternalHttpAsyncExecRuntime.this);
                }
            }

        });
    }

    @Override
    public Cancellable execute(
            final String id, final AsyncClientExchangeHandler exchangeHandler, final HttpClientContext context) {
        final AsyncConnectionEndpoint endpoint = ensureValid();
        if (endpoint.isConnected()) {
            if (log.isDebugEnabled()) {
                log.debug("{} start execution {}", ConnPoolSupport.getId(endpoint), id);
            }
            final RequestConfig requestConfig = context.getRequestConfig();
            final Timeout responseTimeout = requestConfig.getResponseTimeout();
            if (responseTimeout != null) {
                endpoint.setSocketTimeout(responseTimeout);
            }
            endpoint.execute(id, exchangeHandler, context);
            if (context.getRequestConfig().isHardCancellationEnabled()) {
                return () -> {
                    exchangeHandler.cancel();
                    return true;
                };
            }
        } else {
            connectEndpoint(context, new FutureCallback<AsyncExecRuntime>() {

                @Override
                public void completed(final AsyncExecRuntime runtime) {
                    if (log.isDebugEnabled()) {
                        log.debug("{} start execution {}", ConnPoolSupport.getId(endpoint), id);
                    }
                    try {
                        endpoint.execute(id, exchangeHandler, pushHandlerFactory, context);
                    } catch (final RuntimeException ex) {
                        failed(ex);
                    }
                }

                @Override
                public void failed(final Exception ex) {
                    exchangeHandler.failed(ex);
                }

                @Override
                public void cancelled() {
                    exchangeHandler.failed(new InterruptedIOException());
                }

            });
        }
        return Operations.nonCancellable();
    }

    @Override
    public void markConnectionReusable(final Object newState, final TimeValue newValidDuration) {
        reusable = true;
        state = newState;
        validDuration = newValidDuration;
    }

    @Override
    public void markConnectionNonReusable() {
        reusable = false;
        state = null;
        validDuration = null;
    }

    @Override
    public AsyncExecRuntime fork() {
        return new InternalHttpAsyncExecRuntime(log, manager, connectionInitiator, pushHandlerFactory, tlsConfig);
    }

}