text:
package fi.nls.oskari.fe.input.format.gml;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.xml.stream.XMLStreamException;

import org.geotools.styling.Style;
import org.junit.Test;

import fi.nls.oskari.fe.engine.GroovyFeatureEngine;
import fi.nls.oskari.fe.input.XMLInputProcessor;
import fi.nls.oskari.fe.input.format.gml.recipe.GroovyParserRecipe;
import fi.nls.oskari.fe.output.OutputProcessor;
import fi.nls.oskari.fe.output.OutputStreamProcessor;
import fi.nls.oskari.fe.output.format.jsonld.JsonLdOutputProcessor;
import fi.nls.oskari.fe.output.format.png.geotools.MapContentOutputProcessor;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;

/**
 * @todo implement some asserts
 *
 */
public class TestInspireGML {

	interface TestOutputProcessor extends OutputProcessor {

		public int getFeatureCount();
	}

	static GroovyClassLoader gcl = new GroovyClassLoader();

	/**
	 *
	 * @param recipePath
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Class<GroovyParserRecipe> setupGroovyScript(final String recipePath) {

		InputStreamReader reader = new InputStreamReader(
				TestInspireGML.class.getResourceAsStream(recipePath));

		GroovyCodeSource codeSource = new GroovyCodeSource(reader, recipePath,
				".");

		Class<GroovyParserRecipe> recipeClazz = (Class<GroovyParserRecipe>) gcl
				.parseClass(codeSource, true);

		return recipeClazz;

	}

	/**
	 *
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IOException
	 * @throws XMLStreamException
	 */
	@Test
	public void test_CuzkCz_AU_WFS_GMLtoPNG() throws InstantiationException,
			IllegalAccessException, IOException, XMLStreamException {

		GroovyFeatureEngine engine = new GroovyFeatureEngine();

		XMLInputProcessor inputProcessor = new StaxGMLInputProcessor();

		Style sldStyle = MapContentOutputProcessor
				.createSLDStyle("/fi/nls/oskari/fe/output/style/INSPIRE_SLD/AU.AdministrativeUnit.Default.xml");

		OutputStreamProcessor outputProcessor = new MapContentOutputProcessor(
				"EPSG:3035", sldStyle);

		InputStream inp = getClass()
				.getResourceAsStream(
						"/fi/nls/oskari/fe/input/format/gml/au/cuzk_cz-wfs-ELF-AU-wfs.xml");

		try {
			inputProcessor.setInput(inp);

			FileOutputStream fouts = new FileOutputStream("AU-cuzk_cz.png");
			try {
				outputProcessor.setOutput(fouts);

				GroovyParserRecipe recipe = setupGroovyScript(
						"/fi/nls/oskari/fe/input/format/gml/au/INSPIRE_generic_AU.groovy")
						.newInstance();
				engine.setRecipe(recipe);

				engine.setInputProcessor(inputProcessor);
				engine.setOutputProcessor(outputProcessor);

				engine.process();

			} finally {
				fouts.close();
			}

		} finally {
			inp.close();
		}

	}

	/*
	 * @Test public void test_IgnFr_AU_WFS_GMLtoPNG() throws
	 * InstantiationException, IllegalAccessException, IOException,
	 * XMLStreamException {
	 *
	 * GroovyFeatureEngine engine = new GroovyFeatureEngine();
	 *
	 *
	 * Style sldStyle = MapContentOutputProcessor .createSLDStyle(
	 * "/fi/nls/oskari/fe/output/style/INSPIRE_SLD/AU.AdministrativeUnit.Default.xml"
	 * );
	 *
	 * OutputStreamProcessor outputProcessor = new MapContentOutputProcessor(
	 * "EPSG:3857", sldStyle);
	 *
	 * InputStream inp = getClass() .getResourceAsStream(
	 * "/fi/nls/oskari/fe/input/format/gml/au/ign_fr-ELF-AU-wfs.xml");
	 *
	 * try { inputProcessor.setInput(inp);
	 *
	 * FileOutputStream fouts = new FileOutputStream("AU-ign_fr.png"); try {
	 * outputProcessor.setOutput(fouts);
	 *
	 * GroovyParserRecipe recipe = setupGroovyScript(
	 * "/fi/nls/oskari/fe/input/format/gml/au/ELF_generic_AU.groovy").
	 * newInstance(); engine.setRecipe(recipe);
	 *
	 * engine.setInputProcessor(inputProcessor);
	 * engine.setOutputProcessor(outputProcessor);
	 *
	 * engine.process();
	 *
	 * } finally { fouts.close(); }
	 *
	 * } finally { inp.close(); }
	 *
	 * }
	 */

	/* Let's not - JSON-LD a bit too slow atm */
	/*
	 * @Test public void test_CuzkCz_AU_WFS_GMLtoJSONLD() throws
	 * InstantiationException, IllegalAccessException, IOException,
	 * XMLStreamException {
	 *
	 * GroovyFeatureEngine engine = new GroovyFeatureEngine();
	 *
	 * XMLInputProcessor inputProcessor = new StaxGMLInputProcessor();
	 * OutputStreamProcessor outputProcessor = new JsonLdOutputProcessor();
	 *
	 * InputStream inp = getClass() .getResourceAsStream(
	 * "/fi/nls/oskari/fe/input/format/gml/au/cuzk_cz-wfs-ELF-AU-wfs.xml.xml");
	 *
	 * try { inputProcessor.setInput(inp); FileOutputStream fouts = new
	 * FileOutputStream("AU.json"); try { outputProcessor.setOutput(fouts);
	 *
	 * GroovyParserRecipe recipe = setupGroovyScript(
	 * "/fi/nls/oskari/fe/input/format/gml/au/ELF_generic_AU.groovy")
	 * .newInstance(); engine.setRecipe(recipe);
	 *
	 * engine.setInputProcessor(inputProcessor);
	 * engine.setOutputProcessor(outputProcessor);
	 *
	 * engine.process(); } finally { fouts.close(); }
	 *
	 * } finally { inp.close(); }
	 *
	 * }
	 */

	/**
	 *
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IOException
	 * @throws XMLStreamException
	 */
	@Test
	public void test_IgnEs_GN_WFS_GMLtoPNG() throws InstantiationException,
			IllegalAccessException, IOException, XMLStreamException {

		GroovyFeatureEngine engine = new GroovyFeatureEngine();

		XMLInputProcessor inputProcessor = new StaxGMLInputProcessor();
		OutputStreamProcessor outputProcessor = new MapContentOutputProcessor(
				"EPSG:3857");

		InputStream inp = getClass()
				.getResourceAsStream(
						"/fi/nls/oskari/fe/input/format/gml/gn/ign_es-INSPIRE-GN-wfs.xml");

		try {
			inputProcessor.setInput(inp);

			FileOutputStream fouts = new FileOutputStream(
					"GN-INSPIRE-ign_es.png");
			try {
				outputProcessor.setOutput(fouts);

				GroovyParserRecipe recipe = setupGroovyScript(
						"/fi/nls/oskari/fe/input/format/gml/gn/INSPIRE_generic_GN.groovy")
						.newInstance();
				engine.setRecipe(recipe);

				engine.setInputProcessor(inputProcessor);
				engine.setOutputProcessor(outputProcessor);

				engine.process();

			} finally {
				fouts.close();
			}

		} finally {
			inp.close();
		}

	}

	/**
	 *
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IOException
	 * @throws XMLStreamException
	 */
	@Test
	public void test_IgnEs_GN_WFS_GMLtoJSONLD() throws InstantiationException,
			IllegalAccessException, IOException, XMLStreamException {

		GroovyFeatureEngine engine = new GroovyFeatureEngine();

		XMLInputProcessor inputProcessor = new StaxGMLInputProcessor();
		OutputStreamProcessor outputProcessor = new JsonLdOutputProcessor();

		InputStream inp = getClass()
				.getResourceAsStream(
						"/fi/nls/oskari/fe/input/format/gml/gn/ign_es-INSPIRE-GN-wfs.xml");

		try {
			inputProcessor.setInput(inp);
			FileOutputStream fouts = new FileOutputStream("GN-ign_es.json");
			try {
				outputProcessor.setOutput(fouts);

				GroovyParserRecipe recipe = setupGroovyScript(
						"/fi/nls/oskari/fe/input/format/gml/gn/INSPIRE_generic_GN.groovy")
						.newInstance();
				engine.setRecipe(recipe);

				engine.setInputProcessor(inputProcessor);
				engine.setOutputProcessor(outputProcessor);

				engine.process();
			} finally {
				fouts.close();
			}

		} finally {
			inp.close();
		}

	}

	/*
	 * @Test public void test_IgnEs_AU_WFS_GMLtoPNG() throws
	 * InstantiationException, IllegalAccessException, IOException,
	 * XMLStreamException {
	 *
	 * GroovyFeatureEngine engine = new GroovyFeatureEngine();
	 *
	 * XMLInputProcessor inputProcessor = new StaxGMLInputProcessor();
	 * OutputStreamProcessor outputProcessor = new MapContentOutputProcessor(
	 * "EPSG:3857");
	 *
	 * InputStream inp = getClass() .getResourceAsStream(
	 * "/fi/nls/oskari/fe/input/format/gml/au/ig_es-INSPIRE-AU-wfs.xml");
	 *
	 * try { inputProcessor.setInput(inp);
	 *
	 * FileOutputStream fouts = new FileOutputStream("AU-INSPIRE-ign_es.png");
	 * try { outputProcessor.setOutput(fouts);
	 *
	 * GroovyParserRecipe recipe = setupGroovyScript(
	 * "/fi/nls/oskari/fe/input/format/gml/au/INSPIRE_generic_AU.groovy").
	 * newInstance(); engine.setRecipe(recipe);
	 *
	 * engine.setInputProcessor(inputProcessor);
	 * engine.setOutputProcessor(outputProcessor);
	 *
	 * engine.process();
	 *
	 * } finally { fouts.close(); }
	 *
	 * } finally { inp.close(); }
	 *
	 * }
	 */

	/*
	 * @Test public void test_IgnEs_AU_WFS_GMLtoJSONLD() throws
	 * InstantiationException, IllegalAccessException, IOException,
	 * XMLStreamException {
	 *
	 * GroovyFeatureEngine engine = new GroovyFeatureEngine();
	 *
	 * XMLInputProcessor inputProcessor = new StaxGMLInputProcessor();
	 * OutputStreamProcessor outputProcessor = new JsonLdOutputProcessor();
	 *
	 * InputStream inp = getClass() .getResourceAsStream(
	 * "/fi/nls/oskari/fe/input/format/gml/au/ig_es-INSPIRE-AU-wfs.xml");
	 *
	 * try { inputProcessor.setInput(inp); FileOutputStream fouts = new
	 * FileOutputStream("AU-ign_es.json"); try {
	 * outputProcessor.setOutput(fouts);
	 *
	 * GroovyParserRecipe recipe = setupGroovyScript(
	 * "/fi/nls/oskari/fe/input/format/gml/au/INSPIRE_generic_AU.groovy").
	 * newInstance(); engine.setRecipe(recipe);
	 *
	 * engine.setInputProcessor(inputProcessor);
	 * engine.setOutputProcessor(outputProcessor);
	 *
	 * engine.process(); } finally { fouts.close(); }
	 *
	 * } finally { inp.close(); }
	 *
	 * }
	 */

	/* Let's not - JSON-LD a bit too slow atm */
	/*
	 * @Test public void test_GeonorgeNo_GN_WFS_GMLtoJSONLD() throws
	 * InstantiationException, IllegalAccessException, IOException,
	 * XMLStreamException {
	 *
	 * GroovyFeatureEngine engine = new GroovyFeatureEngine();
	 *
	 * XMLInputProcessor inputProcessor = new StaxGMLInputProcessor();
	 * OutputStreamProcessor outputProcessor = new JsonLdOutputProcessor();
	 *
	 * InputStream inp = getClass() .getResourceAsStream(
	 * "/fi/nls/oskari/fe/input/format/gml/gn/geonorge_no-ELF-GN-wfs.xml");
	 *
	 * try { inputProcessor.setInput(inp); FileOutputStream fouts = new
	 * FileOutputStream("GN.json"); try { outputProcessor.setOutput(fouts);
	 *
	 * GroovyParserRecipe recipe = setupGroovyScript(
	 * "/fi/nls/oskari/fe/input/format/gml/gn/ELF_generic_GN.groovy").
	 * .newInstance(); engine.setRecipe(recipe);
	 *
	 * engine.setInputProcessor(inputProcessor);
	 * engine.setOutputProcessor(outputProcessor);
	 *
	 * engine.process(); } finally { fouts.close(); }
	 *
	 * } finally { inp.close(); }
	 *
	 * }
	 */

