text:
#ifndef _RPC_INTERFACE_PROC_CLIENT_HELPER_H_
#define _RPC_INTERFACE_PROC_CLIENT_HELPER_H_

#include <refos-rpc/rpc.h>
#include <refos/refos.h>
#include <refos/error.h>
#include <refos-rpc/proc_client.h>
#include <refos-util/cspace.h>

/*! @file
    @brief Helper functions for the process server interface.

    This file contains a simple layer of helper functions that make using the procserv interface
    much easier, but are too complex to have been generated by the stub generator.
*/

/* Should mirror definitions in window.h. */
#define PROC_WINDOW_PERMISSION_WRITE 0x1
#define PROC_WINDOW_PERMISSION_READ 0x2
#define PROC_WINDOW_PERMISSION_READWRITE \
        (PROC_WINDOW_PERMISSION_WRITE | PROC_WINDOW_PERMISSION_READ)
#define PROC_WINDOW_FLAGS_UNCACHED 0x1

seL4_CPtr rpc_copyout_cptr(seL4_CPtr v);

/*! @brief Create a new sync endpoint. Helper function for proc_new_endpoint_internal().
    @return Recieved cap if success, 0 otherwise.
*/
static inline seL4_CPtr
proc_new_endpoint(void) {
    refos_err_t errnoRetVal = EINVALID;
    seL4_CPtr tcap = proc_new_endpoint_internal(&errnoRetVal);
    if (errnoRetVal != ESUCCESS || tcap == 0) {
        REFOS_SET_ERRNO(errnoRetVal);
        return 0;
    }
    REFOS_SET_ERRNO(ESUCCESS);
    return tcap;
}

/*! @brief Delete a created endpoint. */
static inline void
proc_del_endpoint(seL4_CPtr ep) {
    seL4_CNode_Delete(REFOS_CSPACE, ep, REFOS_CSPACE_DEPTH);
    csfree(ep);
}

/*! @brief Create a new sync endpoint. Helper function for proc_new_async_endpoint_internal().
    @return Recieved cap if success, 0 otherwise.
*/
static inline seL4_CPtr
proc_new_async_endpoint(void) {
    refos_err_t errnoRetVal = EINVALID;
    seL4_CPtr tcap = proc_new_async_endpoint_internal(&errnoRetVal);
    if (errnoRetVal != ESUCCESS || tcap == 0) {
        REFOS_SET_ERRNO(errnoRetVal);
        return 0;
    }
    REFOS_SET_ERRNO(ESUCCESS);
    return tcap;
}

/*! @brief Delete a created async endpoint. */
static inline void
proc_del_async_endpoint(seL4_CPtr ep) {
    seL4_CNode_Delete(REFOS_CSPACE, ep, REFOS_CSPACE_DEPTH);
    csfree(ep);
}

/*! @brief Create a new sync endpoint, and then mints a badged async endpoint from it, before
           discarding the capability to the original.
    @param badge The badge to mint endpoint with.
    @return Minted cap if success, 0 otherwise.
*/
static inline seL4_CPtr
proc_new_async_endpoint_badged(int badge) {
    seL4_CPtr tcap = proc_new_async_endpoint();
    if (!tcap) {
        return 0;
    }
    seL4_CPtr bgcap = csalloc();
    if (!bgcap) {
        proc_del_async_endpoint(tcap);
        REFOS_SET_ERRNO(ENOMEM);
        return 0;
    }
    /* Mint the badged cap. */
    int error = seL4_CNode_Mint (
        REFOS_CSPACE, bgcap, REFOS_CDEPTH,
        REFOS_CSPACE, tcap, REFOS_CDEPTH,
        seL4_AllRights, seL4_CapData_Badge_new(badge)
    );
    if (error != seL4_NoError) {
        proc_del_async_endpoint(tcap);
        REFOS_SET_ERRNO(EINVALID);
        return 0;
    }
    proc_del_async_endpoint(tcap);
    REFOS_SET_ERRNO(ESUCCESS);
    return bgcap;
}

/*! @brief Create a new memory window segment (with extra parameters). Helper function for
           proc_create_mem_window_internal().
    @param vaddr The window base address in the calling client's VSpace.
    @param size The size of the mem window.
    @param permissions The read / write permission bitmask.
    @param permissions The flags bitmask (cached / uncached).
    @return Capability to created window if success, 0 otherwise (errno will be set).
*/
static inline seL4_CPtr
proc_create_mem_window_ext(uint32_t vaddr, uint32_t size, uint32_t permission, uint32_t flags)
{
    refos_err_t errnoRetVal = EINVALID;
    seL4_CPtr tcap = proc_create_mem_window_internal(vaddr, size, permission, flags, &errnoRetVal);
    if (errnoRetVal != ESUCCESS || tcap == 0) {
        REFOS_SET_ERRNO(errnoRetVal);
        return 0;
    }
    REFOS_SET_ERRNO(ESUCCESS);
    return tcap;
}

/*! @brief Create a new memory window segment. Helper function for
           proc_create_mem_window_internal(). Permission is set to PROC_WINDOW_PERMISSION_READWRITE,
           and flags 0x0.
    @param vaddr The window base address in the calling client's VSpace.
    @param size The size of the mem window.
    @return Capability to created window if success, 0 otherwise (errno will be set).
*/
static inline seL4_CPtr
proc_create_mem_window(uint32_t vaddr, uint32_t size)
{
    return proc_create_mem_window_ext(vaddr, size, PROC_WINDOW_PERMISSION_READWRITE, 0x0);
}

/*! @brief Clones a new thread for process. Helper function for proc_clone_internal().
    @param func The entry point function of the new thread.
    @param childStack The stack vaddr of the new thread.
    @param flags Unused, must be 0.
    @param arg Unused, must be 0.
    @return threadID if success, negative if error occured (errno will be set).
*/
static inline int
proc_clone(int (*func)(void *), void *childStack, int flags, void *arg)
{
    (void) flags;
    refos_err_t errnoRetVal = EINVALID;
    int threadID = proc_clone_internal((seL4_Word) func, (seL4_Word) childStack, flags,
            (seL4_Word) arg, &errnoRetVal);
    REFOS_SET_ERRNO(errnoRetVal);
    return threadID;
}

#endif /* _RPC_INTERFACE_PROC_CLIENT_HELPER_H_ */

redpajama_set_name: RedPajamaGithub


text:
namespace Assertions
{
    using System;
    using System.Diagnostics;

    public class Program
    {
        public static void SelectionSort<T>(T[] arr) where T : IComparable<T>
        {
            for (int index = 0; index < arr.Length - 1; index++)
            {
                int minElementIndex = FindMinElementIndex(arr, index, arr.Length - 1);
                Swap(ref arr[index], ref arr[minElementIndex]);
            }
        }

        public static int BinarySearch<T>(T[] arr, T value) where T : IComparable<T>
        {
            return BinarySearch(arr, value, 0, arr.Length - 1);
        }

        public static void Main()
        {
            int[] arr = new int[] { 3, -1, 15, 4, 17, 2, 33, 0 };
            Console.WriteLine("arr = [{0}]", string.Join(", ", arr));
            SelectionSort(arr);
            Console.WriteLine("sorted = [{0}]", string.Join(", ", arr));

            SelectionSort(new int[0]); // Test sorting empty array
            SelectionSort(new int[1]); // Test sorting single element array

            Console.WriteLine(BinarySearch(arr, -1000));
            Console.WriteLine(BinarySearch(arr, 0));
            Console.WriteLine(BinarySearch(arr, 17));
            Console.WriteLine(BinarySearch(arr, 10));
            Console.WriteLine(BinarySearch(arr, 1000));
        }

        private static int FindMinElementIndex<T>(T[] arr, int startIndex, int endIndex)
            where T : IComparable<T>
        {
            Debug.Assert(arr != null, "Array cannot be null");

            int minElementIndex = startIndex;
            for (int i = startIndex + 1; i <= endIndex; i++)
            {
                if (arr[i].CompareTo(arr[minElementIndex]) < 0)
                {
                    minElementIndex = i;
                }
            }

            return minElementIndex;
        }

        private static void Swap<T>(ref T x, ref T y)
        {
            T oldX = x;
            x = y;
            y = oldX;
        }

        private static int BinarySearch<T>(T[] arr, T value, int startIndex, int endIndex)
            where T : IComparable<T>
        {
            Debug.Assert(arr != null, "Array cannot be null");

            while (startIndex <= endIndex)
            {
                int midIndex = (startIndex + endIndex) / 2;
                if (arr[midIndex].Equals(value))
                {
                    return midIndex;
                }

                if (arr[midIndex].CompareTo(value) < 0)
                {
                    // Search on the right half
                    startIndex = midIndex + 1;
                }
                else
                {
                    // Search on the right half
                    endIndex = midIndex - 1;
                }
            }

            // Searched value not found
            return -1;
        }
    }
}


