text:
<?php

/* partials/nav-toggle.html.twig */
class __TwigTemplate_fde1f18fbad03c47de3ec90b31e2de4e355c7cd3bea0e19989297c6545c2aa9f extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "<button class=\"lines-button x\" type=\"button\" role=\"button\" aria-label=\"Toggle Navigation\" data-sidebar-mobile-toggle>

</button>
";
    }

    public function getTemplateName()
    {
        return "partials/nav-toggle.html.twig";
    }

    public function getDebugInfo()
    {
        return array (  19 => 1,);
    }
}
/* <button class="lines-button x" type="button" role="button" aria-label="Toggle Navigation" data-sidebar-mobile-toggle>*/
/*     */
/* </button>*/
/* */


text:
<?php declare(strict_types=1);

namespace Sturdy\Activity\Meta;

use Exception;

/**
 * Compile a resource
 */
class ResourceCompiler
{
	private $fieldDescriptors;

	/**
	 * Compile resource
	 *
	 * @return CacheItem_Resource
	 */
	public function compile(Resource $resource, TagMatcher $matcher): CacheItem_Resource
	{
		$hints = $matcher->findBestMatch($resource->getHints());
		$order = $matcher->findBestMatch($resource->getOrders());
		if ($order !== null) {
			$order = array_flip(array_values($order->getFields()));
		} else {
			$order = [];
		}

		$verbs = [];
		$root = false;
		foreach ($resource->getVerbs() as $name => $variants) {
			$verb = $matcher->findBestMatch($variants);
			if ($verb) {
				$verbs[$name] = [$verb->getMethod(), $verb->getFlags()->toInt()];
				$root = $verb->getFlags()->getRoot();
			}
		}

		if ($root && count($verbs) > 1) {
			throw new Exception("A root resource may only have one verb.");
		}

		$type = $resource->getObjectType();
		$this->compileObjectType($type, $matcher);

		$item = $root ? new CacheItem_RootResource : new CacheItem_Resource;
		$item->setClass($resource->getClass());
		if ($hints) {
			$item->setHints($hints->getLabel(), $hints->getIcon(), $hints->getSection(), $hints->getComponent(), $hints->getLayout(), $hints->getVariant(), $hints->getClear());
		}
		$item->setTags($matcher->getTags());

		$i = count($order);
		$fields = [];
		foreach ($type->getFieldDescriptors() as $descriptor) {
			$fields[$order[$descriptor[0]] ?? $i++] = $descriptor;
		}
		ksort($fields);
		foreach ($fields as $descriptor) {
			$item->addField(...$descriptor);
		}
		foreach ($verbs as $name => [$method, $flags]) {
			$item->setVerb($name, $method, $flags);
		}

		return $item;
	}

	private function compileObjectType($object, TagMatcher $matcher): void
	{
		$fieldDescriptors = [];
		foreach ($object->getFields() as $name => $variants) {
			$field = $matcher->findBestMatch($variants);
			if ($field) {
				$type = $field->getType();
				if ($type instanceof Type\ObjectType || $type instanceof Type\TupleType) {
					$this->compileObjectType($type, $matcher);
				}
				$fieldDescriptors[] = [
					$name,
					$type->getDescriptor(),
					$field->getDefaultValue(),
					$field->getFlags()->toInt(),
					$field->getAutocomplete(),
					$field->getLabel(),
					$field->getIcon(),
					$field->getSharedStatePoolName(),
				];
			}
		}
		$object->setFieldDescriptors($fieldDescriptors);
	}
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * _scripts/widgets/download-modal.js
 * Code for opening the download overlay widget on the homepage
 */

import modal from '~/lib/modal'

export function openDownloadOverlay () {
    modal.then(($) => {
        var $openModal
        $openModal = $('.open-modal')
        console.log('Open the download overlay!')
        $openModal.leanModal({
            // Add this class to download buttons to make them close it.
            closeButton: '.close-modal',
            disableCloseOnOverlayClick: true
        })
        // This is what actually opens the modal overlay.
        $openModal.click()
    })
}


text:
using Microsoft.Azure.Commands.TrafficManager.Models;
using Microsoft.Azure.Commands.TrafficManager.Utilities;
using System.Management.Automation;
using ProjectResources = Microsoft.Azure.Commands.TrafficManager.Properties.Resources;

namespace Microsoft.Azure.Commands.TrafficManager
{
    using Hyak.Common;
    using System.Collections;
    using System.Net;

    [Cmdlet(VerbsCommon.New, "AzureRmTrafficManagerProfile"), OutputType(typeof(TrafficManagerProfile))]
    public class NewAzureTrafficManagerProfile : TrafficManagerBaseCmdlet
    {
        [Parameter(Mandatory = true, HelpMessage = "The name of the profile.")]
        [ValidateNotNullOrEmpty]
        public string Name { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "The resource group to which the profile belongs.")]
        [ValidateNotNullOrEmpty]
        public string ResourceGroupName { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "The status of the profile.")]
        [ValidateSet(Constants.StatusEnabled, Constants.StatusDisabled, IgnoreCase = false)]
        [ValidateNotNullOrEmpty]
        public string ProfileStatus { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "The relative name of the profile.")]
        [ValidateNotNullOrEmpty]
        public string RelativeDnsName { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "The Ttl value of the DNS configurations.")]
        [ValidateNotNullOrEmpty]
        public uint Ttl { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "The traffic routing method of the profile.")]
        [ValidateSet(Constants.Performance, Constants.Weighted, Constants.Priority, Constants.Geographic, IgnoreCase = false)]
        [ValidateNotNullOrEmpty]
        public string TrafficRoutingMethod { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "The protocol of the monitor.")]
        [ValidateSet(Constants.HTTP, Constants.HTTPS, IgnoreCase = false)]
        [ValidateNotNullOrEmpty]
        public string MonitorProtocol { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "The port of the monitor.")]
        [ValidateNotNullOrEmpty]
        public uint MonitorPort { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "The path of the monitor.")]
        [ValidateNotNullOrEmpty]
        public string MonitorPath { get; set; }

        [Alias("Tags")]
        [Parameter(Mandatory = false, HelpMessage = "A hash table which represents resource tags.")]
        public Hashtable Tag { get; set; }

        public override void ExecuteCmdlet()
        {
            // We are not supporting etags yet, NewAzureTrafficManagerProfile should not overwrite any existing profile.
            // Since our create operation is implemented using PUT, it will overwrite by default.
            // Therefore, we need to check whether the Profile exists before we actually try to create it.
            try
            {
                this.TrafficManagerClient.GetTrafficManagerProfile(this.ResourceGroupName, this.Name);

                throw new PSArgumentException(string.Format(ProjectResources.Error_CreateExistingProfile, this.Name, this.ResourceGroupName));
            }
            catch (CloudException exception)
            {
                if (exception.Response.StatusCode.Equals(HttpStatusCode.NotFound))
                {
                    TrafficManagerProfile profile = this.TrafficManagerClient.CreateTrafficManagerProfile(
                    this.ResourceGroupName,
                    this.Name,
                    this.ProfileStatus,
                    this.TrafficRoutingMethod,
                    this.RelativeDnsName,
                    this.Ttl,
                    this.MonitorProtocol,
                    this.MonitorPort,
                    this.MonitorPath,
                    this.Tag);

                    this.WriteVerbose(ProjectResources.Success);
                    this.WriteObject(profile);
                }
                else
                {
                    throw;
                }
            }
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proc. Acad. nat. Sci. Philad. 42: 237 (1890)

#### Original name
Leptosphaeria brunellae Ellis & Everh.

### Remarks
null


text:
package com.example.diary.uczen;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.example.diary.*;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class UczenArchiwumActivity extends Activity {
	static String rokW = "puste";
	String rok_szkolny;
	Intent i;
	List<Map<String, String>> result = null;
	Bundle b;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_uczen_archiwum);
		result = Utilities.query(this, "getRokSz");
		ArrayList<String> lista = new ArrayList<String>();
		int b = result.size();

		for(int a=0;a<b;a++){
			rok_szkolny = result.get(a).get("rok_szkolny");
			lista.add(a, rok_szkolny );
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista);
		Spinner spinner = (Spinner)findViewById(R.id.wybranyRok);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				rokW = parent.getItemAtPosition(position).toString();

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				Toast.makeText(getApplicationContext(), "Wybierz rok", Toast.LENGTH_SHORT).show();

			}
		});

	}

		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// Inflate the menu; this adds items to the action bar if it is present.
			getMenuInflater().inflate(R.menu.archiwum_student, menu);
			return true;
		}

		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			// Handle action bar item clicks here. The action bar will
			// automatically handle clicks on the Home/Up button, so long
			// as you specify a parent activity in AndroidManifest.xml.
			int id = item.getItemId();
			if (id == R.id.action_settings) {
				return true;
			}
			return super.onOptionsItemSelected(item);
		}
		public void onOceny(View v){
			i = new Intent(this,UczenArchiwumOcenyActivity.class);
			b = getIntent().getExtras();
			i.putExtra("rokW", rokW);
			i.putExtras(b);
			//i.putExtra("id_ucznia",getIntent().getExtras().getString("id"));
			//i.putExtra("rok_szkolny", rokW);
			startActivity(i);
		}

		public void onOgloszenia(View v){
			i = new Intent(this,UczenArchiwumOgloszeniaActivity.class);
			Bundle bundle = getIntent().getExtras();
			i.putExtra("rokW", rokW);
			i.putExtras(bundle);
			startActivity(i);
		}
		public void onUwagi(View v){
			i = new Intent(this,UczenArchiwumUwagiActivity.class);
			Bundle bundle = getIntent().getExtras();
			i.putExtras(bundle);
			i.putExtra("rokW", rokW);

			startActivity(i);
		}
		public void onObecnosci(View v){
			i = new Intent(this,UczenArchiwumObecnosciActivity.class);
			Bundle bundle = getIntent().getExtras();
			i.putExtra("rokW", rokW);
			i.putExtras(bundle);
			startActivity(i);
		}
	}


text:
const { environment } = require('@rails/webpacker')
const url = require('./loaders/url');

environment.loaders.prepend('url', url);
environment.loaders.get('file').test = /\.(eot|otf|ttf|woff|woff2)$/i

environment.loaders.get('sass').use.splice(-1, 0, {
  loader: 'resolve-url-loader',
  options: {
    attempts: 1
  }
});

environment.config.merge({
  resolve: {
    alias: {
      'jquery.dirtyforms': 'jquery.dirtyforms/jquery.dirtyforms',
    },
  },
  externals: {
    // Treat window and document as an external to fix jquery.dirtyforms
    // import:
    // https://github.com/snikch/jquery.dirtyforms/issues/82#issuecomment-376834484
    window: 'window',
    document: 'document',
  },
});

module.exports = environment


text:
<?php
declare(strict_types = 1);

namespace App\Service\Authentication;