	/**
	 *
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IOException
	 * @throws XMLStreamException
	 */
	@Test
	public void test_IgnEs_TN_WFS_GMLtoPNG()
			throws InstantiationException, IllegalAccessException, IOException,
			XMLStreamException {

		GroovyFeatureEngine engine = new GroovyFeatureEngine();

		XMLInputProcessor inputProcessor = new StaxGMLInputProcessor();

		Style sldStyle = MapContentOutputProcessor
				.createSLDStyle("/fi/nls/oskari/fe/output/style/INSPIRE_SLD/TN.RoadTransportNetwork.RoadLink.Default.sld");

		OutputStreamProcessor outputProcessor = new MapContentOutputProcessor(
				"EPSG:3785", sldStyle);

		InputStream inp = getClass()
				.getResourceAsStream(
						"/fi/nls/oskari/fe/input/format/gml/tn/ign_es-inspire-TN-wfs.xml");

		try {
			inputProcessor.setInput(inp);

			FileOutputStream fouts = new FileOutputStream("TN-ign_es.png");
			try {
				outputProcessor.setOutput(fouts);

				GroovyParserRecipe recipe = setupGroovyScript(
						"/fi/nls/oskari/fe/input/format/gml/tn/INSPIRE_generic_TN.groovy")
						.newInstance();
				engine.setRecipe(recipe);

				engine.setInputProcessor(inputProcessor);
				engine.setOutputProcessor(outputProcessor);

				engine.process();

			} finally {
				fouts.close();
			}

		} finally {
			inp.close();
		}

	}

}


text:
import {
    Component,
    Input,
    Inject,
    Optional,
    ViewChild,
} from '@angular/core';

import {
    NG_VALIDATORS,
    NG_ASYNC_VALIDATORS,
    NG_VALUE_ACCESSOR,
    NgModel,
} from '@angular/forms';

import {ElementBase} from '../element-base';

import {ValidatorArray} from '../validate';

@Component({
    selector: 'text',
    templateUrl: './text.component.html',
    styleUrls: ['./form.scss'],
    providers: [{
        provide: NG_VALUE_ACCESSOR,
        useExisting: TextComponent,
        multi: true,
    }]
})
export class TextComponent extends ElementBase<string> {
    @Input() public placeholder: string;

    @ViewChild(NgModel) public model: NgModel;

    constructor(
        @Optional() @Inject(NG_VALIDATORS) validators: ValidatorArray,
        @Optional() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: ValidatorArray
    ) {
        super(validators, asyncValidators);
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace vr {

class VectorIconTexture : public UiTexture {
 public:
  VectorIconTexture() {}

  VectorIconTexture(const VectorIconTexture&) = delete;
  VectorIconTexture& operator=(const VectorIconTexture&) = delete;

  ~VectorIconTexture() override {}

  void SetColor(SkColor color) { SetAndDirty(&color_, color); }

  SkColor GetColor() const { return color_; }

  void SetIcon(const gfx::VectorIcon* icon) { SetAndDirty(&icon_, icon); }

 private:
  void Draw(SkCanvas* sk_canvas, const gfx::Size& texture_size) override {
    if (icon_ == nullptr || icon_->is_empty())
      return;
    cc::SkiaPaintCanvas paint_canvas(sk_canvas);
    gfx::Canvas gfx_canvas(&paint_canvas, 1.0f);

    size_.set_height(texture_size.height());
    size_.set_width(texture_size.width());

    float icon_size = size_.height();
    float icon_corner_offset = (size_.height() - icon_size) / 2;
    VectorIcon::DrawVectorIcon(
        &gfx_canvas, *icon_, icon_size,
        gfx::PointF(icon_corner_offset, icon_corner_offset), color_);
  }

  gfx::SizeF size_;
  const gfx::VectorIcon* icon_ = nullptr;
  SkColor color_ = SK_ColorWHITE;
};

VectorIcon::VectorIcon(int texture_width)
    : texture_(std::make_unique<VectorIconTexture>()),
      texture_width_(texture_width) {}
VectorIcon::~VectorIcon() {}

void VectorIcon::SetColor(SkColor color) {
  texture_->SetColor(color);
}

SkColor VectorIcon::GetColor() const {
  return texture_->GetColor();
}

void VectorIcon::SetIcon(const gfx::VectorIcon& icon) {
  texture_->SetIcon(&icon);
}

void VectorIcon::SetIcon(const gfx::VectorIcon* icon) {
  texture_->SetIcon(icon);
}

UiTexture* VectorIcon::GetTexture() const {
  return texture_.get();
}

bool VectorIcon::TextureDependsOnMeasurement() const {
  return false;
}

gfx::Size VectorIcon::MeasureTextureSize() {
  return gfx::Size(texture_width_, texture_width_);
}

void VectorIcon::DrawVectorIcon(gfx::Canvas* canvas,
                                const gfx::VectorIcon& icon,
                                float size_px,
                                const gfx::PointF& corner,
                                SkColor color) {
  gfx::ScopedCanvas scoped(canvas);
  canvas->Translate(
      {static_cast<int>(corner.x()), static_cast<int>(corner.y())});

  // Don't use CreateVectorIcon() because its icon caching is not thread safe.
  // Instead, just redraw the VectorIcon.
  PaintVectorIcon(canvas, icon, size_px, color);
}

}  // namespace vr


text:
namespace web_app {

namespace {

void CompleteWith404(
    mojo::Remote<network::mojom::URLLoaderClient> loader_client) {
  auto generated_response = web_package::mojom::BundleResponse::New();
  generated_response->response_code = net::HTTP_NOT_FOUND;
  // Setting the Content-Type header makes Chrome return a nicer error page
  // that shows the actual error code ("HTTP ERROR 404") instead of just
  // "ERR_INVALID_RESPONSE".
  generated_response->response_headers["Content-Type"] =
      "text/html;charset=utf-8";
  auto response_head = web_package::CreateResourceResponse(generated_response);

  mojo::ScopedDataPipeConsumerHandle consumer_handle;
  mojo::ScopedDataPipeProducerHandle producer_handle;

  auto result = mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle);
  if (result != MOJO_RESULT_OK) {
    loader_client->OnComplete(
        network::URLLoaderCompletionStatus(net::ERR_INSUFFICIENT_RESOURCES));
    return;
  }
  producer_handle.reset();  // The response is empty.

  loader_client->OnReceiveResponse(std::move(response_head),
                                   std::move(consumer_handle), absl::nullopt);

  loader_client->OnComplete(network::URLLoaderCompletionStatus(net::OK));
}

void LogErrorMessageToConsole(int frame_tree_node_id,
                              const std::string& error_message) {
  // TODO(crbug.com/1334594): The console message will vanish from the console
  // if the user does not have the `Preserve Log` option enabled, since it is
  // triggered before the navigation commits. We should try to use a similar
  // approach as in crrev.com/c/3397976, but `FrameTreeNode` is not part of
  // content/public.

  // Find the `RenderFrameHost` associated with the `FrameTreeNode`
  // corresponding to the `frame_tree_node_id`, and then log the message.
  content::WebContents* web_contents =
      content::WebContents::FromFrameTreeNodeId(frame_tree_node_id);
  if (!web_contents) {
    return;
  }
  web_contents->ForEachRenderFrameHostWithAction(
      [frame_tree_node_id,
       &error_message](content::RenderFrameHost* render_frame_host) {
        if (render_frame_host->GetFrameTreeNodeId() == frame_tree_node_id) {
          render_frame_host->AddMessageToConsole(
              blink::mojom::ConsoleMessageLevel::kError, error_message);
          return content::RenderFrameHost::FrameIterationAction::kStop;
        }
        return content::RenderFrameHost::FrameIterationAction::kContinue;
      });
}

base::expected<std::reference_wrapper<const WebApp>, std::string>
FindIsolatedWebApp(Profile* profile, const IsolatedWebAppUrlInfo& url_info) {
  // TODO(b/242738845): Defer navigation in IsolatedAppThrottle until
  // WebAppProvider is ready to ensure we never fail this DCHECK.
  auto* web_app_provider = WebAppProvider::GetForWebApps(profile);
  DCHECK(web_app_provider->is_registry_ready());
  const WebAppRegistrar& registrar = web_app_provider->registrar();
  const WebApp* iwa = registrar.GetAppById(url_info.app_id());

  if (iwa == nullptr || !iwa->is_locally_installed()) {
    return base::unexpected(base::StrCat(
        {"Isolated Web App not installed: ", url_info.origin().Serialize()}));
  }

  if (!iwa->isolation_data().has_value()) {
    return base::unexpected(base::StrCat(
        {"App is not an Isolated Web App: ", url_info.origin().Serialize()}));
  }

  return *iwa;
}

}  // namespace

IsolatedWebAppURLLoaderFactory::IsolatedWebAppURLLoaderFactory(
    int frame_tree_node_id,
    Profile* profile,
    mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver)
    : network::SelfDeletingURLLoaderFactory(std::move(factory_receiver)),
      frame_tree_node_id_(frame_tree_node_id),
      profile_(profile) {}

IsolatedWebAppURLLoaderFactory::~IsolatedWebAppURLLoaderFactory() = default;

void IsolatedWebAppURLLoaderFactory::CreateLoaderAndStart(
    mojo::PendingReceiver<network::mojom::URLLoader> loader_receiver,
    int32_t request_id,
    uint32_t options,
    const network::ResourceRequest& resource_request,
    mojo::PendingRemote<network::mojom::URLLoaderClient> loader_client,
    const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  DCHECK(resource_request.url.SchemeIs(chrome::kIsolatedAppScheme));
  DCHECK(resource_request.url.IsStandard());

  base::expected<IsolatedWebAppUrlInfo, std::string> url_info =
      IsolatedWebAppUrlInfo::Create(resource_request.url);
  if (!url_info.has_value()) {
    LogErrorAndFail(url_info.error(), std::move(loader_client));
    return;
  }

  base::expected<std::reference_wrapper<const WebApp>, std::string> iwa =
      FindIsolatedWebApp(profile_, *url_info);
  if (!iwa.has_value()) {
    LogErrorAndFail(iwa.error(), std::move(loader_client));
    return;
  }

  IsolationData isolation_data = iwa->get().isolation_data().value();
  if (absl::holds_alternative<IsolationData::DevModeProxy>(
          isolation_data.content)) {
    CompleteWith404(mojo::Remote<network::mojom::URLLoaderClient>(
        std::move(loader_client)));
    return;
  }

  LogErrorAndFail("IsolatedWebAppURLLoaderFactory not implemented",
                  std::move(loader_client));
}

void IsolatedWebAppURLLoaderFactory::LogErrorAndFail(
    const std::string& error_message,
    mojo::PendingRemote<network::mojom::URLLoaderClient> client) {
  LogErrorMessageToConsole(frame_tree_node_id_, error_message);

  mojo::Remote<network::mojom::URLLoaderClient>(std::move(client))
      ->OnComplete(network::URLLoaderCompletionStatus(net::ERR_FAILED));
}

// static
mojo::PendingRemote<network::mojom::URLLoaderFactory>
IsolatedWebAppURLLoaderFactory::Create(
    int frame_tree_node_id,
    content::BrowserContext* browser_context) {
  DCHECK(browser_context);
  DCHECK(!browser_context->ShutdownStarted());

  mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote;

  // The IsolatedWebAppURLLoaderFactory will delete itself when there are no
  // more receivers - see the
  // network::SelfDeletingURLLoaderFactory::OnDisconnect method.
  new IsolatedWebAppURLLoaderFactory(
      frame_tree_node_id, Profile::FromBrowserContext(browser_context),
      pending_remote.InitWithNewPipeAndPassReceiver());

  return pending_remote;
}

}  // namespace web_app


text:
package org.xclcharts.common;

import java.util.Random;

import org.xclcharts.renderer.XEnum;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Paint.FontMetrics;
import android.graphics.Path;
import android.graphics.PathEffect;

/**
 * @ClassName DrawHelper
 * @Description  集中了绘制中,相关的一些小函数
 * @author XiongChuanLiang<br/>(xcl_168@aliyun.com)
 *
 */

public class DrawHelper {

