text:
namespace url {

namespace {

template<typename CHAR, typename UCHAR>
void DoAppendStringOfType(const CHAR* source, int length,
                          SharedCharTypes type,
                          CanonOutput* output) {
  for (int i = 0; i < length; i++) {
    if (static_cast<UCHAR>(source[i]) >= 0x80) {
      // ReadChar will fill the code point with kUnicodeReplacementCharacter
      // when the input is invalid, which is what we want.
      unsigned code_point;
      ReadUTFChar(source, &i, length, &code_point);
      AppendUTF8EscapedValue(code_point, output);
    } else {
      // Just append the 7-bit character, possibly escaping it.
      unsigned char uch = static_cast<unsigned char>(source[i]);
      if (!IsCharOfType(uch, type))
        AppendEscapedChar(uch, output);
      else
        output->push_back(uch);
    }
  }
}

// This function assumes the input values are all contained in 8-bit,
// although it allows any type. Returns true if input is valid, false if not.
template<typename CHAR, typename UCHAR>
void DoAppendInvalidNarrowString(const CHAR* spec, int begin, int end,
                                 CanonOutput* output) {
  for (int i = begin; i < end; i++) {
    UCHAR uch = static_cast<UCHAR>(spec[i]);
    if (uch >= 0x80) {
      // Handle UTF-8/16 encodings. This call will correctly handle the error
      // case by appending the invalid character.
      AppendUTF8EscapedChar(spec, &i, end, output);
    } else if (uch <= ' ' || uch == 0x7f) {
      // This function is for error handling, so we escape all control
      // characters and spaces, but not anything else since we lack
      // context to do something more specific.
      AppendEscapedChar(static_cast<unsigned char>(uch), output);
    } else {
      output->push_back(static_cast<char>(uch));
    }
  }
}

// Overrides one component, see the Replacements structure for
// what the various combionations of source pointer and component mean.
void DoOverrideComponent(const char* override_source,
                         const Component& override_component,
                         const char** dest,
                         Component* dest_component) {
  if (override_source) {
    *dest = override_source;
    *dest_component = override_component;
  }
}

// Similar to DoOverrideComponent except that it takes a UTF-16 input and does
// not actually set the output character pointer.
//
// The input is converted to UTF-8 at the end of the given buffer as a temporary
// holding place. The component identifying the portion of the buffer used in
// the |utf8_buffer| will be specified in |*dest_component|.
//
// This will not actually set any |dest| pointer like DoOverrideComponent
// does because all of the pointers will point into the |utf8_buffer|, which
// may get resized while we're overriding a subsequent component. Instead, the
// caller should use the beginning of the |utf8_buffer| as the string pointer
// for all components once all overrides have been prepared.
bool PrepareUTF16OverrideComponent(const base::char16* override_source,
                                   const Component& override_component,
                                   CanonOutput* utf8_buffer,
                                   Component* dest_component) {
  bool success = true;
  if (override_source) {
    if (!override_component.is_valid()) {
      // Non-"valid" component (means delete), so we need to preserve that.
      *dest_component = Component();
    } else {
      // Convert to UTF-8.
      dest_component->begin = utf8_buffer->length();
      success = ConvertUTF16ToUTF8(&override_source[override_component.begin],
                                   override_component.len, utf8_buffer);
      dest_component->len = utf8_buffer->length() - dest_component->begin;
    }
  }
  return success;
}

}  // namespace

// See the header file for this array's declaration.
const unsigned char kSharedCharTypeTable[0x100] = {
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 0x00 - 0x0f
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 0x10 - 0x1f
    0,                           // 0x20  ' ' (escape spaces in queries)
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x21  !
    0,                           // 0x22  "
    0,                           // 0x23  #  (invalid in query since it marks the ref)
    CHAR_QUERY | CHAR_USERINFO,  // 0x24  $
    CHAR_QUERY | CHAR_USERINFO,  // 0x25  %
    CHAR_QUERY | CHAR_USERINFO,  // 0x26  &
    0,                           // 0x27  '  (Try to prevent XSS.)
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x28  (
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x29  )
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x2a  *
    CHAR_QUERY | CHAR_USERINFO,  // 0x2b  +
    CHAR_QUERY | CHAR_USERINFO,  // 0x2c  ,
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x2d  -
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_COMPONENT,  // 0x2e  .
    CHAR_QUERY,                  // 0x2f  /
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT,  // 0x30  0
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT,  // 0x31  1
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT,  // 0x32  2
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT,  // 0x33  3
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT,  // 0x34  4
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT,  // 0x35  5
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT,  // 0x36  6
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT,  // 0x37  7
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_COMPONENT,             // 0x38  8
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_COMPONENT,             // 0x39  9
    CHAR_QUERY,  // 0x3a  :
    CHAR_QUERY,  // 0x3b  ;
    0,           // 0x3c  <  (Try to prevent certain types of XSS.)
    CHAR_QUERY,  // 0x3d  =
    0,           // 0x3e  >  (Try to prevent certain types of XSS.)
    CHAR_QUERY,  // 0x3f  ?
    CHAR_QUERY,  // 0x40  @
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT,  // 0x41  A
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT,  // 0x42  B
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT,  // 0x43  C
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT,  // 0x44  D
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT,  // 0x45  E
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT,  // 0x46  F
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x47  G
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x48  H
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x49  I
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x4a  J
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x4b  K
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x4c  L
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x4d  M
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x4e  N
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x4f  O
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x50  P
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x51  Q
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x52  R
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x53  S
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x54  T
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x55  U
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x56  V
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x57  W
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_COMPONENT, // 0x58  X
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x59  Y
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x5a  Z
    CHAR_QUERY,  // 0x5b  [
    CHAR_QUERY,  // 0x5c  '\'
    CHAR_QUERY,  // 0x5d  ]
    CHAR_QUERY,  // 0x5e  ^
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x5f  _
    CHAR_QUERY,  // 0x60  `
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT,  // 0x61  a
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT,  // 0x62  b
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT,  // 0x63  c
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT,  // 0x64  d
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT,  // 0x65  e
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT,  // 0x66  f
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x67  g
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x68  h
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x69  i
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x6a  j
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x6b  k
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x6c  l
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x6d  m
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x6e  n
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x6f  o
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x70  p
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x71  q
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x72  r
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x73  s
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x74  t
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x75  u
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x76  v
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x77  w
    CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_COMPONENT,  // 0x78  x
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x79  y
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x7a  z
    CHAR_QUERY,  // 0x7b  {
    CHAR_QUERY,  // 0x7c  |
    CHAR_QUERY,  // 0x7d  }
    CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT,  // 0x7e  ~
    0,           // 0x7f
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 0x80 - 0x8f
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 0x90 - 0x9f
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 0xa0 - 0xaf
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 0xb0 - 0xbf
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 0xc0 - 0xcf
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 0xd0 - 0xdf
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 0xe0 - 0xef
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 0xf0 - 0xff
};

const char kHexCharLookup[0x10] = {
    '0', '1', '2', '3', '4', '5', '6', '7',
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
};

const char kCharToHexLookup[8] = {
    0,         // 0x00 - 0x1f
    '0',       // 0x20 - 0x3f: digits 0 - 9 are 0x30 - 0x39
    'A' - 10,  // 0x40 - 0x5f: letters A - F are 0x41 - 0x46
    'a' - 10,  // 0x60 - 0x7f: letters a - f are 0x61 - 0x66
    0,         // 0x80 - 0x9F
    0,         // 0xA0 - 0xBF
    0,         // 0xC0 - 0xDF
    0,         // 0xE0 - 0xFF
};

const base::char16 kUnicodeReplacementCharacter = 0xfffd;

void AppendStringOfType(const char* source, int length,
                        SharedCharTypes type,
                        CanonOutput* output) {
  DoAppendStringOfType<char, unsigned char>(source, length, type, output);
}

void AppendStringOfType(const base::char16* source, int length,
                        SharedCharTypes type,
                        CanonOutput* output) {
  DoAppendStringOfType<base::char16, base::char16>(
      source, length, type, output);
}

bool ReadUTFChar(const char* str, int* begin, int length,
                 unsigned* code_point_out) {
  // This depends on ints and int32s being the same thing. If they're not, it
  // will fail to compile.
  // TODO(mmenke): This should probably be fixed.
  if (!base::ReadUnicodeCharacter(str, length, begin, code_point_out) ||
      !base::IsValidCharacter(*code_point_out)) {
    *code_point_out = kUnicodeReplacementCharacter;
    return false;
  }
  return true;
}

bool ReadUTFChar(const base::char16* str, int* begin, int length,
                 unsigned* code_point_out) {
  // This depends on ints and int32s being the same thing. If they're not, it
  // will fail to compile.
  // TODO(mmenke): This should probably be fixed.
  if (!base::ReadUnicodeCharacter(str, length, begin, code_point_out) ||
      !base::IsValidCharacter(*code_point_out)) {
    *code_point_out = kUnicodeReplacementCharacter;
    return false;
  }
  return true;
}

void AppendInvalidNarrowString(const char* spec, int begin, int end,
                               CanonOutput* output) {
  DoAppendInvalidNarrowString<char, unsigned char>(spec, begin, end, output);
}

void AppendInvalidNarrowString(const base::char16* spec, int begin, int end,
                               CanonOutput* output) {
  DoAppendInvalidNarrowString<base::char16, base::char16>(
      spec, begin, end, output);
}

bool ConvertUTF16ToUTF8(const base::char16* input, int input_len,
                        CanonOutput* output) {
  bool success = true;
  for (int i = 0; i < input_len; i++) {
    unsigned code_point;
    success &= ReadUTFChar(input, &i, input_len, &code_point);
    AppendUTF8Value(code_point, output);
  }
  return success;
}

bool ConvertUTF8ToUTF16(const char* input, int input_len,
                        CanonOutputT<base::char16>* output) {
  bool success = true;
  for (int i = 0; i < input_len; i++) {
    unsigned code_point;
    success &= ReadUTFChar(input, &i, input_len, &code_point);
    AppendUTF16Value(code_point, output);
  }
  return success;
}

void SetupOverrideComponents(const char* base,
                             const Replacements<char>& repl,
                             URLComponentSource<char>* source,
                             Parsed* parsed) {
  // Get the source and parsed structures of the things we are replacing.
  const URLComponentSource<char>& repl_source = repl.sources();
  const Parsed& repl_parsed = repl.components();

  DoOverrideComponent(repl_source.scheme, repl_parsed.scheme,
                      &source->scheme, &parsed->scheme);
  DoOverrideComponent(repl_source.username, repl_parsed.username,
                      &source->username, &parsed->username);
  DoOverrideComponent(repl_source.password, repl_parsed.password,
                      &source->password, &parsed->password);

  // Our host should be empty if not present, so override the default setup.
  DoOverrideComponent(repl_source.host, repl_parsed.host,
                      &source->host, &parsed->host);
  if (parsed->host.len == -1)
    parsed->host.len = 0;

  DoOverrideComponent(repl_source.port, repl_parsed.port,
                      &source->port, &parsed->port);
  DoOverrideComponent(repl_source.path, repl_parsed.path,
                      &source->path, &parsed->path);
  DoOverrideComponent(repl_source.query, repl_parsed.query,
                      &source->query, &parsed->query);
  DoOverrideComponent(repl_source.ref, repl_parsed.ref,
                      &source->ref, &parsed->ref);
}

bool SetupUTF16OverrideComponents(const char* base,
                                  const Replacements<base::char16>& repl,
                                  CanonOutput* utf8_buffer,
                                  URLComponentSource<char>* source,
                                  Parsed* parsed) {
  bool success = true;

  // Get the source and parsed structures of the things we are replacing.
  const URLComponentSource<base::char16>& repl_source = repl.sources();
  const Parsed& repl_parsed = repl.components();

  success &= PrepareUTF16OverrideComponent(
      repl_source.scheme, repl_parsed.scheme,
      utf8_buffer, &parsed->scheme);
  success &= PrepareUTF16OverrideComponent(
      repl_source.username, repl_parsed.username,
      utf8_buffer, &parsed->username);
  success &= PrepareUTF16OverrideComponent(
      repl_source.password, repl_parsed.password,
      utf8_buffer, &parsed->password);
  success &= PrepareUTF16OverrideComponent(
      repl_source.host, repl_parsed.host,
      utf8_buffer, &parsed->host);
  success &= PrepareUTF16OverrideComponent(
      repl_source.port, repl_parsed.port,
      utf8_buffer, &parsed->port);
  success &= PrepareUTF16OverrideComponent(
      repl_source.path, repl_parsed.path,
      utf8_buffer, &parsed->path);
  success &= PrepareUTF16OverrideComponent(
      repl_source.query, repl_parsed.query,
      utf8_buffer, &parsed->query);
  success &= PrepareUTF16OverrideComponent(
      repl_source.ref, repl_parsed.ref,
      utf8_buffer, &parsed->ref);

  // PrepareUTF16OverrideComponent will not have set the data pointer since the
  // buffer could be resized, invalidating the pointers. We set the data
  // pointers for affected components now that the buffer is finalized.
  if (repl_source.scheme)   source->scheme = utf8_buffer->data();
  if (repl_source.username) source->username = utf8_buffer->data();
  if (repl_source.password) source->password = utf8_buffer->data();
  if (repl_source.host)     source->host = utf8_buffer->data();
  if (repl_source.port)     source->port = utf8_buffer->data();
  if (repl_source.path)     source->path = utf8_buffer->data();
  if (repl_source.query)    source->query = utf8_buffer->data();
  if (repl_source.ref)      source->ref = utf8_buffer->data();

  return success;
}

#ifndef WIN32

int _itoa_s(int value, char* buffer, size_t size_in_chars, int radix) {
  const char* format_str;
  if (radix == 10)
    format_str = "%d";
  else if (radix == 16)
    format_str = "%x";
  else
    return EINVAL;

  int written = snprintf(buffer, size_in_chars, format_str, value);
  if (static_cast<size_t>(written) >= size_in_chars) {
    // Output was truncated, or written was negative.
    return EINVAL;
  }
  return 0;
}

int _itow_s(int value, base::char16* buffer, size_t size_in_chars, int radix) {
  if (radix != 10)
    return EINVAL;

  // No more than 12 characters will be required for a 32-bit integer.
  // Add an extra byte for the terminating null.
  char temp[13];
  int written = snprintf(temp, sizeof(temp), "%d", value);
  if (static_cast<size_t>(written) >= size_in_chars) {
    // Output was truncated, or written was negative.
    return EINVAL;
  }

  for (int i = 0; i < written; ++i) {
    buffer[i] = static_cast<base::char16>(temp[i]);
  }
  buffer[written] = '\0';
  return 0;
}

#endif  // !WIN32

}  // namespace url


