text:
using System;

namespace HarshPoint.ShellployGenerator.Builders
{
    internal static class PropertyModelValidator
    {
        internal static void ValidateDoesNotContain<T>(
            PropertyModel existing,
            PropertyModel inserted
        )
        {
            if (inserted == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(inserted));
            }

            if (existing != null)
            {
                var existingElement = existing.FirstElementOfType<T>();
                if (existingElement != null)
                {
                    throw Logger.Fatal.InvalidOperationFormat(
                        SR.ParameterBuilder_AttemptedToNest,
                        inserted.GetType().Name,
                        existingElement.GetType().Name
                    );
                }
            }
        }

        private static readonly HarshLogger Logger
            = HarshLog.ForContext(typeof(PropertyModelValidator));
    }
}


text:
class CControlViewTestSceneBase : public BaseTestScene
{
public:
	virtual void onNextBtnClick(Ref* pSender);
	virtual void onBackBtnClick(Ref* pSender);
	virtual void onRefBtnClick(Ref* pSender);
};

//////////////////////////////////////////////////////

class CControlViewBasicTest : public CControlViewTestSceneBase
{
public:
	CREATE_FUNC(CControlViewBasicTest);
	virtual bool init();
	void onTouched(Ref* pSender, float fx, float fy);
	Sprite* m_pIcon;
};

//////////////////////////////////////////////////////

static int CControlView_test_idx;

static Scene* getCControlViewTestScene()
{
	switch(CControlView_test_idx)
	{
	case 0:
		return CControlViewBasicTest::create();
	default:
		CControlView_test_idx = 0;
		return CControlViewBasicTest::create();
	}
	return NULL;
}

static Scene* pushCControlViewTestScene()
{
	CControlView_test_idx = 0;
	Scene* pScene = getCControlViewTestScene();
	Director::getInstance()->pushScene(pScene);
	return pScene;
}

static void nextCControlViewTestScene()
{
	CControlView_test_idx++;
	Scene* pScene = getCControlViewTestScene();
	Director::getInstance()->replaceScene(pScene);
}

static void backCControlViewTestScene()
{
	CControlView_test_idx--;
	Scene* pScene = getCControlViewTestScene();
	Director::getInstance()->replaceScene(pScene);
}

static void refCControlViewTestScene()
{
	Scene* pScene = getCControlViewTestScene();
	Director::getInstance()->replaceScene(pScene);
}

#endif //__CControlViewTEST_H__

redpajama_set_name: RedPajamaGithub


text:
from netmiko import ConnectHandler
import os
import errno
import datetime
import time
from IPy import IP
from colorama import init, Fore, Back, Style
import sys
from Cmd import line
import getpass

timestamp = time.strftime(".%H%M%S")

__author__ = "John Ng"
__copyright__ = "Copyright 2018, John Ng"
__license__ = "MIT License"
__version__ = "v1.0 Beta"
__status__ = "Experimental"

init(strip=False)
print('\033[31m' + 'This is a Python script to generate pre-defined commands for Cisco IOS, IOS XE, CatOS devices,')
print('IPs will be pulled from excel file and saved in each individual text files according to IP Address & timestamp')
print('Please Note...Normal device config generation time and resources consumption still applies.')
print(Fore.CYAN + Style.BRIGHT + '[v1.0 Beta]')
init(wrap=False)
print('\033[30m')

cleanslate = sys.stdout

try:
    ipaddr = input('Please enter IP Address : ') # Manual IP Prompt
    #ipaddr = iprecs # Pull data through excel file from xcelip module
    IP(ipaddr)
except ValueError:
    print('Invalid Ip Detected')
    sys.exit(1)

username = input('Please enter username : ')
password = input('Please enter device password : ')
#password = getpass.getpass(prompt='Please enter device password : ')
secret = input('Please enter enable password : ')
#secret = getpass.getpass(prompt='Please enter enable password : ')
cisco_devices = {
    'device_type': 'cisco_ios',
    'ip': ipaddr,
    'username': username,
    'password': password,
    'secret': secret,
    'global_delay_factor': 2,
}
#if not os.path.exists("C:/sshoutput/"): # Test block for cuscomized target direcotory
    #os.mkdir("C:/sshoutput/")
#path = 'C:/sshoutput/'

fileout = open(ipaddr + str(timestamp) + ".txt", "a")
print('Generating.....')
sys.stdout = fileout
#net_connect2 = ConnectHandler(**cisco_devices)
net_connect = ConnectHandler(**cisco_devices)
#ios_commands = ['show clock', 'show version', 'show inventory raw', 'show env all',
 #   'show ip int bri', 'show log', 'show process cpu sorted',
  #              'show process cpu history', 'show memory', 'show memory sorted', 'show cdp nei', 'show ip route',
   #             'show switch']
ios_commands = line
net_connect.enable()
net_connect.send_command('term len 0')

for command in ios_commands:
    print('=============== ' + command + ' ===============' + '\n')
    output = net_connect.send_command_expect(command)
    print(output + '\n')
outrun = net_connect.send_command('show run')
print('=============== ' + 'show run' + ' ===============' + '\n' + outrun)

net_connect.disconnect()
sys.stdout = cleanslate
fileout.close()

print('Pelaksanaan Perintah Selesai')
print('\n')
try:
    input("Press Enter to Continue..")
except SyntaxError:
    pass

"""
output = net_connect.send_command('show ip int brief')
print(output, file=open(ipaddr + str(timestamp) + ".txt", "a"))
print(output)
sys.stdout = orig_outp
f.close()
"""


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#ifdef IRIX
#endif

#ifdef LINUX
#endif

#ifdef BSD
#endif

#ifdef READLINE
#include <readline/readline.h>
#endif

#define LINE_BUFF_SIZE 1024

#include "mpsh.h"
#include "state.h"

/*
struct word_list *global_env;
*/

int control_term;

main(argc,argv,env)
int argc;
char *argv[];
char *env[];
{
	char *line;
	char *pr;
	int len;

#ifndef READLINE
	line = (char *) malloc(LINE_BUFF_SIZE+1);
#endif

	init_all(argc,argv,env);

	setpgid(getpid(),getpid());
	signal(SIGTTOU,SIG_IGN);
	set_terminal(0);

#ifdef READLINE
	for(;;) {
		parse_depth = 0;
		pr = get_prompt();
		if(line = readline(pr)) {
			parse_and_run(line,INTERACTIVE);
		} else {
			/* EOF */
			if(number_of_jobs() > 0 ) {
				puts("");
				show_jobs(NULL,-1);
			} else {
				puts("");
				if(true_or_false(get_env("mpsh-eof-exit")))
					exit(0);
			}
		}
		free(pr);
		free(line);
	}

#else
	for(;;) {
		parse_depth = 0;
		pr = get_prompt();
		printf("%s",pr);
		free(pr);
		if(fgets(line,LINE_BUFF_SIZE,stdin)) {
			len = strlen(line);
			if(line > 0 && line[len-1] == '\n')
				line[len-1] = '\0';
			parse_and_run(line,INTERACTIVE);
		} else {
			/* EOF */
			if(number_of_jobs() > 0 ) {
				puts("");
				clearerr(stdin);
				show_jobs(NULL,-1);
			} else {
				puts("");
				if(true_or_false(get_env("mpsh-eof-exit")))
					exit(0);
			}
		}
	}
#endif

}

parse_and_run(text_command,interactive)
char *text_command;
int interactive;
{
	char *pt;
	struct command *command;
	struct command *initial_command;
	int ret;

	ret = 0;

	if(parse_depth++ > MAX_PARSE_DEPTH) {
		report_error("Excessive parse depth",NULL,0,0);
		return(-1);
	}

	/* Init parse tree structs */
	command = initial_command = init_command();
	command->text = (char *) malloc(BUFF_SIZE);
	command->text[0] = '\0';
	command->state = STATE_SPACE;

	pt = expand_macros(text_command);

	while(command->state != STATE_DONE) {
		if(*pt) {
			add_command_text_letter(initial_command,*pt);
			command = parse_char(command,*pt);
			if(!command) return(1);
			pt++;
		} else {
			command = parse_char(command,'\n');
			if(!command) return(1);
		}
	}

	if(initial_command->words != NULL) {
		/* MORE PARSING */
		shift_set_operators(initial_command);
		if(!expand_env(initial_command)) goto skip;
		expand_globbing(initial_command);
		expand_job_num(initial_command);

		/* This goes in the last command struct in the pipeline,
		   rather than the first, because of the job entry mechanism.
		*/
		command->expansion = get_command_expansion(initial_command);

		if(!expand_mp(initial_command)) goto skip;

		/* DEBUG */
		/*
		display_command(initial_command);
		*/

		if((command->flags & FLAG_DISPLAY_TEXT) && interactive)
			puts(initial_command->text);

		/* Save this info for history, before exec command */
		command->dir = dup_cwd();

		/* EXECUTE COMMAND */
		ret = exec_command(initial_command);
	}

	check_for_job_exit();

	skip:

	free_command(initial_command);

	return(ret);
}


text:
<?php

namespace App\Http\Controllers\Web;

use App\Auth\Registrar;
use App\Http\Controllers\Controller;
use App\Types\CauseInterestType;
use Illuminate\Http\Request;

class ProfileAboutController extends Controller
{
    /**
     * Add Authentication Middleware.
     */
    public function __construct(Registrar $registrar)
    {
        $this->registrar = $registrar;

        $this->middleware('auth:web');

        $this->causes = CauseInterestType::labels();
    }

    /**
     * Display the User Details Form.
     */
    public function edit()
    {
        return view('profiles.about.edit', [
            'user' => auth()
                ->guard('web')
                ->user(),
            'causes1' => array_slice(
                $this->causes,
                0,
                count($this->causes) / 2,
            ),
            'causes2' => array_slice($this->causes, count($this->causes) / 2),
            'index1' => 0,
            'index2' => 6,
        ]);
    }