	private static DrawHelper instance = null;

	public DrawHelper(){}

	public static synchronized DrawHelper getInstance()
	{
		if(instance == null){
			instance = new DrawHelper();
		}
		return instance;
	}

	/**
	 *  得到一个随机颜色
	 * @return 随机颜色
	 */
	public int randomColor() {
	    Random random = new Random();
        int red = random.nextInt(256) ;
        int green = random.nextInt(256) ;
        int blue = random.nextInt(256);
        return Color.rgb(red, green, blue);
    }

	/**
	 * 通过透明度,算出对应颜色的浅色应当是什么效果
	 * @param color 颜色
	 * @param alpha 透明度
	 * @return 浅色
	 */
	public int getLightColor(int color,int alpha)
	{
		Paint paint = new Paint();
		paint.setColor(color);
		paint.setAlpha(alpha);
		return paint.getColor();
	}

	/**
	 * 得到深色
	 * @param color 颜色
	 * @return 深色
	 */
	public int getDarkerColor(int color){
	    float[] hsv = new float[3];
	    Color.colorToHSV(color, hsv);
	    hsv[1] = hsv[1] + 0.1f;
	    hsv[2] = hsv[2] - 0.1f;
	    int darkerColor = Color.HSVToColor(hsv);
	    return  darkerColor ;
	}

	/**
	 * 得到单个字的高度
	 * @param paint 画笔
	 * @return 高度
	 */
	public int getPaintFontHeight(Paint paint)
	{
	     FontMetrics fm = paint.getFontMetrics();
		 int charHeight = (int) Math.ceil(fm.descent - fm.ascent);
		 return charHeight;
	}

	/**
	 * 得到字符串的宽度
	 * @param paint 画笔
	 * @param str 字符串
	 * @return 宽度
	 */
	public float getTextWidth(Paint paint,String str)
	{
		if(str.length() == 0) return 0.0f;
		//float width = Math.abs(paint.measureText(str, 0, str.length()));
		return paint.measureText(str, 0, str.length());
	}

	/**
	 *  用于计算文字的竖直累加高度
	 * @param paint 画笔
	 * @param str   字符串
	 * @return 高度
	 */
	public int calcTextHeight(Paint paint,String str)
	{
		if(str.length() == 0) return 0;
		return getPaintFontHeight(paint) * str.length();
	}

	/**
	 *  绘制旋转了指定角度的文字
	 * @param text	文字
	 * @param x		X坐标
	 * @param y		y坐标
	 * @param paint	画笔
	 * @param angle 角度
	 */
	public void drawRotateText(  String text ,
									float x ,float y,float angle,
									Canvas canvas,
									Paint paint
									){

		if(text.length() == 0 ) return;

		if(angle != 0){
			canvas.rotate(angle, x, y);
		}
		canvas.drawText(text, x, y, paint);
		if(angle != 0){
			canvas.rotate(-angle, x, y);
		}
	}

	/**
	 * 绘制等腰三角形
	 * @param baseLine		底线长度
	 * @param baseLnCentX	底线中心点X坐标
	 * @param baseLnCentY	底线中心点Y坐标
	 * @param direction		三角形方向
	 * @param style			填充风格
	 * @param canvas		画布
	 * @param paint			画笔
	 */
	public void drawTrigangle(	float baseLine,
								float baseLnCentX,
								float baseLnCentY,
								XEnum.TriangleDirection direction,
								XEnum.TriangleStyle style,
								Canvas canvas,
								Paint paint)
	{
		 // 计算偏移量
		   int offset = (int)(baseLine / 2 * Math.tan(60 * Math.PI / 180));

		   Path path = new Path();

		   // 计算三角形3个顶点的坐标
	        switch (direction)
	        {
	            case UP: //向上

	                path.moveTo(baseLnCentX- baseLine / 2 , baseLnCentY);
	                path.lineTo(baseLnCentX + baseLine / 2,baseLnCentY);
	                path.lineTo(baseLnCentX,baseLnCentY - offset);
	                path.close();
	                break;

	            case DOWN: //向下

	                path.moveTo( baseLnCentX - baseLine / 2 , baseLnCentY);
	                path.lineTo(baseLnCentX + baseLine / 2,baseLnCentY);
	                path.lineTo(baseLnCentX,baseLnCentY + offset);
	                path.close();

	                break;
	            case LEFT: //向左

	                path.moveTo(baseLnCentX , baseLnCentY - baseLine / 2);
	                path.lineTo(baseLnCentX , baseLnCentY + baseLine / 2);
	                path.lineTo(baseLnCentX - offset ,baseLnCentY);
	                path.close();

	                break;
	            case RIGHT: //向右

	                path.moveTo(baseLnCentX , baseLnCentY - baseLine / 2);
	                path.lineTo(baseLnCentX , baseLnCentY + baseLine / 2);
	                path.lineTo(baseLnCentX + offset ,baseLnCentY);
	                path.close();
	                break;
	        }

	        //三角形的填充风格
	        switch (style)
	        {
	            case OUTLINE : //空心
	                paint.setStyle(Paint.Style.STROKE);
	                break;
	            case FILL : //FILL
	               paint.setStyle(Paint.Style.FILL);
	               break;
	        }
	        canvas.drawPath(path,paint);
	}

	public PathEffect getDotLineStyle()
	{
		PathEffect effects = new DashPathEffect(new float[] { 2, 2, 2, 2}, 1);
		return effects;
	}

	public PathEffect getDashLineStyle()
	{
		//虚实线
		PathEffect effects = new DashPathEffect(new float[] { 4, 8, 5, 10}, 1);
		return effects;
	}

	/**
	 * 绘制点
	 * @param startX	起始点X坐标
	 * @param startY	起始点Y坐标
	 * @param stopX		终止点X坐标
	 * @param stopY		终止点Y坐标
	 * @param canvas	画布
	 * @param paint		画笔
	 */
	public void drawDotLine(float startX,float startY,
			 float stopX,float stopY,
			 Canvas canvas,
			 Paint paint)
	{
		//PathEffect effects = new DashPathEffect(new float[] { 2, 2, 2, 2}, 1);
		paint.setPathEffect(getDotLineStyle());
		canvas.drawLine(startX, startY, stopX, stopY, paint);
	}

	/**
	 * 绘制虚实线
	 * @param startX	起始点X坐标
	 * @param startY	起始点Y坐标
	 * @param stopX		终止点X坐标
	 * @param stopY		终止点Y坐标
	 * @param canvas	画布
	 * @param paint		画笔
	 */
	public void drawDashLine(float startX,float startY,
							 float stopX,float stopY,
							 Canvas canvas,
							 Paint paint)
	{
		//虚实线
		//PathEffect effects = new DashPathEffect(new float[] { 4, 8, 5, 10}, 1);
		paint.setPathEffect(getDashLineStyle());
		canvas.drawLine(startX, startY, stopX, stopY, paint);
	}

	//下次应当做的:虚实线 比例的灵活定制,线的阴影渲染
	public void drawLine(XEnum.LineStyle style,
				float startX,float startY,
				float stopX,float stopY,
				Canvas canvas,
				Paint paint
			 	)
	{

		switch(style)
		{
		case SOLID:
			canvas.drawLine(startX, startY, stopX, stopY, paint);
			break;
		case DOT:
			drawDotLine(startX, startY, stopX, stopY, canvas,paint);
			break;
		case DASH:
			//虚实线
			drawDashLine(startX, startY, stopX, stopY, canvas,paint);
			break;
		}
	}

	/**
	 * 绘制图中显示所占比例 的扇区
	 * @param paintArc	画笔
	 * @param cirX	x坐标
	 * @param cirY	y坐标
	 * @param radius	半径
	 * @param offsetAgent	偏移角度
	 * @param curretAgent	当前角度
	 * @throws Exception	例外
	 */
	public void drawPercent(Canvas canvas, Paint paintArc,
			final float cirX,
			final float cirY,
			final float radius,
			final float startAngle,
			final float sweepAngle,boolean useCenter) throws Exception
	{
		try{
			float arcLeft =  cirX - radius;
	        float arcTop  =  cirY - radius ;
	        float arcRight = cirX  +  radius ;
	        float arcBottom = cirY +  radius ;
	        RectF arcRF0 = new RectF(arcLeft ,arcTop,arcRight,arcBottom);

			//在饼图中显示所占比例
			canvas.drawArc(arcRF0, startAngle, sweepAngle, useCenter, paintArc);
		}catch( Exception e){
			throw e;
		}
	}

	public void drawPathArc(Canvas canvas, Paint paintArc,
			final float cirX,
			final float cirY,
			final float radius,
			final float startAngle,
			final float sweepAngle) throws Exception
	{
		try{
			float arcLeft =  cirX - radius;
	        float arcTop  =  cirY - radius ;
	        float arcRight = cirX  +  radius ;
	        float arcBottom = cirY +  radius ;
	        RectF arcRF0 = new RectF(arcLeft ,arcTop,arcRight,arcBottom);

			//弧形
			 Path path = new Path();
			 path.addArc(arcRF0,startAngle, sweepAngle);
			 canvas.drawPath(path, paintArc);

		}catch( Exception e){
			throw e;
		}
	}

}


text:
import multiprocessing

import requests
from aiohttp.web_response import json_response

from trellio import *
from trellio.registry import Repository, Registry

processes = []

class ServiceA(TCPService):
    def __init__(self):
        super().__init__("service_a", "1", host_port=8001, host_ip='0.0.0.0')

    @api
    async def echo(self, data):
        return data

class ServiceClientA(TCPServiceClient):
    def __init__(self):
        super(ServiceClientA, self).__init__("raven", "1")

    @request
    def echo(self, data, test=True):
        return locals()

class ServiceB(HTTPService):
    def __init__(self):
        super().__init__("service_b", "1", host_port=8000, host_ip='0.0.0.0')
        self._client_a = ServiceClientA()

    @get(path="/{data}/")
    async def get_echo(self, request):
        data = request.match_info.get('data')
        d = await self._client_a.echo(data)
        return json_response(text=d)

class ServiceBTCP(TCPService):
    def __init__(self):
        super().__init__("service_b", "1", host_port=8003, host_ip='0.0.0.0')
        self._client_a = ServiceClientA()

    @api
    async def get_echo(self, data):
        data = request.match_info.get('data')
        d = await self._client_a.echo(data)
        return d

def start_registry():
    repository = Repository()
    registry = Registry('0.0.0.0', 4500, repository)
    registry.start()

def start_service_a():
    Host.configure(http_port=8002, tcp_port=8001, tcp_host='0.0.0.0', service_name="service_a", service_version="1")
    Host.attach_tcp_service(ServiceA())
    Host.run()

def start_service_b():
    client_a = ServiceClientA()
    service_b = ServiceB()
    tcp_service = ServiceBTCP()

    Host.configure(http_port=8000, tcp_port=8003, http_host='0.0.0.0', service_name="service_b", service_version="1",
                   registry_host='0.0.0.0', registry_port=4500)

    service_b.clients = [client_a]
    tcp_service.clients = [client_a]
    Host.attach_http_service(service_b)
    Host.attach_tcp_service(tcp_service)
    Host.run()

def setup_module():
    global processes
    for target in [start_registry, start_service_a, start_service_b]:
        p = multiprocessing.Process(target=target)
        p.start()
        processes.append(p)

        # allow the subsystems to start up.
        # sleep for awhile
        import time
        time.sleep(1)

def restart_service_a():
    processes[1].terminate()
    p = multiprocessing.Process(target=start_service_a)
    p.start()
    processes[1] = p
    import time
    time.sleep(1)

def teardown_module():
    for p in processes:
        p.terminate()

def test_service_b():
    url = 'http://0.0.0.0:8000/blah/'
    r = requests.get(url)
    assert r.text == 'blah'
    assert r.status_code == 200

if __name__ == "__main__":
    setup_module()
    # restart_service_a()
    test_service_b()


text:
export interface User {
    username: string,
    password: string
}


text:
package eu.chargetime.ocpp.wss;

import java.util.List;
import javax.net.ssl.SSLContext;
import org.java_websocket.WebSocketServerFactory;
import org.java_websocket.server.DefaultSSLWebSocketServerFactory;

/** Base implementation of WssFactoryBuilder. */
public class BaseWssFactoryBuilder implements WssFactoryBuilder {

  private SSLContext sslContext;
  private List<String> ciphers;

  private BaseWssFactoryBuilder() {}