text:
local Class = require 'utils.class'
local Global = Class{
   debug = false,
   name='global',
   sprite_path='assets/sprites/',
   item_path='assets/items/',
   hud_path='assets/hud/',
   trap_path='assets/trap/',
   gravity = 2000,
   cellsize = 70,
   tileWidth = 70,
   tileHeight = 70,

   --internal useage
   free_camera = false
}

return Global

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.idea;

import com.intellij.idea.extensions.BombExplodedExtension;
import org.intellij.lang.annotations.JdkConstants;
import org.junit.jupiter.api.extension.ExtendWith;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@ExtendWith(BombExplodedExtension.class)
public @interface Bombed {
  int year();
  @JdkConstants.CalendarMonth int month();
  int day();
  int time() default 0;
  String user();
  String description() default "";
}


text:
/*jslint node: true */
"use strict";
var db = require('./db.js');

function generateQueriesToArchiveJoint(conn, objJoint, reason, arrQueries, cb){
	var func = (reason === 'uncovered') ? generateQueriesToRemoveJoint : generateQueriesToVoidJoint;
	func(conn, objJoint.unit.unit, arrQueries, function(){
		conn.addQuery(arrQueries, "INSERT "+conn.getIgnore()+" INTO archived_joints (unit, reason, json) VALUES (?,?,?)",
			[objJoint.unit.unit, reason, JSON.stringify(objJoint)]);
		cb();
	});
}

function generateQueriesToRemoveJoint(conn, unit, arrQueries, cb){
	generateQueriesToUnspendOutputsSpentInArchivedUnit(conn, unit, arrQueries, function(){
		conn.addQuery(arrQueries, "DELETE FROM aa_responses WHERE trigger_unit=? OR response_unit=?", [unit, unit]);
		conn.addQuery(arrQueries, "DELETE FROM original_addresses WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM sent_mnemonics WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM witness_list_hashes WHERE witness_list_unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM earned_headers_commission_recipients WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM unit_witnesses WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM authentifiers WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM unit_authors WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM parenthoods WHERE child_unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM address_definition_changes WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM inputs WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM outputs WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM spend_proofs WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM data_feeds WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM poll_choices WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM polls WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM votes WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM attested_fields WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM attestations WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM asset_metadata WHERE asset=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM asset_denominations WHERE asset=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM asset_attestors WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM assets WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM messages WHERE unit=?", [unit]);
	//	conn.addQuery(arrQueries, "DELETE FROM balls WHERE unit=?", [unit]); // if it has a ball, it can't be uncovered
		conn.addQuery(arrQueries, "DELETE FROM units WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM joints WHERE unit=?", [unit]);
		cb();
	});
}

