text:
package com.vmware.action.vcd;

import com.vmware.action.base.BaseSingleVappJsonAction;
import com.vmware.config.ActionDescription;
import com.vmware.config.WorkflowConfig;
import com.vmware.util.SystemUtils;

@ActionDescription("Copies the testbed json for the selected Vapp to the clipboard.")
public class CopyVappJsonToClipboard extends BaseSingleVappJsonAction {
    public CopyVappJsonToClipboard(WorkflowConfig config) {
        super(config);
    }

    @Override
    public void process() {
        log.info("Copying testbed json for Vapp {} to clipboard", vappData.getSelectedVappName());
        SystemUtils.copyTextToClipboard(vappData.getJsonData());
    }
}


text:
if ($('#my-dropzone').length  ) {
	Dropzone.autoDiscover = false;

	var myDropzone = new Dropzone("#my-dropzone");
	myDropzone.on("success", function(file) {
		file = JSON.parse(file.xhr.responseText);
		if(file.error){
			//$("#my-dropzone").children().last().remove();
			alert(file.error);
			return false;
		}

		$('#upload').append(file.html);
		$('#totalSize').text(file.totalSize);
		console.log(file);
	});
}

$('.fancybox').fancybox();

$('.deleteshare').click(function(e){

	$.ajax({
		url: baseUrl+'/upload/share/delete/'+e.currentTarget.id,
	}).done(function(data) {
		if(data.length)
			alert(data);
	});
})

redpajama_set_name: RedPajamaGithub


text:
#ifndef _EMQ_PACKET_H_
#define _EMQ_PACKET_H_

#include <stdint.h>

#include "emq.h"
#include "protocol.h"

int emq_check_response_header(protocol_response_header *header, uint8_t cmd, uint32_t bodylen);

int emq_check_response_header_mini(protocol_response_header *header, uint8_t cmd);

int emq_check_event_header(protocol_event_header *header, uint8_t type1, uint8_t type2);

int emq_check_status(protocol_response_header *header, uint8_t status);
int emq_get_error(protocol_response_header *header);

int emq_auth_request(emq_client *client, const char *name, const char *password);
int emq_ping_request(emq_client *client);
int emq_stat_request(emq_client *client);
int emq_save_request(emq_client *client, uint8_t async);
int emq_flush_request(emq_client *client, uint32_t flags);

int emq_user_create_request(emq_client *client, const char *name, const char *password, uint64_t perm);
int emq_user_list_request(emq_client *client);
int emq_user_rename_request(emq_client *client, const char *from, const char *to);
int emq_user_set_perm_request(emq_client *client, const char *name, uint64_t perm);
int emq_user_delete_request(emq_client *client, const char *name);

int emq_queue_create_request(emq_client *client, const char *name, uint32_t max_msg, uint32_t max_msg_size, uint32_t flags);
int emq_queue_declare_request(emq_client *client, const char *name);
int emq_queue_exist_request(emq_client *client, const char *name);
int emq_queue_list_request(emq_client *client);
int emq_queue_rename_request(emq_client *client, const char *from, const char *to);
int emq_queue_size_request(emq_client *client, const char *name);
int emq_queue_push_request(emq_client *client, const char *name, uint32_t msg_size);
int emq_queue_get_request(emq_client *client, const char *name);
int emq_queue_pop_request(emq_client *client, const char *name, uint32_t timeout);
int emq_queue_confirm_request(emq_client *client, const char *name, uint64_t tag);
int emq_queue_subscribe_request(emq_client *client, const char *name, uint32_t flags);
int emq_queue_unsubscribe_request(emq_client *client, const char *name);
int emq_queue_purge_request(emq_client *client, const char *name);
int emq_queue_delete_request(emq_client *client, const char *name);

int emq_route_create_request(emq_client *client, const char *name, uint32_t flags);
int emq_route_exist_request(emq_client *client, const char *name);
int emq_route_list_request(emq_client *client);
int emq_route_keys_request(emq_client *client, const char *name);
int emq_route_rename_request(emq_client *client, const char *from, const char *to);
int emq_route_bind_request(emq_client *client, const char *name, const char *queue, const char *key);
int emq_route_unbind_request(emq_client *client, const char *name, const char *queue, const char *key);
int emq_route_push_request(emq_client *client, const char *name, const char *key, uint32_t msg_size);
int emq_route_delete_request(emq_client *client, const char *name);

int emq_channel_create_request(emq_client *client, const char *name, uint32_t flags);
int emq_channel_exist_request(emq_client *client, const char *name);
int emq_channel_list_request(emq_client *client);
int emq_channel_rename_request(emq_client *client, const char *from, const char *to);
int emq_channel_publish_request(emq_client *client, const char *name, const char *topic, uint32_t msg_size);
int emq_channel_subscribe_request(emq_client *client, const char *name, const char *topic);
int emq_channel_psubscribe_request(emq_client *client, const char *name, const char *pattern);
int emq_channel_unsubscribe_request(emq_client *client, const char *name, const char *topic);
int emq_channel_punsubscribe_request(emq_client *client, const char *name, const char *pattern);
int emq_channel_delete_request(emq_client *client, const char *name);

#endif


text:
@class ORMAttributeDescription;
@class ORMEntityDescription;

@interface ORMEntityDescription : NSObject

#pragma mark Life-cycle
- (id)initWithClass:(Class)managedClass;

#pragma mark Managed Class
@property (nonatomic, readonly) Class managedClass;

#pragma mark Entity
@property (nonatomic, readonly) NSString *name;
@property (nonatomic, readonly) ORMEntityDescription *superentity;
@property (nonatomic, readonly) NSArray *entityHierarchy;

#pragma mark Properties
@property (nonatomic, readonly) ORMAttributeDescription *(^attribute)(NSString *name);
@property (nonatomic, readonly) NSDictionary *properties;
@property (nonatomic, readonly) NSDictionary *allProperties;

#pragma mark Constraints
@property (nonatomic, readonly) void (^unique)(NSArray *names);
@property (nonatomic, readonly) NSSet *uniqueConstraints;
@property (nonatomic, readonly) NSSet *allUniqueConstraints;

@end


text:
layout: post
title: "Building an OpenBSD BGP Looking Glass"
date: 2013-01-27 23:03:00 -0600
comments: false
categories:
- Nerd Projects
- Networking
- IPv6
- ISP
- BGP
- System Administration
---
One of the really handy things that has been included in OpenBSD for quite some while, is a handy shell, and CGI BGP looking glass. Rather than copy and paste someone elses blog, I'll just [link the handy guide I followed](http://www.knowledgebombs.net/blog/2012/12/13/bgplg-from-scratch.html). This guide is complete, including explaining why ping/ping6/traceroute/traceroute6 don't work under /var in the chrooted environment.

<!--more-->

Since apache is being phased out in OpenBSD, I wonder what the solution will be for nginx? Someone will probably rewrite it in a fancy way.

**Update:** I have since [written a blog](/2014/05/14/openbsd-5-dot-5-bgplg/) about building an OpenBSD BGPLG with nginx.


text:
<?php
namespace Neos\Flow\Configuration;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Configuration\Source\YamlSource;
use Neos\Flow\Package\Package;
use Neos\Utility\Arrays;
use Neos\Utility\PositionalArraySorter;

/**
 * @Flow\Proxy(FALSE)
 */
class RouteConfigurationProcessor
{
    /**
     * The maximum number of recursions when merging subroute configurations.
     *
     * @var integer
     */
    const MAXIMUM_SUBROUTE_RECURSIONS = 99;

    /**
     * Counts how many SubRoutes have been loaded. If this number exceeds MAXIMUM_SUBROUTE_RECURSIONS, an exception is thrown
     *
     * @var integer
     */
    protected $subRoutesRecursionLevel = 0;

    /**
     * @var array
     */
    protected $routeSettings;

    /**
     * @var array
     */
    protected $orderedListOfContextNames;

    /**
     * @var Package[]
     */
    protected $packages;

    /**
     * @var YamlSource
     */
    protected $configurationSource;

    /**
     * RouteConfigurationProcessor constructor.
     *
     * @param array $routeSettings
     * @param array $orderedListOfContextNames
     * @param array $packages
     * @param $configurationSource
     */
    public function __construct(array $routeSettings, array $orderedListOfContextNames, array $packages, $configurationSource)
    {
        $this->routeSettings = $routeSettings;
        $this->orderedListOfContextNames = $orderedListOfContextNames;
        $this->packages = $packages;
        $this->configurationSource = $configurationSource;
    }

    /**
     * @param $routeDefinitions
     * @return array
     * @throws Exception\ParseErrorException
     * @throws Exception\RecursionException
     */
    public function process($routeDefinitions)
    {
        $routeDefinitions = $this->includeSubRoutesFromSettings($routeDefinitions);
        $routeDefinitions = $this->mergeRoutesWithSubRoutes($routeDefinitions);
        return $routeDefinitions;
    }

    /**
     * Merges routes from Neos.Flow.mvc.routes settings into $routeDefinitions
     * NOTE: Routes from settings will always be appended to existing route definitions from the main Routes configuration!
     *
     * @param array $routeDefinitions
     * @return array
     */
    protected function includeSubRoutesFromSettings($routeDefinitions)
    {
        if ($this->routeSettings === null) {
            return;
        }
        $sortedRouteSettings = (new PositionalArraySorter($this->routeSettings))->toArray();
        foreach ($sortedRouteSettings as $packageKey => $routeFromSettings) {
            if ($routeFromSettings === false) {
                continue;
            }
            $subRoutesName = $packageKey . 'SubRoutes';
            $subRoutesConfiguration = ['package' => $packageKey];
            if (isset($routeFromSettings['variables'])) {
                $subRoutesConfiguration['variables'] = $routeFromSettings['variables'];
            }
            if (isset($routeFromSettings['suffix'])) {
                $subRoutesConfiguration['suffix'] = $routeFromSettings['suffix'];
            }
            $routeDefinitions[] = [
                'name' => $packageKey,
                'uriPattern' => '<' . $subRoutesName . '>',
                'subRoutes' => [
                    $subRoutesName => $subRoutesConfiguration
                ]
            ];
        }

        return $routeDefinitions;
    }

