text:
#include "struct_metal.h"

#include <algorithm>
#include <functional>
#include <limits>
#include <sstream>
#include <string>
#include <vector>

#include "taichi/rhi/metal/constants.h"
#include "taichi/runtime/metal/data_types.h"
#include "taichi/runtime/metal/features.h"
#include "taichi/runtime/metal/kernel_utils.h"
#include "taichi/math/arithmetic.h"
#include "taichi/util/line_appender.h"

namespace taichi::lang {
namespace metal {
namespace {
namespace shaders {
#define TI_INSIDE_METAL_CODEGEN
#include "taichi/runtime/metal/shaders/runtime_structs.metal.h"
#include "taichi/runtime/metal/shaders/runtime_utils.metal.h"
#include "taichi/runtime/metal/shaders/snode_bit_pointer.metal.h"
#undef TI_INSIDE_METAL_CODEGEN

#include "taichi/runtime/metal/shaders/runtime_structs.metal.h"

}  // namespace shaders

constexpr size_t kListManagerDataSize = sizeof(shaders::ListManagerData);
constexpr size_t kNodeManagerDataSize = sizeof(shaders::NodeManagerData);
constexpr size_t kNodeManagerElemIndexSize =
    sizeof(shaders::NodeManagerData::ElemIndex);
constexpr size_t kSNodeMetaSize = sizeof(shaders::SNodeMeta);
constexpr size_t kSNodeExtractorsSize = sizeof(shaders::SNodeExtractors);

static_assert(kNodeManagerElemIndexSize == sizeof(int32_t),
              "sizeof(NodeManagerData::ElemIndex) != 4");

constexpr int kAlignment = 8;

inline size_t bitmasks_stride(int n) {
  constexpr int kBitsPerByte = 8;
  const int bytes_needed = iroundup(n, kBitsPerByte) / kBitsPerByte;
  // The roundup is to align the stride to 8-bytes.
  return iroundup(bytes_needed, kAlignment);
}

class StructCompiler {
 public:
  CompiledStructs run(SNode &root) {
    TI_ASSERT(root.type == SNodeType::root);
    collect_snodes(root);
    auto snodes_rev = snodes_;
    std::reverse(snodes_rev.begin(), snodes_rev.end());
    {
      max_snodes_ = 0;
      has_sparse_snode_ = false;
#define CHECK_UNSUPPORTED_TYPE(type_case)                                \
  else if (ty == SNodeType::type_case) {                                 \
    TI_ERROR("Metal backend does not support SNode=" #type_case " yet"); \
  }
      for (const auto &sn : snodes_) {
        const auto ty = sn->type;
        if (ty == SNodeType::place) {
          // do nothing
        }
        CHECK_UNSUPPORTED_TYPE(quant_array)
        CHECK_UNSUPPORTED_TYPE(hash)
        else {
          max_snodes_ = std::max(max_snodes_, sn->id);
        }
        has_sparse_snode_ = has_sparse_snode_ || is_supported_sparse_type(ty);
      }
      ++max_snodes_;
    }
#undef CHECK_UNSUPPORTED_TYPE

    CompiledStructs result;
    result.root_snode_type_name = root.node_type_name;
    result.root_size = compute_snode_size(&root);
    for (auto &n : snodes_rev) {
      generate_types(*n);
    }
    line_appender_.dump(&result.snode_structs_source_code);
    result.root_id = root.id;
    result.max_snodes = max_snodes_;
    result.snode_descriptors = std::move(snode_descriptors_);
    TI_DEBUG("Metal: root_id={} root_size={}", result.root_id,
             result.root_size);
    return result;
  }

 private:
  void collect_snodes(SNode &snode) {
    snodes_.push_back(&snode);
    for (int ch_id = 0; ch_id < (int)snode.ch.size(); ch_id++) {
      auto &ch = snode.ch[ch_id];
      collect_snodes(*ch);
    }
  }

  void emit_snode_stride(SNodeType ty, const std::string &ch_name, int n) {
    if (ty == SNodeType::pointer) {
      emit(
          "  constant static constexpr int elem_stride = "
          "/*pointer ElemIndex=*/{};",
          kNodeManagerElemIndexSize);
    } else {
      emit("  constant static constexpr int elem_stride = {}::stride;",
           ch_name);
    }

    if (ty == SNodeType::bitmasked) {
      emit(
          "  constant static constexpr int stride = elem_stride * n + "
          "/*bitmasked=*/{};",
          bitmasks_stride(n));
    } else if (ty == SNodeType::dynamic) {
      emit(
          "  constant static constexpr int stride = elem_stride * n + "
          "/*dynamic=*/{};",
          kAlignment);
    } else {
      // `root`, `dense`, `bit_struct`
      emit("  constant static constexpr int stride = elem_stride * n;");
    }
    emit("");
  }

  void emit_snode_constructor(const SNode &sn) {
    const auto ty = sn.type;
    const auto &name = sn.node_type_name;
    if (ty == SNodeType::root) {
      emit("  {}(device byte *addr) {{", name);
    } else {
      emit(
          "  {}(device byte *addr, device Runtime *rtm, device MemoryAllocator "
          "*ma) {{",
          name);
    }
    if (ty == SNodeType::bitmasked || ty == SNodeType::dynamic) {
      emit("    rep_.init(addr, /*meta_offset=*/elem_stride * n);");
    } else if (ty == SNodeType::pointer) {
      const auto snid = sn.id;
      emit("    NodeManager nm;");
      emit("    nm.nm_data = (rtm->snode_allocators + {});", snid);
      emit("    nm.mem_alloc = ma;");
      emit("    const auto amb_idx = rtm->ambient_indices[{}];", snid);
      emit("    rep_.init(addr, nm, amb_idx);");
    } else if (ty == SNodeType::root || ty == SNodeType::dense) {
      // `root`, `dense`
      emit("    rep_.init(addr);");
    } else {
      TI_UNREACHABLE;
    }
    emit("  }}\n");
  }

  void emit_snode_get_child_func(SNodeType ty, const std::string &ch_name) {
    emit("  {} children(int i) {{", ch_name);
    if (ty == SNodeType::pointer) {
      emit("    return {{rep_.child_or_ambient_addr(i)}};");
    } else {
      emit("    return {{rep_.addr() + (i * elem_stride)}};");
    }
    emit("  }}\n");
  }

  void emit_snode_activation_funcs(SNodeType ty) {
    emit("  inline bool is_active(int i) {{");
    emit("    return rep_.is_active(i);");
    emit("  }}\n");
    emit("  inline void activate(int i) {{");
    emit("    rep_.activate(i);");
    emit("  }}\n");
    if (ty == SNodeType::dynamic) {
      emit("  inline void deactivate() {{");
      emit("    rep_.deactivate();");
      emit("  }}\n");
    } else {
      emit("  inline void deactivate(int i) {{");
      emit("    rep_.deactivate(i);");
      emit("  }}\n");
    }
  }

  void generate_types(const SNode &snode) {
    if (snode.is_bit_level) {
      // Nothing to generate for bit-level SNodes -- they are part of their
      // parent's intrinsic memory.
      return;
    }
    const auto snty = snode.type;
    const bool is_place = snode.is_place();
    const bool should_gen_cell = !(is_place || (snty == SNodeType::bit_struct));
    if (should_gen_cell) {
      // "_ch" is a legacy word for child. The correct notion should be cell.
      // Generate {snode}_ch
      const std::string class_name = snode.node_type_name + "_ch";
      emit("class {} {{", class_name);
      emit(" public:");
      emit("  {}(device byte *a) : addr_(a) {{}}", class_name);

      std::string stride_str = "0";
      for (int i = 0; i < (int)snode.ch.size(); i++) {
        const auto &ch_node_name = snode.ch[i]->node_type_name;
        emit("  {} get{}(device Runtime *rtm, device MemoryAllocator *ma) {{",
             ch_node_name, i);
        emit("    return {{addr_ + ({}), rtm, ma}};", stride_str);
        stride_str += " + " + ch_node_name + "::stride";
        emit("  }}");
        emit("");
      }
      emit("  device byte *addr() {{ return addr_; }}");
      emit("");
      // Is it possible for this to have no children?
      emit("  constant static constexpr int stride = {};", stride_str);
      emit(" private:");
      emit("  device byte *addr_;");
      emit("}};");
    }
    emit("");
    const auto &node_name = snode.node_type_name;
    if (is_place) {
      const auto dt_name = metal_data_type_name(snode.dt);
      emit("struct {} {{", node_name);
      emit("  // place");
      emit("  constant static constexpr int stride = sizeof({});", dt_name);
      emit("");
      // `place` constructor
      emit("  {}(device byte *v, device Runtime *, device MemoryAllocator *)",
           node_name);
      emit("    : val((device {}*)v) {{}}", dt_name);
      emit("");
      emit("  device {} *val;", dt_name);
      emit("}};");
    } else if (snty == SNodeType::bit_struct) {
      // TODO: bit_struct and place share a lot in common.
      const auto dt_name = metal_data_type_name(DataType(snode.physical_type));
      emit("struct {} {{", node_name);
      emit("  // bit_struct");
      emit("  constant static constexpr int stride = sizeof({});", dt_name);
      emit("");
      // `bit_struct` constructor
      emit("  {}(device byte *b, device Runtime *, device MemoryAllocator *)",
           node_name);
      emit("    : base(b) {{}}");
      emit("");
      emit("  device byte *base;");
      emit("}};");
    } else if (snty == SNodeType::dense || snty == SNodeType::root ||
               snty == SNodeType::bitmasked || snty == SNodeType::dynamic ||
               snty == SNodeType::pointer) {
      const std::string ch_name = fmt::format("{}_ch", node_name);
      emit("struct {} {{", node_name);
      const auto snty_name = snode_type_name(snty);
      emit("  // {}", snty_name);
      const int64 n = snode.num_cells_per_container;
      // There's no assert in metal shading language yet so we have to warn
      // outside.
      if (n > std::numeric_limits<int>::max()) {
        TI_WARN(
            "{}: Snode index might be out of int32 boundary but int64 is not "
            "supported on metal backend.",
            node_name);
      }
      emit("  constant static constexpr int n = {};", n);
      emit_snode_stride(snty, ch_name, n);
      emit_snode_constructor(snode);
      emit_snode_get_child_func(snty, ch_name);
      emit_snode_activation_funcs(snty);
      if (snty == SNodeType::dynamic) {
        emit("  inline int append(int32_t data) {{");
        emit("    return rep_.append(data);");
        emit("  }}\n");
        emit("  inline int length() {{");
        emit("    return rep_.length();");
        emit("  }}\n");
      }
      emit(" private:");
      emit("  SNodeRep_{} rep_;", snty_name);
      emit("}};");
    } else {
      // We have checked the type support previously.
      TI_UNREACHABLE;
    }
    emit("");
  }

  size_t compute_snode_size(const SNode *sn) {
    if (sn->is_place()) {
      return metal_data_type_bytes(to_metal_type(sn->dt));
    }
    if (sn->is_bit_level) {
      // A bit-level SNode occupies a fration of a byte. Just return 0 here and
      // special handling the bit_* SNode containers.
      return 0;
    }
    const int n = sn->num_cells_per_container;
    size_t ch_size = 0;
    if (sn->type == SNodeType::bit_struct) {
      // The host side should have inferred all the necessary info of |sn|.
      TI_ASSERT(sn->physical_type != nullptr);
      ch_size = data_type_size(sn->physical_type);
      // |ch_size| should at least be 4 bytes on GPU. In addition, Metal:
      // 1. does not support 8-byte data types in the device address space.
      // 2. only supports 4-byte atomic integral types (or atomic_bool).
      TI_ERROR_IF(ch_size != 4,
                  "bit_struct physical type must be exactly 32 bits on Metal");
    } else {
      for (const auto &ch : sn->ch) {
        const size_t ch_offset = ch_size;
        const auto *ch_sn = ch.get();
        ch_size += compute_snode_size(ch_sn);
        if (!ch_sn->is_place()) {
          snode_descriptors_.find(ch_sn->id)->second.mem_offset_in_parent =
              ch_offset;
        }
      }
    }

    SNodeDescriptor sn_desc;
    sn_desc.snode = sn;
    sn_desc.element_stride = ch_size;
    sn_desc.num_slots = n;
    sn_desc.stride = ch_size * n;
    if (sn->type == SNodeType::bitmasked) {
      sn_desc.stride += bitmasks_stride(n);
    } else if (sn->type == SNodeType::dynamic) {
      sn_desc.stride += kAlignment;
    } else if (sn->type == SNodeType::pointer) {
      // A `pointer` SNode itself only stores pointers, not the actual data!
      sn_desc.stride = n * kNodeManagerElemIndexSize;
    }
    sn_desc.total_num_elems_from_root = 1;
    for (const auto &e : sn->extractors) {
      sn_desc.total_num_elems_from_root *= e.num_elements_from_root;
    }

    TI_ASSERT(snode_descriptors_.find(sn->id) == snode_descriptors_.end());
    snode_descriptors_[sn->id] = sn_desc;
    return sn_desc.stride;
  }

  template <typename... Args>
  void emit(std::string f, Args &&...args) {
    line_appender_.append(std::move(f), std::move(args)...);
  }

  std::vector<SNode *> snodes_;
  int max_snodes_{0};
  LineAppender line_appender_;
  std::unordered_map<int, SNodeDescriptor> snode_descriptors_;
  bool has_sparse_snode_{false};
};

class RuntimeModuleCompiler {
 public:
  CompiledRuntimeModule run() {
    CompiledRuntimeModule res;
    emit_runtime_structs();
    line_appender_.dump(&res.runtime_utils_source_code);
    res.rand_seeds_size = compute_rand_seeds_size();
    res.runtime_size = compute_snodes_runtime_size() + res.rand_seeds_size;
    return res;
  }

