text:
class Grabcut_app
{
public:
    //control vars
    bool m_overlay = false;
    bool m_show_enclosing_rest = false;
    bool m_validation = false;
    double m_valid_ratio_opacity = 1.0;
    double m_image_opacity = 0.3;
    int m_radius = 2;

    //minimum area rotated rectangle for the segmentation
    cv::RotatedRect m_enclosing_rect;

    void reset();
    void setImageAndWinName( const cv::Mat& _image, const std::string& _winName );
    void showImage(int number = -1);
    void mouseClick( int event, int x, int y, int flags, void* param );
    void nextIter();
    cv::Mat get_segmentation();
    void predict_background(cv::Mat & img0, cv::Mat & img1, cv::Mat & mask, cv::Rect & prev_bbox, bool uncertain = false);
    void set_rectangle(const cv::Rect & rect, bool uncertain = false);

    // Should be called after setImageAndWinName and setRectInMask
    void set_mask(const cv::Mat & mask);

private:
    //consts. and vars for plotting
    const cv::Scalar P_RED = cv::Scalar(0,0,255);
    const cv::Scalar P_PINK = cv::Scalar(230,130,255);
    const cv::Scalar P_BLUE = cv::Scalar(255,0,0);
    const cv::Scalar P_LIGHTBLUE = cv::Scalar(255,255,160);
    const cv::Scalar P_GREEN = cv::Scalar(0,255,0);
    static const int p_thickness = -1;
    int p_number = -1;

    //consts for keyboard inputs
    const int P_BGD_KEY = cv::EVENT_FLAG_CTRLKEY;
    const int P_FGD_KEY = cv::EVENT_FLAG_SHIFTKEY;

    //control consts
    enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 };
    uchar p_rect_state, p_labeling_state, p_pr_labeling_state;
    bool p_is_initialized;

    //ptrs for displaying
    const std::string* p_win_name;
    const cv::Mat* p_image;

    //mats for grabcut
    cv::Mat p_mask, p_bgdModel, p_fgdModel;
    cv::Mat p_mask_valid_fg, p_mask_valid_bg;
    cv::Mat p_mask_cached;
    cv::Mat p_res_cached;
    int p_disp_counter = 0;

    double p_rect_size_ratio = 1.1;
    double p_roi_rect_size_ratio = 2.0;
    cv::Rect p_rect;
    cv::Rect p_roi_rect;

    std::vector<cv::Point> p_fgdPxls, p_bgdPxls, p_prFgdPxls, p_prBgdPxls;

    void setRectInMask();
    void setLblsInMask( int flags, cv::Point p, bool isPr );
    void getBinMask( const cv::Mat & comMask, cv::Mat & binMask);
    void show_temporal_pts(const cv::Point & pt, int flags);

    cv::Mat cyclshift(const cv::Mat &patch, int x_rot, int y_rot);
    void enlarge_bbox(cv::Rect & bbox, double expand_factor);
};

#endif //GRABCUT_ANNOTATION_GRABCUT_APP_H


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

<title>TestCaseActivityStub (MDW 6 API JavaDocs)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.centurylink.mdw.test

Class TestCaseActivityStub

java.lang.Object

com.centurylink.mdw.test.TestCaseActivityStub

public class TestCaseActivityStub
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

TestCaseActivityStub(groovy.lang.Closure<java.lang.Boolean> matcher,
                    groovy.lang.Closure<java.lang.String> completer)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

groovy.lang.Closure<java.lang.String>
getCompleter()

int
getDelay()

groovy.lang.Closure<java.lang.Boolean>
getMatcher()

int
getSleep()

java.util.Map<java.lang.String,java.lang.Object>
getVariables()

void
setCompleter(groovy.lang.Closure<java.lang.String> completer)

void
setDelay(int delay)

void
setMatcher(groovy.lang.Closure<java.lang.Boolean> matcher)

void
setSleep(int sleep)

void
setVariables(java.util.Map<java.lang.String,java.lang.Object> variables)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TestCaseActivityStub

public TestCaseActivityStub(groovy.lang.Closure<java.lang.Boolean> matcher,
                            groovy.lang.Closure<java.lang.String> completer)

Method Detail

getMatcher

public groovy.lang.Closure<java.lang.Boolean> getMatcher()

setMatcher

public void setMatcher(groovy.lang.Closure<java.lang.Boolean> matcher)

getCompleter

public groovy.lang.Closure<java.lang.String> getCompleter()

setCompleter

public void setCompleter(groovy.lang.Closure<java.lang.String> completer)

getVariables

public java.util.Map<java.lang.String,java.lang.Object> getVariables()

setVariables

public void setVariables(java.util.Map<java.lang.String,java.lang.Object> variables)

getSleep

public int getSleep()

setSleep

public void setSleep(int sleep)

getDelay

public int getDelay()

setDelay

public void setDelay(int delay)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2019 CenturyLink, Inc.

redpajama_set_name: RedPajamaGithub


text:
In this lesson we'll continue our journey with the PureScript type system by
looking at type classes, which will allow us to build richer types and leverage
tools we've seen before with our custom types.

