text:
#include <proton/object.h>
#include <proton/handlers.h>
#include <proton/io.h>
#include <proton/event.h>
#include <proton/transport.h>
#include <proton/connection.h>
#include <proton/session.h>
#include <proton/link.h>
#include <proton/delivery.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "reactor.h"
#include "selectable.h"
#include "platform.h"

struct pn_reactor_t {
  pn_record_t *attachments;
  pn_io_t *io;
  pn_collector_t *collector;
  pn_handler_t *global;
  pn_handler_t *handler;
  pn_list_t *children;
  pn_timer_t *timer;
  pn_socket_t wakeup[2];
  pn_selectable_t *selectable;
  pn_event_type_t previous;
  pn_timestamp_t now;
  int selectables;
  int timeout;
  bool yield;
};

pn_timestamp_t pn_reactor_mark(pn_reactor_t *reactor) {
  assert(reactor);
  reactor->now = pn_i_now();
  return reactor->now;
}

pn_timestamp_t pn_reactor_now(pn_reactor_t *reactor) {
  assert(reactor);
  return reactor->now;
}

static void pn_reactor_initialize(pn_reactor_t *reactor) {
  reactor->attachments = pn_record();
  reactor->io = pn_io();
  reactor->collector = pn_collector();
  reactor->global = pn_iohandler();
  reactor->handler = pn_handler(NULL);
  reactor->children = pn_list(PN_OBJECT, 0);
  reactor->timer = pn_timer(reactor->collector);
  reactor->wakeup[0] = PN_INVALID_SOCKET;
  reactor->wakeup[1] = PN_INVALID_SOCKET;
  reactor->selectable = NULL;
  reactor->previous = PN_EVENT_NONE;
  reactor->selectables = 0;
  reactor->timeout = 0;
  reactor->yield = false;
  pn_reactor_mark(reactor);
}

static void pn_reactor_finalize(pn_reactor_t *reactor) {
  for (int i = 0; i < 2; i++) {
    if (reactor->wakeup[i] != PN_INVALID_SOCKET) {
      pn_close(reactor->io, reactor->wakeup[i]);
    }
  }
  pn_decref(reactor->attachments);
  pn_decref(reactor->collector);
  pn_decref(reactor->global);
  pn_decref(reactor->handler);
  pn_decref(reactor->children);
  pn_decref(reactor->timer);
  pn_decref(reactor->io);
}

#define pn_reactor_hashcode NULL
#define pn_reactor_compare NULL
#define pn_reactor_inspect NULL

PN_CLASSDEF(pn_reactor)

pn_reactor_t *pn_reactor() {
  pn_reactor_t *reactor = pn_reactor_new();
  int err = pn_pipe(reactor->io, reactor->wakeup);
  if (err) {
    pn_free(reactor);
    return NULL;
  } else {
    return reactor;
  }
}

pn_record_t *pn_reactor_attachments(pn_reactor_t *reactor) {
  assert(reactor);
  return reactor->attachments;
}

pn_millis_t pn_reactor_get_timeout(pn_reactor_t *reactor) {
  assert(reactor);
  return reactor->timeout;
}

void pn_reactor_set_timeout(pn_reactor_t *reactor, pn_millis_t timeout) {
  assert(reactor);
  reactor->timeout = timeout;
}

void pn_reactor_free(pn_reactor_t *reactor) {
  if (reactor) {
    pn_collector_release(reactor->collector);
    pn_handler_free(reactor->handler);
    reactor->handler = NULL;
    pn_decref(reactor);
  }
}

pn_handler_t *pn_reactor_get_global_handler(pn_reactor_t *reactor) {
  assert(reactor);
  return reactor->global;
}

void pn_reactor_set_global_handler(pn_reactor_t *reactor, pn_handler_t *handler) {
  assert(reactor);
  pn_decref(reactor->global);
  reactor->global = handler;
  pn_incref(reactor->global);
}

pn_handler_t *pn_reactor_get_handler(pn_reactor_t *reactor) {
  assert(reactor);
  return reactor->handler;
}

void pn_reactor_set_handler(pn_reactor_t *reactor, pn_handler_t *handler) {
  assert(reactor);
  pn_decref(reactor->handler);
  reactor->handler = handler;
  pn_incref(reactor->handler);
}

pn_io_t *pn_reactor_io(pn_reactor_t *reactor) {
  assert(reactor);
  return reactor->io;
}

pn_collector_t *pn_reactor_collector(pn_reactor_t *reactor) {
  assert(reactor);
  return reactor->collector;
}

pn_list_t *pn_reactor_children(pn_reactor_t *reactor) {
  assert(reactor);
  return reactor->children;
}

static void pni_selectable_release(pn_selectable_t *selectable) {
  pn_reactor_t *reactor = (pn_reactor_t *) pni_selectable_get_context(selectable);
  pn_incref(selectable);
  if (pn_list_remove(reactor->children, selectable)) {
    reactor->selectables--;
  }
  pn_decref(selectable);
}

pn_selectable_t *pn_reactor_selectable(pn_reactor_t *reactor) {
  assert(reactor);
  pn_selectable_t *sel = pn_selectable();
  pn_selectable_collect(sel, reactor->collector);
  pn_collector_put(reactor->collector, PN_OBJECT, sel, PN_SELECTABLE_INIT);
  pni_selectable_set_context(sel, reactor);
  pn_list_add(reactor->children, sel);
  pn_selectable_on_release(sel, pni_selectable_release);
  pn_decref(sel);
  reactor->selectables++;
  return sel;
}

PN_HANDLE(PNI_TERMINATED)

void pn_reactor_update(pn_reactor_t *reactor, pn_selectable_t *selectable) {
  assert(reactor);
  pn_record_t *record = pn_selectable_attachments(selectable);
  if (!pn_record_has(record, PNI_TERMINATED)) {
    if (pn_selectable_is_terminal(selectable)) {
      pn_record_def(record, PNI_TERMINATED, PN_VOID);
      pn_collector_put(reactor->collector, PN_OBJECT, selectable, PN_SELECTABLE_FINAL);
    } else {
      pn_collector_put(reactor->collector, PN_OBJECT, selectable, PN_SELECTABLE_UPDATED);
    }
  }
}

void pni_handle_final(pn_reactor_t *reactor, pn_event_t *event);

static void pni_reactor_dispatch_post(pn_reactor_t *reactor, pn_event_t *event) {
  assert(reactor);
  assert(event);
  switch (pn_event_type(event)) {
  case PN_CONNECTION_FINAL:
    pni_handle_final(reactor, event);
    break;
  default:
    break;
  }
}

PN_HANDLE(PN_HANDLER)

pn_handler_t *pn_record_get_handler(pn_record_t *record) {
  assert(record);
  return (pn_handler_t *) pn_record_get(record, PN_HANDLER);
}

void pn_record_set_handler(pn_record_t *record, pn_handler_t *handler) {
  assert(record);
  pn_record_def(record, PN_HANDLER, PN_OBJECT);
  pn_record_set(record, PN_HANDLER, handler);
}

PN_HANDLE(PN_REACTOR)

pn_reactor_t *pni_record_get_reactor(pn_record_t *record) {
  return (pn_reactor_t *) pn_record_get(record, PN_REACTOR);
}

void pni_record_init_reactor(pn_record_t *record, pn_reactor_t *reactor) {
  pn_record_def(record, PN_REACTOR, PN_WEAKREF);
  pn_record_set(record, PN_REACTOR, reactor);
}

static pn_connection_t *pni_object_connection(const pn_class_t *clazz, void *object) {
  switch (pn_class_id(clazz)) {
  case CID_pn_delivery:
    return pn_session_connection(pn_link_session(pn_delivery_link((pn_delivery_t *) object)));
  case CID_pn_link:
    return pn_session_connection(pn_link_session((pn_link_t *) object));
  case CID_pn_session:
    return pn_session_connection((pn_session_t *) object);
  case CID_pn_connection:
    return (pn_connection_t *) object;
  case CID_pn_transport:
    return pn_transport_connection((pn_transport_t *) object);
  default:
    return NULL;
  }
}

static pn_reactor_t *pni_reactor(pn_selectable_t *sel) {
  return (pn_reactor_t *) pni_selectable_get_context(sel);
}

pn_reactor_t *pn_class_reactor(const pn_class_t *clazz, void *object) {
  switch (pn_class_id(clazz)) {
  case CID_pn_reactor:
    return (pn_reactor_t *) object;
  case CID_pn_task:
    return pni_record_get_reactor(pn_task_attachments((pn_task_t *) object));
  case CID_pn_transport:
    return pni_record_get_reactor(pn_transport_attachments((pn_transport_t *) object));
  case CID_pn_delivery:
  case CID_pn_link:
  case CID_pn_session:
  case CID_pn_connection:
    {
      pn_connection_t *conn = pni_object_connection(clazz, object);
      pn_record_t *record = pn_connection_attachments(conn);
      return pni_record_get_reactor(record);
    }
  case CID_pn_selectable:
    {
      pn_selectable_t *sel = (pn_selectable_t *) object;
      return pni_reactor(sel);
    }
  default:
    return NULL;
  }
}

pn_reactor_t *pn_object_reactor(void *object) {
  return pn_class_reactor(pn_object_reify(object), object);
}

pn_reactor_t *pn_event_reactor(pn_event_t *event) {
  const pn_class_t *clazz = pn_event_class(event);
  void *context = pn_event_context(event);
  return pn_class_reactor(clazz, context);
}

pn_handler_t *pn_event_handler(pn_event_t *event, pn_handler_t *default_handler) {
  pn_handler_t *handler = NULL;
  pn_link_t *link = pn_event_link(event);
  if (link) {
    handler = pn_record_get_handler(pn_link_attachments(link));
    if (handler) { return handler; }
  }
  pn_session_t *session = pn_event_session(event);
  if (session) {
    handler = pn_record_get_handler(pn_session_attachments(session));
    if (handler) { return handler; }
  }
  pn_connection_t *connection = pn_event_connection(event);
  if (connection) {
    handler = pn_record_get_handler(pn_connection_attachments(connection));
    if (handler) { return handler; }
  }
  switch (pn_class_id(pn_event_class(event))) {
  case CID_pn_task:
    handler = pn_record_get_handler(pn_task_attachments((pn_task_t *) pn_event_context(event)));
    if (handler) { return handler; }
    break;
  case CID_pn_selectable:
    handler = pn_record_get_handler(pn_selectable_attachments((pn_selectable_t *) pn_event_context(event)));
    if (handler) { return handler; }
    break;
  default:
    break;
  }
  return default_handler;
}

pn_task_t *pn_reactor_schedule(pn_reactor_t *reactor, int delay, pn_handler_t *handler) {
  pn_task_t *task = pn_timer_schedule(reactor->timer, reactor->now + delay);
  pn_record_t *record = pn_task_attachments(task);
  pni_record_init_reactor(record, reactor);
  pn_record_set_handler(record, handler);
  if (reactor->selectable) {
    pn_selectable_set_deadline(reactor->selectable, pn_timer_deadline(reactor->timer));
    pn_reactor_update(reactor, reactor->selectable);
  }
  return task;
}

