text:
(function() {
  'use strict';
	var MessageCtrl = function($http, ngNotify, User, Message){
		var _this = this;
    _this.messages = [];
    _this.message = {};

    _this.sendMessage = function(){
      Message.sendMessage(_this.messageData).then(function(data){
        _this.results = data;
      });
    };

    _this.retriveMessages = function(){
      Message.retriveMessages().then(function(data){
        _this.messages = data;
        _this.messageCount = _this.messages.length;
      }, function(error){
        console.log(error);
        ngNotify.set(error.message, "error");
      });
    };

    _this.retriveMessage = function(messageId){
      Message.retriveMessage(messageId).then(function(data){
        _this.message = data;
      });
    };

    _this.deleteMessage = function(message){
      var index = _this.messages.indexOf(message);
      Message.deleteMessage(message._id).then(function(){
        _this.messages.splice(index, 1);
        ngNotify.set('Message deleted successfully ', 'error');
      });
    };
	};

	/* ==========================================================
		setup
	============================================================ */
	angular.module('obbp').controller('MessageCtrl',[
		'$http',
    'ngNotify',
    'User',
    'Message',
		MessageCtrl
	]);
})();


text:
{% extends "machina/board_base.html" %}
{% load i18n %}
{% load staticfiles %}

{% block css %}
  {{ block.super }}
  <link rel="stylesheet" type="text/css" href="{% static 'css/theme.css' %}" />
{% endblock css %}

{% block header_collapse %}
{{ block.super }}

  {% if request.user.is_authenticated %}

      {{ request.user.username }}

{{ request.user.username }}

{{ request.user.email }}

                {% trans "Profile" %}
                {% trans "Account" %}

                {% trans "Sign out" %}

  {% else %}

{% trans "Sign up" %}

{% trans "Sign in" %}

  {% endif %}

{% endblock header_collapse %}

{% block body %}

  {{ block.super }}

        {% trans "Powered by: "%}
        Django, django-machina

{% endblock body %}

redpajama_set_name: RedPajamaGithub


text:
using OpenRAVE;

namespace bodyfunctions
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			using(Context c = Context.Create(DebugLevel.Debug))
			{
				using(Environment e = c.CreateEnvironment())
				{
					e.Load("data/lab1.env.xml");
					e.SetViewer("qtcoin");

					bool pole2added = true;
					Body bodypole2 = e.GetBody("pole2");
					Body bodypole3 = e.GetBody("pole3");

					using(DisposableList<BodyLink> links = bodypole3.Links)
					{
						using(DisposableList<BodyGeometry> geometries = links[0].Geometries)
						{

							float[] pose = bodypole3.TransformF;
							ulong startsimtime = e.SimulationTime;;

							for(int i = 0; i < 10000; ++i) {
						        e.Lock();

								ulong newsimtime = e.SimulationTime;
								double deltatime = (newsimtime-startsimtime)*1e-6;
						        float fanim = (float)System.Math.IEEERemainder(deltatime,1.0);

								// animate around X axis
						        pose[4] = 1.0f + fanim;
								bodypole3.TransformF = pose;

						        // set the color
								geometries[0].SetDiffuseColor(1.0f, 0.0f, fanim);

						        if(fanim > 0.5 && pole2added)
								{
						            // remove the pole
									e.Remove(bodypole2);
						            pole2added = false;
						        }
						        else if(fanim < 0.5 && !pole2added)
								{
									e.Add(bodypole2);
						            pole2added = true;
						        }

						        // unlock
								e.Unlock();

						        // wait until sim time changes
						        while(newsimtime == e.SimulationTime)
						            System.Threading.Thread.Sleep(1);
						    }
						}
					}
				}
			}
		}
	}
}


text:
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <title>transform-style的使用</title>


text:
using Stratis.SmartContracts;

public class TransferFromConstructor : SmartContract
{
    public TransferFromConstructor(ISmartContractState smartContractState, Address address) : base(smartContractState)
    {
        Transfer(address, this.Balance/2);
    }
}


text:
#include <stdlib.h>
#include <stdio.h>
#include <phpcpp.h>

#include "Rsync.hpp"

extern "C" {
PHPCPP_EXPORT void *get_module() {
    static Php::Extension extension("librsync_php", "0.1");

    /**
     * rs_result rs_sig_file (FILE *old_file, FILE *sig_file, size_t block_len, size_t strong_len, rs_stats_t *)
     */
    extension.add("rs_sig_file", php_sig_file, {
            Php::ByVal("old_file", Php::Type::String),
            Php::ByVal("sig_file", Php::Type::String)
            /* FIXME
            Php::ByVal("block_len", Php::Type::Numeric),
            Php::ByVal("strong_len", Php::Type::Numeric)
            */
    });

    /**
     * rs_result rs_loadsig_file (FILE *sig_file, rs_signature_t **, rs_stats_t *)
     * rs_result rs_delta_file (rs_signature_t *, FILE *new_file, FILE *delta_file, rs_stats_t *)
     */
    extension.add("rs_delta_file", php_delta_file, {
            Php::ByVal("sig_file", Php::Type::String),
            Php::ByVal("new_file", Php::Type::String),
            Php::ByVal("delta_file", Php::Type::String)
    });

    /**
     * rs_result rs_patch_file (FILE *basis_file, FILE *delta_file, FILE *new_file, rs_stats_t *)
     */
    extension.add("rs_patch_file", php_patch_file, {
            Php::ByVal("basis_file", Php::Type::String),
            Php::ByVal("delta_file", Php::Type::String),
            Php::ByVal("new_file", Php::Type::String)
    });

    return extension;
}
}


text:
IPC_MESSAGE_CONTROL3(TestHandleWinMsg, int, IPC::HandleWin, int)
IPC_MESSAGE_CONTROL2(TestTwoHandleWinMsg, IPC::HandleWin, IPC::HandleWin)
#endif  // defined(OS_WIN)


text:
package org.openkilda.wfm.topology.switchmanager.error;

import org.openkilda.messaging.error.ErrorType;
import org.openkilda.model.SwitchId;

public class InconsistentDataException extends SwitchManagerException {
    public InconsistentDataException(String message) {
        super(ErrorType.UNPROCESSABLE_REQUEST, message);
    }

    public InconsistentDataException(SwitchId switchId, String details) {
        super(ErrorType.UNPROCESSABLE_REQUEST, makeMessage(switchId, details));
    }

    private static String makeMessage(SwitchId switchId, String details) {
        return String.format("Unable to complete switch verify/sync operation on %s - %s", switchId, details);
    }
}


text:
from bisect import bisect_left, bisect_right
from operator import itemgetter

class SortedCollection(object):
    '''Sequence sorted by a key function.

    SortedCollection() is much easier to work with than using bisect() directly.
    It supports key functions like those use in sorted(), min(), and max().
    The result of the key function call is saved so that keys can be searched
    efficiently.

    Instead of returning an insertion-point which can be hard to interpret, the
    five find-methods return a specific item in the sequence. They can scan for
    exact matches, the last item less-than-or-equal to a key, or the first item
    greater-than-or-equal to a key.

    Once found, an item's ordinal position can be located with the index() method.
    New items can be added with the insert() and insert_right() methods.
    Old items can be deleted with the remove() method.

    The usual sequence methods are provided to support indexing, slicing,
    length lookup, clearing, copying, forward and reverse iteration, contains
    checking, item counts, item removal, and a nice looking repr.

    Finding and indexing are O(log n) operations while iteration and insertion
    are O(n).  The initial sort is O(n log n).

    The key function is stored in the 'key' attibute for easy introspection or
    so that you can assign a new key function (triggering an automatic re-sort).

    In short, the class was designed to handle all of the common use cases for
    bisect but with a simpler API and support for key functions.

    >>> from pprint import pprint
    >>> from operator import itemgetter

    >>> s = SortedCollection(key=itemgetter(2))
    >>> for record in [
    ...         ('roger', 'young', 30),
    ...         ('angela', 'jones', 28),
    ...         ('bill', 'smith', 22),
    ...         ('david', 'thomas', 32)]:
    ...     s.insert(record)

    >>> pprint(list(s))         # show records sorted by age
    [('bill', 'smith', 22),
     ('angela', 'jones', 28),
     ('roger', 'young', 30),
     ('david', 'thomas', 32)]

    >>> s.find_le(29)           # find oldest person aged 29 or younger
    ('angela', 'jones', 28)
    >>> s.find_lt(28)           # find oldest person under 28
    ('bill', 'smith', 22)
    >>> s.find_gt(28)           # find youngest person over 28
    ('roger', 'young', 30)

    >>> r = s.find_ge(32)       # find youngest person aged 32 or older
    >>> s.index(r)              # get the index of their record
    3
    >>> s[3]                    # fetch the record at that index
    ('david', 'thomas', 32)

    >>> s.key = itemgetter(0)   # now sort by first name
    >>> pprint(list(s))
    [('angela', 'jones', 28),
     ('bill', 'smith', 22),
     ('david', 'thomas', 32),
     ('roger', 'young', 30)]

    '''

    def __init__(self, iterable=(), key=None):
        self._given_key = key
        key = (lambda x: x) if key is None else key
        decorated = sorted((key(item), item) for item in iterable)
        self._keys = [k for k, item in decorated]
        self._items = [item for k, item in decorated]
        self._key = key

    def _getkey(self):
        return self._key

    def _setkey(self, key):
        if key is not self._key:
            self.__init__(self._items, key=key)

    def _delkey(self):
        self._setkey(None)

    key = property(_getkey, _setkey, _delkey, 'key function')

    def clear(self):
        self.__init__([], self._key)

    def copy(self):
        return self.__class__(self, self._key)

    def __len__(self):
        return len(self._items)

    def __getitem__(self, i):
        return self._items[i]

    def __iter__(self):
        return iter(self._items)

    def __reversed__(self):
        return reversed(self._items)

    def __repr__(self):
        return '%s(%r, key=%s)' % (
            self.__class__.__name__,
            self._items,
            getattr(self._given_key, '__name__', repr(self._given_key))
        )

    def __reduce__(self):
        return self.__class__, (self._items, self._given_key)

    def __contains__(self, item):
        k = self._key(item)
        i = bisect_left(self._keys, k)
        j = bisect_right(self._keys, k)
        return item in self._items[i:j]

    def index(self, item):
        'Find the position of an item.  Raise ValueError if not found.'
        k = self._key(item)
        i = bisect_left(self._keys, k)
        j = bisect_right(self._keys, k)
        return self._items[i:j].index(item) + i

    def count(self, item):
        'Return number of occurrences of item'
        k = self._key(item)
        i = bisect_left(self._keys, k)
        j = bisect_right(self._keys, k)
        return self._items[i:j].count(item)

    def insert(self, item):
        'Insert a new item.  If equal keys are found, add to the left'
        k = self._key(item)
        i = bisect_left(self._keys, k)
        self._keys.insert(i, k)
        self._items.insert(i, item)

    def insert_right(self, item):
        'Insert a new item.  If equal keys are found, add to the right'
        k = self._key(item)
        i = bisect_right(self._keys, k)
        self._keys.insert(i, k)
        self._items.insert(i, item)

    def remove(self, item):
        'Remove first occurence of item.  Raise ValueError if not found'
        i = self.index(item)
        del self._keys[i]
        del self._items[i]

    def find(self, k):
        'Return first item with a key == k.  Raise ValueError if not found.'
        i = bisect_left(self._keys, k)
        if i != len(self) and self._keys[i] == k:
            return self._items[i]
        raise ValueError('No item found with key equal to: %r' % (k,))

    def find_le(self, k):
        'Return last item with a key <= k.  Raise ValueError if not found.'
        i = bisect_right(self._keys, k)
        if i:
            return self._items[i-1]
        raise ValueError('No item found with key at or below: %r' % (k,))

    def find_lt(self, k):
        'Return last item with a key < k.  Raise ValueError if not found.'
        i = bisect_left(self._keys, k)
        if i:
            return self._items[i-1]
        raise ValueError('No item found with key below: %r' % (k,))

    def find_ge(self, k):
        'Return first item with a key >= equal to k.  Raise ValueError if not found'
        i = bisect_left(self._keys, k)
        if i != len(self):
            return self._items[i]
        raise ValueError('No item found with key at or above: %r' % (k,))

    def find_gt(self, k):
        'Return first item with a key > k.  Raise ValueError if not found'
        i = bisect_right(self._keys, k)
        if i != len(self):
            return self._items[i]
        raise ValueError('No item found with key above: %r' % (k,))