This lesson is built upon chapter 6 of [PureScript by Example](https://leanpub.com/purescript/read#leanpub-auto-type-classes).
Be sure to check it out for a more in-depth look of everything covered.

[Slides](https://speakerdeck.com/jimf/purescript-lunch-n-learn-lesson-8)

## Getting Started

It is assumed that all of the following commands are operational:

- `node`
- `npm`
- `psc`
- `pulp`
- `bower`

If any of these are missing, be sure to go back and check out
[Lesson 1](https://github.com/jimf/purescript-lunchnlearn/tree/master/lesson01).
Then clone this repository and change directories to this lesson:

    $ cd some/directory
    $ git clone https://github.com/jimf/purescript-lunchnlearn.git
    $ cd purescript-lunchnlearn/lesson07
    $ bower install
    $ pulp psci
    > import Prelude
    > import Lesson.TypeClasses
    > import Data.Foldable

Take a look at the slides and [`src/Lesson/TypeClasses.purs`](src/Lesson/TypeClasses.purs)
and play around with code.

## What's New

### Type Classes

- Define implementations of functions that are ultimately specialized to a type
  - __Show__
    - Defines `show` for a type
  - __Eq__
    - Defines how `==` behaves for a type
  - __Ordering__
    - Defines `compare` for a type, which can then be used to define comparison operator behavior
  - __Field__
    - Defines how math operators behave for a type
  - __Semigroup__
    - Defines how `<>` (append) behaves for a type
  - __Monoid__
    - Semigroup that also defines how to create an "empty" element of the type
  - __Foldable__
    - Defines `foldl`, `foldr`, and `foldMap` for a type
    - `foldMap`, as one might expect at this point, operates like a `map` followed by a fold
  - __Functor__
    - Defines how `<$>` (map) behaves for a type


text:
var shortId = require('shortid');
var Maps = require('./maps');
var EventEmitter = require('events').EventEmitter;

/*
  Manage game logic
  Maintain a list of players and their positions
  Mainatin game state and broadcast changes
*/
function Match(options) {
  this.io = options.io;
  this.name = options.name;
  this.id = options.id || shortId.generate();

  this.endWhenEmpty = typeof options.endWhenEmpty === 'boolean' ? options.endWhenEmpty : true;

  // @todo support different game types
  this.type = options.type;

  this.mapName = options.mapName;

  this.players = [];
}

Match.prototype = Object.create(EventEmitter.prototype);

Match.prototype.start = function() {
  // @todo Hook into loop
  // @todo Stop when time is up

  // Load the map
  this.loadMap(this.mapName);

  // Emit start event
  this.emit('start', this);
};

Match.prototype.end = function() {
  // @todo Unhook from loop

  // Emit end event
  this.emit('end', this);
};

Match.prototype.restart = function() {
  this.emit('restart', this);

  this.start();
};

Match.prototype.loadMap = function(mapName) {
  var map = Maps[mapName];

  if (!map) {
    console.error('Map %s not found', mapName);
    return;
  }

  // Copy the map
  this.map = JSON.parse(JSON.stringify(map));

  // Send map
  this.io.to(this.id).emit('map', this.map);
};

Match.prototype.checkWinState = function() {
  var alienItemCount = 0;
  var humanItemCount = 0;

  var gameOver;
  var winReason = '';

  // Check if the moon was destroyed
  if (this.map.items.Moon.hp <= 0) {
    winReason = 'Moon was destroyed.';
  }

  // Check for human or alien items
  var item;
  for (var itemName in this.map.items) {
    item = this.map.items[itemName];

    if (item.hp > 0) {
      if (item.team === 'human') {
        humanItemCount++;
      }
      else if (item.team === 'alien') {
        alienItemCount++;
      }
    }
  }

  // If no more items remain
  if (!alienItemCount) {
    winReason = 'Aliens were defeated.';
    gameOver = true;
  }
  else if (!humanItemCount) {
    winReason = 'Humans were defeated.';
    gameOver = true;
  }

  if (gameOver) {
    console.log('Game over: %s', winReason);

    this.io.to(this.id).emit('gameOver', {
      reason: winReason
    });

    this.restart();
  }
  else {
    console.log('%d human items remain', humanItemCount);
    console.log('%d alien items remain', alienItemCount);
  }
};

Match.prototype.handle = function(eventName, player, data) {
  if (!data) {
    data = {};
  }

  // Add ID to every packet
  data.id = player.id;

  if (eventName === 'weaponHit') {
    var targetId = data.targetId;

    // Find out if it's an item or a player
    var targetItem = this.map.items[targetId];
    var targetPlayer = this.getPlayer(targetId);
    if (targetItem) {
      if (!targetItem.hp) {
        return;
      }

      // @todo make an instance and give takeHit method
      targetItem.hp -= 10;
      if (targetItem.hp <= 0) {
        console.log('Item %s was destroyed', targetId);

        this.io.to(this.id).emit('itemDestroyed', {
          attackerId: targetItem.id,
          targetId: targetId
        });

        this.checkWinState();
      }
      else {
        console.log('Item %s was hit, hp is now %d', targetId, targetItem.hp);

        this.io.to(this.id).emit('itemHit', {
          attackerId: player.id,
          targetId: targetId,
          hp: targetItem.hp
        });
      }
    }
    else if (targetPlayer) {
      if (!targetPlayer.hp) {
        return;
      }

      targetPlayer.takeHit(10, player.id);
      if (targetPlayer.hp <= 0) {
        console.log('Player %s was killed', targetPlayer);

        this.io.to(this.id).emit('playerDestroyed', {
          attackerId: player.id,
          targetId: targetId
        });

        // Respawn the player
        targetPlayer.respawn();

        this.checkWinState();
      }
      else {
        console.log('Player %s was hit, hp is now %d', targetPlayer, targetPlayer.hp);

        this.io.to(this.id).emit('playerHit', {
          attackerId: player.id,
          targetId: targetId,
          hp: targetPlayer.hp
        });
      }
    }
    else {
      console.error('Got hit on untracked entity '+targetId);
    }
  }
  else {
    // Re-broadcast to the entire match
    player.socket.broadcast.to(this.id).emit(eventName, data);
  }
};

Match.prototype.getPlayer = function(id) {
  // Store player
  var foundPlayer = null;
  this.players.some(function(player) {
    if (player.id === id) {
      foundPlayer = player;
      return true;
    }
  });

  return foundPlayer;
}

Match.prototype.join = function(player) {
  // Store player
  var index = this.players.indexOf(player);
  if (index !== -1) {
    console.error('Player %s tried to join match %s twice', player, this.id);
    return;
  }
  // Store the match
  player.match = this;

  // Join the room
  player.socket.join(this.id);

  // @todo Send map state
  player.socket.emit('map', this.map);

  // Send player list
  // @todo should this be sent as a list?
  this.players.forEach(function(otherPlayer) {
    player.socket.emit('joinMatch', otherPlayer.get('joinMatch'));

    player.socket.emit('joinTeam', otherPlayer.get('joinTeam'));

    player.socket.emit('state', otherPlayer.get('state'));
  });

  // Add to player list
  this.players.push(player);

  // Broadcast join that player has joined
  this.handle('joinMatch', player, {
    name: player.name
  });

  // Tell the player they have joined the match and give them their ID
  player.socket.emit('matchJoined', {
    id: player.id
  });

  console.log('Player %s has joined match %s', player, this.id);

  this.emit('playerJoined', this, player);
};

Match.prototype.leave = function(player) {
  // Leave the room
  player.socket.leave(this.id);

  player.match = null;

  // Remove player
  var index = this.players.indexOf(player);
  if (index === -1) {
    throw new Error('Requested to remove player from match, but player wasn\'t present!');
  }
  this.players.splice(index, 1);

  // Notify that player has left
  player.socket.broadcast.to(this.id).emit('leaveMatch', { id: player.id });

  console.log('Player %s has left match %s', player.id, this.id);

  this.emit('playerLeft', this, player);

  // End the match if everyone left
  if (this.endWhenEmpty && this.players.length === 0) {
    this.end();
  }
};

module.exports = Match;


text:
#include "stdafx.h"
#include "pge.h"
#include "private.h"

using namespace pge;

#define UPDATE_VIEW_MATRIX() {   \
	D3DXVECTOR3 Eye = D3DXVECTOR3(m_Eye.X, m_Eye.Y, m_Eye.Z);   \
	D3DXVECTOR3 LookAt = D3DXVECTOR3(m_LookAt.X, m_LookAt.Y, m_LookAt.Z);   \
	D3DXVECTOR3 Up = D3DXVECTOR3(m_Up.X, m_Up.Y, m_Up.Z);   \
	D3DXMatrixLookAtLH(m_pViewMatrix, &Eye, &LookAt, &Up); }

Camera::Camera()
{
	// Initialize matrices
	m_pViewMatrix = new Matrix();
	D3DXMatrixIdentity(m_pViewMatrix);
}

bool Camera::Create(Engine *ParentEngine)
{
	return SceneObject::Create(ParentEngine);
}

void Camera::Destroy()
{
	SafeDelete(m_pViewMatrix);

	// SceneObject::Destroy() must be called last
	SceneObject::Destroy();
}

void Camera::DrawObject()
{ }

void Camera::SetAllVectors(Vector3D Eye, Vector3D LookAt, Vector3D Up)
{
	m_Eye = Eye;
	m_LookAt = LookAt;
	m_Up = Up;

	UPDATE_VIEW_MATRIX();
}

void Camera::TranslateEyeVector(Vector3D Eye)
{
	m_Eye += Eye;

	UPDATE_VIEW_MATRIX();
}

void Camera::TranslateLookAtVector(Vector3D LookAt)
{
	m_LookAt += LookAt;

	UPDATE_VIEW_MATRIX();
}

void Camera::SetEyeVector(Vector3D Eye)
{
	m_Eye = Eye;

	UPDATE_VIEW_MATRIX();
}

void Camera::SetLookAtVector(Vector3D LookAt)
{
	m_LookAt = LookAt;

	UPDATE_VIEW_MATRIX();
}

void Camera::SetUpVector(Vector3D Up)
{
	m_Up = Up;

	UPDATE_VIEW_MATRIX();
}

Matrix *Camera::GetViewMatrix()
{
	return m_pViewMatrix;
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Net;
using System.Net.Mail;
using System.Web.Http;
using Skybrud.WebApi.Json;
using Skybrud.WebApi.Json.Meta;
using Umbraco.Core.Logging;
using Umbraco.Web;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi;
using Skybrud.PropertyEditors.ErrorHandling;

namespace Skybrud.PropertyEditors.NotifyPage {

    [PluginController("NotifyPage")]
    [JsonOnlyConfiguration]
    public class NotifyPageApiController : UmbracoAuthorizedApiController
    {

        public object GetSubscribersByPageId(int id)
        {
            try
            {
                return Request.CreateResponse(JsonMetaResponse.GetSuccess(GetSubscribers(id)));
            }
            catch (Exception ex)
            {
                var error = new Error("Server Error");
                LogHelper.Error<NotifyPageApiController>(error.ToString(), ex);
                return Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, error.Message, error));
            }
        }

        [HttpGet]
        public object SendMessages(int id)
        {

            try
            {
                var _helper = new UmbracoHelper(UmbracoContext.Current);

                var page = _helper.TypedContent(id);

                var subject = "subject";
                var subscribers = GetSubscribers(id);

                foreach (var subscriber in subscribers)
                {
                    // MailContent
                    var content = string.Format(@"Kære abbonnent,

Følgende side er blevet opdateret: {0}
", page.UrlWithDomain());

                    SendMail(subject, content, subscriber);
                }

                return Request.CreateResponse(JsonMetaResponse.GetSuccess(true));
            }
            catch(Exception ex)
            {
                var error = new Error("Server Error");
                LogHelper.Error<NotifyPageApiController>(error.ToString(), ex);
                return Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, error.Message, error));
            }
        }

        ///
        /// Get subscribers to a current page
        ///
        /// <param name="nodeId"></param>
        /// <returns></returns>
        private List<string> GetSubscribers(int nodeId)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ConnectionString;

            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlDataReader data;
                var output = new List<string>();
                using (var command = connection.CreateCommand())
                {
                    {
                        command.CommandText = "SELECT * FROM umbracoNodeSubscribers WHERE NodeId = @NodeId";
                        command.Parameters.AddWithValue("@NodeId", nodeId);

                        data = command.ExecuteReader();

                        if (data.HasRows)
                        {
                            while (data.Read())
                            {
                                output.Add(data.GetString(data.GetOrdinal("Email")));
                            }
                        }
                    }
                }

                return output;
            }
        }

        ///
        /// Send mails to subscribers
        ///
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="email"></param>
        private void SendMail(string subject, string body, string email)
        {

            MailMessage msg = new MailMessage
            {
                Subject = subject,
                From = new MailAddress("no-reply@your-website.com", "Your Mailbot"),
                IsBodyHtml = true,
                Body = (body ?? "").Trim()
            };

            msg.To.Add(new MailAddress(email));

            SmtpClient client = new SmtpClient();
            client.Send(msg);

        }
    }
}


text:
using System.Threading;
using Amazon.SQS.Model;
using NSubstitute;
using Xunit;

namespace JustSaying.UnitTests.AwsTools.MessageHandling.SqsNotificationListener
{
    public class WhenPassingAHandledAndUnhandledMessage : BaseQueuePollingTest
    {
        protected override void Given()
        {
            base.Given();
            Handler.Handle(null)
                .ReturnsForAnyArgs(info => true)
                .AndDoes(x => Thread.Sleep(1)); // Ensure at least one ms wait on processing
        }

        [Fact]
        public void MessagesGetDeserialisedByCorrectHandler()
        {
            SerialisationRegister.Received().DeserializeMessage(
                SqsMessageBody(MessageTypeString));
        }

        [Fact]
        public void ProcessingIsPassedToTheHandlerForCorrectMessage()
        {
            Handler.Received().Handle(DeserialisedMessage);
        }

        [Fact]
        public void MonitoringToldMessageHandlingTime()
        {
            Monitor.Received().HandleTime(Arg.Is<long>(x => x > 0));
        }

        [Fact]
        public void AllMessagesAreClearedFromQueue()
        {
            SerialisationRegister.Received(2).DeserializeMessage(Arg.Any<string>());

            Sqs.Received().DeleteMessageAsync(Arg.Any<DeleteMessageRequest>());
        }
    }

    /*
    Some more:
     * 1. Multiple handling of same message with different handlers
     * 2. etc
    */
}


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

class Producto_model extends CI_Model
{

    public function __construct()
    {
        parent::__construct();
    }

    public function getProductosBySublinea($id)
    {

        $productos = $this->db->get_where('producto', array(
            'sublinea' => $id,
            'estado' => 1
        ))->result();

        return $productos;
    }

    public function getProducto($id)
    {
        return $this->db->get_where('producto', array(
            'id' => $id
        ))->row();
    }

    public function getProductosRelacionados($id)
    {
        $producto = $this->getProducto($id);

        return $this->db->get_where('producto', array(
            'linea' => $producto->linea,
            'id !=' => $id
        ))->result();
    }

}


text:
from typing import Optional

from fastapi import Depends, FastAPI, Security
from fastapi.security import APIKeyQuery
from fastapi.testclient import TestClient
from pydantic import BaseModel

app = FastAPI()

api_key = APIKeyQuery(name="key", auto_error=False)

class User(BaseModel):
    username: str

def get_current_user(oauth_header: Optional[str] = Security(api_key)):
    if oauth_header is None:
        return None
    user = User(username=oauth_header)
    return user

@app.get("/users/me")
def read_current_user(current_user: Optional[User] = Depends(get_current_user)):
    if current_user is None:
        return {"msg": "Create an account first"}
    return current_user

client = TestClient(app)

openapi_schema = {
    "openapi": "3.0.2",
    "info": {"title": "FastAPI", "version": "0.1.0"},
    "paths": {
        "/users/me": {
            "get": {
                "responses": {
                    "200": {
                        "description": "Successful Response",
                        "content": {"application/json": {"schema": {}}},
                    }
                },
                "summary": "Read Current User",
                "operationId": "read_current_user_users_me_get",
                "security": [{"APIKeyQuery": []}],
            }
        }
    },
    "components": {
        "securitySchemes": {
            "APIKeyQuery": {"type": "apiKey", "name": "key", "in": "query"}
        }
    },
}

def test_openapi_schema():
    response = client.get("/openapi.json")
    assert response.status_code == 200, response.text
    assert response.json() == openapi_schema

def test_security_api_key():
    response = client.get("/users/me?key=secret")
    assert response.status_code == 200, response.text
    assert response.json() == {"username": "secret"}

def test_security_api_key_no_key():
    response = client.get("/users/me")
    assert response.status_code == 200, response.text
    assert response.json() == {"msg": "Create an account first"}


text:
.class Lcom/android/server/pm/Installer$1;
.super Ljava/lang/Object;
.source "Installer.java"

# interfaces
.implements Landroid/os/IBinder$DeathRecipient;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/pm/Installer;->connect()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/pm/Installer;

# direct methods
.method constructor <init>(Lcom/android/server/pm/Installer;)V
    .locals 0

    iput-object p1, p0, Lcom/android/server/pm/Installer$1;->this$0:Lcom/android/server/pm/Installer;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public binderDied()V
    .locals 2

    const-string/jumbo v0, "Installer"

    const-string/jumbo v1, "installd died; reconnecting"

    invoke-static {v0, v1}, Landroid/util/Slog;->w(Ljava/lang/String;Ljava/lang/String;)I

    iget-object v0, p0, Lcom/android/server/pm/Installer$1;->this$0:Lcom/android/server/pm/Installer;

    invoke-static {v0}, Lcom/android/server/pm/Installer;->-wrap0(Lcom/android/server/pm/Installer;)V

    return-void
.end method