void pni_event_print(pn_event_t *event) {
  pn_string_t *str = pn_string(NULL);
  pn_inspect(event, str);
  printf("%s\n", pn_string_get(str));
  pn_free(str);
}

bool pni_reactor_more(pn_reactor_t *reactor) {
  assert(reactor);
  return pn_timer_tasks(reactor->timer) || reactor->selectables > 1;
}

void pn_reactor_yield(pn_reactor_t *reactor) {
  assert(reactor);
  reactor->yield = true;
}

bool pn_reactor_quiesced(pn_reactor_t *reactor) {
  assert(reactor);
  pn_event_t *event = pn_collector_peek(reactor->collector);
  // no events
  if (!event) { return true; }
  // more than one event
  if (pn_collector_more(reactor->collector)) { return false; }
  // if we have just one event then we are quiesced if the quiesced event
  return pn_event_type(event) == PN_REACTOR_QUIESCED;
}

bool pn_reactor_process(pn_reactor_t *reactor) {
  assert(reactor);
  pn_reactor_mark(reactor);
  pn_event_type_t previous = PN_EVENT_NONE;
  while (true) {
    pn_event_t *event = pn_collector_peek(reactor->collector);
    //pni_event_print(event);
    if (event) {
      if (reactor->yield) {
        reactor->yield = false;
        return true;
      }
      reactor->yield = false;
      pn_incref(event);
      pn_handler_t *handler = pn_event_handler(event, reactor->handler);
      pn_event_type_t type = pn_event_type(event);
      pn_handler_dispatch(handler, event, type);
      pn_handler_dispatch(reactor->global, event, type);
      pni_reactor_dispatch_post(reactor, event);
      previous = reactor->previous = type;
      pn_decref(event);
      pn_collector_pop(reactor->collector);
    } else {
      if (pni_reactor_more(reactor)) {
        if (previous != PN_REACTOR_QUIESCED && reactor->previous != PN_REACTOR_FINAL) {
          pn_collector_put(reactor->collector, PN_OBJECT, reactor, PN_REACTOR_QUIESCED);
        } else {
          return true;
        }
      } else {
        if (reactor->selectable) {
          pn_selectable_terminate(reactor->selectable);
          pn_reactor_update(reactor, reactor->selectable);
          reactor->selectable = NULL;
        } else {
          return false;
        }
      }
    }
  }
}

static void pni_timer_expired(pn_selectable_t *sel) {
  pn_reactor_t *reactor = pni_reactor(sel);
  pn_timer_tick(reactor->timer, reactor->now);
  pn_selectable_set_deadline(sel, pn_timer_deadline(reactor->timer));
  pn_reactor_update(reactor, sel);
}

static void pni_timer_readable(pn_selectable_t *sel) {
  char buf[64];
  pn_reactor_t *reactor = pni_reactor(sel);
  pn_socket_t fd = pn_selectable_get_fd(sel);
  pn_read(reactor->io, fd, buf, 64);
  pni_timer_expired(sel);
}

static void pni_timer_finalize(pn_selectable_t *sel) {
  pn_reactor_t *reactor = pni_reactor(sel);
  pn_close(reactor->io, pn_selectable_get_fd(sel));
}

pn_selectable_t *pni_timer_selectable(pn_reactor_t *reactor) {
  pn_selectable_t *sel = pn_reactor_selectable(reactor);
  pn_selectable_set_fd(sel, reactor->wakeup[0]);
  pn_selectable_on_readable(sel, pni_timer_readable);
  pn_selectable_on_expired(sel, pni_timer_expired);
  pn_selectable_on_finalize(sel, pni_timer_finalize);
  pn_selectable_set_reading(sel, true);
  pn_selectable_set_deadline(sel, pn_timer_deadline(reactor->timer));
  pn_reactor_update(reactor, sel);
  return sel;
}

int pn_reactor_wakeup(pn_reactor_t *reactor) {
  assert(reactor);
  ssize_t n = pn_write(reactor->io, reactor->wakeup[1], "x", 1);
  if (n < 0) {
    return (int) n;
  } else {
    return 0;
  }
}

void pn_reactor_start(pn_reactor_t *reactor) {
  assert(reactor);
  pn_collector_put(reactor->collector, PN_OBJECT, reactor, PN_REACTOR_INIT);
  reactor->selectable = pni_timer_selectable(reactor);
 }

void pn_reactor_stop(pn_reactor_t *reactor) {
  assert(reactor);
  pn_collector_put(reactor->collector, PN_OBJECT, reactor, PN_REACTOR_FINAL);
  // XXX: should consider removing this fron stop to avoid reentrance
  pn_reactor_process(reactor);
  pn_collector_release(reactor->collector);
}

void pn_reactor_run(pn_reactor_t *reactor) {
  assert(reactor);
  pn_reactor_set_timeout(reactor, 3141);
  pn_reactor_start(reactor);
  while (pn_reactor_process(reactor)) {}
  pn_reactor_stop(reactor);
}


text:
# encoding: utf-8

require 'htmlentities/string'

Camping.goes :Crowdcount

module Crowdcount::Models
  class Count < Base
  end

  class CreateCrowdcount < V 0.1
    def self.up
      create_table :crowdcount_counts do |t|
        t.column :count, :integer
      end
      Count.create(:count => 0)
    end
  end

  class ChangeCrowdcountColumn < V 0.2
    def self.up
      change_column :crowdcount_counts, :count, :bigint
    end
  end
end

module Crowdcount::Controllers
  class Index < R '/'
    def get
      @count = Count.find(:first)
      render :index
    end

    def post
      case input.submit
      when '+'
        Count.find(:first).increment!(:count)
      when '-'
        Count.find(:first).decrement!(:count)
      end
      redirect '/'
    end
  end
end

module Crowdcount::Helpers
  def number_with_delimiter(number, delimiter=",", separator=".")
    begin
      parts = number.to_s.split('.')
      parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimiter}")
      parts.join separator
    rescue
      number
    end
  end
end