    /**
     * Handle Submissions of the User Details Form.
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request)
    {
        $user = auth()
            ->guard('web')
            ->user();

        $this->registrar->validate($request, null, [
            'birthdate' => 'nullable|date|before:now',
            'email' => 'email|nullable|unique:mongodb.users',
            'mobile' => 'mobile|nullable|unique:mongodb.users',
        ]);

        $completedFields = array_filter($request->all());

        $user->fill($completedFields);

        $user->save();

        return redirect(url('profile/subscriptions'));
    }
}


text:
using System;
using System.Collections.Generic;
using KnockoutApi;
using Xrm.Sdk;
using System.Collections;
using SparkleXrm;
using System.Runtime.CompilerServices;

namespace TimeSheet.Client.ViewModel
{
    public class SessionVM
    {
        private bool _supressEvents = false;

        public Observable<Guid> dev1_sessionid = Knockout.Observable<Guid>();
        public Observable<EntityReference> Activity = Knockout.Observable<EntityReference>();

        public Observable<DateTime> dev1_starttime = Knockout.Observable<DateTime>();
        public Observable<DateTime> dev1_endtime = Knockout.Observable<DateTime>();
        public Observable<string> dev1_description = Knockout.Observable<string>();
        public Observable<int?> dev1_duration = Knockout.Observable<int?>();
        public Observable<string> StartTimeTime = Knockout.Observable<string>();
        public Observable<string> EndTimeTime = Knockout.Observable<string>();
        public Observable<string> TimeSoFar = Knockout.Observable<string>();

        public Observable<string> test = Knockout.Observable<string>("test");

        public SessionVM(StartStopSessionViewModel vm, dev1_session data)
        {
            if (data != null)
            {

                this.dev1_sessionid.SetValue(data.dev1_sessionId);
                this.dev1_description.SetValue(data.dev1_Description);
                this.dev1_duration.SetValue(data.dev1_Duration);
                this.dev1_endtime.SetValue(data.dev1_EndTime);
                this.dev1_starttime.SetValue(data.dev1_StartTime);
                // Calculate the time elements
                GetTime(dev1_starttime, StartTimeTime);
                GetTime(dev1_endtime, EndTimeTime);

                // Set activity
                if (data.dev1_LetterId != null)
                {

                    this.Activity.SetValue(data.dev1_LetterId);
                }
                else if (data.dev1_TaskId != null)
                {
                    this.Activity.SetValue(data.dev1_TaskId);

                }
                 // TODO: Add more activity types
            }

            // Add events to calculate duration
            dev1_endtime.Subscribe(delegate(DateTime value) { OnStartEndDateChanged(); });

            dev1_starttime.Subscribe(delegate(DateTime value) { OnStartEndDateChanged(); });

            StartTimeTime.Subscribe(delegate(string value) { OnStartEndDateChanged(); });
            EndTimeTime.Subscribe(delegate(string value) { OnStartEndDateChanged(); });
            dev1_duration.Subscribe(delegate(int? value) { OnDurationChanged(); });
            AddValidation();
        }
        public void OnStartEndDateChanged()
        {
            if (_supressEvents) return;
            _supressEvents = true;

            DateTime startTime = dev1_starttime.GetValue();
            DateTime endTime = dev1_endtime.GetValue();
            int? duration = null;
            startTime = DateTimeEx.AddTimeToDate(startTime, StartTimeTime.GetValue());
            endTime = DateTimeEx.AddTimeToDate(endTime, EndTimeTime.GetValue());

            if (endTime != null && startTime != null)
            {
                endTime.SetDate(startTime.GetDate());
                endTime.SetMonth(startTime.GetMonth());
                endTime.SetFullYear(startTime.GetFullYear());
            }
            duration= CalculateDuration(startTime, endTime);
            this.dev1_duration.SetValue(duration);
            _supressEvents = false;
        }

        public static int? CalculateDuration( DateTime startTime,  DateTime endTime)
        {
            int? duration = null;
            if ((startTime != null) && (endTime != null))
            {

                if ((startTime != null) && (endTime != null))
                {
                    duration = (endTime.GetTime() - startTime.GetTime()) / (1000 * 60);
                }
            }
            return duration;
        }
        public void OnDurationChanged()
        {
             if (_supressEvents) return;
            _supressEvents = true;

            DateTime startTime = dev1_starttime.GetValue();
            string startTimeTime = StartTimeTime.GetValue();
            if ((startTime != null) && (startTimeTime!=null))
            {
                startTime = DateTimeEx.AddTimeToDate(startTime, startTimeTime);
                int? duration = dev1_duration.GetValue();
                int? startTimeMilliSeconds = startTime.GetTime();
                startTimeMilliSeconds = startTimeMilliSeconds + (duration * 1000 * 60);

                DateTime newEndDate = new DateTime((int)startTimeMilliSeconds);
                dev1_endtime.SetValue(newEndDate);
                GetTime(dev1_endtime, EndTimeTime);
            }
            _supressEvents = false;
        }
        public dev1_session GetUpdatedModel()
        {

            dev1_session session = new dev1_session();

            SetTime(dev1_starttime, StartTimeTime);
            SetTime(dev1_endtime, EndTimeTime);

            KnockoutMappingSpecification mapping = new KnockoutMappingSpecification();
            mapping.Ignore = new string[] { "dev1_letterid", "dev1_taskid", "dev1_emailid" };

            if ( this.dev1_sessionid.GetValue()!=null)
                session.dev1_sessionId = this.dev1_sessionid.GetValue();
            session.dev1_Description = this.dev1_description.GetValue();
            session.dev1_StartTime = this.dev1_starttime.GetValue();
            session.dev1_EndTime = this.dev1_endtime.GetValue();
            session.dev1_Duration = this.dev1_duration.GetValue();

            return session;
        }

        private void GetTime(Observable<DateTime> dateProperty,Observable<string> time)
        {
            DateTime dateValue = dateProperty.GetValue();
            if (dateValue != null)
            {
                string timeFormatted = dateValue.Format("h:mm tt");
                time.SetValue(timeFormatted);
            }
        }

        private void SetTime(Observable<DateTime> dateProperty, Observable<string> time)
        {

            DateTime currentDate = dateProperty.GetValue();
            currentDate = DateTimeEx.AddTimeToDate(currentDate, time.GetValue());

            dateProperty.SetValue(currentDate);
        }

        #region Methods
        public void AddValidation()
        {
            SessionVM self = this;

            ValidationRules.CreateRules()
                   .AddRequiredMsg("Enter the activity you wish to stop")
                   .Register(Activity);

            ValidationRules.CreateRules()
                    .AddRequiredMsg("Enter the start date of the session")
                    .AddRule("Start date must be before the end date",delegate(object value) {

                        bool isValid = true;
                        DateTime endTime = self.dev1_endtime.GetValue();
                        if ((endTime != null) && (value!=null))
                            isValid = endTime > (DateTime)value;

                        return isValid;
                    })
                    .Register(dev1_starttime);

            ValidationRules.CreateRules()
                    .AddRequiredMsg("Enter the end time of the session")
                    .Register(dev1_endtime);

            ValidationRules.CreateRules()
                    .AddRequiredMsg("Enter the duration of the session")
                    .Register(dev1_duration);

        }
        #endregion
    }
}


text:
namespace AMDTGpuProfiler
{
gpAbstractTraceDataAccessInterface::gpAbstractTraceDataAccessInterface()
{
}

gpTreeHandler::~gpTreeHandler()
{

}
}


text:
using Microsoft.AspNetCore.Mvc;
using Toucan.Controllers;
using Toucan.Sample.Models;

namespace Toucan.Sample.Controllers
{
    [LoadAndAuthorizeResourceAttribute(typeof(ApplicationUser))]
    public class UsersController : ToucanController
    {
        public IActionResult Details()
        {
            return View(this.GetModelInstance<ApplicationUser>());
        }
    }
}


text:
layout: post

#event information
title:  "Prospects for Life Around Nearby Stars"
cover: "/images/PlanetaSH.jpg"
attribution:
  name: "Artist's impression of a superhabitable planet"
  author: "Ph03nix1986"
  license: "CC BY-SA 4.0"
  name_url: "https://commons.wikimedia.org/wiki/File:PlanetaSH(3).jpg"
  license_url: "https://creativecommons.org/licenses/by-sa/4.0/deed.en"
date:   "2016-10-07 20:00"
endDate:   "2016-10-07 22:30"
creation: "2016-09-27"
start_time: "8:00 PM"
end_time: "10:30 PM"
location:
  name: "Philosophical Society of Washington"
  address:
    - "John Wesley Powell Auditorium"
    - "2170 Florida Avenue NW"
  city: Washington
  state: DC
  zip: 20008
tags: [ 'Philosophical Society of Washington', 'Lectures', 'Astronomy and Aeronautics' ]
excerpt: >
  On October 7 Carey M. Lisse will talk about the current "big picture" for the
  formation and evolution of life on Earth, with special attention to its
  astronomical, geological, and chemical requirements.

---

The [Philosophical Society of Washington](http://www.philsoc.org/)
Lectures are selected to
appeal to those with a general interest in science and do not require
a specialized knowledge of the subject. They always contain
information that is current, explanations that are understandable
and a few controversial issues to be challenged by a critical
listener. The series is designed as much as possible to include a
wide range of disciplines.

The meetings are open to the public, free, and no reservations are
required. Dress is informal. Meetings are followed by lively
conversation. All must exit the Cosmos Club at 10:30 p.m.
Conversations are continued at another location.

This talk will present the current "big picture" for the formation and evolution
of life on Earth, with special attention to its astronomical, geological, and
chemical requirements.  Astronomically, there are 1011 stars in our galaxy, each
according to the latest Kepler results likely to have formed its own Earth-sized
planet.  The Universe is 13.8 billion years (Gyr) old, the Galaxy is about 12
Gyr old, our Sun is ~4.6 Gyr old, and high-Z chemical elements took a few
generations of stars to form.  Sol and our solar system are ~2/3 of the way out
from our spiral galaxy's relatively weak central black hole, in the suburbs so
to speak. The Earth itself is a 4.56 Gyr old, highly differentiated, very unique
object with all its water on the surface, a giant moon stabilizing its spin,
plate tectonics keeping it warm and a shielding magnetic field. Life is found on
the Earth in an incredibly narrow spatial range, -20 to +100 km from the surface
of a body of diameter ~104 km, and is found only where liquid water is
available- we live, work, & die on the thinnest wet rind of the terrestrial
orange. Failed planet harbors for life exist next-door in Venus and Mars.

Historically, the first forms of life appear to have formed in high temperature
environments.  Earth-life was mainly blue-green and single-celled for the first
3.5 Gyr of the planet's existence.  By ~2 Gyr, in the first massive life-based
pollution event in the planet's timeline, phototrophic plant life had driven the
atmosphere out of equilibrium, removing almost all CO2 and converting it in the
O2 without which it is likely there would be few animals and no land dwelling
creatures.  Complex multi-cellular life only arrived after ~3.5 Gyr.  Since
then, multi-cellular life has gone through at least 4 huge upheavals due to
giant impacts.  But for these bug-eyed monsters, trilobites, or giant lizards
would be ruling the Earth.  Creatures even remotely resembling Homo Sapiens have
been on the Earth for only ~4 million years (Myr) out of 4.56 Gyr, an ~10-3 duty
cycle.  Even today bacteria are the most successful forms of life reckoned by
total biomass, and we each carry some of this biomass on our skin, in our gut,
and in our mitochondria.

Carey M. Lisse is Senior Research Scientist in the Applied Physics Laboratory
at Johns Hopkins University.  Prior to assuming his current position he held a
variety of posts at APL and NASA.

Carey has been active in the fields of astronomy and physics since 1985, where
he began as an instrument scientist at NASA/Goddard on the Nobel prize winning
COBE project.  He later moved over to planetary studies, writing his
dissertation on comets detected in the COBE all sky survey.  Since then he has
focused primarily on comets, making important discoveries about their X-ray
emissions and working on the NASA Deep Impact mission from start to finish
including using the Spitzer Space Telescope to observe dust excavated from the
comet 9P/Tempel 1 by the DI Impactor.  He also studies asteroids and x-ray
emission from planets, and searches for the presence of asteroids and comets
around other starts.  Casey is the Chair of the Comet ISON Observing Campaign
Team, overseeing the team's activities.

Carey received a number of awards as part of the COBE team, the JPL Stardust
flight team, and the EPOXI flight team.  He is the recipient of a Space
Telescope Science Institute Science Merit Award, a  Space Foundation Space
Achievement Award, a Johns Hopkins Applied Physics Laboratory Special
Achievement Award, and he was awarded the Isaac Newton Institute Visiting
Fellowship at Cambridge University.  Carey is a AAAS Fellow.  And the Asteroid
12226 Caseylisse is named for him.

The John Wesley Powell Auditorium is adjacent to the Cosmos Club, 2170 Florida
Avenue NW, Washington DC 20008. Entrance is through the club gate, the first
right-hand entrance on Florida Avenue north of the intersection with
Massachusetts Avenue NW. The auditorium entrance is to the left of the gate.


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:background="@color/ghostwhite"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/title_rout"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="@color/teal"
        android:orientation="horizontal">

        <RelativeLayout
            android:id="@+id/home_detail_back_rout"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_centerVertical="true"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/title_imv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:src="@drawable/ic_navigate_before_white_24dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="30dp"
                android:text="返 回"
                android:textColor="@color/white"
                android:textSize="16sp"/>
        </RelativeLayout>

        <!--<ImageView-->
        <!--android:id="@+id/home_detail_title_right_imv"-->
        <!--android:layout_width="30dp"-->
        <!--android:layout_height="30dp"-->
        <!--android:layout_alignParentRight="true"-->
        <!--android:layout_centerVertical="true"-->
        <!--android:layout_marginRight="16dp"-->
        <!--android:src="@drawable/fav_normal"/>-->

    </RelativeLayout>

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/ghostwhite"/>
</LinearLayout>


text:
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace System.Linq
{
	public class EnumerableQuery<T> : EnumerableQuery, IOrderedQueryable<T>, IQueryable<T>, IQueryProvider
	{
		readonly QueryableEnumerable<T> queryable;

		Type IQueryable.ElementType {
			get { return queryable.ElementType; }
		}

		Expression IQueryable.Expression {
			get { return queryable.Expression; }
		}

		IQueryProvider IQueryable.Provider {
			get { return queryable; }
		}

		public EnumerableQuery (Expression expression)
		{
			queryable = new QueryableEnumerable<T> (expression);
		}

		public EnumerableQuery (IEnumerable<T> enumerable)
		{
			queryable = new QueryableEnumerable<T> (enumerable);
		}

		IEnumerator IEnumerable.GetEnumerator ()
		{
			return queryable.GetEnumerator ();
		}

		IEnumerator<T> IEnumerable<T>.GetEnumerator ()
		{
			return queryable.GetEnumerator ();
		}

		IQueryable IQueryProvider.CreateQuery (Expression expression)
		{
			return queryable.CreateQuery (expression);
		}

		object IQueryProvider.Execute (Expression expression)
		{
			return queryable.Execute (expression);
		}

		IQueryable<TElem> IQueryProvider.CreateQuery<TElem> (Expression expression)
		{
			return new EnumerableQuery<TElem> (expression);
		}

		TResult IQueryProvider.Execute<TResult> (Expression expression)
		{
			return queryable.Execute<TResult> (expression);
		}

		public override string ToString ()
		{
			return queryable.ToString ();
		}
	}
}

#endif


text:
package com.evolveum.midpoint.util.aspect;

import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.util.statistics.OperationExecutionLogger;

import java.util.*;

/**
 *  IMPORTANT NOTES:
 *  1. Default dump interval is set to 30 minutes
 *
 *  This is a Singleton Class
 *
 *  ProfilingDataManager serves as a head of profiling data manipulation, configuration and dumping to log.
 *  Some of processes in this class are synchronized for obvious reasons.
 *
 *  @author shood
 * */
public final class ProfilingDataManager {