    /**
     * Loads specified sub routes and builds composite routes.
     *
     * @param array $routesConfiguration
     * @return array
     * @throws Exception\ParseErrorException
     * @throws Exception\RecursionException
     */
    protected function mergeRoutesWithSubRoutes(array $routesConfiguration)
    {
        $mergedRoutesConfiguration = [];
        foreach ($routesConfiguration as $routeConfiguration) {
            if (!isset($routeConfiguration['subRoutes'])) {
                $mergedRoutesConfiguration[] = $routeConfiguration;
                continue;
            }
            $mergedSubRoutesConfiguration = [$routeConfiguration];
            foreach ($routeConfiguration['subRoutes'] as $subRouteKey => $subRouteOptions) {
                if (!isset($subRouteOptions['package'])) {
                    throw new Exception\ParseErrorException(sprintf('Missing package configuration for SubRoute in Route "%s".', (isset($routeConfiguration['name']) ? $routeConfiguration['name'] : 'unnamed Route')), 1318414040);
                }
                if (!isset($this->packages[$subRouteOptions['package']])) {
                    throw new Exception\ParseErrorException(sprintf('The SubRoute Package "%s" referenced in Route "%s" is not available.', $subRouteOptions['package'], (isset($routeConfiguration['name']) ? $routeConfiguration['name'] : 'unnamed Route')), 1318414040);
                }
                /** @var $package PackageInterface */
                $package = $this->packages[$subRouteOptions['package']];
                $subRouteFilename = 'Routes';
                if (isset($subRouteOptions['suffix'])) {
                    $subRouteFilename .= '.' . $subRouteOptions['suffix'];
                }
                $subRouteConfiguration = [];
                foreach (array_reverse($this->orderedListOfContextNames) as $contextName) {
                    $subRouteFilePathAndName = $package->getConfigurationPath() . $contextName . '/' . $subRouteFilename;
                    $subRouteConfiguration = array_merge($subRouteConfiguration, $this->configurationSource->load($subRouteFilePathAndName));
                }
                $subRouteFilePathAndName = $package->getConfigurationPath() . $subRouteFilename;
                $subRouteConfiguration = array_merge($subRouteConfiguration, $this->configurationSource->load($subRouteFilePathAndName));
                if ($this->subRoutesRecursionLevel > self::MAXIMUM_SUBROUTE_RECURSIONS) {
                    throw new Exception\RecursionException(sprintf('Recursion level of SubRoutes exceed ' . self::MAXIMUM_SUBROUTE_RECURSIONS . ', probably because of a circular reference. Last successfully loaded route configuration is "%s".', $subRouteFilePathAndName), 1361535753);
                }

                $this->subRoutesRecursionLevel++;
                $subRouteConfiguration = $this->mergeRoutesWithSubRoutes($subRouteConfiguration);
                $this->subRoutesRecursionLevel--;
                $mergedSubRoutesConfiguration = $this->buildSubRouteConfigurations($mergedSubRoutesConfiguration, $subRouteConfiguration, $subRouteKey, $subRouteOptions);
            }
            $mergedRoutesConfiguration = array_merge($mergedRoutesConfiguration, $mergedSubRoutesConfiguration);
        }

        return $mergedRoutesConfiguration;
    }

    /**
     * Merges all routes in $routesConfiguration with the sub routes in $subRoutesConfiguration
     *
     * @param array $routesConfiguration
     * @param array $subRoutesConfiguration
     * @param string $subRouteKey the key of the sub route: <subRouteKey>
     * @param array $subRouteOptions
     * @return array the merged route configuration
     * @throws Exception\ParseErrorException
     */
    protected function buildSubRouteConfigurations(array $routesConfiguration, array $subRoutesConfiguration, $subRouteKey, array $subRouteOptions)
    {
        $variables = $subRouteOptions['variables'] ?? [];
        $mergedSubRoutesConfigurations = [];
        foreach ($subRoutesConfiguration as $subRouteConfiguration) {
            foreach ($routesConfiguration as $routeConfiguration) {
                $mergedSubRouteConfiguration = $subRouteConfiguration;
                $mergedSubRouteConfiguration['name'] = sprintf('%s :: %s', $routeConfiguration['name'] ?? 'Unnamed Route', $subRouteConfiguration['name'] ?? 'Unnamed Subroute');
                $mergedSubRouteConfiguration['name'] = $this->replacePlaceholders($mergedSubRouteConfiguration['name'], $variables);
                if (!isset($mergedSubRouteConfiguration['uriPattern'])) {
                    throw new Exception\ParseErrorException('No uriPattern defined in route configuration "' . $mergedSubRouteConfiguration['name'] . '".', 1274197615);
                }
                if ($mergedSubRouteConfiguration['uriPattern'] !== '') {
                    $mergedSubRouteConfiguration['uriPattern'] = $this->replacePlaceholders($mergedSubRouteConfiguration['uriPattern'], $variables);
                    $mergedSubRouteConfiguration['uriPattern'] = $this->replacePlaceholders($routeConfiguration['uriPattern'], [$subRouteKey => $mergedSubRouteConfiguration['uriPattern']]);
                } else {
                    $mergedSubRouteConfiguration['uriPattern'] = rtrim($this->replacePlaceholders($routeConfiguration['uriPattern'], [$subRouteKey => '']), '/');
                }
                if (isset($mergedSubRouteConfiguration['defaults'])) {
                    $mergedSubRouteConfiguration['defaults'] = $this->replacePlaceholders($mergedSubRouteConfiguration['defaults'], $variables);
                }
                if (isset($mergedSubRouteConfiguration['routeParts'])) {
                    $mergedSubRouteConfiguration['routeParts'] = $this->replacePlaceholders($mergedSubRouteConfiguration['routeParts'], $variables);
                }
                $mergedSubRouteConfiguration = Arrays::arrayMergeRecursiveOverrule($routeConfiguration, $mergedSubRouteConfiguration);
                unset($mergedSubRouteConfiguration['subRoutes']);
                $mergedSubRoutesConfigurations[] = $mergedSubRouteConfiguration;
            }
        }

        return $mergedSubRoutesConfigurations;
    }

    /**
     * Replaces placeholders in the format <variableName> with the corresponding variable of the specified $variables collection.
     *
     * @param string|array $value
     * @param array $variables
     * @return mixed
     */
    protected function replacePlaceholders($value, array $variables)
    {
        if (is_array($value)) {
            foreach ($value as $arrayKey => $arrayValue) {
                $value[$arrayKey] = $this->replacePlaceholders($arrayValue, $variables);
            }
        } elseif (is_string($value)) {
            foreach ($variables as $variableName => $variableValue) {
                $value = str_replace('<' . $variableName . '>', $variableValue, $value);
            }
        }
        return $value;
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<title>My Email - PennCloud</title>

PennCloud Email

Your email list:

Compose new email:

<form action="/composepage" method="post"><button>Compose</button></form>

Homepage


text:
  Saint-Albain est
       un village
       localisé dans le département de Saône-et-Loire en Bourgogne. Elle totalisait 527 habitants en 2008.

Si vous envisagez de emmenager à Saint-Albain, vous pourrez aisément trouver une maison à acheter.

À Saint-Albain, la valeur moyenne à l'achat d'un appartement se situe à 928 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 021 € du m². À la location la valeur moyenne se situe à 6,19 € du m² par mois.

La commune propose quelques  équipements sportifs, elle dispose, entre autres, de un terrain de tennis et un terrain de sport.

Le parc de logements, à Saint-Albain, se décomposait en 2011 en 65 appartements et 203 maisons soit
 un marché relativement équilibré.

À proximité de Saint-Albain sont positionnées géographiquement les communes de
Asnières-sur-Saône à 4 km, 92 habitants,
Pont-de-Vaux située à 4 km, 2 102 habitants,
Senozan localisée à 3 km, 1 096 habitants,
Reyssouze localisée à 3 km, 859 habitants,
La Salle à 2 km, 482 habitants,
Fleurville à 1 km, 473 habitants,
 entre autres. De plus, Saint-Albain est située à seulement treize km de Mâcon.


text:
import * as path from 'path';
import * as webpack from 'webpack';

export interface EmittedFiles {
  id?: string;
  name?: string;
  file: string;
  initial: boolean;
  asset?: boolean;
  extension: string;
}

export function getEmittedFiles(compilation: webpack.compilation.Compilation): EmittedFiles[] {
  const files: EmittedFiles[] = [];

  // adds all chunks to the list of emitted files such as lazy loaded modules
  for (const chunk of compilation.chunks as webpack.compilation.Chunk[]) {
    for (const file of chunk.files as string[]) {
      files.push({
        // The id is guaranteed to exist at this point in the compilation process
        // tslint:disable-next-line: no-non-null-assertion
        id: chunk.id!.toString(),
        name: chunk.name,
        file,
        extension: path.extname(file),
        initial: chunk.isOnlyInitial(),
      });
    }
  }

  // other all files
  for (const file of Object.keys(compilation.assets)) {
    files.push({ file, extension: path.extname(file), initial: false, asset: true });
  }

  // dedupe
  return files.filter(({ file, name }, index) =>
    files.findIndex(f => f.file === file && (!name || name === f.name)) === index);
}


text:
package ua.com.fielden.platform.dao;

import ua.com.fielden.platform.entity.DynamicEntityKey;
import ua.com.fielden.platform.entity.annotation.EntityType;
import ua.com.fielden.platform.entity.query.IFilter;
import ua.com.fielden.platform.persistence.composite.EntityWithDynamicCompositeKey;

import com.google.inject.Inject;

/**
 * This is a test DAO with a composite key implemented by {@link DynamicEntityKey}.
 *
 * @author TG Team
 *
 */
@EntityType(EntityWithDynamicCompositeKey.class)
public class EntityWithDynamicCompositeKeyDao extends CommonEntityDao<EntityWithDynamicCompositeKey> {

    @Inject
    protected EntityWithDynamicCompositeKeyDao(final IFilter filter) {
        super(filter);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <androidx.appcompat.widget.SwitchCompat
        android:id="@+id/enableSwitch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="@string/enable_swipeactions" />

    <include
        android:id="@+id/actionLeftContainer"
        layout="@layout/swipeactions_row" />

    <include
        android:id="@+id/actionRightContainer"
        layout="@layout/swipeactions_row" />

</LinearLayout>


text:
using Dibware.Template.Presentation.Web.Models.Base;
using System;
using System.ComponentModel.DataAnnotations;

namespace Dibware.Template.Presentation.Web.Models.Account
{
    public class ConfirmAccountViewModel : BaseViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public String UserName { get; set; }

        [Required]
        [Display(Name = "Confirmation Token")]
        public String ConfirmationToken { get; set; }
    }
}


text:
package org.grassroot.android.adapters;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import org.grassroot.android.R;

/**
 * Created by ravi on 6/5/16.
 */
public class ProfileAdapter extends RecyclerView.Adapter<ProfileAdapter.ProfileHolder> {

    final int[] titles;
    final int[] icons;

    public ProfileAdapter(int[] titles, int[] icons) {
        this.titles = titles;
        this.icons = icons;
    }

    @Override
    public ProfileHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_profile,parent,false);
        return new ProfileHolder(v);
    }

    @Override
    public void onBindViewHolder(ProfileHolder holder, int position) {
        holder.icon.setImageResource(icons[position]);
        holder.text.setText(titles[position]);
    }

    @Override
    public int getItemCount() {
        return titles.length;
    }

    public class ProfileHolder extends RecyclerView.ViewHolder {

        private ImageView icon;
        private TextView text;

        public ProfileHolder(View view) {
            super(view);
            icon = (ImageView) view.findViewById(R.id.iv_pp_title_icon);
            text = (TextView) view.findViewById(R.id.txt_pp_title);
        }
    }
}


text:
/**
 * Created by:CaMnter
 */

class Car {