text:
namespace app { namespace Fuse { namespace Animations { struct MixerBase; } } }
namespace app { namespace Uno { namespace UX { struct Property__Fuse_Elements_TextAlignment; } } }

namespace app {
namespace Fuse {
namespace Animations {

struct MasterProperty__Fuse_Elements_TextAlignment;

struct MasterProperty__Fuse_Elements_TextAlignment__uType : ::app::Fuse::Animations::MasterBase__Fuse_Elements_TextAlignment__uType
{
    ::app::Fuse::Animations::MasterPropertyGet __interface_1;
};

MasterProperty__Fuse_Elements_TextAlignment__uType* MasterProperty__Fuse_Elements_TextAlignment__typeof();

void MasterProperty__Fuse_Elements_TextAlignment___ObjInit_1(MasterProperty__Fuse_Elements_TextAlignment* __this, ::app::Uno::UX::Property__Fuse_Elements_TextAlignment* property, ::app::Fuse::Animations::MixerBase* mixerBase);
int MasterProperty__Fuse_Elements_TextAlignment__get_RestValue(MasterProperty__Fuse_Elements_TextAlignment* __this);
::uObject* MasterProperty__Fuse_Elements_TextAlignment__GetPropertyObject(MasterProperty__Fuse_Elements_TextAlignment* __this);
void MasterProperty__Fuse_Elements_TextAlignment__OnInactive(MasterProperty__Fuse_Elements_TextAlignment* __this);

struct MasterProperty__Fuse_Elements_TextAlignment : ::app::Fuse::Animations::MasterBase__Fuse_Elements_TextAlignment
{
    ::uStrong< ::app::Uno::UX::Property__Fuse_Elements_TextAlignment*> Property;

    void _ObjInit_1(::app::Uno::UX::Property__Fuse_Elements_TextAlignment* property, ::app::Fuse::Animations::MixerBase* mixerBase) { MasterProperty__Fuse_Elements_TextAlignment___ObjInit_1(this, property, mixerBase); }
    ::uObject* GetPropertyObject() { return MasterProperty__Fuse_Elements_TextAlignment__GetPropertyObject(this); }
};

}}}

#endif


text:
Action::Action() : container(0), acting(false) {}

void Action::setContainer(MotorsContainer* container) {
  this->container = container;
}

bool Action::update(bool resetNotifications) {
  if (resetNotifications) {
    this->resetNotifications();
  }
  if (this->isNotified() || this->acting) {
    if (this->container != 0) {
      this->act();
    }
    this->resetNotifications();
    return true;
  }
  return false;
}


text:
<?php
namespace app\components;

use yii\base\Widget;
use yii\helpers\Html;

class AnamnesePdfWidget extends Widget{

    public $data;

    public function run(){
        return $this->render('anamnesePdf',['data' => $this->data]);
    }
}
?>


text:
"""
Command line command to run tests
"""

import nose
from percept.management.commands import BaseCommand
from percept.conf.base import settings
import pkgutil
from importlib import import_module
from optparse import make_option

import os

class Command(BaseCommand):
    args = 'cover'
    def command(self, *args, **options):
        try:
            cover = args[0]
            cover = cover.lower() == "true"
        except IndexError:
            cover = False
        if cover:
            #Grab the pythonpath argument and look for tests there
            app_names = settings.INSTALLED_APPS
            #Grab the top level app name from installed_apps
            app_labels = list(set([a.split('.')[0] for a in app_names]))
            app_paths = []
            #We want to figure out coverage for the "lower-level" apps, so import all the top level apps
            #and get their paths
            for al in app_labels:
                mod = import_module(al)
                app_paths.append(os.path.dirname(mod.__file__))
            #Pass paths to pkgutil to get the names of the submodules
            sub_labels = [name for _, name, _ in pkgutil.iter_modules(app_paths) if name not in settings.DO_NOT_COVER]
            #Produce a coverage report for installed_apps
            argv = ['{0}'.format(options['pythonpath']), '--with-coverage', '--cover-package={0}'.format(','.join(app_labels + sub_labels))]
            nose.run(argv=argv)
        else:
            argv = ['{0}'.format(options['pythonpath'])]
            nose.run(argv=argv)


text:
                    Explain your ideal vacation.

                            <input type="checkbox" name="vehicle" value="Bike">Beaches
                            <input type="checkbox" name="vehicle" value="Car">Woods

{{card.id}}


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <PreferenceCategory android:title="Service" >

        <CheckBoxPreference
            android:defaultValue="false"
            android:key="service"
            android:summary="Ladda ned väder i bakgrunden"
            android:title="Bakgrundstjänst" />

        <ListPreference
            android:defaultValue="30"
            android:dependency="service"
            android:entries="@array/updateInterval"
            android:entryValues="@array/updateIntervalValues"
            android:key="updates_interval"
            android:summary="Hur ofta vädret ska laddas ned"
            android:title="Uppdaterings intervall" />

        <CheckBoxPreference
            android:defaultValue="false"
            android:key="notification"
            android:dependency="service"
            android:summary="Om notifikationer ska skickas"
            android:title="Skicka notifikationer" />
    </PreferenceCategory>

    <PreferenceCategory android:title="Widget" >

        <CheckBoxPreference
            android:defaultValue="false"
            android:icon="@drawable/suncloudy"
            android:key="moreInfo"
            android:summary="Om det ska visas mer infomation om vädret"
            android:title="Mer information" />
    </PreferenceCategory>

    <PreferenceCategory android:title="Wallpaper" >

        <CheckBoxPreference
            android:defaultValue="false"
            android:icon="@drawable/sunny"
            android:key="animate_wallpaper"
            android:summary="Animerar bilden på vädret"
            android:title="Animera bilden" />
    </PreferenceCategory>

    <PreferenceCategory android:title="Daydreaming" >

        <CheckBoxPreference
            android:defaultValue="false"
            android:icon="@drawable/sunny"
            android:key="animate_daydream"
            android:summary="Animerar bilden på vädret"
            android:title="Animera bilden" />
    </PreferenceCategory>

</PreferenceScreen>


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<merge
    xmlns:latin="http://schemas.android.com/apk/res/com.udmurtlyk.extrainputmethod.latin"
>
    <include
        latin:keyboardLayout="@xml/key_styles_common" />
    <Row
        latin:keyWidth="9.0%p"
    >
        <include
            latin:keyboardLayout="@xml/rowkeys_qwerty1" />
        <Key
            latin:keyStyle="deleteKeyStyle"
            latin:keyWidth="fillRight" />
    </Row>
    <Row
        latin:keyWidth="9.0%p"
    >
        <include
            latin:keyboardLayout="@xml/rowkeys_qwerty2"
            latin:keyXPos="4.5%p" />
        <Key
            latin:keyStyle="enterKeyStyle"
            latin:keyWidth="fillRight" />
    </Row>
    <Row
        latin:keyWidth="9.0%p"
    >
        <Key
            latin:keyStyle="shiftKeyStyle"
            latin:keyWidth="10.0%p" />
        <include
            latin:keyboardLayout="@xml/rowkeys_qwerty3" />
        <include
            latin:keyboardLayout="@xml/keys_exclamation_question" />
        <Key
            latin:keyStyle="shiftKeyStyle"
            latin:keyWidth="fillRight" />
    </Row>
    <include
        latin:keyboardLayout="@xml/row_qwerty4" />
</merge>


text:
/*
 * This source file is based on code taken from SQLLine 1.0.2
 * See SQLLine notice in LICENSE
 */
package org.apache.hive.beeline;

import java.util.List;

import jline.console.completer.Completer;
import jline.console.completer.StringsCompleter;

class TableNameCompletor implements Completer {
  private final BeeLine beeLine;

  /**
   * @param beeLine
   */
  TableNameCompletor(BeeLine beeLine) {
    this.beeLine = beeLine;
  }

  public int complete(String buf, int pos, List cand) {
    if (beeLine.getDatabaseConnection() == null) {
      return -1;
    }
    return new StringsCompleter(beeLine.getDatabaseConnection().getTableNames(true))
        .complete(buf, pos, cand);
  }
}


text:
module Dissent.Protocol.Shuffle where

import qualified Control.Concurrent.Async        as A (Async, async, wait)

import qualified Dissent.Quorum                  as Q

import qualified Dissent.Types.Quorum            as TQ
import qualified Dissent.Types.Peer              as TP

import qualified Dissent.Protocol.Shuffle.Leader as SL
import qualified Dissent.Protocol.Shuffle.Leader as SS

run :: TQ.Quorum -> IO ()
run quorum =
  let runLeader :: IO (A.Async ())
      runLeader = A.async (SL.run quorum)

      runSlave  :: IO (A.Async ())
      runSlave  = A.async (SS.run quorum)

      actions :: TP.Type -> IO [A.Async ()]
      actions TP.Leader = sequence [ runLeader
                                   , runSlave ]
      actions TP.Slave  = sequence [ runSlave ]

      waitAll :: [A.Async ()] -> IO ()
      waitAll = mapM_ A.wait

  in
    waitAll =<< actions (Q.selfPeerType quorum)