 private:
  void emit_runtime_structs() {
    line_appender_.append_raw(shaders::kMetalRuntimeStructsSourceCode);
    emit("");
    emit("struct Runtime {{");
    emit("  uint32_t rand_seeds[{}];", kNumRandSeeds);
    emit("  SNodeMeta snode_metas[{}];", kMaxNumSNodes);
    emit("  SNodeExtractors snode_extractors[{}];", kMaxNumSNodes);
    emit("  ListManagerData snode_lists[{}];", kMaxNumSNodes);
    emit("  NodeManagerData snode_allocators[{}];", kMaxNumSNodes);
    emit("  NodeManagerData::ElemIndex ambient_indices[{}];", kMaxNumSNodes);
    emit("}};");
    emit("");
    line_appender_.append_raw(shaders::kMetalRuntimeUtilsSourceCode);
    emit("");
    line_appender_.append_raw(shaders::kMetalSNodeBitPointerSourceCode);
    emit("");
  }

  size_t compute_snodes_runtime_size() {
    return kMaxNumSNodes *
           (kSNodeMetaSize + kSNodeExtractorsSize + kListManagerDataSize +
            kNodeManagerDataSize + kNodeManagerElemIndexSize);
  }

  size_t compute_rand_seeds_size() {
    return sizeof(uint32_t) * kNumRandSeeds;
  }

  template <typename... Args>
  void emit(std::string f, Args &&...args) {
    line_appender_.append(std::move(f), std::move(args)...);
  }

  LineAppender line_appender_;
};

}  // namespace

int SNodeDescriptor::total_num_self_from_root(
    const std::unordered_map<int, SNodeDescriptor> &sn_descs) const {
  if (snode->type == SNodeType::root) {
    return 1;
  }
  const auto *psn = snode->parent;
  TI_ASSERT(psn != nullptr);
  return sn_descs.find(psn->id)->second.total_num_elems_from_root;
}

int total_num_self_from_root(const SNodeDescriptorsMap &m, int snode_id) {
  return m.at(snode_id).total_num_self_from_root(m);
}

CompiledStructs compile_structs(SNode &root) {
  return StructCompiler().run(root);
}

CompiledRuntimeModule compile_runtime_module() {
  return RuntimeModuleCompiler{}.run();
}

}  // namespace metal
}  // namespace taichi::lang


text:
package io.vivarium.serialization;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

public class MapCollection implements Iterable<HashMap<String, Object>>
{
    private LinkedList<HashMap<String, Object>> _data;

    public MapCollection()
    {
        _data = new LinkedList<>();
    }

    public void addObject(HashMap<String, Object> obj)
    {
        _data.add(obj);
    }

    public boolean hasNext()
    {
        return _data.size() > 0;
    }

    public HashMap<String, Object> popNext()
    {
        return _data.removeLast();
    }

    @Override
    public String toString()
    {
        return _data.toString();
    }

    @Override
    public Iterator<HashMap<String, Object>> iterator()
    {
        return _data.iterator();
    }
}

redpajama_set_name: RedPajamaGithub


text:
var Fs, Path;

Fs = require('fs');

Path = require('path');

module.exports = function(robot) {
  var jsonFile, list;
  jsonFile = Path.resolve(__dirname, '../ritsuryokoku.json');
  list = JSON.parse(Fs.readFileSync(jsonFile, {
    encoding: 'utf-8'
  }));
  return robot.respond(/ritsuryokoku$/i, function(res) {
    var item;
    item = res.random(list);
    return res.send("" + item.name + " (" + item.roma + ")");
  });
};


text:
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#import <UIKit/UIKit.h>

#define ShakaSpacing 5
#define ShakaButtonSize 45

/** A category that adds helper methods for creating and activating NSLayoutConstraints. */
@interface NSObject (ShakaLayoutHelpers)

/** Applies constraints defined with VFL to views. */
- (NSArray<NSLayoutConstraint *> *)shaka_constraint:(NSString *)format
                                            onViews:(NSDictionary<NSString *, UIView *> *)views;

/** Applies constraints defined with VFL to views. Also applies a custom priority. */
- (NSArray<NSLayoutConstraint *> *)shaka_constraint:(NSString *)format
                                       withPriority:(UILayoutPriority)priority
                                            onViews:(NSDictionary<NSString *, UIView *> *)views;

/** Link two views together, making them have a given attribute be equal. */
- (NSLayoutConstraint *)shaka_equalConstraintForAttribute:(NSLayoutAttribute)attribute
                                                 fromItem:(UIView *)fromItem
                                                   toItem:(UIView *)toItem;

/**
 * Link two views together, making them have a given attribute be equal.
 * Also applies a custom priority.
 */
- (NSLayoutConstraint *)shaka_equalConstraintForAttribute:(NSLayoutAttribute)attribute
                                                 fromItem:(UIView *)fromItem
                                                   toItem:(UIView *)toItem
                                             withPriority:(UILayoutPriority)priority;

/**
 * Link two views together, making them have a given attribute have a given relation.
 * Also applies a custom priority.
 */
- (NSLayoutConstraint *)shaka_relationalConstraintForAttribute:(NSLayoutAttribute)attribute
                                                 fromItem:(UIView *)fromItem
                                                   toItem:(UIView *)toItem
                                                  withRelation:(NSLayoutRelation)relation
                                             withPriority:(UILayoutPriority)priority;

@end


text:
package stormapplied.creditcard.topology;

import backtype.storm.task.TopologyContext;
import backtype.storm.topology.BasicOutputCollector;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseBasicBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import stormapplied.creditcard.Order;
import stormapplied.creditcard.services.AuthorizationService;
import stormapplied.creditcard.services.OrderDao;

import java.util.Map;

public class AuthorizeCreditCard extends BaseBasicBolt {
  private AuthorizationService authorizationService;
  private OrderDao orderDao;

  @Override
  public void prepare(Map config,
                      TopologyContext context) {
    orderDao = new OrderDao();
    authorizationService = new AuthorizationService();
  }

  @Override
  public void declareOutputFields(OutputFieldsDeclarer declarer) {
    declarer.declare(new Fields("order"));
  }

  @Override
  public void execute(Tuple tuple,
                      BasicOutputCollector outputCollector) {
    Order order = (Order) tuple.getValueByField("order");
    boolean isAuthorized = authorizationService.authorize(order);
    if (isAuthorized) {
      orderDao.updateStatusToReadyToShip(order);
    } else {
      orderDao.updateStatusToDenied(order);
    }
    outputCollector.emit(new Values(order));
  }
}


text:
class WorldLocation
  def self.all
    data = Rails.cache.fetch("all", expires_in: 1.day) do
      Services.worldwide_api.world_locations.with_subsequent_pages.to_a
    end

    data
      .select { |l| l["format"] == "World location" && l.dig("details", "slug").present? }
      .map { |location_data| new(location_data) }
  end

  def self.find(location_slug)
    data = Rails.cache.fetch("find_#{location_slug}", expires_in: 1.day) do
      Services
        .worldwide_api
        .world_location(location_slug)
        .parsed_content
    end

    new(data)
  end

  def initialize(data)
    @data = data
  end

  def ==(other)
    other.is_a?(self.class) && other.slug == slug
  end

  def slug
    @data["details"]["slug"]
  end

  def title
    @data["title"]
  end
end


text:
#ifndef VGA_RAST_BITMAP_1_H
#define VGA_RAST_BITMAP_1_H

#include <atomic>
#include <cstdint>

#include "vga/bitmap.h"
#include "vga/rasterizer.h"
#include "vga/graphics_1.h"

namespace vga {
namespace rast {

class Bitmap_1 : public Rasterizer {
public:
  /*
   * Creates a 1bpp bitmap rasterizer with the given width, height, and
   * optional offset.
   */
  Bitmap_1(unsigned width, unsigned height, unsigned top_line = 0);

