text:
namespace v8 {
namespace internal {
namespace test_unwinder {

static void* unlimited_stack_base = std::numeric_limits<void*>::max();

TEST(Unwind_BadState_Fail) {
  UnwindState unwind_state;  // Fields are intialized to nullptr.
  RegisterState register_state;

  bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                                 unlimited_stack_base);
  CHECK(!unwound);
  // The register state should not change when unwinding fails.
  CHECK_NULL(register_state.fp);
  CHECK_NULL(register_state.sp);
  CHECK_NULL(register_state.pc);
}

TEST(Unwind_BuiltinPCInMiddle_Success) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);

  UnwindState unwind_state = isolate->GetUnwindState();
  RegisterState register_state;

  uintptr_t stack[3];
  void* stack_base = stack + arraysize(stack);
  stack[0] = reinterpret_cast<uintptr_t>(stack + 2);  // saved FP (rbp).
  stack[1] = 202;  // Return address into C++ code.
  stack[2] = 303;  // The SP points here in the caller's frame.

  register_state.sp = stack;
  register_state.fp = stack;

  // Put the current PC inside of a valid builtin.
  Code builtin = i_isolate->builtins()->builtin(Builtins::kStringEqual);
  const uintptr_t offset = 40;
  CHECK_LT(offset, builtin->InstructionSize());
  register_state.pc =
      reinterpret_cast<void*>(builtin->InstructionStart() + offset);

  bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                                 stack_base);
  CHECK(unwound);
  CHECK_EQ(reinterpret_cast<void*>(stack + 2), register_state.fp);
  CHECK_EQ(reinterpret_cast<void*>(stack + 2), register_state.sp);
  CHECK_EQ(reinterpret_cast<void*>(202), register_state.pc);
}

// The unwinder should be able to unwind even if we haven't properly set up the
// current frame, as long as there is another JS frame underneath us (i.e. as
// long as the PC isn't in JSEntry). This test puts the PC at the start
// of a JS builtin and creates a fake JSEntry frame before it on the stack. The
// unwinder should be able to unwind to the C++ frame before the JSEntry frame.
TEST(Unwind_BuiltinPCAtStart_Success) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);

  UnwindState unwind_state = isolate->GetUnwindState();
  RegisterState register_state;

  const size_t code_length = 40;
  uintptr_t code[code_length] = {0};
  unwind_state.code_range.start = code;
  unwind_state.code_range.length_in_bytes = code_length * sizeof(uintptr_t);

  uintptr_t stack[6];
  void* stack_base = stack + arraysize(stack);
  stack[0] = 101;
  // Return address into JS code. It doesn't matter that this is not actually in
  // JSEntry, because we only check that for the top frame.
  stack[1] = reinterpret_cast<uintptr_t>(code + 10);
  stack[2] = reinterpret_cast<uintptr_t>(stack + 5);  // saved FP (rbp).
  stack[3] = 303;  // Return address into C++ code.
  stack[4] = 404;
  stack[5] = 505;

  register_state.sp = stack;
  register_state.fp = stack + 2;  // FP to the JSEntry frame.

  // Put the current PC at the start of a valid builtin, so that we are setting
  // up the frame.
  Code builtin = i_isolate->builtins()->builtin(Builtins::kStringEqual);
  register_state.pc = reinterpret_cast<void*>(builtin->InstructionStart());

  bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                                 stack_base);

  CHECK(unwound);
  CHECK_EQ(reinterpret_cast<void*>(stack + 5), register_state.fp);
  CHECK_EQ(reinterpret_cast<void*>(stack + 4), register_state.sp);
  CHECK_EQ(reinterpret_cast<void*>(303), register_state.pc);
}

const char* foo_source = R"(
  function foo(a, b) {
    let x = a * b;
    let y = x ^ b;
    let z = y / a;
    return x + y - z;
  }
  foo(1, 2);
  foo(1, 2);
  %OptimizeFunctionOnNextCall(foo);
  foo(1, 2);
)";

// Check that we can unwind when the pc is within an optimized code object on
// the V8 heap.
TEST(Unwind_CodeObjectPCInMiddle_Success) {
  FLAG_allow_natives_syntax = true;
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);
  HandleScope scope(i_isolate);

  UnwindState unwind_state = isolate->GetUnwindState();
  RegisterState register_state;

  uintptr_t stack[3];
  void* stack_base = stack + arraysize(stack);
  stack[0] = reinterpret_cast<uintptr_t>(stack + 2);  // saved FP (rbp).
  stack[1] = 202;  // Return address into C++ code.
  stack[2] = 303;  // The SP points here in the caller's frame.

  register_state.sp = stack;
  register_state.fp = stack;

  // Create an on-heap code object. Make sure we run the function so that it is
  // compiled and not just marked for lazy compilation.
  CompileRun(foo_source);
  v8::Local<v8::Function> local_foo = v8::Local<v8::Function>::Cast(
      env.local()->Global()->Get(env.local(), v8_str("foo")).ToLocalChecked());
  Handle<JSFunction> foo =
      Handle<JSFunction>::cast(v8::Utils::OpenHandle(*local_foo));

  // Put the current PC inside of the created code object.
  AbstractCode abstract_code = foo->abstract_code();
  // We don't produce optimized code when run with --no-opt.
  if (!abstract_code->IsCode() && FLAG_opt == false) return;
  CHECK(abstract_code->IsCode());

  Code code = abstract_code->GetCode();
  // We don't want the offset too early or it could be the `push rbp`
  // instruction (which is not at the start of generated code, because the lazy
  // deopt check happens before frame setup).
  const uintptr_t offset = code->InstructionSize() - 20;
  CHECK_LT(offset, code->InstructionSize());
  Address pc = code->InstructionStart() + offset;
  register_state.pc = reinterpret_cast<void*>(pc);

  // Check that the created code is within the code range that we get from the
  // API.
  Address start = reinterpret_cast<Address>(unwind_state.code_range.start);
  CHECK(pc >= start && pc < start + unwind_state.code_range.length_in_bytes);

  bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                                 stack_base);
  CHECK(unwound);
  CHECK_EQ(reinterpret_cast<void*>(stack + 2), register_state.fp);
  CHECK_EQ(reinterpret_cast<void*>(stack + 2), register_state.sp);
  CHECK_EQ(reinterpret_cast<void*>(202), register_state.pc);
}