text:
'use strict';

const express = require('express');
const { appendLocals } = require('../lib/helpers');

const router = express.Router();

router.get('/', (req, res) => {
    res = appendLocals(req, res);
    res.status(404).render('404', {
        title: 'Page Not Found'
    });
});

module.exports = router;

// vim: ft=javascript sw=4 sts=4 et:


text:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;

public class ChangeTownNamesCasing
{
    public static void Main(string[] args)
    {
        string connectionString = "Server=.; Database=MinionsDB; Trusted_Connection=True";
        SqlConnection connection = new SqlConnection(connectionString);

        string countryName = Console.ReadLine();
        List<string> allTownsInCountry = new List<string>();
        bool hasUpdated = false;
        using (connection)
        {
            connection.Open();
            allTownsInCountry = GetAllTownsInCountry(countryName, connection);

            if (allTownsInCountry.Any())
            {
                int countryId = GetCountryId(countryName, connection);
                UpdateTowns(countryId, connection);
                hasUpdated = true;
            }
        }

        if (hasUpdated)
        {
            Console.WriteLine($"{allTownsInCountry.Count} town names were affected.");
            Console.WriteLine($"[{string.Join(", ", allTownsInCountry.Select(c => c.ToUpper()))}]");
        }
        else
        {
            Console.WriteLine("No town names were affected.");
        }
    }

    private static int GetCountryId(string countryName, SqlConnection connection)
    {
        string commandString =
            "SELECT TOP 1 c.CountryID FROM Countries AS c WHERE c.Name = @countryName ORDER BY c.CountryID";
        SqlCommand command = new SqlCommand(commandString, connection);
        command.Parameters.AddWithValue("@countryName", countryName);

        int countryId = (int)command.ExecuteScalar();

        return countryId;
    }

    private static void UpdateTowns(int countryId, SqlConnection connection)
    {
        string commandString = "UPDATE Towns " +
                               "SET Name = UPPER(Name) " +
                               "WHERE CountryID = @countryId";
        SqlCommand command = new SqlCommand(commandString, connection);
        command.Parameters.AddWithValue("@countryId", countryId);
        command.ExecuteNonQuery();
    }

    private static List<string> GetAllTownsInCountry(string countryName, SqlConnection connection)
    {
        List<string> towns = new List<string>();
        string commandString = "SELECT t.Name FROM Countries AS c " +
                               "INNER JOIN Towns AS t " +
                               "ON t.CountryID = c.CountryID " +
                               "WHERE c.Name = @countryName";

        SqlCommand command = new SqlCommand(commandString, connection);
        command.Parameters.AddWithValue("@countryName", countryName);
        SqlDataReader reader = command.ExecuteReader();

        using (reader)
        {
            while (reader.Read())
            {
                towns.Add(reader[0].ToString());
            }
        }

        return towns;
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.DataMigration.Models
{
    public partial class ValidateMigrationInputSqlServerSqlMITaskOutput
    {
        internal static ValidateMigrationInputSqlServerSqlMITaskOutput DeserializeValidateMigrationInputSqlServerSqlMITaskOutput(JsonElement element)
        {
            Optional<string> id = default;
            Optional<string> name = default;
            Optional<IReadOnlyList<ReportableException>> restoreDatabaseNameErrors = default;
            Optional<IReadOnlyList<ReportableException>> backupFolderErrors = default;
            Optional<IReadOnlyList<ReportableException>> backupShareCredentialsErrors = default;
            Optional<IReadOnlyList<ReportableException>> backupStorageAccountErrors = default;
            Optional<IReadOnlyList<ReportableException>> existingBackupErrors = default;
            Optional<DatabaseBackupInfo> databaseBackupInfo = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("restoreDatabaseNameErrors"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<ReportableException> array = new List<ReportableException>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(ReportableException.DeserializeReportableException(item));
                    }
                    restoreDatabaseNameErrors = array;
                    continue;
                }
                if (property.NameEquals("backupFolderErrors"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<ReportableException> array = new List<ReportableException>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(ReportableException.DeserializeReportableException(item));
                    }
                    backupFolderErrors = array;
                    continue;
                }
                if (property.NameEquals("backupShareCredentialsErrors"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<ReportableException> array = new List<ReportableException>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(ReportableException.DeserializeReportableException(item));
                    }
                    backupShareCredentialsErrors = array;
                    continue;
                }
                if (property.NameEquals("backupStorageAccountErrors"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<ReportableException> array = new List<ReportableException>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(ReportableException.DeserializeReportableException(item));
                    }
                    backupStorageAccountErrors = array;
                    continue;
                }
                if (property.NameEquals("existingBackupErrors"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<ReportableException> array = new List<ReportableException>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(ReportableException.DeserializeReportableException(item));
                    }
                    existingBackupErrors = array;
                    continue;
                }
                if (property.NameEquals("databaseBackupInfo"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    databaseBackupInfo = DatabaseBackupInfo.DeserializeDatabaseBackupInfo(property.Value);
                    continue;
                }
            }
            return new ValidateMigrationInputSqlServerSqlMITaskOutput(id.Value, name.Value, Optional.ToList(restoreDatabaseNameErrors), Optional.ToList(backupFolderErrors), Optional.ToList(backupShareCredentialsErrors), Optional.ToList(backupStorageAccountErrors), Optional.ToList(existingBackupErrors), databaseBackupInfo.Value);
        }
    }
}


text:
<?php

namespace Slim;

use \Psr\Http\Message\RequestInterface;
use \Psr\Http\Message\ResponseInterface;

/**
 * Default not found handler
 *
 * This is the default Slim application not found handler. All it does is output
 * a clean and simple HTML page with diagnostic information.
 */
class NotFoundHandler
{
    /**
     * Invoke not found handler
     *
     * @param  RequestInterface  $request   The most recent Request object
     * @param  ResponseInterface $response  The most recent REsposne object
     * @return ResponseInterface            The final Response object
     */
    public function __invoke(RequestInterface $request, ResponseInterface $response)
    {
        $response = $response
            ->withStatus(404)
            ->withHeader('Content-Type', 'text/html')
            ->withBody(new Http\Body(fopen('php://temp', 'r+')));

        $response->write($this->generateTemplateMarkup(
            '404 Page Not Found',
            '
The page you are looking for could not be found. Check the address bar to ensure your URL is spelled ' .
            'correctly. If all else fails, you can visit our home page at the link below.
getUri()->getBasePath() . '">Visit the Home Page'
        ));

        return $response;
    }

