text:
const express = require('express')
const router = express.Router()

const passport = require('../config/passport')

const removePoll = require('./privateArea/handlers/handleDeletePoll')
const getPollInfo = require('./privateArea/handlers/handlePostInfoPoll')
const updateStatus = require('./privateArea/handlers/handleUpdateStatus')
const getUserPolls = require('./privateArea/handlers/handleUserPolls')
const infoPoll = require('./infoPoll/handlers/handleInfoPoll')
const handleVote = require('./vote/handlers/handleVote')
const handleUpdateImg = require('./infoPoll/handlers/handleUpdateImg')
const getPolls = require('./home/handlers/handleGetPolls')
const checkVote = require('../middlewares/checkVote')
const checkLogin = require('../middlewares/checkLogin')

router.put('/api/poll/:pollId/vote/:voteIds', checkLogin, checkVote, handleVote)
router.get('/api/infoPoll/:id', infoPoll)
router.get('/api/getPolls/', getPolls)
router.get('/api/infoUser/:id', passport.authenticate('jwt', { session: false }), getUserPolls)
router.post('/privateArea/', getPollInfo)
router.post('/api/updateImg/:id', handleUpdateImg)

router.delete('/api/privateArea/:id', passport.authenticate('jwt', { session: false }), removePoll)
router.put('/api/privateArea/:id/:status', passport.authenticate('jwt', { session: false }), updateStatus)

module.exports = router


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

#nullable enable

using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Text
{
    /// <summary>
    /// Describes a single change when a particular span is replaced with a new text.
    /// </summary>
    public readonly struct TextChange : IEquatable<TextChange>
    {
        /// <summary>
        /// The original span of the changed text.
        /// </summary>
        public TextSpan Span { get; }

        /// <summary>
        /// The new text.
        /// </summary>
        public string NewText { get; }

        /// <summary>
        /// Initializes a new instance of <see cref="TextChange"/>
        /// </summary>
        /// <param name="span">The original span of the changed text.</param>
        /// <param name="newText">The new text.</param>
        public TextChange(TextSpan span, string newText)
            : this()
        {
            if (newText == null)
            {
                throw new ArgumentNullException(nameof(newText));
            }

            this.Span = span;
            this.NewText = newText;
        }

        /// <summary>
        /// Provides a string representation for <see cref="TextChange"/>.
        /// </summary>
        public override string ToString()
        {
            return string.Format("{0}: {{ {1}, \"{2}\" }}", this.GetType().Name, Span, NewText);
        }

        public override bool Equals(object? obj)
        {
            return obj is TextChange && this.Equals((TextChange)obj);
        }

        public bool Equals(TextChange other)
        {
            return
                EqualityComparer<TextSpan>.Default.Equals(this.Span, other.Span) &&
                EqualityComparer<string>.Default.Equals(this.NewText, other.NewText);
        }

        public override int GetHashCode()
        {
            return Hash.Combine(this.Span.GetHashCode(), this.NewText.GetHashCode());
        }

        public static bool operator ==(TextChange left, TextChange right)
        {
            return left.Equals(right);
        }

        public static bool operator !=(TextChange left, TextChange right)
        {
            return !(left == right);
        }

        /// <summary>
        /// Converts a <see cref="TextChange"/> to a <see cref="TextChangeRange"/>.
        /// </summary>
        /// <param name="change"></param>
        public static implicit operator TextChangeRange(TextChange change)
        {
            return new TextChangeRange(change.Span, change.NewText.Length);
        }

        /// <summary>
        /// An empty set of changes.
        /// </summary>
        public static IReadOnlyList<TextChange> NoChanges => SpecializedCollections.EmptyReadOnlyList<TextChange>();
    }
}

redpajama_set_name: RedPajamaGithub


text:
using BEPUphysics.BroadPhaseEntries.MobileCollidables;
using BEPUphysics.EntityStateManagement;

using BEPUphysics.CollisionShapes.ConvexShapes;
using BEPUutilities;

namespace BEPUphysics.Entities.Prefabs
{
    /// <summary>
    /// Cone-shaped object that can collide and move.  After making an entity, add it to a Space so that the engine can manage it.
    /// </summary>
    public class Cone : Entity<ConvexCollidable<ConeShape>>
    {
        /// <summary>
        /// Gets or sets the length of the cone.
        /// </summary>
        public float Height
        {
            get
            {
                return CollisionInformation.Shape.Height;
            }
            set
            {
                CollisionInformation.Shape.Height = value;
            }
        }

        /// <summary>
        /// Gets or sets the radius of the cone.
        /// </summary>
        public float Radius
        {
            get
            {
                return CollisionInformation.Shape.Radius;
            }
            set
            {
                CollisionInformation.Shape.Radius = value;
            }
        }

        private Cone(float high, float rad)
            :base(new ConvexCollidable<ConeShape>(new ConeShape(high, rad)))
        {
        }

        private Cone(float high, float rad, float mass)
            :base(new ConvexCollidable<ConeShape>(new ConeShape(high, rad)), mass)
        {
        }

        /// <summary>
        /// Constructs a physically simulated cone.
        /// </summary>
        /// <param name="position">Position of the cone.</param>
        /// <param name="height">Height of the cone.</param>
        /// <param name="radius">Radius of the cone.</param>
        /// <param name="mass">Mass of the object.</param>
        public Cone(Vector3 position, float height, float radius, float mass)
            : this(height, radius, mass)
        {
            Position = position;
        }

        /// <summary>
        /// Constructs a nondynamic cone.
        /// </summary>
        /// <param name="position">Position of the cone.</param>
        /// <param name="height">Height of the cone.</param>
        /// <param name="radius">Radius of the cone.</param>
        public Cone(Vector3 position, float height, float radius)
            : this(height, radius)
        {
            Position = position;
        }

        /// <summary>
        /// Constructs a physically simulated cone.
        /// </summary>
        /// <param name="motionState">Motion state specifying the entity's initial state.</param>
        /// <param name="height">Height of the cone.</param>
        /// <param name="radius">Radius of the cone.</param>
        /// <param name="mass">Mass of the object.</param>
        public Cone(MotionState motionState, float height, float radius, float mass)
            : this(height, radius, mass)
        {
            MotionState = motionState;
        }

        /// <summary>
        /// Constructs a nondynamic cone.
        /// </summary>
        /// <param name="motionState">Motion state specifying the entity's initial state.</param>
        /// <param name="height">Height of the cone.</param>
        /// <param name="radius">Radius of the cone.</param>
        public Cone(MotionState motionState, float height, float radius)
            : this(height, radius)
        {
            MotionState = motionState;
        }

    }
}


text:
package com.example.english.app;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class clubdesActivity extends AppCompatActivity {
    Button clubstart;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clubdes);
        clubstart = (Button) findViewById(R.id.button27);
        clubstart.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivity(new Intent(clubdesActivity.this,clubstartActivity.class));
                // Perform action on click
            }
        });
    }
}


text:
//Apache2, 2017, WinterDev
//Apache2, 2009, griffm, FO.NET
namespace Fonet.Cli.Parser
{
    /// <summary>
    /// An option that does not expect a parameter.
    /// </summary>
    internal class ParameterlessOption : Option
    {
        /// <summary>
        /// Initializes a new instance of the ParameterlessOption class.
        /// </summary>
        /// <param name="optionName">The name of the option.</param>
        public ParameterlessOption(string optionName)
            : base(optionName)
        {
        }

        /// <summary>
        /// Gets a value indicating whether the option expects an argument.
        /// </summary>
        public override bool ExpectsArgument
        {
            get { return false; }
        }

        /// <summary>
        /// Gets or sets the option's argument.
        /// </summary>
        public override string Argument
        {
            get { throw new CommandLineException("This option cannot have an argument"); }
            set { throw new CommandLineException("This option cannot have an argument"); }
        }
    }
}


text:
import argparse
import os

def processArgv( argv ):
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description =
            "PCHGenerator is a tool for support precompiled header generation. "
            "It scans source files in project and selects the most often used headers "
            "for putting them into precompiled header.",

        epilog =
            "Examples:\n"
            "pch.py -c='-I. -I.. -DDEBUG' main.cpp impl.cpp\n"
            "pch.py -c='-I/boost' -e boost -x serialization thread -- main.cpp\n\n"
            "Author: Lukasz Czerwinski (wo3kie@gmail.com)(https://github.com/wo3kie/pchGenerator)"
    )

    parser.add_argument(
        '-w', '--watch-header',
        default="",
        help=
            'Print debug information for particular header.'
            ' Exact full path expected (eg.:'
            ' C:/MinGW/bin/../lib/gcc/mingw32/3.4.5/../../../../include/c++/3.4.5/vector).'
    )

    parser.add_argument(
        '-t', '--threshold',
        default=50,
        type=int,
        help=
            'Threshold in range 1-100 (default 50) (%%).'
            ' Specifies in how many percent of source files'
            ' a header should appeared, to put it into precompiled header.'
    )

    parser.add_argument(
        '-c', '--compilation-options',
        default="",
        help=
            'Options passed to compiler.'
            ' Compilation options are removed (g++: -c -fPIC).'
            ' Preprocessing option is added (g++: -E).'
            ' Header usage info option is added (g++: -H).'
    )

    parser.add_argument(
        '-e', '--exclude',
        default=[],
        nargs='*',
        help=
            'Do not put such files in PCHeader'
            ' (eg.: -e boost, ignore all boost headers).'
    )

    parser.add_argument(
        '-x', '--exclude-except',
        default=[],
        nargs='*',
        help=
            'Exceptions from exclude list'
            ' (eg.: -e boost -x thread, ignore all boost but thread headers).'
    )

    parser.add_argument(
        '-o', '--output',
        default='precompiled.h',
        help=
            'Output filename (default precompiled.h).'
    )

    parser.add_argument(
        '-p', '--project-path',
        default='',
        help=
            'Path to your project (default `cwd`).'
            ' Used to distinguish projects headers from others.'
    )

    parser.add_argument(
        'files',
        nargs='+',
        help=
            'Source files to be processed.'
    )

    result = parser.parse_args( argv )

    if result.project_path == '':
        result.project_path = os.getcwd()

    return result