module Crowdcount::Views
  def layout
    xhtml_transitional do
      head do
        title "Crowdcount"
        style :type => "text/css" do
          %{
            /* <![CDATA[ */
            * { margin: 0; padding: 0; font-family: "Lucida Grande", Helvetica, Arial, sans-serif; font-size: 100%; }
            body { background-color: #ffffff; color: #000000; padding: 1em; text-align: center; }
            h1 { font-size: 140%; margin-bottom: 0.2em; font-weight: bold; }
            input { margin: 0.25em; width: 2.5em; text-align: center; }
            p#count { font-size: 500%; }
            .clear { clear: both; }
            #footer { margin: 1em; }
            /* ]]> */
          }
        end
      end
      body do
        self << yield
      end
    end
  end

  def index
    div do
      h1 { "crowdcount" }
      p.count! { number_with_delimiter @count.count }
      form :action => R(Index), :method => "post" do
        input :type => 'submit', :name => 'submit', :value => '+'
        input :type => 'submit', :name => 'submit', :value => '-'
      end
    end

    p.footer! { "Created by #{a "Brenton Fletcher", :href => "http://blog.bloople.net"} in #{File.stat(__FILE__).size} bytes of code." }
  end

end

def Crowdcount.create
  Crowdcount::Models.create_schema
  ActiveRecord::Base.default_timezone = :utc
end

redpajama_set_name: RedPajamaGithub


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

<title>JPAChObjectService</title>
<meta name="date" content="2015-06-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

ie.cit.group3.service

Interface JPAChObjectService

All Known Implementing Classes:

JPAChObjectServiceImpl

public interface JPAChObjectService

Method Summary

Methods

Modifier and Type
Method and Description

long
countByCreditlineLike(java.lang.String creditline)

long
countByDescriptionLike(java.lang.String description)

long
countByMediumLike(java.lang.String medium)

long
countByTitleLike(java.lang.String title)

org.springframework.data.domain.Page<ChObject>
findByCreditlineLike(java.lang.String creditline,
                    org.springframework.data.domain.Pageable pageable)

org.springframework.data.domain.Page<ChObject>
findByCreditlineLikeOrderByCreditlineAsc(java.lang.String creditline,
                                        org.springframework.data.domain.Pageable pageable)

org.springframework.data.domain.Page<ChObject>
findByCreditlineLikeOrderByCreditlineDesc(java.lang.String creditline,
                                         org.springframework.data.domain.Pageable pageable)

org.springframework.data.domain.Page<ChObject>
findByDescriptionLike(java.lang.String description,
                     org.springframework.data.domain.Pageable pageable)

org.springframework.data.domain.Page<ChObject>
findByDescriptionLikeOrderByDescriptionAsc(java.lang.String description,
                                          org.springframework.data.domain.Pageable pageable)

org.springframework.data.domain.Page<ChObject>
findByDescriptionLikeOrderByDescriptionDesc(java.lang.String description,
                                           org.springframework.data.domain.Pageable pageable)

org.springframework.data.domain.Page<ChObject>
findByMediumLike(java.lang.String medium,
                org.springframework.data.domain.Pageable pageable)

org.springframework.data.domain.Page<ChObject>
findByMediumLikeOrderByMediumAsc(java.lang.String medium,
                                org.springframework.data.domain.Pageable pageable)

org.springframework.data.domain.Page<ChObject>
findByMediumLikeOrderByMediumDesc(java.lang.String medium,
                                 org.springframework.data.domain.Pageable pageable)

org.springframework.data.domain.Page<ChObject>
findByTitleLike(java.lang.String title,
               org.springframework.data.domain.Pageable pageable)

org.springframework.data.domain.Page<ChObject>
findByTitleLikeOrderByTitleAsc(java.lang.String title,
                              org.springframework.data.domain.Pageable pageable)

org.springframework.data.domain.Page<ChObject>
findByTitleLikeOrderByTitleDesc(java.lang.String title,
                               org.springframework.data.domain.Pageable pageable)

Method Detail

findByTitleLikeOrderByTitleAsc

org.springframework.data.domain.Page<ChObject> findByTitleLikeOrderByTitleAsc(java.lang.String title,
                                                                            org.springframework.data.domain.Pageable pageable)

findByTitleLikeOrderByTitleDesc

org.springframework.data.domain.Page<ChObject> findByTitleLikeOrderByTitleDesc(java.lang.String title,
                                                                             org.springframework.data.domain.Pageable pageable)

findByTitleLike

org.springframework.data.domain.Page<ChObject> findByTitleLike(java.lang.String title,
                                                             org.springframework.data.domain.Pageable pageable)

countByTitleLike

long countByTitleLike(java.lang.String title)

findByDescriptionLikeOrderByDescriptionAsc

org.springframework.data.domain.Page<ChObject> findByDescriptionLikeOrderByDescriptionAsc(java.lang.String description,
                                                                                org.springframework.data.domain.Pageable pageable)

findByDescriptionLikeOrderByDescriptionDesc

org.springframework.data.domain.Page<ChObject> findByDescriptionLikeOrderByDescriptionDesc(java.lang.String description,
                                                                                org.springframework.data.domain.Pageable pageable)

findByDescriptionLike

org.springframework.data.domain.Page<ChObject> findByDescriptionLike(java.lang.String description,
                                                                   org.springframework.data.domain.Pageable pageable)

countByDescriptionLike

long countByDescriptionLike(java.lang.String description)

findByMediumLikeOrderByMediumAsc

org.springframework.data.domain.Page<ChObject> findByMediumLikeOrderByMediumAsc(java.lang.String medium,
                                                                              org.springframework.data.domain.Pageable pageable)

findByMediumLikeOrderByMediumDesc

org.springframework.data.domain.Page<ChObject> findByMediumLikeOrderByMediumDesc(java.lang.String medium,
                                                                               org.springframework.data.domain.Pageable pageable)

findByMediumLike

org.springframework.data.domain.Page<ChObject> findByMediumLike(java.lang.String medium,
                                                              org.springframework.data.domain.Pageable pageable)

countByMediumLike

long countByMediumLike(java.lang.String medium)

findByCreditlineLikeOrderByCreditlineAsc

org.springframework.data.domain.Page<ChObject> findByCreditlineLikeOrderByCreditlineAsc(java.lang.String creditline,
                                                                                org.springframework.data.domain.Pageable pageable)

findByCreditlineLikeOrderByCreditlineDesc

org.springframework.data.domain.Page<ChObject> findByCreditlineLikeOrderByCreditlineDesc(java.lang.String creditline,
                                                                                org.springframework.data.domain.Pageable pageable)

findByCreditlineLike

org.springframework.data.domain.Page<ChObject> findByCreditlineLike(java.lang.String creditline,
                                                                  org.springframework.data.domain.Pageable pageable)

countByCreditlineLike

long countByCreditlineLike(java.lang.String creditline)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package com.anilallewar.microservices.user.api;

import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.anilallewar.microservices.user.dto.UserDTO;

/**
 * REST endpoint for the user functionality
 *
 * @author anilallewar
 *
 */
@RestController
@RequestMapping("/")
public class UserController {

	private static final Logger LOGGER = Logger.getLogger(UserController.class.getName());

	@Value("${mail.domain ?: google.com}")
	private String mailDomain;

	private List<UserDTO> users = Arrays.asList(new UserDTO("Anil", "Allewar", "1", "anil.allewar@" + mailDomain),
			new UserDTO("Stefan", "Weber", "2", "stefan.weber@" + mailDomain),
			new UserDTO("John", "Snow", "3", "john.snow@" + mailDomain));

	/**
	 * Return all users
	 *
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, headers = "Accept=application/json")
	public List<UserDTO> getUsers() {
		return users;
	}

	/**
	 * Return user associated with specific user name
	 *
	 * @param userName
	 * @return
	 */
	@RequestMapping(value = "{userName}", method = RequestMethod.GET, headers = "Accept=application/json")
	public UserDTO getUserByUserName(@PathVariable("userName") String userName) {
		UserDTO userDtoToReturn = null;
		for (UserDTO currentUser : users) {
			if (currentUser.getUserName().equalsIgnoreCase(userName)) {
				userDtoToReturn = currentUser;
				if (LOGGER.isLoggable(Level.INFO)) {
					LOGGER.info(String.format("Found matching user: %s", userDtoToReturn.toString()));
				}
				break;
			}
		}

		return userDtoToReturn;
	}
}


text:
package domains

import (
	"net/http"
	"path/filepath"
	"strings"

	"getmelange.com/backend/framework"
	"getmelange.com/backend/info"
)

// HandleCommon will resolve URLs that occur on the Common domain.
//
// This will serve files out of the `lib` directory in
// `getmelange.com`.
func HandleCommon(
	res http.ResponseWriter,
	req *http.Request,
	env *info.Environment,
) {
	libBase := filepath.Join(env.AssetDirectory, "lib")

	var view framework.View

	// Serve Library Files
	if req.URL.Path == "/main/theme" {
		// Load the Main Theme Files
		mainTheme := filepath.Join("bootswatch-yeti", "3.3.4.css")
		view = framework.ServeFile(libBase, mainTheme)
	} else {
		dirs := strings.Split(req.URL.Path, "/")

		if len(dirs) != 4 {
			framework.WriteView(framework.Error404, res)
			return
		}
		typ, lib, version := dirs[1], dirs[2], dirs[3]

		location := filepath.Join(
			filepath.FromSlash(lib),
			version+"."+filepath.FromSlash(typ),
		)
		view = framework.ServeFile(libBase, location)
	}

	// Resources from Common can be Accessed by All Origins
	framework.WriteView(
		&framework.CORSWrapper{
			Origin: "*",
			View:   view,
		}, res)
}


text:
        Add Job Opening
        Edit Job Opening

{{alert.msg}}

        <form class="form-horizontal text-center" name="vm.jobOpeningForm">

                Job Opening Title

                    <input type="text" class="form-control" ng-model="vm.jobOpening.jobTitle" ng-required="true" />

                Job Opening Code

                    <input type="text" class="form-control" ng-model="vm.jobOpening.jobCode" />

                Experience

                    <input type="text" class="form-control" ng-model="vm.jobOpening.jobExperience" ng-required="true" />

                Job Positions

                    <input type="number" class="form-control" ng-model="vm.jobOpening.jobPositions"
                        ng-required="true" />

                Job Description

                    <textarea rows="12" class="form-control" ng-model="vm.jobOpening.jobDescription" ng-required="true">
                        </textarea>

                Status

                    <select class="form-control" ng-model="vm.jobOpening.isActive"
                        ng-options="opt.id as opt.label for opt in [{id: true, label:'Active'}, {id: false, label:'Inactive'}]"></select>

        </form>

    <button class="btn btn-primary" type="button" ng-disabled="!vm.enableSaveBtn"
        ng-click="vm.saveManageJobOpening(vm.jobOpeningForm)">Save</button>
    <button class="btn btn-warning" type="button" ng-click="vm.cancelManageJobOpening()">Cancel</button>


text:
using Qooba.Framework.Bot.Abstractions;
using System.Threading.Tasks;
using Qooba.Framework.Bot.Abstractions.Models;
using Qooba.Framework.Bot.Abstractions.Models.Attachments;
using Qooba.Framework.Bot.Abstractions.Models.Templates;
using System.Collections.Generic;
using System.Linq;

namespace Qooba.Framework.Bot
{
    public class ListReplyBuilder : IReplyBuilder<ListReplyMessage>
    {
        public async Task<ReplyMessage> ExecuteAsync(IConversationContext context, ListReplyMessage reply)
        {
            return new ReplyMessage
            {
                Attachment = new TemplateAttachment
                {
                    Payload = new ListTemplateAttachmentPayload
                    {
                        Elements = reply.Elements.Select(x =>
                            new Element
                            {
                                Title = x.Title,
                                Subtitle = x.Subtitle,
                                Image_url = x.Image,
                                Default_action = !string.IsNullOrEmpty(x.DefaultActionUrl) ? new DefaultAction { Url = x.DefaultActionUrl } : null,
                                Buttons = x.Buttons.Select(b => b.ToButton()).ToList()
                            }
                        ).ToList()
                    }
                }
            };
        }
    }

    public class ListReplyMessage
    {
        public IList<ListReplyElement> Elements { get; set; }
    }

    public class ListReplyElement
    {
        public string Title { get; set; }

        public string Subtitle { get; set; }

        public string Image { get; set; }

        public string DefaultActionUrl { get; set; }

        public IList<FullButton> Buttons { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/tw__bg_media_badge" />
    <item android:left="@dimen/tw__badge_padding" android:top="@dimen/tw__badge_padding" android:right="@dimen/tw__badge_padding" android:bottom="@dimen/tw__badge_padding">
        <bitmap android:src="@drawable/tw__ic_gif_badge" />
    </item>
</layer-list>


text:
package org.sagebionetworks.web.client.widget.entity.download;

import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static org.sagebionetworks.repo.model.util.ModelConstants.VALID_ENTITY_NAME_REGEX;
import static org.sagebionetworks.web.client.ServiceEntryPointUtils.fixServiceEntryPoint;

import com.google.common.util.concurrent.FutureCallback;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import java.util.List;
import org.sagebionetworks.repo.model.Entity;
import org.sagebionetworks.repo.model.Folder;
import org.sagebionetworks.repo.model.attachment.UploadResult;
import org.sagebionetworks.repo.model.attachment.UploadStatus;
import org.sagebionetworks.repo.model.file.ExternalGoogleCloudUploadDestination;
import org.sagebionetworks.repo.model.file.ExternalObjectStoreUploadDestination;
import org.sagebionetworks.repo.model.file.ExternalS3UploadDestination;
import org.sagebionetworks.repo.model.file.ExternalUploadDestination;
import org.sagebionetworks.repo.model.file.S3UploadDestination;
import org.sagebionetworks.repo.model.file.UploadDestination;
import org.sagebionetworks.repo.model.file.UploadType;
import org.sagebionetworks.web.client.ClientProperties;
import org.sagebionetworks.web.client.ContentTypeUtils;
import org.sagebionetworks.web.client.DisplayConstants;
import org.sagebionetworks.web.client.DisplayUtils;
import org.sagebionetworks.web.client.GWTWrapper;
import org.sagebionetworks.web.client.GlobalApplicationState;
import org.sagebionetworks.web.client.SynapseClientAsync;
import org.sagebionetworks.web.client.SynapseJSNIUtils;
import org.sagebionetworks.web.client.SynapseJavascriptClient;
import org.sagebionetworks.web.client.SynapseJavascriptFactory.OBJECT_TYPE;
import org.sagebionetworks.web.client.SynapseProperties;
import org.sagebionetworks.web.client.events.CancelHandler;
import org.sagebionetworks.web.client.events.EntityUpdatedEvent;
import org.sagebionetworks.web.client.events.UploadSuccessHandler;
import org.sagebionetworks.web.client.security.AuthenticationController;
import org.sagebionetworks.web.client.utils.Callback;
import org.sagebionetworks.web.client.utils.CallbackP;
import org.sagebionetworks.web.client.widget.SynapseWidgetPresenter;
import org.sagebionetworks.web.client.widget.entity.dialog.AddAttachmentHelper;
import org.sagebionetworks.web.client.widget.upload.MultipartUploader;
import org.sagebionetworks.web.client.widget.upload.ProgressingFileUploadHandler;
import org.sagebionetworks.web.shared.WebConstants;
import org.sagebionetworks.web.shared.exceptions.ConflictException;
import org.sagebionetworks.web.shared.exceptions.NotFoundException;
import org.sagebionetworks.web.shared.exceptions.RestServiceException;
import org.sagebionetworks.web.shared.exceptions.UnauthorizedException;

/**
 * This Uploader class supports 2 use cases: B. File Entity, newer client browser: Direct multipart
 * upload to S3, using a PUT to presigned URLs. C. Upload to the NCI proxy.
 *
 * Case B will be the most common case.
 */
public class Uploader
  implements
    UploaderView.Presenter,
    SynapseWidgetPresenter,
    ProgressingFileUploadHandler {

  public static final long OLD_BROWSER_MAX_SIZE = (long) ClientProperties.MB *
  5; // 5MB
  private UploaderView view;
  private UploadSuccessHandler successHandler;
  private CancelHandler cancelHandler;
  private Entity entity;
  private String parentEntityId, currentFileParentEntityId;
  // set if we are uploading to an existing file entity
  private String entityId;
  private CallbackP<String> fileHandleIdCallback;
  private SynapseClientAsync synapseClient;
  private SynapseJSNIUtils synapseJsniUtils;
  private GlobalApplicationState globalAppState;
  private GWTWrapper gwt;
  MultipartUploader multiPartUploader;
  AuthenticationController authenticationController;

  private String[] fileNames;
  private String[] currentFilePath;
  private int currentFilePathElement;
  private int currIndex;
  private JavaScriptObject fileList;
  private NumberFormat percentFormat;
  private boolean fileHasBeenUploaded = false;
  private UploadType currentUploadType;
  private String currentExternalUploadUrl;
  private Long storageLocationId;
  private S3DirectUploader s3DirectUploader;
  private String bucketName, endpointUrl, keyPrefixUUID;
  private SynapseJavascriptClient jsClient;
  private SynapseProperties synapseProperties;
  private EventBus eventBus;

  @Inject
  public Uploader(
    UploaderView view,
    SynapseClientAsync synapseClient,
    SynapseJSNIUtils synapseJsniUtils,
    GWTWrapper gwt,
    AuthenticationController authenticationController,
    MultipartUploader multiPartUploader,
    GlobalApplicationState globalAppState,
    S3DirectUploader s3DirectUploader,
    SynapseJavascriptClient jsClient,
    SynapseProperties synapseProperties,
    EventBus eventBus
  ) {
    this.view = view;
    this.synapseClient = synapseClient;
    fixServiceEntryPoint(synapseClient);
    this.synapseJsniUtils = synapseJsniUtils;
    this.gwt = gwt;
    this.percentFormat = gwt.getNumberFormat("##");
    this.authenticationController = authenticationController;
    this.globalAppState = globalAppState;
    this.multiPartUploader = multiPartUploader;
    this.s3DirectUploader = s3DirectUploader;
    this.jsClient = jsClient;
    this.synapseProperties = synapseProperties;
    this.eventBus = eventBus;
    view.setPresenter(this);
  }

  public Widget configure(
    Entity entity,
    String parentEntityId,
    CallbackP<String> fileHandleIdCallback,
    boolean isEntity
  ) {
    this.view.setPresenter(this);
    this.entity = entity;
    this.entityId = entity != null ? entity.getId() : null;
    this.parentEntityId = parentEntityId;
    this.currentFileParentEntityId = parentEntityId;
    this.fileHandleIdCallback = fileHandleIdCallback;
    this.view.createUploadForm(isEntity, parentEntityId);
    view.resetToInitialState();
    fileList = null;
    resetUploadProgress();
    view.showUploaderUI();

    globalAppState.setDropZoneHandler(fileList -> {
      handleUploads(fileList);
    });

    // async load upload destinations (and update view)
    queryForUploadDestination();
    return this.view.asWidget();
  }

  public void clearState() {
    view.clear();
    // remove handlers
    this.cancelHandler = null;
    this.successHandler = null;
    this.entity = null;
    this.parentEntityId = null;
    this.currentFileParentEntityId = null;
    this.currentUploadType = null;
    this.currentExternalUploadUrl = null;
    bucketName = null;
    keyPrefixUUID = null;
    endpointUrl = null;
    globalAppState.clearDropZoneHandler();
    resetUploadProgress();
  }

  @Override
  public Widget asWidget() {
    return null;
  }

  public void uploadFiles() {
    view.triggerUpload();
  }

  public String[] getSelectedFileNames() {
    return synapseJsniUtils.getMultipleUploadFileNames(fileList);
  }

  public String getSelectedFilesText() {
    String[] selectedFiles = getSelectedFileNames();
    if (selectedFiles == null) return ""; else if (selectedFiles.length == 1) {
      return selectedFiles[0];
    } else {
      return selectedFiles.length + " files";
    }
  }

  @Override
  public void handleUploads() {
    // field validation
    if (fileList == null) {
      // setup upload process.
      fileList = synapseJsniUtils.getFileList(UploaderViewImpl.FILE_FIELD_ID);
      fileHasBeenUploaded = false;
      currIndex = 0;
      if ((fileNames = getSelectedFileNames()) == null) {
        // no files selected.
        view.hideLoading();
        view.showErrorMessage(
          DisplayConstants.NO_FILES_SELECTED_FOR_UPLOAD_MESSAGE
        );
        view.enableUpload();
        return;
      }
    }
    this.handleUploads(fileList);
  }

  public void handleUploads(JavaScriptObject fileList) {
    // SWC-5161: can't drag/drop another file set while this file list is being uploaded.
    globalAppState.clearDropZoneHandler();
    view.disableSelectionDuringUpload();
    this.fileList = fileList;
    view.setSelectedFilenames(getSelectedFilesText());
    fileNames = synapseJsniUtils.getMultipleUploadFileNames(fileList);
    this.uploadBasedOnConfiguration();
  }

  public void updateUploadBannerView(String banner) {
    if (DisplayUtils.isDefined(banner)) view.showUploadingBanner(
      banner
    ); else view.showUploadingToSynapseStorage();
  }

  public void queryForUploadDestination() {
    enableMultipleFileUploads();
    storageLocationId = null;
    if (parentEntityId == null && entity == null) {
      currentUploadType = UploadType.S3;
      view.showUploadingToSynapseStorage();
    } else {
      // we have a parent entity, check to see where we are suppose to upload the file(s)
      String uploadDestinationsEntityId = parentEntityId != null
        ? parentEntityId
        : entity.getId();
      jsClient.getUploadDestinations(
        uploadDestinationsEntityId,
        new AsyncCallback<List<UploadDestination>>() {
          public void onSuccess(List<UploadDestination> uploadDestinations) {
            if (uploadDestinations == null || uploadDestinations.isEmpty()) {
              currentUploadType = UploadType.S3;
              view.showUploadingToSynapseStorage();
            } else if (
              uploadDestinations.get(0) instanceof S3UploadDestination
            ) {
              currentUploadType = UploadType.S3;
              storageLocationId =
                uploadDestinations.get(0).getStorageLocationId();
              updateUploadBannerView(uploadDestinations.get(0).getBanner());
            } else if (
              uploadDestinations.get(
                0
              ) instanceof ExternalGoogleCloudUploadDestination
            ) {
              currentUploadType = UploadType.GOOGLECLOUDSTORAGE;
              storageLocationId =
                uploadDestinations.get(0).getStorageLocationId();
              updateUploadBannerView(uploadDestinations.get(0).getBanner());
            } else if (
              uploadDestinations.get(0) instanceof ExternalUploadDestination
            ) {
              ExternalUploadDestination externalUploadDestination = (ExternalUploadDestination) uploadDestinations.get(
                0
              );
              storageLocationId =
                externalUploadDestination.getStorageLocationId();
              currentUploadType = externalUploadDestination.getUploadType();
              if (currentUploadType == UploadType.SFTP) {
                uploadError(
                  DisplayConstants.ERROR_DEPRECATED_SERVICE,
                  new Exception(DisplayConstants.ERROR_DEPRECATED_SERVICE)
                );
              } else {
                onFailure(
                  new org.sagebionetworks.web.client.exceptions.IllegalArgumentException(
                    "Unsupported external upload type: " +
                    externalUploadDestination.getUploadType()
                  )
                );
              }
            } else if (
              uploadDestinations.get(0) instanceof ExternalS3UploadDestination
            ) {
              ExternalS3UploadDestination externalUploadDestination = (ExternalS3UploadDestination) uploadDestinations.get(
                0
              );
              storageLocationId =
                externalUploadDestination.getStorageLocationId();
              currentUploadType = externalUploadDestination.getUploadType();
              String banner = externalUploadDestination.getBanner();
              if (!DisplayUtils.isDefined(banner)) {
                banner =
                  "Uploading to S3: " + externalUploadDestination.getBucket();
                if (externalUploadDestination.getBaseKey() != null) banner +=
                  "/" + externalUploadDestination.getBaseKey();
              }
              updateUploadBannerView(banner);
              // direct to s3(-like) storage
            } else if (
              uploadDestinations.get(
                0
              ) instanceof ExternalObjectStoreUploadDestination
            ) {
              ExternalObjectStoreUploadDestination externalUploadDestination = (ExternalObjectStoreUploadDestination) uploadDestinations.get(
                0
              );
              storageLocationId =
                externalUploadDestination.getStorageLocationId();
              currentUploadType = externalUploadDestination.getUploadType();
              String banner = externalUploadDestination.getBanner();
              endpointUrl = externalUploadDestination.getEndpointUrl();
              bucketName = externalUploadDestination.getBucket();
              keyPrefixUUID = externalUploadDestination.getKeyPrefixUUID();
              if (!DisplayUtils.isDefined(banner)) {
                banner = "Uploading to " + endpointUrl + " " + bucketName;
                if (keyPrefixUUID != null) banner += "/" + keyPrefixUUID;
              }
              view.showUploadingToS3DirectStorage(endpointUrl, banner);
            } else {
              // unsupported upload destination type
              onFailure(
                new org.sagebionetworks.web.client.exceptions.IllegalArgumentException(
                  "Unsupported upload destination: " +
                  uploadDestinations.get(0).getClass().getName()
                )
              );
            }
          }

          @Override
          public void onFailure(Throwable caught) {
            uploadError(caught.getMessage(), caught);
          }
        }
      );
    }
  }

  /**
   * Get the upload destination (based on the project settings), and continue the upload.
   */
  public void uploadBasedOnConfiguration() {
    // create necessary folders based on webkitRelativePath for the current item, and set parent entity
    // id to correct parent
    // reset the current file parent entity id to the original.
    String relativePath = synapseJsniUtils.getWebkitRelativePath(
      fileList,
      currIndex
    );
    if (relativePath == null || relativePath.isEmpty()) {
      uploadBasedOnConfigurationAfterFolderCreation();
    } else {
      String[] path = relativePath.split("[/]");
      mkdirs(path);
    }
  }

  private void uploadBasedOnConfigurationAfterFolderCreation() {
    if (validateFileName(fileNames[currIndex])) {
      if (
        currentUploadType == UploadType.S3 ||
        currentUploadType == UploadType.GOOGLECLOUDSTORAGE
      ) {
        uploadToS3OrGoogleCloud();
      } else if (currentUploadType == UploadType.SFTP) {
        String message =
          "This file is hosted on a SFTP server. Please use a SFTP client to access this file.";
        uploadError(message, new Exception(message));
      } else {
        String message =
          "Unsupported external upload type specified: " + currentUploadType;
        uploadError(message, new Exception(message));
      }
    }
  }

  private boolean validateFileName(String filename) {
    boolean valid =
      filename.matches(VALID_ENTITY_NAME_REGEX) &&
      (filename.trim().length() == filename.length());
    if (!valid) {
      String message = WebConstants.INVALID_ENTITY_NAME_MESSAGE;
      uploadError(message, new Exception(message));
    }
    return valid;
  }

  /**
   * Create any missing folders based on the relative path
   *
   * @param relativePath
   */
  public void mkdirs(String[] path) {
    // current file path (remove file name)
    this.currentFilePath = new String[path.length - 1];
    for (int i = 0; i < path.length - 1; i++) {
      currentFilePath[i] = path[i];
    }
    this.currentFilePathElement = 0;
    this.currentFileParentEntityId = parentEntityId;
    mkdir();
  }

  private void mkdir() {
    // look up the name (does that entity name exist?)
    jsClient.lookupChild(
      currentFilePath[currentFilePathElement],
      currentFileParentEntityId,
      new AsyncCallback<String>() {
        @Override
        public void onFailure(Throwable caught) {
          if (caught instanceof NotFoundException) {
            // did not find this container, create it!
            createCurrentPathElement();
          } else {
            uploadError(
              "Unable to create target folder structure: " +
              synapseJsniUtils.getWebkitRelativePath(fileList, currIndex),
              caught
            );
          }
        }

        @Override
        public void onSuccess(String parentId) {
          currentFileParentEntityId = parentId;
          mkNextDir();
        }
      }
    );
  }

  private void createCurrentPathElement() {
    Folder f = new Folder();
    f.setName(currentFilePath[currentFilePathElement]);
    f.setParentId(currentFileParentEntityId);
    jsClient
      .createEntity(f)
      .addCallback(
        new FutureCallback<Entity>() {
          @Override
          public void onSuccess(Entity entity) {
            // update the current file parent (container) id to this new folder.
            currentFileParentEntityId = entity.getId();
            mkNextDir();
          }

          @Override
          public void onFailure(Throwable caught) {
            uploadError(
              "Unable to create target folder structure: " +
              synapseJsniUtils.getWebkitRelativePath(fileList, currIndex),
              caught
            );
          }
        },
        directExecutor()
      );
  }

  private void mkNextDir() {
    currentFilePathElement++;
    if (currentFilePathElement < currentFilePath.length) {
      mkdir();
    } else {
      // done making folders!
      uploadBasedOnConfigurationAfterFolderCreation();
    }
  }

  /**
   * Given a sftp link, return a link that goes through the sftp proxy to do the action (GET file or
   * POST upload form)
   *
   * @param realSftpUrl
   * @param globalAppState
   * @return
   */
  public static String getSftpProxyLink(
    String fileNameOverride,
    String realSftpUrl,
    SynapseProperties synapseProperties,
    GWTWrapper gwt
  ) {
    String sftpProxy = synapseProperties.getSynapseProperty(
      WebConstants.SFTP_PROXY_ENDPOINT
    );
    if (sftpProxy != null) {
      String delimiter = sftpProxy.contains("?") ? "&" : "?";

      String escapedRealSftpUrl = gwt.encodeQueryString(realSftpUrl);
      String escapedFileNameOverride = gwt.encodeQueryString(fileNameOverride);
      return (
        sftpProxy +
        delimiter +
        "url=" +
        escapedRealSftpUrl +
        "&filename=" +
        escapedFileNameOverride
      );
    } else {
      // unlikely state
      throw new IllegalArgumentException("Unable to determine SFTP endpoint");
    }
  }

  public boolean checkFileAPISupported() {
    boolean isFileAPISupported = synapseJsniUtils.isFileAPISupported();
    if (!isFileAPISupported) {
      String message = "Multipart upload is not supported on this browser.";
      uploadError(message, new UnsupportedOperationException(message));
    }
    return isFileAPISupported;
  }

  public void uploadToS3OrGoogleCloud() {
    if (checkFileAPISupported()) {
      // use case B from above
      Callback callback = () -> directUploadStep2(fileNames[currIndex]);
      checkForExistingFileName(fileNames[currIndex], callback);
    }
  }

  /**
   * Return the current upload type. Used for testing purposes only.
   *
   * @return
   */
  public UploadType getCurrentUploadType() {
    return currentUploadType;
  }

  /**
   * Set the current upload type. Used for testing purposes only
   *
   * @param currentUploadType
   */
  public void setCurrentUploadType(UploadType currentUploadType) {
    this.currentUploadType = currentUploadType;
  }

  /**
   * Get the current external upload url. Used for testing purposes only.
   *
   * @return
   */
  public String getCurrentExternalUploadUrl() {
    return currentExternalUploadUrl;
  }

  /**
   * Set the current external upload url. Used for testing purposes only.
   *
   * @return
   */
  public void setCurrentExternalUploadUrl(String currentExternalUploadUrl) {
    this.currentExternalUploadUrl = currentExternalUploadUrl;
  }

  public void checkFileSize() throws IllegalArgumentException {
    JavaScriptObject blob = synapseJsniUtils.getFileBlob(
      this.currIndex,
      fileList
    );
    long fileSize = (long) synapseJsniUtils.getFileSize(blob);
    // check
    if (fileSize > OLD_BROWSER_MAX_SIZE) {
      throw new IllegalArgumentException(
        DisplayConstants.LARGE_FILE_ON_UNSUPPORTED_BROWSER
      );
    }
  }

  /**
   * Look for a file with the same name (if we aren't uploading to an existing File already).
   *
   * @param fileName
   * @param callback Called when upload should continue. Otherwise, it is not called.
   */
  public void checkForExistingFileName(
    final String fileName,
    final Callback callback
  ) {
    if (entity != null || currentFileParentEntityId == null) {
      callback.invoke();
    } else {
      synapseClient.getFileEntityIdWithSameName(
        fileName,
        currentFileParentEntityId,
        new AsyncCallback<String>() {
          @Override
          public void onSuccess(final String result) {
            // there was already a file with this name in the directory.

            // confirm we can overwrite
            view.showConfirmDialog(
              "A file named \"" +
              fileName +
              "\" (" +
              result +
              ") already exists in this location. Do you want to update the existing file and create a new version?",
              new Callback() {
                @Override
                public void invoke() {
                  // yes, override
                  entityId = result;
                  callback.invoke();
                }
              },
              new Callback() {
                @Override
                public void invoke() {
                  processNextFile();
                }
              }
            );
          }

          @Override
          public void onFailure(Throwable caught) {
            if (caught instanceof NotFoundException) {
              // there was not already a file with this name in this directory.
              callback.invoke();
            } else if (caught instanceof ConflictException) {
              // there was an entity found with same parent ID and name, but
              // it was not a File Entity.
              view.showErrorMessage(
                "An item named \"" +
                fileName +
                "\" already exists in this location. File could not be uploaded."
              );
              processNextFile();
            } else {
              uploadError(caught.getMessage(), caught);
            }
          }
        }
      );
    }
  }

  public void directUploadStep2(String fileName) {
    // use S3 direct uploader
    JavaScriptObject currentFile = synapseJsniUtils.getFileBlob(
      currIndex,
      fileList
    );
    String contentType = synapseJsniUtils.getContentType(fileList, currIndex);
    contentType = ContentTypeUtils.fixDefaultContentType(contentType, fileName);
    if (endpointUrl != null) {
      s3DirectUploader.configure(
        view.getS3DirectAccessKey(),
        view.getS3DirectSecretKey(),
        bucketName,
        endpointUrl
      );
      s3DirectUploader.uploadFile(
        fileName,
        contentType,
        currentFile,
        this,
        keyPrefixUUID,
        storageLocationId,
        view
      );
    } else {
      this.multiPartUploader.uploadFile(
          fileName,
          contentType,
          currentFile,
          this,
          storageLocationId,
          view
        );
    }
  }

  private void processNextFile() {
    if (currIndex + 1 == fileNames.length) {
      // uploading the last file
      if (!fileHasBeenUploaded) {
        // cancel the upload
        fireCancelEvent();
        clearState();
      } else {
        // finish upload
        view.updateProgress(.99d, "99%", "");
        uploadSuccess();
      }
    } else {
      // more files to upload
      uploadNextFile();
    }
  }

  public void setFileEntityFileHandle(String fileHandleId) {
    if (entityId != null || currentFileParentEntityId != null) {
      synapseClient.setFileEntityFileHandle(
        fileHandleId,
        entityId,
        currentFileParentEntityId,
        new AsyncCallback<String>() {
          @Override
          public void onSuccess(String entityId) {
            fileHasBeenUploaded = true;
            if (currIndex + 1 == fileNames.length) {
              // to new file handle id, or create new file entity with this file handle id
              view.hideLoading();
              refreshAfterSuccessfulUpload(entityId);
            } else {
              // more files to upload
              uploadNextFile();
            }
          }

          @Override
          public void onFailure(Throwable t) {
            uploadError(t.getMessage(), t);
          }
        }
      );
    }
    if (fileHandleIdCallback != null) {
      fileHandleIdCallback.invoke(fileHandleId);
      uploadSuccess();
    }
  }

  public void uploadNextFile() {
    currIndex++;
    // SWC-4274: reset entity id
    Uploader.this.entityId = null;
    handleUploads();
  }

  @Override
  public void setExternalFilePath(
    String path,
    String name,
    Long storageLocationId
  ) {
    if (path.trim().contains(" ")) {
      // encode for user
      path = gwt.encode(path);
      view.setExternalUrl(path);
    }

    boolean isUpdating = entityId != null || entity != null;
    if (isUpdating) {
      // existing entity
      updateExternalFileEntity(
        entityId,
        path,
        name,
        null,
        null,
        null,
        storageLocationId
      );
    } else {
      // new data, use the appropriate synapse call
      createNewExternalFileEntity(
        path,
        name,
        null,
        null,
        null,
        storageLocationId
      );
    }
  }

  public AsyncCallback<Entity> getExternalFileUpdatedCallback() {
    return new AsyncCallback<Entity>() {
      @Override
      public void onSuccess(Entity result) {
        entity = result;
        view.showInfo(DisplayConstants.TEXT_LINK_SUCCESS);
        if (successHandler != null) {
          successHandler.onSuccessfulUpload();
        }

        entityUpdated();
      }

      @Override
      public void onFailure(Throwable caught) {
        view.showErrorMessage(
          DisplayConstants.TEXT_LINK_FAILED + caught.getMessage()
        );
      }
    };
  }

  public void updateExternalFileEntity(
    String entityId,
    String path,
    String name,
    Long fileSize,
    String contentType,
    String md5,
    Long storageLocationId
  ) {
    try {
      synapseClient.updateExternalFile(
        entityId,
        path,
        name,
        contentType,
        fileSize,
        md5,
        storageLocationId,
        getExternalFileUpdatedCallback()
      );
    } catch (Throwable t) {
      view.showErrorMessage(DisplayConstants.TEXT_LINK_FAILED + t.getMessage());
    }
  }

  public void createNewExternalFileEntity(
    final String path,
    final String name,
    Long fileSize,
    String contentType,
    String md5,
    final Long storageLocationId
  ) {
    try {
      synapseClient.createExternalFile(
        currentFileParentEntityId,
        path,
        name,
        contentType,
        fileSize,
        md5,
        storageLocationId,
        getExternalFileUpdatedCallback()
      );
    } catch (RestServiceException e) {
      view.showErrorMessage(DisplayConstants.TEXT_LINK_FAILED + e.getMessage());
    }
  }

  @Override
  public void disableMultipleFileUploads() {
    view.enableMultipleFileUploads(false);
  }

  public void enableMultipleFileUploads() {
    view.enableMultipleFileUploads(true);
  }

  public void setUploaderLinkNameVisible(boolean visible) {
    view.setUploaderLinkNameVisible(visible);
  }

  public void setSuccessHandler(UploadSuccessHandler successHandler) {
    this.successHandler = successHandler;
  }

  public void setCancelHandler(CancelHandler handler) {
    this.cancelHandler = handler;
  }

  public void entityUpdated() {
    eventBus.fireEvent(new EntityUpdatedEvent());
  }

  /**
   * This method is called after the form submit is complete. Note that this is used for use case A
   * and B (see above).
   */
  @Override
  public void handleSubmitResult(String resultHtml) {
    if (resultHtml == null) resultHtml = "";
    // response from server
    // try to parse
    UploadResult uploadResult = null;
    String detailedErrorMessage = null;
    try {
      uploadResult = AddAttachmentHelper.getUploadResult(resultHtml);
      handleSubmitResult(uploadResult);
    } catch (Throwable th) {
      detailedErrorMessage = th.getMessage();
    }
    // wasn't an UplaodResult

    if (uploadResult == null) {
      if (!resultHtml.contains(DisplayConstants.UPLOAD_SUCCESS)) {
        uploadError(detailedErrorMessage, new Exception());
      } else {
        uploadSuccess();
      }
    }
  }

  public void handleSubmitResult(UploadResult uploadResult) {
    if (uploadResult.getUploadStatus() == UploadStatus.SUCCESS) {
      if (
        currentUploadType == null || currentUploadType.equals(UploadType.S3)
      ) {
        // upload result has file handle id if successful
        String fileHandleId = uploadResult.getMessage();
        setFileEntityFileHandle(fileHandleId);
      }
    } else {
      if (isJschAuthorizationError(uploadResult.getMessage())) {
        uploadError(
          DisplayConstants.INVALID_USERNAME_OR_PASSWORD,
          new UnauthorizedException(uploadResult.getMessage())
        );
      } else {
        uploadError(
          "Upload result status indicated upload was unsuccessful. " +
          uploadResult.getMessage(),
          new Exception(uploadResult.getMessage())
        );
      }
    }
  }

  public boolean isJschAuthorizationError(String message) {
    if (message != null) {
      String lowerCaseMessage = message.toLowerCase();
      if (
        lowerCaseMessage.contains("jschexception") &&
        lowerCaseMessage.contains("auth fail")
      ) {
        return true;
      }
    }
    return false;
  }

  public void showCancelButton(boolean showCancel) {
    view.setShowCancelButton(showCancel);
  }

  @Override
  public void cancelClicked() {
    fireCancelEvent();
  }

  /*
   * Private Methods
   */
  private void refreshAfterSuccessfulUpload(String entityId) {
    jsClient.getEntity(
      entityId,
      OBJECT_TYPE.FileEntity,
      new AsyncCallback<Entity>() {
        @Override
        public void onSuccess(Entity result) {
          entity = result;
          uploadSuccess();
        }

        @Override
        public void onFailure(Throwable caught) {
          view.showErrorMessage(caught.getMessage());
        }
      }
    );
  }

  public void uploadError(String message, Throwable t) {
    view.showErrorMessage(DisplayConstants.ERROR_UPLOAD_TITLE, message);
    fireCancelEvent();
  }

  private void fireCancelEvent() {
    // Verified that when this method is called, the input field used for direct upload is no longer
    // available,
    // so that this effectively cancels chunked upload too (after the current chunk upload completes)
    multiPartUploader.cancelUpload();
    view.hideLoading();
    view.clear();
    if (cancelHandler != null) {
      cancelHandler.onCancel();
    }
    view.resetToInitialState();
  }

  private void uploadSuccess() {
    view.showInfo(DisplayConstants.TEXT_UPLOAD_SUCCESS);
    view.clear();
    view.resetToInitialState();
    resetUploadProgress();
    if (successHandler != null) {
      successHandler.onSuccessfulUpload();
    }
    entityUpdated();
  }

  private void resetUploadProgress() {
    fileNames = null;
    fileHasBeenUploaded = false;
    currIndex = 0;
  }

  /**
   * For testing purposes
   *
   * @return
   */
  public void setFileNames(String[] fileNames) {
    this.fileNames = fileNames;
  }

  @Override
  public void updateProgress(
    double currentProgress,
    String progressText,
    String uploadSpeed
  ) {
    view.showProgressBar();
    double percentOfAllFiles = calculatePercentOverAllFiles(
      this.fileNames.length,
      this.currIndex,
      currentProgress
    );
    String textOfAllFiles =
      percentFormat.format(percentOfAllFiles * 100.0) + "% ";
    view.updateProgress(percentOfAllFiles, textOfAllFiles, uploadSpeed);
  }

  @Override
  public void uploadSuccess(String fileHandleId) {
    this.setFileEntityFileHandle(fileHandleId);
  }

  @Override
  public void uploadFailed(String string) {
    this.uploadError(string, new Exception(string));
    jsClient.logError(new Exception(string));
  }

  /**
   * Calculate the upload progress over all file upload given the progress of the current file. This
   * method assumes each file contributes equally to the total upload times.
   *
   * @param numberFiles Number of files to upload.
   * @param currentFileIndex Index of the current file with zero being the first file.
   * @param percentOfCurrentFile The percent complete for the current file. This number should be
   *        between 0.0 and 1.0 (%/100).
   * @return
   */
  public static double calculatePercentOverAllFiles(
    int numberFiles,
    int currentFileIndex,
    double percentOfCurrentFile
  ) {
    double percentPerFile = 1.0 / (double) numberFiles;
    double percentOfAllFiles =
      percentPerFile *
      percentOfCurrentFile +
      (percentPerFile * currentFileIndex);
    return percentOfAllFiles;
  }

  @Override
  public Long getStorageLocationId() {
    return this.storageLocationId;
  }
}


text:
<!DOCTYPE html>
<title>MessageEvent constructor</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/service-workers/service-worker/resources/test-helpers.sub.js"></script>
<script>
test(function() {
  var ev = new MessageEvent("test")
  assert_equals(ev.type, "test", "type attribute")
  assert_equals(ev.target, null, "target attribute")
  assert_equals(ev.currentTarget, null, "currentTarget attribute")
  assert_equals(ev.eventPhase, Event.NONE, "eventPhase attribute")
  assert_equals(ev.bubbles, false, "bubbles attribute")
  assert_equals(ev.cancelable, false, "cancelable attribute")
  assert_equals(ev.defaultPrevented, false, "defaultPrevented attribute")
  assert_equals(ev.isTrusted, false, "isTrusted attribute")
  assert_true(ev.timeStamp > 0, "timeStamp attribute")
  assert_true("initMessageEvent" in ev, "initMessageEvent operation")
  assert_equals(ev.data, null, "data attribute")
  assert_equals(ev.origin, "", "origin attribute")
  assert_equals(ev.lastEventId, "", "lastEventId attribute")
  assert_equals(ev.source, null, "source attribute")
  assert_array_equals(ev.ports, [], "ports attribute")
}, "Default event values")

test(function() {
  var channel = new MessageChannel()
  var ev = new MessageEvent("test", { data: "testData", origin: "testOrigin", lastEventId: "testId", source: window, ports: [channel.port1] })
  assert_equals(ev.type, "test", "type attribute")
  assert_equals(ev.data, "testData", "data attribute")
  assert_equals(ev.origin, "testOrigin", "origin attribute")
  assert_equals(ev.lastEventId, "testId", "lastEventId attribute")
  assert_equals(ev.source, window, "source attribute")
  assert_array_equals(ev.ports, [channel.port1], "ports attribute")
}, "MessageEventInit dictionary")

test(function() {
  assert_throws(new TypeError(), function() {
    new MessageEvent("test", { ports: null })
  })
}, "Passing null for ports member")

test(function() {
  var ev = new MessageEvent("test", { ports: [] })
  assert_true(Array.isArray(ev.ports), "Array.isArray() should return true")
  assert_true(Object.isFrozen(ev.ports), "Object.isFrozen() should return true")
  assert_true(ev.ports === ev.ports, "ev.ports should return the same object")
}, "ports attribute should be a FrozenArray")

test(function() {
  var ev = document.createEvent("messageevent");
  var channel = new MessageChannel()
  ev.initMessageEvent("test", true, false, "testData", "testOrigin", "testId", window, [channel.port1])
  assert_equals(ev.type, "test", "type attribute")
  assert_equals(ev.bubbles, true, "bubbles attribute")
  assert_equals(ev.cancelable, false, "bubbles attribute")
  assert_equals(ev.data, "testData", "data attribute")
  assert_equals(ev.origin, "testOrigin", "origin attribute")
  assert_equals(ev.lastEventId, "testId", "lastEventId attribute")
  assert_equals(ev.source, window, "source attribute")
  assert_array_equals(ev.ports, [channel.port1], "ports attribute")
}, "initMessageEvent operation")

test(function() {
  var ev = document.createEvent("messageevent")
  assert_throws(new TypeError(), function() {
    ev.initMessageEvent("test", true, false, "testData", "testOrigin", "testId", window, null)
  })
}, "Passing null for ports parameter to initMessageEvent")

test(function() {
  var ev = document.createEvent("messageevent")
  assert_equals(MessageEvent.prototype.initMessageEvent.length, 8, "MessageEvent.prototype.initMessageEvent.length should be 8")
  assert_throws(new TypeError(), function() {
    ev.initMessageEvent("test", true, false, "testData", "testOrigin", "testId", window)
  }, "Calling initMessageEvent with only 7 parameters should throw a TypeError")
}, "All parameters to initMessageEvent should be mandatory")

promise_test(function(t) {
    var worker_url = "/service-workers/service-worker/resources/empty-worker.js";
    var scope = "/service-workers/service-worker/resources/";
    var registration;

    return service_worker_unregister_and_register(t, worker_url, scope)
      .then(function(r) {
          registration = r;
          return wait_for_state(t, r.installing, "activated");
        })
      .then(function() {
          var ev = new MessageEvent("test", { source: registration.active });
          assert_equals(ev.source, registration.active, "source attribute should return the ServiceWorker");
          service_worker_unregister(t, scope);
        });
  }, "Passing ServiceWorker for source member");

</script>


text:
package oceanconnect

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestRenewal(t *testing.T) {
	var response string
	reqCount := 0

	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		reqCount++
		fmt.Fprintln(w, response)
	}))
	defer s.Close()

	c := Client{
		c: &http.Client{},
		cfg: Config{
			URL:   s.URL,
			AppID: "<appid>",
		},
	}

	// Test with 300 sec expiry a immediate re-login is issued
	response = `{"accessToken":"85fe3222f362e3b6e943e483bd9c6f9b","tokenType":"bearer","refreshToken":null,"expiresIn":300,"scope":"default"}`
	assert.Nil(t, c.Login(), "expected no error for login")
	assert.Equal(t, 1, reqCount, "request-counter should be 1")

	req, err := http.NewRequest(http.MethodGet, s.URL, nil)
	assert.Nil(t, err, "couldn't get http-request")
	_, err = c.doRequest(req)
	assert.Nil(t, err, "requestFailed")
	assert.Equal(t, 3, reqCount, "request-counter should be 3")

	// Test with 305 sec expiry which shouldnt cause re-login
	response = `{"accessToken":"85fe3222f362e3b6e943e483bd9c6f9b","tokenType":"bearer","refreshToken":null,"expiresIn":305,"scope":"default"}`
	assert.Nil(t, c.Login(), "expected no error for login")
	assert.Equal(t, 4, reqCount, "request-counter should be 4")

	req2, err := http.NewRequest(http.MethodGet, s.URL, nil)
	assert.Nil(t, err, "couldn't get second http-request")
	_, err = c.doRequest(req2)
	assert.Nil(t, err, "requestFailed")
	assert.Equal(t, 5, reqCount, "request-counter should be 5")
}


text:
<?php

// require_once 'Zend/Cloud/Infrastructure/Image.php';

/**
 * List of images
 *
 * @package    Zend_Cloud
 * @subpackage Infrastructure
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cloud_Infrastructure_ImageList implements Countable, Iterator, ArrayAccess
{
    /**
     * @var array Array of Zend_Cloud_Infrastructure_Image
     */
    protected $images = array();

    /**
     * @var int Iterator key
     */
    protected $iteratorKey = 0;

    /**
     * The Image adapter (if exists)
     *
     * @var object
     */
    protected $adapter;

    /**
     * Constructor
     *
     * @param  array $list
     * @param  null|object $adapter
     * @return boolean
     */
    public function __construct($images, $adapter = null)
    {
        if (empty($images) || !is_array($images)) {
            // require_once 'Zend/Cloud/Infrastructure/Exception.php';
            throw new Zend_Cloud_Infrastructure_Exception(__CLASS__ . ' expects an array of images');
        }

        $this->adapter = $adapter;
        $this->constructFromArray($images);
    }

    /**
     * Transforms the Array to array of Instances
     *
     * @param  array $list
     * @return void
     */
    protected function constructFromArray(array $list)
    {
        foreach ($list as $image) {
            $this->addImage(new Zend_Cloud_Infrastructure_Image($image, $this->adapter));
        }
    }

    /**
     * Add an image
     *
     * @param  Image
     * @return ImageList
     */
    protected function addImage(Zend_Cloud_Infrastructure_Image $image)
    {
        $this->images[] = $image;
        return $this;
    }

    /**
     * Return number of images
     *
     * Implement Countable::count()
     *
     * @return int
     */
    public function count()
    {
        return count($this->images);
    }

    /**
     * Return the current element
     *
     * Implement Iterator::current()
     *
     * @return Image
     */
    public function current()
    {
        return $this->images[$this->iteratorKey];
    }

    /**
     * Return the key of the current element
     *
     * Implement Iterator::key()
     *
     * @return int
     */
    public function key()
    {
        return $this->iteratorKey;
    }

    /**
     * Move forward to next element
     *
     * Implement Iterator::next()
     *
     * @return void
     */
    public function next()
    {
        $this->iteratorKey++;
    }

    /**
     * Rewind the Iterator to the first element
     *
     * Implement Iterator::rewind()
     *
     * @return void
     */
    public function rewind()
    {
        $this->iteratorKey = 0;
    }

    /**
     * Check if there is a current element after calls to rewind() or next()
     *
     * Implement Iterator::valid()
     *
     * @return bool
     */
    public function valid()
    {
        $numItems = $this->count();
        if ($numItems > 0 && $this->iteratorKey < $numItems) {
            return true;
        }
        return false;
    }

    /**
     * Whether the offset exists
     *
     * Implement ArrayAccess::offsetExists()
     *
     * @param   int     $offset
     * @return  bool
     */
    public function offsetExists($offset)
    {
        return ($offset < $this->count());
    }

    /**
     * Return value at given offset
     *
     * Implement ArrayAccess::offsetGet()
     *
     * @param   int     $offset
     * @throws  Zend_Cloud_Infrastructure_Exception
     * @return  Image
     */
    public function offsetGet($offset)
    {
        if (!$this->offsetExists($offset)) {
            // require_once 'Zend/Cloud/Infrastructure/Exception.php';
            throw new Zend_Cloud_Infrastructure_Exception('Illegal index');
        }
        return $this->images[$offset];
    }

    /**
     * Throws exception because all values are read-only
     *
     * Implement ArrayAccess::offsetSet()
     *
     * @param   int     $offset
     * @param   string  $value
     * @throws  Zend_Cloud_Infrastructure_Exception
     */
    public function offsetSet($offset, $value)
    {
        // require_once 'Zend/Cloud/Infrastructure/Exception.php';
        throw new Zend_Cloud_Infrastructure_Exception('You are trying to set read-only property');
    }

    /**
     * Throws exception because all values are read-only
     *
     * Implement ArrayAccess::offsetUnset()
     *
     * @param   int     $offset
     * @throws  Zend_Cloud_Infrastructure_Exception
     */
    public function offsetUnset($offset)
    {
        // require_once 'Zend/Cloud/Infrastructure/Exception.php';
        throw new Zend_Cloud_Infrastructure_Exception('You are trying to unset read-only property');
    }
}


text:
<?php

namespace hipanel\modules\ticket\widgets;

use Yii;
use yii\helpers\Html;
use yii\jui\Widget;

class Topic extends Widget
{
    public $topics;

    private function _getColor($item): string
    {
        $colors = [
            'general' => 'label-default',
            'technical' => 'label-primary',
            'vds' => 'label-info',
            'domain' => 'label-success',
            'financial' => 'label-warning',
        ];

        return $colors[$item] ?? $colors['general'];
    }

    public function run()
    {
        if ($this->topics) {
            $html = '
';
            foreach ($this->topics as $item => $label) {
                $label = Yii::t('hipanel:ticket', Html::encode($label));
                $html .= Html::tag('li', Html::tag('span', $label, ['class' => 'label ' . $this->_getColor($item)]));
            }
            $html .= '
';
            echo $html;
        }
    }
}


text:
package cn.ben.tvdemo.data.tvchannel.source.remote;

import java.util.List;

import cn.ben.tvdemo.constant.Constants;
import cn.ben.tvdemo.data.tvchannel.TVChannels;
import cn.ben.tvdemo.data.tvchannel.source.TVChannelsDataSource;
import io.reactivex.Observable;
import io.reactivex.functions.Function;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;

public class TVChannelsRemoteDataSource implements TVChannelsDataSource {
    private static final String LOAD_TV_CHANNELS_BASE_URL = "http://api.avatardata.cn/TVTime/";
    private volatile static TVChannelsRemoteDataSource instance = null;

    public static TVChannelsRemoteDataSource getInstance() {
        if (instance == null) {
            synchronized (TVChannelsRemoteDataSource.class) {
                if (instance == null) {
                    instance = new TVChannelsRemoteDataSource();
                }
            }
        }
        return instance;
    }

    private TVChannelsRemoteDataSource() {
    }

    @Override
    public Observable<List<TVChannels.TVChannel>> getTVChannelsWithPID(String pId) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(LOAD_TV_CHANNELS_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        TVChannelsService service = retrofit.create(TVChannelsService.class);
        Observable<TVChannels> call = service.getTVChannels(Constants.API_KEY, pId);

        return call
                .map(new Function<TVChannels, List<TVChannels.TVChannel>>() {
                    @Override
                    public List<TVChannels.TVChannel> apply(TVChannels tvChannels) throws Exception {
                        if (tvChannels.getError_code() != 0)
                            throw new Exception(tvChannels.getReason());
                        return tvChannels.getResult();
                    }
                });
    }

    @Override
    public void deleteAllTVChannelsWithPID(String pId) {
    }

    @Override
    public void saveTVChannel(TVChannels.TVChannel tvChannel) {
    }

    @Override
    public void cleanup() {
        instance = null;
    }

    @SuppressWarnings("SameParameterValue")
    interface TVChannelsService {
        @GET("LookUp")
        Observable<TVChannels> getTVChannels(@Query("key") String key, @Query("pId") String pId);
    }
}


text:
function DoParameterTypesReplacement(sText)
{
  //replace string with const char*
  var sOutput = sText.replace(/string /g, "const char* ");

  //Replace position with long
  sOutput = sOutput.replace(/position /g, "long ");

  //Replace bool with BOOL
  sOutput = sOutput.replace(/bool /g, "BOOL ");

  //Replace textrange with textrange*
  sOutput = sOutput.replace(/textrange /g, "TextRange* ");

  //Replace cells with char*
  sOutput = sOutput.replace(/cells /g, "char* ");

  //Replace stringresult with char*
  sOutput = sOutput.replace(/stringresult /g, "char* ");

  //Replace colour with COLORREF
  sOutput = sOutput.replace(/colour /g, "COLORREF ");

  //Replace colour with TextToFind*
  sOutput = sOutput.replace(/findtext /g, "TextToFind* ");

  //Replace keymod with DWORD
  sOutput = sOutput.replace(/keymod /g, "DWORD ");

  //Replace formatrange with long
  sOutput = sOutput.replace(/formatrange /g, "RangeToFormat* ");

  return sOutput;
}

function FindBodyParameters(sLine)
{
  var nStartParameters = sLine.indexOf("(");
  var nEndParameters = sLine.indexOf(")");
  var sParameters = sLine.substr(nStartParameters+1, nEndParameters - nStartParameters - 1);

  //Change the parameter types to something which the C++ compiler understands
  sParameters = DoParameterTypesReplacement(sParameters);

  //No first parameter
  if (sParameters.charAt(0) == ",")
    sParameters = "0" + sParameters;
  else
    sParameters = "(WPARAM) " + sParameters;

  //No second parameter
  if (sParameters.charAt(sParameters.length-1) == ",")
    sParameters += " 0";
  else
  {
    var nComma = sParameters.indexOf(", ");
    var sTemp = sParameters.substr(0, nComma + 2);
    sTemp += "(LPARAM)";
    sTemp += sParameters.substr(nComma + 1, sParameters.length - nComma);
    sParameters = sTemp;
  }

  //Ensure we have a "," at the end of the parameters list
  if (sParameters.length && sParameters.charAt(sParameters.length - 1) != ",")
    sParameters += ", ";

  //Add the "bDirect" parameter
  sParameters += "bDirect";

  //Remove the parameter types from the parameter string
  sParameters = sParameters.replace(/const char\*\ /g, "");
  sParameters = sParameters.replace(/long\ /g, "");
  sParameters = sParameters.replace(/int\ /g, "");
  sParameters = sParameters.replace(/BOOL\ /g, "");
  sParameters = sParameters.replace(/TextRange\*\ /g, "");
  sParameters = sParameters.replace(/char\*\ /g, "");
  sParameters = sParameters.replace(/COLORREF\ /g, "");
  sParameters = sParameters.replace(/TextToFind\*\ /g, "");
  sParameters = sParameters.replace(/DWORD\ /g, "");
  sParameters = sParameters.replace(/RangeToFormat\*\ /g, "");

  return sParameters;
}

function FindHeaderParameters(sLine, bDefault)
{
  //find the parameters
  var nStartParameters = sLine.indexOf("(");
  var nEndParameters = sLine.indexOf(")");
  var sParameters = sLine.substr(nStartParameters+1, nEndParameters - nStartParameters - 1);

  //Change the parameter types to something which the C++ compiler understands
  sParameters = DoParameterTypesReplacement(sParameters);

  //No first parameter
  if (sParameters.charAt(0) == ",")
    sParameters = sParameters.substr(2, sParameters.length - 2);

  //No second parameter
  if (sParameters.charAt(sParameters.length-1) == ",")
    sParameters = sParameters.substr(0, sParameters.length - 1);

  //Ensure we have a "," at the end of the parameters list
  if (sParameters.length && sParameters.charAt(sParameters.length - 1) != ",")
    sParameters += ", ";

  //Add the special "BOOL bDirect = TRUE" default parameter
  if (bDefault)
    sParameters += "BOOL bDirect = TRUE";
  else
    sParameters += "BOOL bDirect";

  return sParameters;
}

function FindFunctionNameAndReturn(sLine)
{
  //Find the name of the function
  var nFirstSpace = sLine.indexOf(" ");
  var sTemp = sLine.substr(nFirstSpace+1, sLine.length - nFirstSpace);
  var nEquals = sTemp.indexOf("=");
  var sFunction = sTemp.substr(0, nEquals);

  return sFunction;
}

function FindFunctionName(sLine)
{
  //Find the name of the function
  var nFirstSpace = sLine.indexOf(" ");
  var sTemp = sLine.substr(nFirstSpace+1, sLine.length - nFirstSpace);
  nFirstSpace = sTemp.indexOf(" ");
  sTemp = sTemp.substr(nFirstSpace+1, sTemp.length - nFirstSpace);
  var nEquals = sTemp.indexOf("=");
  var sFunction = sTemp.substr(0, nEquals);

  return sFunction;
}

function HandleFunctionHeader(sLine, bDefault)
{
  //parse out the parameters from the line
  var sParameters = FindHeaderParameters(sLine, bDefault);

  //Find the name of the function
  var sFunctionNameAndReturn = FindFunctionNameAndReturn(sLine);

  //Replace SetFocus with SCISetFocus (to avoid conflict with CWnd::SetFocus)
  sFunctionNameAndReturn = sFunctionNameAndReturn.replace(/SetFocus/g, "SCISetFocus");

  //Create the header output line
  var sOutput = sFunctionNameAndReturn + "(" + sParameters + ")" + ";";

  //Change the parameter types to something which the C++ compiler understands
  sOutput = DoParameterTypesReplacement(sOutput);

  return sOutput;
}

function HandleFunctionBody(sLine)
{
  //Get the basic function header from the other function
  var sHeader = HandleFunctionHeader(sLine, false);

  //Trim off the terminating ";"
  var sHeader = sHeader.substr(0, sHeader.length - 1);

  //Add the C++ class scoping
  var nFirstSpace = sHeader.indexOf(" ");
  var sBody = sHeader.substr(0, nFirstSpace + 1) + " CScintillaCtrl::" + sHeader.substr(nFirstSpace + 1, sHeader.length - nFirstSpace - 1);

  //Remove any padding between the scoping
  //sBody = sParameters.replace(/:: /g, "::");

  //Remove any padding before the class name
  sBody = sBody.replace(/\  CScintillaCtrl::/, " CScintillaCtrl::");

  //Work out the message type from the line
  var sMessage = "SCI_" + FindFunctionName(sLine).toUpperCase();

  //parse out the parameters from the line
  var sParameters = FindBodyParameters(sLine, false);

  //Add the start of the function
  sBody += "\r\n" + "{\r\n";

  //Have we a return value from this function
  if (FindFunctionNameAndReturn(sLine).indexOf("void") != 0)
  {
    sBody += "  return Call(";
  }
  else
  {
    //Add the "Call" function
    sBody += "  Call(";
  }

  //Complete the function body
  sBody += sMessage + ", " + sParameters + ");\r\n}\r\n";

  return sBody;
}

//The actual script implementation

//Ensure the number of arguments are correct
if (WScript.Arguments.length < 1)
{
  WScript.Echo("Usage: ConvertScintillaiface PathToScintillaiface [/CPP]");
  WScript.Quit(1);
}

//Create the file system object
var g_FSO = new ActiveXObject("Scripting.FileSystemObject");

//Open the file as text for parsing
var ifaceFile = g_FSO.OpenTextFile(WScript.Arguments(0), 1, false);

var bCreateHeader = true;
if (WScript.Arguments.length >= 2)
{
  if (WScript.Arguments(1) == "/CPP")
    bCreateHeader = false;
}

//Read in all the text from the file
var bHandlingDeprecatedCategory = false;
var sLine;
while(!ifaceFile.AtEndOfStream)
{
  sLine = ifaceFile.ReadLine();
  if (sLine.length)
  {
    if (sLine.charAt(0) != "#")
    {
      if (sLine.indexOf("fun") == 0)
      {
        if (!bHandlingDeprecatedCategory)
        {
          if (bCreateHeader)
            WScript.Echo(HandleFunctionHeader(sLine, true));
          else
            WScript.Echo(HandleFunctionBody(sLine));
        }
      }
      else if (sLine.indexOf("get") == 0)
      {
        var sFunctionName = FindFunctionName(sLine);

        if (!bHandlingDeprecatedCategory && sFunctionName != "GetDirectFunction" && sFunctionName != "GetDirectPointer")
        {
          if (bCreateHeader)
            WScript.Echo(HandleFunctionHeader(sLine, true));
          else
            WScript.Echo(HandleFunctionBody(sLine));
        }
      }
      else if (sLine.indexOf("set") == 0)
      {
        if (!bHandlingDeprecatedCategory)
        {
          if (bCreateHeader)
            WScript.Echo(HandleFunctionHeader(sLine, true));
          else
            WScript.Echo(HandleFunctionBody(sLine));
        }
      }
      else if (sLine.indexOf("cat") == 0)
      {
        if (sLine.indexOf("Deprecated") != -1)
          bHandlingDeprecatedCategory = true;
        else
          bHandlingDeprecatedCategory = false;
      }
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<comment>
		<sentence>
				<text>odlična , domaća i kvalitetna jela , brza dostava . </text>
				<pairs>
						<pair aspect="jela" anchor="odlična" link="+" sent="+" />
						<pair aspect="dostava" anchor="odlična" link="" sent="" />
						<pair aspect="jela" anchor="kvalitetna" link="+" sent="+" />
						<pair aspect="dostava" anchor="kvalitetna" link="" sent="" />
						<pair aspect="jela" anchor="brza" link="" sent="" />
						<pair aspect="dostava" anchor="brza" link="+" sent="+" />
				</pairs>
		</sentence>
		<sentence>
				<text>uvijek rado naručujem iz kuhače ! </text>
				<pairs />
		</sentence>
		<sentence>
				<text>ostanite ovakvo dobri ! </text>
				<pairs />
		</sentence>
</comment>


text:
use crate::io::AsyncWrite;

use pin_project_lite::pin_project;
use std::io;
use std::marker::PhantomPinned;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::{future::Future, io::IoSlice};

pin_project! {
    /// A future to write a slice of buffers to an `AsyncWrite`.
    #[derive(Debug)]
    #[must_use = "futures do nothing unless you `.await` or poll them"]
    pub struct WriteVectored<'a, 'b, W: ?Sized> {
        writer: &'a mut W,
        bufs: &'a [IoSlice<'b>],
        // Make this future `!Unpin` for compatibility with async trait methods.
        #[pin]
        _pin: PhantomPinned,
    }
}

pub(crate) fn write_vectored<'a, 'b, W>(
    writer: &'a mut W,
    bufs: &'a [IoSlice<'b>],
) -> WriteVectored<'a, 'b, W>
where
    W: AsyncWrite + Unpin + ?Sized,
{
    WriteVectored {
        writer,
        bufs,
        _pin: PhantomPinned,
    }
}

impl<W> Future for WriteVectored<'_, '_, W>
where
    W: AsyncWrite + Unpin + ?Sized,
{
    type Output = io::Result<usize>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<usize>> {
        let me = self.project();
        Pin::new(&mut *me.writer).poll_write_vectored(cx, me.bufs)
    }
}


text:
import {
  Component,
  ChangeDetectionStrategy,
  ViewChild,
  ElementRef,
  Input,
  Output,
  EventEmitter,
  ChangeDetectorRef,
  HostBinding,
} from '@angular/core';

import { MenuWrapperDirective } from '../menu-wrapper/menu-wrapper.directive';
import { OverlayService } from '../overlay/overlay.service';
import { MenuService } from '../menu-wrapper/menu.service';

@Component({
  selector: 'cd-menu-combo-button',
  templateUrl: './menu-combo-button.component.html',
  styleUrls: ['./menu-combo-button.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MenuComboButtonComponent extends MenuWrapperDirective {
  @Input() mainIconName = '';

  @ViewChild('arrow', { read: ElementRef, static: true }) _btnRef!: ElementRef;
  @Output() click = new EventEmitter<void>();

  constructor(
    protected _elemRef: ElementRef,
    protected _overlayService: OverlayService,
    protected _menuService: MenuService,
    protected _cdRef: ChangeDetectorRef
  ) {
    super(_elemRef, _overlayService, _menuService, _cdRef);
  }

  @HostBinding('class.title')
  @Input()
  actionTitle = '';

  handleSubscriptionClose = () => {
    this._btnRef.nativeElement.focus();
    this.active = false;
    this.cleanupComponentRef();
  };

  onClick(_e: MouseEvent) {
    // Capture click event and prevent menu from showing
  }

  onButtonClick(e: MouseEvent) {
    e.preventDefault();
    e.stopImmediatePropagation();
    this.click.emit();
  }

  onArrowClick(e: MouseEvent): void {
    e.preventDefault();
    e.stopImmediatePropagation();
    const target = e.currentTarget as HTMLElement;
    this.active = true;
    target.blur();
    this.createMenu();
  }
}