text:
#import "PHSensorState.h"

@interface PHHumiditySensorState : PHSensorState

/**
 Current humidity in 0.01% steps (e.g. 2000 is 20%)
 Only readwrite for CLIP sensor
 */
@property (nonatomic, strong) NSNumber *humidity;

@end


text:
import { Injectable } from '@angular/core';
import {
    CanActivate,
    Router,
    ActivatedRouteSnapshot,
    RouterStateSnapshot,
    CanActivateChild,
} from '@angular/router';
import { AppConfigService } from '../../services/app-config.service';
import { Observable } from 'rxjs';
import { CommonRoutes } from '../entities/shared.const';

@Injectable({
    providedIn: 'root',
})
export class ModeGuard implements CanActivate, CanActivateChild {
    constructor(
        private router: Router,
        private appConfigService: AppConfigService
    ) {}

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
    ): Observable<boolean> | boolean {
        // Show the right sign-in page for different modes
        return new Observable(observer => {
            if (this.appConfigService.isIntegrationMode()) {
                if (state.url.startsWith(CommonRoutes.SIGN_IN)) {
                    this.router.navigate(
                        [CommonRoutes.EMBEDDED_SIGN_IN],
                        route.queryParams
                    );
                    observer.next(false);
                } else {
                    observer.next(true);
                }
            } else {
                if (state.url.startsWith(CommonRoutes.EMBEDDED_SIGN_IN)) {
                    this.router.navigate(
                        [CommonRoutes.SIGN_IN],
                        route.queryParams
                    );
                    observer.next(false);
                } else {
                    observer.next(true);
                }
            }
        });
    }

    canActivateChild(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
    ): Observable<boolean> | boolean {
        return this.canActivate(route, state);
    }
}


text:
package ini

import "fmt"

type synthaxError struct {
	LineNumber int
	Message    string
}

func (err synthaxError) Error() string {
	return fmt.Sprintf("ini: synthax error on line %d: %s",
		err.LineNumber, err.Message)
}

type overflowError struct {
	Value string
	Type  string
}

func (err overflowError) Error() string {
	return fmt.Sprintf("ini: can't convert '%s' to type %s, it overflows the type",
		err.Value, err.Type)
}

type covertionError struct {
	Value string
	Type  string
}

func (err covertionError) Error() string {
	return fmt.Sprintf("ini: can't convert '%s' to type %s", err.Value, err.Type)
}

func createSynthaxError(lineNumber int, msg string) error {
	return synthaxError{
		LineNumber: lineNumber,
		Message:    msg,
	}
}

func createOverflowError(value, t string) error {
	return overflowError{
		Value: value,
		Type:  t,
	}
}

func createCovertionError(value, t string) error {
	return covertionError{
		Value: value,
		Type:  t,
	}
}

// IsSynthaxError checks if an error is a synthax error.
func IsSynthaxError(err error) bool {
	_, ok := err.(synthaxError)
	return ok
}

// IsOverflowError checks if an error is an overflow error.
func IsOverflowError(err error) bool {
	_, ok := err.(overflowError)
	return ok
}

// IsCovertionError checks if an error is a covertion error.
func IsCovertionError(err error) bool {
	_, ok := err.(covertionError)
	return ok
}


text:
package com.dremio.exec.physical.config;

import java.util.Iterator;
import java.util.List;

import org.apache.calcite.rel.core.JoinRelType;

import com.dremio.common.logical.data.JoinCondition;
import com.dremio.exec.physical.base.AbstractBase;
import com.dremio.exec.physical.base.OpProps;
import com.dremio.exec.physical.base.PhysicalOperator;
import com.dremio.exec.physical.base.PhysicalVisitor;
import com.dremio.exec.proto.UserBitShared.CoreOperatorType;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterators;

@JsonTypeName("merge-join")
public class MergeJoinPOP extends AbstractBase{

  private final PhysicalOperator left;
  private final PhysicalOperator right;
  private final List<JoinCondition> conditions;
  private final JoinRelType joinType;

  @JsonCreator
  public MergeJoinPOP(
      @JsonProperty("props") OpProps props,
      @JsonProperty("left") PhysicalOperator left,
      @JsonProperty("right") PhysicalOperator right,
      @JsonProperty("conditions") List<JoinCondition> conditions,
      @JsonProperty("joinType") JoinRelType joinType
      ) {
    super(props);
    this.left = left;
    this.right = right;
    this.conditions = conditions;
    Preconditions.checkArgument(joinType != null, "Join type is missing!");
    this.joinType = joinType;
  }

  @Override
  public <T, X, E extends Throwable> T accept(PhysicalVisitor<T, X, E> physicalVisitor, X value) throws E {
    return physicalVisitor.visitMergeJoin(this, value);
  }

  @Override
  public PhysicalOperator getNewWithChildren(List<PhysicalOperator> children) {
    Preconditions.checkArgument(children.size() == 2);
    return new MergeJoinPOP(props, children.get(0), children.get(1), conditions, joinType);
  }

  @Override
  public Iterator<PhysicalOperator> iterator() {
    return Iterators.forArray(left, right);
  }

  public PhysicalOperator getLeft() {
    return left;
  }

  public PhysicalOperator getRight() {
    return right;
  }

  public JoinRelType getJoinType() {
    return joinType;
  }

  public List<JoinCondition> getConditions() {
    return conditions;
  }

  @Override
  public int getOperatorType() {
    return CoreOperatorType.MERGE_JOIN_VALUE;
  }
}


text:
class CreateManifestations < ActiveRecord::Migration[5.2]
  def change
    create_table :manifestations do |t|
      t.text :original_title, null: false
      t.text :title_alternative
      t.text :title_transcription
      t.string :classification_number
      t.string :manifestation_identifier
      t.datetime :date_of_publication
      t.datetime :copyright_date
      t.timestamps
      t.string :access_address
      t.integer :language_id, default: 1, null: false
      t.integer :carrier_type_id, default: 1, null: false
      t.integer :start_page
      t.integer :end_page
      t.integer :height
      t.integer :width
      t.integer :depth
      t.integer :price # TODO: 通貨単位
      t.text :fulltext
      t.string :volume_number_string
      t.string :issue_number_string
      t.string :serial_number_string
      t.integer :edition
      t.text :note
      t.boolean :repository_content, default: false, null: false
      t.integer :lock_version, default: 0, null: false
      t.integer :required_role_id, default: 1, null: false
      t.integer :required_score, default: 0, null: false
      t.integer :frequency_id, default: 1, null: false
      t.boolean :subscription_master, default: false, null: false
    end
    #add_index :manifestations, :carrier_type_id
    #add_index :manifestations, :required_role_id
    add_index :manifestations, :access_address
    #add_index :manifestations, :frequency_id
    add_index :manifestations, :manifestation_identifier
    add_index :manifestations, :updated_at
    add_index :manifestations, :date_of_publication
  end
end


text:
Joyride is built on top of appium to run the tests. Thus based from appium's requirements, you will need the following:

#### iOS Requirements

Mac OS X 10.7 or higher, 10.9.2 recommended
XCode >= 4.6.3, 5.1.1 recommended
Apple Developer Tools (iPhone simulator SDK, command line tools)

#### Android Requirements

Android SDK API >= 17 (Additional features require 18/19)
Appium supports Android on OS X, Linux and Windows. Make sure you follow the directions for setting up your environment properly for testing on different OSes: linux, osx, windows

Follow appium's install guide for your environment.  Appium install also includes Node.js.  You can install the appium server as either the GUI version or the standalone command-line version.

A running instance of the appium server is required to run the tests.

#### Other Tools