text:
<?php
namespace Ecbatana\Controller;

use Ecbatana\Database\Database as Database;
use Ecbatana\Controller\Loader as Loader;

class Controller
{
	/**
	 * Variable to hold the database instance
	 *
	 * @var obj
	 */

	private $db;

	/**
	 * Variable to hold the loader instance
	 *
	 * @var obj
	 */

	protected $load;

	/**
	 * Variable to hold the model list
	 *
	 * @var array
	 */

	private $modelList = array();

	/**
	 * This method is used to run the load function from Loader class
	 *
	 * @return TODO
	 */

	protected function load($action, $path, $data = null)
	{
		$this->load = new Loader;
		$this->db = new Database;
		$this->db->run();

		switch ($action) {
			case 'view':
				$view = $path;
				$this->load->view($view, $data);
				break;

			case 'model':
				$model = $path;
				if ($this->load->model($model) === true) {
					$this->{$model} = new $model;
				}
				break;

			default:
				# code...
				break;
		}
	}
}


text:
package io.smalldata.ohmageomh.data.repository;

import io.smalldata.ohmageomh.data.domain.DataPoint;
import io.smalldata.ohmageomh.data.domain.DataPointSearchCriteria;
import io.smalldata.ohmageomh.data.domain.LastDataPointDate;

import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;

/**
 * A set of data point repository methods not automatically implemented by Spring Data repositories.
 *
 * @author Emerson Farrugia
 */
public interface CustomDataPointRepository {

    Iterable<DataPoint> findBySearchCriteria(DataPointSearchCriteria searchCriteria, @Nullable Integer offset,
                                             @Nullable Integer limit);

    List<LastDataPointDate> findLastDataPointDate(List<String> userIds, DataPointSearchCriteria criteria, String dateField);
}


text:
all: clean build style

build:
	platformio run

run:
	platformio run -t upload

clean:
	rm -rf docs
	platformio run -t clean

doc:
	doxygen

style:
	astyle --style=java src/ubx_decoder.cpp


text:
Présentation jouée au perfUG le 28 aout 2014.

