text:
<?php

namespace ChateauLeTap\Bundle\ImageServerBundle\Model;

use ChateauLeTap\Bundle\ImageServerBundle\Exception\ChateauLeTapImageServerBundleLogicException;

/**
 * Generate a border around the image.
 * Calls:
 *  border[<color>][.][<width>x<height>]
 *
 * @author  Adrien Schaegis <adrien.schaegis@chateauletap.com>
 * @version 1.0
 */
class ImageBorderEffect extends ImageEffectAbstract
{
    /**
     * {@inheritdoc}
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Apply a border on the image.
     *
     * @param \Imagick|null $sourceImage     If provided will apply effects on this resource
     * @param array         $extraParameters Contain extraParameters. Key: `border`
     *
     * @return \Imagick
     * @throws ChateauLeTapImageServerBundleLogicException
     */
    public function run($sourceImage = null, array $extraParameters = null)
    {
        if (null !== $extraParameters && true === is_array($extraParameters) && 0 < count($extraParameters) && true === array_key_exists('rounded', $extraParameters)) {
            $this->effectParam = $extraParameters['border'];
        }

        $color  = 'black';
        $size   = null;
        $width  = 2;
        $height = 2;

        if (true === is_string($this->effectParam)) {
            $this->effectParam = strtolower(trim($this->effectParam));
            if (0 < strpos($this->effectParam, '.')) {
                $params = explode('.', $this->effectParam);
                $color  = array_shift($params);
                $size   = array_shift($params);
            } elseif (0 < strpos($this->effectParam, 'x')) {
                $size = $this->effectParam;
            } else {
                $color = $this->effectParam;
            }
        }

        if (null !== $size) {
            if (0 < strpos($size, 'x')) {
                $sizeParams = explode('x', strtolower(trim($size)));
                $width      = strtolower(trim(array_shift($sizeParams)));
                $height     = strtolower(trim(array_shift($sizeParams)));
            }
        }

        $image = parent::run($sourceImage, $extraParameters);

        $image->borderimage($color, $width, $height);

        // TODO: logInfo
        //$this->logInfo("[ImageController::roundedImage] rounding [".$rounding."]");

        $this->result = $image;

        return $image;
    }