// If the PC is within JSEntry but we haven't set up the frame yet, then we
// cannot unwind.
TEST(Unwind_JSEntryBeforeFrame_Fail) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();

  UnwindState unwind_state = isolate->GetUnwindState();
  RegisterState register_state;

  const size_t code_length = 40;
  uintptr_t code[code_length] = {0};
  unwind_state.code_range.start = code;
  unwind_state.code_range.length_in_bytes = code_length * sizeof(uintptr_t);

  // Pretend that it takes 5 instructions to set up the frame in JSEntry.
  unwind_state.js_entry_stub.code.start = code + 10;
  unwind_state.js_entry_stub.code.length_in_bytes = 10 * sizeof(uintptr_t);

  uintptr_t stack[10];
  void* stack_base = stack + arraysize(stack);
  stack[0] = 101;
  stack[1] = 111;
  stack[2] = 121;
  stack[3] = 131;
  stack[4] = 141;
  stack[5] = 151;
  stack[6] = 100;  // Return address into C++ code.
  stack[7] = 303;  // The SP points here in the caller's frame.
  stack[8] = 404;
  stack[9] = 505;

  register_state.sp = stack + 5;
  register_state.fp = stack + 9;

  // Put the current PC inside of JSEntry, before the frame is set up.
  register_state.pc = code + 12;
  bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                                 stack_base);
  CHECK(!unwound);
  // The register state should not change when unwinding fails.
  CHECK_EQ(reinterpret_cast<void*>(stack + 9), register_state.fp);
  CHECK_EQ(reinterpret_cast<void*>(stack + 5), register_state.sp);
  CHECK_EQ(code + 12, register_state.pc);

  // Change the PC to a few instructions later, after the frame is set up.
  register_state.pc = code + 16;
  unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                            stack_base);
  // TODO(petermarshall): More precisely check position within JSEntry rather
  // than just assuming the frame is unreadable.
  CHECK(!unwound);
  // The register state should not change when unwinding fails.
  CHECK_EQ(reinterpret_cast<void*>(stack + 9), register_state.fp);
  CHECK_EQ(reinterpret_cast<void*>(stack + 5), register_state.sp);
  CHECK_EQ(code + 16, register_state.pc);
}

TEST(Unwind_OneJSFrame_Success) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();

  UnwindState unwind_state = isolate->GetUnwindState();
  RegisterState register_state;

  // Use a fake code range so that we can initialize it to 0s.
  const size_t code_length = 40;
  uintptr_t code[code_length] = {0};
  unwind_state.code_range.start = code;
  unwind_state.code_range.length_in_bytes = code_length * sizeof(uintptr_t);

  // Our fake stack has two frames - one C++ frame and one JS frame (on top).
  // The stack grows from high addresses to low addresses.
  uintptr_t stack[10];
  void* stack_base = stack + arraysize(stack);
  stack[0] = 101;
  stack[1] = 111;
  stack[2] = 121;
  stack[3] = 131;
  stack[4] = 141;
  stack[5] = reinterpret_cast<uintptr_t>(stack + 9);  // saved FP (rbp).
  stack[6] = 100;  // Return address into C++ code.
  stack[7] = 303;  // The SP points here in the caller's frame.
  stack[8] = 404;
  stack[9] = 505;

  register_state.sp = stack;
  register_state.fp = stack + 5;

  // Put the current PC inside of the code range so it looks valid.
  register_state.pc = code + 30;

  bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                                 stack_base);

  CHECK(unwound);
  CHECK_EQ(reinterpret_cast<void*>(stack + 9), register_state.fp);
  CHECK_EQ(reinterpret_cast<void*>(stack + 7), register_state.sp);
  CHECK_EQ(reinterpret_cast<void*>(100), register_state.pc);
}

// Creates a fake stack with two JS frames on top of a C++ frame and checks that
// the unwinder correctly unwinds past the JS frames and returns the C++ frame's
// details.
TEST(Unwind_TwoJSFrames_Success) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();

  UnwindState unwind_state = isolate->GetUnwindState();
  RegisterState register_state;

  // Use a fake code range so that we can initialize it to 0s.
  const size_t code_length = 40;
  uintptr_t code[code_length] = {0};
  unwind_state.code_range.start = code;
  unwind_state.code_range.length_in_bytes = code_length * sizeof(uintptr_t);

  // Our fake stack has three frames - one C++ frame and two JS frames (on top).
  // The stack grows from high addresses to low addresses.
  uintptr_t stack[10];
  void* stack_base = stack + arraysize(stack);
  stack[0] = 101;
  stack[1] = 111;
  stack[2] = reinterpret_cast<uintptr_t>(stack + 5);  // saved FP (rbp).
  // The fake return address is in the JS code range.
  stack[3] = reinterpret_cast<uintptr_t>(code + 10);
  stack[4] = 141;
  stack[5] = reinterpret_cast<uintptr_t>(stack + 9);  // saved FP (rbp).
  stack[6] = 100;  // Return address into C++ code.
  stack[7] = 303;  // The SP points here in the caller's frame.
  stack[8] = 404;
  stack[9] = 505;

  register_state.sp = stack;
  register_state.fp = stack + 2;

  // Put the current PC inside of the code range so it looks valid.
  register_state.pc = code + 30;

  bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                                 stack_base);

  CHECK(unwound);
  CHECK_EQ(reinterpret_cast<void*>(stack + 9), register_state.fp);
  CHECK_EQ(reinterpret_cast<void*>(stack + 7), register_state.sp);
  CHECK_EQ(reinterpret_cast<void*>(100), register_state.pc);
}

// If the PC is in JSEntry then the frame might not be set up correctly, meaning
// we can't unwind the stack properly.
TEST(Unwind_JSEntry_Fail) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);

  UnwindState unwind_state = isolate->GetUnwindState();
  RegisterState register_state;

  Code js_entry = i_isolate->heap()->builtin(Builtins::kJSEntry);
  byte* start = reinterpret_cast<byte*>(js_entry->InstructionStart());
  register_state.pc = start + 10;

  bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                                 unlimited_stack_base);
  CHECK(!unwound);
  // The register state should not change when unwinding fails.
  CHECK_NULL(register_state.fp);
  CHECK_NULL(register_state.sp);
  CHECK_EQ(start + 10, register_state.pc);
}

TEST(Unwind_StackBounds_Basic) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();

  UnwindState unwind_state = isolate->GetUnwindState();
  RegisterState register_state;

  const size_t code_length = 10;
  uintptr_t code[code_length] = {0};
  unwind_state.code_range.start = code;
  unwind_state.code_range.length_in_bytes = code_length * sizeof(uintptr_t);

  uintptr_t stack[3];
  stack[0] = reinterpret_cast<uintptr_t>(stack + 2);  // saved FP (rbp).
  stack[1] = 202;  // Return address into C++ code.
  stack[2] = 303;  // The SP points here in the caller's frame.

  register_state.sp = stack;
  register_state.fp = stack;
  register_state.pc = code;

  void* wrong_stack_base = reinterpret_cast<void*>(
      reinterpret_cast<uintptr_t>(stack) - sizeof(uintptr_t));
  bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                                 wrong_stack_base);
  CHECK(!unwound);

  // Correct the stack base and unwinding should succeed.
  void* correct_stack_base = stack + arraysize(stack);
  unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                            correct_stack_base);
  CHECK(unwound);
}