Lancez `grunt serve` pour exposer la présentation sur
[http://localhost:8000/]()


text:
using System;

namespace Keywords.Yield
{
    class cs1
    {
        static void Calc(decimal dividends, decimal price)
        {
            // yield には歩留まりとか出来高みたいな意味があって、
            // こういう変数名を使う人がいてもおかしくはない
            decimal yield = dividends / price;
            Console.WriteLine(yield);
        }
    }
}


text:
namespace quipper {

bool ParsePerfStatFileToProto(const string& path, PerfStatProto* proto) {
  std::vector<char> data;
  if (!FileToBuffer(path, &data)) {
    return false;
  }
  string data_str(data.begin(), data.end());
  return ParsePerfStatOutputToProto(data_str, proto);
}

bool ParsePerfStatOutputToProto(const string& data, PerfStatProto* proto) {
  std::vector<string> lines;
  SplitString(data, '\n', &lines);
  uint64_t time_ms = 0;
  for (size_t i = 0; i < lines.size(); ++i) {
    TrimWhitespace(&lines[i]);
    // Look for lines of the form:
    // "name: 123 123 123"
    // OR
    // "1.234 seconds time elapsed"
    std::vector<string> tokens;
    SplitString(lines[i], ' ', &tokens);
    if (tokens.size() != 4) {
      continue;
    }
    const string& first_token = tokens[0];
    // Look for "name: 123 123 123"
    if (first_token.back() == ':') {
      char* endptr;
      uint64_t count = strtoull(tokens[1].c_str(), &endptr, 10);
      if (*endptr != '\0') {
        continue;
      }
      auto newline = proto->add_line();
      newline->set_count(count);
      newline->set_event_name(first_token.substr(0, first_token.size() - 1));
    }
    // Look for "1.234 seconds time elapsed"
    if (tokens[1] == "seconds" &&
        !SecondsStringToMillisecondsUint64(first_token, &time_ms)) {
      time_ms = 0;
    }
  }
  if (time_ms != 0) {
    for (int i = 0; i < proto->line_size(); ++i) {
      proto->mutable_line(i)->set_time_ms(time_ms);
    }
  }
  return proto->line_size() > 0;
}

bool SecondsStringToMillisecondsUint64(const string& str, uint64_t* out) {
  char* endptr;
  double seconds = strtod(str.c_str(), &endptr);
  if (*endptr != '\0') {
    return false;
  }
  if (seconds < 0) {
    return false;
  }
  *out = (static_cast<uint64_t>(seconds * 1000.0 + 0.5));
  return true;
}

}  // namespace quipper


text:
================
salt.modules.apt
================

.. automodule:: salt.modules.apt
    :members:
    :exclude-members: available_version


text:
module Pione
  module Command
    # BasicCommand provides PIONE's basic command structure. PIONE commands have
    # 4 phases: "init", "setup", "execution", "termination". Concrete commands
    # implement some processings as each phases.
    class BasicCommand < Rootage::StandardCommand
      phase(:init) do |seq|
        seq.clear
        seq << Rootage::InitAction.signal_trap
        seq << Rootage::InitAction.option
        seq << Rootage::InitAction.argument
        seq << Rootage::InitAction.program_name
        seq << InitAction.front
        seq << Rootage::InitAction.program_name # for showing front address
      end

      # Return the program name with the front URI and the parent's front URI.
      def program_name
        additions = []

        # front server URI
        if model[:front]
          additions << "front: %s" % model[:front].uri
        end

        # parent front server URI
        if model[:parent_front]
          additions << "parent: %s" % model[:parent_front].uri
        end

        if additions.empty?
          name
        else
          "%s (%s)" % [name, additions.join(", ")]
        end
      end

      # Exit the running command and return failure status. Note that this
      # method enters termination phase before it exits.
      def abort(msg_or_exception, option={})
        pos = option[:pos] || caller(1).first

        # hide the message because some option errors are meaningless
        if msg_or_exception.is_a?(HideableOptionError)
          Log::Debug.system(msg_or_exception.message, pos)
        end

        super
      end

      private

      def exit_process
        model[:front].terminate if model[:front]
        Global.system_logger.terminate
      end
    end
  end
end


text:
/*

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.
*/

package core

import (
	"fmt"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
	"github.com/onsi/gomega"
	mutationsinternal "github.com/open-policy-agent/gatekeeper/apis/mutations/unversioned"
	mutationsv1 "github.com/open-policy-agent/gatekeeper/apis/mutations/v1"
	podstatus "github.com/open-policy-agent/gatekeeper/apis/status/v1beta1"
	"github.com/open-policy-agent/gatekeeper/pkg/controller/mutatorstatus"
	"github.com/open-policy-agent/gatekeeper/pkg/fakes"
	"github.com/open-policy-agent/gatekeeper/pkg/mutation"
	"github.com/open-policy-agent/gatekeeper/pkg/mutation/match"
	"github.com/open-policy-agent/gatekeeper/pkg/mutation/mutators"
	mutationschema "github.com/open-policy-agent/gatekeeper/pkg/mutation/schema"
	"github.com/open-policy-agent/gatekeeper/pkg/mutation/types"
	"github.com/open-policy-agent/gatekeeper/pkg/readiness"
	"github.com/open-policy-agent/gatekeeper/test/testutils"
	"github.com/pkg/errors"
	"github.com/prometheus/client_golang/prometheus"
	"golang.org/x/net/context"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	apiTypes "k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/rest"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
	"sigs.k8s.io/controller-runtime/pkg/event"
	"sigs.k8s.io/controller-runtime/pkg/manager"
	"sigs.k8s.io/controller-runtime/pkg/metrics"
	"sigs.k8s.io/controller-runtime/pkg/source"
)

const timeout = time.Second * 15

func makeValue(v interface{}) mutationsv1.AssignField {
	return mutationsv1.AssignField{Value: &types.Anything{Value: v}}
}

// setupManager sets up a controller-runtime manager with registered watch manager.
func setupManager(t *testing.T) manager.Manager {
	t.Helper()

	metrics.Registry = prometheus.NewRegistry()
	mgr, err := manager.New(cfg, manager.Options{
		MetricsBindAddress: "0",
		MapperProvider: func(c *rest.Config) (meta.RESTMapper, error) {
			return apiutil.NewDynamicRESTMapper(c)
		},
		Logger: testutils.NewLogger(t),
	})
	if err != nil {
		t.Fatalf("setting up controller manager: %s", err)
	}
	return mgr
}

func newAssign(name, location, value string) *mutationsv1.Assign {
	return &mutationsv1.Assign{
		TypeMeta: metav1.TypeMeta{
			APIVersion: mutationsv1.GroupVersion.String(),
			Kind:       "Assign",
		},
		ObjectMeta: metav1.ObjectMeta{Name: name},
		Spec: mutationsv1.AssignSpec{
			ApplyTo:  []match.ApplyTo{{Groups: []string{""}, Versions: []string{"v1"}, Kinds: []string{"ConfigMap"}}},
			Location: location,
			Parameters: mutationsv1.Parameters{
				Assign: makeValue(value),
			},
		},
	}
}

func TestReconcile(t *testing.T) {
	g := gomega.NewGomegaWithT(t)
	mutator := &mutationsv1.Assign{
		ObjectMeta: metav1.ObjectMeta{
			Name: "assign-test-obj",
		},
		Spec: mutationsv1.AssignSpec{
			ApplyTo:  []match.ApplyTo{{Groups: []string{""}, Versions: []string{"v1"}, Kinds: []string{"ConfigMap"}}},
			Location: "spec.test",
			Parameters: mutationsv1.Parameters{
				Assign: makeValue("works"),
			},
		},
	}
	objName := apiTypes.NamespacedName{Name: "assign-test-obj"}

	// Setup the Manager and Controller.  Wrap the Controller Reconcile function so it writes each request to a
	// channel when it is finished.
	mgr := setupManager(t)
	c := mgr.GetClient()

	// creating the gatekeeper-system namespace is necessary because that's where
	// status resources live by default
	if err := createGatekeeperNamespace(mgr.GetConfig()); err != nil {
		t.Fatalf("want createGatekeeperNamespace(mgr.GetConfig()) error = nil, got %v", err)
	}

	mSys := mutation.NewSystem(mutation.SystemOpts{})

	tracker, err := readiness.SetupTracker(mgr, true, false)
	if err != nil {
		t.Fatal(err)
	}
	testutils.Setenv(t, "POD_NAME", "no-pod")

	pod := fakes.Pod(
		fakes.WithNamespace("gatekeeper-system"),
		fakes.WithName("no-pod"),
	)

	kind := "Assign"
	newObj := func() client.Object { return &mutationsv1.Assign{} }
	newMutator := func(obj client.Object) (types.Mutator, error) {
		assign := obj.(*mutationsv1.Assign) // nolint:forcetypeassert
		unversioned := &mutationsinternal.Assign{}
		if err := mgr.GetScheme().Convert(assign, unversioned, nil); err != nil {
			return nil, err
		}
		return mutators.MutatorForAssign(unversioned)
	}
	events := make(chan event.GenericEvent, 1024)

	rec := newReconciler(mgr, mSys, tracker, func(ctx context.Context) (*corev1.Pod, error) { return pod, nil }, kind, newObj, newMutator, events)
	adder := Adder{EventsSource: &source.Channel{Source: events}}

	err = adder.add(mgr, rec)
	if err != nil {
		t.Fatal(err)
	}

	statusAdder := &mutatorstatus.Adder{}
	err = statusAdder.Add(mgr)
	if err != nil {
		t.Fatal(err)
	}

	ctx := context.Background()
	testutils.StartManager(ctx, t, mgr)

	t.Run("Can add a mutator", func(t *testing.T) {
		err := c.Create(ctx, mutator.DeepCopy())
		if err != nil {
			t.Fatal(err)
		}
	})

	t.Run("Mutator is reported as enforced", func(t *testing.T) {
		g.Eventually(func() error {
			v := &mutationsv1.Assign{}
			v.SetName("assign-test-obj")
			if err := c.Get(ctx, objName, v); err != nil {
				return errors.Wrap(err, "cannot get mutator")
			}
			if len(v.Status.ByPod) < 1 {
				return errors.Errorf("no pod status reported: %+v", v)
			}
			if !v.Status.ByPod[0].Enforced {
				return errors.New("pod not reported as enforced")
			}
			return nil
		}, timeout).Should(gomega.Succeed())
	})

	t.Run("System mutates a resource", func(t *testing.T) {
		u := &unstructured.Unstructured{}
		u.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ConfigMap"})
		_, err := mSys.Mutate(&types.Mutable{Object: u, Source: types.SourceTypeDefault})
		if err != nil {
			t.Fatal(err)
		}

		v, exists, err := unstructured.NestedString(u.Object, "spec", "test")
		if err != nil {
			t.Fatal(err)
		}
		if !exists {
			t.Fatal("mutated value is missing")
		}
		if v != "works" {
			t.Fatalf(`value = %s, expected "works"`, v)
		}
	})

	t.Run("Mutation deletion is honored", func(t *testing.T) {
		err := c.Delete(ctx, mutator.DeepCopy())
		if err != nil {
			t.Fatal(err)
		}
		g.Eventually(func() error {
			u := &unstructured.Unstructured{}
			u.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ConfigMap"})

			_, err := mSys.Mutate(&types.Mutable{Object: u, Source: types.SourceTypeOriginal})
			if err != nil {
				t.Fatal(err)
			}

			_, exists, err := unstructured.NestedString(u.Object, "spec", "test")
			if err != nil {
				return err
			}
			if exists {
				return errors.New("mutated value still exists")
			}
			return nil
		}, timeout).Should(gomega.Succeed())
	})

	t.Run("Conflicting mutators are marked not enforced and conflicts can be resolved", func(t *testing.T) {
		mFoo := newAssign("foo", "spec.foo", "value-1")
		mFooID := types.MakeID(mFoo)
		mBar1 := newAssign("bar-1", "spec.bar[name: bar].qux", "value-2")
		mBar1ID := types.MakeID(mBar1)
		mBar2 := newAssign("bar-2", "spec.bar.qux", "value-3")
		mBar2ID := types.MakeID(mBar2)

		err := c.Create(ctx, mFoo.DeepCopy())
		if err != nil {
			t.Fatal(err)
		}

		err = c.Create(ctx, mBar1.DeepCopy())
		if err != nil {
			t.Fatal(err)
		}

		g.Eventually(func() error {
			err := podStatusMatches(ctx, c, pod, mFooID, hasStatusErrors(nil))
			if err != nil {
				return err
			}

			return podStatusMatches(ctx, c, pod, mBar1ID, hasStatusErrors(nil))
		})

		err = c.Create(ctx, mBar2.DeepCopy())
		if err != nil {
			t.Fatal(err)
		}

		g.Eventually(func() error {
			err := podStatusMatches(ctx, c, pod, mFooID, hasStatusErrors(nil))
			if err != nil {
				return err
			}

			err = podStatusMatches(ctx, c, pod, mBar1ID, hasStatusErrors([]podstatus.MutatorError{{
				Type: mutationschema.ErrConflictingSchemaType,
				Message: mutationschema.NewErrConflictingSchema(mutationschema.IDSet{
					mBar1ID: true, mBar2ID: true,
				}).Error(),
			}}))
			if err != nil {
				return err
			}

			return podStatusMatches(ctx, c, pod, mBar2ID, hasStatusErrors([]podstatus.MutatorError{{
				Type: mutationschema.ErrConflictingSchemaType,
				Message: mutationschema.NewErrConflictingSchema(mutationschema.IDSet{
					mBar1ID: true, mBar2ID: true,
				}).Error(),
			}}))
		}, timeout).Should(gomega.Succeed())

		err = c.Delete(ctx, mBar1.DeepCopy())
		if err != nil {
			t.Fatal(err)
		}

		g.Eventually(func() error {
			err := podStatusMatches(ctx, c, pod, mFooID, hasStatusErrors(nil))
			if err != nil {
				return err
			}

			return podStatusMatches(ctx, c, pod, mBar2ID, hasStatusErrors(nil))
		})
	})
}

func podStatusMatches(ctx context.Context, c client.Client, pod *corev1.Pod, id types.ID, matchers ...PodStatusMatcher) error {
	podStatus := &podstatus.MutatorPodStatus{}

	podStatusName, err := podstatus.KeyForMutatorID(pod.Name, id)
	if err != nil {
		return err
	}

	key := client.ObjectKey{Namespace: pod.Namespace, Name: podStatusName}
	err = c.Get(ctx, key, podStatus)
	if err != nil {
		return err
	}

	for _, m := range matchers {
		err = m(podStatus)
		if err != nil {
			return err
		}
	}

	return nil
}

type PodStatusMatcher func(status *podstatus.MutatorPodStatus) error

func hasStatusErrors(want []podstatus.MutatorError) PodStatusMatcher {
	return func(status *podstatus.MutatorPodStatus) error {
		got := status.Status.Errors
		if diff := cmp.Diff(want, got, cmpopts.SortSlices(sortMutatorErrors), cmpopts.EquateEmpty()); diff != "" {
			return fmt.Errorf("unexpected difference in .status.errors for %q:\n%s", status.Name, diff)
		}
		if len(want) == 0 {
			if !status.Status.Enforced {
				return fmt.Errorf("no errors in .status.errors but Mutator is not enforced")
			}
		} else {
			if status.Status.Enforced {
				return fmt.Errorf("errors in .status.errors but Mutator is enforced")
			}
		}

		return nil
	}
}

func sortMutatorErrors(left, right podstatus.MutatorError) bool {
	return left.Message < right.Message
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
namespace Utils
{
    public class EnumHelper
    {
        /// <summary>
        /// Gets the string values associated with the enum.
        /// </summary>
        /// <returns>IEnumerable of strings</returns>
        public static IEnumerable<string> GetStringValues(Type enumType)
        {
            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in enumType.GetFields())
            {
                //Check for our custom attribute
                DescriptionAttribute[] stringValueAttributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
                if (stringValueAttributes.Length > 0)
                {
                    yield return stringValueAttributes[0].Description;
                }
            }
        }

        /// <summary>
        /// Gets the values as a IEnumerable datasource.
        /// </summary>
        /// <returns>IEnumerable for data binding</returns>
        public static IEnumerable<DictionaryEntry> GetEnumsAsDictionary(Type enumType)
        {
            Type underlyingType = Enum.GetUnderlyingType(enumType);

            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fieldInfo in enumType.GetFields())
            {
                //Check for our custom attribute
                DescriptionAttribute[] stringValueAttributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
                if (stringValueAttributes.Length > 0)
                {
                    //yield return new DictionaryEntry(Convert.ChangeType(Enum.Parse(enumType, fieldInfo.Name, false), underlyingType, System.Globalization.CultureInfo.InvariantCulture), stringValueAttributes[0].Description);
                    yield return new DictionaryEntry(fieldInfo.Name, stringValueAttributes[0].Description);
                }
            }
        }

        /// <summary>
        /// Gets the values as a dictionary
        /// </summary>
        /// <param name="enumType">Dictionary of string</param>
        /// <returns></returns>
        public static Dictionary<int, string> GetEnumsAsStrictDictionary(Type enumType)
        {
            Dictionary<int, string> dico = new Dictionary<int, string>(enumType.GetFields().GetLength(0));
            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fieldInfo in enumType.GetFields())
            {
                //Check for our custom attribute
                DescriptionAttribute[] stringValueAttributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
                if (stringValueAttributes.Length > 0)
                {
                    dico.Add(Convert.ToInt32(Enum.Parse(enumType, fieldInfo.Name, false)), stringValueAttributes[0].Description);
                }
            }
            return dico;
        }
    }
}