  engine: string;

  constructor(engine: string) {
    this.engine = engine;
  }

  display() {
    console.log("「Car」「engine」" + this.engine)
  }

}

const car = new Car('engine');
car.display();

class Shape {

  area: number;

  constructor(area: number) {
    this.area = area;
  }

}

class Circle extends Shape {

  display(): void {
    console.log("「Circle」「area」" + this.area);
  }

}

const circle = new Circle(2233);
circle.display();

class PrinterClass {

  display(): void {
    console.log("「Circle」「display」")
  }

}

class StringPrinter extends PrinterClass {

  display(): void {
    super.display();
    console.log("「StringPrinter」「display」");
  }

}

const stringPrinter = new StringPrinter();
stringPrinter.display();

class Static {

  static value: number;

  display(): void {
    console.log("「Static」「display」「value」", Static.value);
  }

}

Static.value = 233;
const staticObject = new Static();
staticObject.display();

console.log("「Static」「display」「value」", (staticObject instanceof Static));


text:
<?php

/**
 * PluginCommune form.
 *
 * @package    ##PROJECT_NAME##
 * @subpackage filter
 * @author     ##AUTHOR_NAME##
 * @version    SVN: $Id: sfDoctrineFormFilterPluginTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
abstract class PluginCommuneFormFilter extends BaseCommuneFormFilter
{
}


text:
    /**
     * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
     * Or merges two observable sequences into a single observable sequence.
     *
     * @example
     * 1 - merged = sources.merge(1);
     * 2 - merged = source.merge(otherSource);
     * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
     * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
     */
    observableProto.merge = function (maxConcurrentOrOther) {
        if (typeof maxConcurrentOrOther !== 'number') {
            return observableMerge(this, maxConcurrentOrOther);
        }
        var sources = this;
        return new AnonymousObservable(function (observer) {
            var activeCount = 0,
                group = new CompositeDisposable(),
                isStopped = false,
                q = [],
                subscribe = function (xs) {
                    var subscription = new SingleAssignmentDisposable();
                    group.add(subscription);
                    subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
                        var s;
                        group.remove(subscription);
                        if (q.length > 0) {
                            s = q.shift();
                            subscribe(s);
                        } else {
                            activeCount--;
                            if (isStopped && activeCount === 0) {
                                observer.onCompleted();
                            }
                        }
                    }));
                };
            group.add(sources.subscribe(function (innerSource) {
                if (activeCount < maxConcurrentOrOther) {
                    activeCount++;
                    subscribe(innerSource);
                } else {
                    q.push(innerSource);
                }
            }, observer.onError.bind(observer), function () {
                isStopped = true;
                if (activeCount === 0) {
                    observer.onCompleted();
                }
            }));
            return group;
        });
    };


text:
{% extends "menu.html" %}
{% load userdata %}
{% load static_dbg %}

{% block content %}

  <input class="form-control" id="search_field" placeholder="Buscar" />

  <button class="btn btn-primary" id="search_btn">Buscar</button>
  Ajuda

Resultats de la cerca