    /**
     * {@inheritdoc}
     */
    public function getArrayConfig()
    {
        return [
            'key'     => 'border',
            'sample'  => 'border<color>.<width>x<height>',
            'params'  => [
                'optional' => [
                    'color'  => 'Color of the border. (ex: `red`, `white`, `black`, ...)',
                    'width'  => 'Width of the border',
                    'height' => 'Height of the border',
                ],
                'required' => null,
            ],
            'comment' => null,
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getTest()
    {
        return 'borderred.20x10';
    }
}


text:
package com.github.ambry.store;

import com.codahale.metrics.MetricRegistry;
import com.github.ambry.clustermap.DiskId;
import com.github.ambry.clustermap.PartitionId;
import com.github.ambry.clustermap.ReplicaId;
import com.github.ambry.config.StoreConfig;
import com.github.ambry.utils.Time;
import com.github.ambry.utils.Utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The storage manager that handles all the stores on this node. The stores on each disk are handled by a
 * {@link DiskManager}
 */
public class StorageManager {
  private final Map<PartitionId, DiskManager> partitionToDiskManager = new HashMap<>();
  private final List<DiskManager> diskManagers = new ArrayList<>();
  private final StorageManagerMetrics metrics;
  private static final Logger logger = LoggerFactory.getLogger(StorageManager.class);

  /**
   * Constructs a {@link StorageManager}
   * @param config the settings for store configuration.
   * @param scheduler the {@link ScheduledExecutorService} for executing background tasks.
   * @param registry the {@link MetricRegistry} used for store-related metrics.
   * @param replicas all the replicas on this disk.
   * @param keyFactory the {@link StoreKeyFactory} for parsing store keys.
   * @param recovery the {@link MessageStoreRecovery} instance to use.
   * @param hardDelete the {@link MessageStoreHardDelete} instance to use.
   * @param time the {@link Time} instance to use.
   */
  public StorageManager(StoreConfig config, ScheduledExecutorService scheduler, MetricRegistry registry,
      List<? extends ReplicaId> replicas, StoreKeyFactory keyFactory, MessageStoreRecovery recovery,
      MessageStoreHardDelete hardDelete, Time time) throws StoreException {
    verifyConfigs(config);
    metrics = new StorageManagerMetrics(registry);

    Map<DiskId, List<ReplicaId>> diskToReplicaMap = new HashMap<>();
    for (ReplicaId replica : replicas) {
      DiskId disk = replica.getDiskId();
      List<ReplicaId> replicasForDisk = diskToReplicaMap.get(disk);
      if (replicasForDisk == null) {
        replicasForDisk = new ArrayList<>();
        diskToReplicaMap.put(disk, replicasForDisk);
      }
      replicasForDisk.add(replica);
    }
    for (Map.Entry<DiskId, List<ReplicaId>> entry : diskToReplicaMap.entrySet()) {
      DiskId disk = entry.getKey();
      List<ReplicaId> replicasForDisk = entry.getValue();
      DiskManager diskManager =
          new DiskManager(disk, replicasForDisk, config, scheduler, metrics, keyFactory, recovery, hardDelete, time);
      diskManagers.add(diskManager);
      for (ReplicaId replica : replicasForDisk) {
        partitionToDiskManager.put(replica.getPartitionId(), diskManager);
      }
    }
  }

  /**
   * Verify that the {@link StoreConfig} has valid settings.
   * @param config the {@link StoreConfig} to verify.
   * @throws StoreException if the {@link StoreConfig} is invalid.
   */
  private void verifyConfigs(StoreConfig config) throws StoreException {
    /* NOTE: We must ensure that the store never performs hard deletes on the part of the log that is not yet flushed.
       We do this by making sure that the retention period for deleted messages (which determines the end point for hard
       deletes) is always greater than the log flush period. */
    if (config.storeDeletedMessageRetentionDays < config.storeDataFlushIntervalSeconds / Time.SecsPerDay + 1) {
      throw new StoreException("Message retention days must be greater than the store flush interval period",
          StoreErrorCodes.Initialization_Error);
    }
  }

  /**
   * Start the {@link DiskManager}s for all disks on this node.
   */
  public void start() throws InterruptedException {
    logger.info("Starting storage manager");
    List<Thread> startupThreads = new ArrayList<>();
    for (final DiskManager diskManager : diskManagers) {
      Thread thread = Utils.newThread("disk-manager-startup-" + diskManager.getDisk(), new Runnable() {
        @Override
        public void run() {
          try {
            diskManager.start();
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error("Disk manager startup thread interrupted for disk " + diskManager.getDisk(), e);
          }
        }
      }, false);
      thread.start();
      startupThreads.add(thread);
    }
    for (Thread startupThread : startupThreads) {
      startupThread.join();
    }
    logger.info("Starting storage manager complete");
  }

  /**
   * @param id the {@link PartitionId} to find the store for.
   * @return the {@link Store} corresponding to the given {@link PartitionId}, or {@code null} if no store was found for
   *         that partition, or that store was not started.
   */
  public Store getStore(PartitionId id) {
    DiskManager diskManager = partitionToDiskManager.get(id);
    return diskManager != null ? diskManager.getStore(id) : null;
  }

  /**
   * Shutdown the {@link DiskManager}s for the disks on this node.
   * @throws StoreException
   */
  public void shutdown() throws StoreException {
    logger.info("Shutting down storage manager");
    for (DiskManager diskManager : diskManagers) {
      diskManager.shutdown();
    }
    logger.info("Shutting down storage manager complete");
  }
}

redpajama_set_name: RedPajamaGithub


text:
actions :install, :remove
default_action :install

attribute :name,   kind_of: String, name_attribute: true
attribute :config, kind_of: [TrueClass, FalseClass]


text:
package org.emmalanguage.mitos.jobsflinksep;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.functions.KeySelector;

import java.util.ArrayList;
import java.util.List;

/**
 * // BB 0
 * i = 1
 * coll = <200 elements>
 * do {
 *     // BB 1
 *     i = i + 1
 *     coll.map{x => x + 1}
 * } while (i < 100)
 * // BB 2
 */

public class ControlFlowMicrobenchmark {

	public static void main(String[] args) throws Exception {
		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		//env.getConfig().setParallelism(1);

		final int numSteps = Integer.parseInt(args[0]);
		final int numElements = Integer.parseInt(args[1]);

		List<Integer> coll = new ArrayList<>(numElements);
		for (int i = 0; i < numElements; i++) {
			coll.add(i);
		}

		for (int i=0; i < numSteps; i++) {

			DataSet<Integer> ds = env.fromCollection(coll).setParallelism(env.getParallelism()).partitionCustom(new Partitioner<Integer>() {
				@Override
				public int partition(Integer x, int numParts) {
					return x % numParts;
				}
			}, new KeySelector<Integer, Integer>() {
				@Override
				public Integer getKey(Integer x) throws Exception {
					return x;
				}
			});

			DataSet<Integer> inced = ds.map(new MapFunction<Integer, Integer>() {
				@Override
				public Integer map(Integer i) throws Exception {
					return i + 1;
				}
			});

			coll = inced.collect();
			assert coll.size() == numElements;
		}
	}
}


text:
"""Utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import os
from absl import logging
import numpy as np
import tensorflow.compat.v1 as tf
from tensorflow.compat.v1.io import gfile
from scratchgan import reader

EVAL_FILENAME = "evaluated_checkpoints.csv"
GLOVE_DIM = 300
GLOVE_STD = 0.3836  # Standard dev. of GloVe embeddings.

def _get_embedding_initializer(vocab_file, embedding_source, vocab_size):
  """Loads pretrained embeddings from a file in GloVe format."""
  with gfile.GFile(embedding_source, "r") as f:
    embedding_lines = f.readlines()

  # First line contains embedding dim.
  _, embedding_dim = list(map(int, embedding_lines[0].split()))
  # Get the tokens as strings.
  tokens = [line.split()[0] for line in embedding_lines[1:]]
  # Get the actual embedding matrix.
  unsorted_emb = np.array(
      [[float(x) for x in line.split()[1:]] for line in embedding_lines[1:]])

  # Get the expected vocab order.
  with gfile.GFile(vocab_file, "r") as f:
    tokens_order = [l.strip() for l in f.readlines()]
  assert vocab_size == len(tokens_order)

  # Put the embeddings in the order.
  sorted_emb = np.zeros((vocab_size, embedding_dim))
  for i, token in enumerate(tokens_order):
    if token in tokens:
      sorted_emb[i, :] = unsorted_emb[tokens.index(token), :]
    else:  # If we don't have a pretrained embedding, initialize randomly.
      sorted_emb[i, :] = np.random.normal(
          loc=0.0, scale=GLOVE_STD, size=(GLOVE_DIM,))

  return sorted_emb.astype(np.float32)

def append_position_signal(embeddings, position_dim=8):
  """Append position signal. See get_position_signal."""
  batch_size, sequence_length, embedding_dim = embeddings.get_shape().as_list()
  positions = get_position_signal(sequence_length, position_dim)

  # Append to embeddings.
  position_inputs = tf.tile(positions[None, :, :], [batch_size, 1, 1])
  embeddings_pos = tf.concat([embeddings, position_inputs], axis=2)
  embeddings_pos.shape.assert_is_compatible_with(
      [batch_size, sequence_length, embedding_dim + position_dim])
  return embeddings_pos

def get_position_signal(sequence_length, position_dim=8):
  """Return fixed position signal as sine waves.

  Sine waves frequencies are linearly spaced so that shortest is 2 and
  longest is half the maximum length. That way the longest frequency
  is long enough to be monotonous over the whole sequence length.
  Sine waves are also shifted so that they don't all start with the same
  value.
  We don't use learned positional embeddings because these embeddings are
  projected linearly along with the original embeddings, and the projection is
  learned.

  Args:
    sequence_length: int, T, length of the sequence..
    position_dim: int, P, number of sine waves.

  Returns:
    A [T, P] tensor, position embeddings.
  """
  # Compute the frequencies.
  periods = tf.exp(
      tf.lin_space(
          tf.log(2.0), tf.log(tf.to_float(sequence_length)), position_dim))
  frequencies = 1.0 / periods  # Shape [T, P].

  # Compute the sine waves.
  xs = frequencies[None, :] * tf.to_float(tf.range(sequence_length)[:, None])
  shifts = tf.lin_space(0.0, 2.0, position_dim)[None, :]  # [1, P]
  positions = tf.math.cos(math.pi * (xs + shifts))  # [T, P]
  positions.shape.assert_is_compatible_with([sequence_length, position_dim])
  return positions

def get_mask_by_length(lengths, max_length):
  """Returns a mask where x[i , j] = (j < lengths[i]).

  Args:
    lengths: [B] tensor of int32 such that 0 <= lengths[i] <= max_length.
    max_length: scalar tensor of int32.

  Returns:
    [B, max_length] tensor of booleans such that x[i, j] is True
    if and only if j < lengths[i].
  """
  batch_size = lengths.get_shape().as_list()[0]
  indices = tf.range(start=0, limit=max_length)
  all_indices = tf.tile(indices[None, :], [batch_size, 1])
  all_lengths = tf.tile(lengths[:, None], [1, max_length])
  mask = (all_indices < all_lengths)
  mask_boolean = tf.cast(mask, tf.bool)
  return mask_boolean

def get_mask_past_symbol(reference, symbol, optimize_for_tpu=False):
  """For each row, mask is True before and at the first occurrence of symbol."""
  batch_size, max_length = reference.get_shape().as_list()
  symbol = tf.convert_to_tensor(symbol)
  symbol.shape.assert_is_compatible_with([])

  first_indices = get_first_occurrence_indices(reference, symbol,
                                               optimize_for_tpu)
  first_indices.shape.assert_is_compatible_with([batch_size])

  keep_lengths = tf.minimum(first_indices, max_length)
  mask = get_mask_by_length(keep_lengths, max_length)
  mask.shape.assert_is_compatible_with([batch_size, max_length])
  mask.set_shape([batch_size, max_length])
  return mask

def get_first_occurrence_indices(reference, symbol, optimize_for_tpu=False):
  """For each row in reference, get index after the first occurrence of symbol.

  If symbol is not present on a row, return reference.shape[1] instead.

  Args:
    reference: [B, T] tensor of elements of the same type as symbol.
    symbol: int or [] scalar tensor of the same dtype as symbol.
    optimize_for_tpu: bool, whether to use a TPU-capable variant.

  Returns:
    A [B] reference of tf.int32 where x[i] is such that
    reference[i, x[i]-1] == symbol, and reference[i, j] != symbol
    for j<i-1. If symbol is not present on row i then x[i] = T.
  """
  if optimize_for_tpu:
    # Run code which can be compiled on TPU.
    # Transpose refernce to [T, B]
    reference = tf.transpose(reference, [1, 0])
    range_tensor = tf.range(reference.shape.as_list()[0])
    indexes = tf.stack([range_tensor] * reference.shape.as_list()[1], 1)
    symbol = tf.stack([symbol] * reference.shape.as_list()[1], 0)

    initial_indices = tf.constant(
        reference.shape.as_list()[0],
        shape=[reference.shape.as_list()[1]],
        dtype=tf.int32)

    # We want a function which moves backwards.
    def fn(current_index, elems):
      ref, ind = elems
      return tf.where(tf.equal(ref, symbol), ind + 1, current_index)

    min_indexes = tf.scan(
        fn, (reference, indexes),
        initializer=initial_indices,
        parallel_iterations=1,
        reverse=True)
    return min_indexes[0]

  batch_size, max_length = reference.get_shape().as_list()
  symbol = tf.convert_to_tensor(symbol)
  symbol.shape.assert_is_compatible_with([])
  # Add symbol at the end of each row, to make sure tf.where works.
  tensor = tf.concat(
      [reference, tf.tile(symbol[None, None], [batch_size, 1])], axis=1)
  index_all_occurrences = tf.where(tf.equal(tensor, symbol))
  index_all_occurrences = tf.cast(index_all_occurrences, tf.int32)
  # `index_all_occurrences` is a [N, 2] tensor with coordinates of all positions
  # of `symbol` in `tensor`. So N will be >= batch size since there can be
  # several `symbol` in one row of tensor. We need to take only the position
  # of the first occurrence for each row. `segment_min` does that, taking the
  # lowest column index for each row index.
  index_first_occurrences = tf.segment_min(index_all_occurrences[:, 1],
                                           index_all_occurrences[:, 0])
  index_first_occurrences.set_shape([batch_size])
  index_first_occurrences = tf.minimum(index_first_occurrences + 1, max_length)
  return index_first_occurrences

def sequence_to_sentence(sequence, id_to_word):
  """Turn a sequence into a sentence , inverse of sentence_to_sequence."""
  words = []
  for token_index in sequence:
    if token_index in id_to_word:
      words.append(id_to_word[token_index])
    else:
      words.append(reader.UNK)
  return " ".join(words)

def batch_sequences_to_sentences(sequences, id_to_word):
  return [sequence_to_sentence(sequence, id_to_word) for sequence in sequences]

def write_eval_results(checkpoint_dir, all_gen_sentences, checkpoint_name,
                       mean_train_prob, mean_valid_prob, mean_gen_prob, fid):
  """Write evaluation results to disk."""
  to_write = ",".join(
      map(str, [
          checkpoint_name, mean_train_prob, mean_valid_prob, mean_gen_prob, fid
      ]))
  eval_filepath = os.path.join(checkpoint_dir, EVAL_FILENAME)
  previous_eval_content = ""
  if gfile.exists(eval_filepath):
    with gfile.GFile(eval_filepath, "r") as f:
      previous_eval_content = f.read()
  with gfile.GFile(eval_filepath, "w") as f:
    f.write(previous_eval_content + to_write + "\n")

  with gfile.GFile(
      os.path.join(checkpoint_dir, checkpoint_name + "_sentences.txt"),
      "w") as f:
    f.write("\n".join(all_gen_sentences))

def maybe_pick_models_to_evaluate(checkpoint_dir):
  """Pick a checkpoint to evaluate that has not been evaluated already."""
  logging.info("Picking checkpoint to evaluate from %s.", checkpoint_dir)

  filenames = gfile.listdir(checkpoint_dir)
  filenames = [f[:-5] for f in filenames if f[-5:] == ".meta"]
  logging.info("Found existing checkpoints: %s", filenames)

  evaluated_filenames = []
  if gfile.exists(os.path.join(checkpoint_dir, EVAL_FILENAME)):
    with gfile.GFile(os.path.join(checkpoint_dir, EVAL_FILENAME), "r") as f:
      evaluated_filenames = [l.strip().split(",")[0] for l in f.readlines()]
    logging.info("Found already evaluated checkpoints: %s", evaluated_filenames)

  checkpoints_to_evaluate = [
      f for f in filenames if f not in evaluated_filenames
  ]
  logging.info("Remaining potential checkpoints: %s", checkpoints_to_evaluate)

  if checkpoints_to_evaluate:
    return os.path.join(checkpoint_dir, checkpoints_to_evaluate[0])
  else:
    return None

def get_embedding_path(data_dir, dataset):
  """By convention, this is where we store the embedding."""
  return os.path.join(data_dir, "glove_%s.txt" % dataset)

def make_partially_trainable_embeddings(vocab_file, embedding_source,
                                        vocab_size, trainable_embedding_size):
  """Makes embedding matrix with pretrained GloVe [1] part and trainable part.

  [1] Pennington, J., Socher, R., & Manning, C. (2014, October). Glove: Global
  vectors for word representation. In Proceedings of the 2014 conference on
  empirical methods in natural language processing (EMNLP) (pp. 1532-1543).

  Args:
    vocab_file: vocabulary file.
    embedding_source: path to the actual embeddings.
    vocab_size: number of words in vocabulary.
    trainable_embedding_size: size of the trainable part of the embeddings.

  Returns:
    A matrix of partially pretrained embeddings.
  """

  # Our embeddings have 2 parts: a pre-trained, frozen, GloVe part,
  # and a trainable, randomly initialized part.
  # The standard deviation of the GloVe part is used to initialize
  # the trainable part, so that both part have roughly the same distribution.
  #
  # Let g_ij be the j-th coordinates of the GloVe embedding of the i-th word.
  # So that 0 < i < |vocab| and 0 < j < 300.
  # Then sum_ij (g_ij - sum_kl g_kl)^2 = (0.3836)^2
  #
  # In reality g_ij follows a truncated normal distribution
  # min(max(N(0, s), -4.2), 4.2) but we approximate it by N(0, 0.3836).
  embedding_initializer = _get_embedding_initializer(
      vocab_file=vocab_file,
      embedding_source=embedding_source,
      vocab_size=vocab_size)
  pretrained_embedding = tf.get_variable(
      "pretrained_embedding",
      initializer=embedding_initializer,
      dtype=tf.float32)
  trainable_embedding = tf.get_variable(
      "trainable_embedding",
      shape=[vocab_size, trainable_embedding_size],
      initializer=tf.initializers.random_normal(mean=0.0, stddev=GLOVE_STD))
  # We just concatenate embeddings, they will pass through a projection
  # matrix afterwards.
  embedding = tf.concat([pretrained_embedding, trainable_embedding], axis=1)
  return embedding


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LASI.Utilities;

namespace LASI.Content.Tagging
{
    internal class PhraseExtractor
    {
        public TextNode ExtractAndConsume(ref string phraseString)
        {
            phraseString = phraseString.Trim();
            var tagStart = 0;
            var tagEnd = phraseString.Substring(tagStart).IndexOf(" (", StringComparison.Ordinal);
            if (tagEnd == -1 || tagEnd < tagStart)
            {
                var tt = phraseString.SplitRemoveEmpty(' ');
                var taggedPair = new TaggedText(text: tt[1], tag: tt[0]);
                phraseString = string.Empty;
                return new TextNode(taggedPair.Tag + ":  " + taggedPair.Text);
            }
            var tagLength = tagEnd;
            var tag = phraseString.Substring(tagStart + 1, tagLength - 1);
            var innerTextEnd = phraseString.IndexOf("))", StringComparison.Ordinal);
            var innerTextLen = innerTextEnd - tagEnd + 1;
            var innerText = phraseString.Substring(tagEnd + 1, innerTextLen);
            if (innerText.Count(c => c == '(') > 0)
            {
                phraseString = phraseString.Substring(tagLength + innerText.Length).Trim();
                var taggedPair = new TaggedText(tag: tag, text: innerText);
                var result = new TextNode(taggedPair.Tag + ":  " + taggedPair.Text);
                result.AppentChild(ExtractAndConsume(ref innerText));
                return result;
            }
            else
            {
                phraseString = phraseString.Substring(innerTextEnd + 1).Trim();
                var tagged = new TaggedText(tag: "X", text: string.Format("({0} {1})", tag, innerText));
                var result = new TextNode(tagged.Tag + ":  " + tagged.Text);
                result.AppentChild(ExtractAndConsume(ref innerText));
                return result;
            }
        }
    }
    class TextNode
    {
        public TextNode(string text) => Text = text;

        public override string ToString() => Children.Aggregate(Text, (result, child) => result + child);

        public void AppentChild(TextNode child)
        {
            children.Add(child);
        }

        public string Text { get; }

        public IReadOnlyList<TextNode> Children => children;

        readonly List<TextNode> children = new List<TextNode>();
    }
}


text:
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';

import { SchemaFormItemInputComponent } from './schema-form-item-input.component';
import { SharedModule } from '../../../modules/shared/shared.module';
import { FormsModule } from '@angular/forms';
import { SchemaFormModule } from '../schema-form.module';

describe('SchemaFormItemInputComponent', () => {
  let component: SchemaFormItemInputComponent;
  let fixture: ComponentFixture<SchemaFormItemInputComponent>;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      imports: [
        FormsModule,
        SharedModule,
        SchemaFormModule,
      ],
      declarations: [
        // SchemaFormItemInputComponent,
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SchemaFormItemInputComponent);
    component = fixture.componentInstance;
    component.data = {};
    component.item = {};
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
package br.com.geraldoferraz.testyourquery.config.provider;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import br.com.geraldoferraz.testyourquery.config.EntityManagerProvider;

public class PersistenceUnitProvider implements EntityManagerProvider {

	private String persistenceUnit;
	private EntityManagerFactory createEntityManagerFactory;

	public PersistenceUnitProvider(String persistenceUnit) {
		this.persistenceUnit = persistenceUnit;
	}

	public EntityManagerFactory getEntityManagerFactory() {
		if(createEntityManagerFactory == null){
			createEntityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnit);
		}
		return createEntityManagerFactory;
	}

	public String getPersistenceUnit() {
		return persistenceUnit;
	}

}


text:
package jenkins.slaves;

import hudson.AbortException;
import hudson.Extension;
import hudson.remoting.Channel;
import hudson.remoting.Channel.Listener;
import hudson.remoting.ChannelBuilder;
import hudson.remoting.Engine;
import hudson.slaves.SlaveComputer;
import jenkins.AgentProtocol;
import jenkins.model.Jenkins;
import jenkins.security.HMACConfidentialKey;
import org.jenkinsci.remoting.nio.NioChannelHub;

import javax.inject.Inject;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * {@link AgentProtocol} that accepts connection from slave agents.
 *
 *
Security

 *

 * Once connected, remote slave agents can send in commands to be
 * executed on the master, so in a way this is like an rsh service.
 * Therefore, it is important that we reject connections from
 * unauthorized remote slaves.
 *
 *

 * We do this by computing HMAC of the slave name.
 * This code is sent to the slave inside the <tt>.jnlp</tt> file
 * (this file itself is protected by HTTP form-based authentication that
 * we use everywhere else in Jenkins), and the slave sends this
 * token back when it connects to the master.
 * Unauthorized slaves can't access the protected <tt>.jnlp</tt> file,
 * so it can't impersonate a valid slave.
 *
 *

 * We don't want to force the JNLP slave agents to be restarted
 * whenever the server restarts, so right now this secret master key
 * is generated once and used forever, which makes this whole scheme
 * less secure.
 *
 * @author Kohsuke Kawaguchi
 * @since 1.467
 */
@Extension
public class JnlpSlaveAgentProtocol extends AgentProtocol {
    @Inject
    NioChannelSelector hub;

    @Override
    public String getName() {
        return "JNLP-connect";
    }

    @Override
    public void handle(Socket socket) throws IOException, InterruptedException {
        new Handler(hub.getHub(),socket).run();
    }

    protected static class Handler extends JnlpSlaveHandshake {

        /**
         * @deprecated as of 1.559
         *      Use {@link #Handler(NioChannelHub, Socket)}
         */
        public Handler(Socket socket) throws IOException {
            this(null,socket);
        }

        public Handler(NioChannelHub hub, Socket socket) throws IOException {
            super(hub,socket,
                    new DataInputStream(socket.getInputStream()),
                    new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8")),true));
        }

        protected void run() throws IOException, InterruptedException {
            final String secret = in.readUTF();
            final String nodeName = in.readUTF();

            if(!SLAVE_SECRET.mac(nodeName).equals(secret)) {
                error("Unauthorized access");
                return;
            }

            SlaveComputer computer = (SlaveComputer) Jenkins.getInstance().getComputer(nodeName);
            if(computer==null) {
                error("No such slave: "+nodeName);
                return;
            }

            if(computer.getChannel()!=null) {
                error(nodeName+" is already connected to this master. Rejecting this connection.");
                return;
            }

            out.println(Engine.GREETING_SUCCESS);

            jnlpConnect(computer);
        }

        protected Channel jnlpConnect(SlaveComputer computer) throws InterruptedException, IOException {
            final String nodeName = computer.getName();
            final OutputStream log = computer.openLogFile();
            PrintWriter logw = new PrintWriter(log,true);
            logw.println("JNLP agent connected from "+ socket.getInetAddress());

            try {
                ChannelBuilder cb = createChannelBuilder(nodeName);

                computer.setChannel(cb.withHeaderStream(log).build(socket), log,
                    new Listener() {
                        @Override
                        public void onClosed(Channel channel, IOException cause) {
                            if(cause!=null)
                                LOGGER.log(Level.WARNING, Thread.currentThread().getName()+" for + " + nodeName + " terminated",cause);
                            try {
                                socket.close();
                            } catch (IOException e) {
                                // ignore
                            }
                        }
                    });
                return computer.getChannel();
            } catch (AbortException e) {
                logw.println(e.getMessage());
                logw.println("Failed to establish the connection with the slave");
                throw e;
            } catch (IOException e) {
                logw.println("Failed to establish the connection with the slave " + nodeName);
                e.printStackTrace(logw);
                throw e;
            }
        }
    }

    private static final Logger LOGGER = Logger.getLogger(JnlpSlaveAgentProtocol.class.getName());

    /**
     * This secret value is used as a seed for slaves.
     */
    public static final HMACConfidentialKey SLAVE_SECRET = new HMACConfidentialKey(JnlpSlaveAgentProtocol.class,"secret");
}


text:
#ifndef FREERDP_LIB_CORE_GATEWAY_NTLM_H
#define FREERDP_LIB_CORE_GATEWAY_NTLM_H

typedef struct rdp_ntlm rdpNtlm;

#include <winpr/wtypes.h>
#include <freerdp/api.h>
#include <winpr/sspi.h>

FREERDP_LOCAL rdpNtlm* ntlm_new(void);
FREERDP_LOCAL void ntlm_free(rdpNtlm* ntlm);

FREERDP_LOCAL BOOL ntlm_authenticate(rdpNtlm* ntlm, BOOL* pbContinueNeeded);

FREERDP_LOCAL BOOL ntlm_client_init(rdpNtlm* ntlm, BOOL confidentiality, LPCTSTR user,
                                    LPCTSTR domain, LPCTSTR password,
                                    SecPkgContext_Bindings* Bindings);

FREERDP_LOCAL BOOL ntlm_client_make_spn(rdpNtlm* ntlm, LPCTSTR ServiceClass, LPCTSTR hostname);

FREERDP_LOCAL SSIZE_T ntlm_client_query_auth_size(rdpNtlm* ntlm);
FREERDP_LOCAL SSIZE_T ntlm_client_get_context_max_size(rdpNtlm* ntlm);

FREERDP_LOCAL BOOL ntlm_client_encrypt(rdpNtlm* ntlm, ULONG fQOP, SecBufferDesc* Message,
                                       size_t sequence);

FREERDP_LOCAL BOOL ntlm_client_set_input_buffer(rdpNtlm* ntlm, BOOL copy, const void* data,
                                                size_t size);
FREERDP_LOCAL const SecBuffer* ntlm_client_get_output_buffer(rdpNtlm* ntlm);

#endif /* FREERDP_LIB_CORE_GATEWAY_NTLM_H */


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/linux/remote_desktop_portal.h"

#include <glib-object.h>

#include <utility>

#include "base/check.h"
#include "base/rand_util.h"
#include "base/sequence_checker.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "remoting/base/logging.h"
#include "third_party/webrtc/modules/desktop_capture/linux/wayland/xdg_desktop_portal_utils.h"

namespace remoting {
namespace xdg_portal {
namespace {

constexpr char kRemoteDesktopInterfaceName[] =
    "org.freedesktop.portal.RemoteDesktop";
constexpr char kPortalPrefix[] = "remotedesktop";

using webrtc::Scoped;
using webrtc::xdg_portal::kDesktopObjectPath;
using webrtc::xdg_portal::kSessionInterfaceName;
using webrtc::xdg_portal::RequestResponse;

void UnsubscribeSignalHandler(GDBusConnection* connection, guint& signal_id) {
  if (signal_id) {
    g_dbus_connection_signal_unsubscribe(connection, signal_id);
    signal_id = 0;
  }
}

}  // namespace

RemoteDesktopPortal::RemoteDesktopPortal(
    webrtc::ScreenCastPortal::PortalNotifier* notifier)
    : notifier_(notifier) {
  screencast_portal_ = std::make_unique<webrtc::ScreenCastPortal>(
      webrtc::CaptureType::kScreen, this, OnScreenCastPortalProxyRequested,
      OnSourcesRequestResponseSignal, this);
  DETACH_FROM_SEQUENCE(sequence_checker_);
}

RemoteDesktopPortal::~RemoteDesktopPortal() {
  Stop();
}

void RemoteDesktopPortal::Stop() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (context_) {
    g_main_context_pop_thread_default(context_);
    g_main_context_unref(context_);
  }
  if (screencast_portal_)
    screencast_portal_.reset();
  UnsubscribeSignalHandlers();
  webrtc::xdg_portal::TearDownSession(std::move(session_handle_), proxy_,
                                      cancellable_, connection_);
  session_handle_.clear();
  proxy_ = nullptr;
  cancellable_ = nullptr;
  connection_ = nullptr;
}

void RemoteDesktopPortal::UnsubscribeSignalHandlers() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  UnsubscribeSignalHandler(connection_, start_request_signal_id_);
  UnsubscribeSignalHandler(connection_, session_request_signal_id_);
  UnsubscribeSignalHandler(connection_, devices_request_signal_id_);
  UnsubscribeSignalHandler(connection_, session_closed_signal_id_);
}

void RemoteDesktopPortal::Start() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // We create and run our own thread-default context so that all the callbacks
  // are called on this thread rather than going to the main thread.
  context_ = g_main_context_new();
  g_main_context_push_thread_default(context_);

  HOST_LOG << "Starting screen cast portal";
  cancellable_ = g_cancellable_new();
  screencast_portal_->SetSessionDetails({.cancellable = cancellable_});
  screencast_portal_->Start();

  HOST_LOG << "Starting remote desktop portal";
  webrtc::xdg_portal::RequestSessionProxy(kRemoteDesktopInterfaceName,
                                          OnProxyRequested, cancellable_, this);

  // OpenPipewireRemote (defined on the screencast portal) is the last
  // asynchronous call in the combined portal setup so we wait for the
  // screencast portal to go into either failed/succeeded state before stopping
  // our loop.
  while (context_ && screencast_portal_status_ == RequestResponse::kUnknown) {
    g_main_context_iteration(context_, /*may_block=*/true);
  }
  if (context_) {
    g_main_context_pop_thread_default(context_);
    g_main_context_unref(context_);
    context_ = nullptr;
  }

  HOST_LOG << "Session setup finished";
}

uint32_t RemoteDesktopPortal::pipewire_stream_node_id() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(screencast_portal_);
  return screencast_portal_->pipewire_stream_node_id();
}

// static
void RemoteDesktopPortal::OnProxyRequested(GObject* gobject,
                                           GAsyncResult* result,
                                           gpointer user_data) {
  RemoteDesktopPortal* that = static_cast<RemoteDesktopPortal*>(user_data);
  DCHECK_CALLED_ON_VALID_SEQUENCE(that->sequence_checker_);
  DCHECK(that);
  Scoped<GError> error;
  // We have to acquire the proxy object via "_finish" here since otherwise
  // the result will be freed upon return from this callback (and before newly
  // posted task on the task runner can start/finish).
  GDBusProxy* proxy = g_dbus_proxy_new_finish(result, error.receive());
  if (!proxy) {
    if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
      return;
    LOG(ERROR) << "Failed to get a proxy for the portal: " << error->message;
    that->OnPortalDone(RequestResponse::kError);
    return;
  }
  that->RequestSession(proxy);
}

// static
void RemoteDesktopPortal::OnScreenCastPortalProxyRequested(GObject* /*object*/,
                                                           GAsyncResult* result,
                                                           gpointer user_data) {
  webrtc::ScreenCastPortal* that =
      static_cast<webrtc::ScreenCastPortal*>(user_data);
  DCHECK(that);

  Scoped<GError> error;
  GDBusProxy* proxy = g_dbus_proxy_new_finish(result, error.receive());
  if (!proxy) {
    if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
      return;
    LOG(ERROR) << "Failed to create a proxy for the screen cast portal: "
               << error->message;
    that->OnPortalDone(RequestResponse::kError);
    return;
  }
  that->SetSessionDetails({.proxy = proxy});

  HOST_LOG << "Successfully created proxy for the screen cast portal.";
}

void RemoteDesktopPortal::RequestSession(GDBusProxy* proxy) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!proxy_);
  DCHECK(!connection_);
  proxy_ = proxy;
  connection_ = g_dbus_proxy_get_connection(proxy);
  webrtc::xdg_portal::SetupSessionRequestHandlers(
      kPortalPrefix, OnSessionRequested, OnSessionRequestResponseSignal,
      connection_, proxy_, cancellable_, portal_handle_,
      session_request_signal_id_, this);
}

// static
void RemoteDesktopPortal::OnSessionRequested(GDBusProxy* proxy,
                                             GAsyncResult* result,
                                             gpointer user_data) {
  RemoteDesktopPortal* that = static_cast<RemoteDesktopPortal*>(user_data);
  DCHECK_CALLED_ON_VALID_SEQUENCE(that->sequence_checker_);
  that->OnSessionRequestResult(proxy, result);
}

// static
void RemoteDesktopPortal::OnDevicesRequested(GDBusProxy* proxy,
                                             GAsyncResult* result,
                                             gpointer user_data) {
  RemoteDesktopPortal* that = static_cast<RemoteDesktopPortal*>(user_data);
  DCHECK(that);
  DCHECK_CALLED_ON_VALID_SEQUENCE(that->sequence_checker_);

  Scoped<GError> error;
  Scoped<GVariant> variant(
      g_dbus_proxy_call_finish(proxy, result, error.receive()));
  if (!variant) {
    LOG(ERROR) << "Failed to select the devices: " << error->message;
    return;
  }

  Scoped<gchar> handle;
  g_variant_get_child(variant.get(), 0, "o", handle.receive());
  if (!handle) {
    LOG(ERROR) << "Failed to initialize the remote desktop session.";
    if (that->devices_request_signal_id_) {
      g_dbus_connection_signal_unsubscribe(that->connection_,
                                           that->devices_request_signal_id_);
      that->devices_request_signal_id_ = 0;
    }
    return;
  }
  HOST_LOG << "Subscribed to devices signal.";
}

void RemoteDesktopPortal::RequestSources() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  screencast_portal_->SourcesRequest();
}

// static
void RemoteDesktopPortal::OnDevicesRequestImpl(GDBusConnection* connection,
                                               const gchar* sender_name,
                                               const gchar* object_path,
                                               const gchar* interface_name,
                                               const gchar* signal_name,
                                               GVariant* parameters,
                                               gpointer user_data) {
  HOST_LOG << "Received device selection signal from session.";
  RemoteDesktopPortal* that = static_cast<RemoteDesktopPortal*>(user_data);
  DCHECK(that);
  DCHECK_CALLED_ON_VALID_SEQUENCE(that->sequence_checker_);

  guint32 portal_response;
  g_variant_get(parameters, "(u@a{sv})", &portal_response, nullptr);
  if (portal_response) {
    LOG(ERROR) << "Failed to select devices for the remote desktop session.";
    return;
  }

  that->RequestSources();
}

void RemoteDesktopPortal::SelectDevices() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  GVariantBuilder builder;

  g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
  g_variant_builder_add(&builder, "{sv}", "multiple",
                        g_variant_new_boolean(false));

  auto name = base::StringPrintf(
      "%s%d", kPortalPrefix, base::RandInt(0, std::numeric_limits<int>::max()));
  g_variant_builder_add(&builder, "{sv}", "handle_token",
                        g_variant_new_string(name.c_str()));
  devices_handle_ =
      webrtc::xdg_portal::PrepareSignalHandle(name.c_str(), connection_);
  devices_request_signal_id_ = webrtc::xdg_portal::SetupRequestResponseSignal(
      devices_handle_.c_str(), OnDevicesRequestImpl, this, connection_);

  HOST_LOG << "Selecting devices from the remote desktop session.";
  g_dbus_proxy_call(
      proxy_, "SelectDevices",
      g_variant_new("(oa{sv})", session_handle_.c_str(), &builder),
      G_DBUS_CALL_FLAGS_NONE, /*timeout=*/-1, cancellable_,
      reinterpret_cast<GAsyncReadyCallback>(OnDevicesRequested), this);
}

// static
void RemoteDesktopPortal::OnSessionRequestResponseSignal(
    GDBusConnection* connection,
    const char* sender_name,
    const char* object_path,
    const char* interface_name,
    const char* signal_name,
    GVariant* parameters,
    gpointer user_data) {
  RemoteDesktopPortal* that = static_cast<RemoteDesktopPortal*>(user_data);
  DCHECK(that);
  DCHECK_CALLED_ON_VALID_SEQUENCE(that->sequence_checker_);

  that->RegisterSessionClosedSignalHandler(
      OnSessionClosedSignal, parameters, that->connection_,
      that->session_handle_, that->session_closed_signal_id_);
  that->screencast_portal_->SetSessionDetails(
      {.session_handle = that->session_handle_});
  that->SelectDevices();
}

// static
void RemoteDesktopPortal::OnSessionClosedSignal(GDBusConnection* connection,
                                                const char* sender_name,
                                                const char* object_path,
                                                const char* interface_name,
                                                const char* signal_name,
                                                GVariant* parameters,
                                                gpointer user_data) {
  RemoteDesktopPortal* that = static_cast<RemoteDesktopPortal*>(user_data);
  DCHECK(that);
  DCHECK_CALLED_ON_VALID_SEQUENCE(that->sequence_checker_);

  HOST_LOG << "Received closed signal from session.";

  // Unsubscribe from the signal and free the session handle to avoid calling
  // Session::Close from the destructor since it's already closed
  g_dbus_connection_signal_unsubscribe(that->connection_,
                                       that->session_closed_signal_id_);
}

// static
void RemoteDesktopPortal::OnSourcesRequestResponseSignal(
    GDBusConnection* connection,
    const char* sender_name,
    const char* object_path,
    const char* interface_name,
    const char* signal_name,
    GVariant* parameters,
    gpointer user_data) {
  RemoteDesktopPortal* that = static_cast<RemoteDesktopPortal*>(user_data);
  DCHECK(that);
  DCHECK_CALLED_ON_VALID_SEQUENCE(that->sequence_checker_);

  HOST_LOG << "Received sources signal from session.";

  uint32_t portal_response;
  g_variant_get(parameters, "(u@a{sv})", &portal_response, nullptr);
  if (portal_response) {
    LOG(ERROR) << "Failed to select sources for the remote desktop session.";
    that->OnPortalDone(RequestResponse::kError);
    return;
  }
  that->StartRequest();
}

void RemoteDesktopPortal::StartRequest() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  webrtc::xdg_portal::StartSessionRequest(
      kPortalPrefix, session_handle_, OnStartRequestResponseSignal,
      OnStartRequested, proxy_, connection_, cancellable_,
      start_request_signal_id_, start_handle_, this);
}

// static
void RemoteDesktopPortal::OnStartRequested(GDBusProxy* proxy,
                                           GAsyncResult* result,
                                           gpointer user_data) {
  RemoteDesktopPortal* that = static_cast<RemoteDesktopPortal*>(user_data);
  DCHECK(that);
  DCHECK_CALLED_ON_VALID_SEQUENCE(that->sequence_checker_);
  that->OnStartRequestResult(proxy, result);
}

// static
void RemoteDesktopPortal::OnStartRequestResponseSignal(
    GDBusConnection* connection,
    const char* sender_name,
    const char* object_path,
    const char* interface_name,
    const char* signal_name,
    GVariant* parameters,
    gpointer user_data) {
  RemoteDesktopPortal* that = static_cast<RemoteDesktopPortal*>(user_data);
  DCHECK(that);
  DCHECK_CALLED_ON_VALID_SEQUENCE(that->sequence_checker_);
  HOST_LOG << "Start signal received.";
  uint32_t portal_response;
  Scoped<GVariant> response_data;
  Scoped<GVariantIter> iter;
  g_variant_get(parameters, "(u@a{sv})", &portal_response,
                response_data.receive());
  if (portal_response || !response_data) {
    LOG(ERROR) << "Failed to start the remote desktop session.";
    return;
  }

  if (g_variant_lookup(response_data.get(), "streams", "a(ua{sv})",
                       iter.receive())) {
    Scoped<GVariant> variant;

    while (g_variant_iter_next(iter.get(), "@(ua{sv})", variant.receive())) {
      uint32_t stream_id;
      Scoped<GVariant> options;

      g_variant_get(variant.get(), "(u@a{sv})", &stream_id, options.receive());
      DCHECK(options.get());

      that->screencast_portal_->SetSessionDetails(
          {.pipewire_stream_node_id = stream_id});
      HOST_LOG << "Pipewire stream node id has been set for the portal";
      break;
    }
  }

  that->screencast_portal_->OpenPipeWireRemote();
  that->OnPortalDone(RequestResponse::kSuccess);
  HOST_LOG << "Remote desktop portal start response successful";
}

void RemoteDesktopPortal::OnPortalDone(RequestResponse result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  LOG(INFO) << "Remote desktop portal setup is done: "
            << webrtc::xdg_portal::RequestResponseToString(result);
  if (result != RequestResponse::kSuccess) {
    Stop();
  }
}

webrtc::xdg_portal::SessionDetails RemoteDesktopPortal::GetSessionDetails() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  HOST_LOG << "Getting session details from the wayland capturer";
  return {proxy_.get(), cancellable_.get(), session_handle_,
          pipewire_stream_node_id()};
}

void RemoteDesktopPortal::OnScreenCastRequestResult(RequestResponse result,
                                                    uint32_t stream_node_id,
                                                    int fd) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  screencast_portal_status_ = result;
  notifier_->OnScreenCastRequestResult(result, stream_node_id, fd);
}

void RemoteDesktopPortal::OnScreenCastSessionClosed() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  notifier_->OnScreenCastSessionClosed();
}

}  // namespace xdg_portal
}  // namespace remoting


text:
import { DragEvent, DragEventHandler, useState } from 'react';

interface Options {
    onDragOver?: (event: DragEvent) => void;
    onDragEnter?: (event: DragEvent) => void;
    onDragLeave?: (event: DragEvent) => void;
    onDrop?: (event: DragEvent) => void;
}

type DragOverReturn = [
    dragsOver: boolean,
    dragHandlers: {
        onDragEnter: DragEventHandler;
        onDragLeave: DragEventHandler;
        onDragOver: DragEventHandler;
        onDrop: DragEventHandler;
    }
];

/**
 * Hooks to manage a dragOver flag
 * Takes an optional filter function to accept only specific drag content
 * Returns the flag and the handlers to pass to the element you want to drag on
 */
const useDragOver = (
    dragFilter: (event: DragEvent) => boolean = () => true,
    dropEffect: 'none' | 'copy' | 'link' | 'move' = 'move',
    { onDragOver, onDragEnter, onDragLeave, onDrop }: Options = {}
): DragOverReturn => {
    const [dragOver, setDragOver] = useState(0);

    const handleDragEnter = (event: DragEvent) => {
        if (dragFilter(event)) {
            event.preventDefault();
            if (dragOver === 0) {
                onDragEnter?.(event);
            }
            setDragOver(dragOver + 1);
        }
    };
    const handleDragLeave = (event: DragEvent) => {
        if (dragFilter(event)) {
            event.preventDefault();
            if (dragOver === 1) {
                onDragLeave?.(event);
            }
            setDragOver(dragOver - 1);
        }
    };
    const handleDragOver = (event: DragEvent) => {
        if (dragFilter(event)) {
            if (event.dataTransfer.effectAllowed === 'all') {
                event.dataTransfer.dropEffect = dropEffect;
            }
            event.preventDefault();
            onDragOver?.(event);
        }
    };

    const handleDrop = (event: DragEvent) => {
        setDragOver(0);
        onDrop?.(event);
    };

    return [
        dragOver > 0,
        { onDragEnter: handleDragEnter, onDragLeave: handleDragLeave, onDragOver: handleDragOver, onDrop: handleDrop },
    ];
};

export default useDragOver;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bookables.Core
{
    using Itenso.TimePeriod;

    /// <summary>
    /// An object responsible to check if IBookableItem is available
    /// </summary>
    public interface IAvailabilityChecker
    {
        /// <summary>
        /// Aks for the availability of a searched timeperiod in a item
        /// </summary>
        /// <param name="bookableItem">An item with periods</param>
        /// <param name="timePeriod">A time period to check if is available</param>
        /// <returns>Returns true if the period is available</returns>
        bool IsAvailable(IBookableItem bookableItem, ITimePeriod timePeriod);
    }
}


text:
import logging

def get_logger():
    # Use the root logger
    return logging.getLogger()


text:
package com.joey.bak.base.ui;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.jaeger.library.StatusBarUtil;
import com.joe.zatuji.MyApplication;
import com.joe.zatuji.R;
import com.joe.zatuji.base.BasePresenter;
import com.joe.zatuji.base.LoadingView;
import com.joe.zatuji.utils.KToast;
import com.joe.zatuji.utils.TUtil;
import com.joe.zatuji.view.LoadingDialog;
import com.squareup.leakcanary.RefWatcher;
import com.umeng.analytics.MobclickAgent;

/**
 * 所有activity的基类
 * Created by Joe on 2016/4/14.
 */
public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity implements LoadingView {
    protected T mPresenter;
    protected Activity mActivity;
    protected MyApplication mApplication;
    private AlertDialog dialog;
    private View loadingView;
    protected LoadingDialog mLoadingDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout());
        this.mActivity=this;
        this.mApplication= (MyApplication) getApplication();
        StatusBarUtil.setColor(this,getResources().getColor(R.color.colorPrimary));
        //initLeakCanary();
        initPM();//初始化presenter和model
        initPresenter();
        initView();
        initLoading();
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void initPM() {
        mPresenter = TUtil.getT(this,0);
        if(mPresenter!=null) mPresenter.onStart();
    }
    protected abstract int getLayout();
    protected abstract void initView();
    protected abstract void initPresenter();

    protected void initLeakCanary(){
        RefWatcher refWatcher = MyApplication.getRefWatcher(this);
        refWatcher.watch(this);
    }

    protected void initLoading() {
        dialog=new AlertDialog.Builder(this).create();
        loadingView = View.inflate(this, R.layout.dialog_loading,null);
    }

    protected  void initListener(){

    }

    @Override
    public void showLoading(){
        dialog.show();
        dialog.setContentView(loadingView);

    }
    @Override
    public void doneLoading(){
        dialog.dismiss();
        if(mLoadingDialog!=null){
            mLoadingDialog.dismiss();
        }

    }
    @Override
    public void showError(String str) {
        KToast.show(str);
    }

    public void showLoading(String msg){
        if(mLoadingDialog==null) mLoadingDialog = new LoadingDialog(mActivity,msg);
        mLoadingDialog.setMessage(msg);
        mLoadingDialog.show();
    }
//    public void doneLoading(){
//        if(loadView!=null&&loadView.isShowing()) loadView.dismiss();
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mPresenter!=null) mPresenter.onRemove();
    }
}


text:
package com.dgrid.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Encryption {

	public static final String RSA = "RSA";

	public static final String RSA_PADDED = "RSA/NONE/OAEPWithSHA1AndMGF1Padding";

	public static final String DSA = "DSA";

	public static final String DES = "DES";

	public static final String DES_PADDED = "DES/ECB/PKCS5Padding";

	public static final String DH = "DH";

	public static final String SHA1withRSA = "SHA1withRSA";

	public static final int DEFAULT_KEY_SIZE = 1024;

	public static final int PRIVATE = 0;

	public static final int PUBLIC = 1;

	private static final String pbeCipherName = "PBEWithMD5AndDES";

	private static Log log = LogFactory.getLog(Encryption.class);

	private static SecureRandom secureRandom = null;

	static {
		try {
			secureRandom = initSecureRandom();
		} catch (Exception e) {
			log.error("Exception initializing encryption provider", e);
		}
	}

	public static KeyPair generateKeyPair(String algorithm, int keySize)
			throws NoSuchAlgorithmException, NoSuchProviderException {
		KeyPairGenerator kpg = KeyPairGenerator.getInstance(algorithm);
		kpg.initialize(keySize, secureRandom);
		KeyPair kp = kpg.generateKeyPair();
		return (kp);
	}

	public static Key generateSecretKey(String algorithm)
			throws NoSuchAlgorithmException {
		KeyGenerator kg = KeyGenerator.getInstance(algorithm);
		Key secret = kg.generateKey();
		return secret;
	}

	public static byte[] sign(byte[] data, PrivateKey privateKey,
			String algorithm) throws RuntimeException {
		try {
			Signature sig = Signature.getInstance(algorithm);
			sig.initSign(privateKey);
			sig.update(data);
			return sig.sign();
		} catch (Exception e) {
			log.error("Exception in sign()", e);
			throw new RuntimeException(e);
		}
	}

	public static String signString(String data, PrivateKey privateKey,
			String algorithm) throws RuntimeException {
		byte[] sigBytes = sign(data.getBytes(), privateKey, algorithm);
		return new String(Base64Encoder.base64Encode(sigBytes));
	}

	public static boolean verify(byte[] data, PublicKey publicKey,
			String algorithm, byte[] signature) throws RuntimeException {
		try {
			Signature sig = Signature.getInstance(algorithm);
			sig.initVerify(publicKey);
			sig.update(data);
			return sig.verify(signature);
		} catch (Exception e) {
			log.error("Exception in verify()", e);
			throw new RuntimeException(e);
		}
	}

	public static boolean verifyBase64(String data, PublicKey publicKey,
			String algorithm, String signatureBase64) throws RuntimeException {
		byte[] sig = Base64Encoder.base64Decode(signatureBase64.getBytes());
		byte[] dataBytes = data.getBytes();
		return verify(dataBytes, publicKey, algorithm, sig);
	}

	public static String encryptStringBase64(String plaintext,
			String algorithm, Key publicKey) throws RuntimeException {
		byte[] bytes = encryptString(plaintext, algorithm, publicKey);
		byte[] encoded = Base64Encoder.base64Encode(bytes);
		return (new String(encoded));
	}

	public static byte[] encryptString(String plaintext, String algorithm,
			Key publicKey) throws RuntimeException {
		try {
			Cipher cipher = Cipher.getInstance(algorithm);
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			byte[] input = plaintext.getBytes();
			byte[] encryptedBytes = cipher.doFinal(input);
			return encryptedBytes;
		} catch (GeneralSecurityException e) {
			log.error("GeneralSecurityException in encryptString()", e);
			throw new RuntimeException(e);
		}
	}

	public static String decryptStringBase64(String ciphertext,
			String algorithm, Key privKey) throws RuntimeException {
		try {
			byte[] bytes = ciphertext.getBytes();
			byte[] decoded = Base64Encoder.base64Decode(bytes);
			String value = decryptString(decoded, algorithm, privKey);
			return value;
		} catch (Exception e) {
			log.error("Exception in encryptString()", e);
			throw new RuntimeException(e);
		}
	}

	public static String decryptString(byte[] ciphertext, String algorithm,
			Key privKey) throws RuntimeException {
		try {
			Cipher cipher = Cipher.getInstance(algorithm, "BC");
			cipher.init(Cipher.DECRYPT_MODE, privKey);
			byte[] decryptedBytes = cipher.doFinal(ciphertext);
			return new String(decryptedBytes);
		} catch (Exception e) {
			log.error("Exception in encryptString()", e);
			throw new RuntimeException(e);
		}
	}

	public static Key getKey(byte[] keyData, String keyType,
			boolean isPrivateKey) throws RuntimeException {
		log.trace("getKey()");
		try {
			// keyType should be RSA
			KeyFactory kf = KeyFactory.getInstance(keyType);
			Key key = null;
			if (isPrivateKey) {
				PKCS8EncodedKeySpec encodedPrivateKey = new PKCS8EncodedKeySpec(
						keyData);
				key = kf.generatePrivate(encodedPrivateKey);
			} else {
				X509EncodedKeySpec encodedPublicKey = new X509EncodedKeySpec(
						keyData);
				key = kf.generatePublic(encodedPublicKey);
			}
			return key;
		} catch (Exception e) {
			log.error("Exception in encryptString()", e);
			throw new RuntimeException(e);
		}
	}

	public static Key getSecretKey(String algorithm, byte[] keyData)
			throws Exception {
		log.trace("getSecretKey()");
		SecretKeySpec keySpec = new SecretKeySpec(keyData, algorithm);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
		return keyFactory.generateSecret(keySpec);
	}

	private static SecureRandom initSecureRandom()
			throws NoSuchAlgorithmException, NoSuchProviderException,
			FileNotFoundException, IOException {
		log.trace("initSecureRandom()");
		Security
				.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
		if (new File("/dev/urandom").exists()) {
			log.info("Salting SecureRandom (SHA1PRNG) from /dev/urandom");
			byte[] salt = new byte[8192];
			FileInputStream fis = new FileInputStream("/dev/urandom");
			fis.read(salt);
			fis.close();
			sr.setSeed(salt);
		}
		return sr;
	}
}


text:
<?php

declare(strict_types = 1);

namespace Saber\Control {

	use \Saber\Core;

	abstract class Module extends Core\Module { }

}


text:
#ifndef _LIBELFP_H
#define _LIBELFP_H 1

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <ar.h>
#include <gelf.h>

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

/* gettext helper macros.  */
#define _(Str) dgettext ("libelf", Str)

/* Helper Macros to write 32 bit and 64 bit functions.  */
#define __elfw2_(Bits, Name) __elf##Bits##_##Name
#define elfw2_(Bits, Name) elf##Bits##_##Name
#define ElfW2_(Bits, Name) Elf##Bits##_##Name
#define ELFW2_(Bits, Name) ELF##Bits##_##Name
#define ELFW_(Name, Bits) Name##Bits
#define __elfw2(Bits, Name) __elfw2_(Bits, Name)
#define elfw2(Bits, Name) elfw2_(Bits, Name)
#define ElfW2(Bits, Name) ElfW2_(Bits, Name)
#define ELFW2(Bits, Name) ELFW2_(Bits, Name)
#define ELFW(Name, Bits)  ELFW_(Name, Bits)

/* Sizes of the external types, for 32 bits objects.  */
#define ELF32_FSZ_ADDR   4
#define ELF32_FSZ_OFF    4
#define ELF32_FSZ_HALF   2
#define ELF32_FSZ_WORD   4
#define ELF32_FSZ_SWORD  4
#define ELF32_FSZ_XWORD  8
#define ELF32_FSZ_SXWORD 8

/* Same for 64 bits objects.  */
#define ELF64_FSZ_ADDR   8
#define ELF64_FSZ_OFF    8
#define ELF64_FSZ_HALF   2
#define ELF64_FSZ_WORD   4
#define ELF64_FSZ_SWORD  4
#define ELF64_FSZ_XWORD  8
#define ELF64_FSZ_SXWORD 8

/* This is an extension of the ELF_F_* enumeration.  The values here are
   not part of the library interface, they are only used internally.  */
enum
{
  ELF_F_MMAPPED = 0x40,
  ELF_F_MALLOCED = 0x80,
  ELF_F_FILEDATA = 0x100
};

/* Get definition of all the external types.  */
#include "exttypes.h"

/* Error values.  */
enum
{
  ELF_E_NOERROR = 0,
  ELF_E_UNKNOWN_ERROR,
  ELF_E_UNKNOWN_VERSION,
  ELF_E_UNKNOWN_TYPE,
  ELF_E_INVALID_HANDLE,
  ELF_E_SOURCE_SIZE,
  ELF_E_DEST_SIZE,
  ELF_E_INVALID_ENCODING,
  ELF_E_NOMEM,
  ELF_E_INVALID_FILE,
  ELF_E_INVALID_OP,
  ELF_E_NO_VERSION,
  ELF_E_INVALID_CMD,
  ELF_E_RANGE,
  ELF_E_ARCHIVE_FMAG,
  ELF_E_INVALID_ARCHIVE,
  ELF_E_NO_ARCHIVE,
  ELF_E_NO_INDEX,
  ELF_E_READ_ERROR,
  ELF_E_WRITE_ERROR,
  ELF_E_INVALID_CLASS,
  ELF_E_INVALID_INDEX,
  ELF_E_INVALID_OPERAND,
  ELF_E_INVALID_SECTION,
  ELF_E_INVALID_COMMAND,
  ELF_E_WRONG_ORDER_EHDR,
  ELF_E_FD_DISABLED,
  ELF_E_FD_MISMATCH,
  ELF_E_OFFSET_RANGE,
  ELF_E_NOT_NUL_SECTION,
  ELF_E_DATA_MISMATCH,
  ELF_E_INVALID_SECTION_HEADER,
  ELF_E_INVALID_DATA,
  ELF_E_DATA_ENCODING,
  ELF_E_SECTION_TOO_SMALL,
  ELF_E_INVALID_ALIGN,
  ELF_E_INVALID_SHENTSIZE,
  ELF_E_UPDATE_RO,
  ELF_E_NOFILE,
  ELF_E_GROUP_NOT_REL,
  ELF_E_INVALID_PHDR,
  ELF_E_NO_PHDR,
  ELF_E_INVALID_OFFSET,
  /* Keep this as the last entry.  */
  ELF_E_NUM
};

/* The visible `Elf_Data' type is not sufficent for some operations due
   to a misdesigned interface.  Extend it for internal purposes.  */
typedef struct
{
  Elf_Data d;
  Elf_Scn *s;
} Elf_Data_Scn;

/* List of `Elf_Data' descriptors.  This is what makes up the section
   contents.  */
typedef struct Elf_Data_List
{
  /* `data' *must* be the first element in the struct.  */
  Elf_Data_Scn data;
  struct Elf_Data_List *next;
  int flags;
} Elf_Data_List;

/* Descriptor for ELF section.  */
struct Elf_Scn
{
  /* We have to distinguish several different situations:

     1. the section is user created.  Therefore there is no file or memory
        region to read the data from.  Here we have two different subcases:

        a) data was not yet added (before the first `elf_newdata' call)

        b) at least one data set is available

     2. this is a section from a file/memory region.  We have to read the
        current content in one data block if we have to.  But we don't
        read the data until it is necessary.  So we have the subcases:

        a) the section in the file has size zero (for whatever reason)

        b) the data of the file is not (yet) read

        c) the data is read and available.

     In addition to this we have different data sets, the raw and the converted
     data.  This distinction only exists for the data read from the file.
     All user-added data set (all but the first when read from the file or
     all of them for user-create sections) are the same in both formats.
     We don't create the converted data before it is necessary.

     The `data_read' element signals whether data is available in the
     raw format.

     If there is data from the file/memory region or if read one data
     set is added the `rawdata_list_read' pointer in non-NULL and points
     to the last filled data set.  `raw_datalist_rear' is therefore NULL
     only if there is no data set at all.

     This so far allows to distinguish all but two cases (given that the
     `rawdata_list' and `data_list' entries are initialized to zero) is
     between not yet loaded data from the file/memory region and a section
     with zero size and type ELF_T_BYTE.   */
  Elf_Data_List data_list;	/* List of data buffers.  */
  Elf_Data_List *data_list_rear; /* Pointer to the rear of the data list. */

  Elf_Data_Scn rawdata;		/* Uninterpreted data of the section.  */

  int data_read;		/* Nonzero if the section was created by the
				   user or if the data from the file/memory
				   is read.  */
  int shndx_index;		/* Index of the extended section index
				   table for this symbol table (if this
				   section is a symbol table).  */

  size_t index;			/* Index of this section.  */
  struct Elf *elf;		/* The underlying ELF file.  */

  union
  {
    Elf32_Shdr *e32;		/* Pointer to 32bit section header.  */
    Elf64_Shdr *e64;		/* Pointer to 64bit section header.  */
  } shdr;

  unsigned int shdr_flags;	/* Section header modified?  */
  unsigned int flags;		/* Section changed in size?  */

  char *rawdata_base;		/* The unmodified data of the section.  */
  char *data_base;		/* The converted data of the section.  */

  struct Elf_ScnList *list;	/* Pointer the the section list element the
				   data is in.  */
};

/* List of section.  */
typedef struct Elf_ScnList
{
  unsigned int cnt;		/* Number of elements of 'data' used.  */
  unsigned int max;		/* Number of elements of 'data' allocated.  */
  struct Elf_ScnList *next;	/* Next block of sections.  */
  struct Elf_Scn data[0];	/* Section data.  */
} Elf_ScnList;

/* elf_getdata_rawchunk result.  */
typedef struct Elf_Data_Chunk
{
  Elf_Data_Scn data;
  union
  {
    Elf_Scn dummy_scn;
    struct Elf_Data_Chunk *next;
  };
} Elf_Data_Chunk;

/* The ELF descriptor.  */
struct Elf
{
  /* What kind of file is underneath (ELF file, archive...).  */
  Elf_Kind kind;

  /* Command used to create this descriptor.  */
  Elf_Cmd cmd;

  /* The binary class.  */
  unsigned int class;

  /* The used file descriptor.  -1 if not available anymore.  */
  int fildes;

  /* Offset in the archive this file starts or zero.  */
  off_t start_offset;

  /* Size of the file in the archive or the entire file size, or ~0
     for an (yet) unknown size.  */
  size_t maximum_size;

  /* Address to which the file was mapped.  NULL if not mapped.  */
  void *map_address;

  /* Describes the way the memory was allocated and if the dirty bit is
     signalled it means that the whole file has to be rewritten since
     the layout changed.  */
  int flags;

  /* When created for an archive member this points to the descriptor
     for the archive. */
  Elf *parent;

  /* Lock to handle multithreaded programs.  */
  rwlock_define (,lock);

  /* Reference counting for the descriptor.  */
  int ref_count;

  struct Elf *next;             /* Used in list of archive descriptors.  */

  union
  {
    struct
    {
      int ehdr_flags;		/* Flags (dirty) for ELF header.  */
      int phdr_flags;		/* Flags (dirty|malloc) for program header.  */
      int shdr_malloced;	/* Nonzero if shdr array was allocated.  */

      /* The next fields are only useful when testing for ==/!= NULL.  */
      void *ehdr;
      void *shdr;
      void *phdr;

      Elf_ScnList *scns_last;	/* Last element in the section list.
				   If NULL the data has not yet been
				   read from the file.  */
      Elf_Data_Chunk *rawchunks; /* List of elf_getdata_rawchunk results.  */
      unsigned int scnincr;	/* Number of sections allocate the last
				   time.  */
      off64_t sizestr_offset;	/* Offset of the size string in the parent
				   if this is an archive member.  */
    } elf;

    struct
    {
      int ehdr_flags;		/* Flags (dirty) for ELF header.  */
      int phdr_flags;		/* Flags (dirty|malloc) for program header.  */
      int shdr_malloced;	/* Nonzero if shdr array was allocated.  */

      Elf32_Ehdr *ehdr;		/* Pointer to the ELF header.  This is
				   never malloced.  */
      Elf32_Shdr *shdr;		/* Used when reading from a file.  */
      Elf32_Phdr *phdr;		/* Pointer to the program header array.  */
      Elf_ScnList *scns_last;	/* Last element in the section list.
				   If NULL the data has not yet been
				   read from the file.  */
      Elf_Data_Chunk *rawchunks; /* List of elf_getdata_rawchunk results.  */
      unsigned int scnincr;	/* Number of sections allocate the last
				   time.  */
      off64_t sizestr_offset;	/* Offset of the size string in the parent
				   if this is an archive member.  */
      Elf32_Ehdr ehdr_mem;	/* Memory used for ELF header when not
				   mmaped.  */
      char __e32scnspad[sizeof (Elf64_Ehdr) - sizeof (Elf32_Ehdr)];

      /* The section array.  */
      Elf_ScnList scns;
    } elf32;

    struct
    {
      int ehdr_flags;		/* Flags (dirty) for ELF header.  */
      int phdr_flags;		/* Flags (dirty|malloc) for program header.  */
      int shdr_malloced;	/* Nonzero if shdr array was allocated.  */

      Elf64_Ehdr *ehdr;		/* Pointer to the ELF header.  This is
				   never malloced.  */
      Elf64_Shdr *shdr;		/* Used when reading from a file.  */
      Elf64_Phdr *phdr;		/* Pointer to the program header array.  */
      Elf_ScnList *scns_last;	/* Last element in the section list.
				   If NULL the data has not yet been
				   read from the file.  */
      Elf_Data_Chunk *rawchunks; /* List of elf_getdata_rawchunk results.  */
      unsigned int scnincr;	/* Number of sections allocate the last
				   time.  */
      off64_t sizestr_offset;	/* Offset of the size string in the parent
				   if this is an archive member.  */
      Elf64_Ehdr ehdr_mem;	/* Memory used for ELF header when not
				   mmaped.  */

      /* The section array.  */
      Elf_ScnList scns;
    } elf64;

    struct
    {
      int has_index;		/* Set when file has index.  0 means
				   undecided, > 0 means it has one.  */
      Elf_Arsym *ar_sym;	/* Symbol table returned by elf_getarsym.  */
      size_t ar_sym_num;	/* Number of entries in `ar_sym'.  */
      char *long_names;		/* If no index is available but long names
				   are used this elements points to the data.*/
      size_t long_names_len;	/* Length of the long name table.  */
      off_t offset;		/* Offset in file we are currently at.
				   elf_next() advances this to the next
				   member of the archive.  */
      Elf_Arhdr elf_ar_hdr;	/* Structure returned by 'elf_getarhdr'.  */
      struct ar_hdr ar_hdr;	/* Header read from file.  */
      char ar_name[16];		/* NUL terminated ar_name of elf_ar_hdr.  */
      char raw_name[17];	/* This is a buffer for the NUL terminated
				   named raw_name used in the elf_ar_hdr.  */
      struct Elf *children;	/* List of all descriptors for this archive. */
    } ar;
  } state;

  /* There absolutely never must be anything following the union.  */
};

/* Type of the conversion functions.  These functions will convert the
   byte order.  */
typedef void (*xfct_t) (void *, const void *, size_t, int);

/* The table with the function pointers.  */
extern const xfct_t __elf_xfctstom[EV_NUM - 1][EV_NUM - 1][ELFCLASSNUM - 1][ELF_T_NUM] attribute_hidden;
extern const xfct_t __elf_xfctstof[EV_NUM - 1][EV_NUM - 1][ELFCLASSNUM - 1][ELF_T_NUM] attribute_hidden;

/* Array with sizes of the external types indexed by ELF version, binary
   class, and type. */
extern const size_t __libelf_type_sizes[EV_NUM - 1][ELFCLASSNUM - 1][ELF_T_NUM] attribute_hidden;
/* We often have to access the size for a type in the current version.  */
#if EV_NUM != 2
# define elf_typesize(class,type,n) \
  elfw2(class,fsize) (type, n, __libelf_version)
#else
# define elf_typesize(class,type,n) \
  (__libelf_type_sizes[EV_CURRENT - 1][ELFW(ELFCLASS,class) - 1][type] * n)
#endif

/* Currently selected version of the ELF specification.  */
extern unsigned int __libelf_version attribute_hidden;

/* The byte value used for filling gaps.  */
extern int __libelf_fill_byte attribute_hidden;

/* Nonzero if the version was set.  */
extern int __libelf_version_initialized attribute_hidden;

/* Index for __libelf_type_sizes et al.  */
#if EV_NUM == 2
# define LIBELF_EV_IDX	0
#else
# define LIBELF_EV_IDX	(__libelf_version - 1)
#endif

#if !ALLOW_UNALIGNED
/* Array with alignment requirements of the internal types indexed by ELF
   version, binary class, and type. */
extern const uint_fast8_t __libelf_type_aligns[EV_NUM - 1][ELFCLASSNUM - 1][ELF_T_NUM] attribute_hidden;
# define __libelf_type_align(class, type)	\
    (__libelf_type_aligns[LIBELF_EV_IDX][class - 1][type] ?: 1)
#else
# define __libelf_type_align(class, type)	1
#endif

/* The libelf API does not have such a function but it is still useful.
   Get the memory size for the given type.

   These functions cannot be marked internal since they are aliases
   of the export elfXX_fsize functions.*/
extern size_t __elf32_msize (Elf_Type __type, size_t __count,
			     unsigned int __version);
extern size_t __elf64_msize (Elf_Type __type, size_t __count,
			     unsigned int __version);

/* Create Elf descriptor from memory image.  */
extern Elf *__libelf_read_mmaped_file (int fildes, void *map_address,
				       off_t offset, size_t maxsize,
				       Elf_Cmd cmd, Elf *parent)
     internal_function;

/* Set error value.  */
extern void __libelf_seterrno (int value) internal_function;

/* Get the next archive header.  */
extern int __libelf_next_arhdr_wrlock (Elf *elf) internal_function;

/* Read all of the file associated with the descriptor.  */
extern char *__libelf_readall (Elf *elf) internal_function;

/* Read the complete section table and convert the byte order if necessary.  */
extern int __libelf_readsections (Elf *elf) internal_function;

/* Store the information for the raw data in the `rawdata_list' element.  */
extern int __libelf_set_rawdata (Elf_Scn *scn) internal_function;
extern int __libelf_set_rawdata_wrlock (Elf_Scn *scn) internal_function;

/* Helper functions for elf_update.  */
extern off_t __elf32_updatenull_wrlock (Elf *elf, int *change_bop,
					size_t shnum) internal_function;
extern off_t __elf64_updatenull_wrlock (Elf *elf, int *change_bop,
					size_t shnum) internal_function;

extern int __elf32_updatemmap (Elf *elf, int change_bo, size_t shnum)
     internal_function;
extern int __elf64_updatemmap (Elf *elf, int change_bo, size_t shnum)
     internal_function;
extern int __elf32_updatefile (Elf *elf, int change_bo, size_t shnum)
     internal_function;
extern int __elf64_updatefile (Elf *elf, int change_bo, size_t shnum)
     internal_function;

/* Alias for exported functions to avoid PLT entries, and
   rdlock/wrlock variants of these functions.  */
extern int __elf_end_internal (Elf *__elf) attribute_hidden;
extern Elf *__elf_begin_internal (int __fildes, Elf_Cmd __cmd, Elf *__ref)
     attribute_hidden;
extern Elf32_Ehdr *__elf32_getehdr_wrlock (Elf *__elf) internal_function;
extern Elf64_Ehdr *__elf64_getehdr_wrlock (Elf *__elf) internal_function;
extern Elf32_Ehdr *__elf32_newehdr_internal (Elf *__elf) attribute_hidden;
extern Elf64_Ehdr *__elf64_newehdr_internal (Elf *__elf) attribute_hidden;
extern Elf32_Phdr *__elf32_getphdr_internal (Elf *__elf) attribute_hidden;
extern Elf64_Phdr *__elf64_getphdr_internal (Elf *__elf) attribute_hidden;
extern Elf32_Phdr *__elf32_getphdr_wrlock (Elf *__elf) attribute_hidden;
extern Elf64_Phdr *__elf64_getphdr_wrlock (Elf *__elf) attribute_hidden;
extern Elf32_Phdr *__elf32_newphdr_internal (Elf *__elf, size_t __cnt)
     attribute_hidden;
extern Elf64_Phdr *__elf64_newphdr_internal (Elf *__elf, size_t __cnt)
     attribute_hidden;
extern Elf_Scn *__elf32_offscn_internal (Elf *__elf, Elf32_Off __offset)
  attribute_hidden;
extern Elf_Scn *__elf64_offscn_internal (Elf *__elf, Elf64_Off __offset)
  attribute_hidden;
extern int __elf_getshnum_rdlock (Elf *__elf, size_t *__dst) internal_function;
extern int __elf_getshstrndx_internal (Elf *__elf, size_t *__dst)
     attribute_hidden;
extern Elf32_Shdr *__elf32_getshdr_rdlock (Elf_Scn *__scn) internal_function;
extern Elf64_Shdr *__elf64_getshdr_rdlock (Elf_Scn *__scn) internal_function;
extern Elf32_Shdr *__elf32_getshdr_wrlock (Elf_Scn *__scn) internal_function;
extern Elf64_Shdr *__elf64_getshdr_wrlock (Elf_Scn *__scn) internal_function;
extern Elf_Scn *__elf_getscn_internal (Elf *__elf, size_t __index)
     attribute_hidden;
extern Elf_Scn *__elf_nextscn_internal (Elf *__elf, Elf_Scn *__scn)
     attribute_hidden;
extern int __elf_scnshndx_internal (Elf_Scn *__scn) attribute_hidden;
extern Elf_Data *__elf_getdata_internal (Elf_Scn *__scn, Elf_Data *__data)
     attribute_hidden;
extern Elf_Data *__elf_getdata_rdlock (Elf_Scn *__scn, Elf_Data *__data)
     internal_function;
extern Elf_Data *__elf_rawdata_internal (Elf_Scn *__scn, Elf_Data *__data)
     attribute_hidden;
extern char *__elf_strptr_internal (Elf *__elf, size_t __index,
				    size_t __offset) attribute_hidden;
extern Elf_Data *__elf32_xlatetom_internal (Elf_Data *__dest,
					    const Elf_Data *__src,
					    unsigned int __encode)
     attribute_hidden;
extern Elf_Data *__elf64_xlatetom_internal (Elf_Data *__dest,
					    const Elf_Data *__src,
					    unsigned int __encode)
     attribute_hidden;
extern Elf_Data *__elf32_xlatetof_internal (Elf_Data *__dest,
					    const Elf_Data *__src,
					    unsigned int __encode)
     attribute_hidden;
extern Elf_Data *__elf64_xlatetof_internal (Elf_Data *__dest,
					    const Elf_Data *__src,
					    unsigned int __encode)
     attribute_hidden;
extern unsigned int __elf_version_internal (unsigned int __version)
     attribute_hidden;
extern unsigned long int __elf_hash_internal (const char *__string)
       __attribute__ ((__pure__, visibility ("hidden")));
extern long int __elf32_checksum_internal (Elf *__elf) attribute_hidden;
extern long int __elf64_checksum_internal (Elf *__elf) attribute_hidden;

extern GElf_Ehdr *__gelf_getehdr_rdlock (Elf *__elf, GElf_Ehdr *__dest)
     internal_function;
extern size_t __gelf_fsize_internal (Elf *__elf, Elf_Type __type,
				     size_t __count, unsigned int __version)
     attribute_hidden;
extern GElf_Shdr *__gelf_getshdr_internal (Elf_Scn *__scn, GElf_Shdr *__dst)
     attribute_hidden;
extern GElf_Sym *__gelf_getsym_internal (Elf_Data *__data, int __ndx,
					 GElf_Sym *__dst) attribute_hidden;

extern uint32_t __libelf_crc32 (uint32_t crc, unsigned char *buf, size_t len)
     attribute_hidden;

/* We often have to update a flag iff a value changed.  Make this
   convenient.  */
#define update_if_changed(var, exp, flag) \
  do {									      \
    __typeof__ (var) *_var = &(var);					      \
    __typeof__ (exp) _exp = (exp);					      \
    if (*_var != _exp)							      \
      {									      \
	*_var = _exp;							      \
	(flag) |= ELF_F_DIRTY;						      \
      }									      \
  } while (0)

/* Align offset to 4 bytes as needed for note name and descriptor data.  */
#define NOTE_ALIGN(n)	(((n) + 3) & -4U)

#endif  /* libelfP.h */


text:
package im.actor.server.commons.serialization

import akka.serialization._
import com.google.protobuf.{ GeneratedMessage ⇒ GGeneratedMessage, ByteString }
import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap.{ Builder ⇒ MapBuilder }
import com.trueaccord.scalapb.GeneratedMessage

import scala.util.{ Failure, Success }

object ActorSerializer {
  private val ARRAY_OF_BYTE_ARRAY = Array[Class[_]](classOf[Array[Byte]])

  // FIXME: dynamically increase capacity
  private val map = new MapBuilder[Int, Class[_]].maximumWeightedCapacity(1024).build()
  private val reverseMap = new MapBuilder[Class[_], Int].maximumWeightedCapacity(1024).build()

  def clean(): Unit = {
    map.clear()
    reverseMap.clear()
  }

  def register(id: Int, clazz: Class[_]): Unit = {
    if (map.containsKey(id)) {
      if (Option(reverseMap.get(clazz)) != Some(id))
        throw new IllegalArgumentException(s"There is already a mapping with id ${id}: ${map.get(id)}")
    } else {
      map.put(id, Class.forName(clazz.getName + '$'))
      reverseMap.put(clazz, id)
    }
  }

  def get(id: Int): Option[Class[_]] = Option(map.get(id))

  def get(clazz: Class[_]) = Option(reverseMap.get(clazz))

  def fromBinary(bytes: Array[Byte]): AnyRef = {
    val SerializedMessage(id, bodyBytes) = SerializedMessage.parseFrom(bytes)

    ActorSerializer.get(id) match {
      case Some(clazz) ⇒
        val field = clazz.getField("MODULE$").get(null)

        clazz
          .getDeclaredMethod("validate", ARRAY_OF_BYTE_ARRAY: _*)
          .invoke(field, bodyBytes.toByteArray) match {
            case Success(msg) ⇒ msg.asInstanceOf[GeneratedMessage]
            case Failure(e)   ⇒ throw e
          }
      case None ⇒ throw new IllegalArgumentException(s"Can't find mapping for id ${id}")
    }
  }

  def toBinary(o: AnyRef): Array[Byte] = {
    ActorSerializer.get(o.getClass) match {
      case Some(id) ⇒
        o match {
          case m: GeneratedMessage  ⇒ SerializedMessage(id, ByteString.copyFrom(m.toByteArray)).toByteArray
          case m: GGeneratedMessage ⇒ SerializedMessage(id, ByteString.copyFrom(m.toByteArray)).toByteArray
          case _                    ⇒ throw new IllegalArgumentException(s"Can't serialize non-scalapb message [${o}]")
        }
      case None ⇒
        throw new IllegalArgumentException(s"Can't find mapping for message [${o}]")
    }
  }
}

class ActorSerializer extends Serializer {

  override def identifier: Int = 3456

  override def includeManifest: Boolean = false

  override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = ActorSerializer.fromBinary(bytes)

  override def toBinary(o: AnyRef): Array[Byte] = ActorSerializer.toBinary(o)
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import classes.entidades.Filial;
import DAO.FilialDAO;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.Funcoes;
import util.Resposta;

/**
 *
 * @author Nicolas
 */
@WebServlet(name = "CadastroFilial", urlPatterns = {"/CadastroFilial"})
public class CadastroFilial extends BaseServlet {

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Filial filial = new Filial();
        Integer id = identificarEdicao(request);
        boolean edicao = false;

        try {

            if (id != null) {
                filial = FilialDAO.consultarPorId(id);
                edicao = true;
            } else {
                id = FilialDAO.maxId();
                filial.setCodigoFilial(id);
            }

        } catch (SQLException | ClassNotFoundException ex) {
            logar(CadastroFilial.class.getName(), ex);
        }

        request.setAttribute("filial", filial);
        request.setAttribute("edicao", edicao);

        processRequest(request, response, "/WEB-INF/jsp/cadastroFilial.jspx");
    }

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Resposta resposta = new Resposta();

        boolean edicao = Boolean.parseBoolean(request.getParameter("edicao"));
        int id = Integer.parseInt(request.getParameter("filialId"));
        String nome = request.getParameter("NomeFilial");
        String nomeFantasia = request.getParameter("NomeFantasia");
        String cnpj = request.getParameter("cnpj");
        String rua = request.getParameter("Rua");
        int num = Integer.parseInt(request.getParameter("Numero"));
        String bairro = request.getParameter("Bairro");
        String estado = request.getParameter("Estado");
        String cidade = request.getParameter("Cidade");

        Filial filial = new Filial(id, nome, nomeFantasia, rua, num, bairro, estado, cidade, cnpj);
        try {

            resposta = validar(filial, id);

            if (resposta.getSucesso()) {
                if (edicao) {
                    FilialDAO.alterar(filial);
                } else {
                    FilialDAO.adicionar(filial);
                }

            }

            request.setAttribute("filial", filial);
            request.getSession().setAttribute("resposta", resposta);

        } catch (SQLException | ClassNotFoundException ex) {
            logar(CadastroFilial.class.getName(), ex);
        }

        if (resposta.getSucesso()) {
            response.sendRedirect(request.getContextPath() + "/BuscaFiliais");
        } else {
            processRequest(request, response, "/WEB-INF/jsp/cadastroFilial.jspx");
        }
    }

    public Resposta validar(Filial filial, int id) throws SQLException, ClassNotFoundException {
        Resposta resposta = new Resposta();

        if (!Funcoes.isCNPJ(filial.getCnpj())) {
            resposta.setErro("Este CNPJ é inválido.", "cnpj");
        }
        if (FilialDAO.cnpjJaCadastrado(filial.getCnpj(), id)) {
            resposta.setErro("Esse CNPJ já está cadastrado", "cnpj");
        }

        return resposta;
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


text:
/**
 * Splits a string into arguments using some separator. If no separator is
 * given, whitespace will be used. Most importantly, quotes in the original
 * string will allow you to group delimited tokens. Single and double quotes
 * can be nested one level.
 *
 * As a convenience, this function has been added to the String prototype,
 * letting you treat it like a function of the string object.
 *
 * Example:

on('chat:message', function(msg) {
    var command, params;

    params = msg.content.splitArgs();
    command = params.shift().substring(1);

    // msg.content: !command with parameters, "including 'with quotes'"
    // command: command
    // params: ["with", "parameters,", "including 'with quotes'"]
});
 */
var bshields = bshields || {};
bshields.splitArgs = (function() {
    'use strict';

    var version = 1.0;

    function splitArgs(input, separator) {
        var singleQuoteOpen = false,
            doubleQuoteOpen = false,
            tokenBuffer = [],
            ret = [],
            arr = input.split(''),
            element, i, matches;
        separator = separator || /\s/g;

        for (i = 0; i < arr.length; i++) {
            element = arr[i];
            matches = element.match(separator);
            if (element === '\'') {
                if (!doubleQuoteOpen) {
                    singleQuoteOpen = !singleQuoteOpen;
                    continue;
                }
            } else if (element === '"') {
                if (!singleQuoteOpen) {
                    doubleQuoteOpen = !doubleQuoteOpen;
                    continue;
                }
            }

            if (!singleQuoteOpen && !doubleQuoteOpen) {
                if (matches) {
                    if (tokenBuffer && tokenBuffer.length > 0) {
                        ret.push(tokenBuffer.join(''));
                        tokenBuffer = [];
                    }
                } else {
                    tokenBuffer.push(element);
                }
            } else if (singleQuoteOpen || doubleQuoteOpen) {
                tokenBuffer.push(element);
            }
        }
        if (tokenBuffer && tokenBuffer.length > 0) {
            ret.push(tokenBuffer.join(''));
        }

        return ret;
    }

    return splitArgs;
}());

String.prototype.splitArgs = String.prototype.splitArgs || function(separator) {
    return bshields.splitArgs(this, separator);
};


text:
package org.ferris.tweial.console.main;

public class StartupEvent {

    public StartupEvent() {
    }

}


text:
package hash

import "crypto"

// Repo hash functions manager
type Repo interface {
	Sum(s string) string
	SumBytes(b []byte) string
	SumTimes(s string, times uint) string
	SumBytesTimes(b []byte, times uint) string
}

// NewHashRepo get hash repo by crypto type
func NewHashRepo(h crypto.Hash) Repo {
	if h == crypto.MD5 {
		return NewMD5()
	} else if h == crypto.SHA1 {
		return NewSHA1()
	} else if h == crypto.SHA224 {
		return NewSHA224()
	} else if h == crypto.SHA256 {
		return NewSHA256()
	} else if h == crypto.SHA384 {
		return NewSHA384()
	} else if h == crypto.SHA512 {
		return NewSHA512()
	} else if h == crypto.SHA512_224 {
		return NewSHA512_224()
	} else if h == crypto.SHA512_256 {
		return NewSHA512_256()
	}

	return nil
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/datacatalog/v1/schema.proto

package com.google.cloud.datacatalog.v1;

public interface SchemaOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.datacatalog.v1.Schema)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The unified GoogleSQL-like schema of columns.
   * The overall maximum number of columns and nested columns is 10,000.
   * The maximum nested depth is 15 levels.
   *

   *
   * repeated .google.cloud.datacatalog.v1.ColumnSchema columns = 2;
   */
  java.util.List<com.google.cloud.datacatalog.v1.ColumnSchema> getColumnsList();
  /**
   *
   *
   *

   * The unified GoogleSQL-like schema of columns.
   * The overall maximum number of columns and nested columns is 10,000.
   * The maximum nested depth is 15 levels.
   *

   *
   * repeated .google.cloud.datacatalog.v1.ColumnSchema columns = 2;
   */
  com.google.cloud.datacatalog.v1.ColumnSchema getColumns(int index);
  /**
   *
   *
   *

   * The unified GoogleSQL-like schema of columns.
   * The overall maximum number of columns and nested columns is 10,000.
   * The maximum nested depth is 15 levels.
   *

   *
   * repeated .google.cloud.datacatalog.v1.ColumnSchema columns = 2;
   */
  int getColumnsCount();
  /**
   *
   *
   *

   * The unified GoogleSQL-like schema of columns.
   * The overall maximum number of columns and nested columns is 10,000.
   * The maximum nested depth is 15 levels.
   *

   *
   * repeated .google.cloud.datacatalog.v1.ColumnSchema columns = 2;
   */
  java.util.List<? extends com.google.cloud.datacatalog.v1.ColumnSchemaOrBuilder>
      getColumnsOrBuilderList();
  /**
   *
   *
   *

   * The unified GoogleSQL-like schema of columns.
   * The overall maximum number of columns and nested columns is 10,000.
   * The maximum nested depth is 15 levels.
   *

   *
   * repeated .google.cloud.datacatalog.v1.ColumnSchema columns = 2;
   */
  com.google.cloud.datacatalog.v1.ColumnSchemaOrBuilder getColumnsOrBuilder(int index);
}