text:
app.controller('HeaderController', function($scope, $state, FrameworkAJAX, SessionService){
    $scope.Actions = {};
    $scope.Model = {};

    $scope.Actions.goTo = function(state){
        $state.go( state );
    };

    $scope.Actions.logout = function(){
        FrameworkAJAX.sendRequest( {method: 'POST', url: '/api/v0/logout', data: {}}, function(){
            console.log('logged out');
            SessionService.getSession();
        }, function(){
            console.log('failed to log out');
        });
    };

    $scope.Actions.updateSession = function( session ){
        if( session ){
            $scope.Model.username = session.username;
            $scope.Model.sessionActive = true;
        } else {
            $scope.Model.username = undefined;
            $scope.Model.sessionActive = false;
        }
    };

    SessionService.registerCallback( $scope.Actions.updateSession );
    SessionService.getSession();
});


text:
using Detached.Samples.RestApi.Models.Inputs;
using Detached.Samples.RestApi.Models.Outputs;
using Detached.Samples.RestApi.Stores;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Detached.Samples.RestApi.Services
{
    public class InvoiceService
    {
        readonly InvoiceStore _invoiceStore;

        public InvoiceService(InvoiceStore invoiceStore)
        {
            _invoiceStore = invoiceStore;
        }

        public Task<IEnumerable<InvoiceListItemOutput>> GetAsync()
        {
            return _invoiceStore.GetAsync();
        }

        public Task SaveAsync(SaveInvoiceInput input)
        {
            return _invoiceStore.SaveAsync(input);
        }
    }
}


text:
$().ready(function(){
  var socket = new Pusher('0eb73a235dd03b3df71a');
  var nextConnectionAttempt = null;

  socket.connection.bind('connecting_in', function(data) {
    updateLight('amber');
    updateControls('connect');
    if(data > 0)
    {
      nextConnectionAttempt = new Date().getTime() + data;
      handleAmberDelay(nextConnectionAttempt);
    }
  });

  socket.connection.bind('connecting', function() {
    updateLight('amber');
    updateControls('connect');
  });

  socket.connection.bind('connected', function(data) {
    resetAmber();
    updateLight('green');
    updateControls('disconnect');
  });

  socket.connection.bind('disconnected', function(data) {
    updateLight('red');
    updateControls('connect');
  });

  $('#connect').click(function() {
    socket.connection.connect();
  });

  $('#disconnect').click(function() {
    socket.connection.disconnect();
  });
});

var lights = ['red', 'amber', 'green'];
function updateLight(light) {
  for(var i = 0; i < lights.length; i++)
  {
    if(lights[i] !== light)
    {
      $("#" + lights[i] + 'on').hide();
      $("#" + lights[i] + 'off').show();
    }
    else
    {
      $("#" + lights[i] + 'on').show();
      $("#" + lights[i] + 'off').hide();
    }
  }
};

var amberDelayTimer = null;
function handleAmberDelay(nextConnectionAttempt) {
  clearTimeout(amberDelayTimer);
  updateAndSetTimer(nextConnectionAttempt);
};

function updateAndSetTimer(nextConnectionAttempt) {
  amberDelayTimer = setTimeout(function() {
    var countdown = Math.round((nextConnectionAttempt - new Date().getTime()) / 1000);
    if(countdown >= 0) // can take a bit longer if using Flash
      $("#amberon").html(countdown);
    updateAndSetTimer(nextConnectionAttempt);
  }, 999);
};

function resetAmber() {
  clearTimeout(amberDelayTimer);
  $("#amberon").html("");
};

var controls = ['connect', 'disconnect'];
function updateControls(addControl) {
  for(var i = 0; i < controls.length; i++)
    if(controls[i] !== addControl)
      $("#" + controls[i]).hide();
    else
      $("#" + controls[i]).show();
};


text:
@interface IDERunSheetArchivePhaseModel : IDERunSheetPhaseModel
{
}

- (id)schemeCommandTitle;
- (int)schemePhaseModelCommand;
- (id)navigableItem_image;
- (Class)detailViewControllerClass;
- (id)runPhase;

@end


text:
"""
  stash

  A python object persistance and caching module

  This source file is subject to the new BSD license that is bundled with this
  package in the file LICENSE.txt. The license is also available online at the
  URL: <http://nikcub.appspot.com/bsd-license.txt>

  :copyright: Copyright (C) 2011 Nik Cubrilovic and others, see AUTHORS
  :license: new BSD, see LICENSE for more details.
"""

import os
import sys
import logging
import time
import functools
import inspect
from types import TypeType

try:
  import hashlib
except ImportError:
  raise Exception('python 2.5+ required')

try:
  import json
except ImportError:
  # python <2.6, simplejson is now a requirement
  try:
    import simplejson as json
  except ImportError:
    try:
      from django.utils import simplejson
    except ImportError:
      logging.exception('stash requires simplejson')
      raise Exception('json is required')

try:
  from google.appengine.api import memcache
  from google.appengine.ext import db
  GAE = True

  class _StashGAEStore(db.Model):
    skey = db.StringProperty(required = True)
    sval = db.TextProperty()
    sttl = db.IntegerProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    expired = db.BooleanProperty(default = False)

except ImportError:
  GAE = False
  db = {}
  try:
    import memcache
    LOCAL_MEMCACHE = True
  except ImportError:
    LOCAL_MEMCACHE = False

__version__ = '0.0.1'
__author__ = 'Nik Cubrilovic <nikcub@gmail.com>'

#---------------------------------------------------------------------------
#   Misc Module Data
#---------------------------------------------------------------------------

GLOBAL_VAR_STORE = {}

_startTime = time.time()

counter = 0

def increment():
  global counter
  counter += 1
  return counter

#---------------------------------------------------------------------------
#   Module Exceptions
#---------------------------------------------------------------------------

class StorageHandlerException(Exception): pass

class FileCacheException(Exception): pass

#---------------------------------------------------------------------------
#   Storage Handlers
#---------------------------------------------------------------------------

class StorageHandler(object):

  options = None

  def __init__(self, options = None):
    """docstring for __init__"""
    if options:
      self.options = options

  def wrap(self, func):
    """docstring for fname"""
    def cache(*args, **kwargs):
      logging.info("Called fetch function with")
      key = self.hash(args[0])
      cache_store = self.get(key)
      if cache_store:
        return cache_store
      val = func(*args, **kwargs)
      if val:
        self.set(key, val)
      return val
    return cache

  def hash(self, key_name):
    return hashlib.sha1(key_name).hexdigest()