{# Emplenat per l'script #}

Registrats

{# Emplenat per l'script #}

        Alumne
        Nom d'usuari
        Administrador
        Canviar contrasenya
        Eliminar

      {# Emplenat per l'script #}

No registrats

{# Emplenat per l'script #}

        Alumne
        Nom d'usuari
        Codi
        Canviar codi
        Cancel·lar

      {# Emplenat per l'script #}

{% if n_unregistered %}

No registrats
Els usuaris no registrats sempre apareixen com a "<usuari> (*)".

    Exportar a CSV (Excel)

    Imprimir (exportar a PDF)

    Generar circulars

<button class="btn btn-link" id="unregistered_toggle">
  {# Emplenat per l'script #}
</button>

        Alumne
        Nom d'usuari
        Codi
        Canviar codi
        Cancel·lar

      {# Emplenat per l'script #}

{% endif %}

Registrats

    Nou aministrador

<button class="btn btn-link" id="registered_toggle">{# Emplenat per l'script #}</button>

        Alumne
        Nom d'usuari
        Administrador
        Canviar contrasenya
        Eliminar

      {# Emplenat per l'script #}

{% endblock content %}

{% block scripts %}

{% endblock scripts %}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using Azure.Core;

namespace Azure.AI.MetricsAdvisor.Models
{
    /// <summary>
    /// Describes an Azure Blob data source which ingests data into a <see cref="DataFeed"/> for anomaly detection.
    /// </summary>
    public class AzureBlobDataFeedSource : DataFeedSource
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AzureBlobDataFeedSource"/> class.
        /// </summary>
        /// <param name="connectionString">The connection string for authenticating to the Azure Storage Account.</param>
        /// <param name="container">The name of the blob container.</param>
        /// <param name="blobTemplate">
        /// This is the template of the Blob file names. For example: /%Y/%m/X_%Y-%m-%d-%h-%M.json. The following parameters are supported:
        /// <list type="bullet">
        /// <item>
        /// <term>%Y</term>
        /// <description>The year formatted as yyyy</description>
        /// </item>
        /// <item>
        /// <term>%m</term>
        /// <description>The month formatted as MM</description>
        /// </item>
        /// <item>
        /// <term>%d</term>
        /// <description>The day formatted as dd</description>
        /// </item>
        /// <item>
        /// <term>%h</term>
        /// <description>The hour formatted as HH</description>
        /// </item>
        /// <item>
        /// <term>%M</term>
        /// <description>The minute formatted as mm</description>
        /// </item>
        /// </list>
        /// </param>
        /// <exception cref="ArgumentNullException"><paramref name="connectionString"/>, <paramref name="container"/>, or <paramref name="blobTemplate"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="connectionString"/>, <paramref name="container"/>, or <paramref name="blobTemplate"/> is empty.</exception>
        public AzureBlobDataFeedSource(string connectionString, string container, string blobTemplate)
            : base(DataFeedSourceType.AzureBlob)
        {
            Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));
            Argument.AssertNotNullOrEmpty(container, nameof(container));
            Argument.AssertNotNullOrEmpty(blobTemplate, nameof(blobTemplate));

            Parameter = new AzureBlobParameter(connectionString, container, blobTemplate);
        }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE617_Reachable_Assertion__rand_15.c
Label Definition File: CWE617_Reachable_Assertion.label.xml
Template File: sources-sink-15.tmpl.c
*/
/*
 * @description
 * CWE: 617 Reachable Assertion
 * BadSource: rand Set data to result of rand(), which may be zero
 * GoodSource: Number greater than ASSERT_VALUE
 * Sink:
 *    BadSink : Assert if n is less than or equal to ASSERT_VALUE
 * Flow Variant: 15 Control flow: switch(6)
 *
 * */

#include "std_testcase.h"

#include <assert.h>

#define ASSERT_VALUE 5

#ifndef OMITBAD

void CWE617_Reachable_Assertion__rand_15_bad()
{
    int data;
    /* Initialize data */
    data = -1;
    switch(6)
    {
    case 6:
        /* POTENTIAL FLAW: Set data to a random value */
        data = RAND32();
        break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
    /* POTENTIAL FLAW: this assertion could trigger if n <= ASSERT_VALUE */
    assert(data > ASSERT_VALUE);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B1() - use goodsource and badsink by changing the switch to switch(5) */
static void goodG2B1()
{
    int data;
    /* Initialize data */
    data = -1;
    switch(5)
    {
    case 6:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    default:
        /* FIX: Use a value greater than the assert value */
        data = ASSERT_VALUE+1;
        break;
    }
    /* POTENTIAL FLAW: this assertion could trigger if n <= ASSERT_VALUE */
    assert(data > ASSERT_VALUE);
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the switch */
static void goodG2B2()
{
    int data;
    /* Initialize data */
    data = -1;
    switch(6)
    {
    case 6:
        /* FIX: Use a value greater than the assert value */
        data = ASSERT_VALUE+1;
        break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
    /* POTENTIAL FLAW: this assertion could trigger if n <= ASSERT_VALUE */
    assert(data > ASSERT_VALUE);
}

void CWE617_Reachable_Assertion__rand_15_good()
{
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE617_Reachable_Assertion__rand_15_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE617_Reachable_Assertion__rand_15_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <inttypes.h>

#include "source.h"
#include "source/backend.h"
#include "utils.h"

/* Total number of source backends */
#define N_SOURCE_BACKENDS 2
static const struct source_backend_vtable *sources[N_SOURCE_BACKENDS];

/**
 * Lookup a source backend in the table.
 */
static size_t find_backend(const char *name, size_t len)
{
	size_t i;

	if (!name || !len) goto ret;
	for (i = 0; i < N_SOURCE_BACKENDS; i++) {
		/* Skip unusable sources */
		if (!sources[i] || !sources[i]->name)
			continue;

		/* If the lengths aren't equal, skip it. */
		if (len != strlen(sources[i]->name))
			continue;

		/* Now, we can match on the name */
		if (!memcmp(sources[i]->name, name, len))
			return i;
	}

ret:
	return SIZE_MAX;
}

/**
 * Initialize the migration source layer.
 *
 * This function \a must be called before any other source_ functions
 * are used, as this sets up the sources themselves.
 */
void source_init(void)
{
	size_t i;

	for (i = 0; i < N_SOURCE_BACKENDS; i++) {
		if (!sources[i] || !sources[i]->init)
			continue;

		if (sources[i]->init()) {
			error("failed to initialize '%s'",
			      sources[i]->name);
			sources[i] = NULL;
		}
	}
}

/**
 * Lookup the configuration callback for a source.
 *
 * \param[in] source Name of the source to look for.
 * \return a pointer to the source's callback function, or NULL.
 */
config_callback_t source_get_config_cb(const char *source, size_t len)
{
	size_t i;

	i = find_backend(source, len);
	if (i == SIZE_MAX) goto ret;

	if (sources[i]->config)
		return sources[i]->config;

ret:
	return NULL;
}

/**
 * Provide an ordered list of migration files, in the order that
 * they would be applied.
 *
 * \param[in]  source   Name of the source to use.
 * \param[in]  cur_rev  Last applied revision.
 * \param[in]  prev_rev Previous revision (for rollbacks.)
 * \param[out] size     Number of migrations in the list.
 * \returns array of pointers to strings representing an ordered
 *          list of migration filenames.
 */
char **source_find_migrations(const char *source, const char *cur_rev,
                              const char *prev_rev, size_t *size)
{
	size_t i;

	if (!source || !size)
		goto ret;

	i = find_backend(source, strlen(source));
	if (i == SIZE_MAX) goto ret;

	if (sources[i]->find_migrations) {
		return sources[i]->find_migrations(cur_rev, prev_rev,
		                                   size);
	}

ret:
	if (size) *size = 0;
	return NULL;
}

/**
 * Get the latest local revision.
 *
 * \param[in] source Name of the source to use.
 * \return The latest local revision as a string, or NULL if the
 *         local revision isn't known.
 */
const char *source_get_local_head(const char *source)
{
	size_t i;

	if (!source) goto err;

	i = find_backend(source, strlen(source));
	if (i != SIZE_MAX)
		return sources[i]->get_head();

err:
	return NULL;
}

/**
 * Get the latest revision of a particular file
 *
 * \param[in] source Name of the source to use.
 * \param[in] file   File name.
 * \return The lastest revision of the file as a string, or NULL if the
 *         revision isn't known.
 */
const char *source_get_file_revision(const char *source, const char *file)
{
	size_t i;

	if (!source || !file) goto err;

	i = find_backend(source, strlen(source));
	if (i != SIZE_MAX && sources[i]->get_file_revision)
		return sources[i]->get_file_revision(file);

err:
	return NULL;
}

/**
 * Get the base path for migrations.
 *
 * \param[in] source Name of the source to use.
 * \return The base path for migrations for the given source, or
 *         NULL if the source doesn't provide it.
 */
const char *source_get_migration_path(const char *source)
{
	size_t i;

	if (!source) goto err;

	i = find_backend(source, strlen(source));
	if (i != SIZE_MAX)
		return sources[i]->get_migration_path();

err:
	return NULL;
}

/**
 * Uninitialize the migration source layer.
 *
 * This must be called after you're done using the
 * \a source layer. This function calls clean-up handlers in
 * the underlying libraries.
 */
void source_uninit(void)
{
	size_t i;

	for (i = 0; i < N_SOURCE_BACKENDS; i++) {
		if (!sources[i] || !sources[i]->uninit)
			continue;

		if (sources[i]->uninit()) {
			error("failed to uninitialize '%s'",
			      sources[i]->name);
		}
	}
}

/**
 * Migration Source Repository
 *
 * Each source must have as 'extern' reference to its vtable here,
 * and an entry in the sources array.
 */
#ifndef IN_TESTS
extern const struct source_backend_vtable file_vtable;
#endif

#ifdef HAVE_GIT
extern const struct source_backend_vtable git_vtable;
#endif

static const struct source_backend_vtable *sources[N_SOURCE_BACKENDS] = {
#ifndef IN_TESTS
	&file_vtable,
#else
	NULL,
#endif

#ifdef HAVE_GIT
	&git_vtable,
#else
	NULL,
#endif
};


text:
package com.errpro.design_patterns.abstract_factory;

public class ConcreteFactory2 extends Factory2 {
	public ProductA getProductA2() {
		return new ProductA2();
	}
	public ProductB getProductB2() {
		return new ProductB2();
	}
}


text:
namespace Dealership.Engine
{
    public class UserNotLoggedCommandHandler
    {

    }
}


text:
package com.maxifier.cliche.guice;

import com.maxifier.cliche.Shell;
import com.maxifier.cliche.ShellFactory;

import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.google.inject.spi.InjectionListener;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;

import java.io.IOException;

/**
 * @author aleksey.didik@maxifier.com (Aleksey Didik)
 */
public class ConsoleShellModule extends AbstractModule {

    private final String promt;
    private final String appName;

    public ConsoleShellModule(String promt, String appName) {
        this.promt = promt;
        this.appName = appName;
    }

    @Override
    protected void configure() {
        final Shell shell;
        try {
            shell = ShellFactory.createConsoleShell(promt, appName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        bind(Shell.class).toInstance(shell);
        bindListener(AnnotatedClassMatcher.with(CommandHandler.class),
                new TypeListener() {
                    @Override
                    public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
                        encounter.register(new InjectionListener<I>() {
                            @Override
                            public void afterInjection(I injectee) {
                                shell.addMainHandler(injectee, "");
                            }
                        });
                    }
                }
        );
    }

}


text:
'use strict';

angular.module('myApp.pantry', ['ngRoute', 'core.pantry', 'core.profile'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/pantry', {
            templateUrl: 'pantry/pantry.html',
            controller: 'PantryCtrl'
        });
    }])

    .controller('PantryCtrl', ['$http', '$scope', 'pantry', 'profile', function ($http, $scope, pantry, profile) {
        $scope.items = pantry.get();
        $scope.maxCalories = profile.getMaxCalories();
        $scope.quantityEdit = [];

        /**
         * Load
         */
        $scope.load = function(){
            for(var i = 0; i < pantry.get().length; i++){
                $scope.quantityEdit.push(false); // Initialize an array to store the edit state of each item
            }
        };

        /**
         * Remove an item from the pantry
         *
         * @param item The item to be removed
         */
        $scope.remove = function(item){
            pantry.remove(item.item);
        };

        /**
         * Change the quantity of a given item from the pantry
         *
         * @param key The key of the item in the pantry
         */
        $scope.quantityChange = function(key){
            pantry.change($scope.items[key].item, $scope.items[key].quantity)
        };

        $scope.load();
    }]);


text:
local Helper = require('spec.helper.helper')
local Promise = require('promise')
local dummy = { dummy = 'dummy' }

describe("2.1.3.1: When rejected, a promise: must not transition to any other state.", function()
  Helper.test_rejected(it, dummy, function(promise, done)
    async()

    local fulfillment = spy.new(function() end)
    local rejection = spy.new(function() end)

    promise:next(fulfillment, rejection)

    Helper.timeout(0.2, function()
      assert.spy(rejection).was_called()
      assert.spy(fulfillment).was_not_called()
      done()
    end)
  end)

  it("trying to reject then immediately fulfill", function(done)
    async()

    local fulfillment = spy.new(function() end)
    local rejection = spy.new(function() end)

    local p = Promise.new()

    p:next(fulfillment, rejection)

    p:reject(dummy)
    p:resolve(dummy)

    Helper.timeout(0.1, function()
      assert.spy(rejection).was_called()
      assert.spy(fulfillment).was_not_called()
      done()
    end)
  end)

  it("trying to reject then fulfill, delayed", function(done)
    async()

    local fulfillment = spy.new(function() end)
    local rejection = spy.new(function() end)

    local p = Promise.new()

    p:next(fulfillment, rejection)

    Helper.timeout(0.05, function()
      p:reject(dummy)
      p:resolve(dummy)
    end)

    Helper.timeout(0.1, function()
      assert.spy(rejection).was_called()
      assert.spy(fulfillment).was_not_called()
      done()
    end)
  end)

  it("trying to reject immediately then fulfill delayed", function(done)
    async()

    local fulfillment = spy.new(function() end)
    local rejection = spy.new(function() end)

    local p = Promise.new()

    p:next(fulfillment, rejection)

    p:reject(dummy)

    Helper.timeout(0.05, function()
      p:resolve(dummy)
    end)

    Helper.timeout(0.1, function()
      assert.spy(rejection).was_called()
      assert.spy(fulfillment).was_not_called()
      done()
    end)
  end)
end)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Acta Mycol. Sin. 6(4): 233 (1987)

#### Original name
Rhizoplaca fumida X.Q. Gao

### Remarks
null


text:
package com.easypost.model;

import java.util.List;
import java.util.Map;

import com.easypost.exception.EasyPostException;
import com.easypost.utils.Utilities;

import lombok.Getter;

@Getter
public final class Shipment extends EasyPostResource {
    private String reference;
    private Boolean isReturn;
    private Address toAddress;
    private Address buyerAddress;
    private Address fromAddress;
    private Address returnAddress;
    private Parcel parcel;
    private CustomsInfo customsInfo;
    private Rate selectedRate;
    private List<Rate> rates;
    private PostageLabel postageLabel;
    private ScanForm scanForm;
    private String orderId;
    private List<Form> forms;
    private Tracker tracker;
    private String insurance;
    private String trackingCode;
    private String status;
    private String refundStatus;
    private String batchId;
    private String batchStatus;
    private String batchMessage;
    private String uspsZone;
    private Map<String, Object> options;
    private List<ShipmentMessage> messages;
    private List<TaxIdentifier> taxIdentifiers;
    private List<CarrierAccount> carrierAccounts;
    private String service;
    private List<Fee> fees;

    /**
     * Get the lowest rate for this Shipment.
     *
     * @return lowest Rate object
     * @throws EasyPostException when the request fails.
     */
    public Rate lowestRate() throws EasyPostException {
        return this.lowestRate(null, null);
    }

    /**
     * Get the lowest rate for this Shipment.
     *
     * @param carriers the carriers to use in the filter.
     * @param services the services to use in the filter.
     * @return lowest Rate object
     * @throws EasyPostException when the request fails.
     */
    public Rate lowestRate(final List<String> carriers, final List<String> services)
            throws EasyPostException {
        return Utilities.getLowestObjectRate(this.getRates(), carriers, services);
    }

    /**
     * Get the lowest rate for this shipment.
     *
     * @param carriers the carriers to use in the query.
     * @return Rate object
     * @throws EasyPostException when the request fails.
     */
    public Rate lowestRate(final List<String> carriers) throws EasyPostException {
        return this.lowestRate(carriers, null);
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 54: 185 (1995)

#### Original name
Corticium coprosmae G. Cunn., 1954

### Remarks
null


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using Internal.TypeSystem;

namespace ILCompiler
{
    // Contains functionality related to name mangling
    partial class CompilerTypeSystemContext
    {
        partial class BoxedValueType : IPrefixMangledType
        {
            TypeDesc IPrefixMangledType.BaseType
            {
                get
                {
                    return ValueTypeRepresented;
                }
            }

            string IPrefixMangledType.Prefix
            {
                get
                {
                    return "Boxed";
                }
            }
        }

        partial class GenericUnboxingThunk : IPrefixMangledMethod
        {
            MethodDesc IPrefixMangledMethod.BaseMethod
            {
                get
                {
                    return _targetMethod;
                }
            }

            string IPrefixMangledMethod.Prefix
            {
                get
                {
                    return "unbox";
                }
            }
        }

        partial class UnboxingThunk : IPrefixMangledMethod
        {
            MethodDesc IPrefixMangledMethod.BaseMethod
            {
                get
                {
                    return _targetMethod;
                }
            }

            string IPrefixMangledMethod.Prefix
            {
                get
                {
                    return "unbox";
                }
            }
        }
    }
}


text:
using System.Linq;
using Csla.TestHelpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Csla.Test.ValidationRules
{
  [TestClass]
  public class CascadeTests
  {
    private static TestDIContext _testDIContext;

    [ClassInitialize]
    public static void ClassInitialze(TestContext testContext)
    {
      _testDIContext = TestDIContextFactory.CreateDefaultContext();
    }

    [TestInitialize]
    public void Initialize()
    {
      TestResults.Reinitialise();
    }

    [TestMethod]
    public void BusinessRules_MustCascade_WhenCascadeOnDirtyPropertiesIsTrue()
    {
      IDataPortal<CascadeRoot> dataPortal = _testDIContext.CreateDataPortal<CascadeRoot>();

      var root = dataPortal.Create();
      root.CascadeOnDirtyProperties = true;
      Assert.AreEqual(0, root.Num1);
      Assert.AreEqual(0, root.Num2);
      Assert.AreEqual(0, root.Num3);
      Assert.AreEqual(0, root.Num4);
      root.Num1 = 1;
      Assert.AreEqual(1, root.Num1); // the value set by test
      Assert.AreEqual(2, root.Num2); // Num2 is set from Num1 rules
      Assert.AreEqual(3, root.Num3); // Num3 is set from Num2 rules
      Assert.AreEqual(4, root.Num4); // Num4 is set from Num3 rules when Cascade propagates down to Num3
    }

    [TestMethod]
    public void BusinessRules_MustNotCascade_WhenCanRunAsAffectedIsFalse()
    {
      IDataPortal<CascadeRoot> dataPortal = _testDIContext.CreateDataPortal<CascadeRoot>();

      var root = dataPortal.Create();
      root.CascadeOnDirtyProperties = true;
      Assert.AreEqual(0, root.Num1);
      Assert.AreEqual(0, root.Num2);
      Assert.AreEqual(0, root.Num3);
      Assert.AreEqual(0, root.Num4);
      Assert.AreEqual(0, root.Num5);
      root.Num1 = 1;
      Assert.AreEqual(1, root.Num1); // the value set by test
      Assert.AreEqual(2, root.Num2); // Num2 is set from Num1 rules
      Assert.AreEqual(3, root.Num3); // Num3 is set from Num2 rules
      Assert.AreEqual(4, root.Num4); // Num4 is set from Num3 rules when Cascade propagates down to Num3
      Assert.AreEqual(0, root.Num5); // Rule on Num4 is not allowed to run as AffectedProperty som Num5 must be unchanged.
    }

    [TestMethod]
    public void BusinessRules_MustNotCascade_WhenCascadeOnDirtyPropertiesIsFalse()
    {
      IDataPortal<CascadeRoot> dataPortal = _testDIContext.CreateDataPortal<CascadeRoot>();

      var root = dataPortal.Create();
      root.CascadeOnDirtyProperties = false;
      Assert.AreEqual(0, root.Num1);
      Assert.AreEqual(0, root.Num2);
      Assert.AreEqual(0, root.Num3);
      Assert.AreEqual(0, root.Num4);
      root.Num1 = 1;
      Assert.AreEqual(1, root.Num1); // the value set by test
      Assert.AreEqual(2, root.Num2); // rerun rules for Num2 without cascade
      Assert.AreEqual(3, root.Num3); // will set Num3 as output from Num2 but not rerun rules for Num3
      Assert.AreEqual(0, root.Num4); // Num4 is unchanged
    }

    [TestMethod]
    [TestCategory("SkipWhenLiveUnitTesting")]
    public void BusinessRules_MustCascadeAsSpreadsheet_WhenCascadeOnDirtyPropertiesIsTrue()
    {
      // complex ruleset
      // calculate the sum of Aa and Ab to Ac
      // copy value of Ac to Ae
      // calculate sum of Ad and Ae to Af
      // copy value of Af to Ag
      IDataPortal<CascadeRoot> dataPortal = _testDIContext.CreateDataPortal<CascadeRoot>();

      var root = dataPortal.Create();
      root.CascadeOnDirtyProperties = true;
      root.CheckRules();
      Assert.AreEqual(0, root.ValueAc);
      Assert.AreEqual(0, root.ValueAg);
      Assert.AreEqual(0, root.ValueAe);
      Assert.AreEqual(0, root.ValueAf);

      root.ValueAa = 10;
      Assert.AreEqual(10, root.ValueAc);
      Assert.AreEqual(10, root.ValueAg);
      Assert.AreEqual(10, root.ValueAe);
      Assert.AreEqual(10, root.ValueAf);

      root.ValueAb = 20;
      Assert.AreEqual(30, root.ValueAc);
      Assert.AreEqual(30, root.ValueAe);
      Assert.AreEqual(30, root.ValueAf);
      Assert.AreEqual(30, root.ValueAg);

      root.ValueAd = 25;
      Assert.AreEqual(55, root.ValueAf);
      Assert.AreEqual(55, root.ValueAg);
    }

    [TestMethod]

    public void BusinessRules_MustCheckBothSums_WhenCascadeOnDirtyPropertiesIsTrue()
    {
      // check that the sum of Ba and Bb is always 100 (and error message on both properties)
      IDataPortal<CascadeRoot> dataPortal = _testDIContext.CreateDataPortal<CascadeRoot>();

      var root = dataPortal.Create();
      root.CascadeOnDirtyProperties = true;
      root.CheckRules();
      Assert.AreEqual(0, root.ValueBa);
      Assert.AreEqual(0, root.ValueBb);
      Assert.IsTrue(root.BrokenRulesCollection.Any(p => p.Property == CascadeRoot.ValueBaProperty.Name));
      Assert.IsTrue(root.BrokenRulesCollection.Any(p => p.Property == CascadeRoot.ValueBbProperty.Name));

      root.ValueBa = 100;
      Assert.IsFalse(root.BrokenRulesCollection.Any(p => p.Property == CascadeRoot.ValueBaProperty.Name));
      Assert.IsFalse(root.BrokenRulesCollection.Any(p => p.Property == CascadeRoot.ValueBbProperty.Name));

      root.ValueBb = 50;
      Assert.IsTrue(root.BrokenRulesCollection.Any(p => p.Property == CascadeRoot.ValueBaProperty.Name));
      Assert.IsTrue(root.BrokenRulesCollection.Any(p => p.Property == CascadeRoot.ValueBbProperty.Name));

      root.ValueBa = 50;
      Assert.IsFalse(root.BrokenRulesCollection.Any(p => p.Property == CascadeRoot.ValueBaProperty.Name));
      Assert.IsFalse(root.BrokenRulesCollection.Any(p => p.Property == CascadeRoot.ValueBbProperty.Name));
    }

    [TestMethod]

    public void BusinessRules_MustRecalculateSumAfterCaclulateFraction_WhenCascadeOnDirtyPropertiesIsTrue()
    {
      // calculate sum of Ca, Cb, Cc and Cd to Ce
      // calculate fraction of Ce to Cd
      // must then recalculate sum again as Cd was changed.
      IDataPortal<CascadeRoot> dataPortal = _testDIContext.CreateDataPortal<CascadeRoot>();

      var root = dataPortal.Create();
      root.CascadeOnDirtyProperties = true;
      root.CheckRules();
      Assert.AreEqual(0, root.ValueCa);
      Assert.AreEqual(0, root.ValueCb);
      Assert.AreEqual(0, root.ValueCc);
      Assert.AreEqual(0, root.ValueCd);
      Assert.AreEqual(0, root.ValueCe);

      root.ValueCa = 5;
      Assert.AreEqual(5, root.ValueCa);
      Assert.AreEqual(0, root.ValueCb);
      Assert.AreEqual(0, root.ValueCc);
      Assert.AreEqual(1.67m, root.ValueCd);
      Assert.AreEqual(6.67m, root.ValueCe);

      root.ValueCb = 15;
      Assert.AreEqual(5, root.ValueCa);
      Assert.AreEqual(15, root.ValueCb);
      Assert.AreEqual(0, root.ValueCc);
      Assert.AreEqual(6.67m, root.ValueCd);
      Assert.AreEqual(26.67m, root.ValueCe);

      root.ValueCc = 25;
      Assert.AreEqual(5, root.ValueCa);
      Assert.AreEqual(15, root.ValueCb);
      Assert.AreEqual(25, root.ValueCc);
      Assert.AreEqual(15.00m, root.ValueCd);
      Assert.AreEqual(60.00m, root.ValueCe);
    }
  }
}


text:
package com.allogica.allogen.types;

import com.allogica.allogen.Compiler;
import com.allogica.allogen.CompilerContext;
import com.allogica.allogen.Scope;
import com.allogica.allogen.idl.model.IDLTypeName;
import com.allogica.allogen.model.TypeName;
import com.allogica.allogen.util.TypeUtils;

import java.util.List;
import java.util.stream.Collectors;

public class VectorType extends AbstractType {

    private TypeName containedType;
    private Scope scope;

    public VectorType(final TypeName typeName) {
        scope = typeName.getScope();
        containedType = typeName.getTemplateArguments().get(0).setScope(scope);
    }

    private TypeName handleTypeName(IDLTypeName typeName) {
        return new TypeName(typeName.getName(), typeName.getTemplateArguments().stream().map(this::handleTypeName).collect(Collectors.toList()), typeName.getNamespaces())
                .setIdlTypeName(typeName);
    }

    @Override
    public void link(Compiler<?, ?> compiler, CompilerContext compilerContext) {
        containedType.setResolvedType(compilerContext.resolve(containedType, scope));
        if (containedType.getResolvedType() == null) {
            throw new RuntimeException(String.format("Type '%s' not found in scope '%s'",
                    containedType, scope));
        }
        containedType.getResolvedType().link(compiler, compilerContext);
    }

    @Override
    public String getTemplateName() {
        return "vectorType";
    }

    @Override
    public List<Type> getDependantTypes() {
        return TypeUtils.getAllDependantTypes(containedType.getResolvedType());
    }

    public TypeName getContainedType() {
        return containedType;
    }

    public VectorType setContainedType(TypeName containedType) {
        this.containedType = containedType;
        return this;
    }

    public Scope getScope() {
        return scope;
    }

    public VectorType setScope(Scope scope) {
        this.scope = scope;
        return this;
    }
}


text:
using System.Linq;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

using Xunit;

namespace System.Net.Security.Tests
{
    public class SslStreamStreamToStreamTest
    {
        private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");

        [ActiveIssue(4467)]
        [Fact]
        public void SslStream_StreamToStream_Authentication_Success()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var client = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var server = new SslStream(serverStream))
            {
                X509Certificate2 certificate = TestConfiguration.GetServerCertificate();
                Task[] auth = new Task[2];
                auth[0] = client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));
                auth[1] = server.AuthenticateAsServerAsync(certificate);

                bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Handshake completed in the allotted time");
            }
        }

        [Fact]
        public void SslStream_StreamToStream_Authentication_IncorrectServerName_Fail()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var client = new SslStream(clientStream))
            using (var server = new SslStream(serverStream))
            {
                Task[] auth = new Task[2];
                auth[0] = client.AuthenticateAsClientAsync("incorrectServer");
                auth[1] = server.AuthenticateAsServerAsync(TestConfiguration.GetServerCertificate());

                Assert.Throws<AuthenticationException>(() =>
                {
                    auth[0].GetAwaiter().GetResult();
                });

                auth[1].GetAwaiter().GetResult();
            }
        }

        [Fact]
        public void SslStream_StreamToStream_Successive_ClientWrite_Sync_Success()
        {
            byte[] recvBuf = new byte[_sampleMsg.Length];
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                bool result = DoHandshake(clientSslStream, serverSslStream);

                Assert.True(result, "Handshake completed.");

                clientSslStream.Write(_sampleMsg);

                serverSslStream.Read(recvBuf, 0, _sampleMsg.Length);

                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");

                clientSslStream.Write(_sampleMsg);

                serverSslStream.Read(recvBuf, 0, _sampleMsg.Length);

                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
            }
        }

        [Fact]
        [ActiveIssue(5896, PlatformID.OSX)]
        public void SslStream_StreamToStream_LargeWrites_Sync_Success()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer:false))
            using (var serverStream = new VirtualNetworkStream(network, isServer:true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                Assert.True(DoHandshake(clientSslStream, serverSslStream), "Handshake complete");

                byte[] largeMsg = Enumerable.Range(0, 4096 * 5).Select(i => (byte)i).ToArray();
                byte[] receivedLargeMsg = new byte[largeMsg.Length];

                // First do a large write and read blocks at a time
                clientSslStream.Write(largeMsg);
                int bytesRead = 0, totalRead = 0;
                while (totalRead < largeMsg.Length &&
                    (bytesRead = serverSslStream.Read(receivedLargeMsg, totalRead, receivedLargeMsg.Length - totalRead)) != 0)
                {
                    totalRead += bytesRead;
                }
                Assert.Equal(receivedLargeMsg.Length, totalRead);
                Assert.Equal(largeMsg, receivedLargeMsg);

                // Then write again and read bytes at a time
                clientSslStream.Write(largeMsg);
                foreach (byte b in largeMsg)
                {
                    Assert.Equal(b, serverSslStream.ReadByte());
                }
            }
        }

        [Fact]
        public void SslStream_StreamToStream_Successive_ClientWrite_Async_Success()
        {
            byte[] recvBuf = new byte[_sampleMsg.Length];
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                bool result = DoHandshake(clientSslStream, serverSslStream);

                Assert.True(result, "Handshake completed.");

                Task[] tasks = new Task[2];

                tasks[0] = serverSslStream.ReadAsync(recvBuf, 0, _sampleMsg.Length);
                tasks[1] = clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
                bool finished = Task.WaitAll(tasks, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Send/receive completed in the allotted time");
                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");

                tasks[0] = serverSslStream.ReadAsync(recvBuf, 0, _sampleMsg.Length);
                tasks[1] = clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
                finished = Task.WaitAll(tasks, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Send/receive completed in the allotted time");
                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
            }
        }

        [Fact]
        public void SslStream_StreamToStream_Write_ReadByte_Success()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer:false))
            using (var serverStream = new VirtualNetworkStream(network, isServer:true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                bool result = DoHandshake(clientSslStream, serverSslStream);
                Assert.True(result, "Handshake completed.");

                for (int i = 0; i < 3; i++)
                {
                    clientSslStream.Write(_sampleMsg);
                    foreach (byte b in _sampleMsg)
                    {
                        Assert.Equal(b, serverSslStream.ReadByte());
                    }
                }
            }
        }

        private bool VerifyOutput(byte[] actualBuffer, byte[] expectedBuffer)
        {
            return expectedBuffer.SequenceEqual(actualBuffer);
        }

        private bool AllowAnyServerCertificate(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None;

            if (!Capability.IsTrustedRootCertificateInstalled())
            {
                expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors;
            }

            Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors);

            if (sslPolicyErrors == expectedSslPolicyErrors)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
        {
            X509Certificate2 certificate = TestConfiguration.GetServerCertificate();
            Task[] auth = new Task[2];

            auth[0] = clientSslStream.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));
            auth[1] = serverSslStream.AuthenticateAsServerAsync(certificate);

            bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
            return finished;
        }
    }
}


text:
#include "CFocus.h"

#include "../nodes/NodeReviews.h"
#include "../nodes/ReviewComment.h"

#include "ModelBase/src/model/TreeManager.h"
#include "ModelBase/src/model/AllTreeManagers.h"

#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/items/ViewItem.h"
#include "VisualizationBase/src/views/MainView.h"
#include "VisualizationBase/src/VisualizationManager.h"
#include "VisualizationBase/src/overlays/HighlightOverlay.h"

#include "../CodeReviewManager.h"

#include "../overlays/CodeReviewCommentOverlay.h"

using namespace Visualization;

namespace CodeReview {

CFocus::CFocus() : Command{"focus"} {}

QHash<int, CFocus::FocusInformation> CFocus::focusList_;

bool CFocus::canInterpret(Visualization::Item*, Visualization::Item*,
		const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& )
{
	if (commandTokens.size() > 0)
		return name() == commandTokens.first();
	return false;
}

Interaction::CommandResult* CFocus::execute(Visualization::Item*, Visualization::Item*,
				const QStringList&, const std::unique_ptr<Visualization::Cursor>&)
{

	Visualization::VisualizationManager::instance().mainScene()->removeOverlayGroup("focusOverlay");

	auto focusInformation = focusList_.value(currentStep_);

	if (focusInformation.type_ == FocusInformation::None){
		currentStep_ = 0;
		focusInformation = focusList_.value(currentStep_);
	}

	if (focusInformation.type_ == FocusInformation::None)
		return new Interaction::CommandResult{};

	auto focusItem = CodeReviewManager::instance().overlayForNodeReviews(focusInformation.node_);

	switch (focusInformation.type_) {
		case FocusInformation::Center:
			Visualization::VisualizationManager::instance().mainView()->
					centerOn(focusItem);
			break;
		case FocusInformation::Highlight:
		{
			auto overlay = new Visualization::HighlightOverlay{focusItem,
					Visualization::HighlightOverlay::itemStyles().get("focus")};
			focusItem->addOverlay(overlay, "focusOverlay");
			break;
		}
		default:
			Q_ASSERT(false);
			break;
	}

	currentStep_++;

	return new Interaction::CommandResult{};
}

QList<Interaction::CommandSuggestion*> CFocus::suggest(Visualization::Item*, Visualization::Item*,
		const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>&)
{
	if (name().startsWith(textSoFar))
		return {new Interaction::CommandSuggestion{name()}};
	return {};
}

CFocus::FocusInformation CFocus::extractFocusInformation(QString line)
{
	if (line.startsWith("[focus"))
	{
		auto endOfCommand = line.indexOf("]");
		// subtract one because of starting [
		auto commandSize = endOfCommand - 1;
		auto commandText = line.mid(1, commandSize);
		QStringList commandTokens = commandText.split("|");

		// remove first token which is "focus"
		commandTokens.pop_front();

		FocusInformation focusInformation;

		if (!commandTokens.isEmpty())
		{
			auto token = commandTokens.takeFirst();
			if (token.startsWith("hi"))
				focusInformation.type_ = FocusInformation::FocusType::Highlight;
			else if (token.startsWith("ce"))
				focusInformation.type_ = FocusInformation::FocusType::Center;
		}

		if (!commandTokens.isEmpty())
		{
			auto stepToken = commandTokens.takeFirst();
			focusInformation.step_ = stepToken.toInt();
		}
		return focusInformation;
	}

	return {};
}

void CFocus::loadFocusInformation()
{
	for (NodeReviews* nodeReviews : *CodeReviewManager::instance().nodeReviewsList())
	{
		if (nodeReviews->reviewComments()->isEmpty())
			continue;

		auto firstComment = nodeReviews->reviewComments()->first()->commentNode();

		if (firstComment->lines()->isEmpty())
			continue;

		auto firstLine = firstComment->lines()->first()->get();

		auto focusInformation = extractFocusInformation(firstLine);

		if (focusInformation.type_ != FocusInformation::None)
		{
			focusInformation.node_ = nodeReviews;
			focusList_.insert(focusInformation.step_, focusInformation);
		}
	}
}

}


text:
package com.google.tsunami.security.scanner.utilities;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.Parameters;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.util.Config;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/** Builds and starts a GRPC-based Tsunami Testbed server. */
public final class TsunamiTestbedServer {

  private static final int DEFAULT_PORT = 8000;

  @Parameters
  private static class TsunamiTestbedServerArgs {
    @Parameter(
        names = "--port",
        description = "The port on which the server listens.",
        validateWith = ValidPort.class)
    public int port = DEFAULT_PORT;

    @Parameter(
        names = {"--help", "-h"},
        description = "Print parameters and description.",
        help = true)
    public boolean help = false;
  }

  public static void main(String[] args) throws Exception {
    TsunamiTestbedServerArgs serverArgs = new TsunamiTestbedServerArgs();
    JCommander jCommander = JCommander.newBuilder().addObject(serverArgs).build();
    try {
      jCommander.parse(args);
      if (serverArgs.help) {
        jCommander.usage();
        return;
      }
    } catch (ParameterException e) {
      System.err.println("Invalid command line: " + e.getMessage());
      return;
    }

    int port = serverArgs.port;

    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);
    System.out.println("Initialized Kubernetes Api Client.");

    final TsunamiTestbedUtil util = new TsunamiTestbedUtil();
    final TsunamiTestbedServer server = new TsunamiTestbedServer();
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {
                try {
                  System.out.println("Shutting down");
                  server.stop();
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            });
    server.start(port, util);
    System.out.format("Testbed service listening on %d\n", port);
    server.blockUntilShutdown();
  }

  private Server server;

  private void start(int port, TsunamiTestbedUtil util) throws IOException {
    server =
        ServerBuilder.forPort(port).addService(new TsunamiTestbedService(util)).build().start();
  }

  private void stop() throws Exception {
    server.shutdownNow();
    if (!server.awaitTermination(5, TimeUnit.SECONDS)) {
      System.err.println("Timed out waiting for server shutdown");
    }
  }

  private void blockUntilShutdown() throws InterruptedException {
    if (server != null) {
      server.awaitTermination();
    }
  }
}