  public static BaseWssFactoryBuilder builder() {
    return new BaseWssFactoryBuilder();
  }

  public BaseWssFactoryBuilder ciphers(List<String> ciphers) {
    this.ciphers = ciphers;
    return this;
  }

  public BaseWssFactoryBuilder sslContext(SSLContext sslContext) {
    this.sslContext = sslContext;
    return this;
  }

  @Override
  public WebSocketServerFactory build() {
    verify();

    return ciphers == null
        ? new DefaultSSLWebSocketServerFactory(sslContext)
        : new CustomSSLWebSocketServerFactory(sslContext, ciphers);
  }

  @Override
  public void verify() {
    if (sslContext == null) {
      throw new IllegalStateException("sslContext must be set");
    }
  }
}


text:
package net.sf.katta.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * An unsynchronized map like structure which maintains for each key a
 * {@link List} of values.
 *
 *
 */
public class One2ManyListMap<K, V> implements Serializable {

  private static final long serialVersionUID = 1L;
  protected final Map<K, List<V>> _map;

  public One2ManyListMap() {
    this(new HashMap<K, List<V>>());
  }

  public One2ManyListMap(Map<K, List<V>> map) {
    _map = map;
  }

  public void add(K key) {
    List<V> values = _map.get(key);
    if (values == null) {
      values = new ArrayList<V>(3);
      _map.put(key, values);
    }
  }

  public void add(K key, V value) {
    List<V> values = _map.get(key);
    if (values == null) {
      values = new ArrayList<V>(3);
      _map.put(key, values);
    }
    values.add(value);
  }

  public void addAll(K key, Collection<V> newValues) {
    List<V> values = _map.get(key);
    if (values == null) {
      values = new ArrayList<V>(newValues.size());
      _map.put(key, values);
    }
    values.addAll(newValues);
  }

  /**
   * @param key
   * @return the list to the given key or an empty list
   */
  public List<V> getValues(K key) {
    List<V> values = _map.get(key);
    if (values == null) {
      values = Collections.emptyList();
    }
    return values;
  }

  /**
   * Removes the value from the given key list.
   *
   * @param key
   * @param value
   * @return if value has exists or not
   */
  public boolean removeValue(K key, V value) {
    List<V> values = _map.get(key);
    if (values == null) {
      return false;
    }

    boolean success = values.remove(value);
    if (values.size() == 0) {
      _map.remove(key);
    }

    return success;
  }

  /**
   * @param key
   * @return a list with all values belonging to the given key
   */
  public List<V> removeKey(K key) {
    List<V> list = getValues(key);
    _map.remove(key);
    return list;
  }

  /**
   * @param key
   * @return true if map contains the key
   */
  public boolean containsKey(K key) {
    return _map.containsKey(key);
  }

  /**
   *
   * @param value
   * @return true if map contains the value
   */
  public boolean containsValue(V value) {
    Collection<List<V>> values = _map.values();
    for (List<V> list : values) {
      if (list.contains(value)) {
        return true;
      }
    }
    return false;
  }

  /**
   * @see HashMap#keySet()
   * @return a set view of the keys contained in this map.
   */
  public Set<K> keySet() {
    return _map.keySet();
  }

  /**
   * @see HashMap#size()
   * @return the size of the map
   */
  public int size() {
    return _map.size();
  }

  public Map<K, List<V>> asMap() {
    return _map;
  }

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

}


text:
#pragma once

#include <unistd.h>
#include <cstdio>

#include "modules/drivers/lidar/velodyne/driver/input.h"

namespace apollo {
namespace drivers {
namespace velodyne {

using apollo::drivers::velodyne::VelodynePacket;

// static int FIRING_DATA_PORT = 2368;
// static int POSITIONING_DATA_PORT = 8308;
static const int POLL_TIMEOUT = 1000;  // one second (in msec)

/** @brief Live Velodyne input from socket. */
class SocketInput : public Input {
 public:
  SocketInput();
  virtual ~SocketInput();
  void init(const int& port) override;
  int get_firing_data_packet(VelodynePacket* pkt);
  int get_positioning_data_packet(NMEATimePtr nmea_time);

 private:
  int sockfd_;
  int port_;
  bool input_available(int timeout);
};

}  // namespace velodyne
}  // namespace drivers
}  // namespace apollo


text:
START_ATF_NAMESPACE
    namespace std
    {
        namespace Detail
        {

            Info::std__out_of_rangector_out_of_range5_ptr std__out_of_rangector_out_of_range5_next(nullptr);
            Info::std__out_of_rangector_out_of_range5_clbk std__out_of_rangector_out_of_range5_user(nullptr);

            Info::std__out_of_rangector_out_of_range7_ptr std__out_of_rangector_out_of_range7_next(nullptr);
            Info::std__out_of_rangector_out_of_range7_clbk std__out_of_rangector_out_of_range7_user(nullptr);

            Info::std__out_of_rangedtor_out_of_range9_ptr std__out_of_rangedtor_out_of_range9_next(nullptr);
            Info::std__out_of_rangedtor_out_of_range9_clbk std__out_of_rangedtor_out_of_range9_user(nullptr);

            void std__out_of_rangector_out_of_range5_wrapper(struct std::out_of_range* _this, std::basic_string<char>* _Message)
            {
               std__out_of_rangector_out_of_range5_user(_this, _Message, std__out_of_rangector_out_of_range5_next);
            };

            void std__out_of_rangector_out_of_range7_wrapper(struct std::out_of_range* _this, struct std::out_of_range* __that)
            {
               std__out_of_rangector_out_of_range7_user(_this, __that, std__out_of_rangector_out_of_range7_next);
            };

            void std__out_of_rangedtor_out_of_range9_wrapper(struct std::out_of_range* _this)
            {
               std__out_of_rangedtor_out_of_range9_user(_this, std__out_of_rangedtor_out_of_range9_next);
            };