class NullHandler(StorageHandler):
  """docstring for NullHandler"""
  def __init__(self, options):
    return None

  def wrap(self, func):
    return func

class GlobalVarHandler(StorageHandler):

  def __init__(self, options):
    pass

  def get(self, key):
    if GLOBAL_VAR_STORE.has_attr('key'):
      return GLOBAL_VAR_STORE[key]
    return None

  def set(self, key, value):
    GLOBAL_VAR_STORE[key] = value
    return True

class MemcacheHandler(StorageHandler):

  _config_default = {
    'host': ':127.0.0.1:11211'
  }
  def __init__(self, options):
    pass

  def fname(self):
    """docstring for fname"""
    pass

  def fname(self):
    """docstring for fname"""
    pass

class FileStorage(StorageHandler):
  """docstring for FileCacheHandler"""

  cache_folder = None
  file_extension = 'txt'

  def __init__(self, **kwargs):
    """Initialize FileStorageHandler"""

    if kwargs.get('cache_dir'):
      self._setup_cache_folder(kwargs.get('cache_dir'))

  def _setup_cache_folder(self, cache_folder = None):
    """Set the cache folder to store the cache to by either taking user supplied
    argument or setting to a temporary directory"""
    if cache_folder:
      cache_folder = self._parse_cache_folder(cache_folder)
    else:
      import tempfile
      cache_folder = tempfile.gettempdir()

    self.cache_folder = cache_folder

  def _parse_cache_folder(self, cache_folder):
    """Take the user supplied cache folder argument and sanitize the path, check
    that it is writable and return the value.
    """

    # If it is a relative path, prepend current directory
    if not cache_folder.startswith('/'):
      cache_folder = os.path.join(os.path.dirname(__file__), cache_folder)

    # TODO check that it is writable
    if not os.path.isdir(cache_folder):
      raise FileCacheException("Not a valid cache folder: %s (got: %s)" % (cf, os.path.isdir(cf)))

    return cache_folder

  def set_cache_dir(self, cache_folder):
    """Set the cache directory to store cache to"""
    return self._setup_cache_folder(cache_folder)

  def get_filepath(self, key):
    if not self.cache_folder:
      self._setup_cache_folder()
    return os.path.join(self.cache_folder, "%s.txt" % key)

  def get(self, key):
    file_path = self.get_filepath(key)

    if not os.path.isfile(file_path):
      return None

    logging.info("CACHE HIT (%s)" % file_path)

    val = open(file_path).read()

    try:
      val = json.loads(val)
    except ValueError:
      pass
    return val

  def set(self, key, value, ttl = 60 * 60):
    # TODO set the key based on timeout
    # ie. some sort of key hash taking the filename along with a time that will
    # only make the key valid again if looked up in that time
    file_path = self.get_filepath(key)

    if type(value) != str:
      value = json.dumps(value)

    try:
      logging.info("Writing value to key %s" % key)
      logging.info(value)

      f = open(file_path, 'w')
      f.write(value)
    except Exception, e:
      logging.error("Exception: could not write file %s" % (file_path))
      logging.exception(e)
      return False
    return True

class GAEMemcacheHandler(StorageHandler):
  """docstring for GAEMemcacheHandler"""

  ttl = 60 * 60 * 24 * 4

  def get(self, key):
    """docstring for get"""
    return memcache.get(key)

  def set(self, key, value):
    """docstring for set"""
    return memcache.set(key, value, self.ttl)

  def delete(self, key):
    return memcache.delete(key)

# TODO  implement datastore cache
class GAEDatastoreHandler(StorageHandler):

  def get(self, key):
    q = db.GqlQuery("SELECT * FROM _StashGAEStore WHERE skey = :1", key)
    if not q:
      return None
    return json.loads(q.sval)

  def set(self, key, value):
    val = json.dumps(value)
    r = _StashGAEStore(
      skey = key,
      sval = val,
    )
    r.put()

  def delete(self, key):
    return None

#---------------------------------------------------------------------------
#   Serializers
#---------------------------------------------------------------------------

class Serializer(object):

  def __init__(self):
    """docstring for __init__"""
    pass

  def dumps(self):
    """docstring for dumps"""
    pass

  def load(self, str):
    pass

#---------------------------------------------------------------------------
#   Stash Object
#---------------------------------------------------------------------------

class Stash(object):
  """Base and root stash object"""

  def __init__(self, **kwargs):
    """Initialize"""
    self.handlers = []
    handler = kwargs.pop('handler', False)
    if handler:
      self._add_handler(handler)

  def _add_handler(self, handler, **kwargs):
    if type(handler) == str and handler in globals():
      handler = globals()[handler]
    if not issubclass(handler, StorageHandler):
     raise StorageHandlerException, "%s is not of type StorageHandler" % handler
    ins = handler(**kwargs)
    self.handlers.append(ins)

  def get(self, key):
    for h in self.handlers:
      # logging.info("Stash: get(%s) with %s" % (key, h))
      r = h.get(key)
      if r:
        return r
      return None

  def set(self, key, val):
    for h in self.handlers:
      # logging.info("Stash: set(%s, %s) with %s" % (key, val, h))
      h.set(key, val)

  def delete(self, key):
    for h in self.handlers:
      # logging.info("Stash: del(%s) with %s" % (key, h))
      h.delete(key)

_stash = Stash()

#---------------------------------------------------------------------------
#   Handler Class
#---------------------------------------------------------------------------

def autoConf(**kwargs):
  """Attepts to auto configure a core Stash cache object based on capabilities
  discovered through imports and default attempts. Detect if we are on AppEngine
  either dev or production, detect if memcache is present and active, etc.

  Falls back on providing a FileStorage handler and a single root Stash
  """
  if GAE:
    _stash._add_handler(GAEMemcacheHandler)
    _stash._add_handler(GAEDatastoreHandler)
  else:
    _stash._add_handler(FileStorage)
    logging.info('Stash: not on google appengine')

  # OLD VERSION - single handler only support
  #
  # if len(_stash.handlers) == 0:
  #   handler = kwargs.get('handler')
  #
  # else:
  #   if GAE:
  #     return GAEMemcacheHandler()
  #   if LOCAL_MEMCACHE and kwargs.get('memcache_server', False):
  #     return MemcacheHandler()
  #   return FileStorage()

def handler(**kwargs):
  # Factory for returning a handler based on either passed options or by
  # taking a best guess based on imports that worked or failed (ie. GAE vs not)

  # If we were not passed a handler, lets take a guess

  if GAE:
    return GAEMemcacheHandler()
  if LOCAL_MEMCACHE and kwargs.get('memcache_server', False):
    return MemcacheHandler()
  return FileStorage()

# cache decorator
class Cache(object):
  """
    cache decorator
  """

  def __init__(self, func):
    self.func = func
    logging.info(func.__name__)
    self.cache = {}

  def __call__(self, *args):
    try:
      logging.info('cache:')
      logging.info(args)
      val = self.func(*args)
      return val
    except:
      return None
      return self.func(*args)

  def __repr__(self):
    return self.func.__doc__

  def __get__(self, obj, objtype):
    return functools.partial(self.__call__, obj)

def get(key):
  if len(_stash.handlers) == 0:
    autoConf()
  return _stash.get(key)

def set(key, val, ttl = 60 * 60 * 24):
  if len(_stash.handlers) == 0:
    autoConf()
  return _stash.set(key, val)

def delete(key):
  if len(_stash.handlers) == 0:
    autoConf()
  return _stash.delete(key)


text:
<?php

namespace RealEstate;

/**
 * Class BouwTypeDetails
 *
 * @package RealEstate
 * @author Jordi Jolink <mail@jordijolink.nl>
 */
class BouwType extends House
{
    /**
     * @var BouwTypeDetails
     */
    public $BouwTypeDetails;
}


text:
/*
 * Gets a rarity by id
 */

SELECT * FROM rarities WHERE id = $1;


text:
<?php

declare(strict_types=1);

namespace Gilek\Ewus;

interface EwusExceptionInterface
{
}


text:
"""Contains classes concerning Wav2Vec2ForCTC."""

from sparknlp.common import *
from sparknlp.common.annotator_type import AnnotatorType