use App\Service\User\DoctrineFindUserByThirdPartyAuthentication;
use App\Service\User\FindUserByEmailInterface;
use App\Service\User\PhpPasswordHash;
use Doctrine\ORM\EntityManagerInterface;
use Interop\Container\ContainerInterface;
use Zend\Authentication\Storage\Session;
use Zend\ServiceManager\Factory\FactoryInterface;

/**
 * @codeCoverageIgnore
 */
class Factory implements FactoryInterface
{
    /**
     * {@inheritdoc}
     * @throws \Interop\Container\Exception\NotFoundException
     */
    public function __invoke(
        ContainerInterface $container,
        $requestedName,
        array $options = null
    ) : ZendAuthenticationService {
        $entityManager = $container->get(EntityManagerInterface::class);
        return new ZendAuthenticationService(
            $container->get(FindUserByEmailInterface::class),
            new DoctrineFindUserByThirdPartyAuthentication($entityManager),
            $entityManager,
            new Session(),
            new PhpPasswordHash()
        );
    }
}


text:
package com.oney.gcm;

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;

import java.io.IOException;

public class GcmRegistrationService extends IntentService {

    private static final String TAG = "GcmRegistrationService";

    public GcmRegistrationService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Resources resources = getApplication().getResources();
        String packageName = getApplication().getPackageName();

        int resourceId = resources.getIdentifier("gcm_defaultSenderId", "string", packageName);
        String projectNumber = getString(resourceId);
        Log.i(TAG, "projectNumber: " + projectNumber);

        if (projectNumber == null) {
            Intent i = new Intent("RNGcmRegistrationServiceResult");
            Bundle bundle = new Bundle();
            bundle.putBoolean("success", false);
            bundle.putString("message", "Failed to get gcm_defaultSenderId, please check if android/app/google-services.json exists");
            i.putExtras(bundle);
            sendBroadcast(i);

            return;
        }

        try {
            InstanceID instanceID = InstanceID.getInstance(this);
            String token = instanceID.getToken(projectNumber,
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            Log.i(TAG, "GCM Registration Token: " + token);

            registeredToken(token);

        } catch (Exception e) {
            Log.d(TAG, "Failed to complete token refresh", e);
            String message = e.getMessage();

            Intent i = new Intent("RNGcmRegistrationServiceResult");
            Bundle bundle = new Bundle();
            bundle.putBoolean("success", false);
            bundle.putString("message", "Failed to get GCM token, error is " + message);
            i.putExtras(bundle);
            sendBroadcast(i);
        }
    }
    private void registeredToken(String token) {
        Intent i = new Intent("RNGcmRegistrationServiceResult");
        Bundle bundle = new Bundle();
        bundle.putBoolean("success", true);
        bundle.putString("token", token);
        i.putExtras(bundle);
        sendBroadcast(i);
    }

}


text:
'Copyright 2019 Esri

'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.
Imports ESRI.ArcGIS.esriSystem
Imports ESRI.ArcGIS.Catalog
Imports ESRI.ArcGIS.ADF.CATIDs
Imports System.Runtime.InteropServices

<ComClass(TextView.ClassId, TextView.InterfaceId, TextView.EventsId), _
 ProgId("TextTabVBNET.TextView")> _
Public Class TextView
    Implements ESRI.ArcGIS.CatalogUI.IGxView
#Region "COM Registration Function(s)"
    <ComRegisterFunction(), ComVisibleAttribute(False)> _
    Public Shared Sub RegisterFunction(ByVal registerType As Type)
        ' Required for ArcGIS Component Category Registrar support
        ArcGISCategoryRegistration(registerType)

        'Add any COM registration code after the ArcGISCategoryRegistration() call

    End Sub

    <ComUnregisterFunction(), ComVisibleAttribute(False)> _
    Public Shared Sub UnregisterFunction(ByVal registerType As Type)
        ' Required for ArcGIS Component Category Registrar support
        ArcGISCategoryUnregistration(registerType)

        'Add any COM unregistration code after the ArcGISCategoryUnregistration() call

    End Sub

#Region "ArcGIS Component Category Registrar generated code"
    ''' <summary>
    ''' Required method for ArcGIS Component Category registration -
    ''' Do not modify the contents of this method with the code editor.
    ''' </summary>
    Private Shared Sub ArcGISCategoryRegistration(ByVal registerType As Type)
        Dim regKey As String = String.Format("HKEY_CLASSES_ROOT\CLSID\{{{0}}}", registerType.GUID)
        GxTabViews.Register(regKey)

    End Sub
    ''' <summary>
    ''' Required method for ArcGIS Component Category unregistration -
    ''' Do not modify the contents of this method with the code editor.
    ''' </summary>
    Private Shared Sub ArcGISCategoryUnregistration(ByVal registerType As Type)
        Dim regKey As String = String.Format("HKEY_CLASSES_ROOT\CLSID\{{{0}}}", registerType.GUID)
        GxTabViews.Unregister(regKey)

    End Sub

#End Region
#End Region

#Region "COM GUIDs"
    ' These  GUIDs provide the COM identity for this class
    ' and its COM interfaces. If you change them, existing
    ' clients will no longer be able to access the class.
    Public Const ClassId As String = "1629e1b8-2a12-4fae-a509-75930843bcaf"
    Public Const InterfaceId As String = "63a2a982-39d8-4996-84f5-0ec678abab12"
    Public Const EventsId As String = "836e2190-9c11-4df9-9e47-2a4c3dde7710"
#End Region

    ' A creatable COM class must have a Public Sub New()
    ' with no parameters, otherwise, the class will not be
    ' registered in the COM registry and cannot be created
    ' via CreateObject.
#Region "Member Variables"
    Private WithEvents m_pSelection As GxSelection
    Private m_txtStream As Object
    Private m_fso As Object
    Private frmTextView As New FrmTextView
#End Region
    Public Sub New()
        MyBase.New()
    End Sub
    Private Sub OnSelectionChanged(ByVal Selection As IGxSelection, ByRef initiator As Object) Handles m_pSelection.OnSelectionChanged
        'Refresh view
        Refresh()
    End Sub

    Public Sub Activate(ByVal Application As ESRI.ArcGIS.CatalogUI.IGxApplication, ByVal Catalog As ESRI.ArcGIS.Catalog.IGxCatalog) Implements ESRI.ArcGIS.CatalogUI.IGxView.Activate
        m_pSelection = Application.Selection
        Refresh()
    End Sub

    Public Function Applies(ByVal Selection As ESRI.ArcGIS.Catalog.IGxObject) As Boolean Implements ESRI.ArcGIS.CatalogUI.IGxView.Applies
        'Set applies
        Applies = (Not Selection Is Nothing) And (TypeOf Selection Is IGxTextFile)
    End Function

    Public ReadOnly Property ClassID1() As ESRI.ArcGIS.esriSystem.UID Implements ESRI.ArcGIS.CatalogUI.IGxView.ClassID
        Get
            'Set class ID
            Dim pUID As New UID
            pUID.Value = "TextTabVBNET.TextView"
            ClassID1 = pUID
        End Get
    End Property

    Public Sub Deactivate() Implements ESRI.ArcGIS.CatalogUI.IGxView.Deactivate
        'Prevent circular reference
        If Not m_pSelection Is Nothing Then m_pSelection = Nothing
    End Sub

    Public ReadOnly Property DefaultToolbarCLSID() As ESRI.ArcGIS.esriSystem.UID Implements ESRI.ArcGIS.CatalogUI.IGxView.DefaultToolbarCLSID
        Get
            'You can set it to the CLSID of the toolbar you want to use
            DefaultToolbarCLSID = Nothing
        End Get
    End Property

    Public ReadOnly Property hWnd() As Integer Implements ESRI.ArcGIS.CatalogUI.IGxView.hWnd
        Get
            Try
                'Set view handle to be the control handle
                hWnd = frmTextView.txtContents.Handle
            Catch ex As Exception
                System.Windows.Forms.MessageBox.Show(ex.ToString())
            End Try
        End Get
    End Property

    Public ReadOnly Property Name() As String Implements ESRI.ArcGIS.CatalogUI.IGxView.Name
        Get
            'Set view name
            Name = "Text"
        End Get
    End Property

    Public Sub Refresh() Implements ESRI.ArcGIS.CatalogUI.IGxView.Refresh
        Dim pGxSelection As IGxSelection
        Dim pLocation As IGxObject
        pGxSelection = m_pSelection
        pLocation = pGxSelection.Location

        'Clean up
        frmTextView.txtContents.Clear()

        Dim fname As String
        fname = LCase(pLocation.Name)

        If InStr(fname, ".txt") Then
            If m_fso Is Nothing Then m_fso = CreateObject("Scripting.FileSystemObject")
            Const forReading = 1
            Try
                m_txtStream = m_fso.OpenTextFile(pLocation.FullName, forReading)
                frmTextView.txtContents.Text = m_txtStream.ReadAll.ToString
                m_txtStream.Close()
            Catch ex As Exception
                System.Windows.Forms.MessageBox.Show(ex.ToString())
            Finally
                m_fso = Nothing
                m_txtStream = Nothing
            End Try
        End If
    End Sub

    Public ReadOnly Property SupportsTools() As Boolean Implements ESRI.ArcGIS.CatalogUI.IGxView.SupportsTools
        Get
            'If you want this view to support tools, you can set it to "True"
            SupportsTools = False
        End Get
    End Property

    Public Sub SystemSettingChanged(ByVal flag As Integer, ByVal section As String) Implements ESRI.ArcGIS.CatalogUI.IGxView.SystemSettingChanged
        'Do nothing
    End Sub
End Class


text:
#include <aws/gamelift/model/GameServerClaimStatus.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace GameLift
  {
    namespace Model
    {
      namespace GameServerClaimStatusMapper
      {

        static const int CLAIMED_HASH = HashingUtils::HashString("CLAIMED");

        GameServerClaimStatus GetGameServerClaimStatusForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == CLAIMED_HASH)
          {
            return GameServerClaimStatus::CLAIMED;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<GameServerClaimStatus>(hashCode);
          }

          return GameServerClaimStatus::NOT_SET;
        }

        Aws::String GetNameForGameServerClaimStatus(GameServerClaimStatus enumValue)
        {
          switch(enumValue)
          {
          case GameServerClaimStatus::CLAIMED:
            return "CLAIMED";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace GameServerClaimStatusMapper
    } // namespace Model
  } // namespace GameLift
} // namespace Aws


text:
import json
import logging

from docker import APIClient

from kubeflow.fairing.builders.base_builder import BaseBuilder
from kubeflow.fairing.builders import dockerfile
from kubeflow.fairing.constants import constants

logger = logging.getLogger(__name__)