  /*
   * Creates a 1bpp bitmap rasterizer with the given width, height, background
   * image, and optional offset.
   */
  Bitmap_1(unsigned width, unsigned height, Pixel const * background,
           unsigned top_line = 0);

  ~Bitmap_1();

  RasterInfo rasterize(unsigned, unsigned, Pixel *) override;

  Bitmap get_bg_bitmap() const;
  Graphics1 make_bg_graphics() const;

  /*
   * Flips the display pages at the next vblank.
   */
  void pend_flip();

  /*
   * Flips the display pages right fricking now.
   */
  void flip_now();

  void set_fg_color(Pixel);
  void set_bg_color(Pixel);

  std::uint32_t *get_fg_buffer() const { return _fb[_page1]; }
  std::uint32_t *get_bg_buffer() const { return _fb[!_page1]; }

  bool can_fg_use_bitband() const;
  bool can_bg_use_bitband() const;
  void copy_bg_to_fg() const;

private:
  unsigned _lines;
  unsigned _words_per_line;
  unsigned _top_line;
  bool _page1;
  std::atomic<bool> _flip_pended;
  Pixel _clut[2];
  std::uint32_t *_fb[2];
  Pixel const * _background;
};

}  // namespace rast
}  // namespace vga

#endif  // VGA_RAST_BITMAP_1_H


text:
package com.jogl.engine.utils.io;

import java.io.*;
import java.util.ArrayList;

public class JoglFileInputStream extends FileInputStream {
    protected static final StringBuilder tempBuffer = new StringBuilder();
    private long baseFileOffset;
    private String currentLabel = null;
    private int currentLabelIndex = -1;
    private final ArrayList<String> labelTable = new ArrayList<>();
    private PrintStream parserDescriptionOutStream;
    private final byte[] temp4byteArray = new byte[4];

    private final static int INT = 0;
    private final static int STRING_FIXED = 1;
    private final static int FLOAT = 2;
    private final static int STRING_NULL_TERMINATED = 3;
    private final static int SKIP = 4;
    private final static int SHORT = 5;
    private final static int LONG = 6;
    private final static int BYTE = 7;
    private File descriptionFile;

    public void setCurrentLabel(String currentLabel) {
        if (parserDescriptionOutStream != null) {
            this.currentLabel = currentLabel;
            currentLabelIndex = getOrCreateLabelIndex(currentLabel);
        }
    }

    public void storeFileParsingDescriptionInfo(File file) throws FileNotFoundException, IOException {
        descriptionFile = file;
        file.delete();
        parserDescriptionOutStream = new PrintStream(file);
        parserDescriptionOutStream.write(intToByteArray(0));
    }

    public void closeFileParsingDescriptionInfo() throws FileNotFoundException, IOException {
        parserDescriptionOutStream.close();
        int offsetToStringTable = (int) descriptionFile.length();
        try (RandomAccessFile stream = new RandomAccessFile(descriptionFile, "rw")) {
            stream.seek(offsetToStringTable);
            for (int i = 0; i < labelTable.size(); i++) {
                String label = labelTable.get(i);
                stream.writeInt(label.length());
                stream.write(label.getBytes());
            }
            stream.seek(0);
            stream.writeInt(offsetToStringTable);
        }
    }

    private int getOrCreateLabelIndex(String label) {
        for (int i = 0; i < labelTable.size(); i++) {
            if (labelTable.get(i).equals(label)) {
                return i;
            }
        }

        labelTable.add(label);
        return labelTable.size() - 1;
    }

    private void saveParsingChunk(int offset, int type, int size) throws IOException {
        if (parserDescriptionOutStream != null) {
            parserDescriptionOutStream.write(intToByteArray(currentLabelIndex));
            parserDescriptionOutStream.write(intToByteArray(offset));
            parserDescriptionOutStream.write(intToByteArray(size));
            parserDescriptionOutStream.write(intToByteArray(type));
        }
    }

    private void saveParsingChunk(int type, int size) throws IOException {
        if (parserDescriptionOutStream != null) {
            int offset = (int) getChannel().position();
            saveParsingChunk(offset, type, size);
        }
    }

    public byte[] intToByteArray(int value) {
        temp4byteArray[0] = (byte) (value >>> 24);
        temp4byteArray[1] = (byte) (value >>> 16);
        temp4byteArray[2] = (byte) (value >>> 8);
        temp4byteArray[3] = (byte) (value);
        return temp4byteArray;
    }

    public JoglFileInputStream(File file) throws FileNotFoundException {
        super(file);
    }

    public void rememberFileOffset() throws IOException {
        baseFileOffset = getChannel().position();
    }

    public int getAbsolutePosition() throws IOException {
        return (int) getChannel().position();
    }

    public void setAbsolutePosition(int pos) throws IOException {
        getChannel().position(baseFileOffset + pos);
    }

    public void setRelativePosition(int pos) throws IOException {
        long position = getChannel().position();
        getChannel().position(position + pos);
    }

    public String readTabEndedString() throws IOException {
        while (true) {
            int value = read();
            if (value == 0) {
                return null;
            }
            if (value == '\t') {
                String result = tempBuffer.toString();
                tempBuffer.setLength(0);
                return result;
            }

            tempBuffer.append((char) value);
        }
    }

    public String readNullTerminatedString(String label) throws IOException {
        setCurrentLabel(label);
        return readNullTerminatedString();
    }

    public String readNullTerminatedString() throws IOException {
        int offset = 0;
        if (parserDescriptionOutStream != null) {
            offset = (int) getChannel().position();
        }

        int readCount = 0;
        while (true) {
            int value = read();
            readCount++;
            if (value == -1) {
                tempBuffer.setLength(0);
                return null;
            }

            if (value == 0) {
                String result = tempBuffer.toString();
                tempBuffer.setLength(0);
                saveParsingChunk(offset, STRING_NULL_TERMINATED, readCount);
                return result;
            }

            tempBuffer.append((char) value);
        }
    }

    public void readBytes(byte[] buffer, String label) throws IOException {
        setCurrentLabel(label);
        saveParsingChunk(BYTE, buffer.length);
        read(buffer);
    }

    public void readBytes(byte[] buffer) throws IOException {
        read(buffer);
    }

    public String readString(int count, String label) throws IOException {
        setCurrentLabel(label);
        return readString(count);
    }

    public String readString(int count) throws IOException {
        saveParsingChunk(STRING_FIXED, count);
        for (int i = 0; i < count; i++) {
            int value = read();
            if (value == 0) {

            } else {
                tempBuffer.append((char) value);
            }

        }
        String result = tempBuffer.toString();
        tempBuffer.setLength(0);

        return result;
    }

    public int readInt(String label) throws IOException {
        setCurrentLabel(label);
        saveParsingChunk(INT, 4);
        return (read() & 0xFF) | ((read() & 0xFF) << 8) | ((read() & 0xFF) << 16) | ((read() & 0xFF) << 24);
    }

    public int readInt() throws IOException {
        saveParsingChunk(INT, 4);
        return (read() & 0xFF) | ((read() & 0xFF) << 8) | ((read() & 0xFF) << 16) | ((read() & 0xFF) << 24);
    }

    public float[] readVector3() throws IOException {
        return readFloatArray(3);
    }

    public float[] readFloatArray(int size) throws IOException {
        float[] vector = new float[size];
        for (int i = 0; i < size; i++) {
            vector[i] = readFloat();
        }
        return vector;
    }

    public float readFloat(String label) throws IOException {
        setCurrentLabel(label);
        return readFloat();
    }

    public float readFloat() throws IOException {
        saveParsingChunk(FLOAT, 4);
        int value = (read() & 0xFF) | ((read() & 0xFF) << 8) | ((read() & 0xFF) << 16) | ((read() & 0xFF) << 24);
        return Float.intBitsToFloat(value);
    }

    public long readLong(String label) throws IOException {
        setCurrentLabel(label);
        return readLong();
    }

    public long readLong() throws IOException {
        saveParsingChunk(LONG, 8);
        return (read() & 0xFF) | ((read() & 0xFF) << 8)
                | ((read() & 0xFF) << 16) | ((read() & 0xFF) << 24)
                | ((((long) read() & 0xFF)) << 32) | ((((long) read() & 0xFF)) << 40)
                | ((((long) read() & 0xFF)) << 48) | ((((long) read() & 0xFF)) << 56);
    }

    public short readShort(String label) throws IOException {
        setCurrentLabel(label);
        return readShort();
    }

    public short readShort() throws IOException {
        saveParsingChunk(SHORT, 2);
        getAbsolutePosition();
        return (short) ((read() & 0xFF) | ((read() & 0xFF) << 8));
    }

    public int readByte(String label) throws IOException {
        setCurrentLabel(label);
        return readByte();
    }

    public int readByte() throws IOException {
        saveParsingChunk(BYTE, 1);
        return read();
    }

    public ArraySizeAndOffset readArraySizeAndOffset() throws IOException {
        int offset = readInt();
        int usedCount = readInt();
        skipBytes(4);
        return new ArraySizeAndOffset(offset, usedCount);
    }

    public ArraySizeAndOffset readArraySizeAndOffset(String label) throws IOException {
        int offset = readInt(label + "ArrayOffset");
        int usedCount = readInt(label + "ArrayCount");
        skipBytes(4, label + "ArrayOffsetCountSkip");
        return new ArraySizeAndOffset(offset, usedCount);
    }

    public void skipBytes(int count, String label) throws IOException {
        setCurrentLabel(label);
        skipBytes(count);
    }

    public void skipBytes(int count) throws IOException {
        saveParsingChunk(SKIP, count);
        skip(count);
    }

    public class ArraySizeAndOffset {
        private final int offset;
        private final int count;

        public ArraySizeAndOffset(int offset, int count) {
            this.offset = offset;
            this.count = count;
        }

        public int getCount() {
            return count;
        }

        public int getOffset() {
            return offset;
        }

        @Override
        public String toString() {
            return "Count=" + count + " Offset=" + offset;
        }
    }
}


text:
<?php
namespace DataFixtures\ORM;

use Entity\RoleInfoTranslation;

use Entity\RoleInfo;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

use Entity\UserAuth;
use Entity\User;

/**
 * Load user data fixtures
 *
 * @author jignesh <jignesh.dadhaniya@vendev.in>
 *
 */
class LoadUserRolesData extends AbstractFixture implements OrderedFixtureInterface, FixtureInterface, ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * {@inheritDoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $roleInfo = new RoleInfo();
        $roleInfo->setName('ROLE_ADMIN');
        $roleInfo->setDisplayName('Admin');
        $roleInfo->setType('A');
        $roleInfo->addTranslation(new RoleInfoTranslation('de_DE', 'displayName', 'Admin-at'));
        $roleInfo->addTranslation(new RoleInfoTranslation('en_GB', 'displayName', 'Admin'));