class Wav2Vec2ForCTC(AnnotatorModel,
                     HasBatchedAnnotateAudio,
                     HasAudioFeatureProperties,
                     HasEngine):
    """Wav2Vec2 Model with a language modeling head on top for Connectionist Temporal
    Classification (CTC). Wav2Vec2 was proposed in wav2vec 2.0: A Framework for
    Self-Supervised Learning of Speech Representations by Alexei Baevski, Henry Zhou,
    Abdelrahman Mohamed, Michael Auli.

    The annotator takes audio files and transcribes it as text. The audio needs to be
    provided pre-processed an array of floats.

    Note that this annotator is currently not supported on Apple Silicon processors such
    as the M1. This is due to the processor not supporting instructions for XLA.

    Pretrained models can be loaded with ``pretrained`` of the companion object:

    >>> speechToText = Wav2Vec2ForCTC.pretrained() \\
    ...     .setInputCols(["audio_assembler"]) \\
    ...     .setOutputCol("text")

    The default model is ``"asr_wav2vec2_base_960h"``, if no name is provided.

    For available pretrained models please see the
    `Models Hub <https://nlp.johnsnowlabs.com/models>`__.

    To see which models are compatible and how to import them see
    https://github.com/JohnSnowLabs/spark-nlp/discussions/5669 and to see more extended
    examples, see
    `Wav2Vec2ForCTCTestSpec <https://github.com/JohnSnowLabs/spark-nlp/blob/master/src/test/scala/com/johnsnowlabs/nlp/annotators/audio/Wav2Vec2ForCTCTestSpec.scala>`__.

    ====================== ======================
    Input Annotation types Output Annotation type
    ====================== ======================
    ``AUDIO``              ``DOCUMENT``
    ====================== ======================

    Parameters
    ----------

    batchSize
        Size of each batch, by default 2

    Examples
    --------
    >>> import sparknlp
    >>> from sparknlp.base import *
    >>> from sparknlp.annotator import *
    >>> from pyspark.ml import Pipeline
    >>> audioAssembler = AudioAssembler() \\
    ...     .setInputCol("audio_content") \\
    ...     .setOutputCol("audio_assembler")
    >>> speechToText = Wav2Vec2ForCTC \\
    ...     .pretrained() \\
    ...     .setInputCols(["audio_assembler"]) \\
    ...     .setOutputCol("text")
    >>> pipeline = Pipeline().setStages([audioAssembler, speechToText])
    >>> processedAudioFloats = spark.createDataFrame([[rawFloats]]).toDF("audio_content")
    >>> result = pipeline.fit(processedAudioFloats).transform(processedAudioFloats)
    >>> result.select("text.result").show(truncate = False)
    +------------------------------------------------------------------------------------------+
    |result                                                                                |
    +------------------------------------------------------------------------------------------+
    |[MISTER QUILTER IS THE APOSTLE OF THE MIDLE CLASES AND WE ARE GLAD TO WELCOME HIS GOSPEL ]|
    +------------------------------------------------------------------------------------------+
    """
    name = "Wav2Vec2ForCTC"

    inputAnnotatorTypes = [AnnotatorType.AUDIO]

    configProtoBytes = Param(Params._dummy(),
                             "configProtoBytes",
                             "ConfigProto from tensorflow, serialized into byte array. Get with "
                             "config_proto.SerializeToString()",
                             TypeConverters.toListInt)

    def setConfigProtoBytes(self, b):
        """Sets configProto from tensorflow, serialized into byte array.

        Parameters
        ----------
        b : List[int]
            ConfigProto from tensorflow, serialized into byte array
        """
        return self._set(configProtoBytes=b)

    @keyword_only
    def __init__(self, classname="com.johnsnowlabs.nlp.annotators.audio.Wav2Vec2ForCTC",
                 java_model=None):
        super(Wav2Vec2ForCTC, self).__init__(
            classname=classname,
            java_model=java_model
        )
        self._setDefault(
            batchSize=2
        )

    @staticmethod
    def loadSavedModel(folder, spark_session):
        """Loads a locally saved model.

        Parameters
        ----------
        folder : str
            Folder of the saved model
        spark_session : pyspark.sql.SparkSession
            The current SparkSession

        Returns
        -------
        Wav2Vec2ForCTC
            The restored model
        """
        from sparknlp.internal import _Wav2Vec2ForCTC
        jModel = _Wav2Vec2ForCTC(folder, spark_session._jsparkSession)._java_obj
        return Wav2Vec2ForCTC(java_model=jModel)

    @staticmethod
    def pretrained(name="asr_wav2vec2_base_960h", lang="en", remote_loc=None):
        """Downloads and loads a pretrained model.

        Parameters
        ----------
        name : str, optional
            Name of the pretrained model, by default
            "asr_wav2vec2_base_960h"
        lang : str, optional
            Language of the pretrained model, by default "en"
        remote_loc : str, optional
            Optional remote address of the resource, by default None. Will use
            Spark NLPs repositories otherwise.

        Returns
        -------
        Wav2Vec2ForCTC
            The restored model
        """
        from sparknlp.pretrained import ResourceDownloader
        return ResourceDownloader.downloadModel(Wav2Vec2ForCTC, name, lang, remote_loc)


text:
title:  "Garmin Embedded Courses"
date:   2014-07-26 18:59:35
category: running
---


text:
package com.gdn.venice.client.view.handlers;

import com.gwtplatform.mvp.client.UiHandlers;

public interface MainPageUiHandlers extends UiHandlers {
	void onNavigationPaneSectionClicked(String path, String pageName);
	void onSetInSlot(String pageName);
}


text:
/*
This file contains some functions used for bibliography formatting.
The bibtex bibliography is read by `readBibliography` and parsed using
the bibtex [bibtex-js](https://code.google.com/p/bibtex-js/) parser.
The bibliography object is stored  in document.bibliography. A reference
section is added at the end of the notebook. Citations are formated according
to the simple templates described in the object cit_tpl (see the file latex_envs_jup).
These templates can be customized.
*/

if (typeof Jupyter == 'undefined'){var Jupyter=IPython;} //for IPython 3.x
document.bibliography={};
var bibmsg="";

function readBibliography(callback){
require(["nbextensions/usability/latex_envs/bibtex2"], function () {

	document.bibliography={}; bibmsg="";
    document.bibtex_parser = new BibtexParser();

    function parse_bibtex(string) {
        document.bibtex_parser.setInput(string);
        document.bibtex_parser.bibtex();
        // {KEY: {AUTHOR:..., BIB_KEY:...}}
        return document.bibtex_parser.getEntries();
    }

    $.get(bibliofile, function (data){
        var json = parse_bibtex(data)
        $.extend(document.bibliography, json);
    }).fail(function () {bibmsg="The bib file "+bibliofile+" was not found\n\n"; console.log(bibmsg)})
	.always(function (){if (typeof callback != "undefined") {callback()}})

    })
	return true
}

//..... This function is from calico-documents-tools.js .........
    function find_cell(cell_type, text) {
	// Finds first cell of cell_type that starts with text
	// cell_type and text are interpreted as a regular expression
	var cell = undefined;
	var cells = Jupyter.notebook.get_cells();
	for (var x = 0; x < cells.length; x++) {
	    var temp = cells[x];
	    if (temp.cell_type.match(cell_type) != undefined) {
		var temp_text = temp.get_text();
		var re = new RegExp("^" + text);
		if (re.test(temp_text)) {
		    cell = cells[x];
		    break;
		}
	    }
	}
	return cell;
    }
//.............................................................

function createReferenceSection() {

	//console.log("Create refs section");
	if (Object.keys(cit_table).length==0){ //it is not necessary to create the reference section since there will be nothing in it!
	return
}

//..... This part is from calico-documents-tools.js .......
	// If there is a References section, replace it:
	var reference_cell = find_cell("markdown", "#+ References");
	var cells = Jupyter.notebook.get_cells();
	// default to top-level heading:
	var references = "# References\n\n";
	if (reference_cell == undefined) {
            reference_cell = Jupyter.notebook.select(cells.length-1).insert_cell_below("markdown");
	} else {
	    // already exists:
	    references = reference_cell.get_text().match("# References")[0] + "\n\n";
	}
//............................................................

if (bibmsg!="") {references += ' ' +  bibmsg + ' '};
var str="Nothing yet"
for (key in  cit_table) {  // cit_table is populated during the edition and rendering of each markdown cell. It is possible to reload all citations by pressing the toolbar LaTeX refresh button
    var citation = document.bibliography[key.toUpperCase()];
	var opening_cit='[';  var closing_cit=']';
    if (cite_by=='apalike'){var opening_cit='(';  var closing_cit=')' }
     str = opening_cit +''
                +  cit_table[key]['key']  + '' + closing_cit+' '
    if (!(citation==undefined)){
		//check the type of citation, eg ARTICLE, INPROCEEDINGS, INBOOK, etc
        if (citation['reftype'] in cit_tpl) {var type=citation['reftype']} else {var type='UNKNOWN'};

		//replace %words% in template
        str += cit_tpl[type].replace(/%([\w:]+)+%/g, function(rep) {
				//case of %AUTHOR:format%
				if (rep.slice(1,7)=='AUTHOR') {
					var out=rep.slice(1,-1).split(':');
					if (out.length>1) {
						 var val=formatAuthors(makeAuthorsArray(citation['AUTHOR']),out[1],etal);
					}
					else{
						 var val=formatAuthors(makeAuthorsArray(citation['AUTHOR']),'default',etal);
					}
				return val
				//case of other keywords
				}
				else{
					if (citation[rep.slice(1, -1)]==undefined)
						return "";
					else
	        			return citation[rep.slice(1, -1)].replace(/[{}]/g,"") || "";
					}
				 });
		//
        if (citation['URL']!=undefined) {str+= '  [online]('+citation['URL']+')'};
    }
    else {
        str+="!! _This reference was not found in "+ bibliofile +" _ !!"
    }
    references += str + '\n\n'
    //console.log(str)

    reference_cell.unrender();
    reference_cell.set_text(references);
    reference_cell.render();
    }
}

function generateReferences() {

	readBibliography(createReferenceSection);
	}

// ........... Other utilitary functions for formatting authors and references .........