            ::std::array<hook_record, 3> out_of_range_functions =
            {
                _hook_record {
                    (LPVOID)0x140195740L,
                    (LPVOID *)&std__out_of_rangector_out_of_range5_user,
                    (LPVOID *)&std__out_of_rangector_out_of_range5_next,
                    (LPVOID)cast_pointer_function(std__out_of_rangector_out_of_range5_wrapper),
                    (LPVOID)cast_pointer_function((void(std::out_of_range::*)(std::basic_string<char>*))&std::out_of_range::ctor_out_of_range)
                },
                _hook_record {
                    (LPVOID)0x140195880L,
                    (LPVOID *)&std__out_of_rangector_out_of_range7_user,
                    (LPVOID *)&std__out_of_rangector_out_of_range7_next,
                    (LPVOID)cast_pointer_function(std__out_of_rangector_out_of_range7_wrapper),
                    (LPVOID)cast_pointer_function((void(std::out_of_range::*)(struct std::out_of_range*))&std::out_of_range::ctor_out_of_range)
                },
                _hook_record {
                    (LPVOID)0x1401957b0L,
                    (LPVOID *)&std__out_of_rangedtor_out_of_range9_user,
                    (LPVOID *)&std__out_of_rangedtor_out_of_range9_next,
                    (LPVOID)cast_pointer_function(std__out_of_rangedtor_out_of_range9_wrapper),
                    (LPVOID)cast_pointer_function((void(std::out_of_range::*)())&std::out_of_range::dtor_out_of_range)
                },
            };
        }; // end namespace Detail
    }; // end namespace std
END_ATF_NAMESPACE


text:
package com.karasiq.shadowcloud.config

import com.typesafe.config.Config

case class BuffersConfig(rootConfig: Config, readChunks: Long, repair: Long) extends WrappedConfig

object BuffersConfig extends WrappedConfigFactory[BuffersConfig] {
  override def apply(config: Config): BuffersConfig = {
    BuffersConfig(
      config,
      config.getMemorySize("read-chunks").toBytes,
      config.getMemorySize("repair").toBytes
    )
  }
}


text:
/*
 * Created by SharpDevelop.
 * User: lextm
 * Date: 3/14/2010
 * Time: 1:18 PM
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Lextm.SharpSnmpLib.Messaging;
using Lextm.SharpSnmpLib.Pipeline;

namespace Lextm.SharpSnmpLib.Agent
{
    /// <summary>
    /// Logger class, who logs message processed to the rolling log file.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
    internal class RollingLogger : ILogger
    {
        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private const string Empty = "-";

        public RollingLogger()
        {
            if (!Logger.IsInfoEnabled)
            {
                return;
            }

            Logger.Info(string.Format(CultureInfo.InvariantCulture, "#Software: #SNMP Agent {0}", System.Reflection.Assembly.GetEntryAssembly().GetName().Version));
            Logger.Info("#Version: 1.0");
            Logger.Info(string.Format(CultureInfo.InvariantCulture, "#Date: {0}", DateTime.UtcNow));
            Logger.Info("#Fields: date time s-ip cs-method cs-uri-stem s-port cs-username c-ip sc-status cs-version time-taken");
        }

        public void Log(ISnmpContext context)
        {
            if (Logger.IsInfoEnabled)
            {
                Logger.Info(GetLogEntry(context));
            }
        }

        private static string GetLogEntry(ISnmpContext context)
        {
            return string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}",
                DateTime.UtcNow,
                context.Binding.Endpoint.Address,
                context.Request.TypeCode() == SnmpType.Unknown ? Empty : context.Request.TypeCode().ToString(),
                GetStem(context.Request.Pdu().Variables),
                context.Binding.Endpoint.Port,
                context.Request.Parameters.UserName,
                context.Sender.Address,
                (context.Response == null) ? Empty : context.Response.Pdu().ErrorStatus.ToErrorCode().ToString(),
                context.Request.Version,
                DateTime.Now.Subtract(context.CreatedTime).TotalMilliseconds);
        }

        private static string GetStem(ICollection<Variable> variables)
        {
            if (variables.Count == 0)
            {
                return Empty;
            }

            StringBuilder result = new StringBuilder();
            foreach (Variable v in variables)
            {
                result.AppendFormat("{0};", v.Id);
            }

            if (result.Length > 0)
            {
                result.Length--;
            }

            return result.ToString();
        }
    }
}


text:
from nova.tests.integrated.v3 import api_sample_base

class FlavorRxtxJsonTest(api_sample_base.ApiSampleTestBaseV3):
    extension_name = 'os-flavor-rxtx'

    def test_flavor_rxtx_get(self):
        flavor_id = 1
        response = self._do_get('flavors/%s' % flavor_id)
        subs = {
            'flavor_id': flavor_id,
            'flavor_name': 'm1.tiny'
        }
        subs.update(self._get_regexes())
        self._verify_response('flavor-rxtx-get-resp', subs, response, 200)

    def test_flavors_rxtx_detail(self):
        response = self._do_get('flavors/detail')
        subs = self._get_regexes()
        self._verify_response('flavor-rxtx-list-resp', subs, response, 200)

    def test_flavors_rxtx_create(self):
        subs = {
            'flavor_id': 100,
            'flavor_name': 'flavortest'
        }
        response = self._do_post('flavors',
                                 'flavor-rxtx-post-req',
                                 subs)
        subs.update(self._get_regexes())
        self._verify_response('flavor-rxtx-post-resp', subs, response, 201)


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

<TITLE>
IFlowReconcileService
</TITLE>

<META NAME="date" CONTENT="2013-07-13">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      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

net.floodlightcontroller.flowcache

Interface IFlowReconcileService

All Superinterfaces:
IFloodlightService, java.io.Serializable

All Known Implementing Classes:
FlowReconcileManager

public interface IFlowReconcileService
extends IFloodlightService

Method Summary

 void
addFlowReconcileListener(IFlowReconcileListener listener)

          Add a flow reconcile listener

 void
clearFlowReconcileListeners()

          Remove all flow reconcile listeners

 void
flowQueryGenericHandler(FlowCacheQueryResp flowResp)

          Generic flow query handler to insert FlowMods into the reconcile pipeline.

 void
reconcileFlow(OFMatchReconcile ofmRcIn)

          Reconcile flow.

 void
removeFlowReconcileListener(IFlowReconcileListener listener)

          Remove a flow reconcile listener

 void
updateFlowForDestinationDevice(IDevice device,
                               IFlowQueryHandler handler,
                               IFlowCacheService.FCQueryEvType fcEvType)

          Updates the flows to a device after the device moved to a new location

 void
updateFlowForSourceDevice(IDevice device,
                          IFlowQueryHandler handler,
                          IFlowCacheService.FCQueryEvType fcEvType)

          Updates the flows from a device

Method Detail

addFlowReconcileListener

void addFlowReconcileListener(IFlowReconcileListener listener)

Add a flow reconcile listener

Parameters:
listener - The module that can reconcile flows

removeFlowReconcileListener

void removeFlowReconcileListener(IFlowReconcileListener listener)

Remove a flow reconcile listener

Parameters:
listener - The module that no longer reconcile flows

clearFlowReconcileListeners

void clearFlowReconcileListeners()

Remove all flow reconcile listeners

reconcileFlow

void reconcileFlow(OFMatchReconcile ofmRcIn)

Reconcile flow. Returns false if no modified flow-mod need to be
 programmed if cluster ID is providced then pnly flows in the given
 cluster are reprogrammed

Parameters:
ofmRcIn - the ofm rc in

updateFlowForDestinationDevice

void updateFlowForDestinationDevice(IDevice device,
                                    IFlowQueryHandler handler,
                                    IFlowCacheService.FCQueryEvType fcEvType)

Updates the flows to a device after the device moved to a new location

 Queries the flow-cache to get all the flows destined to the given device.
 Reconciles each of these flows by potentially reprogramming them to its
 new attachment point

Parameters:
device - device that has moved
handler - handler to process the flows
fcEvType - Event type that triggered the update

updateFlowForSourceDevice

void updateFlowForSourceDevice(IDevice device,
                               IFlowQueryHandler handler,
                               IFlowCacheService.FCQueryEvType fcEvType)

Updates the flows from a device

 Queries the flow-cache to get all the flows source from the given device.
 Reconciles each of these flows by potentially reprogramming them to its
 new attachment point

Parameters:
device - device where the flow originates
handler - handler to process the flows
fcEvType - Event type that triggered the update

flowQueryGenericHandler

void flowQueryGenericHandler(FlowCacheQueryResp flowResp)

Generic flow query handler to insert FlowMods into the reconcile pipeline.

Parameters:
flowResp -

      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:
<link rel="import" href="components/context-free-parser/context-free-parser.html">
<link rel="import" href="components/core-ajax/core-ajax.html">

<polymer-element name="catalog-item-view" extends="object-view" block>
<template>

  <core-ajax id="scraper" handleAs="json" url="{{scraperUrl}}?{{value.org}}/{{value.repo}}/{{value.repo}}.html" on-core-response="{{scrapeDataReady}}"></core-ajax>
  <context-free-parser id="parser" on-data-ready="{{parserDataReady}}"></context-free-parser>

  <shadow></shadow>

</template>
<script>

  Polymer({
    scraperUrl: 'http://compound.selfip.net/bowertopia/php/git-scrape.php',

    valueChanged: function() {
      //this.$.scraper.abort();
      this.scrapedData = null;
      if (this.value && this.value.org && this.value.repo && !this.value.info) {
        this.value.info = { 'status': 'loading...' };
        this.$.scraper.go();
      }
    },

    scrapeDataReady: function(event) {
      var data = event.detail.response;
      this.$.parser.text = data.html;
      delete data.html;
      this.scrapedData = data;
    },

    parserDataReady: function() {
      //console.log('parserDataReady', this.value.info, this.scrapedData);
      this.value.info = this.scrapedData;
      this.value.info.docs = this.$.parser.data;
      //this.$.view.refresh();
    }
  });

</script>
</polymer-element>


text:
> You can use the same mount point and dynamically switch between multiple components using the reserved `<component>` element and dynamically bind to its `is` attribute:
>
> https://vuejs.org/v2/guide/components.html#Dynamic-Components

## 📖 Rule Details

This rule reports the `<component>` elements which do not have `v-bind:is` attributes.

👎 Examples of **incorrect** code for this rule:

```html
<template>
    <component></component>
</template>
```

👍 Examples of **correct** code for this rule:

```html
<template>
    <component :is="type"></component>
</template>
```

## 🔧 Options

Nothing.


text:
<!DOCTYPE html>
<html lang="en">
<head>

  <!-- Basic Page Needs
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta charset="utf-8">
  <title>groupBy</title>
  <meta name="description" content="">
  <meta name="author" content="">

  <!-- Mobile Specific Metas
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- FONT
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link href='//fonts.googleapis.com/css?family=Raleway:400,300,600' rel='stylesheet' type='text/css'>

  <!-- CSS
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="stylesheet" href="/static/css/normalize.min.css">
  <link rel="stylesheet" href="/static/css/skeleton.min.css">
  <link rel="stylesheet" href="/static/css/switch.css">

  <!-- Scripts
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <!--<script src="/static/js/handlebars-v3.0.3.js"></script>-->
  <script src="/static/js/app.js"></script>

  <link rel="icon" type="image/png" href="/static/favicon.ico">

</head>
<body>

  {{{content}}}

</body>
</html>


text:
require "io/console"
require "unix_crypt"

module Itamae
  module Centos7Base
    SALT_CHARSET =
      "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    SALT_LENGTH = 8

    def self.salt
      SALT_LENGTH.times.inject("") do |s, _|
        s << SALT_CHARSET[rand(SALT_CHARSET.size)]
      end
    end
  end
end

namespace :itamae do
  desc "Make password hash (SHA-512)"
  task :mkpasswd do
    print "Enter your password: "
    password = STDIN.noecho(&:gets).chomp
    puts

    print "Confirm your password: "
    confirmation = STDIN.noecho(&:gets).chomp
    puts

    if password != confirmation
      puts "Error! Not match"
      abort
    end

    puts UnixCrypt::SHA512.build(password, Itamae::Centos7Base.salt)
  end
end


text:
namespace Microsoft.Azure.Management.WebSites.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Container App container resource requirements.
    /// </summary>
    public partial class ContainerResources
    {
        /// <summary>
        /// Initializes a new instance of the ContainerResources class.
        /// </summary>
        public ContainerResources()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ContainerResources class.
        /// </summary>
        /// <param name="cpu">Required CPU in cores, e.g. 0.5</param>
        /// <param name="memory">Required memory, e.g. "250Mb"</param>
        public ContainerResources(double? cpu = default(double?), string memory = default(string))
        {
            Cpu = cpu;
            Memory = memory;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets required CPU in cores, e.g. 0.5
        /// </summary>
        [JsonProperty(PropertyName = "cpu")]
        public double? Cpu { get; set; }

        /// <summary>
        /// Gets or sets required memory, e.g. "250Mb"
        /// </summary>
        [JsonProperty(PropertyName = "memory")]
        public string Memory { get; set; }

    }
}


text:
"""BIG-IP® utility module

REST URI
    ``http://localhost/mgmt/tm/util/dig``

GUI Path
    N/A

REST Kind
    ``tm:util:dig:*``
"""

from f5.bigip.mixins import CommandExecutionMixin
from f5.bigip.resource import UnnamedResource

class Dig(UnnamedResource, CommandExecutionMixin):
    """BIG-IP® utility command

    .. note::

        This is an unnamed resource so it has no ~Partition~Name pattern
        at the end of its URI.
    """

    def __init__(self, util):
        super(Dig, self).__init__(util)
        self._meta_data['required_command_parameters'].update(('utilCmdArgs',))
        self._meta_data['required_json_kind'] = 'tm:util:dig:runstate'
        self._meta_data['allowed_commands'].append('run')


text:
	// 'Safe' default settings.  This allows new build modes to be added to the
	// project without requiring the manual updating of all 'local build control'
	// sections in every module and header file.

#endif

//*****************************************************************************
//
// Include files required by this header.
//
// Note: Do NOT place any 'using' directives or declarations in header files -
// put them at the top of the source files that require them.
// Use fully-qualified names in header files.
//
//*****************************************************************************

//*****************************************************************************
//
// Exported constants and macros.
// - Wrap these definitions in a namespace whenever possible
//
//*****************************************************************************

namespace
{
	// constant definitions here
}

#define szSteamBootStrapperIconIdEnvVar  "__STEAM_BOOTSTRAPPER_ICON_ID__"

//*****************************************************************************
//
// Exported scalar type and enumerated type definitions.
// - Wrap these definitions in a namespace whenever possible
//
//*****************************************************************************

namespace
{
// scalar and enumerated type definitions here
}

//*****************************************************************************
//
// Exported class, structure, and complex type definitions.
// - Wrap these definitions in a namespace whenever possible
//
//*****************************************************************************

namespace
{
	// class, structure, and complex type definitions here
}

//*****************************************************************************
//
// Exported function prototypes
// - Wrap these definitions in a namespace whenever possible
// - declared extern here, and defined without storage class in the source file.
//
//*****************************************************************************

namespace
{
	// function prototypes here
}

//*****************************************************************************
//
// Exported variable and data declarations
// - Wrap these definitions in a namespace whenever possible
// - declared extern here, and defined without storage class in the source file.
//
//*****************************************************************************

namespace
{
	// variable and data declarations here
}

//*****************************************************************************
//
// Inline function definitions.
//
//*****************************************************************************

#endif


text:
<?php

declare(strict_types=1);

namespace UthandoSessionManager\Form;

use TwbBundle\Form\View\Helper\TwbBundleForm;
use UthandoSessionManager\Options\SessionConfigOptions;
use Zend\Filter\StringTrim;
use Zend\Filter\StripTags;
use Zend\Filter\ToInt;
use Zend\Form\Element\Number;
use Zend\Form\Element\Text;
use Zend\Form\Fieldset;
use Zend\Hydrator\ClassMethods;
use Zend\I18n\Validator\IsInt;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\Validator\StringLength;

class SessionConfigOptionsFieldSet extends Fieldset implements InputFilterProviderInterface
{
    public function __construct($name = null, array $options = [])
    {
        parent::__construct($name, $options);

        $this->setHydrator(new ClassMethods())
            ->setObject(new SessionConfigOptions());
    }

    public function init()
    {
        $this->add([
            'name' => 'name',
            'type' => Text::class,
            'options' => [
                'label' => 'Name',
                'column-size' => 'md-8',
                'twb-layout' => TwbBundleForm::LAYOUT_HORIZONTAL,
                'label_attributes' => [
                    'class' => 'col-md-4',
                ],
            ],
        ]);

        $this->add([
            'name' => 'save_path',
            'type' => Text::class,
            'options' => [
                'label' => 'Save Path',
                'column-size' => 'md-8',
                'twb-layout' => TwbBundleForm::LAYOUT_HORIZONTAL,
                'label_attributes' => [
                    'class' => 'col-md-4',
                ],
            ],
        ]);

        $this->add([
            'name' => 'remember_me_seconds',
            'type' => Number::class,
            'options' => [
                'label' => 'Remember Me Seconds',
                'column-size' => 'md-8',
                'twb-layout' => TwbBundleForm::LAYOUT_HORIZONTAL,
                'label_attributes' => [
                    'class' => 'col-md-4',
                ],
            ],
        ]);

        $this->add([
            'name' => 'cookie_lifetime',
            'type' => Number::class,
            'options' => [
                'label' => 'Cookie Lifetime',
                'column-size' => 'md-8',
                'twb-layout' => TwbBundleForm::LAYOUT_HORIZONTAL,
                'label_attributes' => [
                    'class' => 'col-md-4',
                ],
            ],
        ]);
    }

    /**
     * @return array
     */
    public function getInputFilterSpecification()
    {
        return [
            'name' => [
                'required' => false,
                'filters' => [
                    ['name' => StripTags::class],
                    ['name' => StringTrim::class],
                ],
                'validators' => [
                    ['name' => StringLength::class, 'options' => [
                        'encoding' => 'UTF-8',
                    ]],
                ],
            ],
            'save_path' => [
                'required' => false,
                'filters' => [
                    ['name' => StripTags::class],
                    ['name' => StringTrim::class],
                ],
                'validators' => [
                    ['name' => StringLength::class, 'options' => [
                        'encoding' => 'UTF-8',
                    ]],
                ],
            ],
            'remember_me_seconds' => [
                'required' => false,
                'filters' => [
                    ['name' => StripTags::class],
                    ['name' => StringTrim::class],
                    ['name' => ToInt::class],
                ],
                'validators' => [
                    ['name' => IsInt::class],
                ],
            ],
            'cookie_lifetime' => [
                'required' => false,
                'filters' => [
                    ['name' => StripTags::class],
                    ['name' => StringTrim::class],
                    ['name' => ToInt::class],
                ],
                'validators' => [
                    ['name' => IsInt::class],
                ],
            ],
        ];
    }
}