    /**
     * Generate diagnostic template markup
     *
     * This method accepts a title and body content to generate an HTML document layout.
     *
     * @param  string $title The title of the HTML template
     * @param  string $body  The body content of the HTML template
     * @return string
     */
    protected function generateTemplateMarkup($title, $body)
    {
        return sprintf(
            "<title>%s</title>
%s
%s",
            $title,
            $title,
            $body
        );
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tibialyzer {
    public partial class Outfiter : Form, TabInterface {
        PictureBox colorPicker;
        private OutfiterOutfit outfit = new OutfiterOutfit();
        private int colorIndex = 0;
        private Dictionary<string, int> outfitMap = new Dictionary<string, int>();
        private Dictionary<string, int> mountMap = new Dictionary<string, int>();

        public Outfiter() {
            InitializeComponent();
            InitializeSettings();
            ApplyLocalization();

            outfit.facing = Facing.Down;

            outfitList.Items.Clear();
            List<string> sortedItems = new List<string>();
            for(int i = 0; i < OutfiterManager.outfiterOutfitNames.Count; i++) {
                string outfit = OutfiterManager.outfiterOutfitNames[i].Replace('_', ' ');
                sortedItems.Add(outfit);
                outfitMap.Add(outfit, i);
            }
            sortedItems.Sort();
            outfitList.Items.AddRange(sortedItems.ToArray());
            sortedItems.Clear();

            mountsList.Items.Clear();
            for (int i = 0; i < OutfiterManager.outfiterMountNames.Count; i++) {
                string mount = OutfiterManager.outfiterMountNames[i].Replace('_', ' ');
                sortedItems.Add(mount);
                mountMap.Add(mount, i);
            }
            mountsList.Items.AddRange(sortedItems.OrderBy(o => o == "None" ? "--" : o).ToArray());
            sortedItems.Clear();

            outfitList.SelectedIndex = 0;
            mountsList.SelectedIndex = 0;

            outfitList.ReadOnly = true;
            mountsList.ReadOnly = true;

            colorPicker = new PictureBox();
            colorPicker.Location = new Point(headColorButton.Location.X + headColorButton.Width + 10, headColorButton.Location.Y);
            colorPicker.Size = new Size(OutfiterManager.OutfitColorBoxSize * OutfiterManager.OutfitColorsPerRow, OutfiterManager.OutfitColorBoxSize * 7);
            colorPicker.Image = null;
            colorPicker.MouseDown += ChangeOutfitColor;
            this.Controls.Add(colorPicker);
            RefreshColorPicker(0);
        }

        private void RefreshColorPicker(int colorIndex) {
            this.colorIndex = colorIndex;
            headColorButton.Enabled = true;
            primaryColorButton.Enabled = true;
            secondaryColorButton.Enabled = true;
            detailColorButton.Enabled = true;
            switch(colorIndex) {
                case 0: headColorButton.Enabled = false; break;
                case 1: primaryColorButton.Enabled = false; break;
                case 2: secondaryColorButton.Enabled = false; break;
                case 3: detailColorButton.Enabled = false; break;
            }
            Image oldImage = colorPicker.Image;
            colorPicker.Image = OutfiterManager.GenerateColorImage(outfit.colors[colorIndex]);
            if (oldImage != null) {
                oldImage.Dispose();
            }
        }

        private void ChangeOutfitColor(object sender, MouseEventArgs e) {
            int index = OutfiterManager.ColorIndex(e.X, e.Y);
            if (index < 0) return;
            outfit.colors[colorIndex] = index;
            RefreshColorPicker(colorIndex);
            RefreshImage();
        }

        public void InitializeSettings() {
        }

        public void ApplyLocalization() {
        }

        public void RefreshImage() {
            Image oldImage = outfiterImageBox.Image;
            outfiterImageBox.Image = outfit.GetImage();
            if (oldImage != null) {
                oldImage.Dispose();
            }
            outfiterCode.Text = outfit.ToString();
        }

        private void outfitList_SelectedIndexChanged(object sender, EventArgs e) {
            if (refreshing_controls) return;
            if ((sender as ListBox).SelectedIndex < 0) return;
            outfit.outfit = outfitMap[(sender as ListBox).Items[(sender as ListBox).SelectedIndex].ToString()];
            RefreshImage();
        }

        private void mountsList_SelectedIndexChanged(object sender, EventArgs e) {
            if (refreshing_controls) return;
            if ((sender as ListBox).SelectedIndex < 0) return;
            outfit.mount = mountMap[(sender as ListBox).Items[(sender as ListBox).SelectedIndex].ToString()];
            RefreshImage();
        }

        private void headColorButton_Click(object sender, EventArgs e) {
            RefreshColorPicker(0);
        }

        private void primaryColorButton_Click(object sender, EventArgs e) {
            RefreshColorPicker(1);
        }

        private void secondaryColorButton_Click(object sender, EventArgs e) {
            RefreshColorPicker(2);
        }

        private void detailColorButton_Click(object sender, EventArgs e) {
            RefreshColorPicker(3);
        }

        private void femaleCheckbox_CheckedChanged(object sender, EventArgs e) {
            if (refreshing_controls) return;
            outfit.gender = (sender as CheckBox).Checked ? Gender.Female : Gender.Male;
            RefreshImage();
        }

        private void addon1Checkbox_CheckedChanged(object sender, EventArgs e) {
            if (refreshing_controls) return;
            outfit.addon1 = (sender as CheckBox).Checked;
            RefreshImage();
        }

        private void addon2Checkbox_CheckedChanged(object sender, EventArgs e) {
            if (refreshing_controls) return;
            outfit.addon2 = (sender as CheckBox).Checked;
            RefreshImage();
        }

        private void viewOnTibiaWikiButton_Click(object sender, EventArgs e) {
            MainForm.OpenUrl("http://tibia.wikia.com/wiki/Outfiter?" + outfit.ToString());
        }

        private void saveOutfitImageButton_Click(object sender, EventArgs e) {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.AddExtension = true;
            dialog.DefaultExt = "png";
            dialog.Title = "Save Outfit Image";
            string baseName = String.Format("outfit_{0}_{1}", OutfiterManager.outfiterOutfitNames[outfit.outfit], OutfiterManager.outfiterMountNames[outfit.mount]);
            if (File.Exists(baseName + ".png")) {
                int i = 1;
                while (File.Exists(baseName + " (" + i.ToString() + ").png")) i++;
                dialog.FileName = baseName + " (" + i.ToString() + ").png";
            } else {
                dialog.FileName = baseName + ".png";
            }
            DialogResult result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK) {
                using (Bitmap outfitImage = outfit.GetImage() as Bitmap) {
                    using(Image clampedImage = outfitImage.Clamp()) {
                        clampedImage.Save(dialog.FileName);
                    }
                }
            }
        }

        private void applyButton_Click(object sender, EventArgs e) {
            outfit.FromString(outfiterCode.Text);
            RefreshImage();
            RefreshOutfitControls();
        }

        private void rotateLeftButton_Click(object sender, EventArgs e) {
            outfit.Rotate(-1);
            RefreshImage();
        }

        private void rotateRightButton_Click(object sender, EventArgs e) {
            outfit.Rotate(1);
            RefreshImage();
        }

        private void randomizeButton_Click(object sender, EventArgs e) {
            outfit.facing = Facing.Down;
            outfit.colors[0] = Constants.Random.Next(OutfiterManager.outfitColors.Count);
            outfit.colors[1] = Constants.Random.Next(OutfiterManager.outfitColors.Count);
            outfit.colors[2] = Constants.Random.Next(OutfiterManager.outfitColors.Count);
            outfit.colors[3] = Constants.Random.Next(OutfiterManager.outfitColors.Count);
            outfit.outfit = Constants.Random.Next(OutfiterManager.outfiterOutfitNames.Count);
            outfit.mount = Constants.Random.Next(OutfiterManager.outfiterMountNames.Count);
            outfit.addon1 = Constants.Random.Next(10) > 5;
            outfit.addon2 = Constants.Random.Next(10) > 5;
            outfit.gender = Constants.Random.Next(10) > 5 ? Gender.Male : Gender.Female;
            RefreshColorPicker(0);
            RefreshImage();
            RefreshOutfitControls();
        }

        private bool refreshing_controls = false;
        private void RefreshOutfitControls() {
            refreshing_controls = true;
            outfitList.SelectedIndex = outfit.outfit;
            mountsList.SelectedIndex = outfit.mount;
            addon1Checkbox.Checked = outfit.addon1;
            addon2Checkbox.Checked = outfit.addon2;
            femaleCheckbox.Checked = outfit.gender == Gender.Female;
            refreshing_controls = false;
        }
    }
}


text:
<?php

namespace craft\controllers;

use Craft;
use craft\helpers\Assets;
use craft\helpers\FileHelper;
use craft\helpers\Image;
use craft\web\Controller;
use craft\web\UploadedFile;
use yii\web\Response;

Craft::$app->requireEdition(Craft::Pro);

/**
 * The RebrandController class is a controller that handles various control panel re-branding tasks such as uploading,
 * cropping and deleting site logos and icons.
 * Note that all actions in the controller require an authenticated Craft session via [[allowAnonymous]].
 *
 * @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
 * @since 3.0
 */
class RebrandController extends Controller
{
    /**
     * Allowed types of site images.
     *
     * @var array
     */
    private $_allowedTypes = ['logo', 'icon'];

    // Public Methods
    // =========================================================================

    /**
     * Handles Control Panel logo and site icon uploads.
     *
     * @return Response
     */
    public function actionUploadSiteImage(): Response
    {
        $this->requireAcceptsJson();
        $this->requireAdmin();
        $type = Craft::$app->getRequest()->getRequiredBodyParam('type');

        if (!in_array($type, $this->_allowedTypes, true)) {
            return $this->asErrorJson(Craft::t('app', 'That is not an allowed image type.'));
        }

        // Grab the uploaded file
        if (($file = UploadedFile::getInstanceByName('image')) === null) {
            return $this->asErrorJson(Craft::t('app', 'There was an error uploading your photo'));
        }

        $filename = Assets::prepareAssetName($file->name, true, true);

        if (!Image::canManipulateAsImage($file->getExtension())) {
            return $this->asErrorJson(Craft::t('app', 'The uploaded file is not an image.'));
        }

        $targetPath = Craft::$app->getPath()->getRebrandPath().'/'.$type.'/';

        if (!is_dir($targetPath)) {
            FileHelper::createDirectory($targetPath);
        } else {
            FileHelper::clearDirectory($targetPath);
        }

        $fileDestination = $targetPath.'/'.$filename;

        move_uploaded_file($file->tempName, $fileDestination);

        $imagesService = Craft::$app->getImages();
        $imagesService->cleanImage($fileDestination);
        $imagesService->loadImage($fileDestination)->scaleToFit(300, 300)->saveAs($fileDestination);
        $html = $this->getView()->renderTemplate('settings/general/_images/'.$type);

        return $this->asJson([
            'html' => $html,
        ]);
    }