function generateQueriesToVoidJoint(conn, unit, arrQueries, cb){
	generateQueriesToUnspendOutputsSpentInArchivedUnit(conn, unit, arrQueries, function(){
		// we keep witnesses, author addresses, and the unit itself
		conn.addQuery(arrQueries, "DELETE FROM witness_list_hashes WHERE witness_list_unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM earned_headers_commission_recipients WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM authentifiers WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "UPDATE unit_authors SET definition_chash=NULL WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM address_definition_changes WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM inputs WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM outputs WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM spend_proofs WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM data_feeds WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM poll_choices WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM polls WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM votes WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM attested_fields WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM attestations WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM asset_metadata WHERE asset=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM asset_denominations WHERE asset=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM asset_attestors WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM assets WHERE unit=?", [unit]);
		conn.addQuery(arrQueries, "DELETE FROM messages WHERE unit=?", [unit]);
		cb();
	});
}

function generateQueriesToUnspendOutputsSpentInArchivedUnit(conn, unit, arrQueries, cb){
	generateQueriesToUnspendTransferOutputsSpentInArchivedUnit(conn, unit, arrQueries, function(){
		generateQueriesToUnspendHeadersCommissionOutputsSpentInArchivedUnit(conn, unit, arrQueries, function(){
			generateQueriesToUnspendWitnessingOutputsSpentInArchivedUnit(conn, unit, arrQueries, cb);
		});
	});
}

function generateQueriesToUnspendTransferOutputsSpentInArchivedUnit(conn, unit, arrQueries, cb){
	conn.query(
		"SELECT src_unit, src_message_index, src_output_index \n\
		FROM inputs \n\
		WHERE inputs.unit=? \n\
			AND inputs.type='transfer' \n\
			AND NOT EXISTS ( \n\
				SELECT 1 FROM inputs AS alt_inputs \n\
				WHERE inputs.src_unit=alt_inputs.src_unit \n\
					AND inputs.src_message_index=alt_inputs.src_message_index \n\
					AND inputs.src_output_index=alt_inputs.src_output_index \n\
					AND alt_inputs.type='transfer' \n\
					AND inputs.unit!=alt_inputs.unit \n\
			)",
		[unit],
		function(rows){
			rows.forEach(function(row){
				conn.addQuery(
					arrQueries,
					"UPDATE outputs SET is_spent=0 WHERE unit=? AND message_index=? AND output_index=?",
					[row.src_unit, row.src_message_index, row.src_output_index]
				);
			});
			cb();
		}
	);
}

function generateQueriesToUnspendHeadersCommissionOutputsSpentInArchivedUnit(conn, unit, arrQueries, cb){
	conn.query(
		"SELECT headers_commission_outputs.address, headers_commission_outputs.main_chain_index \n\
		FROM inputs \n\
		CROSS JOIN headers_commission_outputs \n\
			ON inputs.from_main_chain_index <= +headers_commission_outputs.main_chain_index \n\
			AND inputs.to_main_chain_index >= +headers_commission_outputs.main_chain_index \n\
			AND inputs.address = headers_commission_outputs.address \n\
		WHERE inputs.unit=? \n\
			AND inputs.type='headers_commission' \n\
			AND NOT EXISTS ( \n\
				SELECT 1 FROM inputs AS alt_inputs \n\
				WHERE headers_commission_outputs.main_chain_index >= alt_inputs.from_main_chain_index \n\
					AND headers_commission_outputs.main_chain_index <= alt_inputs.to_main_chain_index \n\
					AND inputs.address=alt_inputs.address \n\
					AND alt_inputs.type='headers_commission' \n\
					AND inputs.unit!=alt_inputs.unit \n\
			)",
		[unit],
		function(rows){
			rows.forEach(function(row){
				conn.addQuery(
					arrQueries,
					"UPDATE headers_commission_outputs SET is_spent=0 WHERE address=? AND main_chain_index=?",
					[row.address, row.main_chain_index]
				);
			});
			cb();
		}
	);
}

function generateQueriesToUnspendWitnessingOutputsSpentInArchivedUnit(conn, unit, arrQueries, cb){
	conn.query(
		"SELECT witnessing_outputs.address, witnessing_outputs.main_chain_index \n\
		FROM inputs \n\
		CROSS JOIN witnessing_outputs \n\
			ON inputs.from_main_chain_index <= +witnessing_outputs.main_chain_index \n\
			AND inputs.to_main_chain_index >= +witnessing_outputs.main_chain_index \n\
			AND inputs.address = witnessing_outputs.address \n\
		WHERE inputs.unit=? \n\
			AND inputs.type='witnessing' \n\
			AND NOT EXISTS ( \n\
				SELECT 1 FROM inputs AS alt_inputs \n\
				WHERE witnessing_outputs.main_chain_index >= alt_inputs.from_main_chain_index \n\
					AND witnessing_outputs.main_chain_index <= alt_inputs.to_main_chain_index \n\
					AND inputs.address=alt_inputs.address \n\
					AND alt_inputs.type='witnessing' \n\
					AND inputs.unit!=alt_inputs.unit \n\
			)",
		[unit],
		function(rows){
			rows.forEach(function(row){
				conn.addQuery(
					arrQueries,
					"UPDATE witnessing_outputs SET is_spent=0 WHERE address=? AND main_chain_index=?",
					[row.address, row.main_chain_index]
				);
			});
			cb();
		}
	);
}

exports.generateQueriesToArchiveJoint = generateQueriesToArchiveJoint;


text:
/************************************************************************
*																		*
*	SciCal																*
*	A scientific calculator made by Javascript							*
*	Author: Neo13 <a.derakhshan.iut@gmail.com>							*
*	License: MIT														*
*																		*
************************************************************************/

import { Node } from "./node";
import "babel-polyfill";

export class Tree extends Node {
/**
 *
 * Tree
 * A binary tree structure
 *
 */
	constructor () {
		super(null, null, null);
		this.length = 0;
	}

	push (node) {
		if (this.value === null) {
			//	The tree is empty
			this.right = node.right;
			this.left = node.left;
			this.value = node.value;
		} else {
			//	When tree is not empty look for the first empty place
			var queue = [],
				cur = this;

			while(cur.right !== null && cur.left !== null) {
				queue.push(cur.left);
				queue.push(cur.right);
				cur = queue.shift();
			}

			if (cur.left === null) {
				cur.left = node;
			} else {
				cur.right = node;
			}

		}

		this.length++;
		return this;
	}

	* [Symbol.iterator] () {
		//	Defines a post-order DFS traverse generator which is used to solve tokenized equations professional
		let stack = [this, this.right, this.left], cur = null;
		while(stack.length !== 0) {
			cur = stack.pop();
			if (cur.left !== null) {
				stack.push(cur);
				if (cur.right !== null) {
					stack.push(cur.right);
				}
				stack.push(cur.left);
			} else {
				yield cur;
				if (stack.length !== 0) {
					yield stack.pop();
				} else {
					break;
				}
			}
		}
		return;
	}
}


text:
require 'rtst'
require 'set'
require 'fileutils'
require 'test/unit'

class RTSTTests < Test::Unit::TestCase
	def setup
	  # set this if you want reproducible runs
	  # srand 43776

      # 1000 unique, random strings
	  @items = Set.new
	  while @items.size < 1000
	  	item = rand.to_s + rand.to_s + rand.to_s + rand.to_s
	  	@items << item
	  end

	  @tree = RTST.new
	end

	def teardown
	end

	def test_fill
		@items.each do |item|
			assert_nil @tree.set(item, item)
		end
	end

	def test_read
		test_fill
		@items.each do |item|
			assert_equal item, @tree.get(item)
		end
	end

	def test_remove
		test_fill

		@removed = Set.new
		@items.first(200).each do |item|
			@removed << item
			@tree.remove item
		end

		@items.each do |item|
			if @removed.include? item
				assert_nil @tree.get(item)
			else
				assert_equal item, @tree.get(item)
			end
		end
	end

	def test_each
		test_remove

		result = @tree.each do |key, value, distance|
			assert_equal key, value
			assert_equal 0, distance
			assert @items.include? key
			assert !@removed.include?(key)
    		@items.delete key
    		nil # Need to return nil to go through all the tree
		end

		assert_equal @removed.size, @items.size
	end

	def dump_tree(tree,filename)
	    FileUtils.rm([filename,"#{filename}.png"], :force => true)
	    tree.dump(filename)
	    assert File.exists?(filename)
	    system("dot -Gcharset=latin1 -Kdot -Tpng -O #{filename}")
	    FileUtils.rm([filename])
	end

	def test_compacity
	    words = %w{
	    	compacity
	    	compact
	    	compacted
	    	community
	    	commuter
	    	commuters
	    	compute
	    }

	    words.each do |word|
	    	assert_nil @tree.set(word, word)
	    end

	    words.each do |word|
	    	assert_equal word, @tree.get(word)
	    end

	    dump_tree @tree, "test_compacity.dot"
	end

	def test_dump_and_graphviz
		@items.first(20).each do |item|
			@tree.set item, item
	    end

	    dump_tree @tree, "test_rtst_dump.dot"
	end

	def test_french_dictionary
		@items = []

		words = IO.readlines("|zcat liste.de.mots.francais.frgut.txt.gz")
		words.shuffle!

		words.first(32).each do |line|
			line = line.strip
			assert_nil @tree.set(line,line)
		end

	    dump_tree @tree, "francais.dot"

		words.first(32).each do |line|
			line = line.strip
			assert_equal line, @tree.get(line)
		end

	end
end


text:
static std::string file = "Resources/bear.obj";

#if (COMPILE_MODEL == TRUE)
#include "Bear_model.h"

Bear::Bear() : ObjectModel(bear_vertice, bear_n_vertice, bear_normal, bear_n_normal, bear_face, bear_n_face)
{
    material.set_property(Material::SPECULAR, Color(0.9, 0.9, 0.9));
    material.set_property(Material::SHININESS, 150);
    material.set_property(Material::DIFFUSE, Color(0.8, 0.8, 0.8));
}
#else
Bear::Bear() : ObjectModel() {}
#endif

Bear::~Bear() {}


text:
static ID object_id;
static ID sc_id;

static void sd_free(SerializationDescriptor sd) {
  if (!sd) {
    return;
  }

  sd->serializer = Qnil;
  sd->serializer_type = Qnil;
  sd->attributes = Qnil;
  sd->method_fields = Qnil;
  sd->has_one_associations = Qnil;
  sd->has_many_associations = Qnil;
  sd->aliases = Qnil;
  xfree(sd);
}

void sd_mark(SerializationDescriptor data) {
  rb_gc_mark(data->serializer);
  rb_gc_mark(data->serializer_type);
  rb_gc_mark(data->attributes);
  rb_gc_mark(data->method_fields);
  rb_gc_mark(data->has_one_associations);
  rb_gc_mark(data->has_many_associations);
  rb_gc_mark(data->aliases);
}

static VALUE sd_alloc(VALUE klass) {
  SerializationDescriptor sd = ALLOC(struct _SerializationDescriptor);

  sd->serializer = Qnil;
  sd->serializer_type = Qnil;
  sd->attributes = Qnil;
  sd->method_fields = Qnil;
  sd->has_one_associations = Qnil;
  sd->has_many_associations = Qnil;
  sd->aliases = Qnil;

  sd->attributes_writer = create_empty_attributes_writer();

  return Data_Wrap_Struct(klass, sd_mark, sd_free, sd);
}

SerializationDescriptor sd_read(VALUE descriptor) {
  return (SerializationDescriptor)DATA_PTR(descriptor);
}

void sd_set_writer(SerializationDescriptor sd, VALUE object) {
  if (sd->attributes_writer.object_type != Unknown) {
    return;
  }

  sd->attributes_writer = create_attributes_writer(object);
}

VALUE sd_serializer_set(VALUE self, VALUE serializer) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);

  sd->serializer = serializer;
  return Qnil;
}

VALUE sd_serializer_ref(VALUE self) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);

  return sd->serializer;
}

VALUE sd_attributes_set(VALUE self, VALUE attributes) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);

  sd->attributes = attributes;
  return Qnil;
}

VALUE sd_attributes_ref(VALUE self) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);
  return sd->attributes;
}

VALUE sd_method_fields_set(VALUE self, VALUE method_fields) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);
  sd->method_fields = method_fields;
  return Qnil;
}

VALUE sd_method_fields_ref(VALUE self) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);
  return sd->method_fields;
}

VALUE sd_has_one_associations_set(VALUE self, VALUE has_one_associations) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);
  sd->has_one_associations = has_one_associations;
  return Qnil;
}

VALUE sd_has_one_associations_ref(VALUE self) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);
  return sd->has_one_associations;
}

VALUE sd_has_many_associations_set(VALUE self, VALUE has_many_associations) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);
  sd->has_many_associations = has_many_associations;
  return Qnil;
}

VALUE sd_has_many_associations_ref(VALUE self) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);
  return sd->has_many_associations;
}

VALUE sd_type_set(VALUE self, VALUE type) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);
  sd->serializer_type = type;
  return Qnil;
}

VALUE sd_type_aref(VALUE self) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);
  return sd->serializer_type;
}

VALUE sd_aliases_set(VALUE self, VALUE aliases) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);
  sd->aliases = aliases;
  return Qnil;
}

VALUE sd_aliases_aref(VALUE self) {
  SerializationDescriptor sd = (SerializationDescriptor)DATA_PTR(self);
  return sd->aliases;
}

void panko_init_serialization_descriptor(VALUE mPanko) {
  object_id = rb_intern("@object");
  sc_id = rb_intern("@sc");

  VALUE cSerializationDescriptor =
      rb_define_class_under(mPanko, "SerializationDescriptor", rb_cObject);

  rb_define_alloc_func(cSerializationDescriptor, sd_alloc);
  rb_define_method(cSerializationDescriptor, "serializer=", sd_serializer_set,
                   1);
  rb_define_method(cSerializationDescriptor, "serializer", sd_serializer_ref,
                   0);

  rb_define_method(cSerializationDescriptor, "attributes=", sd_attributes_set,
                   1);
  rb_define_method(cSerializationDescriptor, "attributes", sd_attributes_ref,
                   0);

  rb_define_method(cSerializationDescriptor,
                   "method_fields=", sd_method_fields_set, 1);
  rb_define_method(cSerializationDescriptor, "method_fields",
                   sd_method_fields_ref, 0);

  rb_define_method(cSerializationDescriptor,
                   "has_one_associations=", sd_has_one_associations_set, 1);
  rb_define_method(cSerializationDescriptor, "has_one_associations",
                   sd_has_one_associations_ref, 0);

  rb_define_method(cSerializationDescriptor,
                   "has_many_associations=", sd_has_many_associations_set, 1);
  rb_define_method(cSerializationDescriptor, "has_many_associations",
                   sd_has_many_associations_ref, 0);

  rb_define_method(cSerializationDescriptor, "type=", sd_type_set, 1);
  rb_define_method(cSerializationDescriptor, "type", sd_type_aref, 0);

  rb_define_method(cSerializationDescriptor, "aliases=", sd_aliases_set, 1);
  rb_define_method(cSerializationDescriptor, "aliases", sd_aliases_aref, 0);
}


text:
import React, { Fragment } from 'react';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { useSelector } from 'react-redux';

import { ClipboardIcon } from '../Icon';
import { State } from '../reducers';
import * as selectors from '../selectors';

import Loader from './Loader';

import styles from './Gist.module.css';

const Gist: React.FC = () => {
  const showLoader = useSelector(selectors.showGistLoaderSelector);

  return (

      { showLoader ? <Loader /> : <Links />}

  );
};

interface CopiedProps {
  href: string;
}

interface CopiedState {
  copied: boolean;
}

class Copied extends React.PureComponent<CopiedProps, CopiedState> {
  public constructor(props: CopiedProps) {
    super(props);
    this.state = { copied: false };
  }

  public render() {
    return (

        {this.props.children}
        <CopyToClipboard text={this.props.href} onCopy={this.copied}>
          <button className={styles.button}><ClipboardIcon /></button>
        </CopyToClipboard>
        Copied!

    );
  }

  private copied = () => {
    this.setState({ copied: true });
    setTimeout(() => { this.setState({ copied: false }); }, 1000);
  }
}