TEST(Unwind_StackBounds_WithUnwinding) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();

  UnwindState unwind_state = isolate->GetUnwindState();
  RegisterState register_state;

  // Use a fake code range so that we can initialize it to 0s.
  const size_t code_length = 40;
  uintptr_t code[code_length] = {0};
  unwind_state.code_range.start = code;
  unwind_state.code_range.length_in_bytes = code_length * sizeof(uintptr_t);

  // Our fake stack has two frames - one C++ frame and one JS frame (on top).
  // The stack grows from high addresses to low addresses.
  uintptr_t stack[11];
  void* stack_base = stack + arraysize(stack);
  stack[0] = 101;
  stack[1] = 111;
  stack[2] = 121;
  stack[3] = 131;
  stack[4] = 141;
  stack[5] = reinterpret_cast<uintptr_t>(stack + 9);  // saved FP (rbp).
  stack[6] = reinterpret_cast<uintptr_t>(code + 20);  // JS code.
  stack[7] = 303;  // The SP points here in the caller's frame.
  stack[8] = 404;
  stack[9] = reinterpret_cast<uintptr_t>(stack) +
             (12 * sizeof(uintptr_t));                 // saved FP (OOB).
  stack[10] = reinterpret_cast<uintptr_t>(code + 20);  // JS code.

  register_state.sp = stack;
  register_state.fp = stack + 5;

  // Put the current PC inside of the code range so it looks valid.
  register_state.pc = code + 30;

  // Unwind will fail because stack[9] FP points outside of the stack.
  bool unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                                 stack_base);
  CHECK(!unwound);

  // Change the return address so that it is not in range.
  stack[10] = 202;
  unwound = v8::Unwinder::TryUnwindV8Frames(unwind_state, &register_state,
                                            stack_base);
  CHECK(!unwound);
}

TEST(PCIsInV8_BadState_Fail) {
  UnwindState unwind_state;
  void* pc = nullptr;

  CHECK(!v8::Unwinder::PCIsInV8(unwind_state, pc));
}

TEST(PCIsInV8_ValidStateNullPC_Fail) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();

  UnwindState unwind_state = isolate->GetUnwindState();
  void* pc = nullptr;

  CHECK(!v8::Unwinder::PCIsInV8(unwind_state, pc));
}

void TestRangeBoundaries(const UnwindState& unwind_state, byte* range_start,
                         size_t range_length) {
  void* pc = range_start - 1;
  CHECK(!v8::Unwinder::PCIsInV8(unwind_state, pc));
  pc = range_start;
  CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
  pc = range_start + 1;
  CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
  pc = range_start + range_length - 1;
  CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
  pc = range_start + range_length;
  CHECK(!v8::Unwinder::PCIsInV8(unwind_state, pc));
  pc = range_start + range_length + 1;
  CHECK(!v8::Unwinder::PCIsInV8(unwind_state, pc));
}

TEST(PCIsInV8_InCodeOrEmbeddedRange) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();

  UnwindState unwind_state = isolate->GetUnwindState();

  byte* code_range_start = const_cast<byte*>(
      reinterpret_cast<const byte*>(unwind_state.code_range.start));
  size_t code_range_length = unwind_state.code_range.length_in_bytes;
  TestRangeBoundaries(unwind_state, code_range_start, code_range_length);

  byte* embedded_range_start = const_cast<byte*>(
      reinterpret_cast<const byte*>(unwind_state.embedded_code_range.start));
  size_t embedded_range_length =
      unwind_state.embedded_code_range.length_in_bytes;
  TestRangeBoundaries(unwind_state, embedded_range_start,
                      embedded_range_length);
}

// PCIsInV8 doesn't check if the PC is in JSEntrydirectly. It's assumed that the
// CodeRange or EmbeddedCodeRange contain JSEntry.
TEST(PCIsInV8_InJSEntryRange) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);

  UnwindState unwind_state = isolate->GetUnwindState();

  Code js_entry = i_isolate->heap()->builtin(Builtins::kJSEntry);
  byte* start = reinterpret_cast<byte*>(js_entry->InstructionStart());
  size_t length = js_entry->InstructionSize();

  void* pc = start;
  CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
  pc = start + 1;
  CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
  pc = start + length - 1;
  CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
}

// Large code objects can be allocated in large object space. Check that this is
// inside the CodeRange.
TEST(PCIsInV8_LargeCodeObject) {
  FLAG_allow_natives_syntax = true;
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);
  HandleScope scope(i_isolate);

  UnwindState unwind_state = isolate->GetUnwindState();

  // Create a big function that ends up in CODE_LO_SPACE.
  const int instruction_size = Page::kPageSize + 1;
  STATIC_ASSERT(instruction_size > kMaxRegularHeapObjectSize);
  std::unique_ptr<byte[]> instructions(new byte[instruction_size]);

  CodeDesc desc;
  desc.buffer = instructions.get();
  desc.buffer_size = instruction_size;
  desc.instr_size = instruction_size;
  desc.reloc_size = 0;
  desc.constant_pool_size = 0;
  desc.unwinding_info = nullptr;
  desc.unwinding_info_size = 0;
  desc.origin = nullptr;
  Handle<Object> self_ref;
  Handle<Code> foo_code =
      i_isolate->factory()->NewCode(desc, Code::WASM_FUNCTION, self_ref);

  CHECK(i_isolate->heap()->InSpace(*foo_code, CODE_LO_SPACE));
  byte* start = reinterpret_cast<byte*>(foo_code->InstructionStart());

  void* pc = start;
  CHECK(v8::Unwinder::PCIsInV8(unwind_state, pc));
}

}  // namespace test_unwinder
}  // namespace internal
}  // namespace v8


text:
function make_annotation_payload_with_only_tags(url, title, user, tags, group) {
        payload = {
			"document": {
				"title": title
				},
            "uri": url,
            "tags": tags,
//			"text": Date().toString(),
			"group": group,
			"permissions":
					{
					"read": ["group:" + group],
					"admin": ["acct:" + user + "@hypothes.is"],
					"update": ["acct:" + user + "@hypothes.is"],
					"delete": ["acct:" + user + "@hypothes.is"]
					}
		};
        return JSON.stringify(payload);
}

function make_annotation_payload_from_selection(url, title, user, start, end, prefix, quote, tags, group) {
    payload = {
			"group": group,
			"document": {
				"title": title
				},
		   "target": [{
			   "selector": [{
								"prefix": prefix,
								"exact": quote,
								"type": "TextQuoteSelector",
								"suffix": ''
								},
							{
								"start": start,
								"end": end,
								"type": "TextPositionSelector"
							}]
            }],
            "uri": url,
            "tags": tags,
            "text": '',
			"permissions":
					{
					"read": ["group:" + group],
					"admin": ["acct:" + user + "@hypothes.is"],
					"update": ["acct:" + user + "@hypothes.is"],
					"delete": ["acct:" + user + "@hypothes.is"]
					}
		};
    return JSON.stringify(payload);
}

// promisified xhr

function makeRequest (opts) {
//  alert('makeRequest: ' + opts.url);
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open(opts.method, opts.url);
    xhr.onload = function () {
      if (this.status >= 200 && this.status < 300) {
        resolve(xhr.response);
      } else {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      }
    };
    xhr.onerror = function () {
      reject({
        status: this.status,
        statusText: xhr.statusText
      });
    };
    if (opts.headers) {
      Object.keys(opts.headers).forEach(function (key) {
        xhr.setRequestHeader(key, opts.headers[key]);
      });
    }
    var params = opts.params;
    if (params && typeof params === 'object') {
      params = Object.keys(params).map(function (key) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
      }).join('&');
    }
    xhr.send(params);
  });
}

function unique(list) {
  var seen = {};
  return list.filter(function(x) {
    if (seen[x])
      return;
    seen[x] = true;
    return x;
  })
}