    /**
     * Deletes Control Panel logo and site icon images.
     *
     * @return Response
     */
    public function actionDeleteSiteImage(): Response
    {
        $this->requireAdmin();
        $type = Craft::$app->getRequest()->getRequiredBodyParam('type');

        if (!in_array($type, $this->_allowedTypes, true)) {
            $this->asErrorJson(Craft::t('app', 'That is not an allowed image type.'));
        }

        FileHelper::clearDirectory(Craft::$app->getPath()->getRebrandPath().'/'.$type);

        $html = $this->getView()->renderTemplate('settings/general/_images/'.$type);

        return $this->asJson([
            'html' => $html,
        ]);
    }
}


text:
import React from "react";
import PropTypes from "prop-types";
import { css } from "emotion";
import { CaretDownMUI, CaretDownSUI } from "@hig/icons";
import Input from "@hig/input";
import ThemeContext from "@hig/theme-context";

import stylesheet from "./InputPresenter.stylesheet";

function customStylesheet(inputStylesheet, props, themeData) {
  const { multiple, variant } = props;

  return {
    ...inputStylesheet,
    input: {
      ...inputStylesheet.input,
      cursor: `pointer`,
      whiteSpace: `nowrap`,
      textOverflow: `ellipsis`,
      fontStyle: multiple ? `italic` : {},
      paddingRight:
        variant === `line`
          ? `calc(${themeData["density.spacings.large"]} + ${themeData["input.line.paddingHorizontal"]}px)`
          : `calc(${themeData["density.spacings.large"]} + ${themeData["input.box.paddingHorizontal"]})`,
    },
  };
}

export default function InputPresenter(props) {
  const {
    isOpen,
    multiple,
    onChange,
    onInputChange,
    stylesheet: userStylesheet,
    typable,
    ...otherProps
  } = props;
  const dropdownInputStylesheet = (styles, componentProps, themeData) => {
    const dropdownInputStyles = customStylesheet(
      styles,
      componentProps,
      themeData
    );
    return userStylesheet
      ? userStylesheet(dropdownInputStyles, componentProps, themeData)
      : dropdownInputStyles;
  };
  const handleChange = (event) => {
    onChange(event);

    if (onInputChange) {
      onInputChange(event);
    }
  };

  return (
    <ThemeContext.Consumer>
      {({ resolvedRoles, metadata }) => {
        const CaretIcon =
          metadata.densityId === `medium-density` ? CaretDownMUI : CaretDownSUI;
        const iconColor = isOpen
          ? resolvedRoles[`colorScheme.indicator.on`]
          : resolvedRoles[`input.indicator.default`];

        return (
          <div className={css(stylesheet(props, resolvedRoles).inputWrapper)}>
            <Input
              {...otherProps}
              multiple={multiple}
              onChange={handleChange}
              readOnly={!typable}
              stylesheet={dropdownInputStylesheet}
            />
            <CaretIcon
              style={stylesheet(props, resolvedRoles).caret}
              color={iconColor}
            />
          </div>
        );
      }}
    </ThemeContext.Consumer>
  );
}

InputPresenter.propTypes = {
  isOpen: PropTypes.bool,
  multiple: PropTypes.bool,
  onChange: PropTypes.func,
  onInputChange: PropTypes.func,
  stylesheet: PropTypes.func,
  typable: PropTypes.bool,
};


text:
'use strict';
const common = require('../common');
const http = require('http');
const util = require('util');
const stream = require('stream');

// Verify that when piping a stream to an `OutgoingMessage` (or a type that
// inherits from `OutgoingMessage`), if data is emitted after the
// `OutgoingMessage` was closed - no `write after end` error is raised (this
// should be the case when piping - when writing data directly to the
// `OutgoingMessage` this error should be raised).

function MyStream() {
  stream.call(this);
}
util.inherits(MyStream, stream);

const server = http.createServer(common.mustCall(function(req, res) {
  const myStream = new MyStream();
  myStream.pipe(res);

  process.nextTick(common.mustCall(() => {
    res.end();
    myStream.emit('data', 'some data');

    // If we got here - 'write after end' wasn't raised and the test passed.
    process.nextTick(common.mustCall(() => server.close()));
  }));
}));

server.listen(0);

server.on('listening', common.mustCall(function() {
  http.request({
    port: server.address().port,
    method: 'GET',
    path: '/'
  }).end();
}));


text:
<!doctype html>

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

      all files / ol/ vectortile.js

        83.33%
        Statements
        40/48

        0%
        Branches
        0/2

        61.54%
        Functions
        8/13