class DockerBuilder(BaseBuilder):
    """A builder using the local Docker client"""

    def __init__(self,
                 registry=None,
                 image_name=constants.DEFAULT_IMAGE_NAME,
                 base_image=constants.DEFAULT_BASE_IMAGE,
                 preprocessor=None,
                 push=True,
                 dockerfile_path=None,
                 executable_path_prefix=None):
        super().__init__(
            registry=registry,
            image_name=image_name,
            push=push,
            base_image=base_image,
            preprocessor=preprocessor,
            dockerfile_path=dockerfile_path)
        self.executable_path_prefix = executable_path_prefix

    def build(self):
        logging.info("Building image using docker")
        self.docker_client = APIClient(version='auto')
        self._build()
        if self.push:
            self.publish()

    def _build(self):
        """build the docker image"""
        docker_command = self.preprocessor.get_command()
        logger.warning("Docker command: {}".format(docker_command))
        if not docker_command:
            logger.warning("Not setting a command for the output docker image.")
        install_reqs_before_copy = self.preprocessor.is_requirements_txt_file_present()
        if self.dockerfile_path:
            dockerfile_path = self.dockerfile_path
        else:
            dockerfile_path = dockerfile.write_dockerfile(
                docker_command=docker_command,
                path_prefix=self.preprocessor.path_prefix,
                base_image=self.base_image,
                install_reqs_before_copy=install_reqs_before_copy,
                executable_path_prefix=self.executable_path_prefix)
        self.preprocessor.output_map[dockerfile_path] = 'Dockerfile'
        context_file, context_hash = self.preprocessor.context_tar_gz()
        self.image_tag = self.full_image_name(context_hash)
        logger.warning('Building docker image {}...'.format(self.image_tag))
        with open(context_file, 'rb') as fileobj:
            bld = self.docker_client.build(
                path='.',
                custom_context=True,
                fileobj=fileobj,
                tag=self.image_tag,
                encoding='utf-8'
            )
        for line in bld:
            self._process_stream(line)

    def publish(self):
        """push the docker image to the docker registry"""
        logger.warning('Publishing image {}...'.format(self.image_tag))
        for line in self.docker_client.push(self.image_tag, stream=True):
            self._process_stream(line)

    def _process_stream(self, line):
        """
        Parse the docker command output by line

        :param line:  a line of the command output message

        """
        raw = line.decode('utf-8').strip()
        lns = raw.split('\n')
        for ln in lns:
            try:
                ljson = json.loads(ln)
                if ljson.get('error'):
                    msg = str(ljson.get('error', ljson))
                    logger.error('Build failed: %s', msg)
                    raise Exception('Image build failed: ' + msg)
                else:
                    if ljson.get('stream'):
                        msg = 'Build output: {}'.format(
                            ljson['stream'].strip())
                    elif ljson.get('status'):
                        msg = 'Push output: {} {}'.format(
                            ljson['status'],
                            ljson.get('progress')
                        )
                    elif ljson.get('aux'):
                        msg = 'Push finished: {}'.format(ljson.get('aux'))
                    else:
                        msg = str(ljson)
                    logger.info(msg)

            except json.JSONDecodeError:
                logger.warning('JSON decode error: {}'.format(ln))


text:
import * as Actions from '../actions';

type Action = Actions.All;

export function cardsVisibleReducer(state = false, action: Action) {
  switch (action.type) {
    case Actions.SHOW_CARDS:
      return true;
    case Actions.HIDE_CARDS:
    case Actions.LEAVE_GAME:
      return false;
    case Actions.SET_GAME_STATE:
      return action.payload.cardsVisible;
    default:
      return state;
  }
}


text:
using namespace WelsEnc;
#define SVC_ME_TEST_NUM 10
static void FillWithRandomData (uint8_t* p, int32_t Len) {
  for (int32_t i = 0; i < Len; i++) {
    p[i] = rand() % 256;
  }
}

//preprocess related
int32_t SumOf8x8SingleBlock_ref (uint8_t* pRef, const int32_t kiRefStride) {
  int32_t iSum = 0, i;
  for (i = 0; i < 8; i++) {
    iSum +=  pRef[0]    + pRef[1]  + pRef[2]  + pRef[3];
    iSum +=  pRef[4]    + pRef[5]  + pRef[6]  + pRef[7];
    pRef += kiRefStride;
  }
  return iSum;
}
int32_t SumOf16x16SingleBlock_ref (uint8_t* pRef, const int32_t kiRefStride) {
  int32_t iSum = 0, i;
  for (i = 0; i < 16; i++) {
    iSum +=  pRef[0]    + pRef[1]  + pRef[2]  + pRef[3];
    iSum +=  pRef[4]    + pRef[5]  + pRef[6]  + pRef[7];
    iSum    +=  pRef[8]    + pRef[9]  + pRef[10]  + pRef[11];
    iSum    +=  pRef[12]  + pRef[13]  + pRef[14]  + pRef[15];
    pRef += kiRefStride;
  }
  return iSum;
}

void SumOf8x8BlockOfFrame_ref (uint8_t* pRefPicture, const int32_t kiWidth, const int32_t kiHeight,
                               const int32_t kiRefStride,
                               uint16_t* pFeatureOfBlock, uint32_t pTimesOfFeatureValue[]) {
  int32_t x, y;
  uint8_t* pRef;
  uint16_t* pBuffer;
  int32_t iSum;
  for (y = 0; y < kiHeight; y++) {
    pRef = pRefPicture  + kiRefStride * y;
    pBuffer  = pFeatureOfBlock + kiWidth * y;
    for (x = 0; x < kiWidth; x++) {
      iSum = SumOf8x8SingleBlock_c (pRef + x, kiRefStride);

      pBuffer[x] = iSum;
      pTimesOfFeatureValue[iSum]++;
    }
  }
}

void SumOf16x16BlockOfFrame_ref (uint8_t* pRefPicture, const int32_t kiWidth, const int32_t kiHeight,
                                 const int32_t kiRefStride,
                                 uint16_t* pFeatureOfBlock, uint32_t pTimesOfFeatureValue[]) {
  //TODO: this is similar to SumOf8x8BlockOfFrame_c expect the calling of single block func, refactor-able?
  int32_t x, y;
  uint8_t* pRef;
  uint16_t* pBuffer;
  int32_t iSum;
  for (y = 0; y < kiHeight; y++) {
    pRef = pRefPicture  + kiRefStride * y;
    pBuffer  = pFeatureOfBlock + kiWidth * y;
    for (x = 0; x < kiWidth; x++) {
      iSum = SumOf16x16SingleBlock_c (pRef + x, kiRefStride);

      pBuffer[x] = iSum;
      pTimesOfFeatureValue[iSum]++;
    }
  }
}

void InitializeHashforFeature_ref (uint32_t* pTimesOfFeatureValue, uint16_t* pBuf, const int32_t kiListSize,
                                   uint16_t** pLocationOfFeature, uint16_t** pFeatureValuePointerList) {
  //assign location pointer
  uint16_t* pBufPos  = pBuf;
  for (int32_t i = 0 ; i < kiListSize; ++i) {
    pLocationOfFeature[i] =
      pFeatureValuePointerList[i] = pBufPos;
    pBufPos      += (pTimesOfFeatureValue[i] << 1);
  }
}
void FillQpelLocationByFeatureValue_ref (uint16_t* pFeatureOfBlock, const int32_t kiWidth, const int32_t kiHeight,
    uint16_t** pFeatureValuePointerList) {
  //assign each pixel's position
  uint16_t* pSrcPointer  =  pFeatureOfBlock;
  int32_t iQpelY = 0;
  for (int32_t y = 0; y < kiHeight; y++) {
    for (int32_t x = 0; x < kiWidth; x++) {
      uint16_t uiFeature = pSrcPointer[x];
      ST32 (&pFeatureValuePointerList[uiFeature][0], ((iQpelY << 16) | (x << 2)));
      pFeatureValuePointerList[uiFeature] += 2;
    }
    iQpelY += 4;
    pSrcPointer += kiWidth;
  }
}

#define GENERATE_SumOfSingleBlock(anchor, method, flag) \
TEST (SVC_ME_FunTest, method) {\
  uint32_t uiCPUFlags = WelsCPUFeatureDetect(NULL); \
  if ((uiCPUFlags & flag) == 0 && flag != 0) \
    return; \
  ENFORCE_STACK_ALIGN_1D (uint8_t,  uiRefBuf,   16*320, 16);\
  int32_t iRes[2];\
  for (int32_t k = 0; k < SVC_ME_TEST_NUM; k++) {\
    FillWithRandomData (uiRefBuf,16*320);\
    iRes[0] = anchor (uiRefBuf,320);\
    iRes[1] = method (uiRefBuf,320);\
    ASSERT_EQ (iRes[0], iRes[1]);\
  }\
}

GENERATE_SumOfSingleBlock (SumOf8x8SingleBlock_ref, SumOf8x8SingleBlock_c, 0)
GENERATE_SumOfSingleBlock (SumOf16x16SingleBlock_ref, SumOf16x16SingleBlock_c, 0)

#ifdef X86_ASM
GENERATE_SumOfSingleBlock (SumOf8x8SingleBlock_ref, SumOf8x8SingleBlock_sse2, WELS_CPU_SSE2)
GENERATE_SumOfSingleBlock (SumOf16x16SingleBlock_ref, SumOf16x16SingleBlock_sse2, WELS_CPU_SSE2)
#endif

#ifdef HAVE_NEON
GENERATE_SumOfSingleBlock (SumOf8x8SingleBlock_ref, SumOf8x8SingleBlock_neon, WELS_CPU_NEON)
GENERATE_SumOfSingleBlock (SumOf16x16SingleBlock_ref, SumOf16x16SingleBlock_neon, WELS_CPU_NEON)
#endif

#ifdef HAVE_NEON_AARCH64
GENERATE_SumOfSingleBlock (SumOf8x8SingleBlock_ref, SumOf8x8SingleBlock_AArch64_neon, WELS_CPU_NEON)
GENERATE_SumOfSingleBlock (SumOf16x16SingleBlock_ref, SumOf16x16SingleBlock_AArch64_neon, WELS_CPU_NEON)
#endif

#define ENFORCE_NEW_ALIGN_1D(_tp, _nm, _nbuff, _sz, _al) \
_tp *_nbuff = new _tp[(_sz)+(_al)-1]; \
_tp *_nm = _nbuff + ((_al)-1) - (((uintptr_t)(_nbuff + ((_al)-1)) & ((_al)-1))/sizeof(_tp));