const Links: React.FC = () => {
  const codeUrl = useSelector(selectors.codeUrlSelector);
  const gistUrl = useSelector((state: State) => state.output.gist.url);
  const permalink = useSelector(selectors.permalinkSelector);
  const urloUrl = useSelector(selectors.urloUrlSelector);

  return (
    <Fragment>
      <Copied href={permalink}>Permalink to the playground</Copied>
      { gistUrl ? <Copied href={gistUrl}>Direct link to the gist</Copied> : null }
      <Copied href={codeUrl}>Embedded code in link</Copied>
      <NewWindow href={urloUrl}>Open a new thread in the Rust user forum</NewWindow>
    </Fragment>
  );
};

interface NewWindowProps {
  href: string;
}

const NewWindow: React.FC<NewWindowProps> = props => (

    {props.children}

);

export default Gist;


text:
const webdriver = require('selenium-webdriver')

const url = 'http://localhost:8080/index.html'

const driver = new webdriver.Builder()
    .forBrowser('chrome')
    .build()

exports.driver = driver
exports.By = webdriver.By
exports.findId = id => driver.findElement(webdriver.By.id(id))
exports.findCSS = css => driver.findElements(webdriver.By.cssSelector(css))
exports.findxpath = xpath =>driver.findElements(webdriver.By.xpath(xpath))
exports.go = _ => driver.navigate().to(url)
exports.sleep = millis => driver.sleep(millis)


text:
typedef struct fd_indicator_animation_s fd_indicator_animation_t;

typedef bool (*fd_indicator_animation_step_fn_t)(void *state);
typedef void (*fd_indicator_animation_event_fn_t)(void);

typedef struct {
    bool done;
    fd_indicator_animation_step_fn_t step_fn;
    void *step_state;
    fd_indicator_animation_event_fn_t done_fn;
} fd_indicator_animation_phase_t;

typedef struct fd_indicator_animation_s {
    bool running;
    bool canceling;
    bool rerun;
    fd_indicator_animation_phase_t in;
    fd_indicator_animation_phase_t cycle;
    fd_indicator_animation_phase_t out;
    fd_indicator_animation_event_fn_t done_fn;
} fd_indicator_animation_t;

static uint8_t fd_indicator_animation_ease_quad_pulse[] = {
 // in
 0, 1, 2, 5, 8, 13, 19, 26,
 34, 43, 53, 64, 76, 90, 104, 119,
 136, 151, 165, 179, 191, 202, 212, 221,
 229, 236, 242, 247, 250, 253, 254, 255,
 // out
 255, 254, 253, 250, 247, 242, 236, 229,
 221, 212, 202, 191, 179, 165, 151, 136,
 119, 104, 90, 76, 64, 53, 43, 34,
 26, 19, 13, 8, 5, 2, 1, 0,
};

static uint8_t fd_indicator_animation_ease_linear_in[] = {
 0, 31, 63, 95, 127, 159, 191, 223, 255
};

static uint8_t fd_indicator_animation_ease_linear_out[] = {
 255, 223, 191, 159, 127, 95, 63, 31, 0,
};

static uint8_t fd_indicator_animation_ease_single[] = {
 255,
};

static void fd_indicator_running_check(void);

void fd_indicator_animation_phase_initialize(fd_indicator_animation_phase_t *phase) {
    phase->done = false;
    phase->step_fn = 0;
    phase->step_state = 0;
    phase->done_fn = 0;
}

void fd_indicator_animation_phase_run(fd_indicator_animation_phase_t *phase) {
    phase->done = phase->step_fn == 0;
}

bool fd_indicator_animation_phase_step(fd_indicator_animation_phase_t *phase, bool finish) {
    if (phase->done) {
        return true;
    }
    bool done = (*phase->step_fn)(phase->step_state);
    if (done) {
        if (finish) {
            phase->done = true;
        }
        if (phase->done_fn != 0) {
            phase->done_fn();
        }
    }
    return false;
}

void fd_indicator_animation_initialize(fd_indicator_animation_t *animation) {
    animation->running = false;
    animation->canceling = false;
    animation->rerun = false;
    fd_indicator_animation_phase_initialize(&animation->in);
    fd_indicator_animation_phase_initialize(&animation->cycle);
    fd_indicator_animation_phase_initialize(&animation->out);
    animation->done_fn = 0;
}

void fd_indicator_animation_run(fd_indicator_animation_t *animation) {
    if (!animation->running) {
        animation->running = true;
        animation->canceling = false;
        animation->rerun = false;
        fd_indicator_animation_phase_run(&animation->in);
        fd_indicator_animation_phase_run(&animation->cycle);
        fd_indicator_animation_phase_run(&animation->out);
        fd_indicator_running_check();
    } else {
        if (animation->canceling) {
            if (animation->cycle.done) {
                animation->rerun = true;
            } else {
                animation->canceling = false;
            }
        }
    }
}

void fd_indicator_animation_cancel(fd_indicator_animation_t *animation) {
    animation->canceling = true;
    animation->rerun = false;
}

void fd_indicator_animation_step(fd_indicator_animation_t *animation) {
    if (animation->running) {
        if (fd_indicator_animation_phase_step(&animation->in, true)) {
            if (fd_indicator_animation_phase_step(&animation->cycle, animation->canceling)) {
                fd_indicator_animation_phase_step(&animation->out, true);
            }
        }
        if (animation->in.done && animation->cycle.done && animation->out.done) {
            animation->running = false;
            if (animation->rerun) {
                fd_indicator_animation_run(animation);
            }
            if (!animation->running && (animation->done_fn != 0)) {
                (*animation->done_fn)();
            }
            if (!animation->running) {
                fd_indicator_running_check();
            }
        }
    }
}

typedef struct {
    float base;
    float scale;
} fd_indicator_animation_equ_t;

uint8_t fd_indicator_animation_equ(fd_indicator_animation_equ_t equ, float v) {
    float f = equ.base + equ.scale * v;
    int32_t r = (int32_t)(f + 0.5f);
    if (r < 0) {
        return 0;
    }
    if (r > 255) {
        return 255;
    }
    return (uint8_t)r;
}

typedef struct {
    uint32_t index;
    uint32_t count;
    uint32_t size;
    uint8_t *values;
    fd_indicator_animation_equ_t r;
    fd_indicator_animation_equ_t g;
    fd_indicator_animation_equ_t b;
    uint32_t led;
} fd_indicator_animation_list_step_rgb_state_t;

void fd_indicator_animation_list_step_rgb_initialize(fd_indicator_animation_list_step_rgb_state_t *state) {
    state->index = 0;
    state->r.base = 0.0f;
    state->r.scale = 1.0f;
    state->g.base = 0.0f;
    state->g.scale = 1.0f;
    state->b.base = 0.0f;
    state->b.scale = 1.0f;
}

bool fd_indicator_animation_list_step_rgb(void *state_p) {
    fd_indicator_animation_list_step_rgb_state_t *state = state_p;
    if (state->index < state->size) {
        float v = state->values[state->index];
        uint8_t r = fd_indicator_animation_equ(state->r, v);
        uint8_t g = fd_indicator_animation_equ(state->g, v);
        uint8_t b = fd_indicator_animation_equ(state->b, v);
        switch (state->led) {
            case 1:
                fd_led_set_d1(r, g, b);
                break;
            case 2:
                fd_led_set_d2(r, g, b);
                break;
            case 3:
                fd_led_set_d3(r, g, b);
                break;
            default:
                break;
        }
    }
    ++state->index;
    bool done = state->index >= state->size;
    if (done) {
        if (state->index >= state->count) {
            state->index = 0;
        }
    }
    return done;
}

typedef struct {
    uint32_t index;
    uint32_t size;
    uint8_t *values;
    fd_indicator_animation_equ_t o;
    fd_indicator_animation_equ_t g;
} fd_indicator_animation_list_step_og_state_t;

void fd_indicator_animation_list_step_og_initialize(fd_indicator_animation_list_step_og_state_t *state) {
    state->index = 0;
    state->o.base = 0.0f;
    state->o.scale = 1.0f;
    state->g.base = 0.0f;
    state->g.scale = 1.0f;
}

bool fd_indicator_animation_list_step_og(void *state_p) {
    fd_indicator_animation_list_step_og_state_t *state = state_p;
    float v = state->values[state->index++];
    uint8_t o = fd_indicator_animation_equ(state->o, v);
    uint8_t g = fd_indicator_animation_equ(state->g, v);
    fd_led_set_usb(o, g);
    bool done = state->index >= state->size;
    if (done) {
        state->index = 0;
    }
    return done;
}

typedef struct {
    uint32_t index;
    uint32_t size;
    uint8_t *values;
    fd_indicator_animation_equ_t r;
    uint32_t led;
} fd_indicator_animation_list_step_r_state_t;

void fd_indicator_animation_list_step_r_initialize(fd_indicator_animation_list_step_r_state_t *state) {
    state->index = 0;
    state->r.base = 0.0f;
    state->r.scale = 1.0f;
}

bool fd_indicator_animation_list_step_r(void *state_p) {
    fd_indicator_animation_list_step_r_state_t *state = state_p;
    float v = state->values[state->index++];
    uint8_t r = fd_indicator_animation_equ(state->r, v);
    switch (state->led) {
        case 0:
            fd_led_set_d0(r);
            break;
        case 4:
            fd_led_set_d4(r);
            break;
        default:
            break;
    }
    bool done = state->index >= state->size;
    if (done) {
        state->index = 0;
    }
    return done;
}

// USB power indication

typedef struct {
    fd_indicator_usb_condition_t condition_showing;
    fd_indicator_usb_condition_t condition_current;

    fd_indicator_animation_list_step_og_state_t in_state;
    fd_indicator_animation_list_step_og_state_t cycle_state;
    fd_indicator_animation_list_step_og_state_t out_state;
    fd_indicator_animation_t animation;
} fd_indicator_usb_t;

static
fd_indicator_usb_t usb;

static
void usb_initialize(void) {
    usb.condition_showing = usb.condition_current = fd_indicator_usb_condition_unpowered;
    fd_indicator_animation_initialize(&usb.animation);
}

static
void usb_off(void) {
    fd_led_set_usb(0, 0);
}

static
void usb_show(void);

static
void usb_run(
    float o, float g,
    float in_base, float in_scale,
    float cycle_base, float cycle_scale,
    float out_base, float out_scale
) {
    usb.in_state.o.base = o * in_base;
    usb.in_state.o.scale = o * in_scale;
    usb.in_state.g.base = g * in_base;
    usb.in_state.g.scale = g * in_scale;

    usb.cycle_state.o.base = o * cycle_base;
    usb.cycle_state.o.scale = o * cycle_scale;
    usb.cycle_state.g.base = g * cycle_base;
    usb.cycle_state.g.scale = g * cycle_scale;

    usb.out_state.o.base = o * out_base;
    usb.out_state.o.scale = o * out_scale;
    usb.out_state.g.base = g * out_base;
    usb.out_state.g.scale = g * out_scale;

    fd_indicator_animation_initialize(&usb.animation);
    usb.animation.in.step_fn = fd_indicator_animation_list_step_og;
    usb.animation.in.step_state = &usb.in_state;
    usb.animation.cycle.step_fn = fd_indicator_animation_list_step_og;
    usb.animation.cycle.step_state = &usb.cycle_state;
    usb.animation.out.step_fn = fd_indicator_animation_list_step_og;
    usb.animation.out.step_state = &usb.out_state;
    usb.animation.done_fn = usb_show;

    fd_indicator_animation_run(&usb.animation);
}