function authorSplit(singleAuthor) {
    var firstName, givenName, jr;
	switch (singleAuthor.split(',').length) {
		case 1:
		    firstName=singleAuthor.split(' ')[0];
		    givenName=singleAuthor.split(' ')[1];
		    break;
		case 2:
		    firstName=singleAuthor.split(', ')[1];
		    givenName=singleAuthor.split(', ')[0];
		    break;
		case 3:
		    firstName=singleAuthor.split(', ')[2];
		    givenName=singleAuthor.split(', ')[0];
		    jr=singleAuthor.split(', ')[1];
		    break;
	}
	return {firstName:firstName.trim(), givenName:givenName.trim()}
}

function makeAuthorsArray(bibtexAuthors){
    var listSingleAuthors=bibtexAuthors.split(' and ');
    var authorsArray=listSingleAuthors.map(
    function(x) {
         return authorSplit(x)
             });
    return authorsArray
}

function formatSingleAuthorObject(author,format){
        var str;
        switch (format){
            case 'InitialsGiven':
                str = author.firstName.split(' ').reduce(function (x,y){return x+y[0].toUpperCase()+'.'},'')
                + ' '+ author.givenName;
                break;
            case 'GivenInitials':
                str = author.givenName + ' '+ author.firstName.split(' ').reduce(function (x,y){return x+y[0].toUpperCase()+'.'},'') ;
                break;
            case 'FirstGiven':
                str =  author.firstName + ' '+ author.givenName;
                break;
            case 'GivenFirst':
                str =  author.givenName +' '+ author.firstName;
                break;
            case 'Given':
                str =  author.givenName;
                break;
            default:
                str =  author.firstName +' '+ author.givenName;
        }
     return str;
    }

function formatAuthors(authorsArray, format, etal){
    etal= typeof etal !== 'undefined' ? etal : 2;  //default value
    var str="";
    var kmax;
    fullAuthors = authorsArray.length<=etal
    fullAuthors ? kmax=authorsArray.length : kmax=etal+1
    for (var k = 0; k < kmax-1; k++){
        str += formatSingleAuthorObject(authorsArray[k],format)+', '
    }
    str=str.slice(0,-2) //cut last 2 chars
    if (fullAuthors) {
		if (kmax>1) {str += ' and '}
        str += formatSingleAuthorObject(authorsArray[k],format)
        }
    else{
        str += ' et al.'
    }
    return str
}


text:
<?php
/**
 * Reddogs (https://github.com/reddogs-at)
 *
 * @see https://github.com/reddogs-at/reddogs-oauth2-server for the canonical source repository
 * @license https://github.com/reddogs-at/reddogs-oauth2-server/blob/master/LICENSE MIT License
 */
declare(strict_types = 1);
namespace Reddogs\OAuth2\Server\Entity;

use League\OAuth2\Server\Entities\ScopeEntityInterface;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="reddogs_oauth2_server_scope")
 */
class Scope implements ScopeEntityInterface
{
    /**
     * Id
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     *
     * @var integer
     */
    private $id;

    /**
     * Identifier
     *
     * @ORM\Column(type="string")
     *
     * @var string
     */
    private $identifier;

    /**
     * Constructor
     *
     * @param string $identifier
     */
    public function __construct(string $identifier = null)
    {
        $this->identifier = $identifier;
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get identifier
     *
     * {@inheritDoc}
     * @see \League\OAuth2\Server\Entities\ScopeEntityInterface::getIdentifier()
     */
    public function getIdentifier()
    {
        return $this->identifier;
    }

    /**
     * Json serialize
     *
     * {@inheritDoc}
     * @see JsonSerializable::jsonSerialize()
     */
    public function jsonSerialize()
    {

    }
}


text:
window.addEventListener('load', function () {
  'use strict';

  function log() {
    document.querySelector('#foreachasync-console').innerHTML +=
      '\n' + Array.prototype.join.call(arguments, ' | ');
    console.log.apply(console, arguments);
  }

  var forEachAsync = window.forEachAsync
    ;

  log('i', 'item', 'ms');
  forEachAsync([2, 11, 37, 42], function (item, i) {
    var ms = Math.floor(Math.random() * 1000)
      ;

    return new Promise(function (resolve) {
      setTimeout(function () {
        log(i, item, ms);
        resolve();
      }, ms);
    });
  }).then(function () {
    log('All Done');
  });
});


text:
package fi.vrk.xroad.catalog.persistence.repository;

import fi.vrk.xroad.catalog.persistence.entity.PostOfficeBoxAddressMunicipalityName;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Optional;

public interface PostOfficeBoxAddressMunicipalityNameRepository extends CrudRepository<PostOfficeBoxAddressMunicipalityName, Long> {

    Optional<List<PostOfficeBoxAddressMunicipalityName>> findAnyByPostOfficeBoxAddressMunicipalityId(Long postOfficeBoxAddressMunicipalityId);

    @Query("SELECT p FROM PostOfficeBoxAddressMunicipalityName p WHERE p.postOfficeBoxAddressMunicipality.id = :postOfficeBoxAddressMunicipalityId "
            + "AND p.language = :language")
    Optional<PostOfficeBoxAddressMunicipalityName> findAny(@Param("postOfficeBoxAddressMunicipalityId") Long postOfficeBoxAddressMunicipalityId,
                                                           @Param("language") String language);

}


text:
cask "qqlive" do
  version "2.34.0.53140"
  sha256 "660e4df02e99bf4814fad0134696ab21285ca32638b1f8f5427df794bf3fa775"

  url "https://dldir1.qq.com/qqtv/mac/QQLive_distribute_universal_#{version}.dmg"
  name "QQLive"
  name "TencentVideo"
  name "腾讯视频"
  desc "Tencent video streaming and sharing platform"
  homepage "https://v.qq.com/download.html#mac"

  livecheck do
    url :homepage
    regex(%r{href=.*/QQLive_distribute_universal_(\d+(?:\.\d+)+)\.dmg}i)
  end

  auto_updates true
  depends_on macos: ">= :yosemite"

  app "QQLive.app"