text:
Profile

      <legend> Edit My Profile</legend>
      <form method="post" ng-submit="profile.updateProfile()">

           Username
          <input type="text" class="form-control" ng-model="profile.user.username" />

           Email Address
          <input type="email" class="form-control" ng-model="profile.user.email" />

				<button type="submit"
							class="btn-save btn"
							ng-class="{'btn-primary': !profile.btnSaved, 'btn-success': profile.btnSaved === true, 'btn-danger': profile.btnSaved === 'error' || profile.user.username === '' || profile.user.username === null}"
							ng-disabled="profile.user.username === '' || profile.user.username === null">
						 {{profile.btnSaveText}}
					</button>
      </form>

Characters

      {{profile.user}}

{{character.name}}

Armory

			<form method="post" ng-submit="profile.importCharacter()">

					 Character Name
					<input type="text" class="form-control" ng-model="profile.characterName" />

				<button type="submit"
							class="btn-save btn"
							ng-class="{'btn-primary': !profile.btnSaved, 'btn-success': profile.btnSaved === true, 'btn-danger': profile.btnSaved === 'error' || profile.characterName === '' || profile.characterName === null}"
							ng-disabled="profile.characterName === '' || profile.characterName === null">
						 {{profile.btnSaveText}}
					</button>
			</form>


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template min_assign</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.Accumulators">
<link rel="up" href="../../../numeric_operators_library_reference.html#header.boost.accumulators.numeric.functional_hpp" title="Header <boost/accumulators/numeric/functional.hpp>">
<link rel="prev" href="promote.html" title="Struct template promote">
<link rel="next" href="max_assign.html" title="Struct template max_assign">

Home
Libraries
People
FAQ
More

Struct template min_assign

boost::numeric::functional::min_assign

Synopsis

// In header: <boost/accumulators/numeric/functional.hpp>

template<typename Left, typename Right, typename LeftTag, typename RightTag>
struct min_assign :
  public boost::numeric::functional::min_assign_base< Left, Right, void >
{
};

Copyright © 2005, 2006 Eric Niebler

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
namespace DigiRazor.PasswordValidation.Factories
{
    public interface IPasswordRulesFactory
    {
        PasswordRules CreatePasswordRules();
    }
}


text:
package com.coveros.selenified.services.check;

import com.coveros.selenified.services.Response;
import com.coveros.selenified.utilities.Reporter;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.util.List;

/**
 * Verify will handle all verifications performed on the actual web services
 * calls themselves. These asserts are custom to the framework, and in addition to
 * providing easy object oriented capabilities, they assist in
 * troubleshooting and debugging failing tests.
 *
 * @author Max Saperstone
 * @version 3.3.1
 * @lastupdate 10/24/2019
 */
public class VerifyEquals extends Equals {

    /**
     * The default constructor passing in the app and output file
     *
     * @param response - the response from the web services call
     * @param reporter - the file to write all logging out to
     */
    public VerifyEquals(Response response, Reporter reporter) {
        this.response = response;
        this.reporter = reporter;
    }

    ///////////////////////////////////////////////////////
    // assertions about the page in general
    ///////////////////////////////////////////////////////

    /**
     * Verifies the actual response code is equals to the expected response
     * code, and writes that out to the output file.
     *
     * @param expectedCode - the expected response code
     */
    @Override
    public void code(int expectedCode) {
        checkCode(expectedCode);
    }

    /**
     * Verifies the actual response json payload is equal to the expected
     * response json payload, and writes that out to the output file.
     *
     * @param expectedJson - the expected response json object
     */
    @Override
    public void objectData(JsonObject expectedJson) {
        checkObjectData(expectedJson);
    }

    /**
     * Verifies the actual response json payload is equal to the expected
     * response json payload, and writes that out to the output file.
     *
     * @param expectedJson - the expected response json array
     */
    @Override
    public void arrayData(JsonArray expectedJson) {
        checkArrayData(expectedJson);
    }

    /**
     * Verifies the actual response json payload contains a key with a value equal to the expected
     * value. The jsonKeys should be passed in as crumbs of the keys leading to the field with
     * the expected value. This result will be written out to the output file.
     *
     * @param jsonKeys      - the crumbs of json object keys leading to the field with the expected value
     * @param expectedValue - the expected value
     */
    @Override
    public void nestedValue(List<String> jsonKeys, Object expectedValue) {
        checkNestedValue(jsonKeys, expectedValue);
    }

    /**
     * Verifies the actual response payload is equal to the expected
     * response payload, and writes that out to the output file.
     *
     * @param expectedMessage - the expected response message
     */
    @Override
    public void message(String expectedMessage) {
        checkMessage(expectedMessage);
    }

    /**
     * Verifies the actual response payload contains the number of elements
     * in an array as expected, and writes that out to the output file.
     *
     * @param expectedSize - the expected array size
     */
    @Override
    public void arraySize(int expectedSize) {
        checkArraySize(expectedSize);
    }

    /**
     * Verifies the actual response payload contains a key with a value of the number of elements
     * in an array as expected, and writes that out to the output file.
     *
     * @param expectedSize - the expected array size
     */
    @Override
    public void nestedArraySize(List<String> jsonKeys, int expectedSize) {
        checkNestedArraySize(jsonKeys, expectedSize);
    }
}


text:
<?php

namespace biz\behnke\jquery\ui\widgets;

use biz\behnke\jquery\ui\jQueryUI;
use biz\behnke\w3c\html\inline\A;

/**
 * Description of Button
 *
 * @author Marco Behnke <marco@behnke.biz>
 * @see http://jqueryui.com/demos/button/
 */
class Button extends jQueryUI
{

	protected $defConfig = array(
		'label' => 'My Button',
		'text' => true,
		'disabled' => false,
		'icons' => array('primary' => null, 'secondary' => null),
	);

	protected function __construct($match, $scope = null)
	{
		parent::__construct($match, $scope = null);
		$this->type(A::getInstance());
	}

}


text:
class ServerSocket : private Socket {
public:

    ServerSocket(int port);
    ServerSocket(){};
    virtual ~ServerSocket();

    const ServerSocket& operator << (const std::string&) const;
    const ServerSocket& operator >> (std::string&) const;

    void accept(ServerSocket&);

};

#endif


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Twice.Models.Scheduling;
using Twice.Models.Scheduling.Processors;
using Twice.Models.Twitter;

namespace Twice.Tests.Models.Scheduling.Processors
{
	[TestClass, ExcludeFromCodeCoverage]
	public class CreateStatusProcessorTests
	{
		[TestMethod, TestCategory( "Models.Scheduling.Processors" )]
		[SuppressMessage( "ReSharper", "PossibleMultipleEnumeration" )]
		public async Task ImagesAreUploaded()
		{
			try
			{
				// Arrange
				File.WriteAllBytes( "file1.png", new byte[] { 1, 2, 3, 4 } );
				File.WriteAllBytes( "file2.bmp", new byte[] { 5, 6, 7, 8 } );

				var ctx1 = new Mock<IContextEntry>();
				ctx1.Setup( c => c.UserId ).Returns( 1 );
				ctx1.Setup( c => c.Twitter.UploadMediaAsync( new byte[] { 1, 2, 3, 4 }, "image/png", new[] { 2ul } ) )
					.Returns( Task.FromResult( new LinqToTwitter.Media { MediaID = 888 } ) )
					.Verifiable();
				ctx1.Setup( c => c.Twitter.UploadMediaAsync( new byte[] { 5, 6, 7, 8 }, "image/bmp", new[] { 2ul } ) )
					.Returns( Task.FromResult( new LinqToTwitter.Media { MediaID = 999 } ) )
					.Verifiable();

				Func<IEnumerable<ulong>, bool> mediaCheck = ids => ids.Contains( 888ul ) && ids.Contains( 999ul );
				ctx1.Setup( c => c.Twitter.Statuses.TweetAsync( It.IsAny<string>(), It.Is<IEnumerable<ulong>>( ids => mediaCheck( ids ) ), It.IsAny<ulong>() ) )
					.Returns( Task.FromResult( DummyGenerator.CreateDummyStatus() ) )
					.Verifiable();

				var ctx2 = new Mock<IContextEntry>();
				ctx2.Setup( c => c.UserId ).Returns( 2 );
				ctx2.Setup( c => c.Twitter.Statuses.TweetAsync( It.IsAny<string>(), It.Is<IEnumerable<ulong>>( ids => mediaCheck( ids ) ), It.IsAny<ulong>() ) )
					.Returns( Task.FromResult( DummyGenerator.CreateDummyStatus() ) )
					.Verifiable();

				var contextList = new Mock<ITwitterContextList>();
				contextList.Setup( c => c.Contexts ).Returns( new[] { ctx1.Object, ctx2.Object } );

				var config = new Mock<ITwitterConfiguration>();
				config.SetupGet( c => c.MaxImageSize ).Returns( int.MaxValue );

				var proc = new CreateStatusProcessor( contextList.Object, config.Object );

				var job = new SchedulerJob
				{
					FilesToAttach = new List<string> { "file1.png", "file2.bmp" },
					AccountIds = new List<ulong> { 1, 2 }
				};

				// Act
				await proc.Process( job );

				// Assert
				ctx1.Verify( c => c.Twitter.UploadMediaAsync( new byte[] { 1, 2, 3, 4 }, "image/png", new[] { 2ul } ), Times.Once() );
				ctx1.Verify( c => c.Twitter.UploadMediaAsync( new byte[] { 5, 6, 7, 8 }, "image/bmp", new[] { 2ul } ), Times.Once() );

				ctx1.Verify( c => c.Twitter.Statuses.TweetAsync( It.IsAny<string>(), It.Is<IEnumerable<ulong>>( ids => mediaCheck( ids ) ), It.IsAny<ulong>() ),
					Times.Once() );
				ctx2.Verify( c => c.Twitter.Statuses.TweetAsync( It.IsAny<string>(), It.Is<IEnumerable<ulong>>( ids => mediaCheck( ids ) ), It.IsAny<ulong>() ),
					Times.Once() );
			}
			finally
			{
				File.Delete( "file1.png" );
				File.Delete( "file2.bmp" );
			}
		}

		[TestMethod, TestCategory( "Models.Scheduling.Processors" )]
		public async Task TooBigImageIsNotUploaded()
		{
			try
			{
				// Arrange
				File.WriteAllBytes( "file3.png", new byte[] { 1 } );

				var ctx1 = new Mock<IContextEntry>();
				ctx1.Setup( c => c.UserId ).Returns( 1 );
				ctx1.Setup( c => c.Twitter.UploadMediaAsync( It.IsAny<byte[]>(), It.IsAny<string>(), It.IsAny<IEnumerable<ulong>>() ) )
					.Returns( Task.FromResult( new LinqToTwitter.Media() ) )
					.Verifiable();

				var config = new Mock<ITwitterConfiguration>();
				config.SetupGet( c => c.MaxImageSize ).Returns( 0 );

				var contextList = new Mock<ITwitterContextList>();
				contextList.Setup( c => c.Contexts ).Returns( new[] { ctx1.Object } );

				var proc = new CreateStatusProcessor( contextList.Object, config.Object );

				var job = new SchedulerJob
				{
					FilesToAttach = new List<string> { "file3.png" }
				};

				// Act
				await proc.Process( job );

				// Assert
				ctx1.Verify( c => c.Twitter.UploadMediaAsync( It.IsAny<byte[]>(), It.IsAny<string>(), It.IsAny<IEnumerable<ulong>>() ), Times.Never() );
			}
			finally
			{
				File.Delete( "file3.png" );
			}
		}