static
void usb_start_animation_powered_not_charging(void) {
    fd_indicator_animation_list_step_og_initialize(&usb.in_state);
    usb.in_state.size = sizeof(fd_indicator_animation_ease_linear_in);
    usb.in_state.values = fd_indicator_animation_ease_linear_in;

    fd_indicator_animation_list_step_og_initialize(&usb.cycle_state);
    usb.cycle_state.size = sizeof(fd_indicator_animation_ease_single);
    usb.cycle_state.values = fd_indicator_animation_ease_single;

    fd_indicator_animation_list_step_og_initialize(&usb.out_state);
    usb.out_state.size = sizeof(fd_indicator_animation_ease_linear_out);
    usb.out_state.values = fd_indicator_animation_ease_linear_out;

    usb_run(0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f);
}

static
void usb_start_animation_powered_charging(void) {
    fd_indicator_animation_list_step_og_initialize(&usb.in_state);
    usb.in_state.size = sizeof(fd_indicator_animation_ease_linear_in);
    usb.in_state.values = fd_indicator_animation_ease_linear_in;

    fd_indicator_animation_list_step_og_initialize(&usb.cycle_state);
    usb.cycle_state.size = sizeof(fd_indicator_animation_ease_quad_pulse);
    usb.cycle_state.values = fd_indicator_animation_ease_quad_pulse;

    fd_indicator_animation_list_step_og_initialize(&usb.out_state);
    usb.out_state.size = sizeof(fd_indicator_animation_ease_linear_out);
    usb.out_state.values = fd_indicator_animation_ease_linear_out;

    usb_run(1.0f, 0.0f, 0.0f, 0.2f, 51.0f, 0.8f, 0.0f, 0.2f);
}

static
void usb_show(void) {
    switch (usb.condition_current) {
        case fd_indicator_usb_condition_unpowered:
            usb_off();
        break;
        case fd_indicator_usb_condition_powered_not_charging:
            usb_start_animation_powered_not_charging();
        break;
        case fd_indicator_usb_condition_powered_charging:
            usb_start_animation_powered_charging();
        break;
    }
    usb.condition_showing = usb.condition_current;
}

void fd_indicator_set_usb_condition(fd_indicator_usb_condition_t condition) {
    if (usb.condition_current == condition) {
        return;
    }

    if (usb.condition_showing == condition) {
        fd_indicator_animation_run(&usb.animation);
        usb.condition_current = condition;
        return;
    }

    if (usb.animation.running) {
        fd_indicator_animation_cancel(&usb.animation);
        usb.condition_current = condition;
        return;
    }

    // start usb animation
    usb.condition_current = condition;

    usb_show();
}

// communication indication

typedef struct {
    fd_indicator_connection_condition_t condition_showing;
    fd_indicator_connection_condition_t condition_current;

    fd_indicator_animation_list_step_rgb_state_t cycle_state;
    fd_indicator_animation_t animation;

    uint32_t led;
    float r;
    float g;
    float b;
    fd_indicator_animation_event_fn_t done_fn;
} fd_indicator_connection_t;

static
void connection_initialize(fd_indicator_connection_t *connection, uint32_t led, float r, float g, float b, fd_indicator_animation_event_fn_t done_fn) {
    connection->condition_showing = connection->condition_current = fd_indicator_connection_condition_unconnected;
    fd_indicator_animation_initialize(&connection->animation);
    connection->led = led;
    connection->r = r;
    connection->g = g;
    connection->b = b;
    connection->done_fn = done_fn;
}

static
void connection_off(fd_indicator_connection_t *connection) {
    switch (connection->led) {
        case 1:
            fd_led_set_d1(0, 0, 0);
        break;
        case 2:
            fd_led_set_d2(0, 0, 0);
        break;
        case 3:
            fd_led_set_d3(0, 0, 0);
        break;
    }
}

static
void connection_run(
    fd_indicator_connection_t *connection,
    float cycle_base, float cycle_scale
) {
    connection->cycle_state.r.base = connection->r * cycle_base;
    connection->cycle_state.r.scale = connection->r * cycle_scale;
    connection->cycle_state.g.base = connection->g * cycle_base;
    connection->cycle_state.g.scale = connection->g * cycle_scale;
    connection->cycle_state.b.base = connection->b * cycle_base;
    connection->cycle_state.b.scale = connection->b * cycle_scale;
    connection->cycle_state.led = connection->led;

    fd_indicator_animation_t *animation = &connection->animation;
    fd_indicator_animation_initialize(animation);
    animation->cycle.step_fn = fd_indicator_animation_list_step_rgb;
    animation->cycle.step_state = &connection->cycle_state;
    animation->done_fn = connection->done_fn;

    fd_indicator_animation_run(animation);
}

static
void connection_start_animation_not_syncing(fd_indicator_connection_t *connection) {
    fd_indicator_animation_list_step_rgb_state_t *cycle_state = &connection->cycle_state;
    fd_indicator_animation_list_step_rgb_initialize(cycle_state);
    cycle_state->count = 3 * 32 + sizeof(fd_indicator_animation_ease_quad_pulse);
    cycle_state->size = sizeof(fd_indicator_animation_ease_quad_pulse);
    cycle_state->values = fd_indicator_animation_ease_quad_pulse;

    connection_run(connection, 0.0f, 0.1f);
}

static
void connection_start_animation_syncing(fd_indicator_connection_t *connection) {
    fd_indicator_animation_list_step_rgb_state_t *cycle_state = &connection->cycle_state;
    fd_indicator_animation_list_step_rgb_initialize(cycle_state);
    cycle_state->count = sizeof(fd_indicator_animation_ease_quad_pulse);
    cycle_state->size = sizeof(fd_indicator_animation_ease_quad_pulse);
    cycle_state->values = fd_indicator_animation_ease_quad_pulse;

    connection_run(connection, 0.0f, 1.0f);
}

static
void connection_show(fd_indicator_connection_t *connection) {
    switch (connection->condition_current) {
        case fd_indicator_connection_condition_unconnected:
            connection_off(connection);
        break;
        case fd_indicator_connection_condition_not_syncing:
            connection_start_animation_not_syncing(connection);
        break;
        case fd_indicator_connection_condition_syncing:
            connection_start_animation_syncing(connection);
        break;
    }
    connection->condition_showing = connection->condition_current;
}

static
void connection_set_condition(fd_indicator_connection_t *connection, fd_indicator_connection_condition_t condition) {
    if (connection->condition_current == condition) {
        return;
    }

    if (connection->condition_showing == condition) {
        fd_indicator_animation_run(&connection->animation);
        connection->condition_current = condition;
        return;
    }

    if (connection->animation.running) {
        fd_indicator_animation_cancel(&connection->animation);
        connection->condition_current = condition;
        return;
    }

    // start animation
    connection->condition_current = condition;

    connection_show(connection);
}

// usb communication indication

static
fd_indicator_connection_t usb_connection;

static
void usb_connection_show(void) {
    connection_show(&usb_connection);
}

void fd_indicator_set_usb_connection_condition(fd_indicator_connection_condition_t condition) {
    connection_set_condition(&usb_connection, condition);
}

// ble communication indication

static
fd_indicator_connection_t ble_connection;

static
void ble_connection_show(void) {
    connection_show(&ble_connection);
}

void fd_indicator_set_ble_connection_condition(fd_indicator_connection_condition_t condition) {
    connection_set_condition(&ble_connection, condition);
}

// identify indication

typedef struct {
    fd_indicator_identify_condition_t condition_showing;
    fd_indicator_identify_condition_t condition_current;

    fd_indicator_animation_list_step_rgb_state_t cycle_state;
    fd_indicator_animation_t animation;
} fd_indicator_identify_t;

static
fd_indicator_identify_t identify;

static
fd_timer_t identify_timer;

static
void identify_timer_callback(void) {
    fd_indicator_set_identify_condition(fd_indicator_identify_condition_inactive);
}

static
void identify_initialize(void) {
    identify.condition_showing = identify.condition_current = fd_indicator_identify_condition_inactive;
    fd_indicator_animation_initialize(&identify.animation);
    identify.cycle_state.led = 2;

    fd_timer_add(&identify_timer, identify_timer_callback);
}

static
void identify_off(void) {
    fd_led_set_d2(0, 0, 0);
}

static
void identify_show(void);

static
void identify_run(
    float r, float g, float b,
    float cycle_base, float cycle_scale
) {
    identify.cycle_state.r.base = r * cycle_base;
    identify.cycle_state.r.scale = r * cycle_scale;
    identify.cycle_state.g.base = g * cycle_base;
    identify.cycle_state.g.scale = g * cycle_scale;
    identify.cycle_state.b.base = b * cycle_base;
    identify.cycle_state.b.scale = b * cycle_scale;

    fd_indicator_animation_initialize(&identify.animation);
    identify.animation.cycle.step_fn = fd_indicator_animation_list_step_rgb;
    identify.animation.cycle.step_state = &identify.cycle_state;
    identify.animation.done_fn = identify_show;

    fd_indicator_animation_run(&identify.animation);
}

static
void identify_start_animation_active(void) {
    fd_indicator_animation_list_step_rgb_initialize(&identify.cycle_state);
    identify.cycle_state.count = sizeof(fd_indicator_animation_ease_quad_pulse);
    identify.cycle_state.size = sizeof(fd_indicator_animation_ease_quad_pulse);
    identify.cycle_state.values = fd_indicator_animation_ease_quad_pulse;

    identify_run(1.0f, 1.0f, 1.0f, 0.0f, 1.0f);
}

static
void identify_show(void) {
    switch (identify.condition_current) {
        case fd_indicator_identify_condition_inactive:
            identify_off();
        break;
        case fd_indicator_identify_condition_active:
            identify_start_animation_active();
        break;
    }
    identify.condition_showing = identify.condition_current;
}

void fd_indicator_set_identify_condition(fd_indicator_identify_condition_t condition) {
    if (identify.condition_current == condition) {
        return;
    }

    if (identify.condition_showing == condition) {
        fd_indicator_animation_run(&identify.animation);
        identify.condition_current = condition;
        return;
    }

    if (identify.animation.running) {
        fd_indicator_animation_cancel(&identify.animation);
        identify.condition_current = condition;
        return;
    }

    // start identify animation
    identify.condition_current = condition;

    identify_show();
}

void fd_indicator_set_identify_condition_active(fd_time_t duration) {
    fd_indicator_set_identify_condition(fd_indicator_identify_condition_active);
    fd_timer_start(&identify_timer, duration);
}

// error indication

typedef struct {
    fd_indicator_error_condition_t condition_showing;
    fd_indicator_error_condition_t condition_current;

    fd_indicator_animation_list_step_r_state_t cycle_state;
    fd_indicator_animation_t animation;
} fd_indicator_error_t;

static
fd_indicator_error_t error;

static
void error_initialize(void) {
    error.condition_showing = error.condition_current = fd_indicator_error_condition_inactive;
    fd_indicator_animation_initialize(&error.animation);
}

static
void error_off(void) {
    fd_led_set_d0(0);
    fd_led_set_d4(0);
}

static
void error_flip(void) {
    error.cycle_state.led = error.cycle_state.led == 0 ? 4 : 0;
}

static
void error_show(void);