    /*
    *   private instance of ProfilingDataManager
    * */
    private static ProfilingDataManager profilingDataManager = null;

    private static final int DEFAULT_DUMP_INTERVAL = 30;
    private static final int DEFAULT_PERF_DUMP_INTERVAL = 10;
    private static byte topTenMethodNumber = 5;

    private static boolean profilingTest = false;

    public enum Subsystem {
        REPOSITORY,
        TASK_MANAGER,
        PROVISIONING,
        SYNCHRONIZATION_SERVICE,
        MODEL,
        UCF,
        WORKFLOW,
        WEB
    }

    public static final List<Subsystem> SUBSYSTEMS = Arrays.asList(Subsystem.values());

    public static final String INDENT_STRING = " ";
    private static final String ARGS_NULL = "NULL";
    private static final String ARGS_EMPTY = "NO ARGS";

    private static boolean isRepositoryProfiled = false;
    private static boolean isTaskManagerProfiled = false;
    private static boolean isProvisioningProfiled = false;
    private static boolean isSynchronizationServiceProfiled = false;
    private static boolean isModelProfiled = false;
    private static boolean isUcfProfiled = false;
    private static boolean isWorkflowProfiled = false;
    private static boolean isWebProfiled = false;

    private static final ArrayComparator ARRAY_COMPARATOR = new ArrayComparator();

    private static final Trace LOGGER = TraceManager.getTrace(ProfilingDataManager.class);

    private long lastDumpTimestamp;
    private long lastPerformanceDumpTimestamp;
    private int minuteDumpInterval = DEFAULT_DUMP_INTERVAL;

    private boolean isPerformanceProfiled = false;

    private Map<String, MethodUsageStatistics> performanceMap = new HashMap<>();

    private static final String PRINT_RIGHT_ARROW = "->";

    public static ProfilingDataManager getInstance() {

        if(profilingDataManager == null){
            profilingDataManager = new ProfilingDataManager(DEFAULT_DUMP_INTERVAL, false);
        }

        return profilingDataManager;
    }

    private ProfilingDataManager(int dumpInterval, boolean performance) {
        this.isPerformanceProfiled = performance;
        this.minuteDumpInterval = dumpInterval;
        lastDumpTimestamp = System.currentTimeMillis();
        lastPerformanceDumpTimestamp = System.currentTimeMillis();
    }

    public void configureProfilingDataManager(Map<Subsystem, Boolean> profiledSubsystems, Integer dumpInterval,
                                              boolean subsystemProfilingActive, boolean performance, boolean request){

        isPerformanceProfiled = performance;

        if(subsystemProfilingActive || isPerformanceProfiled || request){
            OperationExecutionLogger.activateSubsystemProfiling();
        }else {
            OperationExecutionLogger.deactivateSubsystemProfiling();
        }

        subsystemConfiguration(profiledSubsystems);

        //Configure the dump interval
        if(dumpInterval != null && dumpInterval > 0){
            minuteDumpInterval = dumpInterval;
        }

        profilingTest = false;
        profilingDataManager = new ProfilingDataManager(minuteDumpInterval, performance);
    }

    public void configureProfilingDataManagerForTest(Map<Subsystem, Boolean> subsystems, boolean performance){
        subsystemConfiguration(subsystems);

        topTenMethodNumber = 10;
        profilingDataManager = new ProfilingDataManager(30, performance);
        profilingTest = true;
    }

    public void applyGranularityFilterOnEnd(String className, String methodName, Object[] args, Subsystem subsystem, long startTime, long processingStartTime){

        ProfilingDataLog profilingEvent;
        profilingEvent = prepareProfilingDataLog(className, methodName, startTime, args);
        String key = prepareKey(profilingEvent);

        if(isRepositoryProfiled && Subsystem.REPOSITORY.equals(subsystem)){
            updateOverallStatistics(performanceMap, profilingEvent, key,  Subsystem.REPOSITORY);

        } else if(isModelProfiled && Subsystem.MODEL.equals(subsystem)){
            updateOverallStatistics(performanceMap, profilingEvent, key, Subsystem.MODEL);

        } else if (isProvisioningProfiled && Subsystem.PROVISIONING.equals(subsystem)){
            updateOverallStatistics(performanceMap, profilingEvent, key, Subsystem.PROVISIONING);

        } else if (isTaskManagerProfiled && Subsystem.TASK_MANAGER.equals(subsystem)){
            updateOverallStatistics(performanceMap, profilingEvent, key, Subsystem.TASK_MANAGER);

        } else if (isUcfProfiled && Subsystem.UCF.equals(subsystem)){
            updateOverallStatistics(performanceMap, profilingEvent, key, Subsystem.UCF);

        } else if(isSynchronizationServiceProfiled && Subsystem.SYNCHRONIZATION_SERVICE.equals(subsystem)){
            updateOverallStatistics(performanceMap, profilingEvent, key, Subsystem.SYNCHRONIZATION_SERVICE);

        } else if(isWorkflowProfiled && Subsystem.WORKFLOW.equals(subsystem)){
            updateOverallStatistics(performanceMap, profilingEvent, key, Subsystem.WORKFLOW);
        }

        Long processingEstTime = System.nanoTime() - processingStartTime;
        logEventProcessingDuration(key, processingEstTime);

        ProfilingDataManager.getInstance().dumpToLog();
    }

    private void logEventProcessingDuration(String key, long est){
        if (performanceMap.get(key) != null) {
            performanceMap.get(key).updateProcessTimeList(est);
        }
    }

    public void prepareRequestProfilingEvent(ProfilingDataLog requestEvent){
        String key = requestEvent.getClassName();
        updateOverallStatistics(performanceMap, requestEvent, key, Subsystem.WEB);
    }

    private String prepareKey(ProfilingDataLog log){
        String key = log.getClassName();
        key = key.concat(PRINT_RIGHT_ARROW);
        key = key.concat(log.getMethodName());

        return key;
    }

    public synchronized void dumpToLog() {
        if (profilingTest) {
            return;
        }

        long currentTime = System.currentTimeMillis();

        if(currentTime >= (lastDumpTimestamp + minutesToMillis(minuteDumpInterval))){
            if(LOGGER.isDebugEnabled()){

                printEverything(false);

                //Set next dump cycle
                lastDumpTimestamp = System.currentTimeMillis();
                cleanEverything();
            }
        }

        //Print performance statistics if needed
        if(isPerformanceProfiled){
            if(currentTime >= (lastPerformanceDumpTimestamp + minutesToMillis(DEFAULT_PERF_DUMP_INTERVAL))){
                new PerformanceStatistics();
                lastPerformanceDumpTimestamp = System.currentTimeMillis();
            }
        }
    }

    public void printEverything(boolean afterTest){
        if(isModelProfiled){
            printMap(performanceMap, Subsystem.MODEL, afterTest);
        }
        if(isProvisioningProfiled) {
            printMap(performanceMap, Subsystem.PROVISIONING, afterTest);
        }
        if(isRepositoryProfiled)  {
            printMap(performanceMap, Subsystem.REPOSITORY, afterTest);
        }
        if(isTaskManagerProfiled) {
            printMap(performanceMap, Subsystem.TASK_MANAGER, afterTest);
        }
        if(isUcfProfiled) {
            printMap(performanceMap, Subsystem.UCF, afterTest);
        }
        if(isWorkflowProfiled){
            printMap(performanceMap, Subsystem.WORKFLOW, afterTest);
        }
        if(isSynchronizationServiceProfiled) {
            printMap(performanceMap, Subsystem.SYNCHRONIZATION_SERVICE, afterTest);
        }
        if(isWebProfiled){
            printMap(performanceMap, Subsystem.WEB, afterTest);
        }
    }