text:
package com.balram.applocker;

import android.app.Application;

import com.balram.locker.view.AppLocker;

/**
 * Created by Balram 12/11/16.
 */

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        AppLocker.getInstance().enableAppLock(this);
    }
}


text:
from social_core.backends.microsoft import MicrosoftOAuth2

class EduHelFiAzure(MicrosoftOAuth2):
    name = 'eduhelfi'
    domain_uuid = None
    AUTHORIZATION_URL = \
        'https://login.microsoftonline.com/edu.hel.fi/oauth2/v2.0/authorize'
    ACCESS_TOKEN_URL = \
        'https://login.microsoftonline.com/edu.hel.fi/oauth2/v2.0/token'

    def auth_params(self, *args, **kwargs):
        params = super().auth_params(*args, **kwargs)
        params['domain_hint'] = 'edu.hel.fi'
        params['prompt'] = 'login'
        return params


text:
let fs;
let readline;
let inquirer;

try {
  fs = require('fs');
  readline = require('readline');
  inquirer = require('inquirer');
} catch (e) {
  console.log(`🙁  Packages missing, run 'npm install' / 'yarn install' first`);
  process.exit(0);
}

// Require questions
const questions = require('./_config/questions');

// Require global config
const config = require('./_config/config');

// Require the setup tool
const tool = require('./setup');