text:
@implementation NSString (NSStringAdditions)

+ (NSString *)addressFromData:(NSData *)data
{
    return [self addressFromSockaddr:(struct sockaddr *)[data bytes]];
}

+ (NSString *)addressFromSockaddr:(struct sockaddr *)genericIP
{
    struct sockaddr_in *ipv4;
    struct sockaddr_in6 *ipv6;
    NSString *result = nil;
    char buffer[255];

    memset(buffer, 0, sizeof(buffer));
    switch (genericIP->sa_family) {
        case AF_INET:
            ipv4 = (struct sockaddr_in *)genericIP;
            inet_ntop(genericIP->sa_family, (void *)&(ipv4->sin_addr), buffer, sizeof(buffer) - 1);
            break;
        case AF_INET6:
            ipv6 = (struct sockaddr_in6 *)genericIP;
            inet_ntop(genericIP->sa_family, (void *)&(ipv6->sin6_addr), buffer, sizeof(buffer) - 1);
            break;
        case AF_UNSPEC:
            break;
        default:
            NSAssert(NO, @"unknown %d", genericIP->sa_family);
            break;
    }
    if (buffer[0]) {
        result = [NSString stringWithFormat:@"%s", buffer];
    }
    return result;
}

- (NSString*) URLEncodedString
{
    NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(
        kCFAllocatorDefault,
        (CFStringRef)self,
        NULL,
        CFSTR("!*'();:@&=+$,/?%#[]"),
        kCFStringEncodingUTF8);

	return [result autorelease];
}

- (NSString*) URLDecodedString
{
	NSString *result = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
        kCFAllocatorDefault,
        (CFStringRef)self,
        CFSTR(""),
        kCFStringEncodingUTF8);

	return [result autorelease];
}

- (NSString *) md5
{
	const char *cStr = [self UTF8String];
	unsigned char result[16];
	CC_MD5( cStr, strlen(cStr), result );
	return [NSString stringWithFormat:
		@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
		result[0], result[1], result[2], result[3],
		result[4], result[5], result[6], result[7],
		result[8], result[9], result[10], result[11],
		result[12], result[13], result[14], result[15]
		];
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
     <item android:drawable="@drawable/ic_btn_red_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/ic_btn_red_normal" android:state_pressed="false"/>
</selector>


text:
package com.rashwan.reactive_popular_movies.feature.discoverMovies.nearbyMovies.di;

import com.rashwan.reactive_popular_movies.dI.PerFragment;
import com.rashwan.reactive_popular_movies.feature.discoverMovies.nearbyMovies.NearbyMoviesFragment;

import dagger.Subcomponent;

/**
 * Created by rashwan on 3/15/17.
 */

@PerFragment
@Subcomponent(modules = NearbyMoviesModule.class)
public interface NearbyMoviesComponent {
    void inject(NearbyMoviesFragment target);
}


text:
extern crate proc_macro;

use std::convert::From;
use std::iter::Extend;

use proc_macro2::{TokenTree, TokenStream, Delimiter};
use quote::quote;
use syn::{
    Data,
    Fields,
    DeriveInput,
    FieldsNamed,
    Type,
    AttrStyle,
    Ident,
    Lit,
    parse_macro_input,
    parse_str,
};

static INVALID_STRUCT: &str = "Struct must be a named struct. Not unnamed or unit.";
static INVALID_VARIANT: &str = "Variant must be a struct. Not an enum or union.";
static VALID_ATTR: &str = "Either #[getter(skip)] or #[getter(rename=\"name\")].";

enum FieldAttribute {
    Skip,
    Rename(Ident),
}

fn parse_attribute_tokens(token_stream: TokenStream) -> FieldAttribute {
    // There must be tokens
    let first_token_tree = token_stream
        .into_iter()
        .next()
        .unwrap_or_else(|| panic!("The getter attribute has no tokens. {}", VALID_ATTR));

    // First token tree needs to be a parentheses grouping
    let mut inner_token_iter = match first_token_tree {
        TokenTree::Group(group) => match group.delimiter() {
            Delimiter::Parenthesis => group
                .stream()
                .into_iter(),
            _ => panic!("The getter attribute grouping must be parentheses. {}",
                        VALID_ATTR),
        },
        _ => panic!("The getter attribute must have a grouping. {}", VALID_ATTR),
    };

    let second_token_tree = inner_token_iter
        .next()
        .unwrap_or_else(|| panic!("No getter option has been specified. {}", VALID_ATTR));

    let third_token_tree = inner_token_iter.next();
    let fourth_token_tree = inner_token_iter.next();
    let fifth_token_tree = inner_token_iter.next();

    // Second token needs to be either skip or rename
    match second_token_tree {
        TokenTree::Ident(ident) => if ident == "skip" {
            // Check if more tokens follow.
            if third_token_tree.is_some() {
                panic!("No further tokens must follow skip. {}", VALID_ATTR);
            }
            return FieldAttribute::Skip;
        } else if ident != "rename" {
            panic!("Invalid attribute {}. {}", &ident, VALID_ATTR);
        },
        _ => panic!("No identifier found. {}", VALID_ATTR),
    }

    match third_token_tree {
        Some(TokenTree::Punct(p)) => if p.as_char() != '=' {
            panic!("Punctuation must be '='. {}", VALID_ATTR);
        },
        _ => panic!("rename must be followed by '=' punctuation. {}", VALID_ATTR),
    }

    let name = match fourth_token_tree {
        Some(TokenTree::Literal(l)) => match Lit::new(l) {
            Lit::Str(lstr) => lstr.value(),
            _ => panic!("Name litera must be a string. {}", VALID_ATTR),
        },
        _ => panic!("Name must be a literal. {}", VALID_ATTR),
    };

    if fifth_token_tree.is_some() {
        panic!("No futher tokens must follow the literal in rename. {}", VALID_ATTR);
    }

    let new_name = match parse_str::<Ident>(&name) {
        Ok(nn) => nn,
        Err(e) => panic!("{}", e),
    };

    FieldAttribute::Rename(new_name)
}

fn isolate_named_fields<'a>(ast: &'a DeriveInput) -> Result<&'a FieldsNamed, &'static str> {
    match ast.data {
        Data::Struct(ref structure) => {
            match structure.fields {
                Fields::Named(ref fields) => Ok(fields),
                Fields::Unnamed(_) | Fields::Unit => Err(INVALID_STRUCT),
            }
        },
        Data::Enum(_) | Data::Union(_) => Err(INVALID_VARIANT),
    }
}

fn getters_from_fields(fields: &FieldsNamed) -> Vec<proc_macro2::TokenStream> {
    fields.named
        .iter()
        .map(|field| {
            let field_name = field.ident.as_ref().unwrap(); // Must never fail.
            let returns = &field.ty;
            let maybie_lifetime = match &field.ty {
                Type::Reference(type_reference) => type_reference.lifetime.as_ref(),
                _ => None,
            };

            // Check for skip or rename field attributes. We deal with the last attribute.
            let mf_attribute: Option<FieldAttribute> = field.attrs
                .iter()
                .fold(None, |m_last, attr| match (attr.path.is_ident("getter"), m_last) {
                    (true, _) => {
                        match attr.style {
                            AttrStyle::Outer => (),
                            AttrStyle::Inner(_) => panic!(
                                "The getter attribute is an outer not inner attribute."
                            ),
                        }

                        Some(parse_attribute_tokens(attr.tokens.to_owned()))
                    },
                    (false, Some(last)) => Some(last),
                    (false, None) => None,
                });

            let maybie_getter_name: Option<&Ident> = match mf_attribute {
                Some(FieldAttribute::Rename(ref name)) => Some(name),
                Some(FieldAttribute::Skip) => None,
                None => Some(field_name)
            };

            match (maybie_lifetime, maybie_getter_name) {
                (Some(lifetime), Some(getter_name)) => quote!(
                    pub fn #getter_name(&#lifetime self) -> #returns {
                        self.#field_name
                    }
                ),
                (None, Some(getter_name)) => quote!(
                    pub fn #getter_name(&self) -> &#returns {
                        &self.#field_name
                    }
                ),
                (_, None) => quote!(),
            }
        })
        .collect()
}

/// # Derive getters
/// Generate getter methods for all named struct fields in a seperate struct `impl` block.
/// Getter methods share the name of the field they're 'getting'. Methods return an
/// immutable reference to the field.
#[proc_macro_derive(Getters, attributes(getter))]
pub fn getters(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);

    let struct_name = &ast.ident;
    let (impl_generics, struct_generics, where_clause) = ast.generics.split_for_impl();

    let fields = isolate_named_fields(&ast).unwrap();
    let methods = getters_from_fields(fields);

    quote!(
        impl #impl_generics #struct_name #struct_generics
            #where_clause
        {
            #(#methods)*
        }
    ).into()
}


text:
<resources>
  <string name="app_name">HomePageDemo</string>
  <string name="tab_android">Android</string>
  <string name="tab_favorite">Favorite</string>
  <string name="tab_alarm">Alarm</string>
  <string name="tab_emotion">Emotion</string>
  <string name="title_home">Home</string>
  <string name="title_dashboard">Dashboard</string>
  <string name="title_notifications">Notifications</string>
</resources>


text:
'use strict'

var debug = require('debug')('imock:server:routes:responses')
var express = require('express')
var responses = require('../models/responses')
var util = require('../models/util')
var router = express.Router()

// Create response
router.post('/', function (req, res, next) {
    var data = req.body
    var campaign = req.baseUrl.match(/\/api\/response\/(.*)/)[1]

    // {path} must be not empty
    if (data.path != null && data.path != undefined) {
        // Create response object and store to redis database
        responses.create(req, campaign, data, function (reply) {
            return next(reply)
        })

    } else {
        return next(util.getMessage(500, 'Empty response name'))
    }
})

// Modify response
router.put('/', function (req, res, next) {
    var data = req.body
    var campaign = req.baseUrl.match(/\/api\/response\/(.*)/)[1]

    // {path} must be not empty
    if (data.path != null && data.path != undefined) {
        // Modify service object
        responses.modify(req, campaign, data, function (reply) {
            return next(reply)
        })

    } else {
        return next(util.getMessage(500, 'Empty service name'))
    }
})

// Delete response
router.delete('/', function (req, res, next) {
    var data = req.body
    var campaign = req.baseUrl.match(/\/api\/response\/(.*)/)[1]

    // {path} must be not empty
    if (data.path != null && data.path != undefined) {
        // Delete service and responses
        responses.delete(req, campaign, data, function (reply) {
            return next(reply)
        })

    } else {
        return next(util.getMessage(500, 'Empty service name'))
    }
})

// Display response details or list of responses
router.get('/', function (req, res, next) {
    var locals = res.locals
    var campaign = req.baseUrl.match(/\/api\/responses?\/(.*)/)[1]

    // Response details or list of response
    if (req.query.search != null && req.query.search != undefined) {
        // Get detail response
        responses.detail(req, campaign, function (reply) {
            if (reply.status == 200) {
                locals.status = 200
                locals.payload = reply.message
                next()
            } else {
                return next(reply)
            }
        })

    } else {
        // Get list of response
        responses.list(req, campaign, function (reply) {
            if (reply.status == 200) {
                locals.status = 200
                locals.payload = reply.message
                next()
            } else {
                return next(reply)
            }
        })
    }
})

module.exports = router


text:
'use strict';

// signup controller
app.controller('SignupFormController', ['$scope', '$http', '$state', function($scope, $http, $state) {

    $scope.user = {};
    $scope.authError = null;
    $scope.signup = function() {

        $scope.authError = null;
        // Try to create
        $http.post(
            '/api/users/signup', $scope.user )
        .then(
            function(response) {
                //Success Callback
                if ( !response.data.user ) {
                  $scope.authError = response;
                }else{
                    console.log("Signup with success : go app.home")
                  $state.go('access.signin');
                }
            }, function(x) {
                //Failure Callback
                $scope.authError = 'Server Error';
            });
    };
  }])
 ;


text:
#include <gst/gst.h>
#include "BaseRtpEndpointImpl.hpp"
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <MediaState.hpp>
#include <ConnectionState.hpp>
#include <ctime>
#include <SignalHandler.hpp>
#include <MediaType.hpp>

#include "RembParams.hpp"