        $roleInfoPrv = new RoleInfo();
        $roleInfoPrv->setName('ROLE_PRIVATE');
        $roleInfoPrv->setDisplayName('Private');
        $roleInfoPrv->setType('C');
        $roleInfoPrv->addTranslation(new RoleInfoTranslation('de_DE', 'displayName', 'Private-at'));
        $roleInfoPrv->addTranslation(new RoleInfoTranslation('en_GB', 'displayName', 'Private'));

        $roleInfoCmp = new RoleInfo();
        $roleInfoCmp->setName('ROLE_COMPANY');
        $roleInfoCmp->setDisplayName('Company');
        $roleInfoCmp->setType('C');
        $roleInfoCmp->addTranslation(new RoleInfoTranslation('de_DE', 'displayName', 'Company-at'));
        $roleInfoCmp->addTranslation(new RoleInfoTranslation('en_GB', 'displayName', 'Company'));

        $manager->persist($roleInfo);
        $manager->persist($roleInfoPrv);
        $manager->persist($roleInfoCmp);

        $manager->flush();

        $this->addReference('ROLE_ADMIN', $roleInfo);
        $this->addReference('ROLE_PRIVATE', $roleInfoPrv);
        $this->addReference('ROLE_COMPANY', $roleInfoCmp);
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 2; // the order in which fixtures will be loaded
    }
}


text:
id: 4565
title: Cimbalino Toolkit 2.2.0
date: 2016-04-05T16:12:33+00:00
author: Pedro Lamas
layout: post
guid: https://www.pedrolamas.com/?p=4565
permalink: /2016/04/05/cimbalino-toolkit-2-2-0/
dsq_thread_id:
  - '4722246581'
image: /wp-content/uploads/2014/06/Cimbalino.Toolkit@4x-400x270.png
categories:
  - Windows
  - Windows Phone
tags:
  - Cimbalino
  - UWP
  - Windows
  - Windows 10
  - Windows Phone
  - WPDev
---

**Update: there was a packaging error in 2.2.0 which I already fixed and so the most current version is now 2.2.1!**

[**Cimbalino Toolkit**](http://cimbalino.org/) version 2.2.0 is now available!

This new version includes improved support for Windows Phone Silverlight 8.1 (WP81) so that developers can take advantage of its specific API's (such as the [FileOpenPicker](https://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.pickers.fileopenpicker.aspx))

This brings the total number of supported platforms to 5:

- Windows Phone Silverlight 8.0 apps (WP8)
- Windows Phone Silverlight 8.1 apps (WP81)
- Windows Phone 8.1 apps (WPA81)
- Windows Store 8.1 apps (Win81)
- Windows 10 UWP apps (UAP)

Here's the full change log for version 2.0.0:

- Improved compatibility with Windows Phone Silverlight 8.1 (WP81)
- New [Cimbalino.Toolkit.Controls](https://www.nuget.org/packages/Cimbalino.Toolkit.Controls) library (includes the [HamburgerFrame for Windows 10](/2016/03/07/cimbalino-toolkit-hamburger-controls-for-uwp/))
- New IFilePickerService to handle the file picker (when available)
- Improvements over the INavigationService implementation
- Other fixes and improvements


text:
- Upgrade "tar" dev dependency because of a vulnerability

## 1.6.1
- Update release script : no need to pass a "v" before version number when releasing

## 1.6.0
**technical improvements**
- Support Node 10
- Upgrade Gulp to v4

## 1.5.0
**security improvements**
- Remove unused 'moment' depencency

## 1.4.0
**security improvements**
- Fix version of 'event-stream' to 3.3.4

## 1.3.0
**features**
- Remove react-validation dependency

## 1.2.2
**features**
- Add release script

## 1.2.0
**features**
- Add "autoSelectOnBlur" prop

## 1.1.1
**bug fixes**
- Fix issue ("noResultsText" can now be passed either by config or by props)

## 1.1.0
**features**
- Add a Configuration.js file

## 1.0.0
- Initialization


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

namespace Azure.ResourceManager.Network.Models
{
    public partial class VirtualHubRouteTable : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsCollectionDefined(Routes))
            {
                writer.WritePropertyName("routes");
                writer.WriteStartArray();
                foreach (var item in Routes)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
        }

        internal static VirtualHubRouteTable DeserializeVirtualHubRouteTable(JsonElement element)
        {
            Optional<IList<VirtualHubRoute>> routes = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("routes"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<VirtualHubRoute> array = new List<VirtualHubRoute>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(VirtualHubRoute.DeserializeVirtualHubRoute(item));
                    }
                    routes = array;
                    continue;
                }
            }
            return new VirtualHubRouteTable(Optional.ToList(routes));
        }
    }
}


text:
package com.evolveum.midpoint.web.component.data;

import com.evolveum.midpoint.web.component.data.column.CheckBoxHeaderColumn;
import com.evolveum.midpoint.web.component.data.column.CheckBoxPanel;
import com.evolveum.midpoint.web.component.util.Selectable;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxCallListener;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;

import java.util.List;

public class SelectableDataTable<T> extends DataTable<T, String> {

    public SelectableDataTable(String id, List<IColumn<T, String>> columns, IDataProvider<T> dataProvider, int rowsPerPage) {
        super(id, columns, dataProvider, rowsPerPage);
    }

    @Override
    protected Item<T> newRowItem(String id, int index, final IModel<T> model) {
        final Item<T> rowItem = new SelectableRowItem<T>(id, index, model);

        rowItem.setOutputMarkupId(true);

//        rowItem.add(new AttributeAppender("class", new AbstractReadOnlyModel<String>() {
//
//            @Override
//            public String getObject() {
//                T object = rowItem.getModel().getObject();
//                if (!(object instanceof Selectable)) {
//                    return "";
//                }
//
//                Selectable selectable = (Selectable) object;
//                return selectable.isSelected() ? "selectedRow" : "";
//            }
//        }));
//
//        rowItem.add(new AjaxEventBehavior("onclick") {
//
//            @Override
//            protected void onEvent(AjaxRequestTarget target) {
//                T object = rowItem.getModel().getObject();
//                if (!(object instanceof Selectable)) {
//                    return;
//                }
//
//                Selectable selectable = (Selectable) object;
//                selectable.setSelected(!selectable.isSelected());
//
//                //update table row
//                target.add(rowItem);
//                //update checkbox header column, if we found some
//                CheckBoxPanel headerCheck = CheckBoxHeaderColumn.findCheckBoxColumnHeader(SelectableDataTable.this);
//                if (headerCheck == null) {
//                    return;
//                }
//
//                headerCheck.getPanelComponent().setModelObject(
//                        CheckBoxHeaderColumn.shoulBeHeaderSelected(SelectableDataTable.this));
//                target.add(headerCheck);
//            }
//
//            @Override
//            protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
//                super.updateAjaxAttributes(attributes);
//
//                attributes.getAjaxCallListeners().add(
//                        new AjaxCallListener().onPrecondition("return !dropClickEvent(attrs);"));
//            }
//        });

        return rowItem;
    }

    public static class SelectableRowItem<T> extends Item<T> {

        public SelectableRowItem(String id, int index, IModel<T> model) {
            super(id, index, model);
        }
    }
}


text:
class ARQLVM

    def initialize(ns = nil)
        @ns = ns
        @stack = []
        @current_model = nil
    end

    def select_model(model_name)
        if @ns.nil?
            false
        else
            @stack << @ns.lookup(model_name)[:class_name]
        end
    end

    def filter(&filter_expr)
        top_elem = @stack.pop

        if top_elem.nil?
            raise "Can not apply filter to an empty stack"
        elsif top_elem.is_a? Enumerable
            @stack << top_elem.find_all(&filter_expr)
        elsif top_elem.is_a? Class and top_elem.ancestors.member? ActiveRecordBaseProxy
            @stack << top_elem.all.find_all(&filter_expr)
        else
            raise "Can not apply filter to #{top_elem.class}"
        end
    end

    # Takes a class from the top of the stack and attempts to find an element of
    # that class with the id of itemid and push the result back to the top of the
    # stack.
    # Will raise an error if the stack was empty.
    def lookup(itemid)
        model = pop

        if model.nil?
            raise "No model selected"
        else
            item = model.find(itemid.to_i)

            push item
        end
    end

    def push(*elem)
        @stack.push *elem
    end

    def pop(n = nil)
        if n.nil?
            @stack.pop
        else
            @stack.pop(n)
        end
    end

    # Duplicates the top element on the stack
    def dup
        push @stack.last unless @stack.last.nil?
    end

    # Applies the top N arguments from the stack to the passed function where N is the function's arity
    def apply(&function)
        n = function.arity
        items = pop(n)
        push(function.call(*items))
    end

    # Indicates whether the current VM stack is empty
    def empty?
        @stack.empty?
    end

    def dump_stack!
        puts "Stack size: #{@stack.length}"
        @stack.reverse.each { |item| puts "  #{item.class} @ #{item.to_s[0..64]}" }
    end

    def size
        @stack.length
    end
end


text:
@import url('https://fonts.googleapis.com/css?family=Marvel:400,700');

html {
  box-sizing: border-box;
}

*, *:before, *:after {
  box-sizing: inherit;
}


text:
DropText
========
The text editor for iOS synchronizing with Dropbox.

# Feature

- Create folders and text files and synchronise with Dropbox.
	- If you create folders or text files on a PC or Mac, those are shown up on the app.
	- If you edit files, those will be reflected on the app.
- The file written in Markdown(.md or .markdown), can be previewed as a formatted document.
- An advertisement is shown on bottom of the app, but you can remove by paying 2$.


text:
@interface UIButton (Gradient)

-(void)applyGradient;
-(void)applyRedGradient;

@end