#define GENERATE_SumOfFrame(anchor, method, kiWidth, kiHeight, flag) \
TEST (SVC_ME_FunTest, method##_##kiWidth##x##kiHeight) {\
uint32_t uiCPUFlags = WelsCPUFeatureDetect(NULL); \
if ((uiCPUFlags & flag) == 0 && flag != 0) \
  return; \
ENFORCE_NEW_ALIGN_1D (uint8_t, pRefPicture, pRefPictureBuff, ((kiHeight+16)*((((kiWidth+15)>>4)<<4)+16)), 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t, pFeatureOfBlock1, pFeatureOfBlockBuff1, (kiWidth*kiHeight), 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t, pFeatureOfBlock2, pFeatureOfBlockBuff2, (kiWidth*kiHeight), 16) \
uint32_t pTimesOfFeatureValue[2][65536]; \
for (int32_t k = 0; k < SVC_ME_TEST_NUM; k++) {\
  FillWithRandomData (pRefPicture,(kiHeight+16)*((((kiWidth+15)>>4)<<4)+16));\
  memset(pTimesOfFeatureValue[0], 0, 65536*sizeof(uint32_t)); \
  memset(pTimesOfFeatureValue[1], 0, 65536*sizeof(uint32_t)); \
  anchor (pRefPicture,kiWidth,kiHeight,((((kiWidth+15)>>4)<<4)+16),pFeatureOfBlock1,pTimesOfFeatureValue[0]); \
  method (pRefPicture,kiWidth,kiHeight,((((kiWidth+15)>>4)<<4)+16),pFeatureOfBlock2,pTimesOfFeatureValue[1]); \
  for(int32_t j=0;j<kiWidth*kiHeight;j++){\
      ASSERT_EQ (pFeatureOfBlock1[j], pFeatureOfBlock2[j]);\
  }\
  for(int32_t  j=0;j<65536;j++){\
      ASSERT_EQ (pTimesOfFeatureValue[0][j], pTimesOfFeatureValue[1][j]);\
  }\
}\
delete[] pRefPictureBuff; \
delete[] pFeatureOfBlockBuff1; \
delete[] pFeatureOfBlockBuff2; \
}

#define GENERATE_InitializeHashforFeature(anchor, method, kiWidth, kiHeight, flag) \
TEST (SVC_ME_FunTest, method##_##kiWidth##x##kiHeight) {\
uint32_t uiCPUFlags = WelsCPUFeatureDetect(NULL); \
if ((uiCPUFlags & flag) == 0 && flag != 0) \
  return; \
ENFORCE_NEW_ALIGN_1D (uint8_t, pRefPicture, pRefPictureBuff, ((kiHeight+16)*((((kiWidth+15)>>4)<<4)+16)), 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t, pFeatureOfBlock, pFeatureOfBlockBuff, (kiWidth*kiHeight), 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t, pLocation1, pLocationBuff1, (kiWidth*kiHeight)*2, 16) \
ENFORCE_NEW_ALIGN_1D (uint32_t, pTimesOfFeatureValue, pTimesOfFeatureValueBuff, 65536, 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t*, pLocationFeature0, pLocationFeature0Buff, 65536, 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t*, pLocationFeature1, pLocationFeature1Buff, 65536, 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t*, pFeaturePointValueList0, pFeaturePointValueList0Buff, 65536, 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t*, pFeaturePointValueList1, pFeaturePointValueList1Buff, 65536, 16) \
for (int32_t k = 0; k < SVC_ME_TEST_NUM; k++) { \
  FillWithRandomData (pRefPicture,(kiHeight+16)*((((kiWidth+15)>>4)<<4)+16)); \
  memset(pTimesOfFeatureValue, 0, 65536*sizeof(uint32_t)); \
  memset(pLocationFeature0, 0, 65536*sizeof(uint16_t*)); \
  memset(pFeaturePointValueList0, 0, 65536*sizeof(uint16_t*)); \
  memset(pLocationFeature1, 0, 65536*sizeof(uint16_t*)); \
  memset(pFeaturePointValueList1, 0, 65536*sizeof(uint16_t*)); \
  SumOf8x8BlockOfFrame_c (pRefPicture,kiWidth,kiHeight,((((kiWidth+15)>>4)<<4)+16),pFeatureOfBlock,pTimesOfFeatureValue); \
  int32_t iActSize = 65536;\
  anchor ( pTimesOfFeatureValue, pLocation1, iActSize, pLocationFeature0, pFeaturePointValueList0);\
  method ( pTimesOfFeatureValue, pLocation1, iActSize, pLocationFeature1, pFeaturePointValueList1); \
  for(int32_t j =0; j<65536; j++) { \
    EXPECT_EQ (pLocationFeature0[j], pLocationFeature1[j]); \
    EXPECT_EQ (pFeaturePointValueList0[j], pFeaturePointValueList1[j]); \
  } \
} \
delete[] pRefPictureBuff; \
delete[] pFeatureOfBlockBuff; \
delete[] pLocationBuff1; \
delete[] pTimesOfFeatureValueBuff; \
delete[] pLocationFeature0Buff; \
delete[] pFeaturePointValueList0Buff; \
delete[] pLocationFeature1Buff; \
delete[] pFeaturePointValueList1Buff; \
}

#define GENERATE_FillQpelLocationByFeatureValue(anchor, method, kiWidth, kiHeight, flag) \
TEST (SVC_ME_FunTest, method##_##kiWidth##x##kiHeight) {\
uint32_t uiCPUFlags = WelsCPUFeatureDetect(NULL); \
if ((uiCPUFlags & flag) == 0 && flag != 0) \
  return; \
ENFORCE_NEW_ALIGN_1D (uint8_t, pRefPicture, pRefPictureBuff, ((kiHeight+16)*((((kiWidth+15)>>4)<<4)+16)), 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t, pFeatureOfBlock, pFeatureOfBlockBuff, (kiWidth*kiHeight), 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t, pLocation1, pLocationBuff1, (kiWidth*kiHeight)*2, 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t, pLocation2, pLocationBuff2, (kiWidth*kiHeight)*2, 16) \
ENFORCE_NEW_ALIGN_1D (uint32_t, pTimesOfFeatureValue, pTimesOfFeatureValueBuff, 65536, 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t*, pLocationFeature0, pLocationFeature0Buff, 65536, 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t*, pLocationFeature1, pLocationFeature1Buff, 65536, 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t*, pFeaturePointValueList0, pFeaturePointValueList0Buff, 65536, 16) \
ENFORCE_NEW_ALIGN_1D (uint16_t*, pFeaturePointValueList1, pFeaturePointValueList1Buff, 65536, 16) \
for (int32_t k = 0; k < SVC_ME_TEST_NUM; k++) { \
  FillWithRandomData (pRefPicture,(kiHeight+16)*((((kiWidth+15)>>4)<<4)+16)); \
  memset(pTimesOfFeatureValue, 0, 65536*sizeof(uint32_t)); \
  memset(pLocationFeature0, 0, 65536*sizeof(uint16_t*)); \
  memset(pFeaturePointValueList0, 0, 65536*sizeof(uint16_t*)); \
  memset(pLocationFeature1, 0, 65536*sizeof(uint16_t*)); \
  memset(pFeaturePointValueList1, 0, 65536*sizeof(uint16_t*)); \
  SumOf8x8BlockOfFrame_c (pRefPicture,kiWidth,kiHeight,((((kiWidth+15)>>4)<<4)+16),pFeatureOfBlock,pTimesOfFeatureValue); \
  int32_t iActSize = 65536; \
  InitializeHashforFeature_c ( pTimesOfFeatureValue, pLocation1, iActSize, pLocationFeature0, pFeaturePointValueList0); \
  InitializeHashforFeature_c( pTimesOfFeatureValue, pLocation2, iActSize, pLocationFeature1, pFeaturePointValueList1); \
  anchor(pFeatureOfBlock, kiWidth, kiHeight, pFeaturePointValueList0); \
  method(pFeatureOfBlock, kiWidth, kiHeight, pFeaturePointValueList1); \
  for(int32_t j =0; j<kiWidth*kiHeight*2; j++) { \
    EXPECT_EQ (pLocation1[j], pLocation2[j]); \
  } \
} \
delete[] pRefPictureBuff; \
delete[] pFeatureOfBlockBuff; \
delete[] pLocationBuff1; \
delete[] pLocationBuff2; \
delete[] pTimesOfFeatureValueBuff; \
delete[] pLocationFeature0Buff; \
delete[] pFeaturePointValueList0Buff; \
delete[] pLocationFeature1Buff; \
delete[] pFeaturePointValueList1Buff; \
}

GENERATE_InitializeHashforFeature (InitializeHashforFeature_ref, InitializeHashforFeature_c, 10, 10, 0)
GENERATE_FillQpelLocationByFeatureValue (FillQpelLocationByFeatureValue_ref, FillQpelLocationByFeatureValue_c, 16, 16, 0)
GENERATE_InitializeHashforFeature (InitializeHashforFeature_ref, InitializeHashforFeature_c, 640, 320, 0)
GENERATE_FillQpelLocationByFeatureValue (FillQpelLocationByFeatureValue_ref, FillQpelLocationByFeatureValue_c, 640, 320, 0)
#ifdef X86_ASM
GENERATE_InitializeHashforFeature (InitializeHashforFeature_ref, InitializeHashforFeature_sse2, 10, 10, WELS_CPU_SSE2)
GENERATE_FillQpelLocationByFeatureValue (FillQpelLocationByFeatureValue_ref, FillQpelLocationByFeatureValue_sse2, 16,
    16, WELS_CPU_SSE2)
GENERATE_InitializeHashforFeature (InitializeHashforFeature_ref, InitializeHashforFeature_sse2, 640, 320, WELS_CPU_SSE2)
GENERATE_FillQpelLocationByFeatureValue (FillQpelLocationByFeatureValue_ref, FillQpelLocationByFeatureValue_sse2, 640,
    320, WELS_CPU_SSE2)
#endif

GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_c, 1, 1, 0)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_c, 1, 1, 0)
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_c, 1, 320, 0)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_c, 1, 320, 0)
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_c, 640, 320, 0)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_c, 640, 320, 0)

#ifdef X86_ASM
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_sse2, 6, 6, WELS_CPU_SSE2)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_sse2, 6, 6, WELS_CPU_SSE2)
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_sse2, 6, 320, WELS_CPU_SSE2)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_sse2, 6, 320, WELS_CPU_SSE2)
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_sse2, 640, 320, WELS_CPU_SSE2)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_sse2, 640, 320, WELS_CPU_SSE2)

GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_sse4, 8, 2, WELS_CPU_SSE41)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_sse4, 16, 2, WELS_CPU_SSE41)
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_sse4, 8, 320, WELS_CPU_SSE41)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_sse4, 16, 320, WELS_CPU_SSE41)
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_sse4, 640, 320, WELS_CPU_SSE41)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_sse4, 640, 320, WELS_CPU_SSE41)
#endif

#ifdef HAVE_NEON
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_neon, 1, 1, WELS_CPU_NEON)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_neon, 1, 1, WELS_CPU_NEON)
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_neon, 1, 320, WELS_CPU_NEON)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_neon, 1, 320, WELS_CPU_NEON)
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_neon, 640, 320, WELS_CPU_NEON)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_neon, 640, 320, WELS_CPU_NEON)
GENERATE_InitializeHashforFeature (InitializeHashforFeature_ref, InitializeHashforFeature_neon, 10, 10, WELS_CPU_NEON)
GENERATE_FillQpelLocationByFeatureValue (FillQpelLocationByFeatureValue_ref, FillQpelLocationByFeatureValue_neon, 16,
    16, WELS_CPU_NEON)
GENERATE_InitializeHashforFeature (InitializeHashforFeature_ref, InitializeHashforFeature_neon, 640, 320, WELS_CPU_NEON)
GENERATE_FillQpelLocationByFeatureValue (FillQpelLocationByFeatureValue_ref, FillQpelLocationByFeatureValue_neon, 640,
    320, WELS_CPU_NEON)