let setups = [];

// Start application by checking which setups are available
fs.readdir('./_viewlayers', (err, files) => {
  files.forEach((file) => {
    if (!file.match(/^\s*?\..*$/)) {
      setups.push(file);
    };
  });

  setups.push(new inquirer.Separator(), config.questions.requestGitUrl);

  const finalQuestions = questions.getQuestions(setups);
  askQuestions(finalQuestions);
});

// Callback => handleAnswers
const askQuestions = (finalQuestions) => {
  inquirer.prompt(finalQuestions).then(handleAnswers);
};

const handleAnswers = (answers) => {
  tool.start(answers);
};


text:
import unittest
import numpy.random as random
import sys

sys.path.append("..")
from op_test_xpu import XPUOpTest
from xpu.get_test_cover_info import (
    create_test_class,
    get_xpu_op_support_types,
    XPUOpTestWrapper,
)
import paddle

paddle.enable_static()

class XPUTestIOUSimilarityOp(XPUOpTestWrapper):
    def __init__(self):
        self.op_name = 'iou_similarity'
        self.use_dynamic_create_class = False

    class TestXPUIOUSimilarityOp(XPUOpTest):
        def init(self):
            self.dtype = self.in_type
            self.place = paddle.XPUPlace(0)
            self.op_type = 'iou_similarity'

        def test_check_output(self):
            self.check_output_with_place(self.place)

        def setUp(self):
            self.init()
            self.boxes1 = random.rand(2, 4).astype(self.dtype)
            self.boxes2 = random.rand(3, 4).astype(self.dtype)
            self.output = random.rand(2, 3).astype(self.dtype)
            self.box_normalized = False
            # run python iou computation
            self._compute_iou()
            self.inputs = {'X': self.boxes1, 'Y': self.boxes2}
            self.attrs = {
                "box_normalized": self.box_normalized,
                'use_xpu': True,
            }
            self.outputs = {'Out': self.output}

        def _compute_iou(
            self,
        ):
            for row in range(self.boxes1.shape[0]):
                for col in range(self.boxes2.shape[0]):
                    xmin1, ymin1, xmax1, ymax1 = self.boxes1[row]
                    xmin2, ymin2, xmax2, ymax2 = self.boxes2[col]
                    if not self.box_normalized:
                        area1 = (ymax1 - ymin1 + 1) * (xmax1 - xmin1 + 1)
                        area2 = (ymax2 - ymin2 + 1) * (xmax2 - xmin2 + 1)
                    else:
                        area1 = (ymax1 - ymin1) * (xmax1 - xmin1)
                        area2 = (ymax2 - ymin2) * (xmax2 - xmin2)

                    inter_xmax = min(xmax1, xmax2)
                    inter_ymax = min(ymax1, ymax2)
                    inter_xmin = max(xmin1, xmin2)
                    inter_ymin = max(ymin1, ymin2)
                    inter_height = inter_ymax - inter_ymin
                    inter_width = inter_xmax - inter_xmin
                    if not self.box_normalized:
                        inter_height += 1
                        inter_width += 1
                    inter_height = max(inter_height, 0)
                    inter_width = max(inter_width, 0)
                    inter_area = inter_width * inter_height
                    union_area = area1 + area2 - inter_area
                    sim_score = inter_area / union_area
                    self.output[row, col] = sim_score

    class TestXPUIOUSimilarityOpWithLoD(TestXPUIOUSimilarityOp):
        def test_check_output(self):
            self.check_output_with_place(self.place, check_dygraph=False)

        def setUp(self):
            super().setUp()
            self.boxes1_lod = [[1, 1]]
            self.output_lod = [[1, 1]]
            self.box_normalized = False
            # run python iou computation
            self._compute_iou()
            self.inputs = {
                'X': (self.boxes1, self.boxes1_lod),
                'Y': self.boxes2,
            }
            self.attrs = {"box_normalized": self.box_normalized}
            self.outputs = {'Out': (self.output, self.output_lod)}

    class TestXPUIOUSimilarityOpWithBoxNormalized(TestXPUIOUSimilarityOp):
        def test_check_output(self):
            self.check_output_with_place(self.place, check_dygraph=False)

        def setUp(self):
            super().setUp()
            self.boxes1_lod = [[1, 1]]
            self.output_lod = [[1, 1]]
            self.box_normalized = True
            # run python iou computation
            self._compute_iou()
            self.inputs = {
                'X': (self.boxes1, self.boxes1_lod),
                'Y': self.boxes2,
            }
            self.attrs = {"box_normalized": self.box_normalized}
            self.outputs = {'Out': (self.output, self.output_lod)}