    private static long minutesToMillis(int minutes){
        return (long)(minutes*60*1000);
    }

    private synchronized void updateOverallStatistics(Map<String, MethodUsageStatistics> logMap, ProfilingDataLog eventLog, String key, Subsystem subsystem){
        if(!logMap.containsKey(key)){
            eventLog.setArgs(prepareArguments(eventLog.args));
            logMap.put(key, new MethodUsageStatistics(eventLog, subsystem));
        } else {
            logMap.get(key).update(eventLog);
        }

        if(logMap.get(key).getSlowestMethodList().size() < topTenMethodNumber){
            eventLog.setArgs(prepareArguments(eventLog.args));
            logMap.get(key).getSlowestMethodList().add(eventLog);
            sort(logMap.get(key).getSlowestMethodList());
        } else {
            if(logMap.get(key).getSlowestMethodList().get(logMap.get(key).getSlowestMethodList().size()-1).getEstimatedTime() < eventLog.getEstimatedTime()){
                eventLog.setArgs(prepareArguments(eventLog.args));
                logMap.get(key).getSlowestMethodList().add(eventLog);
                sort(logMap.get(key).getSlowestMethodList());
                logMap.get(key).setCurrentTopTenMin(logMap.get(key).getSlowestMethodList().get(logMap.get(key).getSlowestMethodList().size()-1).getEstimatedTime());
            }
        }

        if(logMap.get(key).getSlowestMethodList().size() > topTenMethodNumber){
            logMap.get(key).getSlowestMethodList().remove(logMap.get(key).getSlowestMethodList().size()-1);
        }
    }

    private static void printMap(Map<String, MethodUsageStatistics> logMap, Subsystem subsystem, boolean afterTest){
        for (Map.Entry<String, MethodUsageStatistics> usage : logMap.entrySet()){
            final MethodUsageStatistics value = usage.getValue();
            if(subsystem.equals(value.getSubsystem())){
                value.appendToLogger(afterTest);
            }
        }
    }

    public void subsystemConfiguration(Map<Subsystem, Boolean> subsystems){
        isModelProfiled = isSubsystemProfiled(Subsystem.MODEL, subsystems);
        isProvisioningProfiled = isSubsystemProfiled(Subsystem.PROVISIONING, subsystems);
        isRepositoryProfiled = isSubsystemProfiled(Subsystem.REPOSITORY, subsystems);
        isSynchronizationServiceProfiled = isSubsystemProfiled(Subsystem.SYNCHRONIZATION_SERVICE, subsystems);
        isTaskManagerProfiled = isSubsystemProfiled(Subsystem.TASK_MANAGER, subsystems);
        isUcfProfiled = isSubsystemProfiled(Subsystem.UCF, subsystems);
        isWorkflowProfiled = isSubsystemProfiled(Subsystem.WORKFLOW, subsystems);
        isWebProfiled = isSubsystemProfiled(Subsystem.WEB, subsystems);
    }

    private boolean isSubsystemProfiled(Subsystem subsystem, Map<Subsystem, Boolean> map){
        if(map.get(subsystem) != null && map.get(subsystem)){
            return true;
        }

        return false;
    }

    private void cleanEverything(){
        performanceMap.clear();
    }

    private ProfilingDataLog prepareProfilingDataLog(String className, String methodName, long startTime, Object[] args) {
        long eTime = calculateTime(startTime);
        long timestamp = System.currentTimeMillis();

        return new ProfilingDataLog(className, methodName, eTime, timestamp, args);
    }

    private synchronized static List<ProfilingDataLog> sort(List<ProfilingDataLog> list) {
        Collections.sort(list, ARRAY_COMPARATOR);
        return list;
    }

    private static class ArrayComparator implements Comparator<ProfilingDataLog> {

        @Override
        public int compare(ProfilingDataLog o1, ProfilingDataLog o2) {
            return ((Long)o2.getEstimatedTime()).compareTo(o1.getEstimatedTime());
        }

    }

    private long calculateTime(long startTime){
        return (System.nanoTime() - startTime);
    }

    public Map<String, MethodUsageStatistics> getPerformanceMap() {
        return performanceMap;
    }

    public int getMinuteDumpInterval() {
        return minuteDumpInterval;
    }

    private String[] prepareArguments(Object[] args){

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

        StringBuilder sb = new StringBuilder();

        for(Object o: args){
            if (o == null) {
                sb.append(ARGS_NULL);
            } else {
                sb.append(o.toString());
            }

            sb.append(INDENT_STRING);
        }

        return new String[] { sb.toString() };
    }

    public void appendProfilingToTest() {
        OperationExecutionLogger.activateSubsystemProfiling();
    }

    public void stopProfilingAfterTest() {
        OperationExecutionLogger.deactivateSubsystemProfiling();
    }

    public void printMapAfterTest() {
        printEverything(true);
    }

    public Map<String, MethodUsageStatistics> getProfilingData() {
        return performanceMap;
    }
}


text:
import yaml
import pandas as pd
import numpy as np
from numpy import nan
import os, sys
import re
import json

from EDL.dialogue.MatEngine_object import eng1
from EDL.dialogue.func_helpers import CalculateFuncs

eng1.addpath('/Volumes/Encrypted/Mars2020/mars2020/MATLAB/', nargout=0)
eng1.addpath('/Users/ssantini/Code/ExtractDataMatlab/MatlabEngine/', nargout=0)

def generate_scorecard_dataframe(scorecard_dict):

    dict_test = pd.DataFrame.from_dict(scorecard_dict)
    metric_list = []
    type_list = []
    units_list = []
    POST_result_list = []
    direction_list = []
    flag_list = []
    outofspec_list = []
    calculation_list = []
    eval_list = []
    sheet_name = []
    for item in scorecard_dict:
        metric_list.append(item[':metric'])
        type_list.append(item[':type'])
        units_list.append(item[':units'])
        POST_result_list.append(item[':value'])
        direction_list.append(item[':direction'])
        flag_list.append(item[':yellow'])
        outofspec_list.append(item[':red'])
        calculation_list.append(item[':calculation'])
        eval_list.append(item[':evalString'])
        sheet_name.append(item[':sheet'])

        scorecard_dataframe= pd.DataFrame({'metric_name': metric_list,
        'type': type_list,
        'units': units_list,
        'post_results': POST_result_list,
        'direction': direction_list,
        'flag': flag_list,
        'out_of_spec':outofspec_list,
        'calculation':calculation_list,
        'evalString': eval_list,
        'sheet_name': sheet_name

         })
    seen = set()
    unique_metrics = []
    for item in metric_list:
        if item not in seen:
            seen.add(item)
            unique_metrics.append(item)

    return scorecard_dataframe

status_list = []
def generate_scorecard_dataframe_labeled(scorecard_dataframe_labeled):
    for i in list(range(len(scorecard_dataframe_labeled.index.values))):  # list(range(len(scorecard_df.index.values)))
        if pd.isna(scorecard_dataframe_labeled['post_results'][i]) != True and pd.isna(scorecard_dataframe_labeled['flag'][i]) != True \
                and pd.isna(scorecard_dataframe_labeled['direction'][i]) != True and scorecard_dataframe_labeled['direction'][i] != None\
                and scorecard_dataframe_labeled['direction'][i] != 'N/A' and pd.isna(scorecard_dataframe_labeled['out_of_spec'][i]) != True:
                #and scorecard_dataframe_labeled['out_of_spec'][i] != 0 and scorecard_dataframe_labeled['flag'][i] != 0:
                metric_name = scorecard_dataframe_labeled['metric_name'][i]
                result = scorecard_dataframe_labeled['post_results'][i]
                sign = scorecard_dataframe_labeled['direction'][i]
                flag_val = scorecard_dataframe_labeled['flag'][i]
                fail_val = scorecard_dataframe_labeled['out_of_spec'][i]
                if eval(str(scorecard_dataframe_labeled['post_results'][i]) + str(scorecard_dataframe_labeled['direction'][i]) + str(scorecard_dataframe_labeled['flag'][i])) == False \
                                and eval(str(scorecard_dataframe_labeled['post_results'][i]) + str(scorecard_dataframe_labeled['direction'][i]) + str(scorecard_dataframe_labeled['out_of_spec'][i])) == True:
                            status_list.append(str('flagged'))
                elif eval(str(scorecard_dataframe_labeled['post_results'][i]) + str(scorecard_dataframe_labeled['direction'][i]) + str(scorecard_dataframe_labeled['flag'][i])) == False\
                                and eval(str(scorecard_dataframe_labeled['post_results'][i]) + str(scorecard_dataframe_labeled['direction'][i]) + str(scorecard_dataframe_labeled['out_of_spec'][i])) == False:
                            status_list.append(str('out of spec'))
                elif eval(str(scorecard_dataframe_labeled['post_results'][i]) + str(scorecard_dataframe_labeled['direction'][i]) + str(
                            scorecard_dataframe_labeled['flag'][i])) == True \
                             and eval(str(scorecard_dataframe_labeled['post_results'][i]) + str(scorecard_dataframe_labeled['direction'][i]) + str(
                            scorecard_dataframe_labeled['out_of_spec'][i])) == True:
                            status_list.append(str('value is ok'))
                else:
                            status_list.append('N/A')
        else:
            status_list.append('N/A')

    status_df = pd.DataFrame({'status': status_list})
    scorecard_dataframe_labeled['status'] = status_df
    return scorecard_dataframe_labeled

def get_scorecard_arrays(scorecard_df, matfile_path, for_db):
    array_list = []
    eng1.addpath('/Volumes/Encrypted/Mars2020/mars2020/MATLAB/', nargout=0)
    eng1.addpath('/Users/ssantini/Code/ExtractDataMatlab/MatlabEngine/', nargout=0)
    if for_db == True:
        eng1.load(matfile_path, 'output_case', nargout=0)
        output_case = eng1.workspace['output_case']
        output_case_array = np.asarray(output_case)
    for index, row in scorecard_df.iterrows():
        metric = row.metric_name
        print(metric)
        equation = row.calculation
        list_for_load, warning = CalculateFuncs.equation_parser(row.calculation, matfile_path)
        if not row.calculation.startswith("if") or row.calculation.startswith("i ="):
            eqs_to_calc = row.calculation.split(';')
            eqs_to_calc = [x for x in eqs_to_calc if x]
        else:
            eqs_to_calc = [row.calculation]
        ''' Load  variables into workspace'''
        [eng1.load(matfile_path, item, nargout=0) for item in list_for_load]  # load each
        [eng1.workspace[item] for item in list_for_load]
        #eqs_to_calc = [w.replace('[a,b,azl]=size_ellipse(x,y,mean(gcrad_tds/1e3))', '[a,b,azl]=size_ellipse(x,y,(gcrad_tds/1e3))') for w in eqs_to_calc]