#endif

#ifdef HAVE_NEON_AARCH64
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_AArch64_neon, 1, 1, WELS_CPU_NEON)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_AArch64_neon, 1, 1, WELS_CPU_NEON)
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_AArch64_neon, 1, 320, WELS_CPU_NEON)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_AArch64_neon, 1, 320, WELS_CPU_NEON)
GENERATE_SumOfFrame (SumOf8x8BlockOfFrame_ref, SumOf8x8BlockOfFrame_AArch64_neon, 640, 320, WELS_CPU_NEON)
GENERATE_SumOfFrame (SumOf16x16BlockOfFrame_ref, SumOf16x16BlockOfFrame_AArch64_neon, 640, 320, WELS_CPU_NEON)
GENERATE_InitializeHashforFeature (InitializeHashforFeature_ref, InitializeHashforFeature_AArch64_neon, 10, 10,
    WELS_CPU_NEON)
GENERATE_FillQpelLocationByFeatureValue (FillQpelLocationByFeatureValue_ref,
    FillQpelLocationByFeatureValue_AArch64_neon, 16, 16, WELS_CPU_NEON)
GENERATE_InitializeHashforFeature (InitializeHashforFeature_ref, InitializeHashforFeature_AArch64_neon, 640, 320,
    WELS_CPU_NEON)
GENERATE_FillQpelLocationByFeatureValue (FillQpelLocationByFeatureValue_ref,
    FillQpelLocationByFeatureValue_AArch64_neon, 640, 320, WELS_CPU_NEON)
#endif


text:
YUI.add('aui-scrollspy-tests', function(Y) {

    var Assert = Y.Assert,
        suite = new Y.Test.Suite('aui-scrollspy'),
        spy;

    function checkActiveLink(id) {
        var target = spy.get('target'),
            activeLink = target.one('.active'),
            activeAnchor = activeLink.one('a');

        Assert.isNotNull(activeLink);
        Assert.areEqual(activeAnchor.getAttribute('href'), id);
    }

    suite.add(new Y.Test.Case({
        name: 'Scrollspy',

        setUp: function() {
            spy = new Y.Scrollspy({
                scrollNode: '#scrollNode',
                target: '#navbar'
            });
        },

        tearDown: function() {
            spy.destructor();
            spy = null;
        },

        'should set attributes': function() {
            Assert.areEqual(spy.get('scrollNode'), Y.one('#scrollNode'));
            Assert.areEqual(spy.get('target'), Y.one('#navbar'));
            Assert.areEqual(spy.get('offset'), 10);
            spy.set('offset', 15);
            Assert.areEqual(spy.get('offset'), 15);
            Assert.areEqual(spy.get('activeGroup'), 'li, .dropdown');
        },

        'should clear cached links': function() {
            Assert.isNotNull(spy.cachedLinks);
            spy.clearCachedLinks();
            Assert.isNull(spy.cachedLinks);
        },

        'first link should be active': function() {
            checkActiveLink('#fat');
        },

        'should change the active link on scrolling': function() {
            checkActiveLink('#fat');
            spy.get('scrollNode').set('scrollTop', 150);

            spy.on('activate', function() {
                checkActiveLink('#mdo');
            });
        }
    }));

    Y.Test.Runner.add(suite);

}, '', {
    requires: ['test', 'aui-scrollspy']
});


text:
@implementation TranscriptData

@synthesize frameRate;

- (id) initWithTimeCodedStrings:(NSArray*)theStrings
{
	self = [super init];
	if (self != nil) {
		if(!theStrings)
		{
			strings = [[NSMutableArray alloc] init];
		}
		else
		{
			strings = [theStrings mutableCopy];
		}
		frameRate = 29;
	}
	return self;
}

- (void) dealloc
{
	[strings release];
	[super dealloc];
}

- (NSArray*)timeCodedStrings
{
	return strings;
}

- (void)encodeWithCoder:(NSCoder *)coder
{
	[super encodeWithCoder:coder];
	[coder encodeObject:strings forKey:@"AnnotationDataArray"];
	[coder encodeFloat:frameRate forKey:@"AnnotationDataFrameRate"];
}

- (id)initWithCoder:(NSCoder *)coder {
    if(self = [super initWithCoder:coder])
	{
		strings = [[coder decodeObjectForKey:@"AnnotationDataArray"] mutableCopy];
		frameRate = [coder decodeFloatForKey:@"AnnotationDataFrameRate"];
	}
    return self;
}

@end


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/renderer_host/render_widget_helper.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/eintr_wrapper.h"
#include "base/lazy_instance.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "content/browser/gpu/gpu_surface_tracker.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/resource_dispatcher_host_impl.h"
#include "content/common/view_messages.h"

using content::BrowserThread;
using content::RenderViewHostImpl;
using content::ResourceDispatcherHostImpl;

namespace {

typedef std::map<int, RenderWidgetHelper*> WidgetHelperMap;
base::LazyInstance<WidgetHelperMap> g_widget_helpers =
    LAZY_INSTANCE_INITIALIZER;

void AddWidgetHelper(int render_process_id,
                     const scoped_refptr<RenderWidgetHelper>& widget_helper) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  // We don't care if RenderWidgetHelpers overwrite an existing process_id. Just
  // want this to be up to date.
  g_widget_helpers.Get()[render_process_id] = widget_helper.get();
}

}  // namespace

// A helper used with DidReceiveBackingStoreMsg that we hold a pointer to in
// pending_paints_.
class RenderWidgetHelper::BackingStoreMsgProxy {
 public:
  BackingStoreMsgProxy(RenderWidgetHelper* h, const IPC::Message& m);
  ~BackingStoreMsgProxy();
  void Run();
  void Cancel() { cancelled_ = true; }

  const IPC::Message& message() const { return message_; }

 private:
  scoped_refptr<RenderWidgetHelper> helper_;
  IPC::Message message_;
  bool cancelled_;  // If true, then the message will not be dispatched.

  DISALLOW_COPY_AND_ASSIGN(BackingStoreMsgProxy);
};

RenderWidgetHelper::BackingStoreMsgProxy::BackingStoreMsgProxy(
    RenderWidgetHelper* h, const IPC::Message& m)
    : helper_(h),
      message_(m),
      cancelled_(false) {
}

RenderWidgetHelper::BackingStoreMsgProxy::~BackingStoreMsgProxy() {
  // If the paint message was never dispatched, then we need to let the
  // helper know that we are going away.
  if (!cancelled_ && helper_)
    helper_->OnDiscardBackingStoreMsg(this);
}

void RenderWidgetHelper::BackingStoreMsgProxy::Run() {
  if (!cancelled_) {
    helper_->OnDispatchBackingStoreMsg(this);
    helper_ = NULL;
  }
}

RenderWidgetHelper::RenderWidgetHelper()
    : render_process_id_(-1),
#if defined(OS_WIN)
      event_(CreateEvent(NULL, FALSE /* auto-reset */, FALSE, NULL)),
#elif defined(OS_POSIX)
      event_(false /* auto-reset */, false),
#endif
      resource_dispatcher_host_(NULL) {
}

RenderWidgetHelper::~RenderWidgetHelper() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  g_widget_helpers.Get().erase(render_process_id_);

  // The elements of pending_paints_ each hold an owning reference back to this
  // object, so we should not be destroyed unless pending_paints_ is empty!
  DCHECK(pending_paints_.empty());

#if defined(OS_MACOSX)
  ClearAllocatedDIBs();
#endif
}

void RenderWidgetHelper::Init(
    int render_process_id,
    ResourceDispatcherHostImpl* resource_dispatcher_host) {
  render_process_id_ = render_process_id;
  resource_dispatcher_host_ = resource_dispatcher_host;

  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&AddWidgetHelper,
                 render_process_id_, make_scoped_refptr(this)));
}

int RenderWidgetHelper::GetNextRoutingID() {
  return next_routing_id_.GetNext() + 1;
}

// static
RenderWidgetHelper* RenderWidgetHelper::FromProcessHostID(
    int render_process_host_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  WidgetHelperMap::const_iterator ci = g_widget_helpers.Get().find(
      render_process_host_id);
  return (ci == g_widget_helpers.Get().end())? NULL : ci->second;
}

void RenderWidgetHelper::CancelResourceRequests(int render_widget_id) {
  if (render_process_id_ == -1)
    return;

  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&RenderWidgetHelper::OnCancelResourceRequests,
                 this,
                 render_widget_id));
}

void RenderWidgetHelper::CrossSiteSwapOutACK(
    const ViewMsg_SwapOut_Params& params) {
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&RenderWidgetHelper::OnCrossSiteSwapOutACK,
                 this,
                 params));
}

bool RenderWidgetHelper::WaitForBackingStoreMsg(
    int render_widget_id,
                                          const base::TimeDelta& max_delay,
                                          IPC::Message* msg) {
  base::TimeTicks time_start = base::TimeTicks::Now();

  for (;;) {
    BackingStoreMsgProxy* proxy = NULL;
    {
      base::AutoLock lock(pending_paints_lock_);

      BackingStoreMsgProxyMap::iterator it =
          pending_paints_.find(render_widget_id);
      if (it != pending_paints_.end()) {
        BackingStoreMsgProxyQueue &queue = it->second;
        DCHECK(!queue.empty());
        proxy = queue.front();

        // Flag the proxy as cancelled so that when it is run as a task it will
        // do nothing.
        proxy->Cancel();

        queue.pop_front();
        if (queue.empty())
          pending_paints_.erase(it);
      }
    }

    if (proxy) {
      *msg = proxy->message();
      DCHECK(msg->routing_id() == render_widget_id);
      return true;
    }

    // Calculate the maximum amount of time that we are willing to sleep.
    base::TimeDelta max_sleep_time =
        max_delay - (base::TimeTicks::Now() - time_start);
    if (max_sleep_time <= base::TimeDelta::FromMilliseconds(0))
      break;

    base::ThreadRestrictions::ScopedAllowWait allow_wait;
    event_.TimedWait(max_sleep_time);
  }

  return false;
}

void RenderWidgetHelper::DidReceiveBackingStoreMsg(const IPC::Message& msg) {
  int render_widget_id = msg.routing_id();

  BackingStoreMsgProxy* proxy = new BackingStoreMsgProxy(this, msg);
  {
    base::AutoLock lock(pending_paints_lock_);

    pending_paints_[render_widget_id].push_back(proxy);
  }

  // Notify anyone waiting on the UI thread that there is a new entry in the
  // proxy map.  If they don't find the entry they are looking for, then they
  // will just continue waiting.
  event_.Signal();

  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
      base::Bind(&BackingStoreMsgProxy::Run, base::Owned(proxy)));
}