function heredoc(fn) {
 var a = fn.toString();
 var b = a.slice(14, -3);
 return b;
}

function gup(name, str) {
    if (! str)
        str = window.location.href;
    else
        str = '?' + str;
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(str);
    if (results == null)
        return "";
    else
        return results[1];
}

function have_credentials(user, token) {
	if ( (! user) || (! token ) ) {
		alert ( 'Please right-click the extension\'s icon and use Options to set your Hypothesis username and token' );
		return false;
	}
	else {
		return true;
	}
}

function make_picklist(tags, default_tag, picker_id, initial_pick, target_element) {
  var picklist = document.createElement('select');
  picklist.setAttribute('id', picker_id);
  if ( initial_pick != '' ) {
	var option = document.createElement('option');
	option.text = option.value = initial_pick;
	picklist.add(option);
	}
  for ( var i=0; i<tags.length; i++ ) {
	var tag = tags[i];
	option = document.createElement('option');
	option.text = option.value = tag;
	if ( tag == default_tag )
		option.selected = true;
	picklist.add(option)
	}
  var div = document.querySelector(target_element);
  div.appendChild(picklist);
  document.getElementById('go').onclick = function(e) { go() };
}

function make_tag_picklist(tags) {
	chrome.storage.sync.get(null,
		function(items) {
			var default_tag = items.tags_from_list_default;
			make_picklist(tags,
				  default_tag,
				  'tag_picker',
				  '--- choose a personal tag from your (options-specified) list ---',
				  '#tag_container');
	});
}

function make_gdoc_picklist(tags)  {
	chrome.storage.sync.get(null,
		function(items) {
			var default_tag = items.tags_from_gdoc_default;
			make_picklist(tags,
						  default_tag,
						  'gdoc_tag_picker',
						  '--- choose a shared tag from your (options-specified) doc ---',
						  '#gdoc_container');
	});
}

function make_host_picklist(tags) {
	chrome.storage.sync.get(null,
		function(items) {
			var default_tag = items.tags_from_host_default;
			make_picklist(tags,
						  default_tag,
						  'host_tag_picker',
						  '--- choose an investigation page from the host ---',
						  '#host_container');
	});
}

function make_group_picklist(groups) {
  var picklist = document.createElement('select');
  picklist.setAttribute('id', 'group_picker');
  for ( var i=0; i<groups.length; i++ ) {
	var group = groups[i];
	var option = document.createElement('option');
	option.text = group.name;
	option.value = group.id;
	picklist.add(option)
  }
  var div = document.querySelector('#group_container');
  div.appendChild(picklist);
  document.getElementById('go').onclick = function(e) { go() };
}

function go() {

	var user = null;
	var token = null;

	chrome.storage.sync.get({
		user:'',
		token:''
	  }, function(items) {
		user = items.user;
		token = items.token;
		_go(user, token);
	  });
}

function _go(user, token) {

	if ( ! have_credentials(user, token) ) {
		return;
	}

//	var tag_picker = document.getElementById('tag_picker');
//	var gdoc_picker = document.getElementById('gdoc_tag_picker');
	var host_picker = document.getElementById('host_tag_picker');
//	var group_picker = document.getElementById('group_picker');

	var tags = [];

	if ( typeof formatted_date != 'undefined' ) {
		tags.push('digipo:date:' + formatted_date);
	}

	var pick;
	var i;

	i = host_picker.selectedIndex;
	if (i > 0 ) {
		pick = host_picker.options[i].value;
		chrome.storage.sync.set( {'tags_from_host_default': pick});
		tags.push(pick);
	}
	else {
		chrome.storage.sync.set( {'tags_from_host_default': ''});
	}

/*
	i = tag_picker.selectedIndex;
	if (i > 0 ) {
		pick = tag_picker.options[i].value;
		chrome.storage.sync.set( {'tags_from_list_default': pick});
		tags.push(pick);
	}
	else {
		chrome.storage.sync.set( {'tags_from_list_default': ''});
	}

	i = gdoc_tag_picker.selectedIndex;
	if (i > 0 ) {
		pick = gdoc_tag_picker.options[i].value;
		chrome.storage.sync.set( {'tags_from_gdoc_default': pick});
		tags.push(pick);
	}
	else {
		chrome.storage.sync.set( {'tags_from_gdoc_default': ''});
	}

	var k = group_picker.selectedIndex;
	var group = group_picker.options[k].value;
*/

	var group = '__world__';

	var params;

	if ( ( typeof start != 'undefined') && (typeof end != 'undefined' ) ) {
		params = make_annotation_payload_from_selection(
			unencoded_uri,
			doctitle,
			user,
			start,
			end,
			prefix,
			quote,
			tags,
			group
			);
	}
	else {
		params = make_annotation_payload_with_only_tags(
			unencoded_uri,
			doctitle,
			user,
			tags,
			group
			);
	}

	var options = {
		method: 'POST',
		url: 'https://h.jonudell.info/create?token=' + token + '&url=' + encoded_uri,
		headers: {"Content-type":"application/json" },
		params: params
	};

	makeRequest(options)
		.then(function(data) {
			data = JSON.parse(data);
			return (data);
		})
       .then(function(data) {
			var wayback = document.getElementById('wayback');
			if (wayback && wayback.checked) {
				chrome.runtime.sendMessage(
				{
					'action':'wayback',
					'url' : unencoded_uri
				});
			}
			return (data);
		})
	   .then(function(data) {
		chrome.tabs.getCurrent(function(tab) {
			chrome.tabs.remove(tab.id, function() { });
			});
		})
		.catch(function (err) {
			console.error('error: ', err);
		});
}

function defined(x) {
	return (typeof x != 'undefined');
}

var list_containers = function(){/*

Optionally:

And/or:

Post to group:

*/}

var interstitial_style = function(){/*

*/}

function add_listeners() {
document.addEventListener('DOMContentLoaded', function () {

	chrome.runtime.sendMessage(
	{'action':'get_tags_from_host'},
	   function(tags) {
			make_host_picklist(tags);
	});

/*
	chrome.runtime.sendMessage(
	{'action':'get_tags_from_list'},
	   function(tags) {
			make_tag_picklist(tags);
	});

	chrome.runtime.sendMessage(
	{'action':'get_tags_from_gdoc'},
	   function(tags) {
			make_gdoc_picklist(tags);
	});

	chrome.runtime.sendMessage(
	{'action':'get_groups'},
	   function(groups) {
			make_group_picklist(groups);
	});
*/

});

}

function populate_elements() {
	document.querySelector('#page a').href = unencoded_uri;
	document.querySelector('#page a').text = doctitle;
	document.querySelector('#host').innerHTML = host;
	document.querySelector('#logo').src = img;
	document.querySelector('#list_containers').innerHTML = heredoc(list_containers);
	document.head.innerHTML += heredoc(interstitial_style);
}