  zap trash: [
    "~/Library/Caches/com.tencent.tenvideo",
    "~/Library/Containers/com.tencent.tenvideo",
    "~/Library/Cookies/com.tencent.tenvideo.binarycookies",
    "~/Library/Logs/QQLive",
    "~/Library/Preferences/com.tencent.tenvideo.plist",
    "~/Library/Saved Application State/com.tencent.tenvideo.savedState",
    "~/Library/WebKit/com.tencent.tenvideo",
  ]
end


text:
//
//  ___FILENAME___
//  ___PROJECTNAME___
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//  Copyright ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//

#import "___FILEBASENAME___.h"

@implementation ___FILEBASENAMEASIDENTIFIER___

#pragma mark - Initialization

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
#import "AIRMapPolylineManager.h"

#import "RCTBridge.h"
#import "RCTConvert.h"
#import "RCTConvert+CoreLocation.h"
#import "RCTConvert+MoreMapKit.h"
#import "RCTEventDispatcher.h"
#import "UIView+React.h"
#import "AIRMapMarker.h"
#import "RCTViewManager.h"
#import "AIRMapPolyline.h"

@interface AIRMapPolylineManager()

@end

@implementation AIRMapPolylineManager

RCT_EXPORT_MODULE()

- (UIView *)view
{
    AIRMapPolyline *polyline = [AIRMapPolyline new];
    return polyline;
}

RCT_EXPORT_VIEW_PROPERTY(coordinates, AIRMapCoordinateArray)
RCT_EXPORT_VIEW_PROPERTY(strokeColor, UIColor)
RCT_EXPORT_VIEW_PROPERTY(strokeWidth, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(lineCap, CGLineCap)
RCT_EXPORT_VIEW_PROPERTY(lineJoin, CGLineJoin)
RCT_EXPORT_VIEW_PROPERTY(miterLimit, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(lineDashPhase, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(lineDashPattern, NSArray)

// NOTE(lmr):
// for now, onPress events for overlays will be left unimplemented. Seems it is possible with some work, but
// it is difficult to achieve in both ios and android so I decided to leave it out.
//RCT_EXPORT_VIEW_PROPERTY(onPress, RCTBubblingEventBlock)

@end


text:
package output

import (
	"bufio"
	"encoding/json"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/b3log/wide/conf"
	"github.com/b3log/wide/i18n"
	"github.com/b3log/wide/session"
	"github.com/b3log/wide/util"
)

// GoInstallHandler handles request of go install.
func GoInstallHandler(w http.ResponseWriter, r *http.Request) {
	data := map[string]interface{}{"succ": true}
	defer util.RetJSON(w, r, data)

	httpSession, _ := session.HTTPSession.Get(r, "wide-session")
	if httpSession.IsNew {
		http.Error(w, "Forbidden", http.StatusForbidden)

		return
	}
	username := httpSession.Values["username"].(string)
	locale := conf.GetUser(username).Locale

	var args map[string]interface{}

	if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
		logger.Error(err)
		data["succ"] = false

		return
	}

	sid := args["sid"].(string)

	filePath := args["file"].(string)
	curDir := filepath.Dir(filePath)

	cmd := exec.Command("go", "install")
	cmd.Dir = curDir

	setCmdEnv(cmd, username)

	logger.Debugf("go install %s", curDir)

	stdout, err := cmd.StdoutPipe()
	if nil != err {
		logger.Error(err)
		data["succ"] = false

		return
	}

	stderr, err := cmd.StderrPipe()
	if nil != err {
		logger.Error(err)
		data["succ"] = false

		return
	}

	if !data["succ"].(bool) {
		return
	}

	channelRet := map[string]interface{}{}

	if nil != session.OutputWS[sid] {
		// display "START [go install]" in front-end browser

		channelRet["output"] = "" + i18n.Get(locale, "start-install").(string) + "\n"
		channelRet["cmd"] = "start-install"

		wsChannel := session.OutputWS[sid]

		err := wsChannel.WriteJSON(&channelRet)
		if nil != err {
			logger.Error(err)
			return
		}

		wsChannel.Refresh()
	}

	reader := bufio.NewReader(io.MultiReader(stdout, stderr))

	if err := cmd.Start(); nil != err {
		logger.Error(err)
		data["succ"] = false

		return
	}

	go func(runningId int) {
		defer util.Recover()
		defer cmd.Wait()

		logger.Debugf("User [%s, %s] is running [go install] [id=%d, dir=%s]", username, sid, runningId, curDir)

		// read all
		buf, _ := ioutil.ReadAll(reader)

		channelRet := map[string]interface{}{}
		channelRet["cmd"] = "go install"

		if 0 != len(buf) { // build error
			// build gutter lint

			errOut := string(buf)
			lines := strings.Split(errOut, "\n")

			if lines[0][0] == '#' {
				lines = lines[1:] // skip the first line
			}

			lints := []*Lint{}

			for _, line := range lines {
				if len(line) < 1 {
					continue
				}

				if line[0] == '\t' {
					// append to the last lint
					last := len(lints)
					msg := lints[last-1].Msg
					msg += line

					lints[last-1].Msg = msg

					continue
				}

				file := line[:strings.Index(line, ":")]
				left := line[strings.Index(line, ":")+1:]
				index := strings.Index(left, ":")
				lineNo := 0
				msg := left
				if index >= 0 {
					lineNo, _ = strconv.Atoi(left[:index])
					msg = left[index+2:]
				}

				lint := &Lint{
					File:     file,
					LineNo:   lineNo - 1,
					Severity: lintSeverityError,
					Msg:      msg,
				}

				lints = append(lints, lint)
			}

			channelRet["lints"] = lints

			channelRet["output"] = "" + i18n.Get(locale, "install-error").(string) + "\n" + errOut
		} else {
			channelRet["output"] = "" + i18n.Get(locale, "install-succ").(string) + "\n"
		}

		if nil != session.OutputWS[sid] {
			logger.Debugf("User [%s, %s] 's running [go install] [id=%d, dir=%s] has done", username, sid, runningId, curDir)

			wsChannel := session.OutputWS[sid]
			err := wsChannel.WriteJSON(&channelRet)
			if nil != err {
				logger.Warn(err)
			}

			wsChannel.Refresh()
		}

	}(rand.Int())
}


text:
RSpec.shared_examples 'MockController' do
  include_context 'with a defined model and collection'

  let(:controller) do
    double('controller').tap do |mock|
      allow(mock).to receive(:redirect)
      allow(mock).to receive(:render)
    end # tap
  end # let

  describe '#create' do
    def perform_action
      if collection.save
        controller.redirect
      else
        controller.render
      end # if-else
    end # method perform_action

    let(:collection) { described_class.new params }

    describe 'with valid params' do
      let(:params) { valid_params_for_create }

      it 'persists the records' do
        expect { perform_action }.to change(model, :count).by(params.count)
      end # it

      it 'calls controller#redirect' do
        expect(controller).to receive(:redirect)
        perform_action
      end # it
    end # describe

    describe 'with invalid params' do
      let(:params) { invalid_params_for_create }

      it 'does not persist the records' do
        expect { perform_action }.not_to change(model, :count)
      end # it

      it 'calls controller#render' do
        expect(controller).to receive(:render)
        perform_action
      end # it
    end # describe
  end # describe

  describe '#update' do
    def perform_action
      if collection.update_attributes attributes
        controller.redirect
      else
        controller.render
      end # if-else
    end # method perform_action

    let(:collection) { described_class.new valid_params_for_create }

    describe 'with valid attributes' do
      let(:attributes) { valid_params_for_update }

      it 'calls controller#redirect' do
        expect(controller).to receive(:redirect)
        perform_action
      end # it
    end # describe

    describe 'with invalid attributes' do
      let(:attributes) { invalid_params_for_update }

      it 'calls controller#render' do
        expect(controller).to receive(:render)
        perform_action
      end # it
    end # describe
  end # describe
end # shared_examples


text:
// Copyright Abel Sinkovics (abel@sinkovics.hu)  2013.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#include <boost/metaparse/v1/cpp11/fwd/string.hpp>

#include <boost/mpl/char.hpp>

namespace boost
{
  namespace metaparse
  {
    namespace v1
    {
      namespace impl
      {
        template <class S, int N>
        struct at_c;

        template <char C, char... Cs, int N>
        struct at_c<string<C, Cs...>, N> : at_c<string<Cs...>, N - 1> {};

        template <char C, char... Cs>
        struct at_c<string<C, Cs...>, 0> : boost::mpl::char_<C> {};
      }
    }
  }
}

#endif


text:
package de.mhus.lib.cao.fs;

import java.io.File;

import de.mhus.lib.cao.CaoAction;
import de.mhus.lib.cao.CaoException;
import de.mhus.lib.cao.CaoList;
import de.mhus.lib.cao.action.CaoConfiguration;
import de.mhus.lib.cao.action.UploadRenditionConfiguration;
import de.mhus.lib.core.IProperties;
import de.mhus.lib.core.MFile;
import de.mhus.lib.core.MProperties;
import de.mhus.lib.core.strategy.Monitor;
import de.mhus.lib.core.strategy.NotSuccessful;
import de.mhus.lib.core.strategy.OperationResult;
import de.mhus.lib.core.strategy.Successful;
import de.mhus.lib.errors.MException;
import de.mhus.lib.errors.NotFoundException;

public class FsUploadRendition extends CaoAction {

    @Override
    public String getName() {
        return UPLOAD_RENDITION;
    }

    @Override
    public CaoConfiguration createConfiguration(CaoList list, IProperties configuration)
            throws CaoException {
        return new UploadRenditionConfiguration(null, list, null);
    }

    @Override
    public boolean canExecute(CaoConfiguration configuration) {
        try {
            return configuration.getList().size() != 1
                    && configuration.getList().get(0) instanceof FsNode;
        } catch (Throwable t) {
            log().d(t);
            return false;
        }
    }

    @Override
    public OperationResult doExecuteInternal(CaoConfiguration configuration, Monitor monitor)
            throws CaoException {
        if (!canExecute(configuration)) return new NotSuccessful(getName(), "can't execute", -1);

        try {
            FsNode parent = (FsNode) configuration.getList().get(0);

            String rendition =
                    configuration.getProperties().getString(UploadRenditionConfiguration.RENDITION);
            String path =
                    configuration.getProperties().getString(UploadRenditionConfiguration.FILE);
            File file = new File(path);
            if (!file.exists() || !file.isFile()) throw new NotFoundException(path);

            File renditionFile =
                    ((FsCore) parent.getConnection())
                            .getContentFileFor(parent.getFile(), rendition);
            if (renditionFile == null)
                throw new MException("can't create rendition to internal file", rendition);
            MFile.copyFile(file, renditionFile);

            MProperties p = new MProperties(configuration.getProperties());
            p.remove(UploadRenditionConfiguration.RENDITION);
            p.remove(UploadRenditionConfiguration.FILE);
            p.save(new File(renditionFile.getParentFile(), renditionFile.getName() + ".meta"));

            return new Successful(getName());
        } catch (Throwable t) {
            log().d(t);
            return new NotSuccessful(getName(), t.toString(), -1);
        }
    }
}


text:
import {
  AfterViewInit,
  Input,
  ContentChild, Directive, forwardRef} from '@angular/core';
import {FormControl, NG_VALIDATORS, ValidationErrors, Validator} from '@angular/forms';
import { TlInput } from '../../input/input';
import { PasswordValidator } from './password.validator';
import { PasswordRule } from './passwordrule.interface';

@Directive( {
    selector: '[password][ngModel],[password][formControl],[password][formControlName]',
    providers: [
      {
        multi: true,
        provide: NG_VALIDATORS,
        useExisting: forwardRef( () => PasswordDirective),
      }
    ]
} )
export class PasswordDirective implements Validator, AfterViewInit {

    @Input('passwordRule') passwordRule: PasswordRule =
      { digits: false, uppercase: false, specials: false, lowercase: false };

    @ContentChild(TlInput, {static: true}) tlinput;

    ngAfterViewInit() {
      this.tlinput.input.nativeElement.setAttribute('type', 'password');
    }

    validate( c: FormControl ): ValidationErrors {
      return PasswordValidator( this.passwordRule )( c );
    }
}