		[TestMethod, TestCategory( "Models.Scheduling.Processors" )]
		public async Task TweetIsSend()
		{
			// Arrange
			var ctx1 = new Mock<IContextEntry>();
			ctx1.Setup( c => c.UserId ).Returns( 1 );
			ctx1.Setup( c => c.Twitter.Statuses.TweetAsync( "hello world", It.IsAny<IEnumerable<ulong>>(), 111 ) )
				.Returns( Task.FromResult( DummyGenerator.CreateDummyStatus() ) )
				.Verifiable();

			var ctx2 = new Mock<IContextEntry>();
			ctx2.Setup( c => c.UserId ).Returns( 2 );
			ctx2.Setup( c => c.Twitter.Statuses.TweetAsync( "hello world", It.IsAny<IEnumerable<ulong>>(), 111 ) )
				.Returns( Task.FromResult( DummyGenerator.CreateDummyStatus() ) )
				.Verifiable();

			var contextList = new Mock<ITwitterContextList>();
			contextList.Setup( c => c.Contexts ).Returns( new[] { ctx1.Object, ctx2.Object } );

			var job = new SchedulerJob
			{
				AccountIds = new List<ulong> { 1, 2 },
				Text = "hello world",
				InReplyToStatus = 111
			};

			var config = new Mock<ITwitterConfiguration>();
			var proc = new CreateStatusProcessor( contextList.Object, config.Object );

			// Act
			await proc.Process( job );

			// Assert
			ctx1.Verify( c => c.Twitter.Statuses.TweetAsync( "hello world", It.IsAny<IEnumerable<ulong>>(), 111 ), Times.Once() );
			ctx2.Verify( c => c.Twitter.Statuses.TweetAsync( "hello world", It.IsAny<IEnumerable<ulong>>(), 111 ), Times.Once() );
		}

		[TestMethod, TestCategory( "Models.Scheduling.Processors" )]
		public async Task UnknownAccountIsNotUsedForTweeting()
		{
			// Arrange
			var job = new SchedulerJob
			{
				AccountIds = new List<ulong> { 3 },
				Text = "test"
			};

			var ctx1 = new Mock<IContextEntry>();
			ctx1.Setup( c => c.UserId ).Returns( 1 );
			ctx1.Setup( c => c.Twitter.Statuses.TweetAsync( "test", It.IsAny<IEnumerable<ulong>>(), 0 ) )
				.Returns( Task.FromResult( DummyGenerator.CreateDummyStatus() ) )
				.Verifiable();

			var contextList = new Mock<ITwitterContextList>();
			contextList.Setup( c => c.Contexts ).Returns( new[] { ctx1.Object } );

			var config = new Mock<ITwitterConfiguration>();
			var proc = new CreateStatusProcessor( contextList.Object, config.Object );

			// Act
			await proc.Process( job );

			// Assert
			ctx1.Verify( c => c.Twitter.Statuses.TweetAsync( "test", It.IsAny<IEnumerable<ulong>>(), 0 ), Times.Never() );
		}
	}
}


text:
#include "third_party/android_prediction/suggest/policyimpl/dictionary/utils/sparse_table.h"

namespace latinime {

const int SparseTable::NOT_EXIST = -1;
const int SparseTable::INDEX_SIZE = 4;

bool SparseTable::contains(const int id) const {
    const int readingPos = getPosInIndexTable(id);
    if (id < 0 || mIndexTableBuffer->getTailPosition() <= readingPos) {
        return false;
    }
    const int index = mIndexTableBuffer->readUint(INDEX_SIZE, readingPos);
    return index != NOT_EXIST;
}

uint32_t SparseTable::get(const int id) const {
    const int indexTableReadingPos = getPosInIndexTable(id);
    const int index = mIndexTableBuffer->readUint(INDEX_SIZE, indexTableReadingPos);
    const int contentTableReadingPos = getPosInContentTable(id, index);
    if (contentTableReadingPos < 0
            || contentTableReadingPos >= mContentTableBuffer->getTailPosition()) {
        AKLOGE("contentTableReadingPos(%d) is invalid. id: %d, index: %d",
                contentTableReadingPos, id, index);
        return NOT_A_DICT_POS;
    }
    const int contentValue = mContentTableBuffer->readUint(mDataSize, contentTableReadingPos);
    return contentValue == NOT_EXIST ? NOT_A_DICT_POS : contentValue;
}

bool SparseTable::set(const int id, const uint32_t value) {
    const int posInIndexTable = getPosInIndexTable(id);
    // Extends the index table if needed.
    int tailPos = mIndexTableBuffer->getTailPosition();
    while (tailPos <= posInIndexTable) {
        if (!mIndexTableBuffer->writeUintAndAdvancePosition(NOT_EXIST, INDEX_SIZE, &tailPos)) {
            AKLOGE("cannot extend index table. tailPos: %d to: %d", tailPos, posInIndexTable);
            return false;
        }
    }
    if (contains(id)) {
        // The entry is already in the content table.
        const int index = mIndexTableBuffer->readUint(INDEX_SIZE, posInIndexTable);
        if (!mContentTableBuffer->writeUint(value, mDataSize, getPosInContentTable(id, index))) {
            AKLOGE("cannot update value %d. pos: %d, tailPos: %d, mDataSize: %d", value,
                    getPosInContentTable(id, index), mContentTableBuffer->getTailPosition(),
                    mDataSize);
            return false;
        }
        return true;
    }
    // The entry is not in the content table.
    // Create new entry in the content table.
    const int index = getIndexFromContentTablePos(mContentTableBuffer->getTailPosition());
    if (!mIndexTableBuffer->writeUint(index, INDEX_SIZE, posInIndexTable)) {
        AKLOGE("cannot write index %d. pos %d", index, posInIndexTable);
        return false;
    }
    // Write a new block that containing the entry to be set.
    int writingPos = getPosInContentTable(0 /* id */, index);
    for (int i = 0; i < mBlockSize; ++i) {
        if (!mContentTableBuffer->writeUintAndAdvancePosition(NOT_EXIST, mDataSize,
                &writingPos)) {
            AKLOGE("cannot write content table to extend. writingPos: %d, tailPos: %d, "
                    "mDataSize: %d", writingPos, mContentTableBuffer->getTailPosition(), mDataSize);
            return false;
        }
    }
    return mContentTableBuffer->writeUint(value, mDataSize, getPosInContentTable(id, index));
}

int SparseTable::getIndexFromContentTablePos(const int contentTablePos) const {
    return contentTablePos / mDataSize / mBlockSize;
}

int SparseTable::getPosInIndexTable(const int id) const {
    return (id / mBlockSize) * INDEX_SIZE;
}

int SparseTable::getPosInContentTable(const int id, const int index) const {
    const int offset = id % mBlockSize;
    return (index * mBlockSize + offset) * mDataSize;
}

} // namespace latinime


text:
<component name="libraryTable">
  <library name="exposed-instrumentation-api-publish-0.5">
    <CLASSES>
      <root url="jar://$USER_HOME$/.android/build-cache/7bd37416bf0aa050776a82d2d435797d783b3d01/output/jars/classes.jar!/" />
      <root url="file://$USER_HOME$/.android/build-cache/7bd37416bf0aa050776a82d2d435797d783b3d01/output/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$ANDROID_HOME$/extras/android/m2repository/com/android/support/test/exposed-instrumentation-api-publish/0.5/exposed-instrumentation-api-publish-0.5-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
import os.path, sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

from auth.mytransport_access import auth_mytransport
CLIENT_ID = "781b4b4a-5921-4e90-ad34-ce4bfb9912c5"
CLIENT_SECRET = "0lXwudYL6HdSdsQwSxQcFAxbLjh56PEls9Jiq3NGaSE="
API_URL = "https://platform.whereismytransport.com"
API_AUTH_URL = "https://identity.whereismytransport.com/connect/token"
ACCESS_TOKEN = auth_mytransport()


text:
CALL login('dba','') ON CLASS db_user;
CREATE CLASS DCL1 (id INTEGER);
INSERT INTO DCL1(id) VALUES(1);
CREATE CLASS DCL2 (id INTEGER);
INSERT INTO DCL2(id) VALUES(1);

CALL add_user('DCL_USER1','DCL1') ON CLASS db_user;
GRANT UPDATE, SELECT ON DCL1, DCL2 TO DCL_USER1;
CALL login('DCL_USER1','DCL1') ON CLASS db_user;
UPDATE dba.DCL1 SET id=2 WHERE id=1;
UPDATE dba.DCL2 SET id=2 WHERE id=1;
CALL login('dba','') ON CLASS db_user;
CALL drop_user('DCL_USER1') ON CLASS db_user;

DROP CLASS DCL1, DCL2;

--+ holdcas off;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>hr.lowcostflights</groupId>
	<artifactId>low-cost-flights</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>low-cost-flights</name>
	<description>Simple low-cost flight search web application</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.3.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-rest</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.2</version>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.datatype</groupId>
			<artifactId>jackson-datatype-jsr310</artifactId>
			<version>2.7.3</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.datatype</groupId>
			<artifactId>jackson-datatype-joda</artifactId>
			<version>2.7.3</version>
		</dependency>
		<dependency>
			<groupId>org.neo4j</groupId>
			<artifactId>neo4j-cypher-compiler-2.1</artifactId>
			<version>2.1.8</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<executable>true</executable>
					<jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
package org.datasays.wes.actions;

import okhttp3.HttpUrl;
import org.datasays.wes.core.RequestInfo;
import org.datasays.wes.types.*;
// documentation: https://www.elastic.co/guide/en/elasticsearch/reference/5.x/cat-repositories.html
public class CatRepositories extends RequestInfo{

	public CatRepositories(String baseUrl){
		super(baseUrl);
	}
	public CatRepositories(HttpUrl baseUrl){
		super(baseUrl);
	}

	// param: string format: a short version of the Accept header, e.g. json, yaml
	public CatRepositories format(String format){
		addParams("format", format);
		return this;
	}
	// param: boolean local: Return local information, do not retrieve the state from master node
	public CatRepositories local(boolean local){
		addParams("local", local);
		return this;
	}
	// param: time masterTimeout: Explicit operation timeout for connection to master node
	public CatRepositories masterTimeout(long masterTimeout){
		addParams("masterTimeout", masterTimeout);
		return this;
	}
	// param: list h: Comma-separated list of column names to display
	public CatRepositories h(String h){
		addParams("h", h);
		return this;
	}
	// param: boolean help: Return help information
	public CatRepositories help(boolean help){
		addParams("help", help);
		return this;
	}
	// param: list s: Comma-separated list of column names or column aliases to sort by
	public CatRepositories s(String s){
		addParams("s", s);
		return this;
	}
	// param: boolean v: Verbose mode. Display column headers
	public CatRepositories v(boolean v){
		addParams("v", v);
		return this;
	}
	// body:null
	@Override
	public void setBody(Object body) {
		super.setBody(body);
	}

	public CatRepositories setParts(){

		return this;
	}

	@Override
	public String parseUrl(String method) {
		if(!"GET".equalsIgnoreCase(method)){
			throw new IllegalArgumentException("Unsupported method:"+method);
		}
		//=>/_cat/repositories
		setUrl("_cat", "repositories");
		return super.parseUrl(method);

	}
}