function get_interstitial_args() {
	var encoded_uri = gup('uri');
	var unencoded_uri = decodeURIComponent(encoded_uri);
	var doctitle = decodeURIComponent(gup('doctitle'));
	var host = decodeURIComponent(gup('host'));
	var img = decodeURIComponent(gup('img'));
	var claim = decodeURIComponent(gup('claim'));
	return {
		encoded_uri		: encoded_uri,
		unencoded_uri	: unencoded_uri,
		doctitle		: doctitle,
		host			: host,
		img				: img,
		claim			: claim
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <display-name>camunda rest api</display-name>

  <servlet>
    <servlet-name>Engine Api</servlet-name>
    <servlet-class>org.apache.wink.server.internal.servlet.RestServlet</servlet-class>
    <init-param>
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>org.camunda.bpm.engine.rest.util.container.JaxrsApplication</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>Engine Api</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

  <!--filter>
    <filter-name>Resteasy</filter-name>
    <filter-class>
      org.jboss.resteasy.plugins.server.servlet.FilterDispatcher
    </filter-class>
    <init-param>
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>org.camunda.bpm.engine.rest.impl.application.DefaultApplication</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>Resteasy</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping-->

</web-app>


text:
export { default as queries } from './queries';
export { default as functions } from './functions';


text:
require 'spec_helper'

describe StandardSkillScoreEntry do
  let(:judge) { FactoryBot.create(:judge) }
  let(:competitor) { FactoryBot.create(:event_competitor, competition: judge.competition) }
  let(:sss) { FactoryBot.create(:standard_skill_score) }
  let(:skill_points) { 5.1 }
  let(:standard_skill_entry) { FactoryBot.create(:standard_skill_entry, points: skill_points) }
  let(:ssre) { FactoryBot.create(:standard_skill_routine_entry, standard_skill_entry: standard_skill_entry) }
  let(:devaluation_percent) { 50 }
  let(:ssse) { FactoryBot.create(:standard_skill_score_entry, standard_skill_routine_entry: ssre, standard_skill_score: sss, difficulty_devaluation_percent: devaluation_percent) }

  it "is able to have 2 different skills scored by the same judge" do
    score_entry = FactoryBot.create(:standard_skill_score_entry)

    score_entry_2 = FactoryBot.build(:standard_skill_score_entry,
                                     standard_skill_score: score_entry.standard_skill_score,
                                     standard_skill_routine_entry: FactoryBot.create(:standard_skill_routine_entry))
    expect(score_entry_2).to be_valid
  end

  describe "#difficulty_devaluation_score" do
    describe "with 0 devaluation" do
      let(:devaluation_percent) { 0 }

      it "returns the full point value when no devaluation" do
        expect(ssse.difficulty_devaluation_score).to eq(0)
      end
    end

    describe "with 50 devaluation" do
      let(:devaluation_percent) { 50 }

      it "returns 1/2 point value when no devaluation" do
        expect(ssse.difficulty_devaluation_score).to eq(skill_points / 2.0)
      end
    end

    describe "with 100 devaluation" do
      let(:devaluation_percent) { 100 }

      it "returns 0 point value when no devaluation" do
        expect(ssse.difficulty_devaluation_score).to eq(skill_points)
      end
    end
  end

  it { is_expected.to validate_inclusion_of(:difficulty_devaluation_percent).in_array([0, 50, 100]) }
  it { is_expected.to validate_presence_of(:standard_skill_score) }
  it { is_expected.to validate_presence_of(:standard_skill_routine_entry) }
  it { is_expected.to validate_presence_of(:wave) }
  it { is_expected.to validate_presence_of(:line) }
  it { is_expected.to validate_presence_of(:cross) }
  it { is_expected.to validate_presence_of(:circle) }
  it { is_expected.to validate_numericality_of(:wave).is_greater_than_or_equal_to(0) }
  it { is_expected.to validate_numericality_of(:line).is_greater_than_or_equal_to(0) }
  it { is_expected.to validate_numericality_of(:cross).is_greater_than_or_equal_to(0) }
  it { is_expected.to validate_numericality_of(:circle).is_greater_than_or_equal_to(0) }
end


text:
<!doctype html>
<html lang="sv">
<meta charset="utf-8" />
<title>ramverk2</title>

<!-- Mithril HTML Slideshow styles -->
<link href="../css/mithril-slideshow.css" rel="stylesheet" />

<!-- Code formatting using highlight.js -->
<link rel="stylesheet" href="../css/default.css">
<link rel="stylesheet" href="../css/tomorrow.css">
<script src="../js/highlight.pack.js"></script>

<!-- Text formatting using Markdown through showdown.js -->
<script src="../js/showdown.min.js"></script>

<!-- Here comes the slides in order -->
<script data-role="slide" data-markdown type="text/html">
#Kursen ramverk2
##Kmom01
###Mikael Roos, dbwebb
</script>

<script data-role="slide" data-markdown type="text/html">
#Agenda

* Kursintro
* Kmom01

</script>

<script data-role="slide" data-markdown type="text/html">
#Allmänt

* ramverk1
* ramverk2
* Förkunskaper till ramverk2

</script>

<script data-role="slide" data-markdown type="text/html">
#Kmom

* 01: Express
* 02: Docker
* 03: Test
* 04: Realtid
* 05: Databas
* 06: Egen modul
* 07/10: Projekt och examination

</script>

<script data-role="slide" data-markdown type="text/html">
#Val av tekniker

* make install test, npm start
* npm install test start
* Validatorer (tråd i forumet)

</script>

<script data-role="slide" data-markdown type="text/html">
#Val av tekniker

* JSX
* CSS, SASS (SCSS), LESS, JSS
* GUI komponenter

</script>

<script data-role="slide" data-markdown type="text/html">
#Tekniker...

* Express backend JSON
* Vue
* React
* React native
* Klienter i egna repon

</script>

<script data-role="slide" data-markdown type="text/html">
#Tekniker...

* SPA-klient (Mithril)
* Electron (Atom)

</script>

<script data-role="slide" data-markdown type="text/html">
#Drift me-sida

* Tråd i forumet om drifta ssh.student
* Frågat IT om fler servrar (nodejs1/2)
* Server för docker-containers

</script>

<script data-role="slide" data-markdown type="text/html">
#Avslutningsvis

* Frågor på det?

</script>

<script data-role="slide" data-markdown type="text/html">
</script>

<!-- include essential js-script -->
<script src="../js/mithril.min.js"></script>
<script src="../js/mithril-slideshow.js"></script>

</html>


text:
cask :v1 => 'github' do
  version :latest
  sha256 :no_check

  url 'https://central.github.com/mac/latest'
  name 'GitHub'
  homepage 'https://mac.github.com/'
  license :oss

  app 'GitHub.app'
  binary 'GitHub.app/Contents/MacOS/github_cli', :target => 'github'

  postflight do
    suppress_move_to_applications
  end

  uninstall :launchctl => [
                           'com.github.GitHub.Conduit',
                           'com.github.GitHub.GHInstallCLI'
                          ]

  zap :delete => [
                  '~/Library/Application Support/GitHub for Mac',
                  '~/Library/Application Support/ShipIt_stderr.log',
                  '~/Library/Application Support/ShipIt_stdout.log',
                  '~/Library/Application Support/com.github.GitHub',
                  '~/Library/Application Support/com.github.GitHub.ShipIt',
                  '~/Library/Caches/GitHub for Mac',
                  '~/Library/Caches/com.github.GitHub',
                  '~/Library/Containers/com.github.GitHub.Conduit',
                 ]
end


text:
#ifndef _CAMERACOMPONENT_H_
#define _CAMERACOMPONENT_H_

#include "PhasedComponent.h"
#include "SceneObject.h"
#include <Box2D/Box2D.h>
#include <boost/enable_shared_from_this.hpp>

namespace af
{
    class CameraComponent : public boost::enable_shared_from_this<CameraComponent>,
                            public PhasedComponent
    {
    public:
        CameraComponent(float width, float height);
        ~CameraComponent();

        virtual ComponentPtr sharedThis() { return shared_from_this(); }

        virtual void accept(ComponentVisitor& visitor);

        virtual void update(float dt);

        b2AABB getAABB() const;

        void setTarget(const SceneObjectPtr& target);

    private:
        virtual void onRegister();

        virtual void onUnregister();

        b2Vec2 sizeD2Orig_;
        b2Vec2 sizeD2_;

        SceneObjectPtr target_;
    };

    typedef boost::shared_ptr<CameraComponent> CameraComponentPtr;
}

#endif


text:
<?php

class Twig_Node_Expression_Binary_Power extends Twig_Node_Expression_Binary {
	/**
	 * Compiles the node to PHP.
	 *
	 * @param Twig_Compiler A Twig_Compiler instance
	 */
	public function compile(Twig_Compiler $compiler) {
		$compiler->raw('pow(')->subcompile($this->getNode('left'))->raw(', ')->subcompile($this->getNode('right'))->raw(')');
	}

	public function operator(Twig_Compiler $compiler) {
		return $compiler->raw('**');
	}
}


text:
package io.github.chronoscala

import org.scalacheck.{Prop, Properties}
import Imports._

object RichDurationSpec extends Properties("RichDuration") with Gens {
  import Prop.forAll

  property("totally ordered") = forAll(for {
    a <- durationGen
    b <- durationGen
    c <- durationGen
  } yield (a, b, c)) { case (a, b, c) =>
    val antisymmetry = !(a <= b && b <= a) || a == b
    val transitivity = !(a <= b && b <= c) || a <= c
    val totality = a <= b || b <= a

    antisymmetry && transitivity && totality
  }
}


text:
'use strict'

const ImmutableAccessControl = require('immutable-access-control')
const ImmutableCoreController = require('../lib/immutable-core-controller')
const ImmutableCoreModel = require('immutable-core-model')
const Promise = require('bluebird')
const _ = require('lodash')
const chai = require('chai')
const immutable = require('immutable-core')

const assert = chai.assert

const dbHost = process.env.DB_HOST || 'localhost'
const dbName = process.env.DB_NAME || 'test'
const dbPass = process.env.DB_PASS || ''
const dbUser = process.env.DB_USER || 'root'

// use the same params for all connections
const connectionParams = {
    database: dbName,
    host: dbHost,
    password: dbPass,
    user: dbUser,
}

describe('immutable-core-controller - read', function () {

    // fake session to use for testing
    var session = {
        accountId: '11111111111111111111111111111111',
        roles: ['all', 'authenticated'],
        sessionId: '22222222222222222222222222222222',
    }

    // define in before
    var fooModel, globalFooModel, mysql, origBam, origBar, origFoo

    before(async function () {
        // create database connection to use for testing
        mysql = await ImmutableCoreModel.createMysqlConnection(connectionParams)
    })

    after(async function () {
        await mysql.close()
    })

    beforeEach(async function () {
        try {
            // reset global data
            immutable.reset()
            ImmutableCoreModel.reset()
            ImmutableAccessControl.reset()
            // drop any test tables if they exist
            await mysql.query('DROP TABLE IF EXISTS foo')
            // create model for controller
            globalFooModel = new ImmutableCoreModel({
                columns: {
                    foo: {
                        index: true,
                        type: 'string',
                    },
                },
                mysql: mysql,
                name: 'foo',
            })
            // sync with database
            await globalFooModel.sync()
            // create local foo model with session
            fooModel = globalFooModel.session(session)
            // create instances
            origBam = await fooModel.create({foo: 'bam'})
            origBar = await fooModel.create({foo: 'bar'})
            origFoo = await fooModel.create({foo: 'foo'})

        }
        catch (err) {
            throw err
        }
    })

    it('should read model instance', async function () {
        // create new controller
        var fooController = new ImmutableCoreController({
            model: globalFooModel,
        })
        // get read method
        var read = fooController.paths['/:id'].get[0].method
        // catch async errors
        try {
            // get instance
            var bam = await read({
                id: origBam.id,
                json: true,
                session: session,
            })
        }
        catch (err) {
            throw err
        }
        // check that data matches
        assert.deepEqual(bam.toJSON(), origBam.toJSON())
    })

    it('should throw 404 error if id not found', async function () {
        // create new controller
        var fooController = new ImmutableCoreController({
            model: globalFooModel,
        })
        // get read method
        var read = fooController.paths['/:id'].get[0].method
        // catch async errors
        try {
            // get instance
            var bam = await read({
                id: 'XXX',
                session: session,
            })
        }
        catch (err) {
            var threw = err
        }
        // check error
        assert.isDefined(threw)
        assert.strictEqual(threw.code, 404)
        assert.strictEqual(threw.message, 'Not Found')
    })

})


text:
/*--------------------------------------------------*/

#import "GLBSpinnerView.h"
#import "GLBLabel.h"

/*--------------------------------------------------*/
#if defined(GLB_TARGET_IOS)
/*--------------------------------------------------*/

@interface GLBActivityView : UIView

@property(nonatomic) UIEdgeInsets margin;
@property(nonatomic) CGFloat spacing;
@property(nonatomic) CGSize panelMaximumSize;

@property(nonatomic, nullable, strong) UIView* panelView;
@property(nonatomic, nullable, strong) GLBSpinnerView* spinnerView;
@property(nonatomic, nullable, strong) GLBLabel* textLabel;

@property(nonatomic, readonly, getter=isShowed) BOOL showed;

@property(nonatomic) NSTimeInterval showDuration;
@property(nonatomic) NSTimeInterval showDelay;
@property(nonatomic) NSTimeInterval hideDuration;
@property(nonatomic) NSTimeInterval hideDelay;

- (void)setup NS_REQUIRES_SUPER;

- (nullable UIView*)preparePanelView;
- (nullable GLBSpinnerView*)prepareSpinnerView;
- (nullable GLBLabel*)prepareTextLabel;

- (void)show;
- (void)showComplete:(nullable GLBSimpleBlock)complete;
- (void)showPrepare:(nullable GLBSimpleBlock)prepare complete:(nullable GLBSimpleBlock)complete;

- (void)hide;
- (void)hideComplete:(nullable GLBSimpleBlock)complete;
- (void)hidePrepare:(nullable GLBSimpleBlock)prepare complete:(nullable GLBSimpleBlock)complete;

@end

/*--------------------------------------------------*/
#endif
/*--------------------------------------------------*/


text:
export function empty(value: any) {
    return (
        typeof value === 'undefined'
        || value === ''
        || value === null
    ) ? false : true;
}

export function isSetButNotValid(value: any) {
    return (
        typeof value !== 'undefined'
        && (
            value === ''
            || value === null
        )
    ) ? false : true;
}


text:
<?php

namespace Acme\DemoBundle\TestService;

class Factory
{
	private $tenantId;

	public function __construct($tenantId)
	{
		$this->tenantId=$tenantId;
	}

	public function get()
	{
		switch($this->tenantId)
		{
			case 123:
				return new EnglishTenantGreeter($this->tenantId);
				break;
			case 456:
				return new FrenchTenantGreeter($this->tenantId);
				break;
		}
	}
}


text:
license: 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.
---

Coordinates
===========

Ensemble de propriétés décrivant les coordonnées géographiques d'une position.

Propriétés
----------

* __latitude__: Latitude en degrés décimaux. _(Number)_
* __longitude__: Longitude en degrés décimaux. _(Number)_
* __altitude__: Hauteur en mètres de la position par rapport à l'[ellipsoïde](http://earth-info.nga.mil/GandG/publications/tr8350.2/wgs84fin.pdf). _(Number)_
* __accuracy__: Niveau de précision de la latitude et de la longitude en mètres. _(Number)_
* __altitudeAccuracy__: Niveau de précision de l'altitude en mètres. _(Number)_
* __heading__: Direction du déplacement, défini en degrés par rapport au Nord géographique et dans le sens des aiguilles d'une montre. _(Number)_
* __speed__: Vitesse au sol du mobile, définie en mètres par seconde. _(Number)_

Description
-----------

L'objet `Coordinates` est créé et rempli par PhoneGap, puis inséré dans l'objet `Position`. L'objet `Position` est ensuite renvoyé à l'utilisateur comme argument de la fonction de callback.

Plateformes supportées
----------------------

- Android
- BlackBerry (OS 4.6)
- BlackBerry WebWorks (OS 5.0 ou plus récent)
- iPhone
- Windows Phone 7 ( Mango )

Exemple rapide
--------------

    // Fonction de callback de succès
    //
    var onSuccess = function(position) {
        alert('Latitude : '                + position.coords.latitude          + '\n' +
              'Longitude : '               + position.coords.longitude         + '\n' +
              'Altitude : '                + position.coords.altitude          + '\n' +
              'Précision : '               + position.coords.accuracy          + '\n' +
              'Précision de l'altitude : ' + position.coords.altitudeAccuracy  + '\n' +
              'Direction : '               + position.coords.heading           + '\n' +
              'Vitesse : '                 + position.coords.speed             + '\n' +
              'Date : '                    + new Date(position.timestamp)      + '\n');
    };

    // Fonction de callback d'erreur
    //
    var onError = function() {
        alert('onError!');
    };

    navigator.geolocation.getCurrentPosition(onSuccess, onError);

Exemple complet
---------------

    <!DOCTYPE html>

        <title>Exemple Coordinates</title>

Singularités Android
--------------------

__altitudeAccuracy:__ Cette propriété n'est pas supportée sur Android et vaudra toujours `null`.


text:
/*
 * Name: memory_manager.h
 * Description: header for main file in memory_manager module
 * Author: G.Molyboga(St.George.Molyboga@gmail.com)
 * Date: 24 May, 2015
 * Review: 31 May, 2015
*/

#ifndef MEMORY_MANAGER_H
#define MEMORY_MANAGER_H

#include "core/header/common/types.h"
#include <stdlib.h>
#include <string.h>

void* vol_malloc( size_t size, e_ret_code& return_code );

void* vol_memcpy( void* to, const void* from,
                  u32 size_in_bytes, e_ret_code& return_code );

void vol_free( void* ptr, e_ret_code& return_code );

#endif // MEMORY_MANAGER_H


text:
package com.smooch.rnsmooch;

import android.content.Intent;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.ReadableType;

import java.util.HashMap;
import java.util.Map;
import java.util.Date;

import io.smooch.core.Smooch;
import io.smooch.core.User;
import io.smooch.ui.ConversationActivity;

public class ReactNativeSmooch extends ReactContextBaseJavaModule {
    @Override
    public String getName() {
        return "SmoochManager";
    }

    public ReactNativeSmooch(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @ReactMethod
    public void show() {
        ConversationActivity.show(getReactApplicationContext(), Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    @ReactMethod
    public void setFirstName(String firstName) {
        User.getCurrentUser().setFirstName(firstName);
    }

    @ReactMethod
    public void setLastName(String lastName) {
        User.getCurrentUser().setLastName(lastName);
    }

    @ReactMethod
    public void setEmail(String email) {
        User.getCurrentUser().setEmail(email);
    }

    @ReactMethod
    public void setSignedUpAt(int date) {
      User.getCurrentUser().setSignedUpAt(new Date(date));
    }

    @ReactMethod
    public void setUserProperties(ReadableMap properties) {
        User.getCurrentUser().addProperties(getUserProperties(properties));
    }

    private Map<String, Object> getUserProperties(ReadableMap properties) {
        ReadableMapKeySetIterator iterator = properties.keySetIterator();
        Map<String, Object> userProperties = new HashMap<>();

        while (iterator.hasNextKey()) {
            String key = iterator.nextKey();
            ReadableType type = properties.getType(key);
            if (type == ReadableType.Boolean) {
                userProperties.put(key, properties.getBoolean(key));
            } else if (type == ReadableType.Number) {
                userProperties.put(key, properties.getDouble(key));
            } else if (type == ReadableType.String) {
                userProperties.put(key, properties.getString(key));
            }
        }

        return userProperties;
    }

}


text:
using sharpbox.WebLibrary.Helpers;

namespace sharpbox.WebLibrary.Core
{
    using System;

    using sharpbox.Dispatch.Model;

    [Serializable]
    public class WebRequest<T>
    {
        public UiAction UiAction { get; set; }
        public CommandName CommandName { get; set; }
        public T Instance { get; set; }
        public object[] Args { get; set; }
        public Io.Model.FileDetail FileDetail { get; set; }

    }
}


text:
class SS::Migration20190717000000
  include SS::Migration::Base

  depends_on "20190705000000"

  def change
    Urgency::Node::Layout.each do |node|
      next if node.state == "closed"
      node.set(state: "closed")
    end
  end
end


text:
/**
 * This class is auto-genereated. [sic]
 *
 * For any issues or feature requests related to this class, please let us know
 * on github and we'll fix in our codegen framework. We'll not be able to accept
 * pull request for this class.
 *
 */
public class FacebookAutoGen {}


text:
import ist from "ist"
import {Fragment, Schema, Node} from "prosemirror-model"
import {schema, eq, doc, blockquote, p, li, ul, em, strong, code, a, br, hr, img} from "prosemirror-test-builder"

let customSchema = new Schema({
  nodes: {
    doc: {content: "paragraph+"},
    paragraph: {content: "(text|contact)*"},
    text: { toDebugString() { return 'custom_text' } },
    contact: {
      inline: true,
      attrs: { name: {}, email: {} },
      leafText(node: Node) { return `${node.attrs.name} <${node.attrs.email}>` }
    },
    hard_break: { toDebugString() { return 'custom_hard_break' } }
  },
})

describe("Node", () => {
  describe("toString", () => {
    it("nests", () => {
      ist(doc(ul(li(p("hey"), p()), li(p("foo")))).toString(),
          'doc(bullet_list(list_item(paragraph("hey"), paragraph), list_item(paragraph("foo"))))')
    })

    it("shows inline children", () => {
      ist(doc(p("foo", img(), br(), "bar")).toString(),
          'doc(paragraph("foo", image, hard_break, "bar"))')
    })

    it("shows marks", () => {
      ist(doc(p("foo", em("bar", strong("quux")), code("baz"))).toString(),
          'doc(paragraph("foo", em("bar"), em(strong("quux")), code("baz")))')
    })
  })

  describe("cut", () => {
    function cut(doc: Node, cut: Node) {
      ist(doc.cut((doc as any).tag.a || 0, (doc as any).tag.b), cut, eq)
    }

    it("extracts a full block", () =>
       cut(doc(p("foo"), "", p("bar"), "", p("baz")),
           doc(p("bar"))))

    it("cuts text", () =>
       cut(doc(p("0"), p("foobarbaz"), p("2")),
           doc(p("bar"))))

    it("cuts deeply", () =>
       cut(doc(blockquote(ul(li(p("a"), p("bc")), li(p("d")), "", li(p("e"))), p("3"))),
           doc(blockquote(ul(li(p("c")), li(p("d")))))))

    it("works from the left", () =>
       cut(doc(blockquote(p("foobar"))),
           doc(blockquote(p("foo")))))

    it("works to the right", () =>
       cut(doc(blockquote(p("foobar"))),
           doc(blockquote(p("bar")))))

    it("preserves marks", () =>
       cut(doc(p("foo", em("bar", img(), strong("baz"), br()), "quux", code("xyz"))),
           doc(p(em("r", img(), strong("baz"), br()), "qu"))))
  })

  describe("between", () => {
    function between(doc: Node, ...nodes: string[]) {
      let i = 0
      doc.nodesBetween((doc as any).tag.a, (doc as any).tag.b, (node, pos) => {
        if (i == nodes.length)
          throw new Error("More nodes iterated than listed (" + node.type.name + ")")
        let compare = node.isText ? node.text! : node.type.name
        if (compare != nodes[i++])
          throw new Error("Expected " + JSON.stringify(nodes[i - 1]) + ", got " + JSON.stringify(compare))
        if (!node.isText && doc.nodeAt(pos) != node)
          throw new Error("Pos " + pos + " does not point at node " + node + " " + doc.nodeAt(pos))
      })
    }

    it("iterates over text", () =>
       between(doc(p("foobarbaz")),
               "paragraph", "foobarbaz"))

    it("descends multiple levels", () =>
       between(doc(blockquote(ul(li(p("foo")), p("b"), ""), p("c"))),
               "blockquote", "bullet_list", "list_item", "paragraph", "foo", "paragraph", "b"))

    it("iterates over inline nodes", () =>
       between(doc(p(em("x"), "foo", em("bar", img(), strong("baz"), br()), "quux", code("xyz"))),
               "paragraph", "foo", "bar", "image", "baz", "hard_break", "quux", "xyz"))
  })

  describe("textBetween", () => {
    it("works when passing a custom function as leafText", () => {
      const d = doc(p("foo", img(), br()))
      ist(d.textBetween(0, d.content.size, '', (node) => {
        if (node.type.name === 'image') return '<image>'
        if (node.type.name === 'hard_break') return '<break>'
        return ""
      }), 'foo<image><break>')
    })

    it("works with leafText", () => {
      const d = customSchema.nodes.doc.createChecked({}, [
        customSchema.nodes.paragraph.createChecked({}, [
          customSchema.text("Hello "),
          customSchema.nodes.contact.createChecked({ name: "Alice", email: "alice@example.com" })
        ])
      ])
      ist(d.textBetween(0, d.content.size), 'Hello Alice <alice@example.com>')
    })

    it("should ignore leafText when passing a custom leafText", () => {
      const d = customSchema.nodes.doc.createChecked({}, [
        customSchema.nodes.paragraph.createChecked({}, [
          customSchema.text("Hello "),
          customSchema.nodes.contact.createChecked({ name: "Alice", email: "alice@example.com" })
        ])
      ])
      ist(d.textBetween(0, d.content.size, '', '<anonymous>'), 'Hello <anonymous>')
    })
  })

  describe("textContent", () => {
    it("works on a whole doc", () => {
      ist(doc(p("foo")).textContent, "foo")
    })

    it("works on a text node", () => {
      ist(schema.text("foo").textContent, "foo")
    })

    it("works on a nested element", () => {
      ist(doc(ul(li(p("hi")), li(p(em("a"), "b")))).textContent,
          "hiab")
    })
  })

  describe("from", () => {
    function from(arg: Node | Node[] | Fragment | null, expect: Node) {
      ist(expect.copy(Fragment.from(arg)), expect, eq)
    }

    it("wraps a single node", () =>
       from(schema.node("paragraph"), doc(p())))

    it("wraps an array", () =>
       from([schema.node("hard_break"), schema.text("foo")], p(br, "foo")))

    it("preserves a fragment", () =>
       from(doc(p("foo")).content, doc(p("foo"))))

    it("accepts null", () =>
       from(null, p()))

    it("joins adjacent text", () =>
       from([schema.text("a"), schema.text("b")], p("ab")))
  })

  describe("toJSON", () => {
    function roundTrip(doc: Node) {
      ist(schema.nodeFromJSON(doc.toJSON()), doc, eq)
    }

    it("can serialize a simple node", () => roundTrip(doc(p("foo"))))

    it("can serialize marks", () => roundTrip(doc(p("foo", em("bar", strong("baz")), " ", a("x")))))

    it("can serialize inline leaf nodes", () => roundTrip(doc(p("foo", em(img(), "bar")))))

    it("can serialize block leaf nodes", () => roundTrip(doc(p("a"), hr(), p("b"), p())))

    it("can serialize nested nodes", () => roundTrip(doc(blockquote(ul(li(p("a"), p("b")), li(p(img()))), p("c")), p("d"))))
  })

  describe("toString", () => {
    it("should have the default toString method [text]", () => ist(schema.text("hello").toString(), "\"hello\""))
    it("should have the default toString method [br]", () => ist(br().toString(), "hard_break"))

    it("should be able to redefine it from NodeSpec by specifying toDebugString method",
       () => ist(customSchema.text("hello").toString(), "custom_text"))

    it("should be respected by Fragment", () =>
      ist(
        Fragment.fromArray(
          [customSchema.text("hello"), customSchema.nodes.hard_break.createChecked(), customSchema.text("world")]
        ),
        "<custom_text, custom_hard_break, custom_text>"
      )
    )
  })

  describe("leafText", () => {
    it("should custom the textContent of a leaf node", () => {
      let contact = customSchema.nodes.contact.createChecked({ name: "Bob", email: "bob@example.com" })
      let paragraph = customSchema.nodes.paragraph.createChecked({}, [customSchema.text('Hello '), contact])

      ist(contact.textContent, "Bob <bob@example.com>")
      ist(paragraph.textContent, "Hello Bob <bob@example.com>")
    })
  })
})