Install the [Specflow extension](https://visualstudiogallery.msdn.microsoft.com/9915524d-7fb0-43c3-bb3c-a8a14fbd40ee) for Visual Studio

Joyride uses NUnit for the testing framework.  The [NUnit Test Runner](http://nunit.org/index.php?p=vsTestAdapter&r=2.6.4).  Or if you use Resharper, this makes it easy.

Your target mobile app.

A real device.  If available, we prefer testing a real device over emulator or simulator.  If you are using a device, ensure your device is setup properly for your environment.

##### Android Devices
* Ensure you are able to see the device using 'adb devices' on android.
* You have the developer options enabled.
* Disabling the lock screen
* Bumping Display setting such as the idle time before the phone sleeps to 30 minutes

##### iOS Devices
* Enabled UI Automation.  Settings -> Developer -> Enable UI Automation
* Have brew installed and install Webkit Debug Proxy for hybrid apps (brew install ios_webkit_debug_proxy)
* Turn on web inspector on Safari. Settings -> Safari -> Advanced -> Web Inspector ON

## Creating your first project

1. Launch Visual Studio and create new solution.
2. Create a test project
3. Install Joyride.Starter using Nuget
4. From here, Joyride.Starter will install the other dependencies which include NUnit, Specflow, Joyride, Joyride.Specflow etc.
5. Joyride adds several directories: Logs, Screenshots, Steps, and Specs.  The "Logs" and "Screenshots" folder store tracing dom data and screenshots respectively.  The "Steps" folder should include your custom "step" binding code for your specs.  The "Specs" folder contains all your .feature files.  After the install, you should see these key files:  *App.config*, *Steps\SpecflowHooks.cs* and a template *Specs\FirstSpec.feature* file.
6. Modify the *App.config* with the appropriate settings under the *joyride* section. The template provides the following:
  ```xml
    <joyride>
        <log>
          <add name="relativeLogPath" value="\..\..\Logs\" />
          <add name="relativeScreenshotPath" value="\..\..\Screenshots\" />
       </log>
       <capabilities>
          <add name="autoLaunch" value="false" type="System.Boolean" />
          <add name="fullReset" value="false" type="System.Boolean" />
          <android>
            <add name="platformName" value="Android" />
            <add name="appPackage" value="com.my.test.app" />
            <add name="appActivity" value="activity-change-or-delete-me" />

          <devices>
              <device name="nexus5">
              <add name="deviceName" value="device-id-replace-me" />
              </device>

            <device name="nexus5_emulator">
               <add name="appActivity" value="change-or-delete-me" />
               <add name="appWaitActivity" value="change-or-delete-me" />
            </device>
          </devices>
        </android>

         <ios>
           <add name="platformName" value="iOS" />
            <add name="bundleId" value="com.my.test.app" />
            <add name="sendKeyStrategy" value="setValue" />

           <devices>
              <device name="iphone5s_4">
                <add name="deviceName" value="iPhone" />
                <add name="platformVersion" value="8.3" />
                <add name="udid" value="udid-replace-me" />
              </device>
            </devices>
         </ios>
       </capabilities>
       <servers>
         <add name="dev" value="http://127.0.0.1:4723/wd/hub" />
         <add name="ci" value="http://127.0.0.1:4723/wd/hub" />
        </servers>
       <run>
         <add name="server" value="dev" />        <!-- change me to one of your available servers -->
         <add name="platform" value="android" />  <!-- either 'android' or 'ios' -->
         <add name="device" value="nexus5" />     <!-- change to target device's name -->
       </run>
    </joyride>
   ```
   The *log* section sets relative paths to the working directory of your binary.  By default, the folders "Log" and "Screenshots" are saved in the same directory as your project directory.

   All the settings under *capabilities* map directly to [Appiums Capabilities](http://appium.io/slate/en/master/?csharp#appium-server-capabilities).  The settings are bundled together using [HandyConfig](https://www.nuget.org/packages/HandyConfig/).

   The *capabilities* section includes global capabilities.  Joyride prefers to launch the app manually by setting *autoLaunch* to false.  Note the *type="System.Boolean"*.  You have to supply the correct type for the capabilities.  For example, you want the *newCommandTimeout* capability with a value of "70", also include *type="System.Int32"*.  If the *type* is not specified, the *"System.String"* is used as the default.

   The *android* and *ios* includes their respective platform capabilities. You can safely remove the section for the unused platform.  Update your app identifier with the appropriate *bundleId* for *ios* or *appPackage* for *android*.

   Similarly, create a *device* target with device specfic capabilities.  If the same capabilitiy is specified here, it will supersede the capability setting before it.  Note the *name* of the device.

   Review the *servers* and *run* section.  The above settings runs on *dev* for localhost, for *platform* using *android* on a *device* target of *nexus5*.  Change your run values accordingly.  For example, on ios, you will be running on remote appium server with a mac, the *platform* of *ios* and your desired device.

7. Define a new app.  In *Steps\SpecflowHooks.cs*, the new app will be used to set Context.MobileApp as below.
   ```csharp
   [BeforeScenario]
   public void BeforeScenario()
   {
        Context.Driver = RemoteMobileDriver.GetInstance();
        // Add your test app here
        // Context.MobileApp = new TestApp();
        Context.MobileApp = new MyCoolApp();
   }

   ```
   If you are creating an app you want to eventually share code, it is best to create a separate project for this.  Create a  new project in VS and add a new class.  Subclass the appropriate platform for your app.  Use *AndroidMobileApplication* or *IosMobileApplication*.

   ```csharp
    public class MyCoolApp : AndroidMobileApplication
    {
        public override string Identifier { get { return "com.my.cool.app"; }}
    }
   ```

   Update SpecflowHooks with the appropriate new app.

8. The first spec is created for you under *Specs\FirstSpec.feature*.  Add the appropriate tag, either *@android* or *@ios*.
   ```gherkin
   # Comment out and add the appropriate tag for your platform
   # @android or @ios

   Feature: My First Feature
	In order to do usercase on my app
	As a user
	I want to be do X

   Scenario: Launch my cool App
   Given I launch the "My Cool App" mobile application
   And I wait for "2" seconds
   And I take a screenshot

   ```
   This first spec will simply launch your app and take a screen shot.
9.  Build your project and run your first test.
10.  If all goes well, you have just ran your first test!


text:
Additional header content

Gets or sets the collection of user-defined styles.

**Namespace:** iTin.Export.Model
**Assembly:** iTin.Export.Core (in iTin.Export.Core.dll) Version: 2.0.0.0 (2.0.0.0)

## Syntax

**C#**

``` C#
public ImagesModel Images { get; set; }
```

**VB**

``` VB
Public Property Images As ImagesModel
	Get
	Set
```

#### Property Value
Type: ImagesModel
Collection of user-defined styles. Each element defines type of content, such as the background color, the alignment type, the data type and the font type.

## Remarks

**ITEE Object Element Usage**

``` XML
<Global.Resources>
  <Images .../>
  ...
</Global.Resources>
```

Compatibility table with native writers.

Comma-Separated Values
CsvWriter	Tab-Separated Values
TsvWriter	SQL Script
SqlScriptWriter	XML Spreadsheet 2003
Spreadsheet2003TabularWriter

X	X	X	X

 A `X` value indicates that the writer supports this element.

## See Also

#### Reference
GlobalResourcesModel Class
iTin.Export.Model Namespace


text:
package org.wso2.carbon.apimgt.impl.issuers;

import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import org.apache.axis2.util.JavaUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opensaml.saml.saml2.core.Assertion;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.impl.utils.SystemScopeUtils;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils;
import org.wso2.carbon.identity.application.common.model.*;
import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants;
import org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil;
import org.wso2.carbon.identity.base.IdentityConstants;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.oauth.OAuthUtil;
import org.wso2.carbon.identity.oauth.cache.CacheEntry;
import org.wso2.carbon.identity.oauth.cache.OAuthCache;
import org.wso2.carbon.identity.oauth.cache.OAuthCacheKey;
import org.wso2.carbon.identity.oauth.callback.OAuthCallback;
import org.wso2.carbon.identity.oauth.common.GrantType;
import org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException;
import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext;
import org.wso2.carbon.identity.oauth2.dao.OAuthTokenPersistenceFactory;
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO;
import org.wso2.carbon.identity.oauth2.model.AccessTokenDO;
import org.wso2.carbon.identity.oauth2.model.RequestParameter;
import org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry;
import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext;
import org.wso2.carbon.identity.oauth2.validators.OAuth2TokenValidationMessageContext;
import org.wso2.carbon.identity.oauth2.validators.scope.ScopeValidator;
import org.wso2.carbon.idp.mgt.IdentityProviderManagementException;
import org.wso2.carbon.idp.mgt.IdentityProviderManager;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.util.UserCoreUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;

import java.text.ParseException;
import java.util.*;

import static org.wso2.carbon.identity.oauth2.util.OAuth2Util.getAppInformationByClientId;
import static org.wso2.carbon.registry.core.jdbc.DumpConstants.RESOURCE;

/**
 * This class implements Scope Validator which represents the functions related to an scope issuer which
 * issues scopes based on requested system scopes.
 */
public class SystemScopesIssuer implements ScopeValidator {

    private static Log log = LogFactory.getLog(SystemScopesIssuer.class);
    private static final String DEFAULT_SCOPE_NAME = "default";
    private static final String PRESERVED_CASE_SENSITIVE_VARIABLE = "preservedCaseSensitive";
    private static final String ACCESS_TOKEN_DO = "AccessTokenDO";
    // The following constants are as same as the constants defined in
    // org.wso2.carbon.apimgt.keymgt.handlers.ResourceConstants.
    // If any changes are taking place in that these should also be updated accordingly.
    // Setting the "retrieveRolesFromUserStoreForScopeValidation" as a System property which is used when
    // skipping the scope role validation during token issuing using JWT bearer grant.
    public static final String CHECK_ROLES_FROM_SAML_ASSERTION = "checkRolesFromSamlAssertion";
    public static final String RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION =
            "retrieveRolesFromUserStoreForScopeValidation";
    private static final String SCOPE_VALIDATOR_NAME = "System scope validator";
    private IdentityProvider identityProvider = null;
    // set role based scopes issuer as the default
    private static final String ISSUER_PREFIX = "default";

    @Override
    public boolean validateScope(OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext) throws
            IdentityOAuth2Exception {

        List<String> authScopes = getScopes(oAuthAuthzReqMessageContext);
        oAuthAuthzReqMessageContext.setApprovedScope(authScopes.toArray(new String[authScopes.size()]));
        return true;
    }

    @Override
    public boolean validateScope(OAuthTokenReqMessageContext oAuthTokenReqMessageContext) throws
            IdentityOAuth2Exception {

        List<String> authScopes = getScopes(oAuthTokenReqMessageContext);
        oAuthTokenReqMessageContext.setScope(authScopes.toArray(new String[authScopes.size()]));
        return true;
    }

    @Override
    public boolean validateScope(OAuth2TokenValidationMessageContext oAuth2TokenValidationMessageContext) throws
            IdentityOAuth2Exception {

        AccessTokenDO accessTokenDO = (AccessTokenDO) oAuth2TokenValidationMessageContext.getProperty(ACCESS_TOKEN_DO);
        if (accessTokenDO == null) {
            return false;
        }
        String resource = getResourceFromMessageContext(oAuth2TokenValidationMessageContext);
        // Return true if there is no resource to validate the token against.
        if (resource == null) {
            return true;
        }
        //Get the list of scopes associated with the access token
        String[] scopes = accessTokenDO.getScope();

        //If no scopes are associated with the token
        if (scopes == null || scopes.length == 0) {
            return true;
        }

        String resourceScope = null;
        int resourceTenantId = -1;

        boolean cacheHit = false;
        // Check the cache, if caching is enabled.
        OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
        CacheEntry result = OAuthCache.getInstance().getValueFromCache(cacheKey);

        //Cache hit
        if (result != null && result instanceof ResourceScopeCacheEntry) {
            resourceScope = ((ResourceScopeCacheEntry) result).getScope();
            resourceTenantId = ((ResourceScopeCacheEntry) result).getTenantId();
            cacheHit = true;
        }

        // Cache was not hit. So retrieve from database.
        if (!cacheHit) {
            Pair<String, Integer> scopeMap = OAuthTokenPersistenceFactory.getInstance()
                    .getTokenManagementDAO().findTenantAndScopeOfResource(resource);

            if (scopeMap != null) {
                resourceScope = scopeMap.getLeft();
                resourceTenantId = scopeMap.getRight();
            }

            cacheKey = new OAuthCacheKey(resource);
            ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope);
            cacheEntry.setTenantId(resourceTenantId);
            //Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for
            //which scopes haven't been defined).
            OAuthCache.getInstance().addToCache(cacheKey, cacheEntry);
        }

        //Return TRUE if - There does not exist a scope definition for the resource
        if (resourceScope == null) {
            if (log.isDebugEnabled()) {
                log.debug("Resource '" + resource + "' is not protected with a scope");
            }
            return true;
        }

        List<String> scopeList = new ArrayList<>(Arrays.asList(scopes));

        // If the access token does not bear the scope required for accessing the Resource.
        if (!scopeList.contains(resourceScope)) {
            if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
                log.debug("Access token '" + accessTokenDO.getAccessToken() + "' does not bear the scope '" +
                        resourceScope + "'");
            }
            return false;
        }

        // If a federated user and CHECK_ROLES_FROM_SAML_ASSERTION system property is set to true,
        // or if a federated user and RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION system property is false,
        // avoid validating user roles.
        // This system property is set at server start using -D option, Thus will be a permanent property.
        if (accessTokenDO.getAuthzUser().isFederatedUser()
                && (Boolean.parseBoolean(System.getProperty(CHECK_ROLES_FROM_SAML_ASSERTION)) ||
                !(Boolean.parseBoolean(System.getProperty(RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION))))) {
            return true;
        }

        AuthenticatedUser authenticatedUser = OAuthUtil
                .getAuthenticatedUser(oAuth2TokenValidationMessageContext.getResponseDTO().getAuthorizedUser());
        String clientId = accessTokenDO.getConsumerKey();
        List<String> requestedScopes = Arrays.asList(scopes);
        List<String> authorizedScopes = null;

        String[] userRoles = null;
        Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
        if (appScopes != null) {
            //If no scopes can be found in the context of the application
            if (isAppScopesEmpty(appScopes, clientId)) {
                authorizedScopes = getAllowedScopes(requestedScopes);
                oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(
                        new String[authorizedScopes.size()]));
                return true;
            }
            userRoles = getUserRoles(authenticatedUser);
            authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
            oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(
                    new String[authorizedScopes.size()]));
        }
        if (ArrayUtils.isEmpty(userRoles)) {
            if (log.isDebugEnabled()) {
                log.debug("No roles associated for the user " + authenticatedUser.getUserName());
            }
            return false;
        }
        return true;
    }

    @Override
    public String getName() {

        return SCOPE_VALIDATOR_NAME;
    }

    public String getPrefix() {

        return ISSUER_PREFIX;
    }

    /**
     * Extract the resource from the access token validation request message
     *
     * @param messageContext Message context of the token validation request
     * @return resource
     */
    private String getResourceFromMessageContext(OAuth2TokenValidationMessageContext messageContext) {

        String resource = null;
        if (messageContext.getRequestDTO().getContext() != null) {
            // Iterate the array of context params to find the 'resource' context param.
            for (OAuth2TokenValidationRequestDTO.TokenValidationContextParam resourceParam :
                    messageContext.getRequestDTO().getContext()) {
                // If the context param is the resource that is being accessed
                if (resourceParam != null && RESOURCE.equals(resourceParam.getKey())) {
                    resource = resourceParam.getValue();
                    break;
                }
            }
        }
        return resource;
    }

    public List<String> getScopes(OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext) {

        List<String> authorizedScopes = null;
        List<String> requestedScopes = new ArrayList<>();
        if (oAuthAuthzReqMessageContext.getApprovedScope() != null) {
            requestedScopes = Arrays.asList(oAuthAuthzReqMessageContext.getApprovedScope());
        }
        String clientId = oAuthAuthzReqMessageContext.getAuthorizationReqDTO().getConsumerKey();
        AuthenticatedUser authenticatedUser = oAuthAuthzReqMessageContext.getAuthorizationReqDTO().getUser();

        Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
        if (appScopes != null) {
            //If no scopes can be found in the context of the application
            if (isAppScopesEmpty(appScopes, clientId)) {
                return getAllowedScopes(requestedScopes);
            }
            String[] userRoles = getUserRoles(authenticatedUser);
            authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
        }
        return authorizedScopes;
    }

    /**
     * This method is used to retrieve authorized scopes with respect to an authorization callback.
     *
     * @param scopeValidationCallback Authorization callback to validate scopes
     * @return authorized scopes list
     */
    public List<String> getScopes(OAuthCallback scopeValidationCallback) {

        List<String> authorizedScopes = null;
        List<String> requestedScopes = Arrays.asList(scopeValidationCallback.getRequestedScope());
        String clientId = scopeValidationCallback.getClient();
        AuthenticatedUser authenticatedUser = scopeValidationCallback.getResourceOwner();

        Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
        if (appScopes != null) {
            //If no scopes can be found in the context of the application
            if (isAppScopesEmpty(appScopes, clientId)) {
                return getAllowedScopes(requestedScopes);
            }
            String[] userRoles = getUserRoles(authenticatedUser);
            authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
        }
        return authorizedScopes;
    }

    /**
     * This method is used to retrieve the authorized scopes with respect to a token.
     *
     * @param tokReqMsgCtx token message context
     * @return authorized scopes list
     */
    public List<String> getScopes(OAuthTokenReqMessageContext tokReqMsgCtx) {

        List<String> authorizedScopes = null;
        List<String> requestedScopes = new ArrayList<>(Arrays.asList(tokReqMsgCtx.getScope()));
        String clientId = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
        AuthenticatedUser authenticatedUser = tokReqMsgCtx.getAuthorizedUser();
        Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
        if (appScopes != null) {
            //If no scopes can be found in the context of the application
            if (isAppScopesEmpty(appScopes, clientId)) {
                return getAllowedScopes(requestedScopes);
            }

            String grantType = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType();
            String[] userRoles = null;

            // If GrantType is SAML20_BEARER and CHECK_ROLES_FROM_SAML_ASSERTION is true, or if GrantType is
            // JWT_BEARER and retrieveRolesFromUserStoreForScopeValidation system property is true,
            // use user roles from assertion or jwt otherwise use roles from userstore.
            String isSAML2Enabled = System.getProperty(APIConstants.SystemScopeConstants.CHECK_ROLES_FROM_SAML_ASSERTION);
            String isRetrieveRolesFromUserStoreForScopeValidation = System
                    .getProperty(APIConstants.SystemScopeConstants.RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION);
            if (GrantType.SAML20_BEARER.toString().equals(grantType) && Boolean.parseBoolean(isSAML2Enabled)) {
                authenticatedUser.setUserStoreDomain("FEDERATED");
                tokReqMsgCtx.setAuthorizedUser(authenticatedUser);
                Assertion assertion = (Assertion) tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.SAML2_ASSERTION);
                userRoles = getRolesFromAssertion(assertion);
            } else if (APIConstants.SystemScopeConstants.OAUTH_JWT_BEARER_GRANT_TYPE.equals(grantType) && !(Boolean
                    .parseBoolean(isRetrieveRolesFromUserStoreForScopeValidation))) {
                configureForJWTGrant(tokReqMsgCtx);
                Map<ClaimMapping, String> userAttributes = authenticatedUser.getUserAttributes();
                if (tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM) != null) {
                    userRoles = getRolesFromUserAttribute(userAttributes,
                            tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM).toString());
                }
            } else {
                userRoles = getUserRoles(authenticatedUser);
            }
            authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
        }
        return authorizedScopes;
    }

    /**
     * This method is used to get roles list of the user.
     *
     * @param authenticatedUser Authenticated user
     * @return roles list
     */
    private String[] getUserRoles(AuthenticatedUser authenticatedUser) {

        String[] userRoles = null;
        String tenantDomain;
        String username;
        if (authenticatedUser.isFederatedUser()) {
            tenantDomain = MultitenantUtils.getTenantDomain(authenticatedUser.getAuthenticatedSubjectIdentifier());
            username = MultitenantUtils.getTenantAwareUsername(authenticatedUser.getAuthenticatedSubjectIdentifier());
        } else {
            tenantDomain = authenticatedUser.getTenantDomain();
            username = authenticatedUser.getUserName();
        }
        String userStoreDomain = authenticatedUser.getUserStoreDomain();
        RealmService realmService = getRealmService();
        try {
            int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
            // If tenant Id is not set in the tokenReqContext, deriving it from username.
            if (tenantId == 0 || tenantId == -1) {
                tenantId = getTenantIdOfUser(username);
            }
            UserStoreManager userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
            String endUsernameWithDomain = addDomainToName(username, userStoreDomain);
            userRoles = userStoreManager.getRoleListOfUser(endUsernameWithDomain);

        } catch (UserStoreException e) {
            //Log and return since we do not want to stop issuing the token in case of scope validation failures.
            log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e);
        }
        return userRoles;
    }

    /**
     * This method is used to get authorized scopes for user from the requested scopes based on roles.
     *
     * @param userRoles       Roles list of user
     * @param requestedScopes Requested scopes
     * @param appScopes       Scopes of the Application
     * @return authorized scopes list
     */
    private List<String> getAuthorizedScopes(String[] userRoles, List<String> requestedScopes,
                                             Map<String, String> appScopes) {

        List<String> defaultScope = new ArrayList<>();
        defaultScope.add(DEFAULT_SCOPE_NAME);

        if (userRoles == null || userRoles.length == 0) {
            userRoles = new String[0];
        }

        List<String> authorizedScopes = new ArrayList<>();
        String preservedCaseSensitiveValue = System.getProperty(PRESERVED_CASE_SENSITIVE_VARIABLE);
        boolean preservedCaseSensitive = JavaUtils.isTrueExplicitly(preservedCaseSensitiveValue);
        List<String> userRoleList;
        if (preservedCaseSensitive) {
            userRoleList = Arrays.asList(userRoles);
        } else {
            userRoleList = new ArrayList<>();
            for (String aRole : userRoles) {
                userRoleList.add(aRole.toLowerCase(Locale.ENGLISH));
            }
        }

        //Iterate the requested scopes list.
        for (String scope : requestedScopes) {
            //Get the set of roles associated with the requested scope.
            String roles = appScopes.get(scope);
            //If the scope has been defined in the context of the App and if roles have been defined for the scope
            if (roles != null && roles.length() != 0) {
                List<String> roleList = new ArrayList<>();
                for (String aRole : roles.split(",")) {
                    if (preservedCaseSensitive) {
                        roleList.add(aRole.trim());
                    } else {
                        roleList.add(aRole.trim().toLowerCase(Locale.ENGLISH));
                    }
                }
                //Check if user has at least one of the roles associated with the scope
                roleList.retainAll(userRoleList);
                if (!roleList.isEmpty()) {
                    authorizedScopes.add(scope);
                }
            } else {
                authorizedScopes.add(scope);
            }
        }
        return (!authorizedScopes.isEmpty()) ? authorizedScopes : defaultScope;
    }

    /**
     * Extract the roles from the user attributes.
     *
     * @param userAttributes retrieved from the token
     * @return roles
     */
    private String[] getRolesFromUserAttribute(Map<ClaimMapping, String> userAttributes, String roleClaim) {

        for (Iterator<Map.Entry<ClaimMapping, String>> iterator = userAttributes.entrySet().iterator(); iterator
                .hasNext(); ) {
            Map.Entry<ClaimMapping, String> entry = iterator.next();
            if (null != entry.getKey().getLocalClaim()) {
                if (roleClaim.equals(entry.getKey().getLocalClaim().getClaimUri()) && StringUtils
                        .isNotBlank(entry.getValue())) {
                    return entry.getValue().replace("\\/", "/").
                            replace("[", "").replace("]", "").
                            replace("\"", "").split(FrameworkUtils.getMultiAttributeSeparator());
                }
            }
        }
        return new String[0];
    }

    /**
     * Add domain to name
     *
     * @param username   Username
     * @param domainName domain name
     * @return String
     */
    protected String addDomainToName(String username, String domainName) {

        return UserCoreUtil.addDomainToName(username, domainName);
    }

    /**
     * Get roles from assertion
     *
     * @param assertion Assertion
     * @return String[]
     */
    protected String[] getRolesFromAssertion(Assertion assertion) {

        return SystemScopeUtils.getRolesFromAssertion(assertion);
    }

    protected void configureForJWTGrant(OAuthTokenReqMessageContext tokReqMsgCtx) {

        SignedJWT signedJWT = null;
        JWTClaimsSet claimsSet = null;
        String[] roles = null;
        try {
            signedJWT = getSignedJWT(tokReqMsgCtx);
        } catch (IdentityOAuth2Exception e) {
            log.error("Couldn't retrieve signed JWT", e);
        }
        if (signedJWT != null) {
            claimsSet = getClaimSet(signedJWT);
        }
        String jwtIssuer = claimsSet != null ? claimsSet.getIssuer() : null;
        String tenantDomain = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain();

        try {
            identityProvider = IdentityProviderManager.getInstance().getIdPByName(jwtIssuer, tenantDomain);
            if (identityProvider != null) {
                if (StringUtils.equalsIgnoreCase(identityProvider.getIdentityProviderName(), "default")) {
                    identityProvider = this.getResidentIDPForIssuer(tenantDomain, jwtIssuer);
                    if (identityProvider == null) {
                        log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
                    }
                }
            } else {
                log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
            }
        } catch (IdentityProviderManagementException | IdentityOAuth2Exception e) {
            log.error("Couldn't initiate identity provider instance", e);
        }

        try {
            roles = claimsSet != null ?
                    claimsSet.getStringArrayClaim(identityProvider.getClaimConfig().getRoleClaimURI()) :
                    null;
        } catch (ParseException e) {
            log.error("Couldn't retrieve roles:", e);
        }

        List<String> updatedRoles = new ArrayList<>();
        if (roles != null) {
            for (String role : roles) {
                String updatedRoleClaimValue = getUpdatedRoleClaimValue(identityProvider, role);
                if (updatedRoleClaimValue != null) {
                    updatedRoles.add(updatedRoleClaimValue);
                } else {
                    updatedRoles.add(role);
                }
            }
        }
        AuthenticatedUser user = tokReqMsgCtx.getAuthorizedUser();
        Map<ClaimMapping, String> userAttributes = user.getUserAttributes();
        String roleClaim = identityProvider.getClaimConfig().getRoleClaimURI();
        if (roleClaim != null) {
            userAttributes
                    .put(ClaimMapping.build(roleClaim, roleClaim, null, false),
                            updatedRoles.toString().replace(" ", ""));
            tokReqMsgCtx.addProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM, roleClaim);
        }
        user.setUserAttributes(userAttributes);
        tokReqMsgCtx.setAuthorizedUser(user);
    }

    /**
     * Method to parse the assertion and retrieve the signed JWT
     *
     * @param tokReqMsgCtx request
     * @return SignedJWT object
     * @throws IdentityOAuth2Exception exception thrown due to a parsing error
     */
    private SignedJWT getSignedJWT(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {

        RequestParameter[] params = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getRequestParameters();
        String assertion = null;
        SignedJWT signedJWT;
        for (RequestParameter param : params) {
            if (param.getKey().equals(APIConstants.SystemScopeConstants.OAUTH_JWT_ASSERTION)) {
                assertion = param.getValue()[0];
                break;
            }
        }
        if (StringUtils.isEmpty(assertion)) {
            String errorMessage = "Error while retrieving assertion";
            throw new IdentityOAuth2Exception(errorMessage);
        }

        try {
            signedJWT = SignedJWT.parse(assertion);
            if (log.isDebugEnabled()) {
                log.debug(signedJWT);
            }
        } catch (ParseException e) {
            String errorMessage = "Error while parsing the JWT.";
            throw new IdentityOAuth2Exception(errorMessage, e);
        }
        return signedJWT;
    }

    /**
     * Method to retrieve claims from the JWT
     *
     * @param signedJWT JWT token
     * @return JWTClaimsSet Object
     */
    private JWTClaimsSet getClaimSet(SignedJWT signedJWT) {

        JWTClaimsSet claimsSet = null;
        try {
            claimsSet = signedJWT.getJWTClaimsSet();
        } catch (ParseException e) {
            log.error("Error when trying to retrieve claimsSet from the JWT:", e);
        }
        return claimsSet;
    }

    private IdentityProvider getResidentIDPForIssuer(String tenantDomain, String jwtIssuer)
            throws IdentityOAuth2Exception {

        String issuer = "";
        IdentityProvider residentIdentityProvider;
        try {
            residentIdentityProvider = IdentityProviderManager.getInstance().getResidentIdP(tenantDomain);
        } catch (IdentityProviderManagementException var7) {
            String errorMsg = String
                    .format("Error while getting Resident Identity Provider of '%s' tenant.", tenantDomain);
            throw new IdentityOAuth2Exception(errorMsg, var7);
        }

        FederatedAuthenticatorConfig[] fedAuthnConfigs = residentIdentityProvider.getFederatedAuthenticatorConfigs();
        FederatedAuthenticatorConfig oauthAuthenticatorConfig = IdentityApplicationManagementUtil.
                getFederatedAuthenticator(fedAuthnConfigs, "openidconnect");
        if (oauthAuthenticatorConfig != null) {
            issuer = IdentityApplicationManagementUtil.getProperty(oauthAuthenticatorConfig.
                    getProperties(), "IdPEntityId").getValue();
        }

        return jwtIssuer.equals(issuer) ? residentIdentityProvider : null;
    }

    /**
     * Check the retireved roles against the role mappings in the IDP and return the updated roles
     *
     * @param identityProvider      used to retrieve the role mappings
     * @param currentRoleClaimValue current roles received through the token
     * @return updated roles
     */
    private String getUpdatedRoleClaimValue(IdentityProvider identityProvider, String currentRoleClaimValue) {

        if (StringUtils.equalsIgnoreCase(IdentityApplicationConstants.RESIDENT_IDP_RESERVED_NAME,
                identityProvider.getIdentityProviderName())) {
            return currentRoleClaimValue;
        }
        currentRoleClaimValue = currentRoleClaimValue.replace("\\/", "/")
                .replace("[", "").replace("]", "")
                .replace("\"", "");

        PermissionsAndRoleConfig permissionAndRoleConfig = identityProvider.getPermissionAndRoleConfig();
        if (permissionAndRoleConfig != null && org.apache.commons.lang3.ArrayUtils.isNotEmpty(
                permissionAndRoleConfig.getRoleMappings())) {
            String[] receivedRoles = currentRoleClaimValue.split(FrameworkUtils.getMultiAttributeSeparator());
            List<String> updatedRoleClaimValues = new ArrayList<>();
            String updatedLocalRole;
            loop:
            for (String receivedRole : receivedRoles) {
                for (RoleMapping roleMapping : permissionAndRoleConfig.getRoleMappings()) {
                    if (roleMapping.getRemoteRole().equals(receivedRole)) {
                        updatedLocalRole = StringUtils.isEmpty(roleMapping.getLocalRole().getUserStoreId())
                                ? roleMapping.getLocalRole().getLocalRoleName()
                                : roleMapping.getLocalRole().getUserStoreId() + UserCoreConstants.DOMAIN_SEPARATOR
                                + roleMapping.getLocalRole().getLocalRoleName();
                        updatedRoleClaimValues.add(updatedLocalRole);
                        continue loop;
                    }
                }
                if (!OAuthServerConfiguration.getInstance().isReturnOnlyMappedLocalRoles()) {
                    updatedRoleClaimValues.add(receivedRole);
                }
            }
            if (!updatedRoleClaimValues.isEmpty()) {
                return StringUtils.join(updatedRoleClaimValues, FrameworkUtils.getMultiAttributeSeparator());
            }
            return null;
        }
        if (!OAuthServerConfiguration.getInstance().isReturnOnlyMappedLocalRoles()) {
            return currentRoleClaimValue;
        }
        return null;
    }

    /**
     * This method is used to get the application scopes including the scopes defined for the APIs subscribed to the
     * application and the API-M REST API scopes set of the current tenant.
     *
     * @param consumerKey       Consumer Key of the application
     * @param authenticatedUser Authenticated User
     * @return Application Scope List
     */
    public Map<String, String> getAppScopes(String consumerKey, AuthenticatedUser authenticatedUser,
                                            List<String> requestedScopes) {

        //Get all the scopes and roles against the scopes defined for the APIs subscribed to the application.
        Map<String, String> appScopes = new HashMap<>();
        boolean isTenantFlowStarted = false;
        String tenantDomain = authenticatedUser.getTenantDomain();
        //Add API Manager rest API scopes set. This list should be loaded at server start up and keep
        //in memory and add it to each and every request coming.
        try {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
            Map<String, String> restAPIScopes = SystemScopeUtils.getRESTAPIScopesForTenant(tenantDomain);
            if (!restAPIScopes.isEmpty()) {
                appScopes.putAll(restAPIScopes);
            }
        } catch (APIManagementException e) {
            log.error("Error while getting scopes of application " + e.getMessage(), e);
        } finally {
            if (isTenantFlowStarted) {
                PrivilegedCarbonContext.endTenantFlow();
            }
        }
        return appScopes;
    }

    /**
     * This method is used to check if the application scope list empty.
     *
     * @param appScopes Application scopes list
     * @param clientId  Client ID of the application
     * @return if the scopes list is empty
     */
    public Boolean isAppScopesEmpty(Map<String, String> appScopes, String clientId) {

        if (appScopes.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("No scopes defined for the Application " + clientId);
            }
            return true;
        }
        return false;
    }

    /**
     * Get the set of default scopes. If a requested scope is matches with the patterns specified in the whitelist,
     * then such scopes will be issued without further validation. If the scope list is empty,
     * token will be issued for default scop1e.
     *
     * @param requestedScopes - The set of requested scopes
     * @return - The subset of scopes that are allowed
     */
    public List<String> getAllowedScopes(List<String> requestedScopes) {

        if (requestedScopes.isEmpty()) {
            requestedScopes.add(DEFAULT_SCOPE_NAME);
        }
        return requestedScopes;
    }

    /**
     * Get RealmService
     *
     * @return RealmService
     */
    protected RealmService getRealmService() {
        return ServiceReferenceHolder.getInstance().getRealmService();
    }

    /**
     * Get tenant Id of the user
     *
     * @param username Username
     * @return int
     */
    protected int getTenantIdOfUser(String username) {
        return IdentityTenantUtil.getTenantIdOfUser(username);
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0004_auto_20170927_1834'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='billingaccount',
            name='balance_brl',
        ),
        migrations.RemoveField(
            model_name='billingaccount',
            name='balance_btc',
        ),
    ]