void RenderWidgetHelper::OnDiscardBackingStoreMsg(BackingStoreMsgProxy* proxy) {
  const IPC::Message& msg = proxy->message();

  // Remove the proxy from the map now that we are going to handle it normally.
  {
    base::AutoLock lock(pending_paints_lock_);

    BackingStoreMsgProxyMap::iterator it =
        pending_paints_.find(msg.routing_id());
    DCHECK(it != pending_paints_.end());
    BackingStoreMsgProxyQueue &queue = it->second;
    DCHECK(queue.front() == proxy);

    queue.pop_front();
    if (queue.empty())
      pending_paints_.erase(it);
  }
}

void RenderWidgetHelper::OnDispatchBackingStoreMsg(
    BackingStoreMsgProxy* proxy) {
  OnDiscardBackingStoreMsg(proxy);

  // It is reasonable for the host to no longer exist.
  content::RenderProcessHost* host =
      content::RenderProcessHost::FromID(render_process_id_);
  if (host)
    host->OnMessageReceived(proxy->message());
}

void RenderWidgetHelper::OnCancelResourceRequests(
    int render_widget_id) {
  resource_dispatcher_host_->CancelRequestsForRoute(
      render_process_id_, render_widget_id);
}

void RenderWidgetHelper::OnCrossSiteSwapOutACK(
    const ViewMsg_SwapOut_Params& params) {
  resource_dispatcher_host_->OnSwapOutACK(params);
}

void RenderWidgetHelper::CreateNewWindow(
    const ViewHostMsg_CreateWindow_Params& params,
    bool no_javascript_access,
    base::ProcessHandle render_process,
    int* route_id,
    int* surface_id) {
  if (params.opener_suppressed || no_javascript_access) {
    // If the opener is supppressed or script access is disallowed, we should
    // open the window in a new BrowsingInstance, and thus a new process. That
    // means the current renderer process will not be able to route messages to
    // it. Because of this, we will immediately show and navigate the window
    // in OnCreateWindowOnUI, using the params provided here.
    *route_id = MSG_ROUTING_NONE;
    *surface_id = 0;
  } else {
    *route_id = GetNextRoutingID();
    *surface_id = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
        render_process_id_, *route_id);
    // Block resource requests until the view is created, since the HWND might
    // be needed if a response ends up creating a plugin.
    resource_dispatcher_host_->BlockRequestsForRoute(
        render_process_id_, *route_id);
  }

  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&RenderWidgetHelper::OnCreateWindowOnUI,
                 this, params, *route_id));
}

void RenderWidgetHelper::OnCreateWindowOnUI(
    const ViewHostMsg_CreateWindow_Params& params,
    int route_id) {
  RenderViewHostImpl* host =
      RenderViewHostImpl::FromID(render_process_id_, params.opener_id);
  if (host)
    host->CreateNewWindow(route_id, params);

  // We only need to resume blocked requests if we used a valid route_id.
  // See CreateNewWindow.
  if (route_id != MSG_ROUTING_NONE) {
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        base::Bind(&RenderWidgetHelper::OnCreateWindowOnIO, this, route_id));
  }
}

void RenderWidgetHelper::OnCreateWindowOnIO(int route_id) {
  resource_dispatcher_host_->ResumeBlockedRequestsForRoute(
      render_process_id_, route_id);
}

void RenderWidgetHelper::CreateNewWidget(int opener_id,
                                         WebKit::WebPopupType popup_type,
                                         int* route_id,
                                         int* surface_id) {
  *route_id = GetNextRoutingID();
  *surface_id = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
      render_process_id_, *route_id);
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(
          &RenderWidgetHelper::OnCreateWidgetOnUI, this, opener_id, *route_id,
          popup_type));
}

void RenderWidgetHelper::CreateNewFullscreenWidget(int opener_id,
                                                   int* route_id,
                                                   int* surface_id) {
  *route_id = GetNextRoutingID();
  *surface_id = GpuSurfaceTracker::Get()->AddSurfaceForRenderer(
      render_process_id_, *route_id);
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(
          &RenderWidgetHelper::OnCreateFullscreenWidgetOnUI, this,
          opener_id, *route_id));
}

void RenderWidgetHelper::OnCreateWidgetOnUI(
    int opener_id, int route_id, WebKit::WebPopupType popup_type) {
  RenderViewHostImpl* host = RenderViewHostImpl::FromID(
      render_process_id_, opener_id);
  if (host)
    host->CreateNewWidget(route_id, popup_type);
}

void RenderWidgetHelper::OnCreateFullscreenWidgetOnUI(int opener_id,
                                                      int route_id) {
  RenderViewHostImpl* host = RenderViewHostImpl::FromID(
      render_process_id_, opener_id);
  if (host)
    host->CreateNewFullscreenWidget(route_id);
}

#if defined(OS_MACOSX)
TransportDIB* RenderWidgetHelper::MapTransportDIB(TransportDIB::Id dib_id) {
  base::AutoLock locked(allocated_dibs_lock_);

  const std::map<TransportDIB::Id, int>::iterator
      i = allocated_dibs_.find(dib_id);
  if (i == allocated_dibs_.end())
    return NULL;

  base::FileDescriptor fd(dup(i->second), true);
  return TransportDIB::Map(fd);
}

void RenderWidgetHelper::AllocTransportDIB(
    size_t size, bool cache_in_browser, TransportDIB::Handle* result) {
  scoped_ptr<base::SharedMemory> shared_memory(new base::SharedMemory());
  if (!shared_memory->CreateAnonymous(size)) {
    result->fd = -1;
    result->auto_close = false;
    return;
  }

  shared_memory->GiveToProcess(0 /* pid, not needed */, result);

  if (cache_in_browser) {
    // Keep a copy of the file descriptor around
    base::AutoLock locked(allocated_dibs_lock_);
    allocated_dibs_[shared_memory->id()] = dup(result->fd);
  }
}

void RenderWidgetHelper::FreeTransportDIB(TransportDIB::Id dib_id) {
  base::AutoLock locked(allocated_dibs_lock_);

  const std::map<TransportDIB::Id, int>::iterator
    i = allocated_dibs_.find(dib_id);

  if (i != allocated_dibs_.end()) {
    if (HANDLE_EINTR(close(i->second)) < 0)
      PLOG(ERROR) << "close";
    allocated_dibs_.erase(i);
  } else {
    DLOG(WARNING) << "Renderer asked us to free unknown transport DIB";
  }
}

void RenderWidgetHelper::ClearAllocatedDIBs() {
  for (std::map<TransportDIB::Id, int>::iterator
       i = allocated_dibs_.begin(); i != allocated_dibs_.end(); ++i) {
    if (HANDLE_EINTR(close(i->second)) < 0)
      PLOG(ERROR) << "close: " << i->first;
  }

  allocated_dibs_.clear();
}
#endif


text:
<?php
namespace Elastica\Test\Query;

use Elastica\Query\Limit;
use Elastica\Test\Base as BaseTest;

class LimitTest extends BaseTest
{
    /**
     * @group unit
     */
    public function testSetType()
    {
        $query = new Limit(10);
        $this->assertEquals(10, $query->getParam('value'));

        $this->assertInstanceOf('Elastica\Query\Limit', $query->setLimit(20));
        $this->assertEquals(20, $query->getParam('value'));
    }