        for item in eqs_to_calc:
            # add each to workspace
            variables = eng1.eval('who')
            eng1.eval(item, nargout=0)
            variables = eng1.eval('who')
            if 'ans' in variables:
                this = 'answer is calculated already'
                answer = eng1.workspace['ans']

        if type(answer) != float: # if array
            if metric == 'Major axis ':
                ejemplo = np.asarray(answer)*2
            else:
                ejemplo = np.asarray(answer)
            array_list.append(ejemplo)
            test = 'its an array'
        elif type(answer) == float and for_db == True:
            array_list.append(np.asarray(answer))
        else:
            array_list.append(np.array(0))
    if for_db == True:
        array_list.append(output_case)
    return array_list

def get_case_numbers(metric_name, scorecard_dataframe, matfile_path, criteria):

    metric_array = scorecard_dataframe.arrays.array[0]
    #metric_array = \
    #scorecard_dataframe[scorecard_dataframe["metric_name"].str.lower().str.contains(metric_name)].arrays.array[0]
    n = len(metric_array)
    metric_status = []
    if len(metric_array) > 0:
        'this means we have an array, we can now calculate the labels'
        flag_value = (scorecard_dataframe.flag.array[0]).astype(str)
        direction = str(scorecard_dataframe.direction.array[0])
        out_of_spec_value = (scorecard_dataframe.out_of_spec.array[0]).astype(str)

        for i in range(len(metric_array)):
            if eval(str(metric_array[i][0]) + (direction) + flag_value) == False \
                    and eval(str(metric_array[i][0]) + (direction) + (out_of_spec_value)) == True:
                metric_status.append('flagged_case')
            elif eval(str(metric_array[i][0]) + (direction) + (flag_value)) == False \
                    and eval(str(metric_array[i][0]) + (direction) + (out_of_spec_value)) == False:
                metric_status.append('out_of_spec_case')
            elif eval(str(metric_array[i][0]) + (direction) + (flag_value)) == True \
                    and eval(str(metric_array[i][0]) + (direction) + (out_of_spec_value)) == True:
                metric_status.append('value ok')
            else:
                metric_status.append('missing information')

    else:
        return 'There is not enough information to calculate this'

    eng1.load(matfile_path, 'output_case', nargout=0)
    output_case = eng1.workspace['output_case']
    output_case_array = np.asarray(output_case)

    indices_fail = []
    indices_flag = []
    cases_fail = []
    cases_flag = []
    if criteria == 'out_of_spec':
        indices_fail = [j for j, x in enumerate(metric_status) if x == 'out_of_spec_case']
        cases_fail = np.take(output_case, indices_fail)
        indices_flag = []
        cases_flag = []
    if criteria == 'flagged':
        indices_flag = [j for j, x in enumerate(metric_status) if x == 'flagged_case']
        cases_flag = np.take(output_case, indices_flag)
        cases_fail = []
        indices_fail = []
    if criteria == 'all cases':
        indices_fail = [j for j, x in enumerate(metric_status) if x == 'out_of_spec_case']
        cases_fail = np.take(output_case, indices_fail)
        indices_flag = [j for j, x in enumerate(metric_status) if x == 'flagged_case']
        cases_flag = np.take(output_case, indices_flag)

    return indices_fail, cases_fail, indices_flag, cases_flag

def scorecard_df_for_db(matout_path, context):
    if context.edlcontext.current_mission == 'm2020':
        mission_name = 'Mars2020'
        db_template = pd.read_excel('/Users/ssantini/Code/Code_Daphne/daphne_brain/EDL/dialogue/func_helpers/db_m2020_template.xlsx')

    file_to_search = os.path.basename(matout_path.replace(".mat", ".yml"))
    scorecard_path = '/Users/ssantini/Code/Code_Daphne/daphne_brain/EDL/data/scorecards/' + file_to_search

    with open(scorecard_path, encoding='utf-8') as file_to_search:
        scorecard_dict = yaml.load(file_to_search)
        scorecard_df = pd.DataFrame(scorecard_dict)

    scorecard_metrics = scorecard_df[':metric'].ravel().tolist()
    db_template = db_template[db_template['metric_name'].isin(scorecard_metrics)]
    metric_list = db_template['metric_name'].ravel().tolist()

    # ''' Get Status of metrics flag/fail/pass'''
    scorecard_subdf = scorecard_df[scorecard_df[':metric'].isin(metric_list)]
    scorecard_subdf = scorecard_subdf[scorecard_subdf[':sheet'].isin(['Entry', 'Parachute Descent', 'Powered Flight'])]

    # ''' Add to template'''
    status_list = scorecard_subdf[':code'].ravel().tolist()
    calc_list = scorecard_subdf[':calculation'].ravel().tolist()
    units_list = scorecard_subdf[':units'].ravel().tolist()

    db_template['calculation'] = calc_list
    db_template = db_template
    # ''' Compute arrays '''
    arrays = get_scorecard_arrays(db_template, matout_path, True)
    output_case = np.asarray(arrays[len(arrays)-1]).ravel()
    # ''' Drop output_case from arrays list'''
    arrays = arrays[:-1]

    # Compute properties for each metric
    dict_list = []
    prctile_1_list = []
    prctile_99_list = []
    average_list = []
    var_list = []
    arr_list = []
    for item in arrays:
        if item.size == 1:
            item = np.full((1,8000), item)
        prctile_1 = np.percentile(np.asarray(item).ravel(), 1)
        prctile_99 = np.percentile(np.asarray(item).ravel(), 99)
        average = np.percentile(np.asarray(item).ravel(), 50)
        var = np.var(np.asarray(item).ravel())
        dictionary = str(json.dumps(dict(zip(output_case, np.asarray(item).ravel()))))
        dict_list.append(dictionary)
        prctile_1_list.append(prctile_1)
        prctile_99_list.append(prctile_99)
        average_list.append(average)
        var_list.append(var)
        arr_list.append(item.ravel().tolist())

    db_template['prctile_1'] = prctile_1_list
    db_template['prctile_99'] = prctile_99_list
    db_template['average'] = average_list
    db_template['variance'] = var_list
    db_template['variance'] = var_list
    db_template['status'] = status_list
    db_template['dict_data'] = dict_list
    db_template['units'] = units_list

    db_template['status'] = db_template['status'].replace([':grey', ':green'], 'ok')
    db_template['status'] = db_template['status'].replace([':yellow'], 'flagged')
    db_template['status'] = db_template['status'].replace([':red'], 'out_of_spec')
    # db_template['arrays'] = arrays

    #### GET DUPLICATES AND DROP NECESSARY ONES #####
    duplicates = db_template[db_template.duplicated(['metric_name'])]
    duplicates.drop(duplicates[duplicates['metric_name'] == 'Number of No Vel Solutions'].index, inplace=True)
    duplicates.drop(duplicates[duplicates['metric_name'] == 'Number of No Alt Solutions'].index, inplace=True)
    duplicates.drop(duplicates[duplicates['metric_name'] == 'Max Velocity Solution Change'].index, inplace=True)
    duplicates.drop(duplicates[duplicates['metric_name'] == 'Number of No Alt Soltuions'].index, inplace=True)
    duplicates.drop(duplicates[duplicates['metric_name'] == 'Number of No Vel Soltuions'].index, inplace=True)

    idx_to_remove = duplicates.index
    db_template.reset_index()
    nav_solutions = db_template[db_template['metric_name'].isin(['Max Velocity Solution Change',
                                                                 'Number of No Vel Solutions',
                                                                 'Number of No Alt Solutions',
                                                                 'Number of No Alt Soltuions',
                                                                 'Number of No Vel Soltuions'])]

    res = list(map(" at ".join, zip(nav_solutions.metric_name.tolist(), nav_solutions.segment_name.tolist())))
    nav_solutions['metric_name'] = res

    db_template.loc[nav_solutions.index] = nav_solutions
    # db_template['metric_id'] = db_template['metric_name'].astype(str) + ext_id
    # Drop the other duplicated measures that are not repeated in events
    db_template = db_template.drop_duplicates(subset='metric_name', keep='first')

    return db_template


text:
namespace Hospital.Data.Common
{
    using Constants;
    using DatabaseModels;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class Seed
    {
        private GenerateRandomData random = new GenerateRandomData();

        internal void SeedAdminAndPatients(ApplicationDbContext context)
        {

            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var userManager = new UserManager<User>(new UserStore<User>(context));

            if (!roleManager.RoleExists(GlobalConstants.adminRoleName))
            {
                var role = new IdentityRole()
                {
                    Name = GlobalConstants.adminRoleName
                };
                roleManager.Create(role);

                var user = new User()
                {
                    UserName = GlobalConstants.adminUserName,
                    Email = GlobalConstants.adminUserName
                };

                for (int i = 0; i < 10; i++)
                {
                    var patient = new User()
                    {
                        UserName = "patient" + i + "@patient.com",
                        Email = "patient" + i + "@patient.com",
                        ClinicalResults = new List<ClinicalResult>()
                        {
                            new ClinicalResult()
                            {
                                StatusResult = StatusResult.Ready
                            },
                            new ClinicalResult()
                            {
                                StatusResult = StatusResult.inProcess
                            }
                        }
                    };

                    context.Users.Add(patient);
                }
                context.SaveChanges();

                IdentityResult createUserResult = userManager.Create(user, GlobalConstants.adminPassword);
                if (createUserResult.Succeeded)
                {
                    userManager.AddToRole(user.Id, GlobalConstants.adminRoleName);
                }
            }
        }

        private Image CreateImage()
        {
            var img = new Image()
            {
                FileName = "doctor1.jpg",
                Path = PathConstants.PathImage
            };

            return img;
        }

        internal void SeedDoctorsClinicalTrialsAndSpecialties(ApplicationDbContext context)
        {
            if (!context.Doctors.Any() || !context.ClinicalTrials.Any() || !context.Specialities.Any())
            {
                for (int i = 1; i < 5; i++)
                {
                    var clinicalTrial = new ClinicalTrial
                    {
                        Title = "Trial - " + i + ".1",
                        Price = random.RandomDataInt(25, 4587),
                        IsAvailable = IsAvailable.Yes,
                    };

                    var clinicalTrial2 = new ClinicalTrial
                    {
                        Title = "Trial - " + i + ".2",
                        Price = random.RandomDataInt(48, 565),
                        IsAvailable = IsAvailable.No,
                    };

                    var listDoctors = new List<Doctor>();
                    for (int j = 0; j < random.RandomDataInt(2, 6); j++)
                    {
                        var doctor = new Doctor
                        {
                            Name = "Doctor - " + random.RandomDataString(6, 10) + " " + random.RandomDataString(10, 13),
                            Image = CreateImage(),
                            Description = random.RandomDataString(400, 1000)
                        };
                        listDoctors.Add(doctor);
                    }

                    var specialty = new Speciality
                    {
                        Title = "Specialty - " + i,
                        Description = random.RandomDataString(200, 500),
                        ClinicalTrials = new HashSet<ClinicalTrial>()
                        {
                            clinicalTrial,
                            clinicalTrial2
                        },
                        Doctors = listDoctors
                    };
                    context.Specialities.Add(specialty);
                    context.SaveChanges();
                }
            }
        }
    }
}


text:
using System.Collections.Immutable;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Semantics;

namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines
{
    /// <summary>
    /// CA1814: Prefer jagged arrays over multidimensional
    /// </summary>
    [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
    public sealed class PreferJaggedArraysOverMultidimensionalAnalyzer : DiagnosticAnalyzer
    {
        internal const string RuleId = "CA1814";

        private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftQualityGuidelinesAnalyzersResources.PreferJaggedArraysOverMultidimensionalTitle), MicrosoftQualityGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftQualityGuidelinesAnalyzersResources));

        private static readonly LocalizableString s_localizableMessageDefault = new LocalizableResourceString(nameof(MicrosoftQualityGuidelinesAnalyzersResources.PreferJaggedArraysOverMultidimensionalMessageDefault), MicrosoftQualityGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftQualityGuidelinesAnalyzersResources));
        private static readonly LocalizableString s_localizableMessageReturn = new LocalizableResourceString(nameof(MicrosoftQualityGuidelinesAnalyzersResources.PreferJaggedArraysOverMultidimensionalMessageReturn), MicrosoftQualityGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftQualityGuidelinesAnalyzersResources));
        private static readonly LocalizableString s_localizableMessageBody = new LocalizableResourceString(nameof(MicrosoftQualityGuidelinesAnalyzersResources.PreferJaggedArraysOverMultidimensionalMessageBody), MicrosoftQualityGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftQualityGuidelinesAnalyzersResources));
        private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftQualityGuidelinesAnalyzersResources.PreferJaggedArraysOverMultidimensionalDescription), MicrosoftQualityGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftQualityGuidelinesAnalyzersResources));

        private const string helpLink = "https://msdn.microsoft.com/en-us/library/ms182277.aspx";

        internal static DiagnosticDescriptor DefaultRule = new DiagnosticDescriptor(RuleId,
                                                                             s_localizableTitle,
                                                                             s_localizableMessageDefault,
                                                                             DiagnosticCategory.Performance,
                                                                             DiagnosticHelpers.DefaultDiagnosticSeverity,
                                                                             isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
                                                                             description: s_localizableDescription,
                                                                             helpLinkUri: helpLink,
                                                                             customTags: WellKnownDiagnosticTags.Telemetry);
        internal static DiagnosticDescriptor ReturnRule = new DiagnosticDescriptor(RuleId,
                                                                             s_localizableTitle,
                                                                             s_localizableMessageReturn,
                                                                             DiagnosticCategory.Performance,
                                                                             DiagnosticHelpers.DefaultDiagnosticSeverity,
                                                                             isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
                                                                             description: s_localizableDescription,
                                                                             helpLinkUri: helpLink,
                                                                             customTags: WellKnownDiagnosticTags.Telemetry);
        internal static DiagnosticDescriptor BodyRule = new DiagnosticDescriptor(RuleId,
                                                                             s_localizableTitle,
                                                                             s_localizableMessageBody,
                                                                             DiagnosticCategory.Performance,
                                                                             DiagnosticHelpers.DefaultDiagnosticSeverity,
                                                                             isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
                                                                             description: s_localizableDescription,
                                                                             helpLinkUri: helpLink,
                                                                             customTags: WellKnownDiagnosticTags.Telemetry);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DefaultRule, ReturnRule, BodyRule);

        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.EnableConcurrentExecution();
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            analysisContext.RegisterSymbolAction(AnalyzeField, SymbolKind.Field);
            analysisContext.RegisterSymbolAction(AnalyzeProperty, SymbolKind.Property);
            analysisContext.RegisterSymbolAction(AnalyzeMethod, SymbolKind.Method);
            analysisContext.RegisterOperationActionInternal(AnalyzeObjectCreation, OperationKind.ArrayCreationExpression);
        }

        private static void AnalyzeField(SymbolAnalysisContext context)
        {
            var field = (IFieldSymbol)context.Symbol;

            if (IsMultiDimensionalArray(field.Type))
            {
                context.ReportDiagnostic(field.CreateDiagnostic(DefaultRule, field.Name));
            }
        }

        private static void AnalyzeProperty(SymbolAnalysisContext context)
        {
            var property = (IPropertySymbol)context.Symbol;

            // If its an override then don't report it as it can only be fixed in the base type.
            if (!property.IsOverride)
            {
                if (IsMultiDimensionalArray(property.Type))
                {
                    context.ReportDiagnostic(property.CreateDiagnostic(DefaultRule, property.Name));
                }

                AnalyzeParameters(context, property.Parameters);
            }
        }

        private static void AnalyzeMethod(SymbolAnalysisContext context)
        {
            var method = (IMethodSymbol)context.Symbol;

            // If its an override then don't report it as it can only be fixed in the base type.
            // If its a getter\setter then we will report on the property instead so skip analyzing the method.
            if (!method.IsOverride && method.AssociatedSymbol == null)
            {
                if (IsMultiDimensionalArray(method.ReturnType))
                {
                    context.ReportDiagnostic(method.CreateDiagnostic(ReturnRule, method.Name, method.ReturnType));
                }

                AnalyzeParameters(context, method.Parameters);
            }
        }

        private static void AnalyzeObjectCreation(OperationAnalysisContext context)
        {
            var arrayCreationExpression = (IArrayCreationExpression)context.Operation;

            if (IsMultiDimensionalArray(arrayCreationExpression.Type))
            {
                context.ReportDiagnostic(arrayCreationExpression.Syntax.CreateDiagnostic(BodyRule, context.ContainingSymbol.Name, arrayCreationExpression.Type));
            }
        }

        private static void AnalyzeParameters(SymbolAnalysisContext context, ImmutableArray<IParameterSymbol> parameters)
        {
            foreach (IParameterSymbol parameter in parameters)
            {
                if (IsMultiDimensionalArray(parameter.Type))
                {
                    context.ReportDiagnostic(parameter.CreateDiagnostic(DefaultRule, parameter.Name));
                }
            }
        }

        /// <summary>
        /// Check if the given type or any of its inner element types is a multi dimensional array
        /// </summary>
        private static bool IsMultiDimensionalArray(ITypeSymbol type)
        {
            while (type.TypeKind == TypeKind.Array)
            {
                var arrayType = (IArrayTypeSymbol)type;

                if (arrayType.Rank > 1)
                {
                    return true;
                }

                type = arrayType.ElementType;
            }

            return false;
        }
    }
}


text:
package options

import (
	"github.com/spf13/pflag"

	"github.com/openshift/origin/pkg/cmd/util/variable"
)

// ImageFormatArgs is a struct that the command stores flag values into.
type ImageFormatArgs struct {
	// ImageTemplate is used in expanding parameterized Docker image references
	// from configuration or a file
	ImageTemplate variable.ImageTemplate
}

// BindImageFormatArgs binds values to the given arguments by using flags
func BindImageFormatArgs(args *ImageFormatArgs, flags *pflag.FlagSet, prefix string) {
	flags.StringVar(&args.ImageTemplate.Format, "images", args.ImageTemplate.Format, "When fetching images used by the cluster for important components, use this format on both master and nodes. The latest release will be used by default.")
	flags.BoolVar(&args.ImageTemplate.Latest, "latest-images", args.ImageTemplate.Latest, "If true, attempt to use the latest images for the cluster instead of the latest release.")
}

// NewDefaultImageFormatArgs returns the default image template
func NewDefaultImageFormatArgs() *ImageFormatArgs {
	config := &ImageFormatArgs{
		ImageTemplate: variable.NewDefaultImageTemplate(),
	}

	return config
}


text:
package com.intellij.xdebugger.impl.ui.tree.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.DumbAware;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.impl.XDebuggerUtilImpl;
import com.intellij.xdebugger.impl.settings.XDebuggerSettingManagerImpl;
import javax.annotation.Nonnull;
import consulo.ui.annotation.RequiredUIAccess;

/**
 * @author nik
 */
public class SortValuesToggleAction extends ToggleAction implements DumbAware {

  @RequiredUIAccess
  @Override
  public void update(@Nonnull AnActionEvent e) {
    super.update(e);
    XDebugSession session = e.getDataContext().getData(XDebugSession.DATA_KEY);
    e.getPresentation().setEnabledAndVisible(session != null && !session.getDebugProcess().isValuesCustomSorted());
  }

  @Override
  public boolean isSelected(AnActionEvent e) {
    return XDebuggerSettingManagerImpl.getInstanceImpl().getDataViewSettings().isSortValues();
  }

  @Override
  public void setSelected(AnActionEvent e, boolean state) {
    XDebuggerSettingManagerImpl.getInstanceImpl().getDataViewSettings().setSortValues(state);
    XDebuggerUtilImpl.rebuildAllSessionsViews(e.getProject());
  }
}


text:
require "typhoeus"

class TSheets::RestAdapter < TSheets::Adapter
  class << self
    def get(url, params, headers)
      puts "GET #{url} (#{headers.inspect}) - #{params.inspect}" if Typhoeus::Config.verbose
      TSheets::HttpResponse.new Typhoeus.get(url, params: params, headers: headers)
    end

    def post(url, data, options)
      puts "POST #{url} (#{options.inspect}) - #{data.inspect}" if Typhoeus::Config.verbose
      TSheets::HttpResponse.new Typhoeus.post(url, body: data.to_json, headers: options)
    end

    def put(url, data, options)
      puts "PUT #{url} (#{options.inspect}) - #{data.inspect}" if Typhoeus::Config.verbose
      TSheets::HttpResponse.new Typhoeus.put(url, body: data.to_json, headers: options)
    end

    def delete(url, data, options)
      puts "DELETE #{url} (#{options.inspect}) - #{data.inspect}" if Typhoeus::Config.verbose
      TSheets::HttpResponse.new Typhoeus.delete(url, params: { ids: data[:ids].join(",") }, headers: options)
    end
  end
end


text:
import { World } from "./World";
import { Unit } from "./Unit/Unit";
import { Event } from "./Util/Event";
import { Vector } from "./Geometry/Vector";
import { ResourceManager } from "./Util/ResourceManager";
import { Resource } from "./Util/RoboPack";

export interface ITextureInfo
{
    Width: number;
    Height: number;
    Object: WebGLTexture;
}

export interface IRendererArgs
{
    world: World;
    canvas: HTMLCanvasElement;

    dotPerPoint?: number;
    debugMode?: boolean;
    disableShadows?: boolean;
    viewport?: Vector;
    center?: Vector;
    noTick?: boolean;
    selectedZ?: number;
}

/**
 * The WebGL parts are based on the examples of Gregg Tavares.
 */
// TODO: Implement debug grid drawing
// TODO: Implement shadows
export class Renderer
{
    private static VertexShader =
    `
        attribute vec4 a_position;
        attribute vec2 a_textureCoord;

        uniform mat4 u_matrix;
        uniform mat4 u_textureMatrix;

        varying vec2 v_textureCoord;

        void main()
        {
            gl_Position = u_matrix * a_position;
            v_textureCoord = (u_textureMatrix * vec4(a_textureCoord, 0, 1)).xy;
        }
    `;