text:
lychee.define('lychee.net.Client').tags({
	platform: 'html'
}).includes([
	'lychee.event.Emitter'
]).supports(function(lychee, global) {

	if (
		typeof WebSocket !== 'undefined'
	) {
		return true;
	}

	return false;

}).exports(function(lychee, global) {

	/*
	 * HELPERS
	 */

	var _receive_handler = function(blob, isBinary) {

		var data = null;
		try {
			data = this.__decoder(blob);
		} catch(e) {
			// Unsupported data encoding
			return false;
		}

		if (
			data instanceof Object
			&& typeof data._serviceId === 'string'
		) {

			var service = _get_service_by_id.call(this, data._serviceId);
			var method  = data._serviceMethod || null;

			if (
				service !== null
				&& method !== null
				&& method.charAt(0) !== '@'
			) {

				if (
					   typeof service.trigger === 'function'
					|| typeof service[method] === 'function'
				) {

					// Remove data frame service header
					delete data._serviceId;
					delete data._serviceMethod;

					if (typeof service.trigger === 'function') {
						service.trigger(method, [ data ]);
					}

					if (typeof service[method] === 'function') {
						service[method](data);
					}

				}

			} else if (method.charAt(0) === '@') {

				if (method === '@plug') {
					_plug_service.call(this, data._serviceId, service);
				} else if (method === '@unplug') {
					_unplug_service.call(this, data._serviceId, service);
				}

			}

		} else {

			this.trigger('receive', [ data ]);

		}

		return true;

	};

	var _is_service_waiting = function(service) {

		for (var w = 0, wl = this.__services.waiting.length; w < wl; w++) {

			if (this.__services.waiting[w] === service) {
				return true;
			}

		}

		return false;

	};

	var _is_service_active = function(service) {

		for (var a = 0, al = this.__services.active.length; a < al; a++) {

			if (this.__services.active[a] === service) {
				return true;
			}

		}

		return false;

	};

	var _get_service_by_id = function(id) {

		var service;

		for (var w = 0, wl = this.__services.waiting.length; w < wl; w++) {

			service = this.__services.waiting[w];
			if (service.getId() === id) {
				return service;
			}

		}

		for (var a = 0, al = this.__services.active.length; a < al; a++) {

			service = this.__services.active[a];
			if (service.getId() === id) {
				return service;
			}

		}

		return null;

	};

	var _plug_service = function(id, service) {

		id = typeof id === 'string' ? id : null;

		if (
			   id === null
			|| service === null
		) {
			return;
		}

		var found = false;

		for (var w = 0, wl = this.__services.waiting.length; w < wl; w++) {

			if (this.__services.waiting[w] === service) {
				this.__services.waiting.splice(w, 1);
				found = true;
				wl--;
			}

		}

		if (found === true) {

			if (lychee.debug === true) {
				console.log('lychee.net.Client: Remote plugged in Service (' + id + ')');
			}

			this.__services.active.push(service);
			service.init && service.init();

		}

	};

	var _unplug_service = function(id, service) {

		id = typeof id === 'string' ? id : null;

		if (
			   id === null
			|| service === null
		) {
			return;
		}

		for (var a = 0, al = this.__services.active.length; a < al; a++) {

			if (this.__services.active[a] === service) {
				this.__services.active.splice(a, 1);
				al--;
			}

		}

		if (lychee.debug === true) {
			console.log('lychee.net.Client: Remote unplugged Service (' + id + ')');
		}

	};

	/*
	 * IMPLEMENTATION
	 */

	var Class = function(encoder, decoder) {

		encoder = encoder instanceof Function ? encoder : function(blob) { return blob; };
		decoder = decoder instanceof Function ? decoder : function(blob) { return blob; };

		this.__encoder = encoder;
		this.__decoder = decoder;
		this.__socket  = null;
		this.__services  = {
			waiting: [], // Waiting Services need to be verified from Remote
			active:  []  // Active Services for allowed interaction
		};

		this.__isBinary  = false;
		this.__isRunning = false;

		lychee.event.Emitter.call(this);

	};

	Class.prototype = {

		listen: function(port, host) {

			port = typeof port === 'number' ? port : 1337;
			host = typeof host === 'string' ? host : 'localhost';

			if (this.__isRunning === true) {
				return false;
			}

			if (lychee.debug === true) {
				console.log('lychee.net.Client: Listening on ' + host + ':' + port);
			}

			var url = 'ws://' + host + ':' + port;

			this.__socket = new WebSocket(url);

			if (
				typeof ArrayBuffer !== 'undefined'
				&& typeof this.__socket.binaryType !== 'undefined'
			) {
				this.__socket.binaryType = 'arraybuffer';
				this.__isBinary = true;
			}

			var that = this;

			this.__socket.onopen = function() {

				that.__isRunning = true;
				that.trigger('connect');

			};

			this.__socket.onmessage = function(event) {

				var blob = null;
				if (
					that.__isBinary === true
					&& event.data instanceof ArrayBuffer
				) {

					var bytes = new Uint8Array(event.data);
					blob = String.fromCharCode.apply(null, bytes);

					_receive_handler.call(that, blob, true);

				} else {

					blob = event.data;

					_receive_handler.call(that, blob, false);

				}

			};

			// WebSocket Close frame is standardized,
			// no deserialization required.

			this.__socket.onclose = function(event) {

				that.__isRunning = false;
				that.trigger('disconnect', [ event.code, event.reason ]);

			};

			return true;

		},

		send: function(data, service) {

			data    = data instanceof Object    ? data    : null;
			service = service instanceof Object ? service : null;

			if (
				data === null
				|| this.__isRunning === false
			) {
				return false;
			}

			if (service !== null) {

				data._serviceId     = service.id     || null;
				data._serviceMethod = service.method || null;

			}

			var blob = this.__encoder(data);
			if (this.__isBinary === true) {

				var bl    = blob.length;
				var bytes = new Uint8Array(bl);

				for (var b = 0; b < bl; b++) {
					bytes[b] = blob.charCodeAt(b);
				}

				blob = bytes.buffer;

			}

			this.__socket.send(blob);

			return true;

		},

		disconnect: function() {

			if (this.__isRunning === true) {

				this.__socket.close();

				return true;

			}

			return false;

		},

		plug: function(service) {

			if (
				   _is_service_waiting.call(this, service) === false
				&& _is_service_active.call(this, service) === false
			) {

				this.__services.waiting.push(service);

				// Please, Remote, plug Service! PING
				this.send({}, {
					id: service.getId(),
					method: '@plug'
				});

				return true;

			}

			return false;

		},

		unplug: function(service) {

			if (
				   _is_service_waiting.call(this, service) === true
				|| _is_service_active.call(this, service) === true
			) {

				// Please, Remote, unplug Service! PING
				this.send({}, {
					id: service.getId(),
					method: '@unplug'
				});

				return true;

			}

			return false;

		}

	};

	return Class;

});


text:
<?php

function () {
	if (doSomething('veryyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy long') && true) {

	}

	while (doSomething('short') && true) {

	}

	do {

	} while (
		doSomething('veryyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy long') && true
	);

	if (
		doSomething('') && true
	) { // Too looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong fucking comment

	}

	if (
		doSomething('')
		// Comment
		&& doAnything()
	) {

	}
};


text:
<?php

if ($this->config->item('use_username', 'tank_auth')) {
	$login_label = 'Email or login';
} else {
	$login_label = 'Email';
}

$login = array(
	'name'	=> 'login',
	'id'	=> 'login',
	'value' => set_value('login'),
	'maxlength'	=> 80,
	'size'	=> 30,
	'placeholder' => $login_label,
	'class' => 'form-control'
);

?>

        <?php echo form_open($this->uri->uri_string(),' class="form-signin form-login" '); ?>
            <?php echo form_input($login); ?>
            <?php echo form_error($login['name']); ?><?php echo isset($errors[$login['name']])?$errors[$login['name']]:''; ?>

            <?php echo form_submit('reset', 'Get a new password','class="btn btn-lg btn-default btn-block btn-login"'); ?>

		<?php echo form_close(); ?>


text:
int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([MemoRealAppDelegate class]));
    }
}


text:
    var   cmds = require('../')
        , fs = require('graceful-fs')
        , path = require('path')
        , cmd = require('../../util/process')
        , haxelib = require('../../util/haxelib')
        , util = require('../../util/util')
        , bars = require('handlebars')
        , fse = require('fs-extra')

var internal = {};

exports.post_build = function(flow, done) {

    flow.log(3,'build - running cpp post process');

    if(flow.target_desktop) {
        flow.log(3,'build - cpp - target desktop post build');
        internal.post_build_desktop(flow, done);
    } else if(flow.target_mobile) {
        flow.log(3,'build - cpp - target mobile post build');
        internal.post_build_mobile(flow, done);
    } else {
        flow.log(3,'build - cpp - non desktop/mobile post build');
        if(done) done();
    }

} //post_build

exports.ios_combine_archs = function(flow, done) {

    if(flow.flags.archs) {

        var archs = flow.flags.archs.split(',');
            archs = archs.map(function(a){ return flow.project.adjust_arch(flow, a.trim()) });

        flow.log(2, "build - ios - combining multiple archs into one", archs);

        var dest = flow.project.get_path_binary_dest_full(flow, flow.project.prepared, 'fat');
            fse.ensureFileSync(dest);

        var args = ['-sdk','iphoneos', 'lipo',
                    '-output', dest,
                    '-create'];

        var input_list = archs.map(function(a){
            var binary_source = flow.project.get_path_binary_name_source(flow, flow.project.prepared, a);
            var source_path = util.normalize(path.join(flow.project.paths.build, 'cpp/' + binary_source));
            return source_path;
        });

        args = args.concat(input_list);

        cmd.exec(flow, 'xcrun', args, { quiet:false }, function(code,out,err){
            if(done) {
                done(code);
            }
        });

        return;

    } else { //if multiple archs

        if(done) {
            done();
        }

    }

} //ios_combine_archs

internal.post_build_mobile = function(flow, done) {

    //run platform specific build chains
    if(flow.target == 'android') {
        return internal.build_android(flow, done);
    }

    if(flow.target == 'ios') {
        return exports.ios_combine_archs(flow, done);
    } //ios

        //other platforms end here
    if(done) {
        done();
    }

} //post_build_mobile

    //runs ant, and such
internal.build_android = function(flow, done) {
    done();
}

internal.build_androidold = function(flow, done) {

    //handle ability to compile store build, vs debug test build
    // var build_type = flow.project.prepared.source.project.app.mobile.android.build_type;
    var build_type = flow.flags['android-build-type'] || 'debug';

        //where to build from
    var project_root = path.join(flow.project.paths.build, flow.config.build.android.project);
        //a build file to remove
    var build_meta_file = path.join(project_root,'bin/build.prop');

        //remove build meta data to ensure build happens
    if(fs.existsSync(build_meta_file)) {
        fs.unlinkSync(build_meta_file);
    }

    var args = [build_type];
    var opt = {
        cwd: project_root,
        quiet:false
    }

            if(flow.timing) console.time('build - android - ant');

    var ant_path = util.normalize(flow.config.build.android.ant_path);

    flow.log(2, 'build - android - using ant at %s', ant_path);

    if(!fs.existsSync(ant_path)) {
        flow.log(1, 'build - android - cannot find ant at specified path %s', ant_path );
        flow.project.failed = true;
        return flow.finished();
    }

    try {

        cmd.exec(flow, ant_path, args, opt, function(code,out,err){

                if(flow.timing) console.timeEnd('build - android - ant');

            if(code != 0) {
                flow.log(1,'build - android - stopping because ant failed to build, exit code %d', code);
                flow.project.failed = true;
                return flow.finished();
            }

                //now move the apk out into the user bin folder
            var apk_name = flow.project.prepared.source.project.app.name + '-' + build_type + '.apk';
            var apk_path = path.join(project_root, 'bin/' + apk_name);
            var apk_dest = path.join(flow.project.paths.output, apk_name);

            if(!fs.existsSync(apk_path)) {

                flow.log(1,'build - android - cannot copy build to output path!');
                flow.log(1,'build - android - missing file because %s build failed to generate an apk:', build_type, apk_path);
                flow.project.failed = true;
                return flow.finished();

            } else {

                    if(flow.timing) console.time('build - apk copy');
                util.copy_path(flow, apk_path, apk_dest);
                    if(flow.timing) console.timeEnd('build - apk copy');

                if(done) {
                    done(code,out,err);
                }

            }

        });

    } catch(e) {
        flow.log(1, 'build - android - cannot execute ant', e );
        return done('cannot execute ant...', null);
    }

} //build_android