    /**
     * @group unit
     */
    public function testToArray()
    {
        $query = new Limit(15);

        $expectedArray = [
            'limit' => ['value' => 15],
        ];

        $this->assertEquals($expectedArray, $query->toArray());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <dbname value = "cool_weather"/>
    <version value ="1"/>
    <list>
        <mapping class ="com.example.coolweather.db.Province"/>
        <mapping class="com.example.coolweather.db.City"/>
        <mapping class="com.example.coolweather.db.County"/>
    </list>
</litepal>


text:
layout: page
title: Church - Church Wedding
date: 2016-05-24
author: Noah Dorsey
tags: weekly links, java
status: published
summary: Proin sodales nunc enim, eu lobortis sapien mollis sit.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 08/27/2017
  endDate: 08/31/2017
  ctyhocn: MKCATHX
  groupCode: CCW
published: true
---
Pellentesque neque velit, lacinia sit amet pulvinar quis, fringilla vitae enim. Nullam libero odio, finibus in nunc non, gravida varius sem. Nulla non urna malesuada, dictum sapien eu, tincidunt odio. Donec ultrices, felis ut fringilla blandit, odio elit dictum lectus, consequat pharetra arcu sapien venenatis odio. Vestibulum nec magna at turpis cursus cursus. Mauris nec libero nec nisi cursus auctor non non lorem. Proin faucibus elementum quam, eu egestas ligula ullamcorper sit amet. In ut magna quam. Integer pretium lectus at augue placerat, a tristique quam faucibus.

* Fusce id tellus eget erat pulvinar congue nec nec orci
* Ut elementum risus a elit tincidunt, a semper tellus imperdiet.

Etiam in leo nulla. Aenean in ligula augue. Etiam ut mattis neque, eget iaculis dui. Morbi ornare quam neque, quis consequat ligula bibendum quis. Etiam vestibulum eros lectus, eu feugiat orci rutrum nec. Fusce congue, felis sit amet vulputate varius, est dolor rutrum eros, in imperdiet mauris dui ac nulla. Ut vehicula erat quis velit feugiat pulvinar eget ut mauris.


text:
'use strict';

function cdManageDojoUsersCtrl($scope, $state, $q, cdDojoService, alertService, tableUtils, usSpinnerService,
  cdBadgesService, $translate, initUserTypes, currentUser, utilsService, cdEventsService) {

  var dojoId = $state.params.id;
  var usersDojosLink = [];
  $scope.userTypes = [];
  $scope.userPermissions = [];
  $scope.selectedUserPermissions = {};
  $scope.canUpdateUserPermissions = false;
  $scope.canRemoveUsers = false;
  $scope.userPermissionsModel = {};
  $scope.isDojoAdmin = false;
  $scope.badgeModel = {};
  $scope.awardBadgeButtonModel = {};
  $scope.manageDojoUsersPageTitle = $translate.instant('Manage Dojo Users');
  $scope.invite = {};
  $scope.queryModel = {};
  $scope.pagination = {itemsPerPage: 10};

  initUserTypes.data = _.map(initUserTypes.data, function(userType){
    userType.title = $translate.instant(userType.title);
    return userType;
  });

  var user = currentUser.data;
  $scope.currentUser = user;
  //Show 404 if current user has no permission to view this page
  cdDojoService.getUsersDojos({userId: $scope.currentUser.id, deleted: 0, dojoId: dojoId}, function (usersDojos) {
    var userDojo = usersDojos[0];
    var isDojoAdmin;
    if(userDojo) {
      isDojoAdmin = _.find(userDojo.userPermissions, function (userPermission) {
        return userPermission.name === 'dojo-admin';
      });
    }

    if(!userDojo || !isDojoAdmin) return $state.go('error-404-no-headers');
    $scope.loadPage(true);
  });

  //Updating user permissions and user types require the same permissions.
  //Remove users also requires the same permissions,
  //therefore we can check if the user can update user permissions & delete users by checking the result from the
  //canUpdateUser method.
  canUpdateUser(function (result) {
    $scope.canUpdateUserPermissions = result;
    $scope.canRemoveUsers = result;
  });

  cdBadgesService.listBadges(function (response) {
    $scope.badges = response.badges;
  });

  $scope.pageChanged = function () {
    $scope.loadPage(false);
  };

  $scope.loadPage = function(resetFlag) {
    $scope.queryModel.sort = $scope.queryModel.sort ? $scope.queryModel.sort: {name: -1};
    var loadPageData = tableUtils.loadPage(resetFlag, $scope.pagination.itemsPerPage, $scope.pagination.pageNo, $scope.filterQuery, $scope.queryModel.sort);
    $scope.pagination.pageNo = loadPageData.pageNo;
    $scope.myDojos = [];
    var users;

    async.series([
      getInviteUserTypes,
      getUsersDojosLink,
      loadDojoUsers,
      retrieveEventsAttended,
      getTotalCount
    ], function (err) {
      if(err) console.error(err);
      users = _.compact(users);
      $scope.users = users;
    });

    function getInviteUserTypes(done) {
      cdDojoService.getUsersDojos({userId: user.id, dojoId: dojoId, deleted: 0}, function (usersDojos) {
        if(!usersDojos || usersDojos.length < 1){
          $state.go('my-dojos');
          return done();
        }
        var userDojo = usersDojos[0];
        user.userTypes = userDojo.userTypes;
        var inviteUserTypes = angular.copy(initUserTypes.data);
        if(_.contains(user.userTypes, 'mentor')) {
          inviteUserTypes = _.without(inviteUserTypes, _.findWhere(inviteUserTypes, {name: 'champion'}));
        } else if(_.contains(user.userTypes, 'parent-guardian')) {
          inviteUserTypes = _.chain(inviteUserTypes)
            .without(_.findWhere(inviteUserTypes, {name: 'champion'}))
            .without(_.findWhere(inviteUserTypes, {name: 'mentor'}))
            .value();
        } else if(_.contains(user.userTypes, 'attendee-o13')) {
          $scope.userTypes = _.chain(inviteUserTypes)
            .without(_.findWhere(inviteUserTypes, {name: 'champion'}))
            .without(_.findWhere(inviteUserTypes, {name: 'mentor'}))
            .without(_.findWhere(inviteUserTypes, {name: 'parent-guardian'}))
            .value();
        } else if(_.contains(user.userTypes, 'attendee-u13')) {
          inviteUserTypes = [];
        }
        $scope.userTypes = inviteUserTypes;

        cdDojoService.getUserPermissions(function (response) {
          $scope.userPermissions = response;
          return done();
        });
      });
    }

    function getUsersDojosLink(done) {
      cdDojoService.getUsersDojos({dojoId:dojoId, deleted: 0, limit$: $scope.pagination.itemsPerPage, skip$: loadPageData.skip}, function (response) {
        usersDojosLink = response;
        return done();
      });
    }

    function loadDojoUsers(done) {
      cdDojoService.loadDojoUsers({dojoId:dojoId, limit$: $scope.pagination.itemsPerPage, skip$: loadPageData.skip, sort$: $scope.queryModel.sort}, function (response) {
        _.each(response, function (user) {
          var thisUsersDojoLink = _.findWhere(usersDojosLink, {userId:user.id});
          user.types = thisUsersDojoLink.userTypes;
          user.frontEndTypes = _.map(thisUsersDojoLink.userTypes, function (userType) {
            var userTypeFound = _.find(initUserTypes.data, function (initUserType) {
              return userType === initUserType.name;
            });
            return $translate.instant(userTypeFound.title);
          });
          user.permissions = thisUsersDojoLink.userPermissions;
          user.isMentor = _.contains(user.types, 'mentor');
          user.isDojoOwner = thisUsersDojoLink.owner === 1;
          user.backgroundChecked = thisUsersDojoLink.backgroundChecked;
          user.userDojoId = thisUsersDojoLink.id;
          $scope.selectedUserPermissions[user.id] = user.permissions;
          $scope.userPermissionsModel[user.id] = {};

          _.each(user.permissions, function (permission) {
            $scope.userPermissionsModel[user.id][permission.name] = true;
          });
        });
        users = response;
        return done();
      });
    }

    function retrieveEventsAttended(done) {
      async.each(users, function (user, cb) {
        cdEventsService.searchApplications({dojoId:dojoId, userId: user.id}, function (applications) {
          _.each(applications, function (application) {
            if(application.attendance && application.attendance.length > 0) {
              if(!user.eventsAttended) user.eventsAttended = 0;
              if(application.ticketType !== 'other') user.eventsAttended += application.attendance.length;
            }
          });
          return cb();
        });
      }, done);
    }

    function getTotalCount(done) {
      //Query the loadDojoUsers service without the limit to get the total number of users.
      cdDojoService.loadDojoUsers({dojoId: dojoId, deleted: 0, limit$: 'NULL'}, function (response) {
        $scope.pagination.totalItems = response.length;
        return done();
      });
    }
  };

  $scope.updateMentorBackgroundCheck = function (user) {
    var userDojo = {
      id: user.userDojoId,
      backgroundChecked: user.backgroundChecked
    };

    cdDojoService.saveUsersDojos(userDojo, null, function (err) {
      alertService.showError(JSON.stringify(err));
    });
  }

  $scope.updateUserPermissions = function(user, permission) {
    var hasPermission = false;
    canUpdateUser(function (result) {
      hasPermission = result;
      if (hasPermission) {
        var query = {dojoId:dojoId};
        delete permission.$$hashKey;
        var userDojoLink = _.findWhere(usersDojosLink, {userId:user.id});
        if($scope.userPermissionsModel[user.id][permission.name]) {
          //Add to user permissions
          if(!userDojoLink.userPermissions) userDojoLink.userPermissions = [];
          userDojoLink.userPermissions.push(permission);
          //Save to db
          if(userDojoLink.userTypes[0] && userDojoLink.userTypes[0].text) userDojoLink.userTypes = _.pluck(userDojoLink.userTypes, 'text');
          cdDojoService.saveUsersDojos(userDojoLink, function (response) {
            if(response.error) {
              alertService.showError($translate.instant(response.error));
              //Revert checkbox
              $scope.userPermissionsModel[user.id][permission.name] = !$scope.userPermissionsModel[user.id][permission.name];
            } else {
              alertService.showAlert($translate.instant('User permissions successfully updated.'));
            }
          }, function (err) {
            alertService.showError($translate.instant('Error saving permission') + ' ' + err);
            //Revert checkbox
            $scope.userPermissionsModel[user.id][permission.name] = !$scope.userPermissionsModel[user.id][permission.name];
          });
        } else {
          //Remove from user permissions
          user.permissions = _.without(user.permissions, _.findWhere(user.permissions, {name: permission.name}));
          userDojoLink.userPermissions = user.permissions;
          if(userDojoLink.userTypes[0] && userDojoLink.userTypes[0].text) userDojoLink.userTypes = _.pluck(userDojoLink.userTypes, 'text');
          //Save to db
          cdDojoService.saveUsersDojos(userDojoLink, function (response) {
            if(response.error)  {
              alertService.showError($translate.instant(response.error));
              //Revert checkbox
              $scope.userPermissionsModel[user.id][permission.name] = !$scope.userPermissionsModel[user.id][permission.name];
              //Re-add permission
              user.permissions.push(permission);
            } else {
              alertService.showAlert($translate.instant('User permissions successfully updated.'));
            }
          }, function (err) {
            alertService.showError($translate.instant('Error removing permission') + ' ' +err);
            //Revert checkbox
            $scope.userPermissionsModel[user.id][permission.name] = !$scope.userPermissionsModel[user.id][permission.name];
          });
        }
      } else {
        alertService.showAlert($translate.instant('You do not have permission to update user permissions'));
        //Revert checkbox
        $scope.userPermissionsModel[user.id][permission.name] = !$scope.userPermissionsModel[user.id][permission.name];
      }
    });
  }

  $scope.loadUserTypes = function(query) {
    var filteredUserTypes = _.chain(initUserTypes.data)
      .filter(function (userType) {
       return userType.title.toLowerCase().indexOf(query.toLowerCase()) > -1;
      })
      .map(function (userType) {
        return userType.title;
      })
      .value();

    return filteredUserTypes;
  }

  $scope.pushChangedUser = function(user, method, $tag) {
    var hasPermission = false;
    canUpdateUser(function (result) {
      hasPermission = result;

      if(hasPermission) {

        var updatedUserTypes = _.chain(angular.copy(user.frontEndTypes))
          .pluck('text')
          .map(function (userType) {
            userType = userType.replace(/-/g, ' ');
            var initUserTypeFound = _.find(initUserTypes.data, function (initUserType) {
              return initUserType.title === userType;
            });
            return initUserTypeFound.name;
          })
          .value();

        var userDojoLink = _.findWhere(usersDojosLink, {userId:user.id});
        if(!userDojoLink.userTypes) userDojoLink.userTypes = [];
        userDojoLink.userTypes = updatedUserTypes;
        cdDojoService.saveUsersDojos(userDojoLink, function (response) {
          if(response.error) {
            alertService.showError($translate.instant(response.error));
            //Revert user types
            if(method === 'add') user.frontEndTypes.pop();
            if(method === 'remove') user.frontEndTypes.push($tag);
          } else {
            alertService.showAlert($translate.instant('User types successfully updated.'));
          }
        }, function (err) {
          alertService.showError($translate.instant('Error saving user type') + ' ' + err);
        });
      } else {
        alertService.showAlert($translate.instant('You do not have permission to update user types'));
        if(method === 'add') user.frontEndTypes.pop();
        if(method === 'remove') user.frontEndTypes.push($tag);
      }
    });
  }

  function canUpdateUser(cb) {
    //Can update user types if:
    // - Current user is champion
    // - Current user is Dojo Admin
    function getUsersDojos() {
      return $q(function (resolve, reject) {
        var query = {userId: $scope.currentUser.id, dojoId: dojoId};
        var isChampion;
        var isDojoAdmin;
        cdDojoService.getUsersDojos(query, function (response) {
          var userDojo = response[0];
          isChampion   = _.contains(userDojo.userTypes, 'champion');
          isDojoAdmin  = _.find(userDojo.userPermissions, function(userPermission) {
                          return userPermission.name === 'dojo-admin';
                        });
          if(isDojoAdmin) $scope.isDojoAdmin = true;
          if(isChampion && isDojoAdmin) return resolve(true);
          return resolve(false);
        }, function (err) {
          alertService.showError($translate.instant('Error loading user dojo entity') + ' <br /> ' +
          (err.error || JSON.stringify(err)));
        });
      });
    }

    getUsersDojos().then(function (result) {
      cb(result);
    });
  }

  $scope.inviteUser = function (invite, context) {
    usSpinnerService.spin('manage-dojo-users-spinner');
    cdDojoService.generateUserInviteToken({email:invite.email, emailSubject: $translate.instant('New Dojo Invitation'), userType:invite.userType.name, dojoId:dojoId}, function (response) {
      usSpinnerService.stop('manage-dojo-users-spinner');
      alertService.showAlert($translate.instant('Invite Sent'));
      context.inviteMentorForm.reset();
    }, function (err) {
      usSpinnerService.stop('manage-dojo-users-spinner');
      alertService.showError($translate.instant('Error sending invite') + ' ' + err);
    });
  }

  $scope.removeUser = function (user) {
    if($scope.canRemoveUsers) {
      usSpinnerService.spin('manage-dojo-users-spinner');
      var userId = user.id;
      cdDojoService.removeUsersDojosLink({userId: userId, dojoId: dojoId, emailSubject: $translate.instant('A user has left your Dojo')}, function (response) {
        if(response.error) {
          usSpinnerService.stop('manage-dojo-users-spinner');
          alertService.showError($translate.instant(response.error));
        } else {
          usSpinnerService.stop('manage-dojo-users-spinner');
          alertService.showAlert($translate.instant('User successfully removed from Dojo.'));
          $scope.loadPage(true);
        }
      }, function (err) {
        usSpinnerService.stop('manage-dojo-users-spinner');
        alertService.showError($translate.instant('Error removing user') + ' ' + err);
      });
    } else {
      alertService.showAlert($translate.instant('You do not have permission to remove users'));
    }
  }

  $scope.badgeSelected = function (user) {
    $scope.awardBadgeButtonModel[user.id] = true;
    $scope.$watch('badgeModel', function (val) {
      if(!val[user.id]) $scope.awardBadgeButtonModel[user.id] = false;
    });
  }

  $scope.awardBadge = function (user, badge) {
    usSpinnerService.spin('manage-dojo-users-spinner');
    var applicationData = {
      user: user,
      badge: badge,
      emailSubject: $translate.instant('You have been awarded a new CoderDojo digital badge!')
    };

    cdBadgesService.sendBadgeApplication(applicationData, function (response) {
      usSpinnerService.stop('manage-dojo-users-spinner');
      if(response.error) return alertService.showError($translate.instant(response.error));
      alertService.showAlert($translate.instant('Badge Application Sent!'));
    });
  }

  $scope.toggleSort = function ($event, columnName) {
    var className, descFlag, sortConfig = {};
    var DOWN = 'glyphicon-chevron-down';
    var UP = 'glyphicon-chevron-up';

    function isDesc(className) {
      var result = className.indexOf(DOWN);
      return result > -1;
    }

    className = $($event.target).attr('class');

    descFlag = isDesc(className);
    if (descFlag) {
      sortConfig[columnName] = -1;
    } else {
      sortConfig[columnName] = 1;
    }

    $scope.queryModel.sort = sortConfig;
    $scope.loadPage($scope.filter, true);
  }

  $scope.getSortClass = utilsService.getSortClass;

}

angular.module('cpZenPlatform')
    .controller('manage-dojo-users-controller', ['$scope', '$state', '$q', 'cdDojoService', 'alertService', 'tableUtils', 'usSpinnerService',
    'cdBadgesService', '$translate', 'initUserTypes', 'currentUser', 'utilsService', 'cdEventsService', cdManageDojoUsersCtrl]);


text:
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{{ site.brand }} - {{ site.title }}</title>
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="{{ site.description }}"> {% if site.meta_author %}
    <meta name="author" content="{{ site.meta_author }}"> {% endif %}
    <meta name="mobile-web-app-capable" content="yes" />
    <meta name="theme-color" content="#ef767a" />
    <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="./web-dist/css/main.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.5/js/tether.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!--<script src="https://use.fontawesome.com/266c035ce0.js"></script>-->
    <script src="https://use.fontawesome.com/a3c2ac8751.js"></script>
    <script src="./web-dist/js/app.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js"></script>
    <script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
    <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Comfortaa|Didact+Gothic|Dosis|Libre+Franklin|Muli|Nunito|Quattrocento+Sans|Raleway|Roboto|Rubik|Ubuntu|Varela+Round"
        rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Sail" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">

</head>


text:
Todo:

* Go through the Statusbar Color Tweaks, including screenshots of some of the customizations


text:
package org.myrobotlab.roomba;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.myrobotlab.logging.LoggerFactory;
import org.slf4j.Logger;

/**
 *
 */
public class RTTTLParser {

  public final static Logger log = LoggerFactory.getLogger(RTTTLParser.class);

  public static HashMap<String, Integer> noteToNum;

  static {
    noteToNum = new HashMap<String, Integer>();
    noteToNum.put("c", new Integer(0));
    noteToNum.put("c#", new Integer(1));
    noteToNum.put("d", new Integer(2));
    noteToNum.put("d#", new Integer(3));
    noteToNum.put("e", new Integer(4));
    noteToNum.put("f", new Integer(5));
    noteToNum.put("f#", new Integer(6));
    noteToNum.put("g", new Integer(7));
    noteToNum.put("g#", new Integer(8));
    noteToNum.put("a", new Integer(9));
    noteToNum.put("a#", new Integer(10));
    noteToNum.put("b", new Integer(11));
    noteToNum.put("h", new Integer(7));
  }

  public static int bpmToMillis(int bpm) {
    return (60 * 1000) / bpm;
  }

  public static void main(String[] args) {
    if (args.length == 0) {
      log.info("usage: roombacomm.RTTTLParser <rttlstring>");
      return;
    }
    String rtttl = args[0];
    ArrayList<Note> notelist = parse(rtttl);
    for (int i = 0; i < notelist.size(); i++) {
      log.info("notelist[" + i + "]=" + notelist.get(i));
    }
  }

  public static ArrayList<Note> parse(String rtttl) {
    log.info("parsing: " + rtttl);
    String rtttl_working = rtttl.toLowerCase();
    String parts[] = rtttl_working.split(":");
    // String name = parts[0];
    String defaults[] = parts[1].split("[,=]");
    String notes[] = parts[2].split(",");

    // global defaults
    int bpm = 63;
    int octave = 6;
    int duration = 4;

    ArrayList<Note> notelist = new ArrayList<Note>();

    for (int i = 0; i < defaults.length; i++) {
      // System.out.println("defaults["+i+"]="+defaults[i]);
      if (defaults[i].equals("b"))
        try {
          bpm = Integer.parseInt(defaults[i + 1]);
        } catch (Exception e) {
        }
      else if (defaults[i].equals("o"))
        try {
          octave = Integer.parseInt(defaults[i + 1]);
        } catch (Exception e) {
        }
      else if (defaults[i].equals("d"))
        try {
          duration = Integer.parseInt(defaults[i + 1]);
        } catch (Exception e) {
        }
    }
    log.info("bpm:" + bpm + ",octave:" + octave + ",duration:" + duration);

    for (int i = 0; i < notes.length; i++) {
      Matcher m = Pattern.compile("(\\d+)*(.+?)(\\d)*(\\.)*").matcher(notes[i]);
      m.find();
      // group(1) == duration (optional)
      // group(2) == note (required)
      // group(3) == scale (optional)
      // group(4) == triplet (optional)
      int dur = duration;
      int oct = octave;
      if (m.group(1) != null)
        try {
          dur = Integer.parseInt(m.group(1));
        } catch (Exception e) {
        }
      if (m.group(4) != null && m.group(4).equals("."))
        dur += dur / 2;
      if (m.group(3) != null)
        try {
          oct = Integer.parseInt(m.group(3));
        } catch (Exception e) {
        }
      if (m.group(2) != null) {
        int notenum;
        if (m.group(2).equals("p")) {
          notenum = 0;
        } else {
          Integer nn = noteToNum.get(m.group(2));
          notenum = nn.intValue();
          notenum = notenum + 12 * oct;
        }
        dur = bpmToMillis(bpm) / dur;
        notelist.add(new Note(notenum, dur));
      }
    }
    return notelist;
  }
}


text:
'use strict';

var fs = require('fs');
var path = require('path');
var lazy = require('lazy-cache')(require);

module.exports = function(dir) {
  if (typeof dir !== 'string') {
    throw new TypeError('expected "' + dir + '" to be a string');
  }

  var dirs = fs.readdirSync(dir);
  var len = dirs.length;
  var idx = -1;
  var res = {}

  while (++idx < len) {
    var name = dirs[idx];
    var fp = path.resolve(dir, name);

    if (isJavaScriptFile(fp)) {
      defineProp(res, basename(name), lazy(fp));
    }
  }
  return res;
};

/**
 * Return true if the file is a `.js` file.
 *
 * @param {String} filepath
 * @return {Boolean}
 */

function isJavaScriptFile(filepath) {
  if (!fs.statSync(filepath).isFile()) {
    return false;
  }
  if (path.basename(filepath) === 'index.js') {
    return false;
  }
  return filepath.slice(-3) === '.js';
}

/**
 * Since we know the file should always be a `.js` file,
 * we can just remove the last 3 characters to get
 * the name.
 *
 * @param {String} filepath
 * @return {String}
 */

function basename(filepath) {
  return filepath.slice(0, filepath.length - 3);
}

function defineProp(cache, name, fn) {
  Object.defineProperty(cache, name, {
    enumerable: true,
    configurable: true,
    get: function () {
      return fn();
    }
  });
}


text:
SYNONYM

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

#### Published in
Trans. Br. mycol. Soc. 76(2): 317 (1981)

#### Original name
Gnomonia pseudoplatani Tubeuf, 1930

### Remarks
null


text:
package com.riddle;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
 *
 * @author Anand11.Singh
 *
 */
public class PrintComments {

	public static void main(String[] args) throws IOException {
		File file = new File("resources\\code.txt");
		FileReader fileReader = new FileReader(file);
		BufferedReader reader = new BufferedReader(fileReader);
		StringBuilder builder = new StringBuilder();
		String line = reader.readLine();
		while (line != null) {
			builder.append(line).append("\n");
			line = reader.readLine();
		}
		reader.close();
		print(builder.toString());
	}

	public static void print(String str) {
		char[] chars = str.toCharArray();
		int len = chars.length;
		boolean singleLineComment = false;
		boolean multiLineComment = false;
		int offset = 0;
		for (int i = 0; i < len; i++) {
			if (!multiLineComment && !singleLineComment && i + 2 < len && chars[i] == '/' && chars[i + 1] == '*'
					&& chars[i + 2] == '*') {
				multiLineComment = true;
				offset = i;
				i += 3;
			} else if (multiLineComment && !singleLineComment && i + 2 < len && chars[i] == '*' && chars[i + 1] == '*'
					&& chars[i + 2] == '/') {
				multiLineComment = false;
				System.out.println(new String(chars, offset, (i + 2) - offset + 1));
			} else if (!multiLineComment && !singleLineComment && i + 1 < len && chars[i] == '/'
					&& chars[i + 1] == '/') {
				singleLineComment = true;
				offset = i;
				i += 2;
			} else if (singleLineComment && chars[i] == '\n') {
				singleLineComment = false;
				System.out.println(new String(chars, offset, (i - 1) - offset + 1));
			}
		}
	}

}