        83.33%
        Lines
        40/48

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199	1×

1×
1×
1×
1×
1×
1×

1×

1×

6×

6×

6×

6×

6×

6×

6×

6×

6×

1×

1×
3×

1×

1×

1×
4×

1×
7×

1×

1×
10×

1×

1×
4×
4×

1×
8×

1×
8×
8×

1×

goog.provide('ol.VectorTile');

goog.require('ol.Tile');
goog.require('ol.TileCoord');
goog.require('ol.TileLoadFunctionType');
goog.require('ol.TileState');
goog.require('ol.dom');
goog.require('ol.proj.Projection');

/**
 * @typedef {{
 *     dirty: boolean,
 *     renderedRenderOrder: (null|function(ol.Feature, ol.Feature):number),
 *     renderedRevision: number,
 *     replayGroup: ol.render.IReplayGroup}}
 */
ol.TileReplayState;

/**
 * @constructor
 * @extends {ol.Tile}
 * @param {ol.TileCoord} tileCoord Tile coordinate.
 * @param {ol.TileState} state State.
 * @param {string} src Data source url.
 * @param {ol.format.Feature} format Feature format.
 * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function.
 */
ol.VectorTile = function(tileCoord, state, src, format, tileLoadFunction) {

  goog.base(this, tileCoord, state);

  /**
   * @private
   * @type {CanvasRenderingContext2D}
   */
  this.context_ = ol.dom.createCanvasContext2D();

  /**
   * @private
   * @type {ol.format.Feature}
   */
  this.format_ = format;

  /**
   * @private
   * @type {Array.<ol.Feature>}
   */
  this.features_ = null;

  /**
   * @private
   * @type {ol.FeatureLoader}
   */
  this.loader_;

  /**
   * Data projection
   * @private
   * @type {ol.proj.Projection}
   */
  this.projection_;

  /**
   * @private
   * @type {ol.TileReplayState}
   */
  this.replayState_ = {
    dirty: false,
    renderedRenderOrder: null,
    renderedRevision: -1,
    replayGroup: null
  };

  /**
   * @private
   * @type {ol.TileLoadFunctionType}
   */
  this.tileLoadFunction_ = tileLoadFunction;

  /**
   * @private
   * @type {string}
   */
  this.url_ = src;

};
goog.inherits(ol.VectorTile, ol.Tile);

/**
 * @return {CanvasRenderingContext2D} The rendering context.
 */
ol.VectorTile.prototype.getContext = function() {
  return this.context_;
};

/**
 * @inheritDoc
 */
ol.VectorTile.prototype.disposeInternal = function() {
  goog.base(this, 'disposeInternal');
};

/**
 * Get the feature format assigned for reading this tile's features.
 * @return {ol.format.Feature} Feature format.
 * @api
 */
ol.VectorTile.prototype.getFormat = function() {
  return this.format_;
};

/**
 * @return {Array.<ol.Feature>} Features.
 */
ol.VectorTile.prototype.getFeatures = function() {
  return this.features_;
};

/**
 * @return {ol.TileReplayState} The replay state.
 */
ol.VectorTile.prototype.getReplayState = function() {
  return this.replayState_;
};

/**
 * @inheritDoc
 */
ol.VectorTile.prototype.getKey = function() {
  return this.url_;
};

/**
 * @return {ol.proj.Projection} Feature projection.
 */
ol.VectorTile.prototype.getProjection = function() {
  return this.projection_;
};

/**
 * Load the tile.
 */
ol.VectorTile.prototype.load = function() {
  if (this.state == ol.TileState.IDLE) {
    this.setState(ol.TileState.LOADING);
    this.tileLoadFunction_(this, this.url_);
    this.loader_(null, NaN, null);
  }
};

/**
 * @param {Array.<ol.Feature>} features Features.
 * @api
 */
ol.VectorTile.prototype.setFeatures = function(features) {
  this.features_ = features;
  this.setState(ol.TileState.LOADED);
};

/**
 * Set the projection of the features that were added with {@link #setFeatures}.
 * @param {ol.proj.Projection} projection Feature projection.
 * @api
 */
ol.VectorTile.prototype.setProjection = function(projection) {
  this.projection_ = projection;
};

/**
 * @param {ol.TileState} tileState Tile state.
 */
ol.VectorTile.prototype.setState = function(tileState) {
  this.state = tileState;
  this.changed();
};

/**
 * Set the feature loader for reading this tile's features.
 * @param {ol.FeatureLoader} loader Feature loader.
 * @api
 */
ol.VectorTile.prototype.setLoader = function(loader) {
  this.loader_ = loader;
};

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


text:
/*                                                                  */
/* This is an automatically generated copyright prolog.             */
/* After initializing,  DO NOT MODIFY OR MOVE                       */
/*  --------------------------------------------------------------- */
/* Licensed Materials - Property of IBM                             */
/* Blue Gene/Q 5765-PER 5765-PRP                                    */
/*                                                                  */
/* (C) Copyright IBM Corp. 2011, 2012 All Rights Reserved           */
/* US Government Users Restricted Rights -                          */
/* Use, duplication, or disclosure restricted                       */
/* by GSA ADP Schedule Contract with IBM Corp.                      */
/*                                                                  */
/*  --------------------------------------------------------------- */
/*                                                                  */
/* end_generated_IBM_copyright_prolog                               */
/*  (C)Copyright IBM Corp.  2007, 2011  */
/**
 * \file src/coll/exscan/mpido_iexscan.c
 * \brief ???
 */

/*#define TRACE_ON */
#include <mpidimpl.h>

int MPIDO_Iexscan(const void *sendbuf, void *recvbuf,
                  int count, MPI_Datatype datatype,
                  MPI_Op op, MPID_Comm * comm_ptr, MPID_Request **request)
{
   /*if (unlikely((data_size == 0) || (user_selected_type == MPID_COLL_USE_MPICH)))*/
   {
      /*
       * If the mpich mpir non-blocking collectives are enabled, return without
       * first constructing the MPID_Request. This signals to the
       * MPIR_Iexscan_impl() function to invoke the mpich nbc implementation
       * of MPI_Iexscan().
       */
      if (MPIDI_Process.mpir_nbc != 0)
       return 0;

      /*
       * MPIR_* nbc implementation is not enabled. Fake a non-blocking
       * MPIR_Iexscan() with a blocking MPIR_Exscan().
       */
      if(unlikely(MPIDI_Process.verbose >= MPIDI_VERBOSE_DETAILS_ALL && comm_ptr->rank == 0))
         fprintf(stderr,"Using MPICH blocking exscan algorithm\n");

      int mpierrno = 0;
      int rc = MPIR_Exscan_impl(sendbuf, recvbuf, count, datatype, op, comm_ptr, &mpierrno);

      /*
       * The blocking exscan has completed - create and complete a
       * MPID_Request object so the MPIR_Iexscan_impl() function does not
       * perform an additional iexscan.
       */
      MPID_Request * mpid_request = MPID_Request_create_inline();
      mpid_request->kind = MPID_COLL_REQUEST;
      *request = mpid_request;
      MPIDI_Request_complete_norelease_inline(mpid_request);

      return rc;
   }

   return 0;
}


text:
require 'codeclimate-test-reporter'
CodeClimate::TestReporter.start
###################################

require 'fileutils'
require 'minitest/autorun'
require 'yaml'

require 'spectro'
require 'spectro/client'
require 'spectro/compiler'

require_relative 'minitest/test_spectro'


text:
namespace content {

void WaitForHitTestData(RenderFrameHost* child_frame) {
  RenderWidgetHostViewBase* child_view =
      static_cast<RenderFrameHostImpl*>(child_frame)
          ->GetRenderWidgetHost()
          ->GetView();

  HitTestRegionObserver observer(child_view->GetFrameSinkId());
  observer.WaitForHitTestData();
}

void WaitForHitTestData(WebContents* guest_web_contents) {
  DCHECK(static_cast<RenderWidgetHostViewBase*>(
             guest_web_contents->GetRenderWidgetHostView())
             ->IsRenderWidgetHostViewChildFrame());
  RenderWidgetHostViewChildFrame* child_view =
      static_cast<RenderWidgetHostViewChildFrame*>(
          guest_web_contents->GetRenderWidgetHostView());

  HitTestRegionObserver observer(child_view->GetFrameSinkId());
  observer.WaitForHitTestData();
}

HitTestRegionObserver::HitTestRegionObserver(
    const viz::FrameSinkId& frame_sink_id)
    : frame_sink_id_(frame_sink_id) {
  CHECK(frame_sink_id.is_valid());
  GetHostFrameSinkManager()->AddHitTestRegionObserver(this);
}

HitTestRegionObserver::~HitTestRegionObserver() {
  GetHostFrameSinkManager()->RemoveHitTestRegionObserver(this);
}

void HitTestRegionObserver::WaitForHitTestData() {
  DCHECK(cached_hit_test_data_.empty());

  for (auto& it : GetHostFrameSinkManager()->display_hit_test_query()) {
    if (it.second->ContainsActiveFrameSinkId(frame_sink_id_)) {
      cached_hit_test_data_ = it.second->GetHitTestData();
      return;
    }
  }

  run_loop_ = std::make_unique<base::RunLoop>();
  run_loop_->Run();
  run_loop_.reset();
}

void HitTestRegionObserver::WaitForHitTestDataChange() {
  DCHECK(!cached_hit_test_data_.empty());

  for (auto& it : GetHostFrameSinkManager()->display_hit_test_query()) {
    DCHECK(it.second->ContainsActiveFrameSinkId(frame_sink_id_));
    if (it.second->GetHitTestData() != cached_hit_test_data_) {
      cached_hit_test_data_ = it.second->GetHitTestData();
      return;
    }
  }

  hit_test_data_change_run_loop_ = std::make_unique<base::RunLoop>();
  hit_test_data_change_run_loop_->Run();
  hit_test_data_change_run_loop_.reset();
}

void HitTestRegionObserver::OnAggregatedHitTestRegionListUpdated(
    const viz::FrameSinkId& frame_sink_id,
    const std::vector<viz::AggregatedHitTestRegion>& hit_test_data) {
  if (hit_test_data_change_run_loop_ &&
      cached_hit_test_data_ != hit_test_data) {
    cached_hit_test_data_ = hit_test_data;
    hit_test_data_change_run_loop_->Quit();
  }

  if (!run_loop_)
    return;

  for (auto& it : hit_test_data) {
    if (it.frame_sink_id == frame_sink_id_ &&
        !(it.flags & viz::HitTestRegionFlags::kHitTestNotActive)) {
      run_loop_->Quit();
      return;
    }
  }
}

const std::vector<viz::AggregatedHitTestRegion>&
HitTestRegionObserver::GetHitTestData() {
  const auto& hit_test_query_map =
      GetHostFrameSinkManager()->display_hit_test_query();
  const auto iter = hit_test_query_map.find(frame_sink_id_);
  DCHECK(iter != hit_test_query_map.end());
  return iter->second.get()->GetHitTestData();
}

}  // namespace content


text:
require "gds_api/publishing_api"

PUBLISHING_API = GdsApi::PublishingApi.new(
  Plek.find("publishing-api"),
  bearer_token: ENV["PUBLISHING_API_BEARER_TOKEN"] || "example",
)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace ISSU.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            // Needed so the WebApi stuff works with EntityFramework
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
            // This must be above the others
            GlobalConfiguration.Configure(WebApiConfig.Register);
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>tts-server test</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />

TTS-Server Demonstration

    <form id="ttsform" action="/tts" method="post" accept-charset="utf-8">

            人声选项:
            <select name="voice">
                {% for voice in voicelist %}
                <option value ="{{voice}}">{{voice}}</option>
                {% end %}
            </select>

            <input id="ttstext" type="text" name="text" value="" />

<input type="submit" value="say it">