internal.post_build_desktop = function(flow, done) {

    if(flow.system == 'mac' || flow.system == 'linux') {

                if(flow.timing) console.time('build - binary chmod');

        cmd.exec(flow, 'chmod', ['+x',flow.project.paths.binary.full], {quiet:true}, function(code,out,err){

                if(flow.timing) console.timeEnd('build - binary chmod');

            if(done) {
                done(code,out,err);
            }

        }); //exec

    } else {

        if(done) {
            done();
        }

    }

} //post_build_desktop

internal.move_binary = function(flow, target_arch) {

    if(flow.target == 'ios') return;

    target_arch = target_arch || flow.target_arch;

    var binary_source = flow.project.get_path_binary_name_source(flow, flow.project.prepared, target_arch);
    var source_path = util.normalize(path.join(flow.project.paths.build, 'cpp/' + binary_source));
    var binary_dest_full = flow.project.get_path_binary_dest_full(flow, flow.project.prepared, target_arch);

    flow.log(3,'build - moving binary for %s from %s to %s', target_arch, source_path, binary_dest_full);

        if(flow.timing) console.time('build - binary copy');

    util.copy_path(flow, source_path, binary_dest_full);

        if(flow.timing) console.timeEnd('build - binary copy');

} //move_binary

internal.build_hxcpp_arch_list = function(flow, arch_list, run_path, hxcpp_file, done ) {

    //no list?
    if(!arch_list) {
        if(done) done();
        return;
    }

        //no more left in list?
    if(arch_list.length <= 0) {
        if(done) done();
        return;
    }

        //remove current arch from list
    var curr_arch = arch_list.shift();

    exports.build_hxcpp(flow, curr_arch, run_path, hxcpp_file, function(err) {

        if(err) {
            flow.log(1, '\n build - stopping because of errors in hxcpp compile, while building arch %s \n', curr_arch);
            flow.project.failed = true;
            return flow.finished();
        }

            //for now lib based projects don't do this step
        if(!flow.project.parsed.project.lib) {
            if(!internal.set_haxe_output) {
                internal.move_binary(flow, curr_arch);
            }
        }

        internal.build_hxcpp_arch_list(flow, arch_list, run_path, hxcpp_file, done);

    }); //run hxcpp

} //build_hxcpp_arch_list

exports.run_hxcpp = function(flow, run_path, hxcpp_file, done) {

    //building multiple archs?
    var archs = [flow.target_arch];

    if(flow.flags.archs) {
        archs = flow.flags.archs.split(',');
        archs = archs.map(function(a){ return flow.project.adjust_arch(flow, a.trim()); });
        flow.log(2, 'build - building multiple archs', archs);
    } else {
            //just build the normal one
        archs = [flow.target_arch];
    }

    internal.build_hxcpp_arch_list(flow, archs, run_path, hxcpp_file, done );

} //run_hxcpp

exports.post_haxe = function(flow, done) {

    var cpp_path = path.join(flow.project.paths.build, 'cpp/');
        cpp_path = path.resolve(flow.project.root, cpp_path);

    internal.set_haxe_output = flow.project.prepared.defines_list.indexOf('set_haxe_output') != -1;

        //write custom xml
    exports.write_hxcpp(flow, cpp_path);

        //build against it
    exports.run_hxcpp(flow, cpp_path, 'flow.Build.xml', done);

} //exports

    //write out the hxcpp file from the flow project into the build folder
exports.write_hxcpp = function(flow, run_path) {

    var dest_file = path.join(run_path,'flow.Build.xml');
    var src_template = path.join(__dirname, 'cpp/flow.Build.xml');

    var context = {
        includes : {
            __haxe : {
                name:'__haxe', file:'Build.xml', path:'Build.xml',
                source:'flow internal', internal:true
            }
        }
    };

    if(flow.project.prepared.hxcpp.includes) {
        for(name in flow.project.prepared.hxcpp.includes) {
            context.includes[name] = flow.project.prepared.hxcpp.includes[name];
        }
    }

    var template_content = fs.readFileSync(src_template, 'utf8');
    var template = bars.compile(template_content);
    var result = template(context);

    fse.ensureFileSync(dest_file);
    fs.writeFileSync(dest_file, result, 'utf8');

        //now, for each of the includes
        //copy them over with a special context
        //that will allow them to know their source

    for(include in context.includes) {

            var node = context.includes[include];

        if(!node.internal) {
            if(fs.existsSync(node.path)) {

                var inc_context = { FLOW_SOURCE:path.dirname(node.path) };
                var inc_content = fs.readFileSync(node.path,'utf8');
                var inc_template = bars.compile(inc_content);
                var inc_result = inc_template(inc_context);

                var inc_dest = path.join(run_path, node.file);

                fse.ensureFileSync(inc_dest);
                fs.writeFileSync(inc_dest, inc_result, 'utf8');

            } else { //if exists
                flow.log(1, 'build - hxcpp - missing external include file?? this will cause errors for sure ', node);
            }

        } //if not internal
    }

} //write_hxcpp

exports.build_hxcpp = function(flow, target_arch, run_path, hxcpp_file, done) {

    var hxcpp_file = hxcpp_file || 'flow.Build.xml';
    var args = [hxcpp_file];

    if(run_path) {
        run_path = util.normalize(run_path, true);
    }

    if(internal.set_haxe_output) {
            //ensure the correct path and executable is used
        var binary_dest = flow.project.get_path_binary_dest_full(flow, flow.project.prepared, target_arch);
            binary_dest = path.relative(run_path, binary_dest);
            binary_dest = path.resolve(run_path, binary_dest);
            binary_dest = util.normalize(binary_dest);
        fse.ensureFileSync(binary_dest);
        flow.log(3, 'build - hxcpp - setting binary output path to', binary_dest);
        args.push("-Dhaxe_output=" + binary_dest);
    }

    if(flow.flags.debug) {
        args.push("-Ddebug");
    }

        //with --log 3+ hxcpp can also be verbose
    if(flow.flags.log > 2) {
        args.push('-verbose');
    }

        //default to no windows console, but allow it through
        //--d show_console or user define in project tree
    if(flow.target == 'windows' &&
       flow.project.prepared.defines_list.indexOf('show_console') == -1) {
        args.push('-Dno_console');
    }

    args.push('-D' + flow.target);
    args.push('-DHAXE_OUTPUT_PART=' + flow.project.prepared.source.project.app.name);

        //get the arch specific flags for hxcpp
    var arch_flags = flow.config.build.hxcpp_defines.arch[target_arch];
    if(arch_flags && arch_flags.constructor == Array) {
        arch_flags.map(function(f) {
            args.push('-D' + f)
        })
    }

        //get the target specific flags for hxcpp
    var target_flags = flow.config.build.hxcpp_defines.target[flow.target];
    if(target_flags && target_flags.constructor == Array) {
        target_flags.map(function(f) {
            args.push('-D' + f)
        })
    }

        //append command line + project based flags
    args = util.array_union(args, flow.project.prepared.hxcpp.flags);

    flow.log(2, 'build - running hxcpp for arch %s ...', target_arch);
    flow.log(3, 'haxelib run hxcpp %s', args.join(' ') );
    flow.log(3, 'running hxcpp from %s', run_path );

    var opt = {
        quiet : false,
        cwd: run_path
    }

    cmd.exec(flow, 'haxelib', ['run','hxcpp'].concat(args), opt, done);

} //build_hxcpp


text:
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.adwords.awreporting.util;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.google.api.ads.adwords.awreporting.util.ManagedCustomerDelegate;
import com.google.api.ads.adwords.jaxws.v201502.cm.Selector;
import com.google.api.ads.adwords.jaxws.v201502.mcm.ApiException;
import com.google.api.ads.adwords.jaxws.v201502.mcm.ManagedCustomer;
import com.google.api.ads.adwords.jaxws.v201502.mcm.ManagedCustomerPage;
import com.google.api.ads.adwords.jaxws.v201502.mcm.ManagedCustomerServiceInterface;

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import java.util.List;
import java.util.Set;

/**
 * Test case for the {@code ManagedCustomerServiceDelegate} class.
 *
 * @author jtoledo@google.com (Julian Toledo)
 */
public class ManagedCustomerServiceDelegateTest {

  private ManagedCustomer managedCustomer;
  @Mock
  private ManagedCustomerServiceInterface managedCustomerServiceInterfaceMock;
  private ManagedCustomerDelegate managedCustomerDelegate;

  @Before
  public void setUp() throws ApiException {
    managedCustomer = new ManagedCustomer();
    managedCustomer.setCustomerId(123L);
    managedCustomer.setCanManageClients(false);
    ManagedCustomerPage managedCustomerPage = new ManagedCustomerPage();
    managedCustomerPage.getEntries().add(managedCustomer);
    managedCustomerPage.setTotalNumEntries(1);

    MockitoAnnotations.initMocks(this);

    when(managedCustomerServiceInterfaceMock.get(
        Mockito.<Selector>anyObject())).thenReturn(managedCustomerPage);

    managedCustomerDelegate = new ManagedCustomerDelegate(managedCustomerServiceInterfaceMock);
  }

  /**
   * Tests the getAccountIds(AdWordsSession adWordsSession).
   *
   * @throws ApiException, exception class for holding a list of service errors
   */
  @Test
  public void testGetAccountIds() throws ApiException {
    Set<Long> set = managedCustomerDelegate.getAccountIds();

    assertTrue(set.contains(123L));

    ArgumentCaptor<Selector> argument = ArgumentCaptor.forClass(Selector.class);
    verify(managedCustomerServiceInterfaceMock).get(argument.capture());
    assertEquals(argument.getValue().getFields().size(), 6);
    assertTrue(argument.getValue().getFields().contains("CustomerId"));
    assertTrue(argument.getValue().getFields().contains("CanManageClients"));
    assertTrue(argument.getValue().getFields().contains("Name"));
    assertTrue(argument.getValue().getFields().contains("CompanyName"));
    assertTrue(argument.getValue().getFields().contains("CurrencyCode"));
    assertTrue(argument.getValue().getFields().contains("DateTimeZone"));
  }

  /**
   * Tests the getAccounts(AdWordsSession adWordsSession).
   *
   * @throws ApiException, exception class for holding a list of service errors
   */
  @Test
  public void testGetAccounts() throws ApiException {
    List<ManagedCustomer> list = managedCustomerDelegate.getAccounts();

    assertEquals(list.get(0), managedCustomer);
    assertEquals(list.get(0).getCustomerId(), new Long(123L));

    ArgumentCaptor<Selector> argument = ArgumentCaptor.forClass(Selector.class);
    verify(managedCustomerServiceInterfaceMock).get(argument.capture());
    assertEquals(argument.getValue().getFields().size(), 6);
    assertTrue(argument.getValue().getFields().contains("CustomerId"));
    assertTrue(argument.getValue().getFields().contains("CanManageClients"));
    assertTrue(argument.getValue().getFields().contains("Name"));
    assertTrue(argument.getValue().getFields().contains("CompanyName"));
    assertTrue(argument.getValue().getFields().contains("CurrencyCode"));
    assertTrue(argument.getValue().getFields().contains("DateTimeZone"));
  }
}