    private static FragmentShader =
    `
        precision mediump float;

        varying vec2 v_textureCoord;

        uniform sampler2D texture;

        void main()
        {
            gl_FragColor = texture2D(texture, v_textureCoord);
        }
    `;

    private static MinFps = 1 / 25;
    private static DebugColor = new Uint8Array([0, 0, 0, 255]);

    private readonly world: World;
    private readonly canvas: HTMLCanvasElement;
    private readonly gl: WebGLRenderingContext;
    private readonly dotPerPoint: number;

    private readonly matrixStack: Mat4Stack;
    private readonly program: WebGLProgram;
    private readonly positionLocation: number;
    private readonly textureCoordLocation: number;
    private readonly matrixLocation: WebGLUniformLocation;
    private readonly textureMatrixLocation: WebGLUniformLocation;
    private readonly textureLocation: WebGLUniformLocation;
    private readonly positionBuffer: WebGLBuffer;
    private readonly textureCoordBuffer: WebGLBuffer;

    private readonly debugMode: boolean;
    private readonly disableShadows: boolean;

    private textures: { [id: string]: any } = {};
    private stop: boolean = false;
    private lastTick: number;
    private center: Vector;
    private viewport: Vector;
    private noTick: boolean;
    private selectedZ: number;
    private selectedUnit: Unit;

    /**
     * Called upon redraw.
     */
    public OnDraw: Event<number> = new Event();

    /**
     * Construct a new game object.
     */
    public constructor(args: IRendererArgs)
    {
        this.world = args.world;
        this.canvas = args.canvas;

        this.dotPerPoint = args.dotPerPoint || 25;
        this.debugMode = args.debugMode || false;
        this.disableShadows = args.disableShadows || false;
        this.viewport = args.viewport || new Vector(6, 6);
        this.center = args.center || new Vector(0, 0);
        this.noTick = args.noTick || false;
        this.selectedZ = args.selectedZ || undefined;

        this.gl = this.canvas.getContext("webgl");
        this.matrixStack = new Mat4Stack();

        // Setup GLSL program
        this.program = this.gl.createProgram();

        const vertexShader = this.gl.createShader(this.gl.VERTEX_SHADER);

        this.gl.shaderSource(vertexShader, Renderer.VertexShader);
        this.gl.compileShader(vertexShader);
        this.gl.attachShader(this.program, vertexShader);

        const fragmentShader = this.gl.createShader(this.gl.FRAGMENT_SHADER);

        this.gl.shaderSource(fragmentShader, Renderer.FragmentShader);
        this.gl.compileShader(fragmentShader);
        this.gl.attachShader(this.program, fragmentShader);

        this.gl.linkProgram(this.program);

        if(!this.gl.getProgramParameter(this.program, this.gl.LINK_STATUS))
        {
            throw new Error("Could not compile WebGL program");
        }

        // Look up where the vertex data needs to go.
        this.positionLocation = this.gl.getAttribLocation(this.program, "a_position");
        this.textureCoordLocation = this.gl.getAttribLocation(this.program, "a_textureCoord");

        // Lookup uniforms
        this.matrixLocation = this.gl.getUniformLocation(this.program, "u_matrix");
        this.textureMatrixLocation = this.gl.getUniformLocation(this.program, "u_textureMatrix");
        this.textureLocation = this.gl.getUniformLocation(this.program, "u_texture");

        // Create a buffer.
        this.positionBuffer = this.gl.createBuffer();
        this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.positionBuffer);

        // Put a unit quad in the buffer
        const positions = [
            0, 0,
            0, 1,
            1, 0,
            1, 0,
            0, 1,
            1, 1,
        ];

        this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(positions), this.gl.STATIC_DRAW);

        // Create a buffer for texture coords
        this.textureCoordBuffer = this.gl.createBuffer();
        this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.textureCoordBuffer);

        // Put textureCoords in the buffer
        const textureCoords = [
            0, 0,
            0, 1,
            1, 0,
            1, 0,
            0, 1,
            1, 1,
        ];

        this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(textureCoords), this.gl.STATIC_DRAW);
    }

    private DrawImage(texture: ITextureInfo,
        sx: number, sy: number, sw: number, sh: number,
        dx: number, dy: number, dw: number, dh: number)
    {
        this.gl.bindTexture(this.gl.TEXTURE_2D, texture.Object);

        // Tell WebGL to use our shader program pair
        this.gl.useProgram(this.program);

        // Setup the attributes to pull data from our buffers
        this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.positionBuffer);
        this.gl.enableVertexAttribArray(this.positionLocation);
        this.gl.vertexAttribPointer(this.positionLocation, 2, this.gl.FLOAT, false, 0, 0);
        this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.textureCoordBuffer);
        this.gl.enableVertexAttribArray(this.textureCoordLocation);
        this.gl.vertexAttribPointer(this.textureCoordLocation, 2, this.gl.FLOAT, false, 0, 0);

        // This matirx will convert from pixels to clip space
        let matrix = Mat4.Orthographic(0, this.gl.canvas.width, this.gl.canvas.height, 0, -1, 1);

        // This matrix moves the origin to the one represented by
        // the current matrix stack.
        matrix = Mat4.Multiply(matrix, this.matrixStack.GetHead());

        // This matrix will translate our quad to dx, dy
        matrix = Mat4.Translate(matrix, dx, dy, 0);

        // This matrix will scale our 1 unit quad
        // from 1 unit to texture.Width, texture.Height units
        matrix = Mat4.Scale(matrix, dw, dh, 1);

        // Set the matrix.
        this.gl.uniformMatrix4fv(this.matrixLocation, false, matrix);

        // Because texture coordinates go from 0 to 1
        // and because our texture coordinates are already a unit quad
        // we can select an area of the texture by scaling the unit quad down
        let textureMatrix = Mat4.Translation(sx / texture.Width, sy / texture.Height, 0);

        textureMatrix = Mat4.Scale(textureMatrix, sw / texture.Width, sh / texture.Height, 1);

        // Set the texture matrix.
        this.gl.uniformMatrix4fv(this.textureMatrixLocation, false, textureMatrix);

        // Tell the shader to get the texture from texture unit 0
        this.gl.uniform1i(this.textureLocation, 0);

        // Draw the quad (2 triangles, 6 vertices)
        this.gl.drawArrays(this.gl.TRIANGLES, 0, 6);
    }

    private LoadTexture(url: string)
    {
        const texture = this.gl.createTexture();

        this.gl.bindTexture(this.gl.TEXTURE_2D, texture);

        // Fill the texture with a 1x1 debug pixel.
        this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, 1, 1, 0,
            this.gl.RGBA, this.gl.UNSIGNED_BYTE, Renderer.DebugColor);

        // Assume all images are not a power of 2
        this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);
        this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);
        this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);

        const info: ITextureInfo = {
            Width: 1,
            Height: 1,
            Object: texture
        };

        const image = new Image();

        image.addEventListener("load", () =>
        {
            info.Width = image.width;
            info.Height = image.height;

            this.gl.bindTexture(this.gl.TEXTURE_2D, info.Object);
            this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, image);
        });

        image.src = url;

        return info;
    }

    public async LoadTextures(): Promise<void>
    {
        const textures = ResourceManager.GetList().filter(r =>
            Resource.GetMeta(r.Buffer).Mime === "image/png");

        for(let resource of textures)
        {
            const uri = resource.Uri;

            this.textures[uri] = this.LoadTexture(resource.GetUrl());
        }
    }

    /**
     * Find a Vector under a pixel point.
     */
    public FindVectorByPixel(x: number, y: number): Vector
    {
        const view = this.viewport.Scale(this.dotPerPoint);

        let dx = this.dotPerPoint;
        let dy = this.dotPerPoint;

        dx *= this.canvas.clientWidth / view.X;
        dy *= this.canvas.clientHeight / view.Y;

        return new Vector(x / dx, y / dy);
    }

    /**
     * Draw the given unit onto the canvas.
     * @param unit
     */
    private DrawUnit(unit: Unit)
    {
        if(!unit || !unit.GetBody())
        {
            return;
        }

        const body = unit.GetBody();
        const position = body.GetPosition();
        const scale = body.GetScale();
        const rotation = body.GetRotation();
        const texture = this.textures[unit.GetTexture()];

        const s = scale.Scale(this.dotPerPoint);
        const c = (position.Sub(this.center).Add(this.viewport.Scale(0.5))).Scale(this.dotPerPoint);
        const p = c.Sub(s.Scale(0.5));

        this.matrixStack.Push();
        this.matrixStack.Translate(p.X + s.X / 2, p.Y + s.Y / 2);
        this.matrixStack.RotateZ(rotation);
        this.matrixStack.Translate(-s.X / 2, -s.Y / 2);

        this.DrawImage(texture,
            0, 0, texture.Width, texture.Height,
            0, 0, s.X, s.Y);

        this.matrixStack.Pop();
    }

    /**
     * Update the canvas.
     */
    private Render()
    {
        const view = this.viewport.Scale(this.dotPerPoint);

        this.canvas.width = view.X;
        this.canvas.height = view.Y;

        // Draw units in the order of their Z index
        const levels: Unit[][] = [];

        const process = (unit: Unit) =>
        {
            const z = unit.GetBody().GetZ();

            if(typeof this.selectedZ == "number" && this.selectedZ != z)
            {
                return;
            }

            if(!levels.hasOwnProperty(z))
            {
                levels[z] = [];
            }

            levels[z].push(unit);
        }

        this.world
            .GetCells()
            .GetArray()
            .forEach(process);

        this.world
            .GetActors()
            .GetArray()
            .forEach(process);

        // Tell WebGL how to convert from clip space to pixels
        this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
        this.gl.clear(this.gl.COLOR_BUFFER_BIT);

        for(let level of levels)
        {
            level && level.forEach(unit => this.DrawUnit(unit));
        }

        if(!this.stop)
        {
            window.requestAnimationFrame(() => this.Render());
        }

        const now = +new Date;
        const dt = Math.min((now - this.lastTick) / 1000, Renderer.MinFps);

        if(!this.noTick)
        {
            this.world.OnTick.Call(dt);
        }

        this.OnDraw.Call(dt);

        this.lastTick = now;
    }

    public SetCenter(center: Vector): void
    {
        this.center = center;
    }

    public Start(): void
    {
        this.lastTick = +new Date;
        this.stop = false;

        window.requestAnimationFrame(() => this.Render());
    }

    public Stop(): void
    {
        this.stop = true;
    }

    /**
     * Only the selected Z index will be rendered.
     */
    public SetSelectedZ(z: number)
    {
        this.selectedZ = z;
    }

    /**
     * The selected unit will have a border around it.
     */
    public SetSelectedUnit(unit: Unit)
    {
        this.selectedUnit = unit;
    }
}

