text:
import re
def checkio(sentense):
    word = re.split("\s+", sentense)
    result = ''
    for w in word:
        result += w + " "
    return result.strip()

if __name__ == '__main__':
    assert checkio('I  like   python') == "I like python", 'Test1'
    assert checkio('No double  whitespaces') == "No double whitespaces", "Test2"
    assert checkio('Normal text with whitespaces') == 'Normal text with whitespaces', 'Test3'
    assert checkio('Triple   spaces,   It   is   not   good.') == 'Triple spaces, It is not good.', 'Test4'
    assert checkio("One, Two,  Three,   Four,    Five,      Six.") == 'One, Two, Three, Four, Five, Six.', "Test5"

    assert checkio('a  b  c   d    e') == 'a b c d e', 'Random1'
    assert checkio('b   b   b') == 'b b b', 'Random2'
    assert checkio('a b  c   d    e') == 'a b c d e', 'Random3'


text:
"""Preprocess a QA file into TFRecords for training dualencoder models."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import gzip
import json
import random

from absl import app
from absl import flags
from bert import tokenization

import six
import tensorflow.compat.v1 as tf
from tqdm import tqdm

FLAGS = flags.FLAGS

flags.DEFINE_string("vocab_file", None,
                    "The vocabulary file that the BERT model was trained on.")

flags.DEFINE_string("input_file", None,
                    "The input JSONL file (gzipped) to read questions from.")

flags.DEFINE_string("output_file", None,
                    "The output TFRecord file to store examples to.")

flags.DEFINE_string("feature_file", None,
                    "The output TFRecord file to store examples to.")

flags.DEFINE_bool(
    "do_lower_case", True,
    "Whether to lower case the input text. Should be True for uncased "
    "models and False for cased models.")

flags.DEFINE_integer(
    "max_seq_length", 192,
    "The maximum total input sequence length after WordPiece tokenization. "
    "Sequences longer than this will be truncated, and sequences shorter "
    "than this will be padded.")

flags.DEFINE_integer(
    "doc_stride", 64,
    "When splitting up a long document into chunks, how much stride to "
    "take between chunks.")

flags.DEFINE_integer(
    "max_query_length", 48,
    "The maximum number of tokens for the question. Questions longer than "
    "this will be truncated to this length.")

flags.DEFINE_bool(
    "version_2_with_negative", True,
    "If true, the input contain some that do not have an answer.")

class Example(object):
  """A single training/test example for simple sequence classification.

     For examples without an answer, the start and end position are -1.
  """

  def __init__(self,
               qas_id,
               question_text,
               doc_tokens,
               orig_answer_text=None,
               start_position=None,
               end_position=None,
               is_impossible=False):
    self.qas_id = qas_id
    self.question_text = question_text
    self.doc_tokens = doc_tokens
    self.orig_answer_text = orig_answer_text
    self.start_position = start_position
    self.end_position = end_position
    self.is_impossible = is_impossible

  def __str__(self):
    return self.__repr__()

  def __repr__(self):
    s = ""
    s += "qas_id: %s" % (tokenization.printable_text(self.qas_id))
    s += ", question_text: %s" % (
        tokenization.printable_text(self.question_text))
    s += ", doc_tokens: [%s]" % (" ".join(self.doc_tokens))
    if self.start_position:
      s += ", start_position: %d" % (self.start_position)
    if self.start_position:
      s += ", end_position: %d" % (self.end_position)
    if self.start_position:
      s += ", is_impossible: %r" % (self.is_impossible)
    return s

def read_examples(input_file):
  """Read a SQuAD-like json file into a list of Examples."""

  def is_whitespace(c):
    if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
      return True
    return False

  reader = tf.gfile.Open(input_file, "rb")
  if input_file.endswith(".gz"):
    reader = gzip.GzipFile(fileobj=reader)
  next(reader)
  examples = []
  for line in tqdm(reader):
    item = json.loads(line.strip())
    paragraph_text = item["context"]
    doc_tokens = []
    char_to_word_offset = []
    prev_is_whitespace = True
    for c in paragraph_text:
      if is_whitespace(c):
        prev_is_whitespace = True
      else:
        if prev_is_whitespace:
          doc_tokens.append(c)
        else:
          doc_tokens[-1] += c
        prev_is_whitespace = False
      char_to_word_offset.append(len(doc_tokens) - 1)

    for qa in item["qas"]:
      qas_id = qa["qid"]
      question_text = qa["question"]

      start_position = None
      end_position = None
      orig_answer_text = None
      is_impossible = False

      start_position = -1
      end_position = -1
      orig_answer_text = ""
      if FLAGS.version_2_with_negative:
        is_impossible = qa["is_impossible"]
      if not is_impossible:
        answer_offset = qa["detected_answers"][0]["char_spans"][0][0]
        answer_end = qa["detected_answers"][0]["char_spans"][0][1]
        answer_length = answer_end - answer_offset + 1
        orig_answer_text = item["context"][answer_offset:answer_end + 1]
        start_position = char_to_word_offset[answer_offset]
        end_position = char_to_word_offset[answer_offset + answer_length - 1]
        # Only add answers where the text can be exactly recovered from the
        # document. If this CAN'T happen it's likely due to weird Unicode
        # stuff so we will just skip the example.
        #
        # Note that this means for training mode, every example is NOT
        # guaranteed to be preserved.
        actual_text = " ".join(doc_tokens[start_position:(end_position + 1)])
        cleaned_answer_text = " ".join(
            tokenization.whitespace_tokenize(orig_answer_text))
        if actual_text.find(cleaned_answer_text) == -1:
          tf.logging.warning("Example %d", len(examples))
          tf.logging.warning(json.dumps(item, indent=2))
          tf.logging.warning("Could not find answer: '%s' vs. '%s'",
                             actual_text, cleaned_answer_text)
          continue

      example = Example(
          qas_id=qas_id,
          question_text=question_text,
          doc_tokens=doc_tokens,
          orig_answer_text=orig_answer_text,
          start_position=start_position,
          end_position=end_position,
          is_impossible=is_impossible)
      examples.append(example)
  reader.close()

  return examples

class FeatureWriter(object):
  """Writes InputFeature to TF example file."""

  def __init__(self, filename):
    self.filename = filename
    self.num_features = 0
    self._writer = tf.python_io.TFRecordWriter(filename)

  def process_feature(self, feature):
    """Write a InputFeature to the TFRecordWriter as a tf.train.Example."""
    self.num_features += 1

    def create_int_feature(values):
      feature = tf.train.Feature(
          int64_list=tf.train.Int64List(value=list(values)))
      return feature

    def create_bytes_feature(value):
      return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

    features = collections.OrderedDict()
    features["unique_ids"] = create_int_feature([feature.unique_id])
    features["qas_id"] = create_bytes_feature(feature.qas_id)
    features["doc_input_ids"] = create_int_feature(feature.doc_input_ids)
    features["doc_input_mask"] = create_int_feature(feature.doc_input_mask)
    features["doc_segment_ids"] = create_int_feature(feature.doc_segment_ids)
    features["qry_input_ids"] = create_int_feature(feature.qry_input_ids)
    features["qry_input_mask"] = create_int_feature(feature.qry_input_mask)
    features["qry_segment_ids"] = create_int_feature(feature.qry_segment_ids)

    features["start_positions"] = create_int_feature([feature.start_position])
    features["end_positions"] = create_int_feature([feature.end_position])
    impossible = 0
    if feature.is_impossible:
      impossible = 1
    features["is_impossible"] = create_int_feature([impossible])

    tf_example = tf.train.Example(features=tf.train.Features(feature=features))
    self._writer.write(tf_example.SerializeToString())

  def close(self):
    self._writer.close()

def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,
                         orig_answer_text):
  """Returns tokenized answer spans that better match the annotated answer."""

  # The SQuAD annotations are character based. We first project them to
  # whitespace-tokenized words. But then after WordPiece tokenization, we can
  # often find a "better match". For example:
  #
  #   Question: What year was John Smith born?
  #   Context: The leader was John Smith (1895-1943).
  #   Answer: 1895
  #
  # The original whitespace-tokenized answer will be "(1895-1943).". However
  # after tokenization, our tokens will be "( 1895 - 1943 ) .". So we can match
  # the exact answer, 1895.
  #
  # However, this is not always possible. Consider the following:
  #
  #   Question: What country is the top exporter of electornics?
  #   Context: The Japanese electronics industry is the lagest in the world.
  #   Answer: Japan
  #
  # In this case, the annotator chose "Japan" as a character sub-span of
  # the word "Japanese". Since our WordPiece tokenizer does not split
  # "Japanese", we just use "Japanese" as the annotation. This is fairly rare
  # in SQuAD, but does happen.
  tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))

  for new_start in range(input_start, input_end + 1):
    for new_end in range(input_end, new_start - 1, -1):
      text_span = " ".join(doc_tokens[new_start:(new_end + 1)])
      if text_span == tok_answer_text:
        return (new_start, new_end)

  return (input_start, input_end)

def _check_is_max_context(doc_spans, cur_span_index, position):
  """Check if this is the 'max context' doc span for the token."""

  # Because of the sliding window approach taken to scoring documents, a single
  # token can appear in multiple documents. E.g.
  #  Doc: the man went to the store and bought a gallon of milk
  #  Span A: the man went to the
  #  Span B: to the store and bought
  #  Span C: and bought a gallon of
  #  ...
  #
  # Now the word 'bought' will have two scores from spans B and C. We only
  # want to consider the score with "maximum context", which we define as
  # the *minimum* of its left and right context (the *sum* of left and
  # right context will always be the same, of course).
  #
  # In the example the maximum context for 'bought' would be span C since
  # it has 1 left context and 3 right context, while span B has 4 left context
  # and 0 right context.
  best_score = None
  best_span_index = None
  for (span_index, doc_span) in enumerate(doc_spans):
    end = doc_span.start + doc_span.length - 1
    if position < doc_span.start:
      continue
    if position > end:
      continue
    num_left_context = position - doc_span.start
    num_right_context = end - position
    score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
    if best_score is None or score > best_score:
      best_score = score
      best_span_index = span_index

  return cur_span_index == best_span_index

class InputFeatures(object):
  """A single set of features of data."""

  def __init__(self,
               unique_id,
               qas_id,
               example_index,
               doc_span_index,
               doc_tokens,
               doc_token_to_orig_map,
               doc_token_is_max_context,
               doc_input_ids,
               doc_input_mask,
               doc_segment_ids,
               qry_tokens,
               qry_input_ids,
               qry_input_mask,
               qry_segment_ids,
               start_position=None,
               end_position=None,
               is_impossible=None):
    self.unique_id = unique_id
    self.qas_id = qas_id
    self.example_index = example_index
    self.doc_span_index = doc_span_index
    self.doc_tokens = doc_tokens
    self.doc_token_to_orig_map = doc_token_to_orig_map
    self.doc_token_is_max_context = doc_token_is_max_context
    self.doc_input_ids = doc_input_ids
    self.doc_input_mask = doc_input_mask
    self.doc_segment_ids = doc_segment_ids
    self.qry_tokens = qry_tokens
    self.qry_input_ids = qry_input_ids
    self.qry_input_mask = qry_input_mask
    self.qry_segment_ids = qry_segment_ids
    self.start_position = start_position
    self.end_position = end_position
    self.is_impossible = is_impossible

def convert_examples_to_features(examples, tokenizer, max_doc_length,
                                 doc_stride, max_query_length, output_fn):
  """Loads a data file into a list of `InputBatch`s."""

  unique_id = 1000000000

  for (example_index, example) in tqdm(enumerate(examples)):
    query_tokens = tokenizer.tokenize(example.question_text)

    if len(query_tokens) > max_query_length - 2:
      query_tokens = query_tokens[0:max_query_length - 2]  # -2 for [CLS], [SEP]

    tok_to_orig_index = []
    orig_to_tok_index = []
    all_doc_tokens = []
    for (i, token) in enumerate(example.doc_tokens):
      orig_to_tok_index.append(len(all_doc_tokens))
      sub_tokens = tokenizer.tokenize(token)
      for sub_token in sub_tokens:
        tok_to_orig_index.append(i)
        all_doc_tokens.append(sub_token)

    tok_start_position = None
    tok_end_position = None
    if example.is_impossible:
      tok_start_position = -1
      tok_end_position = -1
    if not example.is_impossible:
      tok_start_position = orig_to_tok_index[example.start_position]
      if example.end_position < len(example.doc_tokens) - 1:
        tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
      else:
        tok_end_position = len(all_doc_tokens) - 1
      (tok_start_position, tok_end_position) = _improve_answer_span(
          all_doc_tokens, tok_start_position, tok_end_position, tokenizer,
          example.orig_answer_text)

    # The -2 accounts for [CLS] and [SEP]
    max_tokens_for_doc = max_doc_length - 2

    # We can have documents that are longer than the maximum sequence length.
    # To deal with this we do a sliding window approach, where we take chunks
    # of the up to our max length with a stride of `doc_stride`.
    _DocSpan = collections.namedtuple(  # pylint: disable=invalid-name
        "DocSpan", ["start", "length"])
    doc_spans = []
    start_offset = 0
    while start_offset < len(all_doc_tokens):
      length = len(all_doc_tokens) - start_offset
      if length > max_tokens_for_doc:
        length = max_tokens_for_doc
      doc_spans.append(_DocSpan(start=start_offset, length=length))
      if start_offset + length == len(all_doc_tokens):
        break
      start_offset += min(length, doc_stride)

    for (doc_span_index, doc_span) in enumerate(doc_spans):
      doc_tokens, qry_tokens = [], []
      doc_token_to_orig_map = {}
      doc_token_is_max_context = {}
      doc_segment_ids, qry_segment_ids = [], []

      # Question
      qry_tokens.append("[CLS]")
      qry_segment_ids.append(0)
      for token in query_tokens:
        qry_tokens.append(token)
        qry_segment_ids.append(0)
      qry_tokens.append("[SEP]")
      qry_segment_ids.append(0)

      # Document
      doc_tokens.append("[CLS]")
      doc_segment_ids.append(1)
      for i in range(doc_span.length):
        split_token_index = doc_span.start + i
        doc_token_to_orig_map[len(
            doc_tokens)] = tok_to_orig_index[split_token_index]

        is_max_context = _check_is_max_context(doc_spans, doc_span_index,
                                               split_token_index)
        doc_token_is_max_context[len(doc_tokens)] = is_max_context
        doc_tokens.append(all_doc_tokens[split_token_index])
        doc_segment_ids.append(1)
      doc_tokens.append("[SEP]")
      doc_segment_ids.append(1)

      doc_input_ids = tokenizer.convert_tokens_to_ids(doc_tokens)
      qry_input_ids = tokenizer.convert_tokens_to_ids(qry_tokens)

      # The mask has 1 for real tokens and 0 for padding tokens. Only real
      # tokens are attended to.
      doc_input_mask = [1] * len(doc_input_ids)
      qry_input_mask = [1] * len(qry_input_ids)

      # Zero-pad up to the sequence length.
      while len(doc_input_ids) < max_doc_length:
        doc_input_ids.append(0)
        doc_input_mask.append(0)
        doc_segment_ids.append(0)
      while len(qry_input_ids) < max_query_length:
        qry_input_ids.append(0)
        qry_input_mask.append(0)
        qry_segment_ids.append(0)

      assert len(doc_input_ids) == max_doc_length
      assert len(doc_input_mask) == max_doc_length
      assert len(doc_segment_ids) == max_doc_length
      assert len(qry_input_ids) == max_query_length
      assert len(qry_input_mask) == max_query_length
      assert len(qry_segment_ids) == max_query_length

      start_position = None
      end_position = None
      doc_start = doc_span.start
      doc_end = doc_span.start + doc_span.length - 1
      doc_offset = 1
      if not example.is_impossible:
        # For training, if our document chunk does not contain an annotation
        # we throw it out, since there is nothing to predict.
        out_of_span = False
        if not (tok_start_position >= doc_start and
                tok_end_position <= doc_end):
          out_of_span = True
        if out_of_span:
          start_position = 0
          end_position = 0
        else:
          start_position = tok_start_position - doc_start + doc_offset
          end_position = tok_end_position - doc_start + doc_offset
      if example.is_impossible:
        start_position = 0
        end_position = 0

      if example_index < 20:
        tf.logging.info("*** Example ***")
        tf.logging.info("unique_id: %s", unique_id)
        tf.logging.info("example_index: %s", example_index)
        tf.logging.info("doc_span_index: %s", doc_span_index)
        tf.logging.info(
            "doc_tokens: %s",
            " ".join([tokenization.printable_text(x) for x in doc_tokens]))
        tf.logging.info(
            "qry_tokens: %s",
            " ".join([tokenization.printable_text(x) for x in qry_tokens]))
        tf.logging.info(
            "doc_token_to_orig_map: %s", " ".join([
                "%d:%d" % (x, y)
                for (x, y) in six.iteritems(doc_token_to_orig_map)
            ]))
        tf.logging.info(
            "doc_token_is_max_context: %s", " ".join([
                "%d:%s" % (x, y)
                for (x, y) in six.iteritems(doc_token_is_max_context)
            ]))
        tf.logging.info("doc_input_ids: %s",
                        " ".join([str(x) for x in doc_input_ids]))
        tf.logging.info("doc_input_mask: %s",
                        " ".join([str(x) for x in doc_input_mask]))
        tf.logging.info("doc_segment_ids: %s",
                        " ".join([str(x) for x in doc_segment_ids]))
        tf.logging.info("qry_input_ids: %s",
                        " ".join([str(x) for x in qry_input_ids]))
        tf.logging.info("qry_input_mask: %s",
                        " ".join([str(x) for x in qry_input_mask]))
        tf.logging.info("qry_segment_ids: %s",
                        " ".join([str(x) for x in qry_segment_ids]))
        if example.is_impossible:
          tf.logging.info("impossible example")
        if not example.is_impossible:
          answer_text = " ".join(doc_tokens[start_position:(end_position + 1)])
          tf.logging.info("start_position: %d", start_position)
          tf.logging.info("end_position: %d", end_position)
          tf.logging.info("answer: %s",
                          tokenization.printable_text(answer_text))

      feature = InputFeatures(
          unique_id=unique_id,
          qas_id=example.qas_id.encode("utf-8"),
          example_index=example_index,
          doc_span_index=doc_span_index,
          doc_tokens=doc_tokens,
          doc_token_to_orig_map=doc_token_to_orig_map,
          doc_token_is_max_context=doc_token_is_max_context,
          doc_input_ids=doc_input_ids,
          doc_input_mask=doc_input_mask,
          doc_segment_ids=doc_segment_ids,
          qry_tokens=qry_tokens,
          qry_input_ids=qry_input_ids,
          qry_input_mask=qry_input_mask,
          qry_segment_ids=qry_segment_ids,
          start_position=start_position,
          end_position=end_position,
          is_impossible=example.is_impossible)

      # Run callback
      output_fn(feature)

      unique_id += 1

def main(_):
  tokenizer = tokenization.FullTokenizer(
      vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)

  examples = read_examples(input_file=FLAGS.input_file)

  # Pre-shuffle the input to avoid having to make a very large shuffle
  # buffer in in the `input_fn`.
  rng = random.Random(12345)
  rng.shuffle(examples)

  # We write to a temporary file to avoid storing very large
  # constant tensors in memory.
  writer = FeatureWriter(filename=FLAGS.output_file)
  features = []

  def append_feature(feature):
    features.append(feature)
    writer.process_feature(feature)

  convert_examples_to_features(
      examples=examples,
      tokenizer=tokenizer,
      max_doc_length=FLAGS.max_seq_length,
      doc_stride=FLAGS.doc_stride,
      max_query_length=FLAGS.max_query_length,
      output_fn=append_feature)
  writer.close()
  tf.logging.info("%d original examples read.", len(examples))
  tf.logging.info("%d split records written.", writer.num_features)

  if FLAGS.feature_file is not None:
    json.dump([[vars(ee) for ee in examples], [vars(ff) for ff in features]],
              tf.gfile.Open(FLAGS.feature_file, "w"))

if __name__ == "__main__":
  app.run(main)

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace AppCenterEditor
{
    public class AppCenterEditorHttp : Editor
    {
        internal static void MakeDownloadCall(string url, Action<string> resultCallback)
        {
            EdExLogger.LoggerInstance.LogWithTimeStamp("Downloading file: " + url);
            var www = new WWW(url);
            AppCenterEditor.RaiseStateUpdate(AppCenterEditor.EdExStates.OnHttpReq, url, AppCenterEditorHelper.MSG_SPIN_BLOCK);
            EditorCoroutine.Start(PostDownload(www, response =>
            {
                resultCallback(WriteResultFile(url, response));
            }, AppCenterEditorHelper.SharedErrorCallback), www);
        }

        internal static void MakeDownloadCall(IEnumerable<string> urls, Action<IEnumerable<string>> resultCallback)
        {
            EdExLogger.LoggerInstance.LogWithTimeStamp("Downloading files: " + string.Join(", ", urls.ToArray()));
            var wwws = new List<WWW>();
            var downloadRequests = new List<DownloadRequest>();
            foreach (var url in urls)
            {
                var www = new WWW(url);
                wwws.Add(www);
                downloadRequests.Add(new DownloadRequest(url, www));
            }
            AppCenterEditor.RaiseStateUpdate(AppCenterEditor.EdExStates.OnHttpReq, "Downloading files", AppCenterEditorHelper.MSG_SPIN_BLOCK);
            EditorCoroutine.Start(DownloadFiles(downloadRequests, resultCallback, AppCenterEditorHelper.SharedErrorCallback), wwws);
        }

        internal static void MakeGitHubApiCall(string url, Action<string> resultCallback)
        {
            var www = new WWW(url);
            EditorCoroutine.Start(Post(www, response => { OnGitHubSuccess(resultCallback, response); }, AppCenterEditorHelper.SharedErrorCallback), www);
        }

        private static IEnumerator Post(WWW www, Action<string> callBack, Action<string> errorCallback)
        {
            yield return www;
            if (!string.IsNullOrEmpty(www.error))
            {
                errorCallback(www.error);
            }
            else
            {
                callBack(www.text);
            }
        }

        private static IEnumerator PostDownload(WWW www, Action<byte[]> callBack, Action<string> errorCallback)
        {
            yield return www;
            if (!string.IsNullOrEmpty(www.error))
            {
                errorCallback(www.error);
            }
            else
            {
                callBack(www.bytes);
            }
        }

        private static IEnumerator DownloadFiles(IEnumerable<DownloadRequest> downloadRequests, Action<IEnumerable<string>> resultCallback, Action<string> errorCallback)
        {
            var downloadedFiles = new List<string>();
            foreach (var downloadRequest in downloadRequests)
            {
                yield return downloadRequest.WWW;
                if (string.IsNullOrEmpty(downloadRequest.WWW.error))
                {
                    var downloadedFile = WriteResultFile(downloadRequest.Url, downloadRequest.WWW.bytes);
                    downloadedFiles.Add(downloadedFile);
                }
                else
                {
                    errorCallback(downloadRequest.WWW.error);
                    yield break;
                }
            }
            resultCallback(downloadedFiles);
        }

        private static void OnGitHubSuccess(Action<string> resultCallback, string response)
        {
            if (resultCallback == null)
            {
                return;
            }
            var jsonResponse = JsonWrapper.DeserializeObject<List<object>>(response);
            if (jsonResponse == null || jsonResponse.Count == 0)
            {
                return;
            }
            // list seems to come back in ascending order (oldest -> newest)
            var latestSdkTag = (JsonObject)jsonResponse[jsonResponse.Count - 1];
            object tag;
            if (latestSdkTag.TryGetValue("ref", out tag))
            {
                var startIndex = tag.ToString().LastIndexOf('/') + 1;
                var length = tag.ToString().Length - startIndex;
                resultCallback(tag.ToString().Substring(startIndex, length));
            }
            else
            {
                resultCallback(null);
            }
        }

        private static string WriteResultFile(string url, byte[] response)
        {
            AppCenterEditor.RaiseStateUpdate(AppCenterEditor.EdExStates.OnHttpRes, url);
            string fileName;
            if (url.IndexOf("AppCenterEditorExtensions-v") > -1)
            {
                fileName = AppCenterEditorHelper.EDEX_UPGRADE_PATH;
            }
            else if (url.IndexOf("AppCenterAnalytics-v") > -1)
            {
                fileName = AppCenterEditorHelper.ANALYTICS_SDK_DOWNLOAD_PATH;
            }
            else if (url.IndexOf("AppCenterCrashes-v") > -1)
            {
                fileName = AppCenterEditorHelper.CRASHES_SDK_DOWNLOAD_PATH;
            }
            else if (url.IndexOf("AppCenterDistribute-v") > -1)
            {
                fileName = AppCenterEditorHelper.DISTRIBUTE_SDK_DOWNLOAD_PATH;
            }
            else
            {
                fileName = AppCenterEditorHelper.EDEX_PACKAGES_PATH;
            }
            var fileSaveLocation = AppCenterEditorHelper.EDEX_ROOT + fileName;
            var fileSaveDirectory = Path.GetDirectoryName(fileSaveLocation);
            EdExLogger.LoggerInstance.LogWithTimeStamp("Saving " + response.Length + " bytes to: " + fileSaveLocation);
            if (!Directory.Exists(fileSaveDirectory))
            {
                Directory.CreateDirectory(fileSaveDirectory);
            }
            File.WriteAllBytes(fileSaveLocation, response);
            return fileSaveLocation;
        }

        private class DownloadRequest
        {
            public string Url { get; private set; }
            public WWW WWW { get; private set; }

            public DownloadRequest(string url, WWW www)
            {
                Url = url;
                WWW = www;
            }
        }
    }
}


text:
import datetime
import unittest
from distutils.version import LooseVersion

import pandas as pd
import numpy as np
from pandas.api.types import CategoricalDtype

from pyspark import pandas as ps
from pyspark.pandas.config import option_context
from pyspark.pandas.tests.data_type_ops.testing_utils import TestCasesUtils
from pyspark.pandas.typedef.typehints import (
    extension_dtypes_available,
    extension_float_dtypes_available,
)
from pyspark.testing.pandasutils import PandasOnSparkTestCase

class NumOpsTest(PandasOnSparkTestCase, TestCasesUtils):
    """Unit tests for arithmetic operations of numeric data types.

    A few test cases are disabled because pandas-on-Spark returns float64 whereas pandas
    returns float32.
    The underlying reason is the respective Spark operations return DoubleType always.
    """

    @property
    def float_pser(self):
        return pd.Series([1, 2, 3], dtype=float)

    @property
    def float_psser(self):
        return ps.from_pandas(self.float_pser)

    def test_add(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            self.assert_eq(pser + pser, psser + psser)
            self.assert_eq(pser + 1, psser + 1)
            # self.assert_eq(pser + 0.1, psser + 0.1)
            self.assert_eq(pser + pser.astype(bool), psser + psser.astype(bool))
            self.assert_eq(pser + True, psser + True)
            self.assert_eq(pser + False, psser + False)

        with option_context("compute.ops_on_diff_frames", True):
            for pser, psser in self.numeric_pser_psser_pairs:
                self.assertRaises(TypeError, lambda: psser + self.non_numeric_pssers["string"])
                self.assertRaises(TypeError, lambda: psser + self.non_numeric_pssers["datetime"])
                self.assertRaises(TypeError, lambda: psser + self.non_numeric_pssers["date"])
                self.assertRaises(TypeError, lambda: psser + self.non_numeric_pssers["categorical"])
                self.assert_eq(
                    (psser + self.non_numeric_pssers["bool"]).sort_index(),
                    pser + self.non_numeric_psers["bool"],
                )

    def test_sub(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            self.assert_eq(pser - pser, psser - psser)
            self.assert_eq(pser - 1, psser - 1)
            # self.assert_eq(pser - 0.1, psser - 0.1)
            self.assert_eq(pser - pser.astype(bool), psser - psser.astype(bool))
            self.assert_eq(pser - True, psser - True)
            self.assert_eq(pser - False, psser - False)

        with option_context("compute.ops_on_diff_frames", True):
            for pser, psser in self.numeric_pser_psser_pairs:
                self.assertRaises(TypeError, lambda: psser - self.non_numeric_pssers["string"])
                self.assertRaises(TypeError, lambda: psser - self.non_numeric_pssers["datetime"])
                self.assertRaises(TypeError, lambda: psser - self.non_numeric_pssers["date"])
                self.assertRaises(TypeError, lambda: psser - self.non_numeric_pssers["categorical"])
                self.assert_eq(
                    (psser - self.non_numeric_pssers["bool"]).sort_index(),
                    pser - self.non_numeric_psers["bool"],
                )

    def test_mul(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            self.assert_eq(pser * pser, psser * psser)
            self.assert_eq(pser * pser.astype(bool), psser * psser.astype(bool))
            self.assert_eq(pser * True, psser * True)
            self.assert_eq(pser * False, psser * False)

        with option_context("compute.ops_on_diff_frames", True):
            for pser, psser in self.numeric_pser_psser_pairs:
                if psser.dtype in [int, np.int32]:
                    self.assert_eq(
                        (psser * self.non_numeric_pssers["string"]).sort_index(),
                        pser * self.non_numeric_psers["string"],
                    )
                else:
                    self.assertRaises(TypeError, lambda: psser * self.non_numeric_pssers["string"])
                self.assertRaises(TypeError, lambda: psser * self.non_numeric_pssers["datetime"])
                self.assertRaises(TypeError, lambda: psser * self.non_numeric_pssers["date"])
                self.assertRaises(TypeError, lambda: psser * self.non_numeric_pssers["categorical"])
                self.assert_eq(
                    (psser * self.non_numeric_pssers["bool"]).sort_index(),
                    pser * self.non_numeric_psers["bool"],
                )

    def test_truediv(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            if psser.dtype in [float, int, np.int32]:
                self.assert_eq(pser / pser, psser / psser)
                self.assert_eq(pser / pser.astype(bool), psser / psser.astype(bool))
                self.assert_eq(pser / True, psser / True)
                self.assert_eq(pser / False, psser / False)

        with option_context("compute.ops_on_diff_frames", True):
            for pser, psser in self.numeric_pser_psser_pairs:
                self.assertRaises(TypeError, lambda: psser / self.non_numeric_pssers["string"])
                self.assertRaises(TypeError, lambda: psser / self.non_numeric_pssers["datetime"])
                self.assertRaises(TypeError, lambda: psser / self.non_numeric_pssers["date"])
                self.assertRaises(TypeError, lambda: psser / self.non_numeric_pssers["categorical"])
            self.assert_eq(
                (self.float_psser / self.non_numeric_pssers["bool"]).sort_index(),
                self.float_pser / self.non_numeric_psers["bool"],
            )

    def test_floordiv(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            if psser.dtype == float:
                self.assert_eq(pser // pser, psser // psser)
                self.assert_eq(pser // pser.astype(bool), psser // psser.astype(bool))
                self.assert_eq(pser // True, psser // True)
                self.assert_eq(pser // False, psser // False)

        with option_context("compute.ops_on_diff_frames", True):
            for pser, psser in self.numeric_pser_psser_pairs:
                self.assertRaises(TypeError, lambda: psser // self.non_numeric_pssers["string"])
                self.assertRaises(TypeError, lambda: psser // self.non_numeric_pssers["datetime"])
                self.assertRaises(TypeError, lambda: psser // self.non_numeric_pssers["date"])
                self.assertRaises(
                    TypeError, lambda: psser // self.non_numeric_pssers["categorical"]
                )
            if LooseVersion(pd.__version__) >= LooseVersion("0.25.3"):
                self.assert_eq(
                    (self.float_psser // self.non_numeric_pssers["bool"]).sort_index(),
                    self.float_pser // self.non_numeric_psers["bool"],
                )
            else:
                self.assert_eq(
                    (self.float_pser // self.non_numeric_psers["bool"]).sort_index(),
                    ps.Series([1.0, 2.0, np.inf]),
                )

    def test_mod(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            self.assert_eq(pser % pser, psser % psser)
            self.assert_eq(pser % pser.astype(bool), psser % psser.astype(bool))
            self.assert_eq(pser % True, psser % True)
            if psser.dtype in [int, np.int32]:
                self.assert_eq(ps.Series([np.nan, np.nan, np.nan], dtype=float), psser % False)
            else:
                self.assert_eq(
                    ps.Series([np.nan, np.nan, np.nan], dtype=psser.dtype), psser % False
                )

        with option_context("compute.ops_on_diff_frames", True):
            for pser, psser in self.numeric_pser_psser_pairs:
                self.assertRaises(TypeError, lambda: psser % self.non_numeric_pssers["string"])
                self.assertRaises(TypeError, lambda: psser % self.non_numeric_pssers["datetime"])
                self.assertRaises(TypeError, lambda: psser % self.non_numeric_pssers["date"])
                self.assertRaises(TypeError, lambda: psser % self.non_numeric_pssers["categorical"])
            self.assert_eq(
                (self.float_psser % self.non_numeric_pssers["bool"]).sort_index(),
                self.float_pser % self.non_numeric_psers["bool"],
            )

    def test_pow(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            if psser.dtype == float:
                self.assert_eq(pser ** pser, psser ** psser)
                self.assert_eq(pser ** pser.astype(bool), psser ** psser.astype(bool))
                self.assert_eq(pser ** True, psser ** True)
                self.assert_eq(pser ** False, psser ** False)

        with option_context("compute.ops_on_diff_frames", True):
            for pser, psser in self.numeric_pser_psser_pairs:
                self.assertRaises(TypeError, lambda: psser ** self.non_numeric_pssers["string"])
                self.assertRaises(TypeError, lambda: psser ** self.non_numeric_pssers["datetime"])
                self.assertRaises(TypeError, lambda: psser ** self.non_numeric_pssers["date"])
                self.assertRaises(
                    TypeError, lambda: psser ** self.non_numeric_pssers["categorical"]
                )
            self.assert_eq(
                (self.float_psser ** self.non_numeric_pssers["bool"]).sort_index(),
                self.float_pser ** self.non_numeric_psers["bool"],
            )

    def test_radd(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            self.assert_eq(1 + pser, 1 + psser)
            # self.assert_eq(0.1 + pser, 0.1 + psser)
            self.assertRaises(TypeError, lambda: "x" + psser)
            self.assert_eq(True + pser, True + psser)
            self.assert_eq(False + pser, False + psser)
            self.assertRaises(TypeError, lambda: datetime.date(1994, 1, 1) + psser)
            self.assertRaises(TypeError, lambda: datetime.datetime(1994, 1, 1) + psser)

    def test_rsub(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            self.assert_eq(1 - pser, 1 - psser)
            # self.assert_eq(0.1 - pser, 0.1 - psser)
            self.assertRaises(TypeError, lambda: "x" - psser)
            self.assert_eq(True - pser, True - psser)
            self.assert_eq(False - pser, False - psser)
            self.assertRaises(TypeError, lambda: datetime.date(1994, 1, 1) - psser)
            self.assertRaises(TypeError, lambda: datetime.datetime(1994, 1, 1) - psser)

    def test_rmul(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            self.assert_eq(1 * pser, 1 * psser)
            # self.assert_eq(0.1 * pser, 0.1 * psser)
            self.assertRaises(TypeError, lambda: "x" * psser)
            self.assert_eq(True * pser, True * psser)
            self.assert_eq(False * pser, False * psser)
            self.assertRaises(TypeError, lambda: datetime.date(1994, 1, 1) * psser)
            self.assertRaises(TypeError, lambda: datetime.datetime(1994, 1, 1) * psser)

    def test_rtruediv(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            # self.assert_eq(5 / pser, 5 / psser)
            # self.assert_eq(0.1 / pser, 0.1 / psser)
            self.assertRaises(TypeError, lambda: "x" / psser)
            self.assert_eq((True / pser).astype(float), True / psser, check_exact=False)
            self.assert_eq((False / pser).astype(float), False / psser)
            self.assertRaises(TypeError, lambda: datetime.date(1994, 1, 1) / psser)
            self.assertRaises(TypeError, lambda: datetime.datetime(1994, 1, 1) / psser)

    def test_rfloordiv(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            # self.assert_eq(5 // pser, 5 // psser)
            # self.assert_eq(0.1 // pser, 0.1 // psser)
            self.assertRaises(TypeError, lambda: "x" // psser)
            self.assert_eq((True // pser).astype(float), True // psser)
            self.assert_eq((False // pser).astype(float), False // psser)
            self.assertRaises(TypeError, lambda: datetime.date(1994, 1, 1) // psser)
            self.assertRaises(TypeError, lambda: datetime.datetime(1994, 1, 1) // psser)

    def test_rpow(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            # self.assert_eq(1 ** pser, 1 ** psser)
            # self.assert_eq(0.1 ** pser, 0.1 ** psser)
            self.assertRaises(TypeError, lambda: "x" ** psser)
            self.assert_eq((True ** pser).astype(float), True ** psser)
            self.assert_eq((False ** pser).astype(float), False ** psser)
            self.assertRaises(TypeError, lambda: datetime.date(1994, 1, 1) ** psser)
            self.assertRaises(TypeError, lambda: datetime.datetime(1994, 1, 1) ** psser)

    def test_rmod(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            self.assert_eq(1 % pser, 1 % psser)
            # self.assert_eq(0.1 % pser, 0.1 % psser)
            self.assert_eq(True % pser, True % psser)
            self.assert_eq(False % pser, False % psser)
            self.assertRaises(TypeError, lambda: datetime.date(1994, 1, 1) % psser)
            self.assertRaises(TypeError, lambda: datetime.datetime(1994, 1, 1) % psser)

    def test_and(self):
        psser = self.numeric_pssers[0]
        self.assertRaises(TypeError, lambda: psser & True)
        self.assertRaises(TypeError, lambda: psser & False)
        self.assertRaises(TypeError, lambda: psser & psser)

    def test_rand(self):
        psser = self.numeric_pssers[0]
        self.assertRaises(TypeError, lambda: True & psser)
        self.assertRaises(TypeError, lambda: False & psser)

    def test_or(self):
        psser = self.numeric_pssers[0]
        self.assertRaises(TypeError, lambda: psser | True)
        self.assertRaises(TypeError, lambda: psser | False)
        self.assertRaises(TypeError, lambda: psser | psser)

    def test_ror(self):
        psser = self.numeric_pssers[0]
        self.assertRaises(TypeError, lambda: True | psser)
        self.assertRaises(TypeError, lambda: False | psser)

    def test_from_to_pandas(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            self.assert_eq(pser, psser.to_pandas())
            self.assert_eq(ps.from_pandas(pser), psser)

    def test_isnull(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            self.assert_eq(pser.isnull(), psser.isnull())

    def test_astype(self):
        for pser, psser in self.numeric_pser_psser_pairs:
            self.assert_eq(pser.astype(int), psser.astype(int))
            self.assert_eq(pser.astype(float), psser.astype(float))
            self.assert_eq(pser.astype(np.float32), psser.astype(np.float32))
            self.assert_eq(pser.astype(np.int32), psser.astype(np.int32))
            self.assert_eq(pser.astype(np.int16), psser.astype(np.int16))
            self.assert_eq(pser.astype(np.int8), psser.astype(np.int8))
            self.assert_eq(pser.astype(str), psser.astype(str))
            self.assert_eq(pser.astype(bool), psser.astype(bool))
            self.assert_eq(pser.astype("category"), psser.astype("category"))
            cat_type = CategoricalDtype(categories=[2, 1, 3])
            self.assert_eq(pser.astype(cat_type), psser.astype(cat_type))

@unittest.skipIf(not extension_dtypes_available, "pandas extension dtypes are not available")
class IntegralExtensionOpsTest(PandasOnSparkTestCase, TestCasesUtils):
    @property
    def intergral_extension_psers(self):
        dtypes = ["Int8", "Int16", "Int32", "Int64"]
        return [pd.Series([1, 2, 3, None], dtype=dtype) for dtype in dtypes]

    @property
    def intergral_extension_pssers(self):
        return [ps.from_pandas(pser) for pser in self.intergral_extension_psers]

    @property
    def intergral_extension_pser_psser_pairs(self):
        return zip(self.intergral_extension_psers, self.intergral_extension_pssers)

    def test_from_to_pandas(self):
        for pser, psser in self.intergral_extension_pser_psser_pairs:
            self.check_extension(pser, psser.to_pandas())
            self.check_extension(ps.from_pandas(pser), psser)

    def test_isnull(self):
        for pser, psser in self.intergral_extension_pser_psser_pairs:
            self.assert_eq(pser.isnull(), psser.isnull())

@unittest.skipIf(
    not extension_float_dtypes_available, "pandas extension float dtypes are not available"
)
class FractionalExtensionOpsTest(PandasOnSparkTestCase, TestCasesUtils):
    @property
    def fractional_extension_psers(self):
        dtypes = ["Float32", "Float64"]
        return [pd.Series([0.1, 0.2, 0.3, None], dtype=dtype) for dtype in dtypes]

    @property
    def fractional_extension_pssers(self):
        return [ps.from_pandas(pser) for pser in self.fractional_extension_psers]

    @property
    def fractional_extension_pser_psser_pairs(self):
        return zip(self.fractional_extension_psers, self.fractional_extension_pssers)

    def test_from_to_pandas(self):
        for pser, psser in self.fractional_extension_pser_psser_pairs:
            self.check_extension(pser, psser.to_pandas())
            self.check_extension(ps.from_pandas(pser), psser)

    def test_isnull(self):
        for pser, psser in self.fractional_extension_pser_psser_pairs:
            self.assert_eq(pser.isnull(), psser.isnull())

if __name__ == "__main__":
    from pyspark.pandas.tests.data_type_ops.test_num_ops import *  # noqa: F401

    try:
        import xmlrunner  # type: ignore[import]

        testRunner = xmlrunner.XMLTestRunner(output="target/test-reports", verbosity=2)
    except ImportError:
        testRunner = None
    unittest.main(testRunner=testRunner, verbosity=2)


text:
<?php

declare(strict_types=1);

/*
 * This file is part of SolidInvoice project.
 *
 * (c) Pierre du Plessis <open-source@solidworx.co>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace SolidInvoice\UserBundle\Action;

use SolidInvoice\UserBundle\Form\Handler\ProfileEditFormHandler;
use SolidWorx\FormHandler\FormHandler;

final class EditProfile
{
    public function __invoke(FormHandler $formHandler)
    {
        return $formHandler->handle(ProfileEditFormHandler::class);
    }
}


text:
enum class AndroidBackendAPIErrorCode {
  kNetworkError = 7,
  kInternalError = 8,
  kDeveloperError = 10,
  kApiNotConnected = 17,
  kConnectionSuspendedDuringCall = 20,
  kReconnectionTimedOut = 22,
  kPassphraseRequired = 11000,
  kAccessDenied = 11004,
  kAuthErrorResolvable = 11005,
  kAuthErrorUnresolvable = 11006,
  kBadRequest = 11008,
  kBackendGeneric = 11009,
  kBackendResourceExhausted = 11010,
  kInvalidData = 11011,
  kUnmappedErrorCode = 11012,
  kUnexpectedError = 11013,
  kChromeSyncAPICallError = 43502,
  kErrorWhileDoingLeakServiceGRPC = 43504,
  kRequiredSyncingAccountMissing = 43507,
  kLeakCheckServiceAuthError = 43508,
  kLeakCheckServiceResourceExhausted = 43509,
  kMaxValue = kLeakCheckServiceResourceExhausted,
};

#endif  // CHROME_BROWSER_PASSWORD_MANAGER_ANDROID_PASSWORD_STORE_ANDROID_BACKEND_API_ERROR_CODES_H_


text:
A game made by C++ Discord.  [https://discord.gg/J5hBe8F](https://discord.gg/J5hBe8F)

# Context
Hi children, in our current geopolitical context of multi-polarization of powers, everybody knows that a military conflict can break out at any moment, which is why it was decided to set up a data survival policy to be prepared to face an international nuclear conflict.

Our glorious council has arranged with many of the world's best scientific institutions and have decided that the best way for our game to survive an extinction level event is to fragment it in the smallest packets of data possible while still being meaningful.

We developped a top-secret, state-of-the-art compression technology to help us in our endeavor. One single problem, it can't compress line breaks. Which is why we imposed a hard limit on how you can contribute.

# Rules
Every Pull Request(PR) must:
* Compile; (Travis-CI checks this by running the makefile on each PR)
* Not crash the game;
* Must add to the game in some way

# How to Participate
1. Get a GitHub account.
2. Fork the discord game repo.
3. Install git on your computer.
4. Clone your fork.
5. Make your changes.
6. Commit and push those changes.
7. Create a pull request on GitHub.


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

#include "chrome/browser/support_tool/support_tool_handler.h"

#include <algorithm>
#include <cstddef>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>

#include "base/barrier_closure.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/check.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/scoped_refptr.h"
#include "base/strings/string_util.h"
#include "base/task/bind_post_task.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/support_tool/data_collector.h"
#include "chrome/browser/support_tool/support_packet_metadata.h"
#include "components/feedback/pii_types.h"
#include "components/feedback/redaction_tool.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/zlib/google/zip.h"

// Zip archieves the contents of `src_path` into `target_path`. Adds ".zip"
// extension to target file path. Returns the path of zip archive on success, an
// empty path otherwise.
base::FilePath ZipOutput(base::FilePath src_path, base::FilePath target_path) {
  base::FilePath zip_path = target_path.AddExtension(FILE_PATH_LITERAL(".zip"));
  if (!zip::Zip(src_path, zip_path, true)) {
    LOG(ERROR) << "Couldn't zip files";
    return base::FilePath();
  }
  return zip_path;
}

// Creates a unique temp directory to store the output files. The caller is
// responsible for deleting the returned directory. Returns an empty FilePath in
// case of an error.
base::FilePath CreateTempDirForOutput() {
  base::ScopedTempDir temp_dir;
  if (!temp_dir.CreateUniqueTempDir()) {
    LOG(ERROR) << "Unable to create temp dir.";
    return base::FilePath{};
  }
  return temp_dir.Take();
}

SupportToolHandler::SupportToolHandler()
    : SupportToolHandler(/*case_id=*/std::string(),
                         /*email_address=*/std::string(),
                         /*issue_description=*/std::string()) {}

SupportToolHandler::SupportToolHandler(std::string case_id,
                                       std::string email_address,
                                       std::string issue_description)
    : metadata_(case_id, email_address, issue_description),
      task_runner_for_redaction_tool_(
          base::ThreadPool::CreateSequencedTaskRunner(
              {base::TaskPriority::USER_VISIBLE,
               base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})),
      redaction_tool_container_(
          base::MakeRefCounted<feedback::RedactionToolContainer>(
              task_runner_for_redaction_tool_,
              nullptr)) {}

SupportToolHandler::~SupportToolHandler() {
  CleanUp();
}

void SupportToolHandler::CleanUp() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // Clean the temporary directory in a worker thread if it hasn't been removed
  // yet.
  if (!temp_dir_.empty()) {
    base::ThreadPool::PostTask(
        FROM_HERE,
        {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
         base::TaskShutdownBehavior::BLOCK_SHUTDOWN},
        base::GetDeletePathRecursivelyCallback(std::move(temp_dir_)));
    temp_dir_.clear();
  }
}

const std::string& SupportToolHandler::GetCaseId() {
  return metadata_.GetCaseId();
}

const base::Time& SupportToolHandler::GetDataCollectionTimestamp() {
  return data_collection_timestamp_;
}

void SupportToolHandler::AddDataCollector(
    std::unique_ptr<DataCollector> collector) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(collector);
  data_collectors_.emplace_back(std::move(collector));
}

void SupportToolHandler::CollectSupportData(
    SupportToolDataCollectedCallback on_data_collection_done_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!on_data_collection_done_callback.is_null());
  DCHECK(!data_collectors_.empty());

  on_data_collection_done_callback_ =
      std::move(on_data_collection_done_callback);

  base::RepeatingClosure collect_data_barrier_closure = base::BarrierClosure(
      data_collectors_.size(),
      base::BindOnce(&SupportToolHandler::OnAllDataCollected,
                     weak_ptr_factory_.GetWeakPtr()));

  data_collection_timestamp_ = base::Time::NowFromSystemTime();

  for (auto& data_collector : data_collectors_) {
    // DataCollectors will use `redaction_tool_container_` on
    // `task_runner_for_redaction_tool_` to redact PII from the collected logs.
    // All DataCollectors will use the same RedactionTool instance on the same
    // task runner as we need to replace the same PII data with the same
    // place-holder strings (that are stored in RedactionTool instance's data
    // member) in all collected logs to avoid confusing the reader.
    data_collector->CollectDataAndDetectPII(
        base::BindOnce(&SupportToolHandler::OnDataCollected,
                       weak_ptr_factory_.GetWeakPtr(),
                       collect_data_barrier_closure),
        task_runner_for_redaction_tool_, redaction_tool_container_);
  }
}

void SupportToolHandler::OnDataCollected(
    base::RepeatingClosure barrier_closure,
    absl::optional<SupportToolError> error) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (error) {
    collected_errors_.insert(error.value());
  }
  std::move(barrier_closure).Run();
}

void SupportToolHandler::AddDetectedPII(const PIIMap& pii_map) {
  for (auto& pii_data : pii_map) {
    detected_pii_[pii_data.first].insert(pii_data.second.begin(),
                                         pii_data.second.end());
  }
}

void SupportToolHandler::OnAllDataCollected() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  for (auto& data_collector : data_collectors_) {
    AddDetectedPII(data_collector->GetDetectedPII());
  }

  metadata_.InsertErrors(collected_errors_);

  metadata_.PopulateMetadataContents(
      data_collection_timestamp_, data_collectors_,
      base::BindOnce(&SupportToolHandler::OnMetadataContentsPopulated,
                     weak_ptr_factory_.GetWeakPtr()));
}

void SupportToolHandler::OnMetadataContentsPopulated() {
  AddDetectedPII(metadata_.GetPII());
  std::move(on_data_collection_done_callback_)
      .Run(detected_pii_, collected_errors_);
}

void SupportToolHandler::ExportCollectedData(
    std::set<feedback::PIIType> pii_types_to_keep,
    base::FilePath target_path,
    SupportToolDataExportedCallback on_data_exported_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Clear the set of previously collected errors.
  collected_errors_.clear();

  on_data_export_done_callback_ = std::move(on_data_exported_callback);

  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock()}, base::BindOnce(&CreateTempDirForOutput),
      base::BindOnce(&SupportToolHandler::ExportIntoTempDir,
                     weak_ptr_factory_.GetWeakPtr(), pii_types_to_keep,
                     target_path));
}

void SupportToolHandler::ExportIntoTempDir(
    std::set<feedback::PIIType> pii_types_to_keep,
    base::FilePath target_path,
    base::FilePath tmp_path) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (tmp_path.empty()) {
    collected_errors_.insert(
        {SupportToolErrorCode::kDataExportError,
         "Failed to create temporary directory for output."});
    std::move(on_data_export_done_callback_)
        .Run(base::FilePath(), collected_errors_);
    return;
  }

  temp_dir_ = tmp_path;

  base::RepeatingClosure export_data_barrier_closure = base::BarrierClosure(
      data_collectors_.size(),
      base::BindOnce(&SupportToolHandler::OnAllDataCollectorsDoneExporting,
                     weak_ptr_factory_.GetWeakPtr(), temp_dir_, target_path,
                     pii_types_to_keep));

  for (auto& data_collector : data_collectors_) {
    data_collector->ExportCollectedDataWithPII(
        pii_types_to_keep, temp_dir_, task_runner_for_redaction_tool_,
        redaction_tool_container_,
        base::BindOnce(&SupportToolHandler::OnDataCollectorDoneExporting,
                       weak_ptr_factory_.GetWeakPtr(),
                       export_data_barrier_closure));
  }
}

void SupportToolHandler::OnDataCollectorDoneExporting(
    base::RepeatingClosure barrier_closure,
    absl::optional<SupportToolError> error) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (error) {
    collected_errors_.insert(error.value());
  }
  std::move(barrier_closure).Run();
}

void SupportToolHandler::OnAllDataCollectorsDoneExporting(
    base::FilePath tmp_path,
    base::FilePath target_path,
    std::set<feedback::PIIType> pii_types_to_keep) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  metadata_.InsertErrors(collected_errors_);
  metadata_.WriteMetadataFile(
      tmp_path, pii_types_to_keep,
      base::BindOnce(&SupportToolHandler::OnMetadataFileWritten,
                     weak_ptr_factory_.GetWeakPtr(), tmp_path, target_path));
}

void SupportToolHandler::OnMetadataFileWritten(base::FilePath tmp_path,
                                               base::FilePath target_path) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // Archive the contents in the `tmp_path` into `target_path` in a zip file.
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock()},
      base::BindOnce(&ZipOutput, tmp_path, target_path),
      base::BindOnce(&SupportToolHandler::OnDataExportDone,
                     weak_ptr_factory_.GetWeakPtr()));
}

void SupportToolHandler::OnDataExportDone(base::FilePath exported_path) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // Clean-up the temporary directory after exporting the data.
  CleanUp();
  if (exported_path.empty()) {
    collected_errors_.insert({SupportToolErrorCode::kDataExportError,
                              "Failed to archive the output files."});
  }
  std::move(on_data_export_done_callback_)
      .Run(exported_path, collected_errors_);
}


text:
int StringMatch(const char *left, const char *right){
    while(*left && *right){
        if(*left != *right){
            return 0;
        }
        left++;
        right++;
    }
    return (*left == *right);
}

int StringMatchN(const char *left, const char *right, int n){
    while(*left && *right && n){
        if(*left != *right){
            return 0;
        }
        left++;
        right++;
        n--;
    }
    if(0 == n){
        return 1;
    }
    return (*left == *right);
}

void VMMain(int argc, char *argv[]){
    int DirDescriptor, FileDescriptor, Length;
    char LineBuffer[1024];
    char DirectoryName[VM_FILE_SYSTEM_MAX_PATH];
    SVMDirectoryEntry DirectoryEntry;
    int CharactersIn = 0;
    int Mil, Kil, One;

    while(1){
        VMDirectoryCurrent(DirectoryName);
        VMPrint("%s> ",DirectoryName);
        CharactersIn = 0;
        while(1){
            Length = 1;
            VMFileRead(0, LineBuffer + CharactersIn, &Length);
            if('\n' == LineBuffer[CharactersIn]){
                LineBuffer[CharactersIn] = '\0';
                break;
            }
            if((0 == CharactersIn)&&(' ' == LineBuffer[CharactersIn])){
                continue;
            }
            CharactersIn++;
        }

        while(0 < CharactersIn){
            CharactersIn--;
            if(' ' != LineBuffer[CharactersIn]){
                CharactersIn++;
                break;
            }
            LineBuffer[CharactersIn] = '\0';
        }
        if(StringMatch(LineBuffer,"exit")){
            break;
        }
        else if(StringMatch(LineBuffer,"ls")){

            if(VM_STATUS_SUCCESS == VMDirectoryOpen(DirectoryName, &DirDescriptor)){
                VMPrint("   DATE   |  TIME  | TYPE |    SIZE   |    SFN      |  LFN\n");
                while(VM_STATUS_SUCCESS == VMDirectoryRead(DirDescriptor, &DirectoryEntry)){
                    VMPrint("%04d/%02d/%02d %02d:%02d %s ",DirectoryEntry.DModify.DYear, DirectoryEntry.DModify.DMonth, DirectoryEntry.DModify.DDay, (DirectoryEntry.DModify.DHour % 12) ? (DirectoryEntry.DModify.DHour % 12) : 12 , DirectoryEntry.DModify.DMinute, DirectoryEntry.DModify.DHour >= 12 ? "PM" : "AM");
                    VMPrint("%s ", DirectoryEntry.DAttributes & VM_FILE_SYSTEM_ATTR_DIRECTORY ? "<DIR> " : "<FILE>");
                    Mil = DirectoryEntry.DSize / 1000000;
                    Kil = (DirectoryEntry.DSize / 1000) % 1000;
                    One = DirectoryEntry.DSize % 1000;
                    if(Mil){
                        VMPrint("%3d,%03d,%03d ",Mil, Kil, One);
                    }
                    else if(Kil){
                        VMPrint("    %3d,%03d ", Kil, One);
                    }
                    else if(0 == (DirectoryEntry.DAttributes & VM_FILE_SYSTEM_ATTR_DIRECTORY)){
                        VMPrint("        %3d ",One);
                    }
                    else{
                        VMPrint("            ");
                    }
                    VMPrint("%-13s %s\n",DirectoryEntry.DShortFileName, DirectoryEntry.DLongFileName);
                }
                VMDirectoryClose(DirDescriptor);
            }
            else{
                VMPrint("Failed to open directory %s!\n", DirectoryName);
            }
        }
        else if(StringMatchN(LineBuffer,"cd ",3)){
            CharactersIn = 2;
            while(' ' == LineBuffer[CharactersIn]){
                CharactersIn++;
            }
            if('\0' == LineBuffer[CharactersIn]){
                CharactersIn--;
                LineBuffer[CharactersIn] = '/';
            }
            if(VM_STATUS_SUCCESS != VMDirectoryChange(LineBuffer + CharactersIn)){
                VMPrint("Failed to change directory to %s!\n", LineBuffer + CharactersIn);
            }
        }
        else if(StringMatchN(LineBuffer,"rm ",3)){
            CharactersIn = 2;
            while(' ' == LineBuffer[CharactersIn]){
                CharactersIn++;
            }
            if('\0' == LineBuffer[CharactersIn]){
                CharactersIn--;
                LineBuffer[CharactersIn] = '/';
            }
            if(VM_STATUS_SUCCESS != VMDirectoryUnlink(LineBuffer + CharactersIn)){
                VMPrint("Failed to remove node %s!\n", LineBuffer + CharactersIn);
            }
        }
        else if(StringMatchN(LineBuffer,"mkdir ",6)){
            CharactersIn = 5;
            while(' ' == LineBuffer[CharactersIn]){
                CharactersIn++;
            }
            if('\0' == LineBuffer[CharactersIn]){
                CharactersIn--;
                LineBuffer[CharactersIn] = '/';
            }
            if(VM_STATUS_SUCCESS != VMDirectoryCreate(LineBuffer + CharactersIn)){
                VMPrint("Failed to create directory %s!\n", LineBuffer + CharactersIn);
            }
        }
        else if(StringMatchN(LineBuffer,"cat ",4)){
            CharactersIn = 3;
            while(' ' == LineBuffer[CharactersIn]){
                CharactersIn++;
            }
            if(VM_STATUS_SUCCESS == VMFileOpen(LineBuffer + CharactersIn, O_RDONLY, 0644, &FileDescriptor)){
                Length = sizeof(LineBuffer);
                while(VM_STATUS_SUCCESS == VMFileRead(FileDescriptor, LineBuffer, &Length)){
                    if(Length){
                        VMFileWrite(1,LineBuffer,&Length);
                    }
                    if(Length < sizeof(LineBuffer)){
                        break;
                    }
                    Length = sizeof(LineBuffer);
                }
                VMFileClose(FileDescriptor);
            }
            else{
                VMPrint("Failed to open file %s!\n", LineBuffer + CharactersIn);
            }
        }
    }
}


text:
<?php
$imagetypes=array("images/jpeg","images/png","images/jpg","images/x-png","images/gif");

function getimages($dir){
global $imagetypes;
//		array to hold return values;
$retval=array();
//		add trailing slashes if missing;
if(substr($dir, -1)!="/")
$dir.="/images/";
//		Full server path to dir
$fulldir ="{$_SERVER['DOCUMENT_ROOT']}/$dir";
// $fulldir ="localhost/novademo-localhost/images/";
$d=@dir($fulldir) or die("getimages: Failed opening directory {$_SERVER['DOCUMENT_ROOT']}/$dir for reading");
while(false!=($entry= $d->read())){
//		skip hidden files
	if($entry[0] == ".")
	continue;
//		check for image files
	$f=escapeshellarg("$fulldir"."$entry");
	$mimetype=trim(`file -bi $f`);
	foreach($imagetypes as $valid_type){
	if(preg_match("@^{$valid_type}@",$mimetype)){
	$retval[]=array('file' => "/$dir"."$entry", 'size' =>getimagesize("$fulldir"."$entry"));
	break;
	}}}
	$d->close();
return $retval;
}
?>


text:
#ifndef TCPSERVER_H
#define TCPSERVER_H

#include "IPAddress.hpp"
#include "Callback.hpp"
#include "Acceptor.hpp"
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>

namespace soke
{
    class EventLoop;
    class TCPConnection;
    class Socket;

    class TCPServer
    {
    public:
        TCPServer(EventLoop *loop, const IPAddress &addr);
        ~TCPServer() = default;

        // disable the copy operations
        TCPServer(const TCPServer &) = delete;
        TCPServer &operator=(const TCPServer &) = delete;

        void setConnectionCallback(ConnectionCallback callback);
        void setMessageCallback(MessageCallback callback);
        void start();

        void removeConnection(TCPConnectionPtr conn);

    private:
        //void newConnection(int sockfd, const IPAddress &addr);
        void newConnection(std::unique_ptr<Socket> socket);

        EventLoop *loop_;
        Acceptor   acceptor_;
        int        nextConnID;

        std::unordered_map<std::string, TCPConnectionPtr> connections_;
        ConnectionCallback connectionCallback_;
        MessageCallback    messageCallback_;
    };
};

#endif /* TCPSERVER_H */


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class VentanaCreadora : EditorWindow
{
    public GameObject Camara;
    public GameObject CurrentFloor;
    public static GameObject _ParedDerecha, _ParedIzquierda, _ParedArriba, _ParedAbajo;
    public static GameObject _VParedDerecha, _VParedIzquierda, _VParedArriba, _VParedAbajo;

    [ExecuteInEditMode]
    [MenuItem("Creacion De Terreno/Ventana De Dungeon")]

    static void SetiarVentana()
    {
        ((VentanaCreadora)GetWindow(typeof(VentanaCreadora))).Show();
    }

    private void OnGUI()
    {
        CurrentFloor = Selection.activeGameObject;

        if (CurrentFloor)
        {
            EditorGUILayout.LabelField("El nombre del piso actual es :" + CurrentFloor.name);
        }
        #region Modo Manual

        Repaint();

        EditorGUILayout.Space();
        GUILayout.BeginHorizontal();
        GUILayout.Label("", GUILayout.Width(140));

        if (_ParedArriba)
        {
            GUI.color = Color.green;
        }
        else GUI.color = Color.red;

        if (GUILayout.Button("↑", GUILayout.Width(100)))
        {
            DestroyImmediate(_ParedArriba);
            DestroyImmediate(_VParedAbajo);
        }
        GUILayout.EndHorizontal();
        EditorGUILayout.Space();

        GUILayout.BeginHorizontal();

        if (_ParedDerecha)
        {
            GUI.color = Color.green;
        }
        else GUI.color = Color.red;

        GUILayout.Label("", GUILayout.Width(43));
        if (GUILayout.Button("←", GUILayout.Width(100)))
        {
            DestroyImmediate(_ParedDerecha);
            DestroyImmediate(_VParedIzquierda);
        }
        if (_ParedIzquierda)
        {
            GUI.color = Color.green;
        }
        else GUI.color = Color.red;

        GUILayout.Label("", GUILayout.Width(87));
        if (GUILayout.Button("→", GUILayout.Width(100)))
        {
            DestroyImmediate(_ParedIzquierda);
            DestroyImmediate(_VParedDerecha);
        }
        GUILayout.EndHorizontal();
        EditorGUILayout.Space();

        GUILayout.BeginHorizontal();

        if (_ParedAbajo)
        {
            GUI.color = Color.green;
        }
        else GUI.color = Color.red;

        GUILayout.Label("", GUILayout.Width(140));
        if (GUILayout.Button("↓", GUILayout.Width(100)))
        {
            DestroyImmediate(_ParedAbajo);
            DestroyImmediate(_VParedArriba);
        }
        GUILayout.EndHorizontal();

        #endregion
        Repaint();
    }
}


text:
package com.zenjoy.db;

import com.zenjoy.entity.PlayerInfo;
import com.zenjoy.entity.PurchaseRecord;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.*;
import java.util.*;

/**
 * Common iap data exporter for all old slots apps
 * Created by alanmars on 16/6/1.
 */
public class IapDataExporter extends DB {
    private static final String PLAYER_INFO_FILENAME_FORMAT = "%s_%d_top%d_info.csv";
    private static final String IAP_LIST_FILENAME_FORMAT = "%s_%d_top%d_iap_list.csv";
    private static final String PLAYER_INFO_TITLE = "playerId,iapTotal,iapTimes,firstIapTime,firstIapTs,lastIapTime,lastIapTs,platform,createTime,createTs,lastLoginTs,lastLoginChips";
    private static final String IAP_LIST_TITLE = "playerId,platformType,productCount,productType,insertTime,priceUS,_svTime";

    private String _appName;
    private int _topNum;

    public IapDataExporter(String appName, int topNum) {
        _appName = appName;
        _topNum = topNum;
    }

    /**
     * @param topNum how many top players will be returned
     * @param startTime the start time of range during which define top players
     * @param endTime the end time of range during which define top players
     * @return
     * @throws SQLException
     */
    private List<PlayerInfo> getTopIapPlayers(int topNum, String startTime, String endTime) throws SQLException {
        Statement stmt = null;
        String query = String.format("select sum(price) as iapTotal, zentertainId, platform, count(platform) as iapTimes from purchase_record "
                + "where appName='%s' and myTimeStamp >= \'%s\' and myTimeStamp <= \'%s\' group by zentertainId"
                + " order by iapTotal desc limit %d", _appName, startTime, endTime, topNum);
        List<PlayerInfo> result = new ArrayList<PlayerInfo>();
        try {
            stmt = _conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {
                result.add(new PlayerInfo(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
        return result;
    }

    private void exportIapData(List<PlayerInfo> players, String startTime, String endTime, Writer infoWriter, Writer iapWriter) throws SQLException, IOException {
        PreparedStatement pstmt = null;
        String query = String.format("select zentertainId, platform, productId, myTimeStamp, price from purchase_record where zentertainId=? "
                + "and myTimeStamp >= \'%s\' and myTimeStamp <= \'%s\' order by myTimeStamp", startTime, endTime);
        try {
            pstmt = _conn.prepareStatement(query);
            for (PlayerInfo player : players) {
                pstmt.setString(1, player.getPlayerId());
                ResultSet rs = pstmt.executeQuery();
                PurchaseRecord record = null;
                boolean firstRecord = true;
                while (rs.next()) {
                    record = new PurchaseRecord(rs);

                    iapWriter.write(record.toString() + "\n");
                    if (firstRecord) {
                        player.setFirstIapTime(record.getInsertTime());
                        firstRecord = false;
                    }
                }

                if (!firstRecord) {
                    player.setLastIapTime(record.getInsertTime());
                    infoWriter.write(player.toString() + "\n");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (pstmt != null) {
                pstmt.close();
            }
        }
    }

    public void exportAvailableIapData() throws SQLException, IOException {
        //Iap data is available since 2014-11-1
        //export data for 2014
        {
            String startTime = "2014-01-01";
            String endTime = "2015-01-01";
            Writer infoWriter2014 = new FileWriter(String.format(PLAYER_INFO_FILENAME_FORMAT, _appName, 2014, _topNum));
            Writer iapWriter2014 = new FileWriter(String.format(IAP_LIST_FILENAME_FORMAT, _appName, 2014, _topNum));
            List<PlayerInfo> players2014 = getTopIapPlayers(_topNum, startTime, endTime);

            infoWriter2014.write(PLAYER_INFO_TITLE + "\n");
            iapWriter2014.write(IAP_LIST_TITLE + "\n");
            exportIapData(players2014, startTime, endTime, infoWriter2014, iapWriter2014);

            infoWriter2014.close();
            iapWriter2014.close();
        }

        //export data for 2015
        {
            String startTime = "2015-01-01";
            String endTime = "2016-01-01";
            Writer infoWriter2015 = new FileWriter(String.format(PLAYER_INFO_FILENAME_FORMAT, _appName, 2015, _topNum));
            Writer iapWriter2015 = new FileWriter(String.format(IAP_LIST_FILENAME_FORMAT, _appName, 2015, _topNum));
            List<PlayerInfo> players2015 = getTopIapPlayers(_topNum, startTime, endTime);

            infoWriter2015.write(PLAYER_INFO_TITLE + "\n");
            iapWriter2015.write(IAP_LIST_TITLE + "\n");
            exportIapData(players2015, startTime, endTime, infoWriter2015, iapWriter2015);

            infoWriter2015.close();
            iapWriter2015.close();
        }

        //export data for 2016
        {
            String startTime = "2016-01-01";
            String endTime = "2016-04-01";
            Writer infoWriter2016 = new FileWriter(String.format(PLAYER_INFO_FILENAME_FORMAT, _appName, 2016, _topNum));
            Writer iapWriter2016 = new FileWriter(String.format(IAP_LIST_FILENAME_FORMAT, _appName, 2016, _topNum));
            List<PlayerInfo> players2016 = getTopIapPlayers(_topNum, startTime, endTime);

            infoWriter2016.write(PLAYER_INFO_TITLE + "\n");
            iapWriter2016.write(IAP_LIST_TITLE + "\n");
            exportIapData(players2016, startTime, endTime, infoWriter2016, iapWriter2016);

            infoWriter2016.close();
            iapWriter2016.close();
        }
    }
}


text:
#!/usr/local/bin/php
<?php
/**
* $Id: example-wrapper.php 20 2008-05-06 10:41:26Z don.schonknecht $
*
* Note: Although this wrapper works, it would be more efficient to use the S3 class instead
*/

if (!class_exists('S3')) require_once 'S3.php';

// AWS access info
if (!defined('awsAccessKey')) define('awsAccessKey', 'change-this');
if (!defined('awsSecretKey')) define('awsSecretKey', 'change-this');

// Check for CURL
if (!extension_loaded('curl') && !@dl(PHP_SHLIB_SUFFIX == 'so' ? 'curl.so' : 'php_curl.dll'))
	exit("\nERROR: CURL extension not loaded\n\n");

// Pointless without your keys!
if (awsAccessKey == 'change-this' || awsSecretKey == 'change-this')
	exit("\nERROR: AWS access information required\n\nPlease edit the following lines in this file:\n\n".
	"define('awsAccessKey', 'change-me');\ndefine('awsSecretKey', 'change-me');\n\n");

################################################################################

final class S3Wrapper extends S3 {
	private $position = 0, $mode = '', $buffer;

	public function url_stat($path, $flags) {
		self::__getURL($path);
		return (($info = self::getObjectInfo($this->url['host'], $this->url['path'])) !== false) ?
		array('size' => $info['size'], 'mtime' => $info['time'], 'ctime' => $info['time']) : false;
	}

	public function unlink($path) {
		self::__getURL($path);
		return self::deleteObject($this->url['host'], $this->url['path']);
	}

	public function mkdir($path, $mode, $options) {
		self::__getURL($path);
		return self::putBucket($this->url['host'], self::__translateMode($mode));
	}

	public function rmdir($path) {
		self::__getURL($path);
		return self::deleteBucket($this->url['host']);
	}

	public function dir_opendir($path, $options) {
		self::__getURL($path);
		if (($contents = self::getBucket($this->url['host'], $this->url['path'])) !== false) {
			$pathlen = strlen($this->url['path']);
			if (substr($this->url['path'], -1) == '/') $pathlen++;
			$this->buffer = array();
			foreach ($contents as $file) {
				if ($pathlen > 0) $file['name'] = substr($file['name'], $pathlen);
				$this->buffer[] = $file;
			}
			return true;
		}
		return false;
	}

	public function dir_readdir() {
		return (isset($this->buffer[$this->position])) ? $this->buffer[$this->position++]['name'] : false;
	}

	public function dir_rewinddir() {
		$this->position = 0;
	}

	public function dir_closedir() {
		$this->position = 0;
		unset($this->buffer);
	}

	public function stream_close() {
		if ($this->mode == 'w') {
			self::putObject($this->buffer, $this->url['host'], $this->url['path']);
		}
		$this->position = 0;
		unset($this->buffer);
	}

	public function stream_stat() {
		if (is_object($this->buffer) && isset($this->buffer->headers))
			return array(
				'size' => $this->buffer->headers['size'],
				'mtime' => $this->buffer->headers['time'],
				'ctime' => $this->buffer->headers['time']
			);
		elseif (($info = self::getObjectInfo($this->url['host'], $this->url['path'])) !== false)
			return array('size' => $info['size'], 'mtime' => $info['time'], 'ctime' => $info['time']);
		return false;
	}

	public function stream_flush() {
		$this->position = 0;
		return true;
	}

	public function stream_open($path, $mode, $options, &$opened_path) {
		if (!in_array($mode, array('r', 'rb', 'w', 'wb'))) return false; // Mode not supported
		$this->mode = substr($mode, 0, 1);
		self::__getURL($path);
		$this->position = 0;
		if ($this->mode == 'r') {
			if (($this->buffer = self::getObject($this->url['host'], $this->url['path'])) !== false) {
				if (is_object($this->buffer->body)) $this->buffer->body = (string)$this->buffer->body;
			} else return false;
		}
		return true;
	}

	public function stream_read($count) {
		if ($this->mode !== 'r' && $this->buffer !== false) return false;
		$data = substr(is_object($this->buffer) ? $this->buffer->body : $this->buffer, $this->position, $count);
		$this->position += strlen($data);
		return $data;
	}

	public function stream_write($data) {
		if ($this->mode !== 'w') return 0;
		$left = substr($this->buffer, 0, $this->position);
		$right = substr($this->buffer, $this->position + strlen($data));
		$this->buffer = $left . $data . $right;
		$this->position += strlen($data);
		return strlen($data);
	}

	public function stream_tell() {
		return $this->position;
	}

	public function stream_eof() {
		return $this->position >= strlen(is_object($this->buffer) ? $this->buffer->body : $this->buffer);
	}

	public function stream_seek($offset, $whence) {
		switch ($whence) {
			case SEEK_SET:
                if ($offset < strlen($this->buffer->body) && $offset >= 0) {
                    $this->position = $offset;
                    return true;
                } else return false;
            break;
            case SEEK_CUR:
                if ($offset >= 0) {
                    $this->position += $offset;
                    return true;
                } else return false;
            break;
            case SEEK_END:
                $bytes = strlen($this->buffer->body);
                if ($bytes + $offset >= 0) {
                    $this->position = $bytes + $offset;
                    return true;
                } else return false;
            break;
            default: return false;
        }
    }

    private function __getURL($path) {
        $this->url = parse_url($path);
        if (!isset($this->url['scheme']) || $this->url['scheme'] !== 's3') return $this->url;
        if (isset($this->url['user'], $this->url['pass'])) self::setAuth($this->url['user'], $this->url['pass']);
        $this->url['path'] = isset($this->url['path']) ? substr($this->url['path'], 1) : '';
    }

	private function __translateMode($mode) {
		$acl = self::ACL_PRIVATE;
		if (($mode & 0x0020) || ($mode & 0x0004))
			$acl = self::ACL_PUBLIC_READ;
		// You probably don't want to enable public write access
		if (($mode & 0x0010) || ($mode & 0x0008) || ($mode & 0x0002) || ($mode & 0x0001))
			$acl = self::ACL_PUBLIC_READ; //$acl = self::ACL_PUBLIC_READ_WRITE;
		return $acl;
	}
} stream_wrapper_register('s3', 'S3Wrapper');

################################################################################

S3::setAuth(awsAccessKey, awsSecretKey);

$bucketName = uniqid('s3test');

echo "Creating bucket: {$bucketName}\n";
var_dump(mkdir("s3://{$bucketName}"));

echo "\nWriting file: {$bucketName}/test.txt\n";
var_dump(file_put_contents("s3://{$bucketName}/test.txt", "Eureka!"));

echo "\nReading file: {$bucketName}/test.txt\n";
var_dump(file_get_contents("s3://{$bucketName}/test.txt"));

echo "\nContents for bucket: {$bucketName}\n";
foreach (new DirectoryIterator("s3://{$bucketName}") as $b) {
	echo "\t".$b."\n";
}

echo "\nUnlinking: {$bucketName}/test.txt\n";
var_dump(unlink("s3://{$bucketName}/test.txt"));

echo "\nRemoving bucket: {$bucketName}\n";
var_dump(rmdir("s3://{$bucketName}"));

#EOF


text:
package org.metaborg.core.language.dialect;

import javax.annotation.Nullable;

import org.apache.commons.vfs2.FileObject;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.language.ILanguageImpl;

/**
 * Interface for identifying the dialect of a resource.
 */
public interface IDialectIdentifier {
    /**
     * Attempts to identify the dialect of given resource.
     *
     * @param resource
     *            Resource to identify.
     * @return Identified dialect, or null if dialect could not be identified.
     * @throws MetaborgException
     *             When unable to determine if resource requires a dialect.
     * @throws MetaborgException
     *             When resource requires a dialect that is not available.
     */
    @Nullable IdentifiedDialect identify(FileObject resource) throws MetaborgException;

    /**
     * Checks if given resource is of given dialect.
     *
     * @param resource
     *            Resource to check.
     * @param dialect
     *            Dialect to check against.
     * @return True if resource is of given dialect, false otherwise.
     * @throws MetaborgException
     *             When unable to determine if resource requires a dialect.
     * @throws MetaborgException
     *             When resource requires a dialect that is not available.
     */
    boolean identify(FileObject resource, ILanguageImpl dialect) throws MetaborgException;
}


text:
<?php
$TRANSLATIONS = array(
"Could not move %s - File with this name already exists" => "No se pudo mover %s - Ya existe un archivo con ese nombre.",
"Could not move %s" => "No se pudo mover %s",
"File name cannot be empty." => "El nombre de archivo no puede estar vacío.",
"\"%s\" is an invalid file name." => "\"%s\" es un nombre de archivo inválido.",
"Invalid name, '\\', '/', '<', '>', ':', '\"', '|', '?' and '*' are not allowed." => "Nombre inválido, los caracteres \"\\\", \"/\", \"<\", \">\", \":\", \"\", \"|\" \"?\" y \"*\" no están permitidos ",
"The target folder has been moved or deleted." => "La carpeta destino fue movida o eliminada.",
"The name %s is already used in the folder %s. Please choose a different name." => "El nombre %s ya está en uso por la carpeta %s. Por favor elija uno diferente.",
"Not a valid source" => "No es una fuente válida",
"Server is not allowed to open URLs, please check the server configuration" => "La configuración del servidor no le permite abrir URLs, revísela.",
"Error while downloading %s to %s" => "Error mientras se descargaba %s a %s",
"Error when creating the file" => "Error al crear el archivo",
"Folder name cannot be empty." => "El nombre de la carpeta no puede estar vacío.",
"Error when creating the folder" => "Error al crear la carpeta.",
"Unable to set upload directory." => "Incapaz de crear directorio de subida.",
"Invalid Token" => "Token Inválido",
"No file was uploaded. Unknown error" => "No se subió ningún archivo. Error desconocido",
"There is no error, the file uploaded with success" => "No hubo ningún problema, el archivo se subió con éxito",
"The uploaded file exceeds the upload_max_filesize directive in php.ini: " => "El archivo subido sobrepasa la directiva 'upload_max_filesize' en php.ini:",
"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" => "El archivo subido sobrepasa la directiva 'MAX_FILE_SIZE' especificada en el formulario HTML",
"The uploaded file was only partially uploaded" => "El archivo subido fue sólo subido parcialmente",
"No file was uploaded" => "No se subió ningún archivo",
"Missing a temporary folder" => "Falta la carpeta temporal",
"Failed to write to disk" => "Falló al escribir al disco",
"Not enough storage available" => "No hay suficiente espacio disponible",
"Upload failed. Could not find uploaded file" => "Actualización fallida. No se pudo encontrar el archivo subido",
"Upload failed. Could not get file info." => "Actualización fallida. No se pudo obtener información del archivo.",
"Invalid directory." => "Directorio inválido.",
"Files" => "Archivos",
"All files" => "Todos los archivos",
"Unable to upload {filename} as it is a directory or has 0 bytes" => "No ha sido posible subir {filename} porque es un directorio o tiene 0 bytes",
"Total file size {size1} exceeds upload limit {size2}" => "El tamaño total del archivo {size1} excede el límite {size2}",
"Not enough free space, you are uploading {size1} but only {size2} is left" => "No hay suficiente espacio libre. Quiere subir {size1} pero solo quedan {size2}",
"Upload cancelled." => "Subida cancelada.",
"Could not get result from server." => "No se pudo obtener respuesta del servidor.",
"File upload is in progress. Leaving the page now will cancel the upload." => "La subida del archivo está en proceso. Si sale de la página ahora, la subida será cancelada.",
"URL cannot be empty" => "La dirección URL no puede estar vacía",
"{new_name} already exists" => "{new_name} ya existe",
"Could not create file" => "No se pudo crear el archivo",
"Could not create folder" => "No se pudo crear la carpeta",
"Error fetching URL" => "Error al descargar URL.",
"Share" => "Compartir",
"Delete permanently" => "Eliminar permanentemente",
"Delete" => "Eliminar",
"Rename" => "Renombrar",
"Your download is being prepared. This might take some time if the files are big." => "Su descarga está siendo preparada. Esto podría tardar algo de tiempo si los archivos son grandes.",
"Pending" => "Pendiente",
"Error moving file." => "Error al mover el archivo.",
"Error moving file" => "Error moviendo archivo",
"Error" => "Error",
"Could not rename file" => "No se pudo renombrar el archivo",
"Error deleting file." => "Error al borrar el archivo",
"Name" => "Nombre",
"Size" => "Tamaño",
"Modified" => "Modificado",
"_%n folder_::_%n folders_" => array("%n carpeta","%n carpetas"),
"_%n file_::_%n files_" => array("%n archivo","%n archivos"),
"_Uploading %n file_::_Uploading %n files_" => array("Subiendo %n archivo","Subiendo %n archivos"),
"\"{name}\" is an invalid file name." => "\"{name}\" es un nombre de archivo inválido.",
"Your storage is full, files can not be updated or synced anymore!" => "Su almacenamiento está lleno, ¡los archivos no se actualizarán ni sincronizarán más!",
"Your storage is almost full ({usedSpacePercent}%)" => "Su almacenamiento está casi lleno ({usedSpacePercent}%)",
"Encryption App is enabled but your keys are not initialized, please log-out and log-in again" => "La app de crifrado está habilitada pero tus claves no han sido inicializadas, por favor, cierra la sesión y vuelva a iniciarla de nuevo.",
"Invalid private key for Encryption App. Please update your private key password in your personal settings to recover access to your encrypted files." => "La clave privada no es válida para la app de cifrado. Por favor, actualiza la contraseña de tu clave privada en tus ajustes personales para recuperar el acceso a tus archivos cifrados.",
"Encryption was disabled but your files are still encrypted. Please go to your personal settings to decrypt your files." => "El cifrado ha sido deshabilitado pero tus archivos permanecen cifrados. Por favor, ve a tus ajustes personales para descifrar tus archivos.",
"{dirs} and {files}" => "{dirs} y {files}",
"%s could not be renamed" => "%s no pudo ser renombrado",
"Upload (max. %s)" => "Subida (máx. %s)",
"File handling" => "Administración de archivos",
"Maximum upload size" => "Tamaño máximo de subida",
"max. possible: " => "máx. posible:",
"Save" => "Guardar",
"WebDAV" => "WebDAV",
"Use this address to access your Files via WebDAV" => "Use esta URL para acceder via WebDAV",
"New" => "Nuevo",
"New text file" => "Nuevo archivo de texto",
"Text file" => "Archivo de texto",
"New folder" => "Nueva carpeta",
"Folder" => "Carpeta",
"From link" => "Desde enlace",
"You don't have permission to upload or create files here" => "No tienes permisos para subir o crear archivos aquí.",
"Nothing in here. Upload something!" => "No hay nada aquí. ¡Suba algo!",
"Download" => "Descargar",
"Upload too large" => "Subida demasido grande",
"The files you are trying to upload exceed the maximum size for file uploads on this server." => "Los archivos que estás intentando subir sobrepasan el tamaño máximo permitido en este servidor.",
"Files are being scanned, please wait." => "Los archivos están siendo escaneados,  por favor espere.",
"Currently scanning" => "Escaneando en este momento"
);
$PLURAL_FORMS = "nplurals=2; plural=(n != 1);";


text:
package org.bouncycastle.tls.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.security.SecureRandom;
import java.util.Vector;

import org.bouncycastle.PrintTestResult;
import org.bouncycastle.tls.AlertDescription;
import org.bouncycastle.tls.AlertLevel;
import org.bouncycastle.tls.DefaultTlsClient;
import org.bouncycastle.tls.HashAlgorithm;
import org.bouncycastle.tls.ServerOnlyTlsAuthentication;
import org.bouncycastle.tls.SignatureAlgorithm;
import org.bouncycastle.tls.SignatureAndHashAlgorithm;
import org.bouncycastle.tls.TlsAuthentication;
import org.bouncycastle.tls.TlsClientProtocol;
import org.bouncycastle.tls.TlsServerCertificate;
import org.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Hex;

import junit.framework.TestCase;
import junit.framework.TestSuite;

public class BasicTlsTest
    extends TestCase
{
    private static final int PORT_NO = 12001;

    protected boolean isSufficientVMVersion(String vmVersion)
    {
        if (vmVersion == null)
        {
            return false;
        }
        String[] parts = vmVersion.split("\\.");
        if (parts == null || parts.length < 1)
        {
            return false;
        }
        try
        {
            int major = Integer.parseInt(parts[0]);
            if (major != 1)
            {
                return major > 1;
            }
            if (parts.length < 2)
            {
                return false;
            }
            int minor = Integer.parseInt(parts[1]);
            return minor >= 7;
        }
        catch (NumberFormatException e)
        {
            return false;
        }
    }

    public void testConnection()
        throws Exception
    {
        String vmVersion = System.getProperty("java.specification.version");
        if (!isSufficientVMVersion(vmVersion))
        {
            return; // only works on later VMs.
        }

        Thread server = new HTTPSServerThread();

        server.start();

        Thread.yield();

        Socket s = null;

        for (int i = 0; s == null && i != 3; i++)
        {
            Thread.sleep(1000);

            try
            {
                s = new Socket("localhost", PORT_NO);
            }
            catch (IOException e)
            {
                // ignore
            }
        }

        if (s == null)
        {
            throw new IOException("unable to connect");
        }

        TlsClientProtocol protocol = new TlsClientProtocol(s.getInputStream(), s.getOutputStream());
        protocol.connect(new MyTlsClient(new ServerOnlyTlsAuthentication()
        {
            public void notifyServerCertificate(TlsServerCertificate serverCertificate)
                throws IOException
            {
                // NOTE: In production code this MUST verify the certificate!
            }
        }));

        InputStream is = protocol.getInputStream();
        OutputStream os = protocol.getOutputStream();

        os.write("GET / HTTP/1.1\r\n\r\n".getBytes());

        byte[] buf = new byte[4096];
        int read = 0;
        int total = 0;

        while ((read = is.read(buf, total, buf.length - total)) > 0)
        {
            total += read;
        }

        is.close();

        byte[] expected = Hex.decode("485454502f312e3120323030204f4b0d0a436f6e74656e742d547970653a20746578742f68"
            + "746d6c0d0a0d0a3c68746d6c3e0d0a3c626f64793e0d0a48656c6c6f20576f726c64210d0a3c2f626f64793e0d0a3c2f"
            + "68746d6c3e0d0a");
        assertEquals(total, expected.length);

        byte[] tmp = new byte[expected.length];
        System.arraycopy(buf, 0, tmp, 0, total);
        assertTrue(Arrays.areEqual(expected, tmp));
    }

    public static TestSuite suite()
    {
        return new TestSuite(BasicTlsTest.class);
    }

    public static void main(String[] args)
        throws Exception
    {
        PrintTestResult.printResult(junit.textui.TestRunner.run(suite()));
    }

    static class MyTlsClient
        extends DefaultTlsClient
    {
        public void notifyAlertRaised(short alertLevel, short alertDescription, String message, Throwable cause)
        {
            PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out;
            out.println("TLS client raised alert: " + AlertLevel.getText(alertLevel) + ", " + AlertDescription.getText(alertDescription));
            if (message != null)
            {
                out.println("> " + message);
            }
            if (cause != null)
            {
                cause.printStackTrace(out);
            }
        }

        public void notifyAlertReceived(short alertLevel, short alertDescription)
        {
            PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out;
            out.println("TLS client received alert: " + AlertLevel.getText(alertLevel) + ", " + AlertDescription.getText(alertDescription));
        }

        private final TlsAuthentication authentication;

        MyTlsClient(TlsAuthentication authentication)
        {
            super(new BcTlsCrypto(new SecureRandom()));

            this.authentication = authentication;

            this.supportedSignatureAlgorithms = new Vector();
            this.supportedSignatureAlgorithms.addElement(new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa));
            this.supportedSignatureAlgorithms.addElement(new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa));
            this.supportedSignatureAlgorithms.addElement(new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.rsa));
        }

        public TlsAuthentication getAuthentication()
            throws IOException
        {
            return authentication;
        }
    }
}


text:
package seller.viewholder;

import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.example.administrator.myapplication.R;
import com.github.mikephil.charting.charts.PieChart;

/**
 * Created by Administrator on 21/11/2559.
 */
public class PieChartViewHolder extends RecyclerView.ViewHolder {

    public PieChart bestSellerPieChart;

    public PieChartViewHolder(View itemView) {
        super(itemView);
        bestSellerPieChart = (PieChart) itemView.findViewById(R.id.bestSellerPieChart);
    }
}


text:
```javascript
// Async task (same in all examples in this chapter)
function async(arg, callback) {
  console.log('do something with \''+arg+'\', return 1 sec later');
  setTimeout(function() { callback(arg * 2); }, 1000);
}
// Final task (same in all the examples)
function final() { console.log('Done', results); }

// A simple async series:
var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
function series(item) {
  if(item) {
    async( item, function(result) {
      results.push(result);
      return series(items.shift());
    });
  } else {
    return final();
  }
}
series(items.shift());
```

# Full parallel

```javascript
function async(arg, callback) {
  console.log('do something with \''+arg+'\', return 1 sec later');
  setTimeout(function() { callback(arg * 2); }, 1000);
}
function final() { console.log('Done', results); }

var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];

items.forEach(function(item) {
  async(item, function(result){
    results.push(result);
    if(results.length == items.length) {
      final();
    }
  })
});
```

# Limited parallel

```javascript
function async(arg, callback) {
  console.log('do something with \''+arg+'\', return 1 sec later');
  setTimeout(function() { callback(arg * 2); }, 1000);
}
function final() { console.log('Done', results); }

var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
var running = 0;
var limit = 2;

function launcher() {
  while(running < limit && items.length > 0) {
    var item = items.shift();
    async(item, function(result) {
      results.push(result);
      running--;
      if(items.length > 0) {
        launcher();
      } else if(running == 0) {
        final();
      }
    });
    running++;
  }
}

launcher();
```