text:
class UserModel:

    def __init__(self, **kwargs):
        self.db = kwargs.get('db', None)
        self.users = self.db.user
        self.id = None
        self.username = kwargs.get('username', None)
        self.password = kwargs.get('password', None)
        self.role = kwargs.get('role', None)

    def set(self, item, value):
        setattr(self, item, value)

    def get(self, item):
        return getattr(self, item)

    def save(self):

        if self.id is None:
            last_id = self.users.insert({
                'username': self.username,
                'password': self.password,
                'role': self.role
            })
            self.set('id', last_id)
        else:
            self.users.update(
                {'username': self.username},
                {'$set': {
                    'username': self.username,
                    'password': self.password,
                    'role': self.role
                }}
            )

        return True

    def create(self, **kwargs):
        self.id = None
        self.username = kwargs.get('username', None)
        self.password = kwargs.get('password', None)
        self.role = kwargs.get('role', None)
        return self.save()

    def delete(self):
        self.users.remove({'username': self.username})
        self.__reset()
        return True

    def find(self, id):
        user = self.users.find_one({"_id": id})
        if user:
            self.__populate(user)
            return self

        return None

    def find_by_username(self, username):
        user = self.users.find_one({
            'username': username
        })
        if user:
            self.__populate(user)
            return self

        return None

    def __reset(self):
        self.id = None
        self.username = None
        self.password = None
        self.role = None

    def __populate(self, data):
        self.id = data['_id']
        self.username = data['username']
        self.password = data['password']
        self.role = data['role']


text:
// Copyright (c) 2016 Framefield. All rights reserved.
// Released under the MIT license. (see LICENSE.txt)

using System;
using System.Linq;
using Newtonsoft.Json;

namespace Framefield.Core.Commands
{
    public class UpdateInputParameterCommand : ICommand
    {
        public string Name { get; private set; }
        public bool IsUndoable => true;

        public class Entry
        {
            public FunctionType FunctionType;
            public string Name;
            public IValue DefaultValue;
            public MetaInput.RelevanceType Relevance;
            public bool IsMultiInput;
            public float Min, Max, Scale;
            public MetaInput.Scaling ScaleType;

            public Entry(MetaInput input)
            {
                FunctionType = input.OpPart.Type;
                Name = input.Name;
                DefaultValue = input.DefaultValue;
                Relevance = input.Relevance;
                IsMultiInput = input.IsMultiInput;
                if (input.OpPart.Type == FunctionType.Float)
                {
                    Min = input.Min;
                    Max = input.Max;
                    Scale = input.Scale;
                    ScaleType = input.ScaleType;
                }
            }
        }

        public UpdateInputParameterCommand() { }

        public UpdateInputParameterCommand(Operator compOp, Guid metaInputID, Entry changes)
        {
            Name = "Update Input Parameter";
            InitPreviousProperties(compOp, metaInputID);
            ChangeEntry = changes;
        }

        private void InitPreviousProperties(Operator compOp, Guid metaInputID)
        {
            _metaOpID = compOp.Definition.ID;
            _inputID = metaInputID;
            var entry = new Entry(GetInputToUpdate());
            _previousEntry = entry;
        }

        private void ApplyEntryToInput(Entry entry)
        {
            MetaInput inputToUpdate = GetInputToUpdate();
            inputToUpdate.OpPart = BasicMetaTypes.GetMetaOperatorPartOf(entry.FunctionType);
            inputToUpdate.Name = entry.Name;
            inputToUpdate.DefaultValue = entry.DefaultValue;
            inputToUpdate.Relevance = entry.Relevance;
            inputToUpdate.IsMultiInput = entry.IsMultiInput;

            if (entry.FunctionType == FunctionType.Float)
            {
                ApplyFloatEntriesToInput(entry);
            }

            MetaOp.UpdateInput(inputToUpdate);
        }

        private void ApplyFloatEntriesToInput(Entry entry)
        {
            var inputToUpdate = GetInputToUpdate();
            inputToUpdate.Min = entry.Min;
            inputToUpdate.Max = entry.Max;
            inputToUpdate.Scale = entry.Scale;
            inputToUpdate.ScaleType = entry.ScaleType;
        }

        public void Undo()
        {
            ApplyEntryToInput(_previousEntry);
        }

        public void Do()
        {
            ApplyEntryToInput(ChangeEntry);
        }

        private MetaInput GetInputToUpdate()
        {
            var inputToUpdate = (from input in MetaOp.Inputs
                                 where input.ID == _inputID
                                 select input).SingleOrDefault();
            return inputToUpdate;
        }

        private MetaOperator MetaOp => MetaManager.Instance.GetMetaOperator(_metaOpID);

        [JsonProperty]
        private Guid _metaOpID;
        [JsonProperty]
        private Guid _inputID;
        [JsonProperty]
        private Entry _previousEntry;
        [JsonProperty]
        public Entry ChangeEntry { get; private set; }
    }
}


text:
layout: post
title: "Android Sunucuya Terminalden Bağlanma"
date: 2014-01-30 20:28
comments: true
categories:
---

Android üzerinde çalışan bir sunucuya terminalden nasıl bağlanırız ?
Öncelikle sunucunun `1234` nolu port üzerinde çalıştığını varsayalım. Uygulamanızı
AVD üzerinde çalıştırın ve sunucuyu aktif hale getirin. <!-- more -->Şimdi `telnet` ile AVD
ye bağlanmamız gerek. AVD'nin port numarası pencere başlığında yazar.(genelde
5554 tür)

        telnet localhost 5554

yukarıdaki komutla AVDye bağlanmış oluyoruz. Eğer işlem başarılı ise bir komut
istemcisi göreceksiniz.

        redir add tcp:5353:1234

Bu komutla ise 1234 portunu(sunucunun çalıştığı port) 5353 numaralı porta
yonlendirmiş oluyor. Şimdi `exit` diyerek terminale dönelim. Artık  aşağıdaki komutla
sunucuyu bağlanalım.

        telnel localhost 5353

Ve işlem tamam :)


text:
package com.hazelcast.concurrent.lock;

import com.hazelcast.config.Config;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ILock;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.SlowTest;
import com.hazelcast.test.bounce.BounceMemberRule;
import com.hazelcast.test.jitter.JitterRule;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.util.HashSet;
import java.util.Random;

import static com.hazelcast.test.HazelcastTestSupport.assertTrueEventually;
import static com.hazelcast.test.HazelcastTestSupport.generateKeyNotOwnedBy;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

/**
 * Runs a cluster of {@value MEMBER_COUNT + 1} and calls lease lock from {@value DRIVER_COUNT} drivers. During the test bounces
 * {@value MEMBER_COUNT} cluster members (shuts down and restarts). The remaining 1 member is stable (never bounced) but no
 * locks are owned by this member.
 * Asserts that all locks are unlocked eventually.
 */
@RunWith(HazelcastSerialClassRunner.class)
@Category(SlowTest.class)
public class LockLeaseMemberBounceTest {
    private static final int MEMBER_COUNT = 4;
    private static final int DRIVER_COUNT = 4;
    private static final int LEASE_DURATION_MILLIS = 100;
    private static final int TEST_DURATION_SECONDS = 40;
    private static final int LOCK_COUNT = 500;
    private static final int CONCURRENCY = 2;

    @Rule
    public BounceMemberRule bounceMemberRule = BounceMemberRule.with(getConfig())
            .clusterSize(MEMBER_COUNT)
            .driverCount(DRIVER_COUNT).build();
    @Rule
    public JitterRule jitterRule = new JitterRule();

    @Test
    public void leaseShouldExpireWhenMemberBouncing() {
        final HazelcastInstance steadyMember = bounceMemberRule.getSteadyMember();

        String[] lockNames = new String[LOCK_COUNT];
        for (int i = 0; i < lockNames.length; i++) {
            lockNames[i] = generateKeyNotOwnedBy(steadyMember);
        }

        final Driver[] drivers = new Driver[DRIVER_COUNT];
        for (int i = 0; i < drivers.length; i++) {
            drivers[i] = new Driver(bounceMemberRule.getNextTestDriver(), lockNames);
        }

        DriverRunnable[] runnables = new DriverRunnable[drivers.length * CONCURRENCY];
        for (int i = 0; i < drivers.length; i++) {
            for (int j = 0; j < CONCURRENCY; j++) {
                runnables[i * CONCURRENCY + j] = new DriverRunnable(drivers[i]);
            }
        }

        bounceMemberRule.testRepeatedly(runnables, TEST_DURATION_SECONDS);

        assertTrueEventually(new AssertTask() {
            @Override
            public void run() throws Exception {
                for (Driver driver : drivers) {
                    driver.doAssert();
                }
            }
        }, MILLISECONDS.toSeconds(LEASE_DURATION_MILLIS) + 10);
    }

    protected Config getConfig() {
        return new Config();
    }

    public static class DriverRunnable implements Runnable {
        private final Driver client;

        DriverRunnable(Driver client) {
            this.client = client;
        }

        @Override
        public void run() {
            final ILock randomLock = client.getRandomLock();
            randomLock.lock(LEASE_DURATION_MILLIS, MILLISECONDS);
        }
    }

    public static class Driver {
        private final ILock[] locks;
        private Random random = new Random();

        Driver(HazelcastInstance hz, String[] lockNames) {
            locks = new ILock[lockNames.length];
            for (int i = 0; i < locks.length; i++) {
                locks[i] = hz.getLock(lockNames[i]);
            }
        }

        ILock getRandomLock() {
            return locks[random.nextInt(locks.length)];
        }

        void doAssert() {
            for (ILock lock : locks) {
                Assert.assertFalse(lock.isLocked());
            }
        }

        HashSet<ILock> getAllLocked() {
            final HashSet<ILock> locked = new HashSet<ILock>();
            for (ILock lock : locks) {
                if (lock.isLocked()) {
                    locked.add(lock);
                }
            }
            return locked;
        }
    }
}


text:
#include "include/core/SkMath.h"
#include "include/core/SkScalar.h"

SkScalar SkScalarInterpFunc(SkScalar searchKey, const SkScalar keys[],
                            const SkScalar values[], int length) {
    SkASSERT(length > 0);
    SkASSERT(keys != nullptr);
    SkASSERT(values != nullptr);
#ifdef SK_DEBUG
    for (int i = 1; i < length; i++) {
        SkASSERT(keys[i-1] <= keys[i]);
    }
#endif
    int right = 0;
    while (right < length && keys[right] < searchKey) {
        ++right;
    }
    // Could use sentinel values to eliminate conditionals, but since the
    // tables are taken as input, a simpler format is better.
    if (right == length) {
        return values[length-1];
    }
    if (right == 0) {
        return values[0];
    }
    // Otherwise, interpolate between right - 1 and right.
    SkScalar leftKey = keys[right-1];
    SkScalar rightKey = keys[right];
    SkScalar fract = (searchKey - leftKey) / (rightKey - leftKey);
    return SkScalarInterp(values[right-1], values[right], fract);
}


text:
<!doctype html>

    <title>Code coverage report for ol/layer/tilelayer.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / ol/layer/ tilelayer.js

        100%
        Statements
        23/23

        66.67%
        Branches
        4/6

        100%
        Functions
        5/5

        100%
        Lines
        23/23

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100	1×