static
void error_start_animation_active(void) {
    fd_indicator_animation_list_step_r_initialize(&error.cycle_state);
    error.cycle_state.size = sizeof(fd_indicator_animation_ease_quad_pulse);
    error.cycle_state.values = fd_indicator_animation_ease_quad_pulse;
    error.cycle_state.led = 0;

    fd_indicator_animation_initialize(&error.animation);
    error.animation.cycle.step_fn = fd_indicator_animation_list_step_r;
    error.animation.cycle.step_state = &error.cycle_state;
    error.animation.cycle.done_fn = error_flip;
    error.animation.done_fn = error_show;

    fd_indicator_animation_run(&error.animation);
}

static
void error_show(void) {
    switch (error.condition_current) {
        case fd_indicator_error_condition_inactive:
            error_off();
        break;
        case fd_indicator_error_condition_active:
            error_start_animation_active();
        break;
    }
    error.condition_showing = error.condition_current;
}

void fd_indicator_set_error_condition(fd_indicator_error_condition_t condition) {
    if (error.condition_current == condition) {
        return;
    }

    if (error.condition_showing == condition) {
        fd_indicator_animation_run(&error.animation);
        error.condition_current = condition;
        return;
    }

    if (error.animation.running) {
        fd_indicator_animation_cancel(&error.animation);
        error.condition_current = condition;
        return;
    }

    // start error animation
    error.condition_current = condition;

    error_show();
}

// indicator

static bool fd_indicator_running;

void fd_indicator_running_check(void) {
    fd_indicator_running =
        usb.animation.running |
        usb_connection.animation.running |
        ble_connection.animation.running |
        identify.animation.running |
        error.animation.running;
}

void fd_indicator_step(void) {
    if (fd_indicator_running) {
        fd_indicator_animation_step(&usb.animation);
        fd_indicator_animation_step(&usb_connection.animation);
        fd_indicator_animation_step(&ble_connection.animation);
        fd_indicator_animation_step(&identify.animation);
        fd_indicator_animation_step(&error.animation);
    }
}

void fd_indicator_sleep(void) {
    usb_initialize();
    connection_initialize(&usb_connection, 3, 0.0f, 1.0f, 0.0f, usb_connection_show);
    connection_initialize(&ble_connection, 1, 0.0f, 0.0f, 1.0f, ble_connection_show);
    identify_initialize();
    error_initialize();
}

void fd_indicator_initialize(void) {
    fd_indicator_running = false;
    fd_indicator_sleep();

    fd_event_add_callback(FD_EVENT_RTC_TICK, fd_indicator_step);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate OGM, Domain model persistence for NoSQL datastores
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<arquillian xmlns="http://jboss.org/schema/arquillian"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd">

    <defaultProtocol type="Servlet 3.0" />

    <group qualifier="hotrod-client-server" default="true">
        <container qualifier="wildfly" default="true">
            <configuration>
                <property name="jbossHome">${home.wildfly}</property>
                <property name="managementPort">10990</property>
                <property name="javaVmArguments">-XX:MaxPermSize=512m -Djava.net.preferIPv4Stack=true -XX:+IgnoreUnrecognizedVMOptions -Djboss.socket.binding.port-offset=1000</property>
                <property name="serverConfig">standalone.xml</property>
            </configuration>
        </container>
    </group>

</arquillian>


text:
package au.innovation.utility;

public class LogOutput {
	protected static boolean m_bEnable = false;
	protected static boolean m_bEnableDebug = false;

	public static void enable(boolean bEnable) {
		m_bEnable = bEnable;
	}

	public static void setDebug(boolean bEnableDebug) {
		m_bEnableDebug = bEnableDebug;
	}

	public static boolean isEnable() {
		return m_bEnable;
	}

	public static void debug(String strInformation) {
		if (m_bEnableDebug) {
			System.out.print(strInformation);
		}
	}

	public static void print(String strInformation) {
		if (m_bEnable) {
			System.out.print(strInformation);
		}
	}

	public static void printHex(byte ch) {
		if (m_bEnable) {
			System.out.print(StringUtility.byte2Hex(ch));
		}
	}

}


text:
function rcnn_model = rcnn_load_model(rcnn_model_or_file, use_gpu)
% rcnn_model = rcnn_load_model(rcnn_model_or_file, use_gpu)
%   Takes an rcnn_model structure and loads the associated Caffe
%   CNN into memory. Since this is nasty global state that is carried
%   around, a randomly generated 'key' (or handle) is returned.
%   Before making calls to caffe it's a good idea to check that
%   rcnn_model.cnn.key is the same as caffe('get_init_key').

% AUTORIGHTS
% ---------------------------------------------------------
% Copyright (c) 2014, Ross Girshick
%
% This file is part of the R-CNN code and is available
% under the terms of the Simplified BSD License provided in
% LICENSE. Please retain this notice and LICENSE if you use
% this file (or any portion of it) in your project.
% ---------------------------------------------------------

if isstr(rcnn_model_or_file)
  assert(exist(rcnn_model_or_file, 'file') ~= 0);
  ld = load(rcnn_model_or_file);
  rcnn_model = ld.rcnn_model; clear ld;
else
  rcnn_model = rcnn_model_or_file;
end

rcnn_model.cnn.init_key = ...
    caffe('init', rcnn_model.cnn.definition_file, rcnn_model.cnn.binary_file);

if exist('use_gpu', 'var') && ~use_gpu
  caffe('set_mode_cpu');
else
  caffe('set_mode_gpu');
end
caffe('set_phase_test');

rcnn_model.cnn.layers = caffe('get_weights');


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'selector',
  template: `Super Simple HTML<div></div><div></div>`,
  styles: [``]
})
export class BasicComponent implements OnInit {
  constructor() { }

  ngOnInit() { }
}


text:
import { selectAdapterConfigurationStatus } from '@flopflip/react';
import {
  type TAdapterStatus,
  type TAdapterStatusChange,
  AdapterConfigurationStatus,
  AdapterSubscriptionStatus,
} from '@flopflip/types';

import { STATE_SLICE } from '../../store/constants';
import type { TState } from '../../types';
import type { TUpdateStatusAction } from './types';

// Actions
export const UPDATE_STATUS = '@flopflip/status/update';

const initialState: TAdapterStatus = {
  subscriptionStatus: AdapterSubscriptionStatus.Subscribed,
  configurationStatus: AdapterConfigurationStatus.Unconfigured,
};

// Reducer
const reducer = (
  // eslint-disable-next-line @typescript-eslint/default-param-last
  state: TAdapterStatus = initialState,
  action: TUpdateStatusAction
): TAdapterStatus => {
  switch (action.type) {
    case UPDATE_STATUS:
      return {
        ...state,
        ...action.payload.status,
      };

    default:
      return state;
  }
};

export default reducer;

// Action Creators
export const updateStatus = (
  statusChange: TAdapterStatusChange
): TUpdateStatusAction => ({
  type: UPDATE_STATUS,
  payload: statusChange,
});
// Selectors
export const selectStatus = (state: TState) => {
  const { status } = state[STATE_SLICE];

  return selectAdapterConfigurationStatus(status?.configurationStatus);
};


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Ignoring overdraw as the background gives the "click" view -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:orientation="vertical"
    android:paddingEnd="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingStart="16dp"
    android:paddingTop="12dp"
    android:background="@drawable/pressed_item_background">

    <TextView
        android:id="@+id/search_result_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/textColorPrimary"
        android:maxLines="1"
        android:ellipsize="end"
        tools:text="Search Result"/>

</LinearLayout>


text:
package ca.sapon.jici.parser.expression.assignment;

import ca.sapon.jici.evaluator.Environment;
import ca.sapon.jici.evaluator.EvaluatorException;
import ca.sapon.jici.evaluator.type.Type;
import ca.sapon.jici.evaluator.value.Value;
import ca.sapon.jici.lexer.Symbol;
import ca.sapon.jici.lexer.literal.number.IntLiteral;
import ca.sapon.jici.parser.expression.Expression;
import ca.sapon.jici.parser.expression.arithmetic.Arithmetic;
import ca.sapon.jici.parser.expression.reference.Reference;
import ca.sapon.jici.parser.statement.Statement;

public class PostIncrement implements Expression, Statement {
    private static final IntLiteral ONE = new IntLiteral("1", 0) {
        @Override
        public int asInt() {
            return 1;
        }
    };
    protected final Reference inner;
    protected final Arithmetic increment;
    protected final Symbol operator;
    private int start;
    private int end;
    protected Type type = null;

    public PostIncrement(Reference inner, Symbol operator) {
        this(inner, operator, inner.getStart(), operator.getEnd());
    }

    public PostIncrement(Reference inner, Symbol operator, int start, int end) {
        this.inner = inner;
        this.operator = operator;
        increment = new Arithmetic(inner, ONE, operator.getCompoundAssignOperator());
        this.start = start;
        this.end = end;
    }

    @Override
    public void execute(Environment environment) {
        try {
            getType(environment);
            getValue(environment);
        } catch (EvaluatorException exception) {
            throw exception;
        } catch (Exception exception) {
            throw new EvaluatorException(exception, this);
        }
    }

    @Override
    public Type getType(Environment environment) {
        if (type != null) {
            return type;
        }
        increment.getType(environment);
        final Type innerType = increment.getLeftType();
        if (!innerType.isNumeric()) {
            throw new EvaluatorException("Not a numeric type: " + innerType.getName(), inner);
        }
        return type = innerType;
    }

    @Override
    public Value getValue(Environment environment) {
        final Value value = inner.getValue(environment);
        final Value result = increment.getValue(environment);
        inner.setValue(environment, type.getKind().convert(result));
        return value;
    }

    @Override
    public int getStart() {
        return start;
    }

    @Override
    public int getEnd() {
        return end;
    }

    @Override
    public void setStart(int start) {
        this.start = start;
    }

    @Override
    public void setEnd(int end) {
        this.end = end;
    }

    @Override
    public String toString() {
        return "PostIncrement(" + inner.toString() + operator.toString() + ")";
    }
}


text:
id: update
title: "Data updates"
---

<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you 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.
  -->

## Overwrite