support_types = get_xpu_op_support_types('iou_similarity')
for stype in support_types:
    create_test_class(globals(), XPUTestIOUSimilarityOp, stype)

if __name__ == '__main__':
    unittest.main()


text:
var dns = require('native-dns'),
    net = require('net'),
    Log = require('modulelog')('srvclient'),
    cachedRecords = {},
    nextGarbageCollection = 0,
    currentCollectionTimeout = null,
    srvType = dns.consts.nameToQtype('SRV'),
    aType = dns.consts.nameToQtype('A'),
    aaaaType = dns.consts.nameToQtype('AAAA'),
    preprocessor = function(t) { return t; };
delete cachedRecords.a; //don't let V8 try to optimize

dns.setServers = function(list) {
    dns.platform.name_servers = list.map(function(item) {
        var parts = item.split(':');
        return { address: parts[0], port: ~~parts[1] || 53 };
    });
};
dns.getServers = function() {
    return dns.platform.name_servers.map(function(item) {
        return item.address + ':' + (item.port || '53');
    });
};

//todo: figure out how often to reload the servers

function scheduleGarbageCollection(time) {
    if (nextGarbageCollection === 0 || time < nextGarbageCollection) {
        if (currentCollectionTimeout !== null) {
            clearTimeout(currentCollectionTimeout);
        }
        nextGarbageCollection = time;
        currentCollectionTimeout = setTimeout(collectGarbage, time - Date.now());
        //don't let garbage collection prevent node from killing the app
        currentCollectionTimeout.unref();
    }
}

function collectGarbage() {
    //we can't reliably create a timeout in < 10 ms so just clean those now
    var now = Date.now() + 10,
        nextCollection = Infinity,
        name;
    for (name in cachedRecords) {
        if (!cachedRecords.hasOwnProperty(name)) {
            continue;
        }
        if (cachedRecords[name].expire <= now) {
            delete cachedRecords[name];
            continue;
        }
        nextCollection = Math.min(cachedRecords[name].expire, nextCollection);
    }
    nextGarbageCollection = 0;
    currentCollectionTimeout = null;
    if (isFinite(nextCollection)) {
        scheduleGarbageCollection(nextCollection);
    }
}

module.exports.setServers = function(servers) {
    dns.setServers(servers);
};

module.exports.getServers = function() {
    return dns.getServers();
};

module.exports.setPreprocessor = function(fn) {
    if (typeof fn !== 'function') {
        throw new TypeError('preprocessor must be a function');
    }
    preprocessor = fn;
};

//via: http://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers
//except we should allow infinity so there's no isFinite check
function isNumber(n) {
    return !isNaN(parseFloat(n));
}

/**
 * Lower priority means more preferred
 * Higher weight means more preferred
 *
 * First sort by priorities then sort by weights
 */
function compareTargets(a, b) {
    //if the one of them has a non-number priority then bail
    if (isNaN(a.priority) && !isNaN(b.priority)) {
        return 1;
    }
    if (isNaN(b.priority) || a.priority < b.priority) {
        //a is more preferred
        return -1;
    }
    if (b.priority < a.priority) {
        //b is more preferred
        return 1;
    }
    //at this point a.priority is equal to
    if (isNaN(a.weight)) {
        //if b.weight ALSO isn't a number then treat them equal
        return !isNaN(b.weight) ? 1 : 0;
    }
    if (isNaN(b.weight) || a.weight > b.weight) {
        //a is more preferred
        return -1;
    }
    if (b.weight > a.weight) {
        //b is more preferred
        return 1;
    }
    return 0;
}

function sortPriorityWeight(targets) {
    targets.sort(compareTargets);
}

function randomizeWeights(targets) {
    var totalWeights = 0,
        lastPriority = Infinity,
        i = 0,
        tmp = null;
    for (; i < targets.length; i++) {
        if (targets[i].priority !== lastPriority) {
            lastPriority = targets[i].priority;
            continue;
        }
        //todo: better handle weights that are not numbers
        if (isNaN(targets[i - 1].weight)) {
            //just flip the weight that is a number to before the non-number weight
            if (!isNaN(targets[i].weight)) {
                tmp = targets[i - 1];
                targets[i - 1] = targets[i];
                targets[i] = tmp;
            }
            continue;
        }
        //leave the previous numeric weight before the non-number
        if (isNaN(targets[i].weight)) {
            continue;
        }
        totalWeights = targets[i - 1].weight + targets[i].weight;
        //flip them randomly based on weight
        if ((Math.random() * totalWeights) > targets[i - 1].weight) {
            tmp = targets[i - 1];
            targets[i - 1] = targets[i];
            targets[i] = tmp;
        }
    }
}

function SRVTarget(result) {
    this.name = result.name || '';
    this.port = result.port || 0;
    this.priority = parseInt(result.priority, 10);
    this.weight = parseInt(result.weight, 10);
    this.address = result.address;
    this.addressFamily = net.isIP(this.address);
}
SRVTarget.prototype.clone = function() {
    return new SRVTarget({
        name: this.name,
        port: this.port,
        priority: this.priority,
        weight: this.weight,
        address: this.address
    });
};
SRVTarget.prototype.resolve = function(cb) {
    if (typeof cb !== 'function') {
        throw new TypeError('callback must be a function');
    }
    if (this.address !== '' && this.addressFamily === 4) {
        cb(null, this.address);
        return;
    }
    dns.resolve4(this.name, function(err, addresses) {
        if (err) {
            cb(err, null);
            return;
        }
        this.address = addresses[0];
        this.addressFamily = 4;
        cb(null, this.address);
    }.bind(this));
};
SRVTarget.prototype.resolve4 = SRVTarget.prototype.resolve;
SRVTarget.prototype.resolve6 = function(cb) {
    if (typeof cb !== 'function') {
        throw new TypeError('callback must be a function');
    }
    if (this.address !== '' && this.addressFamily === 6) {
        cb(null, this.address);
        return;
    }
    dns.resolve6(this.name, function(err, addresses) {
        if (err) {
            cb(err, null);
            return;
        }
        this.address = addresses[0];
        this.addressFamily = 6;
        cb(null, this.address);
    }.bind(this));
};
SRVTarget.prototype.lookup = function(cb) {
    if (typeof cb !== 'function') {
        throw new TypeError('callback must be a function');
    }
    if (this.address !== '') {
        cb(null, this.address);
        return;
    }
    dns.lookup(this.name, function(err, address) {
        if (err) {
            cb(err, null);
            return;
        }
        this.address = address;
        this.addressFamily = net.isIP(address);
        cb(null, address);
    }.bind(this));
};