1×
1×
1×

1×

1×
6×

6×

6×
6×
6×

6×
6×

1×

1×
3×

1×

1×
6×

1×
3×

1×
6×

goog.provide('ol.layer.Tile');

goog.require('ol');
goog.require('ol.layer.Layer');
goog.require('ol.object');

/**
 * @enum {string}
 */
ol.layer.TileProperty = {
  PRELOAD: 'preload',
  USE_INTERIM_TILES_ON_ERROR: 'useInterimTilesOnError'
};

/**
 * @classdesc
 * For layer sources that provide pre-rendered, tiled images in grids that are
 * organized by zoom levels for specific resolutions.
 * Note that any property set in the options is set as a {@link ol.Object}
 * property on the layer object; for example, setting `title: 'My Title'` in the
 * options means that `title` is observable, and has get/set accessors.
 *
 * @constructor
 * @extends {ol.layer.Layer}
 * @fires ol.render.Event
 * @param {olx.layer.TileOptions=} opt_options Tile layer options.
 * @api stable
 */
ol.layer.Tile = function(opt_options) {
  var options = opt_options ? opt_options : {};

  var baseOptions = ol.object.assign({}, options);

  delete baseOptions.preload;
  delete baseOptions.useInterimTilesOnError;
  goog.base(this,  /** @type {olx.layer.LayerOptions} */ (baseOptions));

  this.setPreload(options.preload !== undefined ? options.preload : 0);
  this.setUseInterimTilesOnError(options.useInterimTilesOnError !== undefined ?
      options.useInterimTilesOnError : true);
};
goog.inherits(ol.layer.Tile, ol.layer.Layer);

/**
 * Return the level as number to which we will preload tiles up to.
 * @return {number} The level to preload tiles up to.
 * @observable
 * @api
 */
ol.layer.Tile.prototype.getPreload = function() {
  return /** @type {number} */ (this.get(ol.layer.TileProperty.PRELOAD));
};

/**
 * Return the associated {@link ol.source.Tile tilesource} of the layer.
 * @function
 * @return {ol.source.Tile} Source.
 * @api stable
 */
ol.layer.Tile.prototype.getSource;

/**
 * Set the level as number to which we will preload tiles up to.
 * @param {number} preload The level to preload tiles up to.
 * @observable
 * @api
 */
ol.layer.Tile.prototype.setPreload = function(preload) {
  this.set(ol.layer.TileProperty.PRELOAD, preload);
};

/**
 * Whether we use interim tiles on error.
 * @return {boolean} Use interim tiles on error.
 * @observable
 * @api
 */
ol.layer.Tile.prototype.getUseInterimTilesOnError = function() {
  return /** @type {boolean} */ (
      this.get(ol.layer.TileProperty.USE_INTERIM_TILES_ON_ERROR));
};

/**
 * Set whether we use interim tiles on error.
 * @param {boolean} useInterimTilesOnError Use interim tiles on error.
 * @observable
 * @api
 */
ol.layer.Tile.prototype.setUseInterimTilesOnError = function(useInterimTilesOnError) {
  this.set(
      ol.layer.TileProperty.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError);
};

  Code coverage
  generated by istanbul at Fri Mar 11 2016 13:34:39 GMT+0100 (CET)


text:
package _eap.comps.workflow;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:AC.xml");

	}
}


text:
<?php

namespace DigitalOcean\Tests\CLI\Domains;

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use DigitalOcean\Tests\TestCase;
use DigitalOcean\CLI\Domains\DestroyCommand;

/**
 * @author Antoine Corcy <contact@sbin.dk>
 */
class DestroyRecordCommandTest extends TestCase
{
    protected $application;
    protected $command;
    protected $commandTester;

    protected function setUp()
    {
        $this->application = new Application();

        $result = (object) array(
            'status' => 'OK',
        );

        $DestroyCommand = $this->getMock('\DigitalOcean\CLI\Domains\DestroyRecordCommand', array('getDigitalOcean'));
        $DestroyCommand
            ->expects($this->any())
            ->method('getDigitalOcean')
            ->will($this->returnValue($this->getMockDigitalOcean('domains', $this->getMockDomains('destroyRecord', $result))));

        $this->application->add($DestroyCommand);

        $this->command = $this->application->find('domains:records:destroy');

        $this->commandTester = new CommandTester($this->command);
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Not enough arguments.
     */
    public function testExecuteNotEnoughArguments()
    {
        $this->commandTester->execute(array(
            'command' => $this->command->getName(),
        ));
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Not enough arguments.
     */
    public function testExecuteWithoutRecordId()
    {
        $this->commandTester->execute(array(
            'command' => $this->command->getName(),
            'id'      => 123,
        ));
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Not enough arguments.
     */
    public function testExecuteWithoutDomainId()
    {
        $this->commandTester->execute(array(
            'command'   => $this->command->getName(),
            'record_id' => 456,
        ));
    }

    public function testExecuteCheckStatusConfirmed()
    {
        $dialog = $this->getDialogAskConfirmation(true);
        $this->command->getHelperSet()->set($dialog, 'dialog');

        $this->commandTester->execute(array(
            'command'   => $this->command->getName(),
            'id'        => 123,
            'record_id' => 456,
        ));

        $this->assertTrue(is_string($this->commandTester->getDisplay()));
        $this->assertRegExp('/\| OK     \|/', $this->commandTester->getDisplay());
    }

    public function testExecuteCheckStatusNotConfirmed()
    {
        $dialog = $this->getDialogAskConfirmation(false);
        $this->command->getHelperSet()->set($dialog, 'dialog');

        $this->commandTester->execute(array(
            'command'   => $this->command->getName(),
            'id'        => 123,
            'record_id' => 456,
        ));

        $this->assertTrue(is_string($this->commandTester->getDisplay()));
        $this->assertRegExp('/Aborted!/', $this->commandTester->getDisplay());
    }
}


text:
param(
    [parameter(Mandatory = $true)][string]$applicationId,
    [parameter(Mandatory = $true)][string]$apiKey,
    [parameter(Mandatory = $true)][string]$releaseName,
    [parameter(Mandatory = $false)]$releaseProperties,
    [parameter(Mandatory = $false)][DateTime]$eventDateTime
)

# background info on how fwlink works: After you submit a web request, many sites redirect through a series of intermediate pages before you finally land on the destination page.
# So when calling Invoke-WebRequest, the result it returns comes from the final page in any redirect sequence. Hence, I set MaximumRedirection to 0, as this prevents the call to
# be redirected. By doing this, we get a resposne with status code 302, which indicates that there is a redirection link from the response body. We grab this redirection link and
# construct the url to make a release annotation.
# Here's how this logic is going to works
# 1. Client send http request, such as:  http://go.microsoft.com/fwlink/?LinkId=625115
# 2. FWLink get the request and find out the destination URL for it, such as:  http://www.bing.com
# 3. FWLink generate a new http response with status code "302" and with destination URL "http://www.bing.com". Send it back to Client.
# 4. Client, such as a powershell script, knows that status code "302" means redirection to new a location, and the target location is "http://www.bing.com"
function GetRequestUrlFromFwLink($fwLink)
{
    $request = Invoke-WebRequest -Uri $fwLink -MaximumRedirection 0 -UseBasicParsing -ErrorAction Ignore
    if ($request.StatusCode -eq "302") {
        return $request.Headers.Location
    }

    return $null
}

function CreateAnnotation($grpEnv)
{
	$retries = 1
	$success = $false
	while (!$success -and $retries -lt 6) {
	    $location = "$grpEnv/applications/$applicationId/Annotations?api-version=2015-11"

		Write-Host "Invoke a web request for $location to create a new release annotation. Attempting $retries"
		set-variable -Name createResultStatus -Force -Scope Local -Value $null
		set-variable -Name createResultStatusDescription -Force -Scope Local -Value $null
		set-variable -Name result -Force -Scope Local

		try {
			$result = Invoke-WebRequest -Uri $location -Method Put -Body $bodyJson -Headers $headers -ContentType "application/json; charset=utf-8" -UseBasicParsing
		} catch {
		    if ($_.Exception){
		        if($_.Exception.Response) {
    				$createResultStatus = $_.Exception.Response.StatusCode.value__
    				$createResultStatusDescription = $_.Exception.Response.StatusDescription
    			}
    			else {
    				$createResultStatus = "Exception"
    				$createResultStatusDescription = $_.Exception.Message
    			}
		    }
		}

		if ($result -eq $null) {
			if ($createResultStatus -eq $null) {
				$createResultStatus = "Unknown"
			}
			if ($createResultStatusDescription -eq $null) {
				$createResultStatusDescription = "Unknown"
			}
		}
 		else {
			    $success = $true
        }

		if ($createResultStatus -eq 409 -or $createResultStatus -eq 404 -or $createResultStatus -eq 401) # no retry when conflict or unauthorized or not found
		{
			break
		}

		$retries = $retries + 1
		sleep 1
	}

	$createResultStatus
	$createResultStatusDescription
	return
}

# Need powershell version 3 or greater for script to run
$minimumPowershellMajorVersion = 3
if ($PSVersionTable.PSVersion.Major -lt $minimumPowershellMajorVersion) {
   Write-Host "Need powershell version $minimumPowershellMajorVersion or greater to create release annotation"
   return
}

$currentTime = (Get-Date).ToUniversalTime()
$annotationDate = $currentTime.ToString("MMddyyyy_HHmmss")
set-variable -Name requestBody -Force -Scope Script
$requestBody = @{}
$requestBody.Id = [GUID]::NewGuid()
$requestBody.AnnotationName = $releaseName
if ($eventDateTime -eq $null) {
    $requestBody.EventTime = $currentTime.GetDateTimeFormats("s")[0] # GetDateTimeFormats returns an array
} else {
    # input must be between NOW and 90 days back maximum
    $maxDaysBack = $currentTime.AddDays(-90)
    if ($eventDateTime -lt $maxDaysBack -Or $eventDateTime -gt $currentTime) {
        $output = "-eventDateTime value must be between NOW and 90 days back maximum"
        throw $output
    }

    $requestBody.EventTime = $eventDateTime.GetDateTimeFormats("s")[0]
}
$requestBody.Category = "Deployment"

if ($releaseProperties -eq $null) {
    $properties = @{}
} else {
    $properties = $releaseProperties
}
$properties.Add("ReleaseName", $releaseName)

$requestBody.Properties = ConvertTo-Json($properties) -Compress

$bodyJson = [System.Text.Encoding]::UTF8.GetBytes(($requestBody | ConvertTo-Json))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("X-AIAPIKEY", $apiKey)

set-variable -Name createAnnotationResult1 -Force -Scope Local -Value $null
set-variable -Name createAnnotationResultDescription -Force -Scope Local -Value ""

# get redirect link from fwlink
$requestUrl = GetRequestUrlFromFwLink("http://go.microsoft.com/fwlink/?prd=11901&pver=1.0&sbp=Application%20Insights&plcid=0x409&clcid=0x409&ar=Annotations&sar=Create%20Annotation")
if ($requestUrl -eq $null) {
    $output = "Failed to find the redirect link to create a release annotation"
    throw $output
}

$createAnnotationResult1, $createAnnotationResultDescription = CreateAnnotation($requestUrl)
if ($createAnnotationResult1)
{
     $output = "Failed to create an annotation with Id: {0}. Error {1}, Description: {2}." -f $requestBody.Id, $createAnnotationResult1, $createAnnotationResultDescription
	 throw $output
}

$str = "Release annotation created. Id: {0}." -f $requestBody.Id
Write-Host $str