Apache Druid stores data [partitioned by time chunk](../design/architecture.md#datasources-and-segments) and supports
overwriting existing data using time ranges. Data outside the replacement time range is not touched. Overwriting of
existing data is done using the same mechanisms as [batch ingestion](../ingestion/index.md#batch).

For example:

- [Native batch](../ingestion/native-batch.md) with `appendToExisting: false`, and `intervals` set to a specific
  time range, overwrites data for that time range.
- [SQL `REPLACE <table> OVERWRITE [ALL | WHERE ...]`](../multi-stage-query/reference.md#replace) overwrites data for
  the entire table or for a specified time range.

In both cases, Druid's atomic update mechanism ensures that queries will flip seamlessly from the old data to the new
data on a time-chunk-by-time-chunk basis.

Ingestion and overwriting cannot run concurrently for the same time range of the same datasource. While an overwrite job
is ongoing for a particular time range of a datasource, new ingestions for that time range are queued up. Ingestions for
other time ranges proceed as normal. Read-only queries also proceed as normal, using the pre-existing version of the
data.

Druid does not support single-record updates by primary key.

## Reindex

Reindexing is an [overwrite of existing data](#overwrite) where the source of new data is the existing data itself. It
is used to perform schema changes, repartition data, filter out unwanted data, enrich existing data, and so on. This
behaves just like any other [overwrite](#overwrite) with regard to atomic updates and locking.

With [native batch](../ingestion/native-batch.md), use the [`druid` input
source](../ingestion/native-batch-input-source.md#druid-input-source). If needed,
[`transformSpec`](../ingestion/ingestion-spec.md#transformspec) can be used to filter or modify data during the
reindexing job.

With SQL, use [`REPLACE <table> OVERWRITE`](../multi-stage-query/reference.md#replace) with `SELECT ... FROM <table>`.
(Druid does not have `UPDATE` or `ALTER TABLE` statements.) Any SQL SELECT query can be used to filter,
modify, or enrich the data during the reindexing job.

## Rolled-up datasources

Rolled-up datasources can be effectively updated using appends, without rewrites. When you append a row that has an
identical set of dimensions to an existing row, queries that use aggregation operators automatically combine those two
rows together at query time.

[Compaction](compaction.md) or [automatic compaction](automatic-compaction.md) can be used to physically combine these
matching rows together later on, by rewriting segments in the background.

## Lookups

If you have a dimension where values need to be updated frequently, try first using [lookups](../querying/lookups.md). A
classic use case of lookups is when you have an ID dimension stored in a Druid segment, and want to map the ID dimension to a
human-readable string that may need to be updated periodically.


text:
<%#
 Copyright 2013-2017 the original author or authors.

 This file is part of the JHipster project, see https://jhipster.github.io/
 for more information.

 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.
-%>
import { HttpInterceptor, EventManager } from 'ng-jhipster';
import { RequestOptionsArgs, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

export class ErrorHandlerInterceptor extends HttpInterceptor {

    constructor(private eventManager: EventManager) {
        super();
    }

    requestIntercept(options?: RequestOptionsArgs): RequestOptionsArgs {
        return options;
    }

    responseIntercept(observable: Observable<Response>): Observable<Response> {
        return <Observable<Response>> observable.catch((error) => {
            if (!(error.status === 401 && (error.text() === '' ||
                (error.json().path && error.json().path.indexOf('/api/account') === 0 )))) {
                this.eventManager.broadcast( {name: '<%=angularAppName%>.httpError', content: error});
            }
            return Observable.throw(error);
        });
    }
}


text:
require 'bio-foo-db/foo-db.rb'

require 'bio/foodb/connect'

require 'bio/foodb/example'


text:
layout: post
title: Cook n Share
projectUrl: http://cooknshare.herokuapp.com/
externalUrl: true
useExcerpt: false
---

 Make food with blocks and share them so others can see your beautiful work!


text:
<?xml version="1.0" encoding="UTF-8"?>
<outputEventAdaptor name="HttpEventAdaptor" statistics="disable"
  trace="enable" type="http" xmlns="http://wso2.org/carbon/eventadaptormanager"/>


text:
require 'signatured3'
print('signatured1: this source was signatured!')


text:
data.raw["item"]["rail-signal"].icon = "__rail-icons__/rail-signal.png"
data.raw["item"]["rail-chain-signal"].icon = "__rail-icons__/rail-chain-signal.png"
data.raw["rail-signal"]["rail-signal"].icon = "__rail-icons__/rail-signal.png"
data.raw["rail-chain-signal"]["rail-chain-signal"].icon = "__rail-icons__/rail-chain-signal.png"


text:
var queryString = window.location.search;
// get the testName from the url
var testName = queryString.split("test=")[1]

// let requirejs handle loading the test
define([ 'jquery', 'testUtilities', testName ], function($, utils, test) {

  utils.log.info("\033[32mTest runner running test '" + testName + "'\033[0m");
  utils.log.info("");

  try {
    test(utils);
  } catch (e) {
    utils.event.error(e);
  }

  utils.log.info("");
  utils.log.info("\033[36mTest '" + testName + "' complete\033[0m");
  utils.log.info("");

  /*
   * This is not strictly nescessary, but speeds up testing because the
   * framework does not have to wait on the idleTimeout
   */
  utils.done()
});


text:
<?php

include 'Admin.php';

class merchant extends admin {

  function __construct() {
    parent::__construct();
    parent::checkauth();
    $this->data['active_page'] = "merchant";
  }
  public function json(){
    $dest_table_as = 'merchant as m';
    $select_values = array('m.*');
    $params = new stdClass();
    $params->dest_table_as = $dest_table_as;
    $params->select_values = $select_values;
    $get = $this->data_model->get($params);
    echo json_encode(array("data" => $get['results']));
  }
  //Data on Page
  public function index() {
    $this->data['title_page'] = "Data Merchant";
    parent::display('admin/merchant/index','admin/merchant/function',TRUE);
  }

  public function add() {
    $this->data['title_page'] = "Tambah Merchant";
    parent::display('admin/merchant/add','admin/merchant/function',FALSE);
  }

  public function post(){
    $name = $this->input->post("name");
    $owner = $this->input->post("owner");
    $email = $this->input->post("email");
    $contact = $this->input->post("contact");
    $address = $this->input->post("address");
    $link = strtolower(preg_replace("/[^a-zA-Z0-9]/", "", $name));

    $params_check = new stdClass();
    $params_check->dest_table_as = 'merchant as m';
    $params_check->select_values = array('m.link', 'm.id');
    $where_data = array("where_column" => 'm.link', "where_value" => $link);
    $params_check->where_tables = array($where_data);
    $check = $this->data_model->get($params_check);
    if (!empty($check['results'])) {
      $params = new stdClass();
      $params->response = FAIL_STATUS;
      $params->message = "Nama sudah digunakan !";
      $params->data = "";
      $result = response_custom($params);
      echo json_encode($result);
      exit();
    }

    $params_data = array(
      "name" => $name,
      "owner" => $owner,
      "link" => $link,
      "email" => $email,
      "contact" => $contact,
      "address" => $address,
      "status" => 'A',
      "update_at" => date('d-m-Y h:m')
    );
    $dest_table = 'merchant';
    $add = $this->data_model->add($params_data, $dest_table);
    $merchant_id = $add["data"];
    $merchant_dir = BACKEND_IMAGE_UPLOAD_FOLDER.'merchant/'.$merchant_id;
    $create_dir = mkdir($merchant_dir);
    $create_logo_dir = mkdir($merchant_dir . "/logo");
    $create_cover_dir = mkdir($merchant_dir. "/cover");
    $create_product_dir = mkdir($merchant_dir. "/product");
    $create_promo_dir = mkdir($merchant_dir. "/promo");

    if (isset($_FILES["logo"])) {
      if ($_FILES["logo"] != "") {
        $upload_logo = image_upload(array($_FILES["logo"]), $merchant_dir . "/logo/");
        $image_logo_name = $upload_logo->data[0];
      } else {
        $image_logo_name = "";
      }
    } else {
      $image_logo_name = "";
    }
    if (isset($_FILES["cover"])) {
      if ($_FILES["cover"] != "") {
        $upload_cover = image_upload(array($_FILES["cover"]), $merchant_dir. "/cover/");
        $image_cover_name = $upload_cover->data[0];
      } else {
        $image_cover_name = "";
      }
    } else {
      $image_cover_name = "";
    }

    $params_update = new stdClass();
    $params_update->new_data = array("logo" => $image_logo_name, "cover" => $image_cover_name);
    $params_update->table_update = 'merchant';
    $where = array("where_column" => 'id', "where_value" => $merchant_id);
    $params_update->where_tables = array($where);
    $update_logo_cover = $this->data_model->update($params_update);
    if ($add['response'] == OK_STATUS) {
      $data = array("link" => base_url() . 'admin/merchant/' . $link);
      $result = get_success($data);
    } else {
      $result = response_fail();
    }
    echo json_encode($result);
  }

  public function detail(){
    $parameter = $this->uri->segment(3);
    $params = new stdClass();
    $params->dest_table_as = 'merchant as m';
    $params->select_values = array('m.*');
    $params->where_tables = array(array("where_column" => 'm.link', "where_value" => $parameter));
    $get = $this->data_model->get($params);
    //CHECK DOMNameList
    if ($get["results"][0] != "") {
      //GET MAIN PROFILE
      $this->data['title_page'] = "Detail Merchant";
      $logo = $get['results'][0]->logo;
      $cover = $get['results'][0]->cover;
      $merchant_id = $get["results"][0]->id;
      $get["results"][0]->logo_old = $get['results'][0]->logo;
      $dir = BACKEND_IMAGE_UPLOAD_FOLDER . 'merchant/' . $get['results'][0]->id.'/';
      $image_dir_logo =  $dir.'logo/'. $logo;
      $check_thumb = check_if_empty($logo, $image_dir_logo);
      if($check_thumb == NO_IMG_NAME){
        $get["results"][0]->logo = BASE_URL.BACKEND_IMAGE_UPLOAD_FOLDER.'noimg.png';
      } else {
        $get["results"][0]->logo = BASE_URL . $dir.'logo/'.$check_thumb;
      }
      $get["results"][0]->cover_old = $get['results'][0]->cover;
      $image_dir_cover = $dir.'cover/' . $cover;
      $check_thumb = check_if_empty($cover, $image_dir_cover);
      if($check_thumb == NO_IMG_NAME){
        $get["results"][0]->cover = BASE_URL.BACKEND_IMAGE_UPLOAD_FOLDER.'noimg.png';
      } else {
        $get["results"][0]->cover = BASE_URL. $dir.'cover/' . $check_thumb;
      }
      $this->data['records'] = $get['results'][0];
      // GET SOCIAL MEDIA ACCOUNT
      $sc = new stdClass();
      $sc->dest_table_as = 'socmed as sc';
      $sc->select_values = array('sc.id as socmed_id','sc.name as socmed_name');
      $get_sc = $this->data_model->get($sc);
      if($get_sc['results'] != ""){
        foreach($get_sc['results'] as $each){
          $scm = new stdClass();
          $scm->dest_table_as = 'merchant_socmed as mc';
          $scm->select_values = array('*');
          $where1 = array("where_column" => 'mc.merchant_id', "where_value" => $merchant_id);
          $where2 = array("where_column" => 'mc.socmed_id', "where_value" => $each->socmed_id);
          $scm->where_tables = array($where1,$where2);
          $get_mc = $this->data_model->get($scm);
          if(empty($get_mc["results"][0])){
            $scm_id = "";
            $scm_url = "";
          } else {
            $scm_id = $get_mc["results"][0]->id;
            $scm_url = $get_mc["results"][0]->url;
          }
          $merchant_scm[] = array("sc_id" => $each->socmed_id,
          "sc_name"=> $each->socmed_name,
          "scm_id"=> $scm_id,
          "scm_url" => $scm_url
        );
      }
    }
    $this->data["merchant_scm"] = $merchant_scm;
    //GET PRODUCTS
    $products = new stdClass();
    $products->dest_table_as = 'product as pr';
    $products->select_values = array('pr.*','pc.name as category_name');
    $where1 = array("where_column" => 'pr.merchant_id', "where_value" => $merchant_id);
    $join1 = array("join_with" => 'product_category as pc', "join_on" => 'pr.product_category_id = pc.id', "join_type" => '');
    $products->where_tables = array($where1);
    $products->join_tables = array($join1);
    $get_products = $this->data_model->get($products);
    if($get_products["results"] !="" ){
      foreach($get_products["results"] as $each){
        $img = new stdClass();
        $img->dest_table_as = 'product_images as pi';
        $img->select_values = array('pi.name as thumbnail');
        $where1 = array("where_column" => 'pi.id_product', "where_value" => $each->id);
        $img->where_tables = array($where1);
        $get_thumbnail = $this->data_model->get($img);
        if(empty($get_thumbnail["results"][0]->thumbnail)){
          $thumbnail = base_url().BACKEND_IMAGE_UPLOAD_FOLDER.'noimg.png';
        } else {
          $img_name = $get_thumbnail["results"][0]->thumbnail;
          $product_dir = BACKEND_IMAGE_UPLOAD_FOLDER.'merchant/'.$merchant_id.'/product/'.$each->id.'/'.$img_name;
          $check_thumb = check_if_empty($img_name, $product_dir);
          if($check_thumb != NO_IMG_NAME){
            $thumbnail  = base_url().$product_dir;
          } else {
            $thumbnail = base_url().BACKEND_IMAGE_UPLOAD_FOLDER.'noimg.png';
          }
        }
        $each->thumbnail = $thumbnail;
      }

      $this->data["merchant_product"] = $get_products["results"];
    }
    parent::display('admin/merchant/detail','admin/merchant/function');
  } else {
    redirect('/admin/404');
  }
}

public function update(){
  $id = $this->input->post("id");
  $name = $this->input->post("name");
  $owner = $this->input->post("owner");
  $email = $this->input->post("email");
  $contact = $this->input->post("contact");
  $address = $this->input->post("address");
  $desc = $this->input->post("desc");
  $status = $this->input->post("status");
  $old_logo = $this->input->post("old_logo");
  $old_cover = $this->input->post("old_cover");
  $link = strtolower(preg_replace("/[^a-zA-Z0-9]/", "", $name));
  $socmed_data = $this->input->post("socmed_data");

  //CHECKNAME
  $params_check = new stdClass();
  $params_check->dest_table_as = 'merchant as m';
  $params_check->select_values = array('m.link', 'm.id');
  $where_data = array("where_column" => 'm.link', "where_value" => $link);
  $params_check->where_tables = array($where_data);
  $check = $this->data_model->get($params_check);
  // print_r($check);
  // print_r($id);
  if (!empty($check['results'])) {
    if ($check['results'][0]->id != $id) {
      $params = new stdClass();
      $params->response = FAIL_STATUS;
      $params->message = "Nama sudah digunakan !";
      $params->data = "";
      $result = response_custom($params);
      echo json_encode($result);
      exit();
    }
  }
  $params_data = new stdClass();
  $params_data->new_data = array(
    "name" => $name,
    "owner" => $owner,
    "link" => $link,
    "email" => $email,
    "contact" => $contact,
    "address" => $address,
    "status" => $status,
    "description" => $desc,
    "update_at" => date('d-m-Y h:m')
  );
  $where = array("where_column" => 'id', "where_value" => $id);
  $params_data->where_tables = array($where);
  $params_data->table_update = 'merchant';
  $update = $this->data_model->update($params_data);
  $error = [];
  if (isset($_FILES["logo"])) {
    if (!empty($_FILES["logo"]["name"])) {
      $upload_logo = image_upload(array($_FILES["logo"]), "assets/images/backend/merchant/" . $id . "/logo/");
      if ($upload_logo->response == OK_STATUS) {
        $image_logo_name = $upload_logo->data[0];
        if ($old_logo != "") {
          $remove_old = unlink('./assets/images/backend/merchant/' . $id . '/logo/' . $old_logo);
        }
      } else {
        if ($upload_logo->data['error']) {
          foreach ($upload_logo->data['error'] as $er) {
            array_push($error, $er);
          }
        }
        $image_logo_name = $old_logo;
      }
    } else {
      $image_logo_name = $old_logo;
    }
  } else {
    $image_logo_name = $old_logo;
  }
  if (isset($_FILES["cover"])) {
    if (!empty($_FILES["cover"]["name"])) {
      $upload_cover = image_upload(array($_FILES["cover"]), "assets/images/backend/merchant/" . $id . "/cover/");
      if ($upload_cover->response == OK_STATUS) {
        $image_cover_name = $upload_cover->data[0];
        if ($old_cover != "") {
          $remove_old = unlink('./assets/images/backend/merchant/' . $id . '/cover/' . $old_cover);
        }
      } else {
        if ($upload_cover->data['error']) {
          foreach ($upload_cover->data['error'] as $er) {
            array_push($error, $er);
          }
        }
        $image_cover_name = $old_cover;
      }
    } else {
      $image_cover_name = $old_cover;
    }
  } else {
    $image_cover_name = $old_cover;
  }

  if(isset($socmed_data)){
    $decode_socmed_data = json_decode($socmed_data);
    if(!empty($decode_socmed_data)){
      $params_delete = new stdClass();
      $where1 = array("where_column" => 'merchant_id', "where_value" => $id);
      $params_delete->where_tables = array($where1);
      $params_delete->table = 'merchant_socmed';
      $delete = $this->data_model->delete($params_delete);
    }
    foreach($decode_socmed_data as $data){

      $new_data = array(
        "socmed_id" => $data->sc_id,
        "merchant_id" => $id,
        "url" => $data->sc_value,
        "update_at" => date('d-m-Y h:m')
      );
      $dest_table_sc = 'merchant_socmed';
      $add_sc = $this->data_model->add($new_data, $dest_table_sc);
    }

  }

  $params_update = new stdClass();
  $params_update->new_data = array("logo" => $image_logo_name, "cover" => $image_cover_name);
  $where = array("where_column" => 'id', "where_value" => $id);
  $params_update->where_tables = array($where);
  $params_update->table_update = 'merchant';
  $update_logo_cover = $this->data_model->update($params_update);
  if ($update['response'] == OK_STATUS ) {
    $params = new stdClass();
    if ($error) {
      $params->response = FAIL_STATUS;
      $params->message = "Peringatan";
      $params->data = array('link' => base_url() . 'admin/merchant/' . $link);
      $params->data = $error;
    } else {
      $params->response = OK_STATUS;
      $params->message = OK_MESSAGE;
      $params->data = array('link' => base_url() . 'admin/merchant/' . $link);
    }
    $result = response_custom($params);
  } else {
    $result = response_fail();
  }
  echo json_encode($result);
}

public function delete_product($id,$merchant_id){

  $params_delete_img = new stdClass();
  $where1 = array("where_column" => 'id_product', "where_value" => $id);
  $params_delete_img->where_tables = array($where1);
  $params_delete_img->table = 'product_images';
  $delete_img = $this->data_model->delete($params_delete_img);

  $product_dir = BACKEND_IMAGE_UPLOAD_FOLDER.'merchant/'.$merchant_id.'/product/'.$id.'/';
  $files = glob($product_dir.'*');

  foreach($files as $file){
    $unlink_files = unlink($file);
  }

  $rm_dir = rmdir($product_dir);

  $params= new stdClass();
  $where1 = array("where_column" => 'id', "where_value" => $id);
  $params->where_tables = array($where1);
  $params->table = 'product';
  $delete_produk = $this->data_model->delete($params);
}

public function delete_socmed($id){
  $params_delete = new stdClass();
  $where1 = array("where_column" => 'id', "where_value" => $id);
  $params_delete->where_tables = array($where1);
  $params_delete->table = 'merchant_socmed';
  $delete = $this->data_model->delete($params_delete);
}

public function delete_promo($id,$merchant_id){
  $params_delete = new stdClass();
  $where1 = array("where_column" => 'id', "where_value" => $id);
  $params_delete->where_tables = array($where1);
  $params_delete->table = 'merchant_promo';
  $delete = $this->data_model->delete($params_delete);
  $dir = BACKEND_IMAGE_UPLOAD_FOLDER.'merchant/'.$merchant_id.'/promo/'.$id.'/';
  $files = glob($dir.'*');
  foreach($files as $file){
    $unlink_files = unlink($file);
  }
  $rm_dir = rmdir($dir);
}

public function delete(){
  $link = $this->input->post("link");

  $where1 = array("where_column" => 'link', "where_value" => $link);
  $dest_table_as = 'merchant';
  $select_values = array('id');
  $params = new stdClass();
  $params->dest_table_as = $dest_table_as;
  $params->select_values = $select_values;
  $params->where_tables = array($where1);
  $get = $this->data_model->get($params);
  // print_r($get);exit();
  $id_delete = $get['results'][0]->id;

  $product_data = new stdClass();
  $product_data->dest_table_as = 'product';
  $product_data->select_values = array('id');
  $product_data->where_tables = array(array("where_column" => 'merchant_id', "where_value" => $id_delete));
  $get_product_data = $this->data_model->get($product_data);
  $product_id = $get_product_data["results"];

  if($product_id != ""){
    $product_id_array = [];
    foreach($product_id as $product){
      array_push($product_id_array,$product->id);
    }
    foreach($product_id_array as $id){
      $this->delete_product($id,$id_delete);
    }
  }

  $socmed_data = new stdClass();
  $socmed_data->dest_table_as = 'merchant_socmed';
  $socmed_data->select_values = array('id');
  $socmed_data->where_tables = array(array("where_column" => 'merchant_id', "where_value" => $id_delete));
  $get_socmed_data = $this->data_model->get($socmed_data);
  $socmed_id = $get_socmed_data["results"];
  if($socmed_id != ""){
    $socmed_id_array = [];
    foreach($socmed_id as $socmed){
      array_push($socmed_id_array,$socmed->id);
    }

    foreach($socmed_id_array as $id){

      $this->delete_socmed($id);
    }
  }

  $promo_data = new stdClass();
  $promo_data->dest_table_as = 'merchant_promo';
  $promo_data->select_values = array('id');
  $promo_data->where_tables = array(array("where_column" => 'merchant_id', "where_value" => $id_delete));
  $get_promo_data = $this->data_model->get($promo_data);
  $promo_id = $get_promo_data["results"];
  if($promo_id != ""){
    $promo_id_array = [];
    foreach($promo_id as $promo){
      array_push($promo_id_array,$promo->id);
    }
    foreach($promo_id_array as $id){
      $this->delete_promo($id,$id_delete);
    }
  }

  $params_delete = new stdClass();
  $where1 = array("where_column" => 'id', "where_value" => $id_delete);
  $params_delete->where_tables = array($where1);
  $params_delete->table = 'merchant';
  $delete = $this->data_model->delete($params_delete);

  $dir = BACKEND_IMAGE_UPLOAD_FOLDER.'merchant/'.$id_delete.'/';
  $files = glob($dir.'*'.'/'.'*');
  $folders = glob($dir.'*');
  // print_r($files);exit();

  foreach($files as $file){
    if(is_file($file)){
      $unlink_files = unlink($file);
    }
    if(is_dir($file)){
      $rm = rmdir($file);
    }
  }

  foreach($folders as $file){
    if(is_file($file)){
      $unlink_files = unlink($file);
    }
    if(is_dir($file)){
      $rm = rmdir($file);
    }
  }

  $rm_dir = rmdir($dir);

  if ($delete['response'] == OK_STATUS) {
    $result = response_success();
  } else {
    $result = response_fail();
  }
  echo json_encode($result);
}

}