class Mat4
{
    /**
     * Makes an identity matrix.
     */
    public static Identity()
    {
        const output = new Float32Array(16);

        output[0] = 1;
        output[1] = 0;
        output[2] = 0;
        output[3] = 0;
        output[4] = 0;
        output[5] = 1;
        output[6] = 0;
        output[7] = 0;
        output[8] = 0;
        output[9] = 0;
        output[10] = 1;
        output[11] = 0;
        output[12] = 0;
        output[13] = 0;
        output[14] = 0;
        output[15] = 1;

        return output;
    }

    /**
     * Multiply by a scaling matrix.
     * @param input
     * @param sx
     * @param sy
     * @param sz
     */
    public static Scale(input: Float32Array, sx: number, sy: number, sz: number)
    {
        const output = new Float32Array(16);

        output[0] = sx * input[0 * 4 + 0];
        output[1] = sx * input[0 * 4 + 1];
        output[2] = sx * input[0 * 4 + 2];
        output[3] = sx * input[0 * 4 + 3];
        output[4] = sy * input[1 * 4 + 0];
        output[5] = sy * input[1 * 4 + 1];
        output[6] = sy * input[1 * 4 + 2];
        output[7] = sy * input[1 * 4 + 3];
        output[8] = sz * input[2 * 4 + 0];
        output[9] = sz * input[2 * 4 + 1];
        output[10] = sz * input[2 * 4 + 2];
        output[11] = sz * input[2 * 4 + 3];

        if (input !== output)
        {
            output[12] = input[12];
            output[13] = input[13];
            output[14] = input[14];
            output[15] = input[15];
        }

        return output;
    }

    /**
     * Multiply by translation matrix.
     * @param input
     * @param tx
     * @param ty
     * @param tz
     */
    public static Translate(input: Float32Array, tx: number, ty: number, tz: number)
    {
        const output = new Float32Array(16);

        const m00 = input[0];
        const m01 = input[1];
        const m02 = input[2];
        const m03 = input[3];
        const m10 = input[1 * 4 + 0];
        const m11 = input[1 * 4 + 1];
        const m12 = input[1 * 4 + 2];
        const m13 = input[1 * 4 + 3];
        const m20 = input[2 * 4 + 0];
        const m21 = input[2 * 4 + 1];
        const m22 = input[2 * 4 + 2];
        const m23 = input[2 * 4 + 3];
        const m30 = input[3 * 4 + 0];
        const m31 = input[3 * 4 + 1];
        const m32 = input[3 * 4 + 2];
        const m33 = input[3 * 4 + 3];

        if (input !== output)
        {
            output[0] = m00;
            output[1] = m01;
            output[2] = m02;
            output[3] = m03;
            output[4] = m10;
            output[5] = m11;
            output[6] = m12;
            output[7] = m13;
            output[8] = m20;
            output[9] = m21;
            output[10] = m22;
            output[11] = m23;
        }

        output[12] = m00 * tx + m10 * ty + m20 * tz + m30;
        output[13] = m01 * tx + m11 * ty + m21 * tz + m31;
        output[14] = m02 * tx + m12 * ty + m22 * tz + m32;
        output[15] = m03 * tx + m13 * ty + m23 * tz + m33;

        return output;
    }

    /**
     * Makes a translation matrix.
     * @param tx
     * @param ty
     * @param tz
     */
    public static Translation(tx: number, ty: number, tz: number)
    {
        const output = new Float32Array(16);

        output[0] = 1;
        output[1] = 0;
        output[2] = 0;
        output[3] = 0;
        output[4] = 0;
        output[5] = 1;
        output[6] = 0;
        output[7] = 0;
        output[8] = 0;
        output[9] = 0;
        output[10] = 1;
        output[11] = 0;
        output[12] = tx;
        output[13] = ty;
        output[14] = tz;
        output[15] = 1;

        return output;
    }

    /**
     * Multiply by a Z rotation matrix.
     * @param other
     * @param angle
     */
    public static RotateZ(other: Float32Array, angle: number)
    {
        const output = new Float32Array(16);

        const m00 = other[0 * 4 + 0];
        const m01 = other[0 * 4 + 1];
        const m02 = other[0 * 4 + 2];
        const m03 = other[0 * 4 + 3];
        const m10 = other[1 * 4 + 0];
        const m11 = other[1 * 4 + 1];
        const m12 = other[1 * 4 + 2];
        const m13 = other[1 * 4 + 3];

        const c = Math.cos(angle);
        const s = Math.sin(angle);

        output[0] = c * m00 + s * m10;
        output[1] = c * m01 + s * m11;
        output[2] = c * m02 + s * m12;
        output[3] = c * m03 + s * m13;
        output[4] = c * m10 - s * m00;
        output[5] = c * m11 - s * m01;
        output[6] = c * m12 - s * m02;
        output[7] = c * m13 - s * m03;

        if (other !== output)
        {
            output[8] = other[8];
            output[9] = other[9];
            output[10] = other[10];
            output[11] = other[11];
            output[12] = other[12];
            output[13] = other[13];
            output[14] = other[14];
            output[15] = other[15];
        }

        return output;
    }

    /**
     * Computes a 4-by-4 orthographic projection matrix given the coordinates of the
     * planes defining the axis-aligned, box-shaped viewing volume. The matrix
     * generated sends that box to the unit box. Note that although left and right
     * are X coordinates and bottom and top are Y coordinates, near and far
     * are not Z coordinates, but rather they are distances along the negative
     * Z-axis. We assume a unit box extending from -1 to 1 in the X and Y
     * dimensions and from -1 to 1 in the Z dimension.
     * @param left The X coordinate of the left plane of the box.
     * @param right The X coordinate of the right plane of the box.
     * @param bottom The Y coordinate of the bottom plane of the box.
     * @param top The Y coordinate of the right plane of the box.
     * @param near The negative Z coordinate of the near plane of the box.
     * @param far The negative Z coordinate of the far plane of the box.
     */
    public static Orthographic(left: number, right: number, bottom: number,
        top: number, near: number, far: number)
    {
        const output = new Float32Array(16);

        output[0] = 2 / (right - left);
        output[1] = 0;
        output[2] = 0;
        output[3] = 0;
        output[4] = 0;
        output[5] = 2 / (top - bottom);
        output[6] = 0;
        output[7] = 0;
        output[8] = 0;
        output[9] = 0;
        output[10] = 2 / (near - far);
        output[11] = 0;
        output[12] = (left + right) / (left - right);
        output[13] = (bottom + top) / (bottom - top);
        output[14] = (near + far) / (near - far);
        output[15] = 1;

        return output;
    }

    /**
     * Multiply by translation matrix.
     * @param a
     * @param b
     */
    public static Multiply(a: Float32Array, b: Float32Array)
    {
        const output = new Float32Array(16);

        const b00 = b[0 * 4 + 0];
        const b01 = b[0 * 4 + 1];
        const b02 = b[0 * 4 + 2];
        const b03 = b[0 * 4 + 3];
        const b10 = b[1 * 4 + 0];
        const b11 = b[1 * 4 + 1];
        const b12 = b[1 * 4 + 2];
        const b13 = b[1 * 4 + 3];
        const b20 = b[2 * 4 + 0];
        const b21 = b[2 * 4 + 1];
        const b22 = b[2 * 4 + 2];
        const b23 = b[2 * 4 + 3];
        const b30 = b[3 * 4 + 0];
        const b31 = b[3 * 4 + 1];
        const b32 = b[3 * 4 + 2];
        const b33 = b[3 * 4 + 3];
        const a00 = a[0 * 4 + 0];
        const a01 = a[0 * 4 + 1];
        const a02 = a[0 * 4 + 2];
        const a03 = a[0 * 4 + 3];
        const a10 = a[1 * 4 + 0];
        const a11 = a[1 * 4 + 1];
        const a12 = a[1 * 4 + 2];
        const a13 = a[1 * 4 + 3];
        const a20 = a[2 * 4 + 0];
        const a21 = a[2 * 4 + 1];
        const a22 = a[2 * 4 + 2];
        const a23 = a[2 * 4 + 3];
        const a30 = a[3 * 4 + 0];
        const a31 = a[3 * 4 + 1];
        const a32 = a[3 * 4 + 2];
        const a33 = a[3 * 4 + 3];

        output[0] = b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30;
        output[1] = b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31;
        output[2] = b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32;
        output[3] = b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33;
        output[4] = b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30;
        output[5] = b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31;
        output[6] = b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32;
        output[7] = b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33;
        output[8] = b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30;
        output[9] = b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31;
        output[10] = b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32;
        output[11] = b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33;
        output[12] = b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30;
        output[13] = b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31;
        output[14] = b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32;
        output[15] = b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33;

        return output;
    }
}

export class Mat4Stack
{
    private stack: Float32Array[];

    public constructor()
    {
        this.stack = [];

        // Since the stack is empty this will put an initial matrix in it
        this.Pop();
    }

    /**
     * Gets a copy of the current matrix (top of the stack)
     */
    public GetHead()
    {
        return this.stack[this.stack.length - 1].slice();
    }

    /**
     * Lets us set the current matrix
     * @param mat
     */
    public SetHead(mat: Float32Array)
    {
        this.stack[this.stack.length - 1] = mat;

        return mat;
    }

    /**
     * Pops the top of the stack restoring the previously saved matrix
     */
    public Pop()
    {
        this.stack.pop();

        // Never let the stack be totally empty
        if (this.stack.length < 1) {
            this.stack[0] = Mat4.Identity();
        }
    }

    /**
     * Pushes a copy of the current matrix on the stack
     */
    public Push()
    {
        this.stack.push(this.GetHead());
    }

    /**
     * Scales the current matrix
     * @param x
     * @param y
     * @param z
     */
    public Scale(x: number, y: number, z: number = 1)
    {
        const mat = this.GetHead();

        this.SetHead(Mat4.Scale(mat, x, y, z));
    }

    /**
     * Translates the current matrix
     * @param x
     * @param y
     * @param z
     */
    public Translate(x: number, y: number, z: number = 0)
    {
        const mat = this.GetHead();

        this.SetHead(Mat4.Translate(mat, x, y, z));
    }

    /**
     * Rotates the current matrix around Z
     * @param angle
     */
    public RotateZ(angle: number)
    {
        const mat = this.GetHead();

        this.SetHead(Mat4.RotateZ(mat, angle));
    }
}


text:
<?php

namespace Google\AdsApi\AdManager\v202211;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class AdUnitCodeErrorReason
{
    const INVALID_CHARACTERS = 'INVALID_CHARACTERS';
    const INVALID_CHARACTERS_WHEN_UTF_CHARACTERS_ARE_ALLOWED = 'INVALID_CHARACTERS_WHEN_UTF_CHARACTERS_ARE_ALLOWED';
    const INVALID_CHARACTERS_FOR_LEGACY_AD_EXCHANGE_TAG = 'INVALID_CHARACTERS_FOR_LEGACY_AD_EXCHANGE_TAG';
    const LEADING_FORWARD_SLASH = 'LEADING_FORWARD_SLASH';
    const RESERVED_CODE = 'RESERVED_CODE';
    const UNKNOWN = 'UNKNOWN';

}