function wrapTargets(targets) {
    for (var i = 0; i < targets.length; i++) {
        targets[i] = new SRVTarget(targets[i]);
    }
    return targets;
}

function _lookup(hostname, server, callback) {
    var kv = {hostname: hostname, address: server.address},
        question, req;
    question = dns.Question({
        name: hostname,
        type: 'SRV'
    });
    req = dns.Request({
        question: question,
        server: server,
        timeout: dns.platform.timeout || 5000
    });
    req.on('timeout', function() {
        Log.warn('timed out talking to dns server', kv);
        callback(new Error('timeout waiting for dns response'), null);
    });
    req.on('message', function(err, answer) {
        if (err) {
            callback(err, null);
            return;
        }
        if (answer.header.rcode !== 0) {
            kv.rcode = answer.header.rcode;
            Log.debug('got non-zero rcode for request', kv);
            callback(new Error('DNS server returned error for ' + hostname + ': ' + dns.consts.RCODE_TO_NAME[answer.header.rcode]));
            return;
        }
        if (!answer.answer || answer.answer.length === 0) {
            Log.debug('got no answers but no error', kv);
            callback(new Error('DNS server returned no answers for ' + hostname + 'but no error'));
            return;
        }
        var cache = {};
        if (answer.additional) {
            answer.additional.forEach(function(a) {
                if (a.type === aType || a.type === aaaaType) {
                    cache[a.name] = a.address;
                }
            });
        }
        callback(null, answer.answer.filter(function(a) {
            return a.type === srvType;
        }).map(function(a) {
            return {
                name: a.target,
                port: a.port,
                weight: a.weight,
                priority: a.priority,
                address: cache[a.target]
            };
        }));
    });
    req.send();
}

function lookup(hostname, callback) {
    var index = 0,
        servers;
    if (!dns.platform.ready) {
        dns.platform.once('ready', function() {
            setImmediate(function() {
                lookup(hostname, callback);
            });
        });
        return;
    }
    servers = dns.platform.name_servers.slice(0, 3);
    if (servers.length < 1) {
        callback(new Error('no dns servers to use'), null);
        return;
    }
    (function call() {
        Log.debug('looking up SRV record', {hostname: hostname, address: servers[index].address});
        _lookup(hostname, servers[index], function(err, res) {
            if (err) {
                if (servers[index]) {
                    setImmediate(call);
                    return;
                }
            }
            callback(err, res);
        });
        index++;
    }())
}

function getTargets(options) {
    var hostname = options.hostname,
        callback = options.callback,
        cache = options.cache || 0,
        onlyFirst = options.single || false,
        sort = options.sort || sortPriorityWeight,
        preprocess = options.preprocessor || preprocessor;
    if (typeof callback !== 'function') {
        if (typeof cache === 'function') {
            callback = cache;
            cache = 0;
        } else {
            throw new TypeError('callback must be a function');
        }
    }
    if (cache > 0) {
        if (!isNumber(cache)) {
            throw new TypeError('cache must be a number');
        }
        if (cachedRecords.hasOwnProperty(hostname) && cachedRecords[hostname].expire > Date.now()) {
            Log.debug('resolved SRV record from cache', {
                hostname: hostname
            });
            callback(null, (onlyFirst ? (cachedRecords[hostname].targets[0] || null) : cachedRecords[hostname].targets.slice()));
            return;
        }
    }
    lookup(hostname, function(err, targets) {
        if (err) {
            callback(err, null);
            return;
        }
        wrapTargets(targets);
        targets = preprocess(targets);
        if (!Array.isArray(targets)) {
            callback(new Error('preprocessor returned non-array'), null);
            return;
        }
        sort(targets);

        if (cache > 0 && targets.length) {
            cachedRecords[hostname] = {
                targets: targets,
                expire: Date.now() + cache
            };
            scheduleGarbageCollection(cachedRecords[hostname].expire);
            targets = targets.slice();
        }
        callback(null, (onlyFirst ? (targets[0] || null) : targets));
    });
}

function getRandomTargets(options) {
    var callback = options.callback,
        onlyFirst = options.single || false;
    if (typeof callback !== 'function') {
        throw new TypeError('callback must be a function');
    }
    options.callback = function(err, targets) {
        if (err) {
            callback(err, null);
            return;
        }
        randomizeWeights(targets);
        callback(null, (onlyFirst ? (targets[0] || null) : targets));
    };
    // we need to always get back all the targets for randomizeWeights to work
    options.single = false;
    //if you passed another sort it won't work...
    if (options.hasOwnProperty('sort')) {
        throw new TypeError('random methods do not support a custom sort function');
    }
    return getTargets(options);
}

exports.getTargets = function(hostname, cache, callback) {
    if (typeof cache === 'function') {
        callback = cache;
        cache = 0;
    }
    return getTargets({
        hostname: hostname,
        cache: cache,
        callback: callback,
        single: false
    });
};

exports.getTarget = function(hostname, cache, callback) {
    if (typeof cache === 'function') {
        callback = cache;
        cache = 0;
    }
    return getTargets({
        hostname: hostname,
        cache: cache,
        callback: callback,
        single: true
    });
};

exports.getRandomTargets = function(hostname, cache, callback) {
    if (typeof cache === 'function') {
        callback = cache;
        cache = 0;
    }
    return getRandomTargets({
        hostname: hostname,
        cache: cache,
        callback: callback,
        single: false
    });
};

exports.getRandomTarget = function(hostname, cache, callback) {
    if (typeof cache === 'function') {
        callback = cache;
        cache = 0;
    }
    return getRandomTargets({
        hostname: hostname,
        cache: cache,
        callback: callback,
        single: true
    });
};

//mostly only available for tests
exports.sortTargets = function(targets) {
    targets.sort(compareTargets);
    return targets;
};


text:
#include "config.h"
#include "core/svg/SVGMatrixTearOff.h"

#include "bindings/core/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/svg/SVGTransformTearOff.h"

namespace blink {

SVGMatrixTearOff::SVGMatrixTearOff(const AffineTransform& staticValue)
    : m_staticValue(staticValue)
    , m_contextTransform(0)
{
}

SVGMatrixTearOff::SVGMatrixTearOff(SVGTransformTearOff* transform)
    : m_contextTransform(transform)
{
    ASSERT(transform);
}

SVGMatrixTearOff::~SVGMatrixTearOff()
{
}

const AffineTransform& SVGMatrixTearOff::value() const
{
    return m_contextTransform ? m_contextTransform->target()->matrix() : m_staticValue;
}

AffineTransform* SVGMatrixTearOff::mutableValue()
{
    return m_contextTransform ? m_contextTransform->target()->mutableMatrix() : &m_staticValue;
}

void SVGMatrixTearOff::commitChange()
{
    if (!m_contextTransform)
        return;

    m_contextTransform->target()->onMatrixChange();
    m_contextTransform->commitChange();
}

#define DEFINE_SETTER(ATTRIBUTE) \
    void SVGMatrixTearOff::set##ATTRIBUTE(double f, ExceptionState& exceptionState) \
    { \
        if (m_contextTransform && m_contextTransform->isImmutable()) { \
            exceptionState.throwDOMException(NoModificationAllowedError, "The attribute is read-only."); \
            return; \
        } \
        mutableValue()->set##ATTRIBUTE(f); \
        commitChange(); \
    }

DEFINE_SETTER(A);
DEFINE_SETTER(B);
DEFINE_SETTER(C);
DEFINE_SETTER(D);
DEFINE_SETTER(E);
DEFINE_SETTER(F);

#undef DEFINE_SETTER

PassRefPtr<SVGMatrixTearOff> SVGMatrixTearOff::translate(double tx, double ty)
{
    RefPtr<SVGMatrixTearOff> matrix = create(value());
    matrix->mutableValue()->translate(tx, ty);
    return matrix.release();
}

PassRefPtr<SVGMatrixTearOff> SVGMatrixTearOff::scale(double s)
{
    RefPtr<SVGMatrixTearOff> matrix = create(value());
    matrix->mutableValue()->scale(s, s);
    return matrix.release();
}

PassRefPtr<SVGMatrixTearOff> SVGMatrixTearOff::scaleNonUniform(double sx, double sy)
{
    RefPtr<SVGMatrixTearOff> matrix = create(value());
    matrix->mutableValue()->scale(sx, sy);
    return matrix.release();
}

PassRefPtr<SVGMatrixTearOff> SVGMatrixTearOff::rotate(double d)
{
    RefPtr<SVGMatrixTearOff> matrix = create(value());
    matrix->mutableValue()->rotate(d);
    return matrix.release();
}

PassRefPtr<SVGMatrixTearOff> SVGMatrixTearOff::flipX()
{
    RefPtr<SVGMatrixTearOff> matrix = create(value());
    matrix->mutableValue()->flipX();
    return matrix.release();
}

PassRefPtr<SVGMatrixTearOff> SVGMatrixTearOff::flipY()
{
    RefPtr<SVGMatrixTearOff> matrix = create(value());
    matrix->mutableValue()->flipY();
    return matrix.release();
}

PassRefPtr<SVGMatrixTearOff> SVGMatrixTearOff::skewX(double angle)
{
    RefPtr<SVGMatrixTearOff> matrix = create(value());
    matrix->mutableValue()->skewX(angle);
    return matrix.release();
}

PassRefPtr<SVGMatrixTearOff> SVGMatrixTearOff::skewY(double angle)
{
    RefPtr<SVGMatrixTearOff> matrix = create(value());
    matrix->mutableValue()->skewY(angle);
    return matrix.release();
}

PassRefPtr<SVGMatrixTearOff> SVGMatrixTearOff::multiply(PassRefPtr<SVGMatrixTearOff> other)
{
    RefPtr<SVGMatrixTearOff> matrix = create(value());
    *matrix->mutableValue() *= other->value();
    return matrix.release();
}

PassRefPtr<SVGMatrixTearOff> SVGMatrixTearOff::inverse(ExceptionState& exceptionState)
{
    AffineTransform transform = value().inverse();
    if (!value().isInvertible())
        exceptionState.throwDOMException(InvalidStateError, "The matrix is not invertible.");

    return create(transform);
}

PassRefPtr<SVGMatrixTearOff> SVGMatrixTearOff::rotateFromVector(double x, double y, ExceptionState& exceptionState)
{
    if (!x || !y)
        exceptionState.throwDOMException(InvalidAccessError, "Arguments cannot be zero.");

    AffineTransform copy = value();
    copy.rotateFromVector(x, y);
    return create(copy);
}

}