text:
<TITLE>Review for BASEketball (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

BASEketball (1998)

reviewed by
James Sanford

        If Universal Pictures really wanted viewers to properly
appreciate ``BASEketball'' the studio should have furnished each
ticket-buyer with a free six-pack. This proud-to-be-stupid comedy,
which unites the creators of ``South Park'' and one of the men behind
the ``Naked Gun'' series, is is the type of movie designed to be
watched in a bar, at a frat house, or after a party.  Putting it in an
alcohol-free theatrical setting makes about as much sense as packing a
suitcase for your trip to Nudestock.

  With its consistently raunchy tone ``BASEketball'' can't
help but invite comparisons to ``There's Something About Mary,'' the
hit that's taken low-brow humor to new heights. Though ``BASEketball''
cheerfully pours on one gross-out after another - a guy drinks from a
bidet, clueless heroes Coop (Trey Parker) and Remer (Matt Stone) knock
back tequila with an 8-year-old boy, a character discovers a woman's
hair stuck between his teeth - nothing here approaches the sick genius
of the ``hair gel'' scene in ``Mary.''

  But two points for trying. Stone and Parker may not be
actors, but they'll do anything to get a reaction or to spice up the
movie's so-called plot. The story involves Coop and Remer's attempts
to save their newly created sport from the clutches of villains Cain
(Robert Vaughn) and curvy black-widow Yvette (Jenny McCarthy, who has
very little screen time and almost nothing to do).

  Unsurprisingly, the best laughs in ``BASEketball'' have
nothing to do with the central story, such as when earnest Yasmine
Bleeth asks that the kids she cares for be referred to as
``health-challenged or life-impaired'' rather than terminally ill.

  Writer-director David Zucker crams as much verbal and visual
humor in each shot as possible - watch the background action carefully
- in an effort to amuse or offend as frequently as possible. The
biggest joke of all, however, may be Zucker's claim in the press
information that the film is based on a true story. Now that is funny.

James Sanford

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package org.rosuda.JRclient;

// JRclient library - client interface to Rserve, see http://www.rosuda.org/Rserve/
// Copyright (C) 2004 Simon Urbanek
// --- for licensing information see LICENSE file in the original JRclient distribution ---

import java.io.*;

/** RFileInputStream is an {@link InputStream} to transfer files
    from Rserve server to the client. It is used very much like
    a {@link FileInputStream}. Currently mark and seek is not supported.
    The current implementation is also "one-shot" only, that means the file
    can be read only once.
    @version $Id: RFileInputStream.java 1330 2005-01-24 18:25:42Z urbaneks $
*/
public class RFileInputStream extends InputStream {
    /** Rtalk class to use for communication with the Rserve */
    Rtalk rt;
    /** set to true when {@link #close} was called.
	Any subsequent read requests on closed stream  result in an
	{@link IOException} or error result */
    boolean closed;
    /** set to true once EOF is reached - or more specifically
	the first time remore fread returns OK and 0 bytes */
    boolean eof;

    /** tries to open file on the R server, using specified {@link Rtalk} object
	and filename. Be aware that the filename has to be specified in host
	format (which is usually unix). In general you should not use directories
	since Rserve provides an own directory for every connection. Future Rserve
	servers may even strip all directory navigation characters for security
	purposes. Therefore only filenames without path specification are considered
	valid, the behavior in respect to absolute paths in filenames is undefined. */
    RFileInputStream(Rtalk rti, String fn) throws IOException {
	rt=rti;
	Rpacket rp=rt.request(Rtalk.CMD_openFile,fn);
	if (rp==null || !rp.isOk())
	    throw new IOException((rp==null)?"Connection to Rserve failed":("Request return code: "+rp.getStat()));
	closed=false; eof=false;
    }

    /** reads one byte from the file. This function should be avoided, since
	{@link RFileInputStream} provides no buffering. This means that each
	call to this function leads to a complete packet exchange between
	the server and the client. Use {@link #read(byte[],int,int)} instead
	whenever possible. In fact this function calls #read(b,0,1).
	@return -1 on any failure, or the acquired byte (0..255) on success */
    public int read() throws IOException {
	byte[] b=new byte[1];
	if (read(b,0,1)<1) return -1;
	return b[0];
    }

    /** Reads specified number of bytes (or less) from the remote file.
	@param b buffer to store the read bytes
	@param off offset where to strat filling the buffer
	@param len maximal number of bytes to read
	@return number of bytes read or -1 if EOF reached
    */
    public int read(byte[] b, int off, int len) throws IOException {
	if (closed) throw new IOException("File is not open");
	if (eof) return -1;
	Rpacket rp=rt.request(Rtalk.CMD_readFile,len);
	if (rp==null || !rp.isOk())
	    throw new IOException((rp==null)?"Connection to Rserve failed":("Request return code: "+rp.getStat()));
	byte[] rd=rp.getCont();
	if (rd==null) {
	    eof=true;
	    return -1;
	};
	int i=0;
	while(i<rd.length) { b[off+i]=rd[i]; i++; };
	return rd.length;
    }

    /** close stream - is not related to the actual Rconnection, calling
	close does not close the Rconnection
    */
    public void close() throws IOException {
	Rpacket rp=rt.request(Rtalk.CMD_closeFile,(byte[])null);
	if (rp==null || !rp.isOk())
	    throw new IOException((rp==null)?"Connection to Rserve failed":("Request return code: "+rp.getStat()));
	closed=true;
    }
}


text:
import { DangerContext } from "./Dangerfile"
import { CISource } from "../ci_source/ci_source"
import { Platform, Comment } from "../platforms/platform"
import {
  inlineResults,
  regularResults,
  mergeResults,
  DangerResults,
  DangerInlineResults,
  resultsIntoInlineResults,
  emptyDangerResults,
  inlineResultsIntoResults,
  sortResults,
  sortInlineResults,
  validateResults,
  isEmptyResults,
} from "../dsl/DangerResults"
import {
  template as githubResultsTemplate,
  inlineTemplate as githubResultsInlineTemplate,
  fileLineToString,
  messageForResultWithIssues as githubMessageForResultWithIssues,
} from "./templates/githubIssueTemplate"
import {
  template as bitbucketServerTemplate,
  inlineTemplate as bitbucketServerInlineTemplate,
  messageForResultWithIssues as bitbucketMessageForResultWithIssues,
} from "./templates/bitbucketServerTemplate"
import {
  template as bitbucketCloudTemplate,
  inlineTemplate as bitbucketCloudInlineTemplate,
  messageForResultWithIssues as bitbucketCloudMessageForResultWithIssues,
} from "./templates/bitbucketCloudTemplate"
import exceptionRaisedTemplate from "./templates/exceptionRaisedTemplate"

import { debug } from "../debug"
import chalk from "chalk"
import { sentence, href, compliment } from "./DangerUtils"
import { DangerRunner } from "./runners/runner"
import { GitDSL } from "../dsl/GitDSL"
import { DangerDSL } from "../dsl/DangerDSL"
import { emptyGitJSON } from "../platforms/github/GitHubGit"
import { writeFileSync } from "fs"

export interface ExecutorOptions {
  /** Should we do a text-only run? E.g. skipping comments */
  stdoutOnly: boolean
  /** Should the output be submitted as a JSON string? */
  jsonOnly: boolean
  /** Should Danger post as much info as possible */
  verbose: boolean
  /** A unique ID to handle multiple Danger runs */
  dangerID: string
  /** Don't send the entire JSON via STDIN, instead store it in tmp, and give the paths */
  passURLForDSL: boolean
  /** Disable Checks support in GitHub */
  disableGitHubChecksSupport?: boolean
  /** Fail if danger report contains failures */
  failOnErrors?: boolean
  /** Dont add danger check to PR */
  noPublishCheck?: boolean
  /** Ignore inline-comments that are in lines which were not changed */
  ignoreOutOfDiffComments: boolean
  /** Makes Danger post a new comment instead of editing its previous one */
  newComment?: boolean
  /** Removes all previous comment and create a new one in the end of the list */
  removePreviousComments?: boolean
}
// This is still badly named, maybe it really should just be runner?

const isTests = typeof jest === "object"

interface ExitCodeContainer {
  exitCode?: number
}

export class Executor {
  private readonly d = debug("executor")
  private readonly log = isTests ? () => "" : console.log
  private readonly logErr = isTests ? () => "" : console.error

  constructor(
    public readonly ciSource: CISource,
    public readonly platform: Platform,
    public readonly runner: DangerRunner,
    public readonly options: ExecutorOptions,
    public readonly process: ExitCodeContainer
  ) {}

  /**
   *  Runs all of the operations for a running just Danger
   * @param {string} file the filepath to the Dangerfile
   * @returns {Promise<DangerResults>} The results of the Danger run
   */

  async runDanger(file: string, runtime: DangerContext) {
    let results = {} as DangerResults

    // If an eval of the Dangerfile fails, we should generate a
    // message that can go back to the CI
    try {
      results = await this.runner.runDangerfileEnvironment([file], [undefined], runtime)
    } catch (error) {
      results = this.resultsForError(error as Error)
    }

    await this.handleResults(results, runtime.danger.git)
    return results
  }

  /**
   * Sets up all the related objects for running the Dangerfile
   * @returns {void} It's a promise, so a void promise
   */
  async dslForDanger(): Promise<DangerDSL> {
    // This checks if the CI source, and the platform support running on
    // an event that's not a PR
    const useSimpleDSL = this.platform.getPlatformReviewSimpleRepresentation && this.ciSource.useEventDSL
    this.d("Using full Danger DSL:", !useSimpleDSL)

    // Can't use the API to grab git metadata
    const git = useSimpleDSL ? emptyGitJSON() : await this.platform.getPlatformGitRepresentation()

    const getDSLFunc = useSimpleDSL
      ? this.platform.getPlatformReviewSimpleRepresentation
      : this.platform.getPlatformReviewDSLRepresentation

    const platformDSL = await getDSLFunc!()

    const utils = { sentence, href }
    return new DangerDSL(platformDSL, git, utils, this.platform.name)
  }

  /**
   * Handle the message aspects of running a Dangerfile
   *
   * @param {DangerResults} results a JSON representation of the end-state for a Danger run
   */
  async handleResults(results: DangerResults, git?: GitDSL) {
    this.d("Got results back:", results)
    if (!results) {
      throw new Error(
        "Got no results back from the Dangerfile evaluation, this is likely an issue with a custom sub-process exiting early."
      )
    }
    validateResults(results)

    this.d(`Evaluator settings`, this.options)

    if (this.options.stdoutOnly || this.options.jsonOnly || (this.ciSource && this.ciSource.useEventDSL)) {
      await this.handleResultsPostingToSTDOUT(results)
    } else {
      await this.handleResultsPostingToPlatform(results, git)
    }

    if (this.options.failOnErrors && results.fails.length > 0) {
      this.process.exitCode = 1
    }
  }
  /**
   * Handle showing results inside the shell.
   *
   * @param {DangerResults} results a JSON representation of the end-state for a Danger run
   */
  async handleResultsPostingToSTDOUT(results: DangerResults) {
    const { fails, warnings, messages, markdowns } = results
    if (this.options.jsonOnly) {
      // Format for Danger Process
      const results = {
        fails,
        warnings,
        messages,
        markdowns,
      }
      process.stdout.write(JSON.stringify(results, null, 2))
    } else {
      this.d("Writing to STDOUT:", results)
      // Human-readable format

      const tick = chalk.bold.greenBright("✓")
      const cross = chalk.bold.redBright("ⅹ")
      let output = ""

      if (fails.length > 0) {
        const s = fails.length === 1 ? "" : "s"
        const are = fails.length === 1 ? "is" : "are"
        const message = chalk.underline.red("Failing the build")
        output = `Danger: ${cross} ${message}, there ${are} ${fails.length} fail${s}.`
      } else if (warnings.length > 0) {
        const message = chalk.underline("not failing the build")
        output = `Danger: ${tick} found only warnings, ${message}`
      } else if (messages.length > 0) {
        output = `Danger: ${tick} passed, found only messages.`
      } else if (!messages.length && !fails.length && !messages.length && !warnings.length) {
        output = `Danger: ${tick} passed review, received no feedback.`
      }

      const allMessages = [...fails, ...warnings, ...messages, ...markdowns].map((m) => m.message)
      const oneMessage = allMessages.join("\n")
      const longMessage = oneMessage.split("\n").length > 30

      // For a short message, show the log at the top
      if (!longMessage) {
        // An empty blank line for visual spacing
        this.log(output)
      }

      const table = [
        fails.length && { name: "Failures", messages: fails.map((f) => f.message) },
        warnings.length && { name: "Warnings", messages: warnings.map((w) => w.message) },
        messages.length && { name: "Messages", messages: messages.map((m) => m.message) },
        markdowns.length && { name: "Markdowns", messages: markdowns.map((m) => m.message) },
      ].filter((r) => r !== 0) as { name: string; messages: string[] }[]

      // Consider looking at getting the terminal width, and making it 60%
      // if over a particular size

      table.forEach((row) => {
        this.log(`## ${chalk.bold(row.name)}`)
        this.log(row.messages.join(chalk.bold("\n-\n")))
      })

      // For a long message show the results at the bottom
      if (longMessage) {
        this.log("")
        this.log(output)
      }

      // An empty blank line for visual spacing
      this.log("")
    }
  }

  /**
   * Handle showing results inside a code review platform
   *
   * @param {DangerResults} results a JSON representation of the end-state for a Danger run
   * @param {GitDSL} git a reference to a git implementation so that inline comments find diffs to work with
   */
  async handleResultsPostingToPlatform(originalResults: DangerResults, git?: GitDSL) {
    // Allow a platform to say "I can do something special with this" - the example case for this
    // is the GitHub Checks API. It doesn't have an API that feels like commenting, so
    // it allows transforming the results after doing its work.
    let results = originalResults
    if (this.platform.platformResultsPreMapper) {
      this.d("Running platformResultsPreMapper:")
      results = await this.platform.platformResultsPreMapper(results, this.options, this.ciSource.commitHash)
      this.d("Received results from platformResultsPreMapper:", results)
    }

    const { fails, warnings, messages, markdowns } = results

    const failureCount = [...fails, ...warnings].length
    const messageCount = [...messages, ...markdowns].length

    this.d("Posting to platform:", results)

    const dangerID = this.options.dangerID
    const failed = fails.length > 0
    const hasMessages = failureCount + messageCount > 0

    let issueURL = undefined

    if (!hasMessages || this.options.removePreviousComments) {
      if (process.env["DANGER_SKIP_WHEN_EMPTY"] === "true") {
        this.log(`Skip posting to platform ${this.platform.name}.`)
      } else {
        if (!hasMessages) {
          this.log(`Found no issues or messages from Danger. Removing any existing messages on ${this.platform.name}.`)
        } else {
          this.log(
            `'removePreviousComments' option specified. Removing any existing messages on ${this.platform.name}.`
          )
        }
        await this.platform.deleteMainComment(dangerID)
        const previousComments = await this.platform.getInlineComments(dangerID)
        for (const comment of previousComments) {
          if (comment && comment.ownedByDanger) {
            await this.deleteInlineComment(comment)
          }
        }
      }
    }

    if (hasMessages) {
      if (fails.length > 0) {
        const s = fails.length === 1 ? "" : "s"
        const are = fails.length === 1 ? "is" : "are"
        this.log(`Failing the build, there ${are} ${fails.length} fail${s}.`)
      } else if (warnings.length > 0) {
        this.log("Found only warnings, not failing the build.")
      } else if (messageCount > 0) {
        this.log("Found only messages, passing those to review.")
      }

      let mergedResults = regularResults(results)
      if (git !== undefined) {
        const previousComments = await this.platform.getInlineComments(dangerID)
        const inline = inlineResults(results)
        let inlineLeftovers = await this.sendInlineComments(inline, git, previousComments)
        inlineLeftovers = this.options.ignoreOutOfDiffComments ? emptyDangerResults : inlineLeftovers
        mergedResults = sortResults(mergeResults(mergedResults, inlineLeftovers))
      }

      // If danger have no comments other than inline to update. Just delete previous main comment.
      if (isEmptyResults(mergedResults)) {
        this.platform.deleteMainComment(dangerID)
      } else {
        let commitID
        if (this.ciSource.commitHash !== undefined) {
          commitID = this.ciSource.commitHash
        } else if (git !== undefined) {
          commitID = git.commits[git.commits.length - 1].sha
        }
        let comment
        if (process.env["DANGER_BITBUCKETSERVER_HOST"]) {
          comment = bitbucketServerTemplate(dangerID, mergedResults, commitID)
        } else if (process.env["DANGER_BITBUCKETCLOUD_OAUTH_KEY"] || process.env["DANGER_BITBUCKETCLOUD_USERNAME"]) {
          comment = bitbucketCloudTemplate(dangerID, mergedResults, commitID)
        } else {
          comment = githubResultsTemplate(dangerID, mergedResults, commitID)
        }

        if (this.options.newComment) {
          issueURL = await this.platform.createComment(dangerID, comment)
        } else {
          issueURL = await this.platform.updateOrCreateComment(dangerID, comment)
        }
        this.log(`Feedback: ${issueURL}`)
      }
    }

    if (!this.options.noPublishCheck) {
      await this.updatePrStatus(!failed, issueURL, results, dangerID)
    }

    // More info, is more info.
    if (this.options.verbose) {
      await this.handleResultsPostingToSTDOUT(results)
    }

    // Write to the GitHub Env if a sub-process has included a reference to github's job summary
    if (results.github?.stepSummary) {
      const filePath = process.env.GITHUB_STEP_SUMMARY
      if (!filePath) {
        throw new Error("process.env.GITHUB_STEP_SUMMARY was not set, which is needed for setSummaryMarkdown")
      }
      writeFileSync(filePath, results.github.stepSummary, "utf8")
    }
  }

  async updatePrStatus(
    passed: boolean | "pending",
    issueURL: string | undefined,
    results: DangerResults,
    dangerID: string
  ) {
    const urlForInfo = issueURL || this.ciSource.ciRunURL
    const successPosting = await this.platform.updateStatus(passed, messageForResults(results), urlForInfo, dangerID)

    if (!successPosting) {
      this.log("Could not add a commit status, the GitHub token for Danger does not have access rights.")
      this.log("If the build fails, then danger will use a failing exit code.")
    }

    if (!successPosting && !passed) {
      this.d("Failing the build due to handleResultsPostingToPlatform not successfully setting a commit status")
      process.exitCode = 1
    }
  }

  /**
   * Send inline comments
   * Returns these violations that didn't pass the validation (e.g. incorrect file/line)
   *
   * @param results Results with inline violations
   */
  sendInlineComments(results: DangerResults, git: GitDSL, previousComments: Comment[] | null): Promise<DangerResults> {
    if (!this.platform.supportsInlineComments) {
      return new Promise((resolve) => resolve(results))
    }

    const inlineResults = resultsIntoInlineResults(results)
    const sortedInlineResults = sortInlineResults(inlineResults)

    let emptyResult: DangerResults = {
      messages: emptyDangerResults.messages,
      markdowns: emptyDangerResults.markdowns,
      fails: emptyDangerResults.fails,
      warnings: emptyDangerResults.warnings,
      meta: results.meta,
    }

    // For every inline result check if there is a comment already
    // if there is - update it and remove comment from deleteComments array (comments prepared for deletion)
    // if there isn't - create a new comment
    // Leftovers in deleteComments array should all be deleted afterwards
    let deleteComments = Array.isArray(previousComments) ? previousComments.filter((c) => c.ownedByDanger) : []
    let commentPromises: Promise<any>[] = []
    const inlineResultsForReview: DangerInlineResults[] = []
    for (let inlineResult of sortedInlineResults) {
      const index = deleteComments.findIndex((p) =>
        p.body.includes(fileLineToString(inlineResult.file, inlineResult.line))
      )
      let promise: Promise<any> | undefined = undefined
      if (index != -1) {
        let previousComment = deleteComments[index]
        deleteComments.splice(index, 1)
        promise = this.updateInlineComment(inlineResult, previousComment)
      } else {
        if (typeof this.platform.createInlineReview === "function") {
          inlineResultsForReview.push(inlineResult)
        } else {
          promise = this.sendInlineComment(git, inlineResult)
        }
      }
      if (promise) {
        commentPromises.push(
          promise.then((_r) => emptyDangerResults).catch((_e) => inlineResultsIntoResults(inlineResult))
        )
      }
    }
    deleteComments.forEach((comment) => {
      let promise = this.deleteInlineComment(comment)
      commentPromises.push(promise.then((_r) => emptyDangerResults).catch((_e) => emptyDangerResults))
    })

    return Promise.all([
      this.sendInlineReview(git, inlineResultsForReview)
        .then((_r) => emptyDangerResults)
        .catch((_e) =>
          inlineResultsForReview
            .map((inlineResult) => inlineResultsIntoResults(inlineResult))
            .reduce(mergeResults, emptyResult)
        ),
      ...commentPromises,
    ]).then((dangerResults) => {
      return new Promise<DangerResults>((resolve) => {
        resolve(dangerResults.reduce((acc, r) => mergeResults(acc, r), emptyResult))
      })
    })
  }

  async sendInlineReview(git: GitDSL, inlineResultsForReview: DangerInlineResults[]): Promise<any> {
    if (inlineResultsForReview.length === 0 || typeof this.platform.createInlineReview !== "function") {
      return emptyDangerResults
    }
    return await this.platform.createInlineReview(
      git,
      inlineResultsForReview.map((result) => ({
        comment: this.inlineCommentTemplate(result),
        path: result.file,
        line: result.line,
      }))
    )
  }

  async sendInlineComment(git: GitDSL, inlineResults: DangerInlineResults): Promise<any> {
    const comment = this.inlineCommentTemplate(inlineResults)
    return await this.platform.createInlineComment(git, comment, inlineResults.file, inlineResults.line)
  }

  async updateInlineComment(inlineResults: DangerInlineResults, previousComment: Comment): Promise<any> {
    const body = this.inlineCommentTemplate(inlineResults)
    // If generated body is exactly the same as current comment we don't send an API request
    if (body == previousComment.body) {
      return
    }

    return await this.platform.updateInlineComment(body, previousComment.id)
  }

  async deleteInlineComment(comment: Comment): Promise<any> {
    return await this.platform.deleteInlineComment(comment.id)
  }

  inlineCommentTemplate(inlineResults: DangerInlineResults): string {
    const results = inlineResultsIntoResults(inlineResults)

    let comment
    if (process.env["DANGER_BITBUCKETSERVER_HOST"]) {
      comment = bitbucketServerInlineTemplate(this.options.dangerID, results, inlineResults.file, inlineResults.line)
    } else if (process.env["DANGER_BITBUCKETCLOUD_OAUTH_KEY"] || process.env["DANGER_BITBUCKETCLOUD_USERNAME"]) {
      comment = bitbucketCloudInlineTemplate(this.options.dangerID, results, inlineResults.file, inlineResults.line)
    } else {
      comment = githubResultsInlineTemplate(this.options.dangerID, results, inlineResults.file, inlineResults.line)
    }
    return comment
  }

  /**
   * Takes an error (maybe a bad eval) and provides a DangerResults compatible object
   * @param error Any JS error
   */
  resultsForError(error: Error) {
    // Need a failing error, otherwise it won't fail CI.
    this.logErr(chalk.red("Danger has failed to run"))
    this.logErr(error)
    return {
      fails: [{ message: "Running your Dangerfile has Failed" }],
      warnings: [],
      messages: [],
      markdowns: [{ message: exceptionRaisedTemplate(error) }],
    }
  }
}

const messageForResults = (results: DangerResults) => {
  if (!results.fails.length && !results.warnings.length) {
    return `All green. ${compliment()}`
  } else {
    if (process.env["DANGER_BITBUCKETSERVER_HOST"]) {
      return bitbucketMessageForResultWithIssues
    } else if (process.env["DANGER_BITBUCKETCLOUD_OAUTH_KEY"] || process.env["DANGER_BITBUCKETCLOUD_USERNAME"]) {
      return bitbucketCloudMessageForResultWithIssues
    } else {
      return githubMessageForResultWithIssues
    }
  }
}


text:
package com.github.lassana.releases.net.model;

import com.google.gson.annotations.SerializedName;

/**
 * @author lassana
 * @since 1/14/14
 */
public class Repository {

    @SerializedName("name")
    private final String mName;
    @SerializedName("description")
    private final String mDescription;

    public Repository(String name, String description) {
        mName = name;
        mDescription = description;
    }

    public String getName() {
        return mName;
    }

    public String getDescription() {
        return mDescription;
    }

    @Override
    public String toString() {
        return mName + "\n" + mDescription;
    }
}


text:
var positionService = angular.module("Position", []);

positionService.factory("PositionService", ["$rootScope", function($rootScope) {
	var currentPosition = {
		lat: 0.0,
		lon: 0.0
	};
	var startPosition = {
		lat: 0.0,
		lon: 0.0
	};
	var speed = 0.0;
	var direction = {
		x: 0.0,
		y: 0.5,
		z: 1.0
	};

	var update = function() {
		$rootScope.$apply();
	}

	return {
		currentPosition: currentPosition,
		startPosition: startPosition,
		speed: speed,
		direction: direction,
		update: update
	}
}]);


text:
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <title>Components: Calendar of Events</title>

    <link type="text/css" rel="stylesheet" href="../../css/MagpieUI.css">

Components: Calendar of Events

        <div style="width: 300px;" data-element="Com.CalendarEvents" data-config='{"data" : {"2015":{"7":{"5":[{"title":"Franz Liszt, Hungarian pianist and composer","url":"http://en.wikipedia.org/wiki/Franz_Liszt"}],"29":[{"title":"Franz Liszt, Hungarian pianist and composer","url":"http://en.wikipedia.org/wiki/Franz_Liszt"}]},"11":{"2":[{"title":"Franz Liszt, Hungarian pianist and composer","url":"http://en.wikipedia.org/wiki/Franz_Liszt"}],"22":[{"title":"Franz Liszt, Hungarian pianist and composer 1","url":"http://en.wikipedia.org/wiki/Franz_Liszt"},{"title":"Franz Liszt, Hungarian pianist and composer 2","url":"http://en.wikipedia.org/wiki/Franz_Liszt"},{"title":"1234567","url":"http://en.wikipedia.org/wiki/Franz_Liszt"}]}}}}'>


text:
import {Component} from '@angular/core';
import NewTaskButtonTemplate from '../templates/newTaskButton.html';
import ProjectService from '../services/project.service';
import ActiveViewService from '../services/activeView.service';

@Component({
    selector: 'newTaskButton',
    template: NewTaskButtonTemplate
})
export default class NewTaskButtonComponent {
    constructor(projectService, activeViewService) {
        this.projectService = projectService
        this.activeViewService = activeViewService
    }

    clicked() {
        this.activeViewService.edit(this.activeViewService.activeTask, this.projectService.newTaskTemplate())
        return true
    }
}

NewTaskButtonComponent.parameters = [
    ProjectService, ActiveViewService
]


text:
<?php
namespace CLI\Threading\Utilities\Pulse;

use CLI\Threading\Utilities\Socket;

class SocketPulse {
	private $communication;
	function __construct() {
		$this->communication = new Socket\ReadWritePair ();
	}
	function pulse() {
		$this->communication->Write ( '.' );
	}
	function wait() {
		$this->communication->Read ( 1 );
	}
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description"
	content="A clientel management website for Judy's Speech">
<meta name="author" content="Scott C. Lewis">

<title>Client Manager</title>

<link href="../bower_components/bootstrap/dist/css/bootstrap.min.css"
	rel="stylesheet">

<link href="../bower_components/metisMenu/dist/metisMenu.min.css"
	rel="stylesheet">

<link
	href="../bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css"
	rel="stylesheet">

<link
	href="../bower_components/datatables-responsive/css/dataTables.responsive.css"
	rel="stylesheet">

<link href="../dist/css/sb-admin-2.css" rel="stylesheet">

<link
	href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css"
	rel="stylesheet">

<link href="../bower_components/font-awesome/css/font-awesome.min.css"
	rel="stylesheet" type="text/css">

				<button type="button" class="navbar-toggle" data-toggle="collapse"
					data-target=".navbar-collapse">
					Toggle navigation
				</button>
				Client Manager

										Task 1 40%
											Complete

											40% Complete (success)

 See
									All Tasks

									 New Comment 4 minutes ago

 See
									All Alerts

 User
								Profile

 Settings

								Logout

								<input type="text" class="form-control" placeholder="Search...">

									<button class="btn btn-default" type="button">

									</button>

								Schedule

								Clients

								Sessions

								Finances

 Overview

 Income

 Bills

								Statistics

 Overview

 Clients

 Sessions

								Notes

								To-Do

Add New Client

New Client

						<form role="form" action="" method="post">

											First Name <input type="text" name="firstName" id="firstName" class="form-control"
												placeholder="John">

									Last Name <input type="text" name="lastName" id="lastName"  class="form-control"
										placeholder="Doe">

										Father's / Guardian's First Name <input
											 type="text" name="fatherName" id="fatherName"  class="form-control" placeholder="Bob">

										Mother's / Guardian's First Name <input
											 type="text" name="motherName" id="motherName" class="form-control" placeholder="Jane">

										Home Address <input class="form-control"
											 type="text" name="address" id="address"  placeholder="Line 1">

									Home Address <input class="form-control"
										 type="text" name="address2" id="address2"  placeholder="Line 2">

										Home City <input class="form-control"
											 type="text" name="city" id="city"  placeholder="Columbus">

									Home Zip Code <input class="form-control"
										type="text" name="zip" id="zip" placeholder="43035">

										Home Phone <input type="tel"
											name="homePhone" id="homePhone" class="form-control" placeholder="740-555-555">

										Cell Phone <input type="tel"
											type="text" name="cellPhone" id="cellPhone" class="form-control" placeholder="740-555-555">

										Email <input class="form-control" type="email"
											name="email" id="email" placeholder="email@example.com">

										Age <select name="age" id="age" class="form-control">
											<option>Unsure</option>
											<option>3</option>
											<option>4</option>
											<option>5</option>
											<option>6</option>
											<option>7</option>
											<option>8</option>
											<option>9</option>
											<option>10</option>
											<option>11</option>
											<option>12</option>
											<option>13</option>
											<option>14</option>
											<option>15</option>
											<option>16</option>
											<option>17</option>
											<option>18</option>
											<option>19+</option>
										</select>

										Grade <select name="grade" id="grade" class="form-control">
											<option>Not a student</option>
											<option>K</option>
											<option>1</option>
											<option>2</option>
											<option>3</option>
											<option>4</option>
											<option>5</option>
											<option>6</option>
											<option>7</option>
											<option>8</option>
											<option>9</option>
											<option>10</option>
											<option>11</option>
											<option>12</option>
											<option>High School Graduate</option>
											<option>College</option>
										</select>

										School <input name="school" id="school" class="form-control" type="text"
											placeholder="Olentangy Orange">

										Goals / Hired Reason
										<textarea class="form-control" rows="3"
											name="goals" id="goals" placeholder="English tutoring, "Th" sounds..."></textarea>

									<button type="submit" name="submit" id="submit" class="btn btn-success" >Create Client</button>

									<button type="reset" class="btn btn-default">Reset</button>
									</form>

<?php

	if(isset($_POST['submit'])) {
		$database = 'sql596452';
		$username = 'sql596452';
		$password = 'iF9*jR1*';
		$hostname = 'sql5.freesqldatabase.com';

		$link = mysql_connect ( $hostname, $username, $password );
		if (! $link) {
			die ( 'Not connected : ' . mysql_error () );
		}
		// make foo the current db
		$db_selected = mysql_select_db ( $database, $link );
		if (! $db_selected) {
			die ( 'Can\'t connect : ' . mysql_error () );
		}
		$firstName = $_POST['firstName'];
		$lastName = $_POST['lastName'];
		$fatherName = $_POST['fatherName'];
		$motherName = $_POST['motherName'];
		$address = $_POST['address'];
		$address2 = $_POST['address2'];
		$city = $_POST['city'];
		$zip = $_POST['zip'];
		$homePhone = $_POST['homePhone'];
		$cellPhone = $_POST['cellPhone'];
		$email = $_POST['email'];
		$age = $_POST['age'];
		$grade = $_POST['grade'];
		$school = $_POST['school'];
		$goals = $_POST['goals'];
		$resultID = mysql_query("SELECT * FROM clients");
		$id = mysql_num_rows($resultID);
		$result = mysql_query ("INSERT INTO clients (ID, firstName, lastName, fatherName, motherName, address, address2, city, zip, homePhone, cellPhone, email, age, grade, school, goals) VALUES (\"{$id}\", \"{$firstName}\", \"{$lastName}\", \"{$fatherName}\", \"{$motherName}\", \"{$address}\", \"{$address2}\", \"{$city}\", \"{$zip}\", \"{$homePhone}\", \"{$cellPhone}\", \"{$email}\", \"{$age}\", \"{$grade}\", \"{$school}\", \"{$goals}\")");
	} else {
		// your html code

	}

	?>


text:
namespace content {

class BackgroundSyncNetworkObserverTest : public testing::Test {
 public:
  BackgroundSyncNetworkObserverTest() : network_changed_count_(0) {
    network_observer_ =
        std::make_unique<BackgroundSyncNetworkObserver>(base::BindRepeating(
            &BackgroundSyncNetworkObserverTest::OnConnectionChanged,
            base::Unretained(this)));
  }

  void SetNetwork(network::mojom::ConnectionType connection_type) {
    network::TestNetworkConnectionTracker::GetInstance()->SetConnectionType(
        connection_type);
    base::RunLoop().RunUntilIdle();
  }

  void OnConnectionChanged() { network_changed_count_++; }

 protected:
  BrowserTaskEnvironment task_environment_;

  std::unique_ptr<BackgroundSyncNetworkObserver> network_observer_;
  int network_changed_count_;
};

TEST_F(BackgroundSyncNetworkObserverTest, NetworkChangeInvokesCallback) {
  SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
  network_changed_count_ = 0;

  SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
  EXPECT_EQ(1, network_changed_count_);
  SetNetwork(network::mojom::ConnectionType::CONNECTION_3G);
  EXPECT_EQ(2, network_changed_count_);
  SetNetwork(network::mojom::ConnectionType::CONNECTION_UNKNOWN);
  EXPECT_EQ(3, network_changed_count_);
  SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
  EXPECT_EQ(4, network_changed_count_);
  SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
  EXPECT_EQ(4, network_changed_count_);
}

TEST_F(BackgroundSyncNetworkObserverTest, ConditionsMetOnline) {
  SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
  EXPECT_TRUE(network_observer_->NetworkSufficient());

  SetNetwork(network::mojom::ConnectionType::CONNECTION_3G);
  EXPECT_TRUE(network_observer_->NetworkSufficient());

  SetNetwork(network::mojom::ConnectionType::CONNECTION_UNKNOWN);
  EXPECT_TRUE(network_observer_->NetworkSufficient());

  SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
  EXPECT_FALSE(network_observer_->NetworkSufficient());
}

TEST_F(BackgroundSyncNetworkObserverTest, GetNetworkOnConstruction) {
  // We need to emulate being disconnected before creating the network observer.
  network_observer_.reset();
  SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);

  auto observer =
      std::make_unique<BackgroundSyncNetworkObserver>(base::BindRepeating(
          &BackgroundSyncNetworkObserverTest::OnConnectionChanged,
          base::Unretained(this)));

  base::RunLoop().RunUntilIdle();

  // The network observer should have learned that the current network is not
  // the default (UNKNOWN) but is in fact NONE.
  EXPECT_EQ(1, network_changed_count_);
  EXPECT_FALSE(observer->NetworkSufficient());
}

}  // namespace content


text:
/**
 * @file   TZ01_battery_charger.h
 * @brief  LiPo battery charger library for Cerevo CDP-TZ01B
 *
 * @author Cerevo Inc.
 */

/*
Copyright 2015 Cerevo Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#ifndef _TZ01_BATTERY_CHARGER_H_
#define _TZ01_BATTERY_CHARGER_H_

/**
 * @brief Battery charger library initialize
 *
 * @param[in] thermistor_enable false: Thermistor disable. true: Thermistor enable.
 * @return Initiaize result.
 * @retval true : Success.
 * @retval false: Failed.
*/
bool TZ01_battery_charger_init(bool thermistor_enable);

/**
 * @brief Set/Restore default configurations
 *
 * @return Setting result.
 * @retval true : Success.
 * @retval false: Failed.
 */
bool TZ01_battery_charger_set_configs(void);

/**
 * @brief Get configurations.
 *
 * @return Register buffer pointer
 * @retval [0]: Reg1 value.
 * @retval [1]: Reg2 value.
 * @retval [2]: Reg3 value.
 * @retval [3]: Reg4 value.
 * @retval [4]: Reg5 value.
 * @retval [5]: Reg6 value.
 * @retval [6]: Reg7 value.
 */
uint8_t* TZ01_battery_charger_get_configs(void);

#endif


text:
<?php namespace Terbium\DbConfig\Facades;

use Illuminate\Support\Facades\Facade;

class DbConfig extends Facade {

    /**
* Get the registered name of the component.
*
* @return string
*/
    protected static function getFacadeAccessor() { return 'db-config'; }

}


text:
class Quizz
{
    private:
        QList<Question*> _questions;
        Score _current_score;
        int _combo; // number of correct answers in a row
        QTime _time; //time when the question began
        int _current_question;

    public:
        Quizz(QList<Question*>);
        Question* nextQuestion();
        Question* currentQuestion();
        bool isFinished();
        void refreshScore(bool); // true if good answer
        int combo() const;
        int score() const;
        int timeLeft() const;
        bool timeOut() const;

};

#endif


text:
<?php
 //WARNING: The contents of this file are auto-generated

$mod_strings = array_merge($mod_strings,
	array(
		 'LBL_SECURITYGROUPS_SUBPANEL_TITLE' => "Grupos de Seguridad",
	)
);

$mod_strings['LBL_AOP_CASE_UPDATES'] = 'Actualizaciones de Casos';
$mod_strings['LBL_CREATE_PORTAL_USER'] = "Crear Usuario del Portal";
$mod_strings['LBL_ENABLE_PORTAL_USER'] = "Habilitar Usuario del Portal";
$mod_strings['LBL_DISABLE_PORTAL_USER'] = "Deshabilitar el Usuario del Portal";
$mod_strings['LBL_CREATE_PORTAL_USER_FAILED'] = "Error al crear el usuario del portal";
$mod_strings['LBL_ENABLE_PORTAL_USER_FAILED'] = "Error al habilitar el usuario del portal";
$mod_strings['LBL_DISABLE_PORTAL_USER_FAILED'] = "Error al deshabilitar el usuario del portal";
$mod_strings['LBL_CREATE_PORTAL_USER_SUCCESS'] = "Usuario del portal creado";
$mod_strings['LBL_ENABLE_PORTAL_USER_SUCCESS'] = "Usuario del portal habilitado";
$mod_strings['LBL_DISABLE_PORTAL_USER_SUCCESS'] = "Usuario del portal deshabilitado";
$mod_strings['LBL_NO_JOOMLA_URL'] = "No se especificó URL del portal";

//THIS FILE IS AUTO GENERATED, DO NOT MODIFY
$mod_strings['LBL_FP_EVENTS_CONTACTS_FROM_FP_EVENTS_TITLE'] = 'Eventos';
$mod_strings['LBL_FP_EVENT_DELEGATES_CONTACTS_1_FROM_FP_EVENT_DELEGATES_TITLE'] = 'Delegados';

?>


text:
/**
 * @file Block.cpp
 *
 * Controller library code
 */

#include <math.h>
#include <string.h>
#include <stdio.h>

#include <uORB/Subscription.hpp>
#include <uORB/Publication.hpp>

#include "Block.hpp"
#include "BlockParam.hpp"

namespace control
{

Block::Block(SuperBlock *parent, const char *name) :
	_name(name),
	_parent(parent),
	_dt(0),
	_subscriptions(),
	_params()
{
	if (getParent() != NULL) {
		getParent()->getChildren().add(this);
	}
}

void Block::getName(char *buf, size_t n)
{
	if (getParent() == NULL) {
		strncpy(buf, _name, n);

	} else {
		char parentName[blockNameLengthMax];
		getParent()->getName(parentName, n);

		if (!strcmp(_name, "")) {
			strncpy(buf, parentName, blockNameLengthMax);

		} else {
			snprintf(buf, blockNameLengthMax, "%s_%s", parentName, _name);
		}
	}
}

void Block::updateParams()
{
	BlockParamBase *param = getParams().getHead();
	int count = 0;

	while (param != NULL) {
		if (count++ > maxParamsPerBlock) {
			char name[blockNameLengthMax];
			getName(name, blockNameLengthMax);
			printf("exceeded max params for block: %s\n", name);
			break;
		}

		//printf("updating param: %s\n", param->getName());
		param->update();
		param = param->getSibling();
	}
}

void Block::updateSubscriptions()
{
	uORB::SubscriptionNode *sub = getSubscriptions().getHead();
	int count = 0;

	while (sub != NULL) {
		if (count++ > maxSubscriptionsPerBlock) {
			char name[blockNameLengthMax];
			getName(name, blockNameLengthMax);
			printf("exceeded max subscriptions for block: %s\n", name);
			break;
		}

		sub->update();
		sub = sub->getSibling();
	}
}

void Block::updatePublications()
{
	uORB::PublicationNode *pub = getPublications().getHead();
	int count = 0;

	while (pub != NULL) {
		if (count++ > maxPublicationsPerBlock) {
			char name[blockNameLengthMax];
			getName(name, blockNameLengthMax);
			printf("exceeded max publications for block: %s\n", name);
			break;
		}

		pub->update();
		pub = pub->getSibling();
	}
}

void SuperBlock::setDt(float dt)
{
	Block::setDt(dt);
	Block *child = getChildren().getHead();
	int count = 0;

	while (child != NULL) {
		if (count++ > maxChildrenPerBlock) {
			char name[40];
			getName(name, 40);
			printf("exceeded max children for block: %s\n", name);
			break;
		}

		child->setDt(dt);
		child = child->getSibling();
	}
}

void SuperBlock::updateChildParams()
{
	Block *child = getChildren().getHead();
	int count = 0;

	while (child != NULL) {
		if (count++ > maxChildrenPerBlock) {
			char name[40];
			getName(name, 40);
			printf("exceeded max children for block: %s\n", name);
			break;
		}

		child->updateParams();
		child = child->getSibling();
	}
}

void SuperBlock::updateChildSubscriptions()
{
	Block *child = getChildren().getHead();
	int count = 0;

	while (child != NULL) {
		if (count++ > maxChildrenPerBlock) {
			char name[40];
			getName(name, 40);
			printf("exceeded max children for block: %s\n", name);
			break;
		}

		child->updateSubscriptions();
		child = child->getSibling();
	}
}

void SuperBlock::updateChildPublications()
{
	Block *child = getChildren().getHead();
	int count = 0;

	while (child != NULL) {
		if (count++ > maxChildrenPerBlock) {
			char name[40];
			getName(name, 40);
			printf("exceeded max children for block: %s\n", name);
			break;
		}

		child->updatePublications();
		child = child->getSibling();
	}
}

} // namespace control


text:
Fabricator(:covered_material) do
  covered_on { Date.today }
end