    </form>


text:
import { spawn, cancel, take, takeEvery } from 'redux-saga/effects';
import CONST from '../constant';
import registry from '../registry';

/**
 * This function register a saga in the cmf registry
 * @param {string} id the saga id you want
 * @param {generator} saga the saga generator
 * @param {object} context optional context to get the registry
 */
export function register(id, saga, context) {
	registry.addToRegistry(`SAGA:${id}`, saga, context);
}

/**
 * This function allow to get a saga from the registry
 * @param {string} id the saga id you want
 * @param {object} context optional context to get the registry
 */
export function get(id, context) {
	return registry.getFromRegistry(`SAGA:${id}`, context);
}

export const registerMany = registry.getRegisterMany(register);

export const isActionCancelable = startAction => action =>
	action.type === `${CONST.WILL_UNMOUNT_SAGA_STOP}_${startAction.saga}` &&
	startAction.event.componentId === action.event.componentId;

export function* onSagaStart(action) {
	const isSagaInfoAnObject = typeof action.saga === 'object';
	const sagaId = isSagaInfoAnObject ? action.saga.id : action.saga;

	if (!sagaId) {
		throw new Error(`no saga id found in action: ${JSON.stringify(action)}`);
	}

	const sagaArgs = isSagaInfoAnObject ? action.saga.args : [];
	const saga = get(sagaId);
	if (!saga) {
		throw new Error(`saga not found: ${sagaId}`);
	}

	const task = yield spawn(
		saga,
		{
			...action.props, // deprecated: you should only read { componentId }
			componentId: action.componentId,
		},
		...sagaArgs,
	);
	yield take(isActionCancelable(action));
	yield cancel(task);
}

export function* handle() {
	yield takeEvery(CONST.DID_MOUNT_SAGA_START, onSagaStart);
	yield take('DO_NOT_QUIT');
}


text:
1. Install mongodb
`$ sudo apt-get install mongodb`
2. Install support for parsing exif
`$ sudo apt-get install python-pyexiv2`
3. Install foorep
`$ sudo pip install foorep`

***

### Ubuntu 10.04 and SIFT Workstation 2.14 (Ubuntu 9.10)
The provided version of mongodb in older Ubuntu is lacking some features that foorep depends on.
Because of this we need to install mongodb from 10gens repository.

1. Uninstall old mongodb
`$ sudo apt-get remove mongodb`
2. Add 10gen Ubuntu repository to sources.list
`$ sudo echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" >> /etc/apt/sources.list`
3. Add 10gen key
`$ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10`
4. Update apt
`$ sudo apt-get update`
5. Install mongodb
`$ sudo apt-get install mongodb-10gen`
6. Install support for parsing exif
`$ sudo apt-get install python-pyexiv2`
7. Remove python-magic, the version bundled with Ubuntu is too old.
`$ sudo apt-get remove python-magic`
8. Install foorep
`$ sudo pip install foorep`


text:
function Start-AP_SPProvisioning_RemovedContentType
{
	<#
	.Synopsis
	Start AP_SPProvisioning_RemovedContentType
	.DESCRIPTION
	The Start for the Action AP_SPProvisioning_RemovedContentType
	.PARAMETER xmlActionObject
	#>
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true,Position=0)]
        [System.Xml.XmlLinkedNode]$xmlActionObject
	)
    Begin
    {
		Write-Verbose "Start Start-AP_SPProvisioning_RemovedContentType"
    }
    Process
    {
		$name = $null;
		$group_name = $null;
		$currentWeb = Get-AP_SPProvisioning_SPEnvironment_CurrentWeb

		if($xmlActionObject.Name) { $name = $xmlActionObject.Name}
		if($xmlActionObject.GroupName) { $group_name = $xmlActionObject.GroupName}

		if($name -eq $null -and $group_name -eq $null)
		{
			Write-Error "Missing attributes. At least one of the attributes [Name or GroupName] must be passed"
		}
		else
		{
			Select-AP_SPProvisioning_ContentType -Web $currentWeb.Web -Name $name -GroupName $group_name
		}
    }
    End
    {
		Write-Verbose "End Start-AP_SPProvisioning_RemovedContentType"
    }
}

function Select-AP_SPProvisioning_ContentType
{
	<#
	.SYNOPSIS
	Checks whether a ContentType or Groups should be deleted
	Pr�ft ob ein ContentType oder Gruppen gel�scht werden sollen
    .DESCRIPTION
	If you have specified a Name, it is deleted. If you specify a group name, all ContentTypes in the group will be removed and the Name will be passed if it is also present.
    Wenn Sie einen Name angegeben haben, wird dieser gel�scht. Wenn Sie eine Gruppenamen angeben, werde alle ContentType in der Gruppe entfernt und der Name wird �bergangen, sollte dieser ebenfalls vorhanden sein.
	.PARAMETER Web
	The Current Web Object
	Das Aktuelle Web Objekt
	.PARAMETER Name
	The name of the ContentType to remove
    Den Namen des ContentType das entfernt werden soll
	.PARAMETER GroupName
	The group names of the ContentTypes to be removed.
    Den Gruppennamen der ContentTypes die entfernt werden sollen.
	#>
	[CmdletBinding()]
	param(
		[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)]
		[ValidateNotNullOrEmpty()]
		$Web,
		$Name,
		$GroupName
	)
	begin
	{
		Write-Verbose "Remove-AP_SPProvisioning_ContentType begin"
	}
	process
	{
		if($GroupName -ne $null)
		{
			Remove-SPProvisioning_AllContentTypeFromGroup -Groupname $GroupName -Web $Web

			Write-Host "Successfully removed Content Types from the group $($GroupName) on current web" -Type success
			Write-Host
		}
		elseif ($Name -ne $null)
		{
			Use-AP_SPProvisioning_PnP_Remove-PnPContentType -Identity $Name -Web $Web -Force $true
			Write-Host "Successfully removed Content Type from $($Name) on current web" -Type success
			Write-Host
		}
		else
		{
			Write-Error "Missing attributes. At least one of the attributes [Name or GroupName] must be passed"
		}
	}
	end
	{
		Write-Verbose "Remove-AP_SPProvisioning_ContentType end"
	}
}

function Remove-SPProvisioning_AllContentTypeFromGroup
{
	<#
	.SYNOPSIS
	Removes all ContentType belonging to the group
	Entfernt alle ContentType die der Gruppe angeh�ren
    .DESCRIPTION
	Removes all ContentType belonging to the group
    Entfernt alle ContentType die der Gruppe angeh�ren
    .PARAMETER Groupname
	The Name of the Group
    Der Name der Gruppe
	.PARAMETER Web
	The Current Web Object
	Das Aktuelle Web Objekt
	#>
	[CmdletBinding()]
	param(
	[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)]
	[ValidateNotNullOrEmpty()]
    $Groupname,
	[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=1)]
	[ValidateNotNullOrEmpty()]
    $Web
	)
	begin
	{
		Write-Verbose "Remove-SPProvisioning_AllContentTypeFromGroup begin"
	}
	process
	{
		Write-Host "START RemoveContentType from Group $($Groupname)"

		$contentTypes = Use-AP_SPProvisioning_PnP_Get-PnPContentType -Web $Web | ? { $_.Group -eq $Groupname } | Sort-Object ID -Descending

		if($contentTypes -eq $null)
		{
			Write-Host "There is no ContentType in the group to delete" -ForegroundColor Yellow
		}
		else
		{
			foreach($contentType in $contentTypes)
			{
				Write-Host "Start Remove ContentType $($contentType.Name)"
				Use-AP_SPProvisioning_PnP_Remove-PnPContentType -Identity $contentType -Web $Web -Force $true
			}
		}

		Write-Host "END RemoveContentType from Group $($Groupname)"
	}
	end
	{
		Write-Verbose "Remove-SPProvisioning_AllContentTypeFromGroup end"
	}
}

function Remove-ContentTypesFromListsCorrectly
{
	<#
	.SYNOPSIS
    Entfert alle ContentTypes von der Liste
    .DESCRIPTION
    Es werden bei allen übergebenen Listen geprüft ob der ContentType eine vom Projekt angelegt wurde,
	wenn ja wird auf dieser Liste ein StandardContentType hinterlegt und den im Projekt verwendete ContentType
	wird entfernt.
	.PARAMETER arrayLists
	Alle Listen die bereinigt werden sollen
	.PARAMETER arrayContentType
	Alle ContentType die vom Projekt angelegt wurden
	#>
	[CmdletBinding()]
	param(
	[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)]
    $arrayLists,
	[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)]
    $arrayContentType
	)
	begin
	{
		Write-Verbose "Remove-ContentTypesFromLists begin"
	}
	process
	{
		Write-Host "START Remove-ContentTypesFromLists"

		foreach($liste in $arrayLists)
		{
			Write-Host "Removing content tyes from List $liste"

			$currentWeb = Get-AP_SPProvisioning_SPEnvironment_CurrentWeb
			$list = Use-AP_SPProvisioning_PnP_Get-PnPList -Identity $liste -Web $currentWeb.Web

			if($list)
			{
				$list.Context.Load($list.ContentTypes)
				$list.Context.ExecuteQuery()

				foreach($contentType in $list.ContentTypes)
				{
					if($arrayContentType -contains $contentType.Name)
					{
						Remove-ContentTypFromListItems -list $list -currentWeb $currentWeb

						Use-AP_SPProvisioning_PnP_Remove-PnPContentTypeFromList -List $list.Title -ContentType $contentType.Name -Web $currentWeb.Web

						Write-Host "Deleted content type $($contentType.Name) from list"
					}
				}
			}
			else
			{
				$text = "ERROR Deleted content type from $liste because List not found"
				Write-Host $text -Type error
				$text = $text + "Soll das Skript weiter machen?"
				Create-QuestionTask -statement $text
			}
		}
	}
	end
	{
		Write-Verbose "Remove-ContentTypesFromLists end"
	}
}