#include "StatsType.hpp"
#include "RTCInboundRTPStreamStats.hpp"
#include "RTCOutboundRTPStreamStats.hpp"
#include "EndpointStats.hpp"
#include "kmsstats.h"
#include "kmsutils.h"

#define GST_CAT_DEFAULT kurento_base_rtp_endpoint_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoBaseRtpEndpointImpl"

#define KMS_MEDIA_DISCONNECTED 0
#define KMS_MEDIA_CONNECTED 1
#define KMS_CONNECTION_DISCONNECTED 0
#define KMS_CONNECTION_CONNECTED 1
#define REMB_PARAMS "remb-params"

#define KMS_STATISTIC_FIELD_PREFIX_SESSION "session-"
#define KMS_STATISTIC_FIELD_PREFIX_SSRC "ssrc-"

#define PARAM_MIN_PORT "minPort"
#define PARAM_MAX_PORT "maxPort"
#define PARAM_MTU "mtu"

#define PROP_MIN_PORT "min-port"
#define PROP_MAX_PORT "max-port"
#define PROP_MTU "mtu"

/* Fixed point conversion macros */
#define FRIC        65536.                  /* 2^16 as a double */
#define FP2D(r)     ((double)(r) / FRIC)

namespace kurento
{
void BaseRtpEndpointImpl::postConstructor ()
{
  SdpEndpointImpl::postConstructor ();

  mediaStateChangedHandlerId = register_signal_handler (G_OBJECT (element),
                               "media-state-changed",
                               std::function <void (GstElement *, guint) > (std::bind (
                                     &BaseRtpEndpointImpl::updateMediaState, this,
                                     std::placeholders::_2) ),
                               std::dynamic_pointer_cast<BaseRtpEndpointImpl>
                               (shared_from_this() ) );

  connStateChangedHandlerId = register_signal_handler (G_OBJECT (element),
                              "connection-state-changed",
                              std::function <void (GstElement *, gchar *, guint) > (std::bind (
                                    &BaseRtpEndpointImpl::updateConnectionState, this,
                                    std::placeholders::_2, std::placeholders::_3) ),
                              std::dynamic_pointer_cast<BaseRtpEndpointImpl>
                              (shared_from_this() ) );
}

BaseRtpEndpointImpl::BaseRtpEndpointImpl (const boost::property_tree::ptree
    &config,
    std::shared_ptr< MediaObjectImpl > parent,
    const std::string &factoryName, bool useIpv6) :
  SdpEndpointImpl (config, parent, factoryName, useIpv6)
{
  current_media_state = std::make_shared <MediaState>
                        (MediaState::DISCONNECTED);
  mediaStateChangedHandlerId = 0;

  current_conn_state = std::make_shared <ConnectionState>
                       (ConnectionState::DISCONNECTED);
  connStateChangedHandlerId = 0;

  guint minPort = 0;
  if (getConfigValue<guint, BaseRtpEndpoint> (&minPort, PARAM_MIN_PORT)) {
    g_object_set (getGstreamerElement (), PROP_MIN_PORT, minPort, NULL);
  }

  guint maxPort = 0;
  if (getConfigValue <guint, BaseRtpEndpoint> (&maxPort, PARAM_MAX_PORT)) {
    g_object_set (getGstreamerElement (), PROP_MAX_PORT, maxPort, NULL);
  }

  guint mtu;
  if (getConfigValue <guint, BaseRtpEndpoint> (&mtu, PARAM_MTU)) {
    GST_INFO ("Predefined RTP MTU: %u", mtu);
    g_object_set (G_OBJECT (element), PROP_MTU, mtu, NULL);
  } else {
    GST_DEBUG ("No predefined RTP MTU found in config; using default");
  }
}

BaseRtpEndpointImpl::~BaseRtpEndpointImpl ()
{
  if (mediaStateChangedHandlerId > 0) {
    unregister_signal_handler (element, mediaStateChangedHandlerId);
  }

  if (connStateChangedHandlerId > 0) {
    unregister_signal_handler (element, connStateChangedHandlerId);
  }
}

void
BaseRtpEndpointImpl::updateMediaState (guint new_state)
{
  std::unique_lock<std::recursive_mutex> lock (mutex);
  std::shared_ptr<MediaState> old_state = current_media_state;

  switch (new_state) {
  case KMS_MEDIA_DISCONNECTED:
    current_media_state = std::make_shared <MediaState>
                          (MediaState::DISCONNECTED);
    break;

  case KMS_MEDIA_CONNECTED:
    current_media_state = std::make_shared <MediaState>
                          (MediaState::CONNECTED);
    break;

  default:
    GST_ERROR ("Invalid media state %u", new_state);
    return;
  }

  if (old_state->getValue() != current_media_state->getValue() ) {
    GST_DEBUG_OBJECT (element, "MediaState changed to '%s'",
        current_media_state->getString().c_str());
    try {
      MediaStateChanged event (shared_from_this (),
          MediaStateChanged::getName (), old_state, current_media_state);
      sigcSignalEmit(signalMediaStateChanged, event);
    } catch (const std::bad_weak_ptr &e) {
      // shared_from_this()
      GST_ERROR ("BUG creating %s: %s", MediaStateChanged::getName ().c_str (),
          e.what ());
    }
  }
}

void
BaseRtpEndpointImpl::updateConnectionState (gchar *sessId, guint new_state)
{
  std::unique_lock<std::recursive_mutex> lock (mutex);
  std::shared_ptr<ConnectionState> old_state = current_conn_state;

  switch (new_state) {
  case KMS_CONNECTION_DISCONNECTED:
    current_conn_state = std::make_shared <ConnectionState>
                         (ConnectionState::DISCONNECTED);
    break;

  case KMS_CONNECTION_CONNECTED:
    current_conn_state = std::make_shared <ConnectionState>
                         (ConnectionState::CONNECTED);
    break;

  default:
    GST_ERROR ("Invalid connection state %u", new_state);
    return;
  }

  if (old_state->getValue() != current_conn_state->getValue() ) {
    GST_DEBUG_OBJECT (element, "ConnectionState changed to '%s'",
        current_conn_state->getString().c_str());
    try {
      ConnectionStateChanged event (shared_from_this(),
          ConnectionStateChanged::getName (), old_state, current_conn_state);
      sigcSignalEmit(signalConnectionStateChanged, event);
    } catch (const std::bad_weak_ptr &e) {
      // shared_from_this()
      GST_ERROR ("BUG creating %s: %s",
          ConnectionStateChanged::getName ().c_str (), e.what ());
    }
  }
}

int BaseRtpEndpointImpl::getMinVideoRecvBandwidth ()
{
  int minVideoRecvBandwidth;

  g_object_get (element, "min-video-recv-bandwidth", &minVideoRecvBandwidth,
                NULL);

  return minVideoRecvBandwidth;
}

void BaseRtpEndpointImpl::setMinVideoRecvBandwidth (int minVideoRecvBandwidth)
{
  g_object_set (element, "min-video-recv-bandwidth", minVideoRecvBandwidth, NULL);
}

int BaseRtpEndpointImpl::getMinVideoSendBandwidth ()
{
  int minVideoSendBandwidth;

  g_object_get (element, "min-video-send-bandwidth", &minVideoSendBandwidth,
                NULL);

  return minVideoSendBandwidth;
}

void BaseRtpEndpointImpl::setMinVideoSendBandwidth (int minVideoSendBandwidth)
{
  g_object_set (element, "min-video-send-bandwidth", minVideoSendBandwidth, NULL);
}

int BaseRtpEndpointImpl::getMaxVideoSendBandwidth ()
{
  int maxVideoSendBandwidth;

  g_object_get (element, "max-video-send-bandwidth", &maxVideoSendBandwidth,
                NULL);

  return maxVideoSendBandwidth;
}

void BaseRtpEndpointImpl::setMaxVideoSendBandwidth (int maxVideoSendBandwidth)
{
  g_object_set (element, "max-video-send-bandwidth", maxVideoSendBandwidth, NULL);
}

std::shared_ptr<MediaState>
BaseRtpEndpointImpl::getMediaState ()
{
  return current_media_state;
}

std::shared_ptr<ConnectionState>
BaseRtpEndpointImpl::getConnectionState ()
{
  return current_conn_state;
}

std::shared_ptr<RembParams>
BaseRtpEndpointImpl::getRembParams ()
{
  std::shared_ptr<RembParams> ret (new RembParams() );
  GstStructure *params;
  gint auxi;
  gfloat auxf;

  g_object_get (G_OBJECT (element), REMB_PARAMS, &params, NULL);

  if (params == nullptr) {
    return ret;
  }

  /* REMB local begin */
  gst_structure_get (params, "packets-recv-interval-top", G_TYPE_INT, &auxi,
                     NULL);
  ret->setPacketsRecvIntervalTop (auxi);

  gst_structure_get (params, "exponential-factor", G_TYPE_FLOAT, &auxf, NULL);
  ret->setExponentialFactor (auxf);

  gst_structure_get (params, "lineal-factor-min", G_TYPE_INT, &auxi, NULL);
  ret->setLinealFactorMin (auxi);

  gst_structure_get (params, "lineal-factor-grade", G_TYPE_FLOAT, &auxf, NULL);
  ret->setLinealFactorGrade (auxf);

  gst_structure_get (params, "decrement-factor", G_TYPE_FLOAT, &auxf, NULL);
  ret->setDecrementFactor (auxf);

  gst_structure_get (params, "threshold-factor", G_TYPE_FLOAT, &auxf, NULL);
  ret->setThresholdFactor (auxf);

  gst_structure_get (params, "up-losses", G_TYPE_INT, &auxi, NULL);
  ret->setUpLosses (auxi);
  /* REMB local end */

  /* REMB remote begin */
  gst_structure_get (params, "remb-on-connect", G_TYPE_INT, &auxi, NULL);
  ret->setRembOnConnect (auxi);
  /* REMB remote end */

  gst_structure_free (params);

  return ret;
}

void
BaseRtpEndpointImpl::setRembParams (std::shared_ptr<RembParams> rembParams)
{
  GstStructure *params = gst_structure_new_empty (REMB_PARAMS);

  /* REMB local begin */
  if (rembParams->isSetPacketsRecvIntervalTop () ) {
    gst_structure_set (params, "packets-recv-interval-top", G_TYPE_INT,
                       rembParams->getPacketsRecvIntervalTop(), NULL);
    GST_DEBUG_OBJECT (element, "New 'packetsRecvIntervalTop' value: %d",
                      rembParams->getPacketsRecvIntervalTop() );
  }

  if (rembParams->isSetExponentialFactor () ) {
    gst_structure_set (params, "exponential-factor", G_TYPE_FLOAT,
                       rembParams->getExponentialFactor(), NULL);
    GST_DEBUG_OBJECT (element, "New 'exponentialFactor' value: %g",
                      rembParams->getExponentialFactor() );
  }

  if (rembParams->isSetLinealFactorMin () ) {
    gst_structure_set (params, "lineal-factor-min", G_TYPE_INT,
                       rembParams->getLinealFactorMin(), NULL);
    GST_DEBUG_OBJECT (element, "New 'linealFactorMin' value: %d",
                      rembParams->getLinealFactorMin() );
  }

  if (rembParams->isSetLinealFactorGrade () ) {
    gst_structure_set (params, "lineal-factor-grade", G_TYPE_FLOAT,
                       rembParams->getLinealFactorGrade(), NULL);
    GST_DEBUG_OBJECT (element, "New 'linealFactorGrade' value: %g",
                      rembParams->getLinealFactorGrade() );
  }

  if (rembParams->isSetDecrementFactor () ) {
    gst_structure_set (params, "decrement-factor", G_TYPE_FLOAT,
                       rembParams->getDecrementFactor(), NULL);
    GST_DEBUG_OBJECT (element, "New 'decrementFactor' value: %g",
                      rembParams->getDecrementFactor() );
  }

  if (rembParams->isSetThresholdFactor () ) {
    gst_structure_set (params, "threshold-factor", G_TYPE_FLOAT,
                       rembParams->getThresholdFactor(), NULL);
    GST_DEBUG_OBJECT (element, "New 'thresholdFactor' value: %g",
                      rembParams->getThresholdFactor() );
  }

  if (rembParams->isSetUpLosses () ) {
    gst_structure_set (params, "up-losses", G_TYPE_INT,
                       rembParams->getUpLosses(), NULL);
    GST_DEBUG_OBJECT (element, "New 'upLosses' value: %d",
                      rembParams->getUpLosses() );
  }

  /* REMB local end */

  /* REMB remote begin */
  if (rembParams->isSetRembOnConnect () ) {
    gst_structure_set (params, "remb-on-connect", G_TYPE_INT,
                       rembParams->getRembOnConnect(), NULL);
    GST_DEBUG_OBJECT (element, "New 'rembOnConnect' value: %d",
                      rembParams->getRembOnConnect() );
  }

  /* REMB remote end */

  g_object_set (G_OBJECT (element), REMB_PARAMS, params, NULL);
  gst_structure_free (params);
}

int
BaseRtpEndpointImpl::getMtu ()
{
  int mtu;

  g_object_get (G_OBJECT (element), PROP_MTU, &mtu, NULL);

  return mtu;
}

void
BaseRtpEndpointImpl::setMtu (int mtu)
{
  GST_INFO ("Set MTU for RTP: %d", mtu);
  g_object_set (G_OBJECT (element), PROP_MTU, mtu, NULL);
}

/******************/
/* RTC statistics */
/******************/
static std::shared_ptr<RTCInboundRTPStreamStats>
createRTCInboundRTPStreamStats (const GstStructure *source_stats,
    gchar *id,
    gchar *ssrc,
    guint nackCount)
{
  guint64 bytesReceived, packetsReceived;
  guint jitter, fractionLost, pliCount, firCount, remb;
  gint packetLost, clock_rate;
  float jitterSec;

  packetLost = jitter = fractionLost = pliCount = firCount = remb =
                                         clock_rate = 0;
  bytesReceived = packetsReceived = G_GUINT64_CONSTANT (0);
  jitterSec = 0.0;

  gst_structure_get (source_stats,
                     "packets-received", G_TYPE_UINT64, &packetsReceived,
                     "octets-received", G_TYPE_UINT64, &bytesReceived,
                     "sent-rb-packetslost", G_TYPE_INT, &packetLost,
                     "sent-rb-fractionlost", G_TYPE_UINT, &fractionLost,
                     "clock-rate", G_TYPE_INT, &clock_rate,
                     "jitter", G_TYPE_UINT, &jitter,
                     NULL);

  /* jitter is computed in timestamp units. Convert it to seconds */
  if (clock_rate > 0) {
    jitterSec = (float) jitter / clock_rate;
  }

  /* Next fields are only available with PLI and FIR statistics patches so */
  /* hey are prone to fail if these patches are not applied in Gstreamer */
  if (!gst_structure_get (source_stats, "sent-pli-count", G_TYPE_UINT, &pliCount,
                          "sent-fir-count", G_TYPE_UINT, &firCount, NULL) ) {
    GST_WARNING ("Current version of gstreamer has neither PLI nor FIR statistics patches applied.");
  }

  if (!gst_structure_get (source_stats, "remb", G_TYPE_UINT, &remb, NULL) ) {
    GST_TRACE ("No remb stats collected");
  }

  return std::make_shared<RTCInboundRTPStreamStats> (id,
      std::make_shared<StatsType> (StatsType::inboundrtp), 0.0, 0, ssrc, "",
      false, "", "", "", firCount, pliCount, nackCount, 0, remb, packetLost,
      (float)fractionLost, packetsReceived, bytesReceived, jitterSec);
}

static std::shared_ptr<RTCOutboundRTPStreamStats>
createRTCOutboundRTPStreamStats (const GstStructure *source_stats,
    gchar *id,
    gchar *ssrc,
    guint nackCount)
{
  guint64 bytesSent, packetsSent, bitRate;
  guint pliCount, firCount, remb, rtt, fractionLost;
  float roundTripTime;
  gint packetLost;

  bytesSent = packetsSent = bitRate = G_GUINT64_CONSTANT (0);
  pliCount = firCount = remb = rtt = 0;

  gst_structure_get (source_stats,
                     "packets-sent", G_TYPE_UINT64, &packetsSent,
                     "octets-sent", G_TYPE_UINT64, &bytesSent,
                     "bitrate", G_TYPE_UINT64, &bitRate,
                     "round-trip-time", G_TYPE_UINT, &rtt,
                     "outbound-fraction-lost", G_TYPE_UINT, &fractionLost,
                     "outbound-packet-lost", G_TYPE_INT, &packetLost,
                     NULL);

  /* the round-trip time (in NTP Short Format, 16.16 fixed point) */
  roundTripTime = FP2D (rtt);

  /* Next fields are only available with PLI and FIR statistics patches so */
  /* hey are prone to fail if these patches are not applied in Gstreamer */
  if (!gst_structure_get (source_stats, "recv-pli-count", G_TYPE_UINT, &pliCount,
                          "recv-fir-count", G_TYPE_UINT, &firCount, NULL) ) {
    GST_WARNING ("Current version of gstreamer has neither PLI nor FIR statistics patches applied.");
  }

  if (!gst_structure_get (source_stats, "remb", G_TYPE_UINT, &remb, NULL) ) {
    GST_TRACE ("No remb stats collected");
  }

  return std::make_shared<RTCOutboundRTPStreamStats> (id,
      std::make_shared<StatsType> (StatsType::outboundrtp), 0.0, 0, ssrc, "",
      false, "", "", "", firCount, pliCount, nackCount, 0, remb, packetLost,
      (float)fractionLost, packetsSent, bytesSent, (float)bitRate,
      roundTripTime);
}

static std::shared_ptr<RTCRTPStreamStats>
createRTCRTPStreamStats (guint nackSent, guint nackRecv,
                         const GstStructure *source_stats)
{
  std::shared_ptr<RTCRTPStreamStats> rtcStats;
  gboolean internal;
  gchar *id, *ssrc_str;
  guint ssrc;

  gst_structure_get (source_stats, "ssrc", G_TYPE_UINT, &ssrc, "internal",
                     G_TYPE_BOOLEAN, &internal, "id", G_TYPE_STRING, &id, NULL);

  ssrc_str = g_strdup_printf ("%u", ssrc);

  if (internal) {
    /* Local SSRC */
    rtcStats =
        createRTCOutboundRTPStreamStats (source_stats, id, ssrc_str, nackRecv);
  } else {
    /* Remote SSRC */
    rtcStats =
        createRTCInboundRTPStreamStats (source_stats, id, ssrc_str, nackSent);
  }

  g_free (ssrc_str);
  g_free (id);

  return rtcStats;
}

static void
collectRTCRTPStreamStats (std::map <std::string, std::shared_ptr<Stats>>
                          &statsReport, double timestamp,
                          int64_t timestampMillis, const GstStructure *session_stats)
{
  guint nackSent, nackRecv;
  gint i, n;

  nackSent = nackRecv = 0;

  gst_structure_get (session_stats, "sent-nack-count", G_TYPE_UINT, &nackSent,
                     "recv-nack-count", G_TYPE_UINT, &nackRecv, NULL);

  n = gst_structure_n_fields (session_stats);

  for (i = 0; i < n; i++) {
    std::shared_ptr<RTCStats> rtcStats;
    const GValue *value;
    const gchar *name;

    name = gst_structure_nth_field_name (session_stats, i);

    // Check field name as set by kmsbasertpendpoint in `append_rtp_session_stats()`.
    if (!g_str_has_prefix (name, KMS_STATISTIC_FIELD_PREFIX_SSRC) ) {
      continue;
    }

    value = gst_structure_get_value (session_stats, name);

    if (!GST_VALUE_HOLDS_STRUCTURE (value) ) {
      gchar *str_val;

      str_val = g_strdup_value_contents (value);
      GST_WARNING ("Unexpected field type (%s) = %s", name, str_val);
      g_free (str_val);

      continue;
    }

    rtcStats = createRTCRTPStreamStats (nackSent, nackRecv,
                                        gst_value_get_structure (value) );

    rtcStats->setTimestamp (timestamp);
    rtcStats->setTimestampMillis (timestampMillis);

    statsReport[rtcStats->getId ()] = rtcStats;
  }
}

static void
collectRTCStats (std::map <std::string, std::shared_ptr<Stats>>
                 &statsReport, double timestamp, int64_t timestampMillis,
                 const GstStructure *rtc_stats)
{
  gint i, n;

  n = gst_structure_n_fields (rtc_stats);

  for (i = 0; i < n; i++) {
    const GValue *value;
    const gchar *name;

    name = gst_structure_nth_field_name (rtc_stats, i);

    // Check field name as set by kmsbasertpendpoint in `append_rtp_session_stats()`.
    if (!g_str_has_prefix (name, KMS_STATISTIC_FIELD_PREFIX_SESSION) ) {
      GST_DEBUG ("Ignoring field %s", name);
      continue;
    }

    value = gst_structure_get_value (rtc_stats, name);

    if (!GST_VALUE_HOLDS_STRUCTURE (value) ) {
      gchar *str_val;

      str_val = g_strdup_value_contents (value);
      GST_WARNING ("Unexpected field type (%s) = %s", name, str_val);
      g_free (str_val);

      continue;
    }

    collectRTCRTPStreamStats (statsReport, timestamp, timestampMillis,
                              gst_value_get_structure (value) );
  }
}

static void
setDeprecatedProperties (std::shared_ptr<EndpointStats> eStats)
{
  std::vector<std::shared_ptr<MediaLatencyStat>> inStats =
        eStats->getE2ELatency();

  for (auto &inStat : inStats) {
    if (inStat->getName() == "sink_audio_default") {
      eStats->setAudioE2ELatency(inStat->getAvg());
    } else if (inStat->getName() == "sink_video_default") {
      eStats->setVideoE2ELatency(inStat->getAvg());
    }
  }
}

void
BaseRtpEndpointImpl::collectEndpointStats (std::map
    <std::string, std::shared_ptr<Stats>>
    &statsReport, std::string id, const GstStructure *e_stats,
    double timestamp, int64_t timestampMillis)
{
  std::shared_ptr<Stats> endpointStats;
  GstStructure *e2e_stats;

  std::vector<std::shared_ptr<MediaLatencyStat>> inputStats;
  std::vector<std::shared_ptr<MediaLatencyStat>> e2eStats;

  if (gst_structure_get (e_stats, "e2e-latencies", GST_TYPE_STRUCTURE,
                         &e2e_stats, NULL) ) {
    collectLatencyStats (e2eStats, e2e_stats);
    gst_structure_free (e2e_stats);
  }

  endpointStats = std::make_shared <EndpointStats> (id,
                  std::make_shared <StatsType> (StatsType::endpoint), timestamp,
                  timestampMillis, 0.0, 0.0, inputStats, 0.0, 0.0, e2eStats);

  setDeprecatedProperties (std::dynamic_pointer_cast <EndpointStats>
                           (endpointStats) );

  statsReport[id] = endpointStats;
}

void
BaseRtpEndpointImpl::fillStatsReport (std::map
                                      <std::string, std::shared_ptr<Stats>>
                                      &report, const GstStructure *stats,
                                      double timestamp, int64_t timestampMillis)
{
  const GstStructure *e_stats, *rtc_stats;

  e_stats = kms_utils_get_structure_by_name (stats, KMS_MEDIA_ELEMENT_FIELD);

  if (e_stats != nullptr) {
    collectEndpointStats (report, getId (), e_stats, timestamp, timestampMillis);
  }

  rtc_stats = kms_utils_get_structure_by_name (stats, KMS_RTC_STATISTICS_FIELD);

  if (rtc_stats != nullptr) {
    collectRTCStats (report, timestamp, timestampMillis, rtc_stats );
  }

  SdpEndpointImpl::fillStatsReport (report, stats, timestamp, timestampMillis);
}

BaseRtpEndpointImpl::StaticConstructor BaseRtpEndpointImpl::staticConstructor;

BaseRtpEndpointImpl::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} /* kurento */


text:
require 'test_helper'

class DismissibleBlocksControllerTest < ActionDispatch::IntegrationTest

  test "dismiss block via ajax" do
    post login_url, params: {
      username: users(:one).username,
      password: users(:one).password
    }
    assert_response :redirect
    assert_redirected_to landing_url
    refute users(:one).dismissed_blocks.include?('lorem')

    put dismissible_blocks_url(format: :json),
      params: { block: 'lorem' },
      xhr: true
    users(:one).reload
    assert users(:one).dismissed_blocks.include?('lorem')
    assert_response :ok
  end

  test "dismiss block fails via ajax; not logged in" do
    put dismissible_blocks_url(format: :json),
      params: { block: 'lorem' },
      xhr: true
    assert_response :unprocessable_entity
  end

end