text:
class RoleContext

  CONTEXTS = [:admin, :gathering, :member]

  LEADER = "leader"
  ASSISTANT = "assistant"
  OVERSEER = "overseer"
  MEMBER = "member"
  VISITOR = "visitor"

  ROLES = [LEADER, ASSISTANT, OVERSEER, MEMBER, VISITOR]
  ASSISTANTS = [ASSISTANT]
  LEADERS = [LEADER, ASSISTANT]
  OVERSEERS = LEADERS + [OVERSEER]
  MEMBERS = OVERSEERS + [MEMBER]
  PARTICIPANTS = MEMBERS + [VISITOR]
  VISITORS = [VISITOR]

  COMMUNITY_ROLES = LEADERS + [MEMBER]
  CAMPUS_ROLES = MEMBERS
  GATHERING_ROLES = ROLES - [OVERSEER]

  class<<self

    def context_for(member, community: nil, campus: nil, gathering: nil)
      RoleContext.new(member, community, campus, gathering)
    end

    def roles_allowed_for(group)
      case group
      when Community then COMMUNITY_ROLES
      when Campus then CAMPUS_ROLES
      when Gathering then GATHERING_ROLES
      else
        []
      end
    end

    def is_role_allowed?(group, role)
      roles_allowed_for(group).include?(role)
    end

  end

  def campus
    @campus
  end

  def community
    @community
  end

  def gathering
    @gathering
  end

  def member
    @member
  end

  def acts_as_community_leader?
    is_community_leader?
  end

  def acts_as_community_member?
    is_community_member? || acts_as_community_leader?
  end

  def acts_as_campus_leader?
    is_campus_leader? || acts_as_community_leader?
  end

  def acts_as_campus_member?
    is_campus_member? || acts_as_campus_overseer?
  end

  def acts_as_campus_overseer?
    is_campus_overseer? || acts_as_campus_leader?
  end

  def acts_as_gathering_leader?
    is_gathering_leader? || is_assigned_overseer? || acts_as_campus_leader?
  end

  def acts_as_gathering_member?
    is_gathering_member? || is_assigned_overseer?
  end

  def acts_as_gathering_visitor?
    @gathering_membership.present?
  end

  def dump_roles
    return unless Rails.env.development? || Rails.env.test?

    roles = []

    COMMUNITY_ROLES.each {|role| roles << "Community #{role.to_s.humanize}? #{self.send("is_community_#{role}?".to_sym)}"}
    CAMPUS_ROLES.each {|role| roles << "Campus #{role.to_s.humanize}? #{self.send("is_campus_#{role}?".to_sym)}"}
    GATHERING_ROLES.each {|role| roles << "Gathering #{role.to_s.humanize}? #{self.send("is_gathering_#{role}?".to_sym)}"}
    roles << "Is Assigned Overseer? #{is_assigned_overseer?}"
    roles << "Acts as Community Leader? #{acts_as_community_leader?}"
    roles << "Acts as Community Member? #{acts_as_community_member?}"
    roles << "Acts as Campus Leader? #{acts_as_campus_leader?}"
    roles << "Acts as Campus Member? #{acts_as_campus_member?}"
    roles << "Acts as Campus Overseer? #{acts_as_campus_overseer?}"
    roles << "Acts as Gathering Leader? #{acts_as_gathering_leader?}"
    roles << "Acts as Gathering Member? #{acts_as_gathering_member?}"
    roles << "Acts as Gathering Visitor? #{acts_as_gathering_visitor?}"
    roles
  end

  protected

    def initialize(member, community, campus, gathering)
      @member = member
      @gathering = gathering
      @campus = campus || (@gathering.present? ? @gathering.campus : nil)
      @community = community || (@campus.present? ? @campus.community : nil)

      @community_membership = member.active_member_of?(@community)
      @campus_membership = member.active_member_of?(@campus)
      @gathering_membership = member.active_member_of?(@gathering)
      @is_assigned_overseer = @gathering.present? && @gathering.is_active_assigned_overseer?(@member)
    end

    ROLES.each do |role|
      class_eval <<-METHODS, __FILE__, __LINE__ + 1
        def is_#{role}?(membership)
          membership.present? && membership.as_#{role}?
        end
      METHODS
    end

    COMMUNITY_ROLES.each do |role|
      class_eval <<-METHODS, __FILE__, __LINE__ + 1
        def is_community_#{role}?
          is_#{role}?(@community_membership)
        end
      METHODS
    end

    CAMPUS_ROLES.each do |role|
      class_eval <<-METHODS, __FILE__, __LINE__ + 1
        def is_campus_#{role}?
          is_#{role}?(@campus_membership)
        end
      METHODS
    end

    GATHERING_ROLES.each do |role|
      class_eval <<-METHODS, __FILE__, __LINE__ + 1
        def is_gathering_#{role}?
          is_#{role}?(@gathering_membership)
        end
      METHODS
    end

    def is_assigned_overseer?
      @is_assigned_overseer
    end

end


text:
layout: post
title: 'Panasonic GF1'
date: '2011-02-25T00:00:00+00:00'
body-class: 'blog'
tags:
- video
- yoomee
- sheffield
img: gf1.jpg
tumblr_url: http://blog.richwells.me/post/40516945239/panasonic-gf1
video: "

  "
---

After saving up for a while I bought a Panasonic GF1 last week, with a 20mm pancake lens. Really enjoying using it- perfect balance of quality and portability and does great video too. This is a quick video I made in imovie. Apologies for the boring shaky close ups!


text:
define({
  "selectAnalysisTools": "Vælg de analyseværktøjer, der skal bruges i widget'en.",
  "graphicalDisplay": "Grafisk visning",
  "toolSetting": "Angiv værktøjsoplysninger",
  "toolLabel": "Værktøjets visningsnavn",
  "showHelpTip": "Vis hjælp-links i widget'en",
  "showCurrentMapExtent": "Vis den indstilling, der skal bruges til den aktuelle kortudstrækning",
  "showCredits": "Vis indstillingen <b>Vis credits</b>",
  "saveAsFeatureService": "Gem resultatet i brugerens konto",
  "showReadyToUseLayers": "Vis lag, der er klar til brug, fra ArcGIS Online Living Atlas of the World",
  "toolNotAvailable": "Dette værktøj er ikke tilgængeligt, fordi kortet ikke indeholder de påkrævede vektorlag.",
  "aggregatePoints": "Aggregér punkter",
  "aggregatePointsUsage": "Aggregér punkter til polygoner, hvor punkterne findes.",
  "calculateDensity": "Beregn tæthed",
  "calculateDensityUsage": "Opret et tæthedskort ud fra punkt- eller linjeobjekter ved at sprede kendte mængder af et fænomen (repræsenteret som attributter af punkter eller linjer) på tværs af kortet.",
  "connectOriginsToDestinations": "Forbind udgangspunkter med destinationer",
  "connectOriginsToDestinationsUsage": "Mål rejsetiden eller -afstanden mellem punktpar.",
  "createBuffers": "Opret buffere",
  "createBuffersUsage": "Opret bufferpolygoner ud fra inputobjekter.",
  "createDriveTimeAreas": "Opret køretidsområder",
  "createDriveTimeAreasUsage": "Opret køretids- (eller køreafstands-) polygoner omkring inputpunkterne for de givne køretidsværdier.",
  "createViewshed": "Opret udsigtsområde",
  "createViewshedUsage": "Opretter områder, der er synlige baseret på steder, som du angiver.",
  "createWatersheds": "Opret vandskel",
  "createWatershedsUsage": "Opretter vandopsamlingsområder baseret på steder, som du angiver.",
  "deriveNewLocations": "Udled nye steder",
  "deriveNewLocationsUsage": "Udled nye objekter fra de inputlag, der opfylder en forespørgsel, som du angiver",
  "dissolveBoundaries": "Opløs grænser",
  "dissolveBoundariesUsage": "Opløs de polygoner, der overlapper eller deler en fælles grænse.",
  "enrichLayer": "Berig lag",
  "enrichLayerUsage": "Berig inputobjekter med person-, sted- og virksomhedsfakta om nærliggende områder.",
  "extractData": "Udtræk data",
  "extractDataDesc": "Udtræk data fra et eller flere lag inden for en given udstrækning",
  "findExistingLocations": "Find eksisterende steder",
  "findExistingLocationsUsage": "Vælg objekter i det inputlag, der opfylder en attribut- og/eller spatial forespørgsel, du angiver",
  "findHotSpots": "Find hotspots",
  "findHotSpotsUsage": "Find statistisk signifikante, spatiale klyngedannelser med inputobjekter eller høje/lave værdier.",
  "findNearest": "Find nærmeste",
  "findNearestUsage": "For hvert objekt i et inputlag skal du finde det nærmeste objekt i et andet lag",
  "findSimilarLocations": "Find lignende steder",
  "findSimilarLocationsUsage": "Mål ensartetheden for kandidatstederne i forhold til et eller flere referencesteder.",
  "interpolatePoints": "Interpolér punkter",
  "interpolatePointsUsage": "Forudsig værdier på nye placeringer baseret på målinger ud fra en samling af punkter.",
  "mergeLayers": "Flet lag",
  "mergeLayersUsage": "Flet objekter fra flere lag til ét nyt lag",
  "overlayLayers": "Overlay af lag",
  "overlayLayersUsage": "Kombinér flere lag til et enkelt lag med oplysninger fra de oprindeligt gemte lag.",
  "planRoutes": "Planlæg ruter",
  "planRoutesUsage": "Bestem, hvordan du effektivt kan fordele opgaver blandt en mobil arbejdsstyrke.",
  "summarizeNearby": "Opsummér i nærheden",
  "summarizeNearbyUsage": "For hvert objekt i et inputlag skal du summere data inden for en bestemt afstand fra objekterne i et andet lag.",
  "summarizeWithin": "Summér inden for",
  "summarizeWithinUsage": "For hver polygon i et inputpolygonlag skal du summere data inden for en bestemt afstand fra objekterne i et andet lag.",
  "traceDownstream": "Gå med strømmen",
  "traceDownstreamUsage": "Bestemmer vandløbsretninger i \"nedstrøms-retning\" fra de placeringer, som du angiver.",
  "allowToExport": "Tillad eksport af resultater"
});


text:
namespace alinous {namespace remote {namespace monitor {

bool MonitorResponceAction::__init_done = __init_static_variables();
bool MonitorResponceAction::__init_static_variables(){
	Java2CppSystem::getSelf();
	ThreadContext* ctx = ThreadContext::newThreadContext();
	{
		GCNotifier __refobj1(ctx, __FILEW__, __LINE__, L"MonitorResponceAction", L"__init_static_variables");
	}
	ctx->localGC();
	delete ctx;
	return true;
}
 MonitorResponceAction::MonitorResponceAction(TransactionMonitorServer* monitorServer, Socket* socket, SocketServer* server, ThreadContext* ctx) throw()  : IObject(ctx), IThreadAction(ctx), socket(nullptr), server(nullptr), monitorServer(nullptr)
{
	__GC_MV(this, &(this->monitorServer), monitorServer, TransactionMonitorServer);
	__GC_MV(this, &(this->socket), socket, Socket);
	__GC_MV(this, &(this->server), server, SocketServer);
}
void MonitorResponceAction::__construct_impl(TransactionMonitorServer* monitorServer, Socket* socket, SocketServer* server, ThreadContext* ctx) throw()
{
	__GC_MV(this, &(this->monitorServer), monitorServer, TransactionMonitorServer);
	__GC_MV(this, &(this->socket), socket, Socket);
	__GC_MV(this, &(this->server), server, SocketServer);
}
 MonitorResponceAction::~MonitorResponceAction() throw()
{
	ThreadContext *ctx = ThreadContext::getCurentContext();
	if(ctx != nullptr){ctx->incGcDenial();}
	__releaseRegerences(false, ctx);
	if(ctx != nullptr){ctx->decGcDenial();}
}
void MonitorResponceAction::__releaseRegerences(bool prepare, ThreadContext* ctx) throw()
{
	ObjectEraser __e_obj1(ctx, __FILEW__, __LINE__, L"MonitorResponceAction", L"~MonitorResponceAction");
	__e_obj1.add(this->socket, this);
	socket = nullptr;
	__e_obj1.add(this->server, this);
	server = nullptr;
	__e_obj1.add(this->monitorServer, this);
	monitorServer = nullptr;
	if(!prepare){
		return;
	}
}
void MonitorResponceAction::execute(ThreadContext* ctx)
{
	{
		std::function<void(void)> finallyLm2= [&, this]()
		{
			this->server->dec(ctx);
			this->socket->close(ctx);
		};
		Releaser finalyCaller2(finallyLm2);
		try
		{
			InputStream* sockstream = this->socket->getInputStream(ctx);
			BufferedInputStream* stream = (new(ctx) BufferedInputStream(sockstream, ctx));
			OutputStream* sockStream = socket->getOutputStream(ctx);
			BufferedOutputStream* outStream = (new(ctx) BufferedOutputStream(sockStream, ctx));
			handleCommand(stream, outStream, ctx);
		}
		catch(Throwable* e)
		{
			this->socket->close(ctx);
			e->printStackTrace(ctx);
			return;
		}
	}
}
void MonitorResponceAction::handleCommand(BufferedInputStream* stream, BufferedOutputStream* outStream, ThreadContext* ctx)
{
	bool loop = true;
	AbstractMonitorCommand* cmd = nullptr;
	while(loop)
	{
		cmd = parseCommand(stream, ctx);
		if(cmd == nullptr)
		{
			throw (new(ctx) AlinousException(ConstStr::getCNST_STR_3576(), ctx));
		}
		int type = cmd->getType(ctx);
		switch(type) {
		case AbstractMonitorCommand::TYPE_FINISH:
			loop = false;
			handleCommand(cmd, outStream, ctx);
			break ;
		case AbstractMonitorCommand::TYPE_TERMINATE:
			loop = false;
			handleCommand(cmd, outStream, ctx);
			break ;
		case AbstractMonitorCommand::TYPE_CONNECT:
		case AbstractMonitorCommand::TYPE_GET_MAX_COMMIT_ID:
		case AbstractMonitorCommand::TYPE_NEW_MAX_COMMIT_ID:
		case AbstractMonitorCommand::TYPE_GET_REGION_INFO:
		case AbstractMonitorCommand::TYPE_NEW_TRANSACTION:
		case AbstractMonitorCommand::TYPE_REPORT_SCHEMA_UPDATED:
		case AbstractMonitorCommand::TYPE_REPORT_CLUSTER_UPDATED:
		case AbstractMonitorCommand::TYPE_ALLOC_OID:
		case AbstractMonitorCommand::TYPE_REPORT_OID:
		case AbstractMonitorCommand::TYPE_VOID:
			handleCommand(cmd, outStream, ctx);
			break ;
		default:
			loop = false;
			break ;
		}
	}
}
void MonitorResponceAction::handleCommand(AbstractMonitorCommand* cmd, BufferedOutputStream* outStream, ThreadContext* ctx)
{
	cmd->executeOnServer(this->monitorServer, outStream, ctx);
}
AbstractMonitorCommand* MonitorResponceAction::parseCommand(BufferedInputStream* stream, ThreadContext* ctx)
{
	AbstractMonitorCommand* cmd = MinitorCommandReader::readFromStream(stream, ctx);
	return cmd;
}
void MonitorResponceAction::__cleanUp(ThreadContext* ctx){
}
}}}


text:
<?php
namespace bablo\model;
use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Table(name="bablo.income")
 * @ORM\Entity
 */
class Income implements \JsonSerializable {
    /**
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    * @ORM\Column(type="integer")
    */
    protected $id;
    /**
     * @ORM\Column(type="float")
     */
    protected $amount;
    /**
     * @ORM\ManyToOne(targetEntity="\bablo\model\Currency")
     * @ORM\JoinColumn(name="currency_id", referencedColumnName="id")
     **/
    protected $currency;
    /**
     * @ORM\Column(type="integer")
     */
    protected $user_id;
    /**
     * @ORM\ManyToOne(targetEntity="\bablo\model\User")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     **/
    protected $user;
    //protected $source;
    /**
     * @ORM\Column(type="datetime")
     */
    protected $date;
    /**
     * @ORM\Column(type="integer")
     */
    protected $currency_id;

    protected $source;
    public function getUser() {
        return $this->user;
    }

    public function setUser($user) {
        $this->user = $user;
    }

        public function getCurrency_id() {
        return $this->currency_id;
    }

    public function setCurrency_id($currency_id) {
        $this->currency_id = $currency_id;
    }

    public function getCurrencyId() {
        return $this->currency_id;
    }

    public function setCurrencyId($currency_id) {
        $this->currency_id = $currency_id;
    }

    public function getId() {
        return $this->id;
    }

    public function setId($id) {
        $this->id = $id;
    }

    public function getAmount() {
        return $this->amount;
    }

    public function getCurrency() {
        return $this->currency;
    }

    public function getUserid() {
        return $this->user_id;
    }

    public function getSource() {
        return $this->source;
    }

    public function getDate() {
        if (!empty($this->date)) {
            return $this->date;//->format('Y-m-d');
        } else return null;
    }

    public function setAmount($amount) {
        $this->amount = $amount;
    }

    public function setCurrency($currency) {
        $this->currency = $currency;
    }

    public function setUserid($userid) {
        $this->user_id = $userid;
    }

    public function setSource($source) {
        $this->source = $source;
    }

    public function setDate($date) {
        $this->date = $date;
    }

    public function getUsdAmount() {
        if (empty($this->currency)) {
            return null;
        }
        $rates = $this->currency->getRates();
        $rate = $rates[0];
        return $rate->getRate() * $this->amount;
    }

    public function jsonSerialize() {
        $obj = [];
        foreach ($this as $prop => $val) {
            $obj[$prop] = $val;
        }
        return $obj;
    }

    public function exchangeArray($data) {
        foreach ($data as $field => $val) {
            $this->$field = $val;
        }
    }

    public function toArray($withId = true, $withCustomFields = true) {
        $customFields = ['currency', 'source', 'usdAmount'];
        $array = [];
        foreach ($this as $key => $value) {
            if (($key !== 'id' || $withId) && (!in_array($key, $customFields) || $withCustomFields)) {
                $array[$key] = $value;
            }
        }
        return $array;
    }

}


text:
package com.box.boxjavalibv2.dao;

import java.io.File;
import java.io.IOException;

import junit.framework.Assert;

import org.apache.commons.io.FileUtils;
import org.junit.Test;

import com.box.boxjavalibv2.testutils.TestUtils;
import com.box.restclientv2.exceptions.BoxRestException;

public class BoxGroupMembershipTest {

    @Test
    public void testParcelRoundTrip() throws BoxRestException, IOException {
        String membershipJson = FileUtils.readFileToString(new File("testdata/groupmembership.json"));
        String userJson = FileUtils.readFileToString(new File("testdata/user.json"));
        String groupJson = FileUtils.readFileToString(new File("testdata/group.json"));
        membershipJson = String.format(membershipJson, userJson, groupJson);

        BoxGroupMembership membership = (BoxGroupMembership) TestUtils.getFromJSON(membershipJson, BoxGroupMembership.class);

        TestParcel parcel = new TestParcel();
        membership.writeToParcel(parcel, 0);
        BoxGroupMembership fromParcel = new BoxGroupMembership(parcel);

        Assert.assertEquals(BoxResourceType.GROUP_MEMBERSHIP.toString(), fromParcel.getType());
        Assert.assertEquals("testid", fromParcel.getId());
        Assert.assertEquals("testrole", fromParcel.getRole());
        Assert.assertNotNull(fromParcel.getUser());
        Assert.assertNotNull(fromParcel.getGroup());
    }

}


text:
import Editor from 'tinymce/core/api/Editor';
import { EditorOptions } from 'tinymce/core/api/OptionTypes';

const option: {
  <K extends keyof EditorOptions>(name: K): (editor: Editor) => EditorOptions[K];
  <T>(name: string): (editor: Editor) => T;
} = (name: string) => (editor: Editor) =>
  editor.options.get(name);

const register = (editor: Editor): void => {
  const registerOption = editor.options.register;

  registerOption('allow_html_in_named_anchor', {
    processor: 'boolean',
    default: false
  });
};

const allowHtmlInNamedAnchor = option<boolean>('allow_html_in_named_anchor');

export {
  register,
  allowHtmlInNamedAnchor
};


text:
package jdk.proxy;

import java.io.FileOutputStream;
import java.io.IOException;

import sun.misc.ProxyGenerator;

public class ProxyUtils {

	public static void generateClassFile(Class<?> clazz, String proxyName) {

		byte[] classFile = ProxyGenerator.generateProxyClass(proxyName, clazz.getInterfaces());
		String paths = clazz.getResource(".").getPath();
		System.out.println(paths);
		FileOutputStream out = null;

		try {
			out = new FileOutputStream(paths+proxyName+".class");
			out.write(classFile);
			out.flush();
		}catch(Exception e) {
			e.printStackTrace();
		}finally{
			try{
				out.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
}


text:
	enum DBTYPE {
		POSTGRESQL, MYSQL, MARIADB, SQLITE, BDB, MONGODB, MEMCACHED
	};

	static Boolean isEnabled(DBTYPE type);

	DBTYPE currenttype;
	String caption;
	String name;
	String version;
	String desc;
	String owner;
	Boolean enabled;
	//Boolean running;
#endif


text:
#include "Http3FrameDispatcher.h"

#include "tscore/Diags.h"
#include "QUICIntUtil.h"

#include "Http3DebugNames.h"

//
// Frame Dispatcher
//

void
Http3FrameDispatcher::add_handler(Http3FrameHandler *handler)
{
  for (Http3FrameType t : handler->interests()) {
    this->_handlers[static_cast<uint8_t>(t)].push_back(handler);
  }
}

Http3ErrorUPtr
Http3FrameDispatcher::on_read_ready(QUICStreamIO &stream_io, uint64_t &nread)
{
  std::shared_ptr<const Http3Frame> frame(nullptr);
  Http3ErrorUPtr error = Http3ErrorUPtr(new Http3NoError());
  nread                = 0;

  while (true) {
    // Read a length of Type field and hopefully a length of Length field too
    uint8_t head[16];
    int64_t read_len = stream_io.peek(head, 16);
    Debug("v_http3", "reading H3 frame: state=%d read_len=%" PRId64, this->_reading_state, read_len);

    if (this->_reading_state == READING_TYPE_LEN) {
      if (read_len >= 1) {
        this->_reading_frame_type_len = QUICVariableInt::size(head);
        this->_reading_state          = READING_LENGTH_LEN;
        Debug("v_http3", "type_len=%" PRId64, this->_reading_frame_type_len);
      } else {
        break;
      }
    }

    if (this->_reading_state == READING_LENGTH_LEN) {
      if (read_len >= this->_reading_frame_type_len + 1) {
        this->_reading_frame_length_len = QUICVariableInt::size(head + this->_reading_frame_type_len);
        this->_reading_state            = READING_PAYLOAD_LEN;
        Debug("v_http3", "length_len=%" PRId64, this->_reading_frame_length_len);
      } else {
        break;
      }
    }

    if (this->_reading_state == READING_PAYLOAD_LEN) {
      if (read_len >= this->_reading_frame_type_len + this->_reading_frame_length_len) {
        size_t dummy;
        QUICVariableInt::decode(this->_reading_frame_payload_len, dummy, head + this->_reading_frame_type_len);
        Debug("v_http3", "payload_len=%" PRId64, this->_reading_frame_payload_len);
        this->_reading_state = READING_PAYLOAD;
      } else {
        break;
      }
    }

    if (this->_reading_state == READING_PAYLOAD) {
      // Create a frame
      // Type field length + Length field length + Payload length
      size_t frame_len = this->_reading_frame_type_len + this->_reading_frame_length_len + this->_reading_frame_payload_len;
      frame            = this->_frame_factory.fast_create(stream_io, frame_len);
      if (frame == nullptr) {
        break;
      }

      // Consume buffer if frame is created
      nread += frame_len;
      stream_io.consume(frame_len);

      // Dispatch
      Http3FrameType type = frame->type();
      Debug("http3", "[RX] [%d] | %s size=%zu", stream_io.stream_id(), Http3DebugNames::frame_type(type), frame_len);
      std::vector<Http3FrameHandler *> handlers = this->_handlers[static_cast<uint8_t>(type)];
      for (auto h : handlers) {
        error = h->handle_frame(frame);
        if (error->cls != Http3ErrorClass::NONE) {
          return error;
        }
      }
      this->_reading_state = READING_TYPE_LEN;
    }
  }

  return error;
}


text:
package io.vertx.mysqlclient.spi;

import io.vertx.core.Vertx;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.SqlConnectOptions;
import io.vertx.sqlclient.spi.Driver;

public class MySQLDriver implements Driver {

  @Override
  public Pool createPool(SqlConnectOptions options, PoolOptions poolOptions) {
    return MySQLPool.pool(wrap(options), poolOptions);
  }

  @Override
  public Pool createPool(Vertx vertx, SqlConnectOptions options, PoolOptions poolOptions) {
    return MySQLPool.pool(vertx, wrap(options), poolOptions);
  }

  @Override
  public boolean acceptsOptions(SqlConnectOptions options) {
    return options instanceof MySQLConnectOptions || SqlConnectOptions.class.equals(options.getClass());
  }

  private static MySQLConnectOptions wrap(SqlConnectOptions options) {
    if (options instanceof MySQLConnectOptions) {
      return (MySQLConnectOptions) options;
    } else {
      return new MySQLConnectOptions(options);
    }
  }

}


text:
package co.cask.cdap.proto.metadata.lineage;

import co.cask.cdap.proto.Id;

import java.util.Objects;

/**
 * Class to serialize program in {@link LineageRecord}.
 */
public class ProgramRecord {
  private final Id.NamespacedId entityId;

  public ProgramRecord(Id.NamespacedId entityId) {
    this.entityId = entityId;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof ProgramRecord)) {
      return false;
    }
    ProgramRecord that = (ProgramRecord) o;
    return Objects.equals(entityId, that.entityId);
  }

  @Override
  public int hashCode() {
    return Objects.hash(entityId);
  }

  @Override
  public String toString() {
    return "ProgramRecord{" +
      "entityId=" + entityId +
      '}';
  }
}


text:
<!DOCTYPE html>

    <title>Week 9 | Cultural Blog</title>

    <link href="stylesheets/culture9.css" rel="stylesheet" type = "text/css">

    <link href='http://fonts.googleapis.com/css?family=Great+Vibes' rel='stylesheet' type='text/css'>

MENU

DevBootcamp

Archives

w3schools

Contact Me

DevCamping with...&nbspEdgar Garza

About

Any Questions?

July 13, 2014

This week, I learned how to ask questions.  Actually writing is more like it. I Google&#8217d a ton of them to build the new layout of my blog. Some are as follows:

Making a carousel in html and jquery.

How do I build a carousel in jquery?

How to use ul for a carousel in html?

Can I use divs to build a carousel in jquery?

How can I put text in my carousel in html?

How can I keep my text inside the carousel using divs?

How can I keep my text inside the carousel using jquery?

How can I hide my overflowing text in a carousel using html? css?

How can I write a manually navigated carousel in jquery?

My questions became longer and longer the more I went deeper into the rabbit hole.  I was searching for anything and everything in Google and YouTube. If it involved JQuery and carousels I probably saw it. I read forums, articles, advertisements, blogs, tutorials, and the more specific my question the better the chances I was going to find an answer. The first question took my to a couple tutorials and blogs that were pretty helpful in getting me familiar with JQuery but I never found that one source that spelled everything out for me. It took a) multiple questions and b) specified searches to piece together my answers.

I found myself solving my problems only to run into another one. First was my need of getting a general overview of JQuery and creating the pseudo code of what I needed. Afterwards I built an underordered list and created divs for my listed-items.  Then there was an issue of hiding and stacking my images that I wanted to insert in my carousel. Afterwards, I needed to correctly write the JQuery function to rotate the images while connecting the first image of my loop with the last, making a infinite loop. But, my divs were not working properly, and learned to stick with the underordered list and items minus the divs. Once that was settled and I finally finished my carousel and I was ready to insert some content, linking it to my blogs. This was my biggest hurdle yet.

My first issue: How do I properly insert text into a carousel with images? Then: How do I get the text/content to rotate within the carousel? Followed by: How do I hide any overflowing text that makes it outside of the carousel frame. Since there was a huge variety of different ways to create a carousel, may of the pieces I needed to solve my problem conflicted with each other. Near the end, I searched for the commonalities between the different solutions and pieced together my code. I knew there was a better way of writing it but at least I'll never forget how to make it, that is for sure.

CHEERS!!!!

DBC Summer 2014

        Tweets by @EGRZ


text:
namespace graphic
{
	class cModel2;

	class cShadow2
	{
	public:
		cShadow2();
		virtual ~cShadow2();

		bool Create(cRenderer &renderer, const int textureWidth, const int textureHeight);
		void Bind(cShader &shader, const Str32 &key);
		void Begin(cRenderer &renderer);
		void End(cRenderer &renderer);
		bool IsLoaded() const;
		void LostDevice();
		void ResetDevice(graphic::cRenderer &renderer);

		// µð¹ö±ë¿ë ÇÔ¼ö.
		void RenderShadowMap(cRenderer &renderer);

	public:
		cSurface2 m_surface;
	};

	inline bool cShadow2::IsLoaded() const { return m_surface.IsLoaded(); }
}


text:
layout: page
title: Citadel International Party
date: 2016-05-24
author: Lori Ward
tags: weekly links, java
status: published
summary: Etiam eget mi accumsan, congue dui.
banner: images/banner/office-01.jpg
booking:
  startDate: 05/25/2016
  endDate: 05/27/2016
  ctyhocn: DENGWHX
  groupCode: CIP
published: true
---
Integer feugiat turpis nibh, eu luctus metus condimentum nec. In vel vestibulum diam. Cras a odio accumsan, fringilla sapien auctor, faucibus arcu. Aliquam quis ullamcorper velit. Praesent non finibus justo. Donec finibus est elementum cursus luctus. Morbi eleifend quis urna non ornare. Duis in sapien ac mauris porta vestibulum malesuada et mi. Nam vehicula elit in neque posuere luctus. Fusce a felis ornare augue dignissim tempus. Nulla vestibulum, turpis iaculis venenatis dignissim, est orci gravida erat, ac suscipit elit lectus id odio. Maecenas convallis orci eget est convallis, sed condimentum libero sagittis. Pellentesque vel condimentum ipsum, in pellentesque purus.

* Vestibulum tincidunt tellus id suscipit pharetra.

Curabitur a purus vel magna porttitor eleifend. Cras dignissim malesuada odio non suscipit. Ut venenatis, nunc non ultrices placerat, purus felis posuere ligula, quis egestas ex eros et massa. Nulla accumsan mi eget ex semper, a vehicula erat commodo. Proin laoreet et nisi sollicitudin rutrum. Curabitur bibendum dui non lacus accumsan semper. Duis ullamcorper velit eget nisi mattis tempus. Nunc nulla augue, elementum et arcu sit amet, blandit auctor sapien.
Nulla id neque in eros condimentum molestie sit amet euismod lectus. In tempor nisi molestie, iaculis mi vitae, convallis felis. Suspendisse nulla sapien, ornare in ultrices a, tempor vel neque. Curabitur eget vestibulum mauris. Nunc facilisis odio sapien, et dapibus mi congue vel. Cras quis ante arcu. Vivamus venenatis ornare metus in tincidunt.


text:
require File.dirname(__FILE__) + '/../test_helper'

class ResponseTest < Test::Unit::TestCase
  def test_response_success
    assert Response.new(true, 'message', :param => 'value').success?
    assert !Response.new(false, 'message', :param => 'value').success?
  end

  def test_get_params
    response = Response.new(true, 'message', :param => 'value')

    assert_equal ['param'], response.params.keys
  end
end