function Add-ContentTypes
{
	<#
	.SYNOPSIS
    Erstellt die ContentTypes auf SharePoint
    .DESCRIPTION
    Es werden die ContentType aus der Provisionierung Konfiguration Datei geladen und
	entsprechend den hinterlegten Attribute angelegt.
    .PARAMETER xmlFile
    Den XML Knoten der Datei.
	#>
	[CmdletBinding()]
	param(
		[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=1)]
		[string]$xmlFile
	)
	begin
	{
		Write-Verbose "CreateContentTypes begin"
	}
	process
	{
		[xml]$wpXml = Get-Content "$($xmlFile)" -Encoding String
		$currentWeb = Get-AP_SPProvisioning_SPEnvironment_CurrentWeb
		$XMLcontentTypes = $wpXml.Provisioning.Templates.ProvisioningTemplate.ContentTypes.ContentType

        $fields = $currentWeb.Web.Fields
        $currentWeb.Web.Context.Load($fields)
        $currentWeb.Web.Context.executeQuery()

		foreach($XMLcontentType in $XMLcontentTypes)
		{
			#variables that needs to be set before starting the script
			$contentTypeGroup = $XMLcontentType.Group
			$contentTypeName = $XMLcontentType.Name
			$contentTypeId = $XMLcontentType.ID
			$contentTypeDescription = $XMLcontentType.Description
			$columns = $XMLcontentType.FieldRefs.FieldRef

			# Creating client context object
			$contentTypes = $currentWeb.Web.ContentTypes
			$contentTypes.Context.Load($contentTypes)

			# send the request containing all operations to the server
			try{
				$contentTypes.Context.executeQuery()
				write-host "info: Loaded Fields and Content Types" -foregroundcolor green
			}
			catch{
				write-host "info: $($_.Exception.Message)" -foregroundcolor red
			}

			# Loop through all content types to verify it doesn't exist
			$checkContentType = $contentTypes | Where-Object { $_.Name -eq $contentTypeName}
			if($checkContentType){
				write-host "Info: The content type $($contentTypeName) already exists." -foregroundcolor red
				$contentTypeExists = $true
			}
			else{
				$contentTypeExists = $false
			}

			# create content type if it doesnt exist based on specified Content Type ID
			if($contentTypeExists -eq $false){

				$ct = Use-AP_SPProvisioning_PnP_Add-PnPContentType -contentTypeName $contentTypeName -contentTypeId $contentTypeId -contentTypeDescription $contentTypeDescription -contentTypeGroup $contentTypeGroup -Web $currentWeb.Web
				write-host "info: create contentType $($ct.Name)" -foregroundcolor green

				# loop through all the columns that needs to be added
				foreach ($column in $columns)
				{
					$hidden = $false;
					$require = $false;
					if($column.Hidden -eq "true") { $hidden = $true; }
					if($column.Required -eq "true") { $require = $true; }

					Use-AP_SPProvisioning_PnP_Add-PnPFieldFromContentType -Field $column.Name -contentTypeId $contentTypeId -Required $require -Hidden $hidden -Web $currentWeb.Web

					write-host "info: added $($column.Name) to $($ct.Name)" -foregroundcolor green
				}
			}
		}
	}
	end
	{
		Write-Verbose "CreateContentTypes end"
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 - Copyright 1999-2011 Alibaba Group.
 -
 - Licensed under the Apache License, Version 2.0 (the "License");
 - you may not use this file except in compliance with the License.
 - You may obtain a copy of the License at
 -
 -      http://www.apache.org/licenses/LICENSE-2.0
 -
 - Unless required by applicable law or agreed to in writing, software
 - distributed under the License is distributed on an "AS IS" BASIS,
 - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 - See the License for the specific language governing permissions and
 - limitations under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <bean class="${package}.consumer.DemoAction" init-method="start">
        <property name="userService" ref="userService"/>
        <property name="userRestService" ref="userRestService"/>
    </bean>

</beans>


text:
// * ======================================================================
// * Filename: symtab.c
// * Description: symtab.h implementation file.
// * Created: Mon May 29 12:44:26 2017 (-0500)
// * Last-Updated: Tue May 30 11:35:33 2017 (-0500)
// * Author: Ivan Guerra <Ivan.E.Guerra-1@ou.edu>
// * ======================================================================
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "symtab.h"
#include "token_list.h"

const float DEFAULT_LOAD_FACTOR = 0.75;

int hashcode(int capacity, const char* lexeme)
{
    int c;
    unsigned long hash = 5381;

    while ((c = *lexeme++))
        hash = ((hash << 5) + hash) + c;

    return (hash % capacity);
}

struct symtab* init_symtab(size_t cap)
{
    struct symtab* m = (struct symtab *)malloc(sizeof(struct symtab));
    if (NULL == m) {
        fprintf(stderr, "Insufficient memory to allocate symtab.\n");
        return NULL;
    }

    m->load_factor = DEFAULT_LOAD_FACTOR;
    m->capacity = cap;
    m->tokens = (struct token_list **)malloc(sizeof(struct token_list *) * cap);
    if (NULL == m->tokens) {
        fprintf(stderr, "Insufficient memory to allocate symtab tokens.\n");
        free(m);
        return NULL;
    }

    for (int i = 0; i < cap; i++)
        m->tokens[i] = NULL;

    return m;
}

void free_symtab(struct symtab* m)
{
    for (int i = 0; i < m->capacity; i++)
        free_list(m->tokens[i]);

    free(m->tokens);
    free(m);
}

bool empty_symtab(const struct symtab* m)
{
    bool is_empty = 1;
    for (int i = 0; i < m->capacity; i++)
        is_empty &= empty_list(m->tokens[i]);

    return is_empty;
}

void set_load_factor(struct symtab* m, float lf)
{
    m->load_factor = lf;
}

float load_factor(const struct symtab* m)
{
    return (size_symtab(m) / (float) m->capacity);
}

size_t size_symtab(const struct symtab* m) {
    size_t total_size = 0;
    for (int i = 0; i < m->capacity; i++)
        total_size += size_list(m->tokens[i]);

    return total_size;
}

size_t count(const struct symtab* m, size_t bucket)
{
    return size_list(m->tokens[bucket]);
}

size_t bucket_count(const struct symtab* m)
{
    return m->capacity;
}

bool insert_token(struct symtab* m, const char* lexeme, struct token* t)
{
    /* Do not allow for insertion of duplicate tokens. */
    if (find(m, lexeme, t))
        return false;

    int code = hashcode(m->capacity, lexeme);
    m->tokens[code] = insert_node(m->tokens[code], t);

    /* If the load factor is exceeded, double the number of buckets. */
    if (load_factor(m) > m->load_factor)
        rehash(m, (2 * (m->capacity)));

    return true;
}

bool remove_token(struct symtab* m, const char* lexeme, struct token* t)
{
    if (!find(m, lexeme, t))
        return false;

    int code = hashcode(m->capacity, lexeme);
    m->tokens[code] = remove_node(m->tokens[code], t);

    return true;
}

bool find(const struct symtab* m, const char* lexeme, const struct token* t)
{
    int code = hashcode(m->capacity, lexeme);
    struct token_list* bucket = m->tokens[code];

    return contains_token(bucket, t);
}

void print_symtab(const struct symtab* m)
{
    for (int i = 0; i < m->capacity; i++) {
        printf("%d: ", i);
        print_list(m->tokens[i]);
    }
}

void rehash(struct symtab* m, size_t nbuckets)
{
    /* Do not rehash to a lesser number of buckets. */
    if (m->capacity >= nbuckets)
        return;

    token_list** tmp = (struct token_list **)realloc(m->tokens, sizeof(struct token_list *) * nbuckets);
    if (NULL == tmp) {
        fprintf(stderr, "Unable to adjust load factor. Insufficient memory for realloc.\n");
        return;
    }
    /* NULL new buckets added by realloc. */
    for (int i = m->capacity; i < nbuckets; i++)
        tmp[i] = NULL;

    int old_capacity = m->capacity;
    m->capacity = nbuckets;
    m->tokens = tmp;

    int old_code = 0;
    int new_code = 0;
    token* data = 0;
    for (int i = 0; i < old_capacity; i++) {
        token_list* bucket = m->tokens[i];
        while (bucket) {
            data = bucket->data;
            old_code = hashcode(old_capacity, data->lexeme);
            new_code = hashcode(nbuckets, data->lexeme);

            if (old_code != new_code) {
                /*
                 * Make a deep copy of the data because the
                 * remove_node method will free the token as a side effect.
                 */
                token* tmp_tok = create_token(data->tt, data->linenum, data->lexeme);

                /* Remove the data from the old bucket. */
                m->tokens[i] = remove_node(m->tokens[i], data);
                bucket = m->tokens[i];

                /* m->capacity was updated earlier so the copied data is inserted into the new bucket. */
                insert_token(m, tmp_tok->lexeme, tmp_tok);
            } else {
                bucket = bucket->next;
            }
        }
    }
}