text:
namespace v8 { namespace internal {

#define __ masm->

static void ProbeTable(MacroAssembler* masm,
                       Code::Flags flags,
                       StubCache::Table table,
                       Register name,
                       Register offset) {
  ExternalReference key_offset(SCTableReference::keyReference(table));
  ExternalReference value_offset(SCTableReference::valueReference(table));

  Label miss;

  // Save the offset on the stack.
  __ push(offset);

  // Check that the key in the entry matches the name.
  __ cmp(name, Operand::StaticArray(offset, times_2, key_offset));
  __ j(not_equal, &miss, not_taken);

  // Get the code entry from the cache.
  __ mov(offset, Operand::StaticArray(offset, times_2, value_offset));

  // Check that the flags match what we're looking for.
  __ mov(offset, FieldOperand(offset, Code::kFlagsOffset));
  __ and_(offset, ~Code::kFlagsTypeMask);
  __ cmp(offset, flags);
  __ j(not_equal, &miss);

  // Restore offset and re-load code entry from cache.
  __ pop(offset);
  __ mov(offset, Operand::StaticArray(offset, times_2, value_offset));

  // Jump to the first instruction in the code stub.
  __ add(Operand(offset), Immediate(Code::kHeaderSize - kHeapObjectTag));
  __ jmp(Operand(offset));

  // Miss: Restore offset and fall through.
  __ bind(&miss);
  __ pop(offset);
}

void StubCache::GenerateProbe(MacroAssembler* masm,
                              Code::Flags flags,
                              Register receiver,
                              Register name,
                              Register scratch) {
  Label miss;

  // Make sure that code is valid. The shifting code relies on the
  // entry size being 8.
  ASSERT(sizeof(Entry) == 8);

  // Make sure the flags does not name a specific type.
  ASSERT(Code::ExtractTypeFromFlags(flags) == 0);

  // Make sure that there are no register conflicts.
  ASSERT(!scratch.is(receiver));
  ASSERT(!scratch.is(name));

  // Check that the receiver isn't a smi.
  __ test(receiver, Immediate(kSmiTagMask));
  __ j(zero, &miss, not_taken);

  // Get the map of the receiver and compute the hash.
  __ mov(scratch, FieldOperand(receiver, HeapObject::kMapOffset));
  __ add(scratch, FieldOperand(name, String::kLengthOffset));
  __ xor_(scratch, flags);
  __ and_(scratch, (kPrimaryTableSize - 1) << kHeapObjectTagSize);

  // Probe the primary table.
  ProbeTable(masm, flags, kPrimary, name, scratch);

  // Primary miss: Compute hash for secondary probe.
  __ sub(scratch, Operand(name));
  __ add(Operand(scratch), Immediate(flags));
  __ and_(scratch, (kSecondaryTableSize - 1) << kHeapObjectTagSize);

  // Probe the secondary table.
  ProbeTable(masm, flags, kSecondary, name, scratch);

  // Cache miss: Fall-through and let caller handle the miss by
  // entering the runtime system.
  __ bind(&miss);
}

void StubCompiler::GenerateLoadGlobalFunctionPrototype(MacroAssembler* masm,
                                                       int index,
                                                       Register prototype) {
  // Load the global or builtins object from the current context.
  __ mov(prototype, Operand(esi, Context::SlotOffset(Context::GLOBAL_INDEX)));
  // Load the global context from the global or builtins object.
  __ mov(prototype,
         FieldOperand(prototype, GlobalObject::kGlobalContextOffset));
  // Load the function from the global context.
  __ mov(prototype, Operand(prototype, Context::SlotOffset(index)));
  // Load the initial map.  The global functions all have initial maps.
  __ mov(prototype,
         FieldOperand(prototype, JSFunction::kPrototypeOrInitialMapOffset));
  // Load the prototype from the initial map.
  __ mov(prototype, FieldOperand(prototype, Map::kPrototypeOffset));
}

void StubCompiler::GenerateLoadArrayLength(MacroAssembler* masm,
                                           Register receiver,
                                           Register scratch,
                                           Label* miss_label) {
  // Check that the receiver isn't a smi.
  __ test(receiver, Immediate(kSmiTagMask));
  __ j(zero, miss_label, not_taken);

  // Check that the object is a JS array.
  __ mov(scratch, FieldOperand(receiver, HeapObject::kMapOffset));
  __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
  __ cmp(scratch, JS_ARRAY_TYPE);
  __ j(not_equal, miss_label, not_taken);

  // Load length directly from the JS array.
  __ mov(eax, FieldOperand(receiver, JSArray::kLengthOffset));
  __ ret(0);
}

void StubCompiler::GenerateLoadShortStringLength(MacroAssembler* masm,
                                                 Register receiver,
                                                 Register scratch,
                                                 Label* miss_label) {
  // Check that the receiver isn't a smi.
  __ test(receiver, Immediate(kSmiTagMask));
  __ j(zero, miss_label, not_taken);

  // Check that the object is a short string.
  __ mov(scratch, FieldOperand(receiver, HeapObject::kMapOffset));
  __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
  __ and_(scratch, kIsNotStringMask | kStringSizeMask);
  __ cmp(scratch, kStringTag | kShortStringTag);
  __ j(not_equal, miss_label, not_taken);

  // Load length directly from the string.
  __ mov(eax, FieldOperand(receiver, String::kLengthOffset));
  __ shr(eax, String::kShortLengthShift);
  __ shl(eax, kSmiTagSize);
  __ ret(0);
}

void StubCompiler::GenerateLoadMediumStringLength(MacroAssembler* masm,
                                                  Register receiver,
                                                  Register scratch,
                                                  Label* miss_label) {
  // Check that the receiver isn't a smi.
  __ test(receiver, Immediate(kSmiTagMask));
  __ j(zero, miss_label, not_taken);

  // Check that the object is a short string.
  __ mov(scratch, FieldOperand(receiver, HeapObject::kMapOffset));
  __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
  __ and_(scratch, kIsNotStringMask | kStringSizeMask);
  __ cmp(scratch, kStringTag | kMediumStringTag);
  __ j(not_equal, miss_label, not_taken);

  // Load length directly from the string.
  __ mov(eax, FieldOperand(receiver, String::kLengthOffset));
  __ shr(eax, String::kMediumLengthShift);
  __ shl(eax, kSmiTagSize);
  __ ret(0);
}

void StubCompiler::GenerateLoadLongStringLength(MacroAssembler* masm,
                                                Register receiver,
                                                Register scratch,
                                                Label* miss_label) {
  // Check that the receiver isn't a smi.
  __ test(receiver, Immediate(kSmiTagMask));
  __ j(zero, miss_label, not_taken);

  // Check that the object is a short string.
  __ mov(scratch, FieldOperand(receiver, HeapObject::kMapOffset));
  __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
  __ and_(scratch, kIsNotStringMask | kStringSizeMask);
  __ cmp(scratch, kStringTag | kLongStringTag);
  __ j(not_equal, miss_label, not_taken);

  // Load length directly from the string.
  __ mov(eax, FieldOperand(receiver, String::kLengthOffset));
  __ shr(eax, String::kLongLengthShift);
  __ shl(eax, kSmiTagSize);
  __ ret(0);
}

void StubCompiler::GenerateLoadFunctionPrototype(MacroAssembler* masm,
                                                 Register receiver,
                                                 Register scratch1,
                                                 Register scratch2,
                                                 Label* miss_label) {
  // Check that the receiver isn't a smi.
  __ test(receiver, Immediate(kSmiTagMask));
  __ j(zero, miss_label, not_taken);

  // Check that the receiver is a function.
  __ mov(scratch1, FieldOperand(receiver, HeapObject::kMapOffset));
  __ movzx_b(scratch2, FieldOperand(scratch1, Map::kInstanceTypeOffset));
  __ cmp(scratch2, JS_FUNCTION_TYPE);
  __ j(not_equal, miss_label, not_taken);

  // Make sure that the function has an instance prototype.
  Label non_instance;
  __ movzx_b(scratch2, FieldOperand(scratch1, Map::kBitFieldOffset));
  __ test(scratch2, Immediate(1 << Map::kHasNonInstancePrototype));
  __ j(not_zero, &non_instance, not_taken);

  // Get the prototype or initial map from the function.
  __ mov(scratch1,
         FieldOperand(receiver, JSFunction::kPrototypeOrInitialMapOffset));

  // If the prototype or initial map is the hole, don't return it and
  // simply miss the cache instead. This will allow us to allocate a
  // prototype object on-demand in the runtime system.
  __ cmp(Operand(scratch1), Immediate(Factory::the_hole_value()));
  __ j(equal, miss_label, not_taken);
  __ mov(eax, Operand(scratch1));

  // If the function does not have an initial map, we're done.
  Label done;
  __ mov(scratch1, FieldOperand(eax, HeapObject::kMapOffset));
  __ movzx_b(scratch2, FieldOperand(scratch1, Map::kInstanceTypeOffset));
  __ cmp(scratch2, MAP_TYPE);
  __ j(not_equal, &done);

  // Get the prototype from the initial map.
  __ mov(eax, FieldOperand(eax, Map::kPrototypeOffset));

  // All done: Return the prototype.
  __ bind(&done);
  __ ret(0);

  // Non-instance prototype: Fetch prototype from constructor field
  // in initial map.
  __ bind(&non_instance);
  __ mov(eax, FieldOperand(scratch1, Map::kConstructorOffset));
  __ ret(0);
}

void StubCompiler::GenerateLoadField(MacroAssembler* masm,
                                     JSObject* object,
                                     JSObject* holder,
                                     Register receiver,
                                     Register scratch1,
                                     Register scratch2,
                                     int index,
                                     Label* miss_label) {
  // Check that the receiver isn't a smi.
  __ test(receiver, Immediate(kSmiTagMask));
  __ j(zero, miss_label, not_taken);

  // Check that the maps haven't changed.
  Register reg =
      __ CheckMaps(object, receiver, holder, scratch1, scratch2, miss_label);

  // Get the properties array of the holder.
  __ mov(scratch1, FieldOperand(reg, JSObject::kPropertiesOffset));

  // Return the value from the properties array.
  int offset = index * kPointerSize + Array::kHeaderSize;
  __ mov(eax, FieldOperand(scratch1, offset));
  __ ret(0);
}

void StubCompiler::GenerateLoadCallback(MacroAssembler* masm,
                                        JSObject* object,
                                        JSObject* holder,
                                        Register receiver,
                                        Register name,
                                        Register scratch1,
                                        Register scratch2,
                                        AccessorInfo* callback,
                                        Label* miss_label) {
  // Check that the receiver isn't a smi.
  __ test(receiver, Immediate(kSmiTagMask));
  __ j(zero, miss_label, not_taken);

  // Check that the maps haven't changed.
  Register reg =
      __ CheckMaps(object, receiver, holder, scratch1, scratch2, miss_label);

  // Push the arguments on the JS stack of the caller.
  __ pop(scratch2);  // remove return address
  __ push(receiver);  // receiver
  __ push(Immediate(Handle<AccessorInfo>(callback)));  // callback data
  __ push(name);  // name
  __ push(reg);  // holder
  __ push(scratch2);  // restore return address

  // Do tail-call to the runtime system.
  ExternalReference load_callback_property =
      ExternalReference(IC_Utility(IC::kLoadCallbackProperty));
  __ TailCallRuntime(load_callback_property, 4);
}

void StubCompiler::GenerateLoadConstant(MacroAssembler* masm,
                                        JSObject* object,
                                        JSObject* holder,
                                        Register receiver,
                                        Register scratch1,
                                        Register scratch2,
                                        Object* value,
                                        Label* miss_label) {
  // Check that the receiver isn't a smi.
  __ test(receiver, Immediate(kSmiTagMask));
  __ j(zero, miss_label, not_taken);

  // Check that the maps haven't changed.
  Register reg =
      __ CheckMaps(object, receiver, holder, scratch1, scratch2, miss_label);

  // Return the constant value.
  __ mov(eax, Handle<Object>(value));
  __ ret(0);
}

void StubCompiler::GenerateLoadInterceptor(MacroAssembler* masm,
                                           JSObject* object,
                                           JSObject* holder,
                                           Register receiver,
                                           Register name,
                                           Register scratch1,
                                           Register scratch2,
                                           Label* miss_label) {
  // Check that the receiver isn't a smi.
  __ test(receiver, Immediate(kSmiTagMask));
  __ j(zero, miss_label, not_taken);

  // Check that the maps haven't changed.
  Register reg =
      __ CheckMaps(object, receiver, holder, scratch1, scratch2, miss_label);

  // Push the arguments on the JS stack of the caller.
  __ pop(scratch2);  // remove return address
  __ push(receiver);  // receiver
  __ push(reg);  // holder
  __ push(name);  // name
  __ push(scratch2);  // restore return address

  // Do tail-call to the runtime system.
  ExternalReference load_ic_property =
      ExternalReference(IC_Utility(IC::kLoadInterceptorProperty));
  __ TailCallRuntime(load_ic_property, 3);
}

void StubCompiler::GenerateLoadMiss(MacroAssembler* masm, Code::Kind kind) {
  ASSERT(kind == Code::LOAD_IC || kind == Code::KEYED_LOAD_IC);
  Code* code = NULL;
  if (kind == Code::LOAD_IC) {
    code = Builtins::builtin(Builtins::LoadIC_Miss);
  } else {
    code = Builtins::builtin(Builtins::KeyedLoadIC_Miss);
  }

  Handle<Code> ic(code);
  __ jmp(ic, code_target);
}

void StubCompiler::GenerateStoreField(MacroAssembler* masm,
                                      JSObject* object,
                                      int index,
                                      Map* transition,
                                      Register receiver_reg,
                                      Register name_reg,
                                      Register scratch,
                                      Label* miss_label) {
  // Check that the object isn't a smi.
  __ test(receiver_reg, Immediate(kSmiTagMask));
  __ j(zero, miss_label, not_taken);

  // Check that the map of the object hasn't changed.
  __ cmp(FieldOperand(receiver_reg, HeapObject::kMapOffset),
         Immediate(Handle<Map>(object->map())));
  __ j(not_equal, miss_label, not_taken);

  // Perform global security token check if needed.
  if (object->IsJSGlobalObject()) {
    __ CheckAccessGlobal(receiver_reg, scratch, miss_label);
  }

  // Stub never generated for non-global objects that require access
  // checks.
  ASSERT(object->IsJSGlobalObject() || !object->IsAccessCheckNeeded());

  // Get the properties array (optimistically).
  __ mov(scratch, FieldOperand(receiver_reg, JSObject::kPropertiesOffset));

  // Perform map transition for the receiver if necessary.
  if (transition != NULL) {
    // Update the map of the object; no write barrier updating is
    // needed because the map is never in new space.
    __ mov(FieldOperand(receiver_reg, HeapObject::kMapOffset),
           Immediate(Handle<Map>(transition)));
  }

  // Write to the properties array.
  int offset = index * kPointerSize + Array::kHeaderSize;
  __ mov(FieldOperand(scratch, offset), eax);

  // Update the write barrier for the array address.
  // Pass the value being stored in the now unused name_reg.
  __ mov(name_reg, Operand(eax));
  __ RecordWrite(scratch, offset, name_reg, receiver_reg);

  // Return the value (register eax).
  __ ret(0);
}

#undef __

#define __ masm()->

// TODO(1241006): Avoid having lazy compile stubs specialized by the
// number of arguments. It is not needed anymore.
Object* StubCompiler::CompileLazyCompile(Code::Flags flags) {
  HandleScope scope;

  // Enter an internal frame.
  __ EnterFrame(StackFrame::INTERNAL);

  // Push a copy of the function onto the stack.
  __ push(edi);

  __ push(edi);  // function is also the parameter to the runtime call
  __ CallRuntime(Runtime::kLazyCompile, 1);
  __ pop(edi);

  __ ExitFrame(StackFrame::INTERNAL);

  // Do a tail-call of the compiled function.
  __ lea(ecx, FieldOperand(eax, Code::kHeaderSize));
  __ jmp(Operand(ecx));

  return GetCodeWithFlags(flags);
}

Object* CallStubCompiler::CompileCallField(Object* object,
                                           JSObject* holder,
                                           int index) {
  // ----------- S t a t e -------------
  // -----------------------------------

  HandleScope scope;
  Label miss;

  // Get the receiver from the stack.
  const int argc = arguments().immediate();
  __ mov(edx, Operand(esp, (argc + 1) * kPointerSize));

  // Check that the receiver isn't a smi.
  __ test(edx, Immediate(kSmiTagMask));
  __ j(zero, &miss, not_taken);

  // Do the right check and compute the holder register.
  Register reg =
      __ CheckMaps(JSObject::cast(object), edx, holder, ebx, ecx, &miss);

  // Get the properties array of the holder and get the function from the field.
  int offset = index * kPointerSize + Array::kHeaderSize;
  __ mov(edi, FieldOperand(reg, JSObject::kPropertiesOffset));
  __ mov(edi, FieldOperand(edi, offset));

  // Check that the function really is a function.
  __ test(edi, Immediate(kSmiTagMask));
  __ j(zero, &miss, not_taken);
  __ mov(ebx, FieldOperand(edi, HeapObject::kMapOffset));  // get the map
  __ movzx_b(ebx, FieldOperand(ebx, Map::kInstanceTypeOffset));
  __ cmp(ebx, JS_FUNCTION_TYPE);
  __ j(not_equal, &miss, not_taken);

  // Invoke the function.
  __ InvokeFunction(edi, arguments(), JUMP_FUNCTION);

  // Handle call cache miss.
  __ bind(&miss);
  Handle<Code> ic = ComputeCallMiss(arguments().immediate());
  __ jmp(ic, code_target);

  // Return the generated code.
  return GetCode(FIELD);
}

Object* CallStubCompiler::CompileCallConstant(Object* object,
                                              JSObject* holder,
                                              JSFunction* function,
                                              CheckType check) {
  // ----------- S t a t e -------------
  // -----------------------------------

  HandleScope scope;
  Label miss;

  // Get the receiver from the stack.
  const int argc = arguments().immediate();
  __ mov(edx, Operand(esp, (argc + 1) * kPointerSize));

  // Check that the receiver isn't a smi.
  if (check != NUMBER_CHECK) {
    __ test(edx, Immediate(kSmiTagMask));
    __ j(zero, &miss, not_taken);
  }

  switch (check) {
    case RECEIVER_MAP_CHECK:
      // Check that the maps haven't changed.
      __ CheckMaps(JSObject::cast(object), edx, holder, ebx, ecx, &miss);
      break;

    case STRING_CHECK:
      // Check that the object is a two-byte string or a symbol.
      __ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
      __ movzx_b(ecx, FieldOperand(ecx, Map::kInstanceTypeOffset));
      __ cmp(ecx, FIRST_NONSTRING_TYPE);
      __ j(above_equal, &miss, not_taken);
      // Check that the maps starting from the prototype haven't changed.
      GenerateLoadGlobalFunctionPrototype(masm(),
                                          Context::STRING_FUNCTION_INDEX,
                                          ecx);
      __ CheckMaps(JSObject::cast(object->GetPrototype()),
                   ecx, holder, ebx, edx, &miss);
      break;

    case NUMBER_CHECK: {
      Label fast;
      // Check that the object is a smi or a heap number.
      __ test(edx, Immediate(kSmiTagMask));
      __ j(zero, &fast, taken);
      __ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
      __ movzx_b(ecx, FieldOperand(ecx, Map::kInstanceTypeOffset));
      __ cmp(ecx, HEAP_NUMBER_TYPE);
      __ j(not_equal, &miss, not_taken);
      __ bind(&fast);
      // Check that the maps starting from the prototype haven't changed.
      GenerateLoadGlobalFunctionPrototype(masm(),
                                          Context::NUMBER_FUNCTION_INDEX,
                                          ecx);
      __ CheckMaps(JSObject::cast(object->GetPrototype()),
                   ecx, holder, ebx, edx, &miss);
      break;
    }

    case BOOLEAN_CHECK: {
      Label fast;
      // Check that the object is a boolean.
      __ cmp(edx, Factory::true_value());
      __ j(equal, &fast, taken);
      __ cmp(edx, Factory::false_value());
      __ j(not_equal, &miss, not_taken);
      __ bind(&fast);
      // Check that the maps starting from the prototype haven't changed.
      GenerateLoadGlobalFunctionPrototype(masm(),
                                          Context::BOOLEAN_FUNCTION_INDEX,
                                          ecx);
      __ CheckMaps(JSObject::cast(object->GetPrototype()),
                   ecx, holder, ebx, edx, &miss);
      break;
    }

    case JSARRAY_HAS_FAST_ELEMENTS_CHECK:
      __ CheckMaps(JSObject::cast(object), edx, holder, ebx, ecx, &miss);
      // Make sure object->elements()->map() != Heap::dictionary_array_map()
      // Get the elements array of the object.
      __ mov(ebx, FieldOperand(edx, JSObject::kElementsOffset));
      // Check that the object is in fast mode (not dictionary).
      __ cmp(FieldOperand(ebx, HeapObject::kMapOffset),
             Immediate(Factory::hash_table_map()));
      __ j(equal, &miss, not_taken);
      break;

    default:
      UNREACHABLE();
  }

  // Get the function and setup the context.
  __ mov(Operand(edi), Immediate(Handle<JSFunction>(function)));
  __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));

  // Jump to the cached code (tail call).
  Handle<Code> code(function->code());
  ParameterCount expected(function->shared()->formal_parameter_count());
  __ InvokeCode(code, expected, arguments(), code_target, JUMP_FUNCTION);

  // Handle call cache miss.
  __ bind(&miss);
  Handle<Code> ic = ComputeCallMiss(arguments().immediate());
  __ jmp(ic, code_target);

  // Return the generated code.
  return GetCode(CONSTANT_FUNCTION);
}

Object* CallStubCompiler::CompileCallInterceptor(Object* object,
                                                 JSObject* holder,
                                                 String* name) {
  // ----------- S t a t e -------------
  // -----------------------------------

  HandleScope scope;
  Label miss;

  // Get the number of arguments.
  const int argc = arguments().immediate();

  // Get the receiver from the stack.
  __ mov(edx, Operand(esp, (argc + 1) * kPointerSize));
  // Check that the receiver isn't a smi.
  __ test(edx, Immediate(kSmiTagMask));
  __ j(zero, &miss, not_taken);

  // Check that maps have not changed and compute the holder register.
  Register reg =
      __ CheckMaps(JSObject::cast(object), edx, holder, ebx, ecx, &miss);

  // Enter an internal frame.
  __ EnterFrame(StackFrame::INTERNAL);

  // Push arguments on the expression stack.
  __ push(edx);  // receiver
  __ push(reg);  // holder
  __ push(Operand(ebp, (argc + 3) * kPointerSize));  // name

  // Perform call.
  ExternalReference load_interceptor =
      ExternalReference(IC_Utility(IC::kLoadInterceptorProperty));
  __ mov(Operand(eax), Immediate(3));
  __ mov(Operand(ebx), Immediate(load_interceptor));

  CEntryStub stub;
  __ CallStub(&stub);

  // Move result to edi and restore receiver.
  __ mov(Operand(edi), eax);
  __ mov(edx, Operand(ebp, (argc + 2) * kPointerSize));  // receiver

  // Exit frame.
  __ ExitFrame(StackFrame::INTERNAL);

  // Check that the function really is a function.
  __ test(edi, Immediate(kSmiTagMask));
  __ j(zero, &miss, not_taken);
  __ mov(ebx, FieldOperand(edi, HeapObject::kMapOffset));
  __ movzx_b(ebx, FieldOperand(ebx, Map::kInstanceTypeOffset));
  __ cmp(ebx, JS_FUNCTION_TYPE);
  __ j(not_equal, &miss, not_taken);

  // Invoke the function.
  __ InvokeFunction(edi, arguments(), JUMP_FUNCTION);

  // Handle load cache miss.
  __ bind(&miss);
  Handle<Code> ic = ComputeCallMiss(argc);
  __ jmp(ic, code_target);

  // Return the generated code.
  return GetCode(INTERCEPTOR);
}

Object* StoreStubCompiler::CompileStoreField(JSObject* object,
                                             int index,
                                             Map* transition,
                                             String* name) {
  // ----------- S t a t e -------------
  //  -- eax    : value
  //  -- ecx    : name
  //  -- esp[0] : return address
  //  -- esp[4] : receiver
  // -----------------------------------

  HandleScope scope;
  Label miss;

  // Get the object from the stack.
  __ mov(ebx, Operand(esp, 1 * kPointerSize));

  // Generate store field code.  Trashes the name register.
  GenerateStoreField(masm(), object, index, transition, ebx, ecx, edx, &miss);

  // Handle store cache miss.
  __ bind(&miss);
  __ mov(Operand(ecx), Immediate(Handle<String>(name)));  // restore name
  Handle<Code> ic(Builtins::builtin(Builtins::StoreIC_Miss));
  __ jmp(ic, code_target);

  // Return the generated code.
  return GetCode(transition == NULL ? FIELD : MAP_TRANSITION);
}

Object* StoreStubCompiler::CompileStoreCallback(JSObject* object,
                                                AccessorInfo* callback,
                                                String* name) {
  // ----------- S t a t e -------------
  //  -- eax    : value
  //  -- ecx    : name
  //  -- esp[0] : return address
  //  -- esp[4] : receiver
  // -----------------------------------

  HandleScope scope;
  Label miss;

  // Get the object from the stack.
  __ mov(ebx, Operand(esp, 1 * kPointerSize));

  // Check that the object isn't a smi.
  __ test(ebx, Immediate(kSmiTagMask));
  __ j(zero, &miss, not_taken);

  // Check that the map of the object hasn't changed.
  __ cmp(FieldOperand(ebx, HeapObject::kMapOffset),
         Immediate(Handle<Map>(object->map())));
  __ j(not_equal, &miss, not_taken);

  // Perform global security token check if needed.
  if (object->IsJSGlobalObject()) {
    __ CheckAccessGlobal(ebx, edx, &miss);
  }

  // Stub never generated for non-global objects that require access
  // checks.
  ASSERT(object->IsJSGlobalObject() || !object->IsAccessCheckNeeded());

  __ pop(ebx);  // remove the return address
  __ push(Operand(esp, 0));  // receiver
  __ push(Immediate(Handle<AccessorInfo>(callback)));  // callback info
  __ push(ecx);  // name
  __ push(eax);  // value
  __ push(ebx);  // restore return address

  // Do tail-call to the runtime system.
  ExternalReference store_callback_property =
      ExternalReference(IC_Utility(IC::kStoreCallbackProperty));
  __ TailCallRuntime(store_callback_property, 4);

  // Handle store cache miss.
  __ bind(&miss);
  __ mov(Operand(ecx), Immediate(Handle<String>(name)));  // restore name
  Handle<Code> ic(Builtins::builtin(Builtins::StoreIC_Miss));
  __ jmp(ic, code_target);

  // Return the generated code.
  return GetCode(CALLBACKS);
}

Object* StoreStubCompiler::CompileStoreInterceptor(JSObject* receiver,
                                                   String* name) {
  // ----------- S t a t e -------------
  //  -- eax    : value
  //  -- ecx    : name
  //  -- esp[0] : return address
  //  -- esp[4] : receiver
  // -----------------------------------

  HandleScope scope;
  Label miss;

  // Get the object from the stack.
  __ mov(ebx, Operand(esp, 1 * kPointerSize));

  // Check that the object isn't a smi.
  __ test(ebx, Immediate(kSmiTagMask));
  __ j(zero, &miss, not_taken);

  // Check that the map of the object hasn't changed.
  __ cmp(FieldOperand(ebx, HeapObject::kMapOffset),
         Immediate(Handle<Map>(receiver->map())));
  __ j(not_equal, &miss, not_taken);

  // Perform global security token check if needed.
  if (receiver->IsJSGlobalObject()) {
    __ CheckAccessGlobal(ebx, edx, &miss);
  }

  // Stub never generated for non-global objects that require access
  // checks.
  ASSERT(receiver->IsJSGlobalObject() || !receiver->IsAccessCheckNeeded());

  __ pop(ebx);  // remove the return address
  __ push(Operand(esp, 0));  // receiver
  __ push(ecx);  // name
  __ push(eax);  // value
  __ push(ebx);  // restore return address

  // Do tail-call to the runtime system.
  ExternalReference store_ic_property =
      ExternalReference(IC_Utility(IC::kStoreInterceptorProperty));
  __ TailCallRuntime(store_ic_property, 3);

  // Handle store cache miss.
  __ bind(&miss);
  __ mov(Operand(ecx), Immediate(Handle<String>(name)));  // restore name
  Handle<Code> ic(Builtins::builtin(Builtins::StoreIC_Miss));
  __ jmp(ic, code_target);

  // Return the generated code.
  return GetCode(INTERCEPTOR);
}

Object* KeyedStoreStubCompiler::CompileStoreField(JSObject* object,
                                                  int index,
                                                  Map* transition,
                                                  String* name) {
  // ----------- S t a t e -------------
  //  -- eax    : value
  //  -- esp[0] : return address
  //  -- esp[4] : key
  //  -- esp[8] : receiver
  // -----------------------------------
  HandleScope scope;
  Label miss;

  __ IncrementCounter(&Counters::keyed_store_field, 1);

  // Get the name from the stack.
  __ mov(ecx, Operand(esp, 1 * kPointerSize));
  // Check that the name has not changed.
  __ cmp(Operand(ecx), Immediate(Handle<String>(name)));
  __ j(not_equal, &miss, not_taken);

  // Get the object from the stack.
  __ mov(ebx, Operand(esp, 2 * kPointerSize));

  // Generate store field code.  Trashes the name register.
  GenerateStoreField(masm(), object, index, transition, ebx, ecx, edx, &miss);

  // Handle store cache miss.
  __ bind(&miss);
  __ DecrementCounter(&Counters::keyed_store_field, 1);
  Handle<Code> ic(Builtins::builtin(Builtins::KeyedStoreIC_Miss));
  __ jmp(ic, code_target);

  // Return the generated code.
  return GetCode(transition == NULL ? FIELD : MAP_TRANSITION);
}

Object* LoadStubCompiler::CompileLoadField(JSObject* object,
                                           JSObject* holder,
                                           int index) {
  // ----------- S t a t e -------------
  //  -- ecx    : name
  //  -- esp[0] : return address
  //  -- esp[4] : receiver
  // -----------------------------------

  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  GenerateLoadField(masm(), object, holder, eax, ebx, edx, index, &miss);
  __ bind(&miss);
  GenerateLoadMiss(masm(), Code::LOAD_IC);

  // Return the generated code.
  return GetCode(FIELD);
}

Object* LoadStubCompiler::CompileLoadCallback(JSObject* object,
                                              JSObject* holder,
                                              AccessorInfo* callback) {
  // ----------- S t a t e -------------
  //  -- ecx    : name
  //  -- esp[0] : return address
  //  -- esp[4] : receiver
  // -----------------------------------

  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  GenerateLoadCallback(masm(), object, holder, eax, ecx, ebx,
                       edx, callback, &miss);
  __ bind(&miss);
  GenerateLoadMiss(masm(), Code::LOAD_IC);

  // Return the generated code.
  return GetCode(CALLBACKS);
}

Object* LoadStubCompiler::CompileLoadConstant(JSObject* object,
                                              JSObject* holder,
                                              Object* value) {
  // ----------- S t a t e -------------
  //  -- ecx    : name
  //  -- esp[0] : return address
  //  -- esp[4] : receiver
  // -----------------------------------

  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  GenerateLoadConstant(masm(), object, holder, eax, ebx, edx, value, &miss);
  __ bind(&miss);
  GenerateLoadMiss(masm(), Code::LOAD_IC);

  // Return the generated code.
  return GetCode(CONSTANT_FUNCTION);
}

Object* LoadStubCompiler::CompileLoadInterceptor(JSObject* receiver,
                                                 JSObject* holder,
                                                 String* name) {
  // ----------- S t a t e -------------
  //  -- ecx    : name
  //  -- esp[0] : return address
  //  -- esp[4] : receiver
  // -----------------------------------
  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  GenerateLoadInterceptor(masm(), receiver, holder, eax, ecx, edx, ebx, &miss);
  __ bind(&miss);
  GenerateLoadMiss(masm(), Code::LOAD_IC);

  // Return the generated code.
  return GetCode(INTERCEPTOR);
}

Object* KeyedLoadStubCompiler::CompileLoadField(String* name,
                                                JSObject* receiver,
                                                JSObject* holder,
                                                int index) {
  // ----------- S t a t e -------------
  //  -- esp[0] : return address
  //  -- esp[4] : name
  //  -- esp[8] : receiver
  // -----------------------------------
  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  __ mov(ecx, (Operand(esp, 2 * kPointerSize)));
  __ IncrementCounter(&Counters::keyed_load_field, 1);

  // Check that the name has not changed.
  __ cmp(Operand(eax), Immediate(Handle<String>(name)));
  __ j(not_equal, &miss, not_taken);

  GenerateLoadField(masm(), receiver, holder, ecx, ebx, edx, index, &miss);
  __ bind(&miss);
  __ DecrementCounter(&Counters::keyed_load_field, 1);
  GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);

  // Return the generated code.
  return GetCode(FIELD);
}

Object* KeyedLoadStubCompiler::CompileLoadCallback(String* name,
                                                   JSObject* receiver,
                                                   JSObject* holder,
                                                   AccessorInfo* callback) {
  // ----------- S t a t e -------------
  //  -- esp[0] : return address
  //  -- esp[4] : name
  //  -- esp[8] : receiver
  // -----------------------------------
  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  __ mov(ecx, (Operand(esp, 2 * kPointerSize)));
  __ IncrementCounter(&Counters::keyed_load_callback, 1);

  // Check that the name has not changed.
  __ cmp(Operand(eax), Immediate(Handle<String>(name)));
  __ j(not_equal, &miss, not_taken);

  GenerateLoadCallback(masm(), receiver, holder, ecx, eax, ebx, edx,
                       callback, &miss);
  __ bind(&miss);
  __ DecrementCounter(&Counters::keyed_load_callback, 1);
  GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);

  // Return the generated code.
  return GetCode(CALLBACKS);
}

Object* KeyedLoadStubCompiler::CompileLoadConstant(String* name,
                                                   JSObject* receiver,
                                                   JSObject* holder,
                                                   Object* value) {
  // ----------- S t a t e -------------
  //  -- esp[0] : return address
  //  -- esp[4] : name
  //  -- esp[8] : receiver
  // -----------------------------------
  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  __ mov(ecx, (Operand(esp, 2 * kPointerSize)));
  __ IncrementCounter(&Counters::keyed_load_constant_function, 1);

  // Check that the name has not changed.
  __ cmp(Operand(eax), Immediate(Handle<String>(name)));
  __ j(not_equal, &miss, not_taken);

  GenerateLoadConstant(masm(), receiver, holder, ecx, ebx, edx, value, &miss);
  __ bind(&miss);
  __ DecrementCounter(&Counters::keyed_load_constant_function, 1);
  GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);

  // Return the generated code.
  return GetCode(CONSTANT_FUNCTION);
}

Object* KeyedLoadStubCompiler::CompileLoadInterceptor(JSObject* receiver,
                                                      JSObject* holder,
                                                      String* name) {
  // ----------- S t a t e -------------
  //  -- esp[0] : return address
  //  -- esp[4] : name
  //  -- esp[8] : receiver
  // -----------------------------------
  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  __ mov(ecx, (Operand(esp, 2 * kPointerSize)));
  __ IncrementCounter(&Counters::keyed_load_interceptor, 1);

  // Check that the name has not changed.
  __ cmp(Operand(eax), Immediate(Handle<String>(name)));
  __ j(not_equal, &miss, not_taken);

  GenerateLoadInterceptor(masm(), receiver, holder, ecx, eax, edx, ebx, &miss);
  __ bind(&miss);
  __ DecrementCounter(&Counters::keyed_load_interceptor, 1);
  GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);

  // Return the generated code.
  return GetCode(INTERCEPTOR);
}

Object* KeyedLoadStubCompiler::CompileLoadArrayLength(String* name) {
  // ----------- S t a t e -------------
  //  -- esp[0] : return address
  //  -- esp[4] : name
  //  -- esp[8] : receiver
  // -----------------------------------
  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  __ mov(ecx, (Operand(esp, 2 * kPointerSize)));
  __ IncrementCounter(&Counters::keyed_load_array_length, 1);

  // Check that the name has not changed.
  __ cmp(Operand(eax), Immediate(Handle<String>(name)));
  __ j(not_equal, &miss, not_taken);

  GenerateLoadArrayLength(masm(), ecx, edx, &miss);
  __ bind(&miss);
  __ DecrementCounter(&Counters::keyed_load_array_length, 1);
  GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);

  // Return the generated code.
  return GetCode(CALLBACKS);
}

Object* KeyedLoadStubCompiler::CompileLoadShortStringLength(String* name) {
  // ----------- S t a t e -------------
  //  -- esp[0] : return address
  //  -- esp[4] : name
  //  -- esp[8] : receiver
  // -----------------------------------
  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  __ mov(ecx, (Operand(esp, 2 * kPointerSize)));
  __ IncrementCounter(&Counters::keyed_load_string_length, 1);

  // Check that the name has not changed.
  __ cmp(Operand(eax), Immediate(Handle<String>(name)));
  __ j(not_equal, &miss, not_taken);

  GenerateLoadShortStringLength(masm(), ecx, edx, &miss);
  __ bind(&miss);
  __ DecrementCounter(&Counters::keyed_load_string_length, 1);
  GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);

  // Return the generated code.
  return GetCode(CALLBACKS);
}

Object* KeyedLoadStubCompiler::CompileLoadMediumStringLength(String* name) {
  // ----------- S t a t e -------------
  //  -- esp[0] : return address
  //  -- esp[4] : name
  //  -- esp[8] : receiver
  // -----------------------------------
  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  __ mov(ecx, (Operand(esp, 2 * kPointerSize)));
  __ IncrementCounter(&Counters::keyed_load_string_length, 1);

  // Check that the name has not changed.
  __ cmp(Operand(eax), Immediate(Handle<String>(name)));
  __ j(not_equal, &miss, not_taken);

  GenerateLoadMediumStringLength(masm(), ecx, edx, &miss);
  __ bind(&miss);
  __ DecrementCounter(&Counters::keyed_load_string_length, 1);
  GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);

  // Return the generated code.
  return GetCode(CALLBACKS);
}

Object* KeyedLoadStubCompiler::CompileLoadLongStringLength(String* name) {
  // ----------- S t a t e -------------
  //  -- esp[0] : return address
  //  -- esp[4] : name
  //  -- esp[8] : receiver
  // -----------------------------------
  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  __ mov(ecx, (Operand(esp, 2 * kPointerSize)));
  __ IncrementCounter(&Counters::keyed_load_string_length, 1);

  // Check that the name has not changed.
  __ cmp(Operand(eax), Immediate(Handle<String>(name)));
  __ j(not_equal, &miss, not_taken);

  GenerateLoadLongStringLength(masm(), ecx, edx, &miss);
  __ bind(&miss);
  __ DecrementCounter(&Counters::keyed_load_string_length, 1);
  GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);

  // Return the generated code.
  return GetCode(CALLBACKS);
}

Object* KeyedLoadStubCompiler::CompileLoadFunctionPrototype(String* name) {
  // ----------- S t a t e -------------
  //  -- esp[0] : return address
  //  -- esp[4] : name
  //  -- esp[8] : receiver
  // -----------------------------------
  HandleScope scope;
  Label miss;

  __ mov(eax, (Operand(esp, kPointerSize)));
  __ mov(ecx, (Operand(esp, 2 * kPointerSize)));
  __ IncrementCounter(&Counters::keyed_load_function_prototype, 1);

  // Check that the name has not changed.
  __ cmp(Operand(eax), Immediate(Handle<String>(name)));
  __ j(not_equal, &miss, not_taken);

  GenerateLoadFunctionPrototype(masm(), ecx, edx, ebx, &miss);
  __ bind(&miss);
  __ DecrementCounter(&Counters::keyed_load_function_prototype, 1);
  GenerateLoadMiss(masm(), Code::KEYED_LOAD_IC);

  // Return the generated code.
  return GetCode(CALLBACKS);
}

#undef __

} }  // namespace v8::internal


text:
package com.bwsw.sj.engine.core.simulation.state

import com.bwsw.common.file.utils.FileStorage
import com.bwsw.sj.common.dal.model.stream.{StreamDomain, TStreamStreamDomain}
import com.bwsw.sj.common.engine.core.environment.{ModuleOutput, StatefulModuleEnvironmentManager}
import com.bwsw.sj.common.engine.core.reporting.PerformanceMetrics
import com.bwsw.sj.common.engine.core.state.StateStorage
import com.bwsw.sj.common.utils.SjTimer
import org.mockito.Mockito.mock

import scala.collection.mutable

/**
  * Mock for [[com.bwsw.sj.common.engine.core.environment.StatefulModuleEnvironmentManager]].
  * Creates [[PartitionedOutputMock]] instead [[com.bwsw.sj.common.engine.core.environment.PartitionedOutput]]
  * and [[RoundRobinOutputMock]] instead [[com.bwsw.sj.common.engine.core.environment.RoundRobinOutput]].
  *
  * @param stateStorage storage of state
  * @param options      user defined options from instance
  * @param outputs      set of output streams from instance
  * @param fileStorage  file storage
  * @param senderThread mock for thread for sending data to the T-Streams service
  * @author Pavel Tomskikh
  */
class ModuleEnvironmentManagerMock(stateStorage: StateStorage,
                                   options: String,
                                   outputs: Array[TStreamStreamDomain],
                                   val senderThread: TStreamsSenderThreadMock,
                                   fileStorage: FileStorage = mock(classOf[FileStorage]))
  extends {
    val producerPolicyByOutput = mutable.Map.empty[String, ModuleOutput]
    val moduleTimer = mock(classOf[SjTimer])
    val performanceMetrics = mock(classOf[PerformanceMetrics])
  } with StatefulModuleEnvironmentManager(
    stateStorage,
    options,
    outputs.asInstanceOf[Array[StreamDomain]],
    producerPolicyByOutput,
    moduleTimer,
    performanceMetrics,
    fileStorage,
    senderThread) {

  /**
    * Allows getting partitioned output for specific output stream
    *
    * @param streamName Name of output stream
    * @return Partitioned output that wrapping output stream
    */
  override def getPartitionedOutput(streamName: String)
                                   (implicit serialize: (AnyRef) => Array[Byte]): PartitionedOutputMock =
    getOutput(streamName, () => new PartitionedOutputMock(outputs.find(_.name == streamName).get, senderThread))

  /**
    * Allows getting round-robin output for specific output stream
    *
    * @param streamName Name of output stream
    * @return Round-robin output that wrapping output stream
    */
  override def getRoundRobinOutput(streamName: String)
                                  (implicit serialize: (AnyRef) => Array[Byte]): RoundRobinOutputMock =
    getOutput(streamName, () => new RoundRobinOutputMock(outputs.find(_.name == streamName).get, senderThread))
}

redpajama_set_name: RedPajamaGithub


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE114_Process_Control__w32_wchar_t_console_66b.c
Label Definition File: CWE114_Process_Control__w32.label.xml
Template File: sources-sink-66b.tmpl.c
*/
/*
 * @description
 * CWE: 114 Process Control
 * BadSource: console Read input from the console
 * GoodSource: Hard code the full pathname to the library
 * Sinks:
 *    BadSink : Load a dynamic link library
 * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#include <windows.h>

#ifndef OMITBAD

void CWE114_Process_Control__w32_wchar_t_console_66b_badSink(wchar_t * dataArray[])
{
    /* copy data out of dataArray */
    wchar_t * data = dataArray[2];
    {
        HMODULE hModule;
        /* POTENTIAL FLAW: If the path to the library is not specified, an attacker may be able to
         * replace his own file with the intended library */
        hModule = LoadLibraryW(data);
        if (hModule != NULL)
        {
            FreeLibrary(hModule);
            printLine("Library loaded and freed successfully");
        }
        else
        {
            printLine("Unable to load library");
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE114_Process_Control__w32_wchar_t_console_66b_goodG2BSink(wchar_t * dataArray[])
{
    wchar_t * data = dataArray[2];
    {
        HMODULE hModule;
        /* POTENTIAL FLAW: If the path to the library is not specified, an attacker may be able to
         * replace his own file with the intended library */
        hModule = LoadLibraryW(data);
        if (hModule != NULL)
        {
            FreeLibrary(hModule);
            printLine("Library loaded and freed successfully");
        }
        else
        {
            printLine("Unable to load library");
        }
    }
}

#endif /* OMITGOOD */


text:
function json_last_error() {
  //  discuss at: http://phpjs.org/functions/json_last_error/
  // original by: Brett Zamir (http://brett-zamir.me)
  //   example 1: json_last_error();
  //   returns 1: 0

  /*
     JSON_ERROR_NONE = 0
     JSON_ERROR_DEPTH = 1 // max depth limit to be removed per PHP comments in json.c (not possible in JS?)
     JSON_ERROR_STATE_MISMATCH = 2 // internal use? also not documented
     JSON_ERROR_CTRL_CHAR = 3 // [\u0000-\u0008\u000B-\u000C\u000E-\u001F] if used directly within json_decode(),
                                     // but JSON functions auto-escape these, so error not possible in JavaScript
     JSON_ERROR_SYNTAX = 4
     */
  return this.php_js && this.php_js.last_error_json ? this.php_js.last_error_json : 0;
}


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* DLLVERSIONINFO.cs -- receives DLL-specific version information
   Ars Magna project, http://arsmagna.ru */

#region Using directives

using System;
using System.Runtime.InteropServices;

using JetBrains.Annotations;

#endregion

// ReSharper disable InconsistentNaming

namespace AM.Win32
{
    /// <summary>
    /// Receives DLL-specific version information.
    /// It is used with the DllGetVersion function.
    /// </summary>
    [PublicAPI]
    [StructLayout(LayoutKind.Sequential)]
    public class DLLVERSIONINFO
    {
        /// <summary>
        /// The size of the structure, in bytes.
        /// This member must be filled in before calling the function.
        /// </summary>
        [CLSCompliant(false)]
        public uint cbSize;

        /// <summary>
        /// The major version of the DLL.
        /// For instance, if the DLL's version is 4.0.950,
        /// this value will be 4.
        /// </summary>
        [CLSCompliant(false)]
        public uint dwMajorVersion;

        /// <summary>
        /// The minor version of the DLL.
        /// For instance, if the DLL's version is 4.0.950,
        /// this value will be 0.
        /// </summary>
        [CLSCompliant(false)]
        public uint dwMinorVersion;

        /// <summary>
        /// The build number of the DLL.
        /// For instance, if the DLL's version is 4.0.950,
        /// this value will be 950.
        /// </summary>
        [CLSCompliant(false)]
        public uint dwBuildNumber;

        /// <summary>
        /// Identifies the platform for which the DLL was built.
        /// </summary>
        [CLSCompliant(false)]
        public uint dwPlatformID;
    }
}


text:
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

module Blockchain.ExtWord
  ( Word128
  , Word160
  , Word256
  , Word512
  , word64ToBytes
  , bytesToWord64
  , word128ToBytes
  , bytesToWord128
  , word160ToBytes
  , bytesToWord160
  , word256ToBytes
  , bytesToWord256
  ) where

import Data.Binary
import Data.Bits
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Legacy.Haskoin.V0102.Network.Haskoin.Crypto.BigWord
       (Word128, Word160, Word256, Word512)

import Data.Ix

import Blockchain.Data.RLP

instance Ix Word256 where
  range (x, y)
    | x == y = [x]
  range (x, y) = x : range (x + 1, y)
  index (x, y) z
    | z < x || z > y =
      error $
      "Ix{Word256}.index: Index (" ++
      show z ++ ") out of range ((" ++ show x ++ "," ++ show y ++ "))"
  index (x, _) z = fromIntegral $ z - x
  inRange (x, y) z
    | z >= x && z <= y = True
  inRange _ _ = False

instance RLPSerializable Word512 where
  rlpEncode val = RLPString $ BL.toStrict $ encode val
  rlpDecode (RLPString s)
    | B.length s == 64 = decode $ BL.fromStrict s
  rlpDecode x = error ("Missing case in rlp2Word512: " ++ show x)

word64ToBytes :: Word64 -> [Word8]
word64ToBytes word = map (fromIntegral . (word `shiftR`)) [64 - 8,64 - 16 .. 0]

bytesToWord64 :: [Word8] -> Word64
bytesToWord64 bytes
  | length bytes == 8 =
    sum $
    map (\(shiftBits, byte) -> fromIntegral byte `shiftL` shiftBits) $
    zip [64 - 8,64 - 16 .. 0] bytes
bytesToWord64 _ =
  error "bytesToWord64 was called with the wrong number of bytes"

word128ToBytes :: Word128 -> [Word8]
word128ToBytes word =
  map (fromIntegral . (word `shiftR`)) [128 - 8,128 - 16 .. 0]

bytesToWord128 :: [Word8] -> Word128
bytesToWord128 bytes
  | length bytes == 16 =
    sum $
    map (\(shiftBits, byte) -> fromIntegral byte `shiftL` shiftBits) $
    zip [128 - 8,128 - 16 .. 0] bytes
bytesToWord128 _ =
  error "bytesToWord128 was called with the wrong number of bytes"

word160ToBytes :: Word160 -> [Word8]
word160ToBytes word =
  map (fromIntegral . (word `shiftR`)) [160 - 8,160 - 16 .. 0]

bytesToWord160 :: [Word8] -> Word160
bytesToWord160 bytes
  | length bytes == 20 =
    sum $
    map (\(shiftBits, byte) -> fromIntegral byte `shiftL` shiftBits) $
    zip [160 - 8,160 - 16 .. 0] bytes
bytesToWord160 _ =
  error "bytesToWord128 was called with the wrong number of bytes"

word256ToBytes :: Word256 -> [Word8]
word256ToBytes word =
  map (fromIntegral . (word `shiftR`)) [256 - 8,256 - 16 .. 0]

instance RLPSerializable Word128 where
  rlpEncode val = RLPString $ BL.toStrict $ encode val
  rlpDecode (RLPString s)
    | B.null s = 0
  rlpDecode (RLPString s)
    | B.length s <= 16 = decode $ BL.fromStrict s
  rlpDecode x = error ("Missing case in rlp2Word128: " ++ show x)

instance RLPSerializable Word32 where
  rlpEncode val = RLPString $ BL.toStrict $ encode val
  rlpDecode (RLPString s)
    | B.null s = 0
  rlpDecode (RLPString s)
    | B.length s <= 4 = decode $ BL.fromStrict s
  rlpDecode x = error ("Missing case in rlp2Word32: " ++ show x)

instance RLPSerializable Word16 where
  rlpEncode val = RLPString $ BL.toStrict $ encode val
  rlpDecode (RLPString s)
    | B.null s = 0
  rlpDecode (RLPString s)
    | B.length s <= 2 = decode $ BL.fromStrict s
  rlpDecode x = error ("Missing case in rlp2Word16: " ++ show x)

bytesToWord256 :: [Word8] -> Word256
bytesToWord256 bytes
  | length bytes == 32 =
    sum $
    map (\(shiftBits, byte) -> fromIntegral byte `shiftL` shiftBits) $
    zip [256 - 8,256 - 16 .. 0] bytes
bytesToWord256 _ =
  error "bytesToWord256 was called with the wrong number of bytes"


text:
package org.kiji.mapreduce.shellext

import org.kiji.schema.shell.ddl.ColumnName

/**
 * A single clause in the main <tt>MAP FIELDS ... AS ( <clauses< )</tt> list.
 *
 *
This can specify a single field to column mapping, a default column family to load
 * to, or other properties of the import.

 *
 *
Instances of <tt>FieldMappingElem</tt> are examined in {{FieldMapping#generateJson}};
 * if you add a new subclass, you must modify the typecase in that method.

 */
abstract class FieldMappingElem

/**
 * A <tt>fieldname => family:qualifier</tt> clause in a field mapping that
 * maps the specified field into the specified target column.
 *
 * @param fieldName the name of the input field.
 * @param colName the name of the target column
 */
class SingleFieldMapping(val fieldName: String, val col: ColumnName) extends FieldMappingElem {
  /** {@inheritDoc} */
  override def equals(other: Any): Boolean = {
    other match {
      case single: SingleFieldMapping => {
        return fieldName == single.fieldName && col.equals(single.col)
      }
      case _ => { return false }
    }
  }

  /** {@inheritDoc} */
  override def hashCode(): Int = {
    return fieldName.hashCode() ^ col.hashCode()
  }
}

/**
 * A <tt>DEFAULT FAMILY (family)</tt> clause in a field mapping; all fields that are not
 * explicitly used elsewhere in the field mapping are mapped to <tt>familyName:fieldName</tt>.
 *
 * @param familyName the name of the column family where target fields should be written.
 */
class DefaultFamilyMapping(val familyName: String) extends FieldMappingElem {
  /** {@inheritDoc} */
  override def equals(other: Any): Boolean = {
    other match {
      case default: DefaultFamilyMapping => {
        return familyName == default.familyName
      }
      case _ => { return false }
    }
  }

  /** {@inheritDoc} */
  override def hashCode(): Int = {
    return familyName.hashCode()
  }
}

/**
 * A <tt>field => $ENTITY</tt> clause, specifying that the named field is to be used
 * as the target entity id during the import.
 *
 * @param fieldName the name of the field to use as the entity id.
 */
class EntityFieldMapping(val fieldName: String) extends FieldMappingElem {
  /** {@inheritDoc} */
  override def equals(other: Any): Boolean = {
    other match {
      case entity: EntityFieldMapping => {
        return fieldName == entity.fieldName
      }
      case _ => { return false }
    }
  }

  /** {@inheritDoc} */
  override def hashCode(): Int = {
    return fieldName.hashCode()
  }
}

/**
 * A <tt>field => $TIMESTAMP</tt> clause, specifying that the named field is to be used
 * as the timestamp for the imported record during the import.
 *
 * @param fieldName the name of the field to use as the timestamp.
 */
class TimestampFieldMapping(val fieldName: String) extends FieldMappingElem {
  /** {@inheritDoc} */
  override def equals(other: Any): Boolean = {
    other match {
      case timestamp: TimestampFieldMapping => {
        return fieldName == timestamp.fieldName
      }
      case _ => { return false }
    }
  }

  /** {@inheritDoc} */
  override def hashCode(): Int = {
    return fieldName.hashCode()
  }
}


text:
package com.sxt.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sxt.inter.IMemberlogin;
import com.sxt.models.Memberlogin;
import com.sxt.service.MemberLoginService;
@Service
public class MemberLoginServiceImpl implements MemberLoginService{
	@Autowired
	private IMemberlogin iMemberLogin;

	@Override
	public void add(Memberlogin login) {
		// TODO Auto-generated method stub
		iMemberLogin.add(login);
	}

}


text:
#ifndef IR_IRUTILS_H_
#define IR_IRUTILS_H_

#include <vector>

#include <boost/none.hpp>
#include <boost/optional/optional.hpp>

#include "frontends/common/constantFolding.h"
#include "frontends/p4/strengthReduction.h"
#include "ir/ir.h"
#include "lib/big_int_util.h"
#include "lib/cstring.h"
#include "lib/error.h"
#include "lib/exceptions.h"

namespace IR {

/// Utility functions for generating IR nodes.
//
// Some of these are just thin wrappers around functions in the IR, but it's nice having everything
// in one place.

/* =========================================================================================
 *  Types
 * ========================================================================================= */

/// @returns a representation of bit<>. If isSigned is true, will return an int<>.
const Type_Bits* getBitType(int size, bool isSigned = false);

/// @returns a representation of bit<> that is just wide enough to fit the given value.
const Type_Bits* getBitTypeToFit(int value);

/* =========================================================================================
 *  Expressions
 * ========================================================================================= */
/// @returns a constant. The value is cached.
const Constant* getConstant(const Type* type, big_int v);

/// @returns a bool literal. The value is cached.
const BoolLiteral* getBoolLiteral(bool value);

/// Applies expression optimizations to the input node.
/// Currently, performs constant folding and strength reduction.
template <class T>
const T* optimizeExpression(const T* node) {
    auto pass = PassRepeated({
        new P4::StrengthReduction(nullptr, nullptr, nullptr),
        new P4::ConstantFolding(nullptr, nullptr, false),
    });
    node = node->apply(pass);
    BUG_CHECK(::errorCount() == 0, "Encountered errors while trying to optimize expressions.");
    return node;
}

/// @returns the "default" value for a given type. The current mapping is
/// Type_Bits       0
/// Type_Boolean    false
const Literal* getDefaultValue(const Type* type);

/* =========================================================================================
 *  Other helper functions
 * ========================================================================================= */
/// @returns the big int value stored in a literal.
big_int getBigIntFromLiteral(const Literal*);

/// @returns the integer value stored in a literal. We use int here.
int getIntFromLiteral(const Literal*);

/// @returns the maximum value that can fit into this type.
/// This function assumes a big int value, meaning it only supports bit vectors and booleans.
// This is 2^(t->size) - 1 for unsigned and 2^(t->size - 1) - 1 for signed.
big_int getMaxBvVal(const Type* t);

/// @returns the maximum big_int value that can fit into this bit width.
big_int getMaxBvVal(int bitWidth);

/// @returns the minimum value that can fit into this type.
// This is 0 for unsigned and -(2^(t->size - 1)) for signed.
big_int getMinBvVal(const Type* t);

/// Given an StructExpression, returns a flat vector of the expressions contained in that
/// struct. Unfortunately, list and struct expressions are similar but have no common ancestors.
/// This is why we require two separate methods.
std::vector<const Expression*> flattenStructExpression(const StructExpression* structExpr);

/// Given an ListExpression, returns a flat vector of the expressions contained in that
/// list.
std::vector<const Expression*> flattenListExpression(const ListExpression* listExpr);

}  // namespace IR

#endif /* IR_IRUTILS_H_ */


text:
package com.querydsl.core.types;

import java.util.List;
import java.util.Map;

import javax.annotation.Nullable;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;

/**
 * {@code QMap} represents a projection of type Map
 *
 *
Usage example

 *

 * {@code
 * List<Map<Expression<?>,?> result = query.from(employee).select(Projections.map(employee.firstName, employee.lastName)).fetch();
 * for (Tuple row : result) {
 *     System.out.println("firstName " + row.get(employee.firstName));
 *     System.out.println("lastName " + row.get(employee.lastName));
 * }
 * }
 *

 *
 * @author tiwe
 *
 */
public class QMap extends FactoryExpressionBase<Map<Expression<?>,?>> {

    private static final long serialVersionUID = -7545994090073480810L;

    private final ImmutableList<Expression<?>> args;

    /**
     * Create a new QMap instance
     *
     * @param args
     */
    protected QMap(Expression<?>... args) {
        super((Class) Map.class);
        this.args = ImmutableList.copyOf(args);
    }

    /**
     * Create a new QMap instance
     *
     * @param args
     */
    protected QMap(ImmutableList<Expression<?>> args) {
        super((Class) Map.class);
        this.args = args;
    }

    /**
     * Create a new QMap instance
     *
     * @param args
     */
    protected QMap(Expression<?>[]... args) {
        super((Class) Map.class);
        ImmutableList.Builder<Expression<?>> builder = ImmutableList.builder();
        for (Expression<?>[] exprs: args) {
            builder.add(exprs);
        }
        this.args = builder.build();
    }

    @Override
    @Nullable
    public <R, C> R accept(Visitor<R, C> v, C context) {
        return v.visit(this, context);
    }

    @Override
    public List<Expression<?>> getArgs() {
        return args;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        } else if (obj instanceof FactoryExpression) {
            FactoryExpression<?> c = (FactoryExpression<?>) obj;
            return args.equals(c.getArgs()) && getType().equals(c.getType());
        } else {
            return false;
        }
    }

    @Override
    @Nullable
    public Map<Expression<?>, ?> newInstance(Object... args) {
        Map<Expression<?>, Object> map = Maps.newHashMap();
        for (int i = 0; i < args.length; i++) {
            map.put(this.args.get(i), args[i]);
        }
        return map;
    }

}


text:
package org.frozenarc.zeframework.tag;

import org.frozenarc.zeframework.applicationexception.ApplicationException;
import org.frozenarc.zeframework.constants.FWConstants;

/**
 * Represents 'checkbutton' tag.
 * @author Manan
 */
public class CheckButtonTag extends InputButtonTag {
    @Override
    public String getInputType() {
        return "checkbox";
    }

    @Override
    public void addAtributes(StringBuilder builder) throws ApplicationException {
        if(pageContext.getAttribute(FWConstants.CHECK_GROUP_TAG_NAME+groupname)!=null) {
            name=groupname;
            valueto=null;
        }
        super.addAtributes(builder);
    }
}


text:
package me.lucko.luckperms.constants;

import lombok.Getter;
import lombok.experimental.UtilityClass;

import java.util.UUID;

@UtilityClass
public class Constants {

    @Getter
    private static final UUID consoleUUID = UUID.fromString("00000000-0000-0000-0000-000000000000");

    @Getter
    private static final String consoleName = "Console";

    @Getter
    private static final UUID importerUUID = UUID.fromString("11111111-1111-1111-1111-111111111111");

    @Getter
    private static final String importerName = "Import";

    @Getter
    private static final String logFormat = "&8(&e%s&8)  [&a%s&8] (&b%s&8) &7--> &f%s";

}


text:
<?xml version="1.0" encoding="UTF-8"?><archetype>
  <id>wannabecool</id>
  <sources>
    <source>src/main/java/domain/persona/Name.java</source>
    <source>src/main/java/domain/persona/package-info.java</source>
    <source>src/main/java/domain/persona/Persona.java</source>
    <source>src/main/java/domain/link/SocialGroup.java</source>
    <source>src/main/java/domain/link/package-info.java</source>
    <source>src/main/java/domain/link/Link.java</source>
    <source>src/main/java/api/PersonaService.java</source>
    <source>src/main/java/api/package-info.java</source>
    <source>src/main/java/api/PermissionDeniedException.java</source>
    <source>src/main/java/api/ExclusiveGroupException.java</source>
    <source>src/main/java/api/SocialGroupService.java</source>
    <source>src/main/java/impl/PersonaServiceImpl.java</source>
    <source>src/main/java/impl/SocialGroupServiceImpl.java</source>
  </sources>
  <resources>
    <resource>enunciate.xml</resource>
  </resources>
</archetype>


text:
'use strict';

var React = require('react');
var _ = require('underscore');

var WeekDaysHeader = require('./WeekDaysHeader.react.js');
var Week = require('./Week.react.js');
var MonthNavigationHeader = require('./MonthNavigationHeader.react.js');
var DataBuilder = require('../../src/dataBuilder.js');

module.exports = React.createClass({

  getInitialState: function getInitialState() {
    return {};
  },

  overEvent: function getOverEvent() {
    return this.state.overEvent;
  },

  render: function render() {
    var data = DataBuilder.build(this.props.month,
                                 this.props.year,
                                 this.props.data,
                                 this.props.config);

    var component = this;
    return (

          {this.props.monthNavigationHeader && <MonthNavigationHeader month={this.props.month}
                                                                      year={this.props.year}
                                                                      onPreviousMonth={this.props.onPreviousMonth}
                                                                      onNextMonth={this.props.onNextMonth} />}
          {this.props.weekDaysHeader && <WeekDaysHeader data={data} />}
          {_.map(data.weeks, function weekToComponent(week, key) {
            return <Week key={key} data={week} calendar={component} />
          })}

    );
  }
});


text:
package cyclops.monads.anym.value;

import com.oath.cyclops.util.box.Mutable;
import cyclops.control.Maybe;
import cyclops.control.Option;
import cyclops.monads.AnyM;
import cyclops.monads.Witness;
import cyclops.monads.Witness.maybe;
import cyclops.monads.Witness.option;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;

public class OptionAnyMValueTest extends BaseAnyMValueTest<option> {
    @Before
    public void setUp() throws Exception {
        just = AnyM.fromOption(Option.of(10));
        none = AnyM.fromOption(Option.none());
    }
    @Test
    public void testPeek() {
        Mutable<Integer> capture = Mutable.of(null);
        just = just.peek(c->capture.set(c));
        assertNotNull(capture.get());

        just.get();
        assertThat(capture.get(),equalTo(10));
    }
}


text: app/config/parameters.yml düzenleyiniz.


text:
build_image_base=postgres:9.5
build_run_user=postgres
build_run_home=/var/lib/postgresql
build_simply=1
build_docker_cmd='[]'
build_dockerfile_aux='ENTRYPOINT []'

# T
# rm -rf /tmp/p; mkdir -p /tmp/p/{data,run}
#docker run -t -u postgres -v /tmp/p/data:/var/lib/postgresql/data -v /tmp/p/run:/run/postgresql -e POSTGRES_PASSWORD=anything -e JPY_PSQL_PASSWORD=anything radiasoft/postgres bash /radia-init.sh
#docker run -t -u postgres -v /tmp/p/data:/var/lib/postgresql/data -v /tmp/p/run:/run/postgresql -e POSTGRES_PASSWORD=anything -e JPY_PSQL_PASSWORD=anything radiasoft/postgres postgres

build_as_root() {
    cd "$build_guest_conf"
    userdel -r "$build_run_user" >& /dev/null || true
    groupadd -g "$build_run_uid" "$build_run_user"
    useradd -m -u "$build_run_uid" -g "$build_run_uid" "$build_run_user"
    rm -rf /docker-entrypoint-initdb.d /docker-entrypoint.sh
    cp radia-init.sh /
    chmod a+r /radia-init.sh
}


text:
#import "MCTActivityVC.h"
#import "MCTComponentFramework.h"
#import "MCTContactCell.h"
#import "MCTFriendsTabVC.h"
#import "MCTMoreVC.h"
#import "MCTProfileVC.h"
#import "MCTScannerVC.h"
#import "MCTSettingsVC.h"
#import "MCTUIUtils.h"
#import "MCTUtils.h"
#import "UIImage+FontAwesome.h"

#define MCT_ROW_HEIGHT 42
#define NUM_ROWS 5

#define MCT_ROW_FRIENDS 0
#define MCT_ROW_PROFILE 1
#define MCT_ROW_SCAN 2
#define MCT_ROW_SETTINGS 3
#define MCT_ROW_STREAM 4

@implementation MCTMoreVC

- (void)viewDidLoad
{
    T_UI();
    self.title = MCTLocalizedString(@"More", nil);

    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.bounces = NO;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.view addSubview:self.tableView];
    [super viewDidLoad];
}

- (NSInteger)rowForIndexPahRow:(NSInteger)oldRow
{
    NSInteger row = oldRow;

    if (oldRow == MCT_ROW_FRIENDS) {
        if (!MCT_SHOW_FRIENDS_IN_MORE) {
            row += 1;
            if (!MCT_SHOW_PROFILE_IN_MORE) {
                row += 1;
                if (!MCT_SHOW_SCAN_IN_MORE) {
                    row += 1;
                }
            }
        }
    } else {
        if (!MCT_SHOW_FRIENDS_IN_MORE) {
            row += 1;
        }
        if (!MCT_SHOW_PROFILE_IN_MORE) {
            row += 1;
        }
        if (!MCT_SHOW_SCAN_IN_MORE) {
            row += 1;
        }
    }

    return row;
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    T_UI();
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    T_UI();
    NSInteger numRows = NUM_ROWS;
    if (!MCT_SHOW_FRIENDS_IN_MORE)
        numRows -= 1;

    if(!MCT_SHOW_PROFILE_IN_MORE)
        numRows -= 1;

    if (!MCT_SHOW_SCAN_IN_MORE)
        numRows -= 1;

    return numRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    T_UI();
    MCTContactCell *cell = [tableView dequeueReusableCellWithIdentifier:@""];
    if (cell == nil) {
        cell = [[MCTContactCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        cell.textLabel.textColor = MCT_APP_TEXT_COLOR;
        cell.paddingX = 15;
        cell.imageView.backgroundColor = [[MCTComponentFramework lookAndFeelManager] primaryOrTintColor];
        cell.imageView.contentMode = UIViewContentModeCenter;

        [MCTUIUtils setBackgroundPlainToView:cell];
        [MCTUIUtils addRoundedBorderToView:cell.imageView
                           withBorderColor:[UIColor clearColor]
                           andCornerRadius:(MCT_ROW_HEIGHT - 10) / 2];

        UIView *sep = [[UIView alloc] initWithFrame:CGRectMake(MCT_ROW_HEIGHT + 20,
                                                               MCT_ROW_HEIGHT - 1,
                                                               self.view.width - MCT_ROW_HEIGHT - 20,
                                                               1)];
        sep.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        sep.backgroundColor = [UIColor MCTSeparatorColor];
        [cell addSubview:sep];

        [self applyStyleToView:cell recursive:YES];
    }

    NSString *icon = nil;
    NSInteger row = [self rowForIndexPahRow:indexPath.row];

    if (row == MCT_ROW_STREAM) {
        icon = @"fa-commenting-o";
        cell.textLabel.text = MCTLocalizedString(@"Stream", nil);
    }
    else if (row == MCT_ROW_PROFILE) {
        icon = @"fa-user";
        cell.textLabel.text = MCTLocalizedString(@"Profile", nil);
    }
    else if (row == MCT_ROW_SCAN) {
        icon = @"fa-qrcode";
        cell.textLabel.text = MCTLocalizedString(@"Scan", nil);
    }
    else if (row== MCT_ROW_SETTINGS) {
        icon = @"fa-tachometer";
        cell.textLabel.text = MCTLocalizedString(@"Settings", nil);
    }
    else if (row == MCT_ROW_FRIENDS) {
        icon = @"fa-users";
        switch (MCT_FRIENDS_CAPTION) {
            case MCTFriendsCaptionColleagues: {
                cell.textLabel.text = MCTLocalizedString(@"Colleagues", nil);
                break;
            }
            case MCTFriendsCaptionContacts: {
                cell.textLabel.text = MCTLocalizedString(@"Contacts", nil);
                break;
            }
            case MCTFriendsCaptionFriends:
            default: {
                cell.textLabel.text = MCTLocalizedString(@"Friends", nil);
                break;
            }
        }
    }
    CGFloat w = (MCT_ROW_HEIGHT - 2 * cell.paddingY) * 0.6;
    cell.imageView.image = [UIImage imageWithIcon:icon
                                  backgroundColor:[UIColor clearColor]
                                        iconColor:[UIColor whiteColor]
                                          andSize:CGSizeMake(w, w)];
    return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    T_UI();
    return MCT_ROW_HEIGHT;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    T_UI();
    UIViewController *vc = nil;

    NSInteger row = [self rowForIndexPahRow:indexPath.row];

    if (row == MCT_ROW_STREAM) {
        vc = [MCTActivityVC viewController];
    }
    else if (row == MCT_ROW_PROFILE) {
        vc = [MCTProfileVC viewController];
    }
    else if (row == MCT_ROW_SCAN) {
        vc = [[MCTScannerVC alloc] init];
    }
    else if (row == MCT_ROW_SETTINGS) {
        vc = [MCTSettingsVC viewController];
    }
    else if (row == MCT_ROW_FRIENDS) {
        vc = [[MCTFriendsTabVC alloc] init];
    }

    if (vc) {
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end


text:
package com.intellij.velocity.psi;

import javax.annotation.Nonnull;

import org.jetbrains.annotations.NonNls;

/**
 * Created by IntelliJ IDEA.
 * User: Alexey Chmutov
 * Date: 27.03.2008
 */
public class VtlOperatorTokenType extends VtlTokenType {
    private final VtlExpressionTypeCalculator myTypeCalculator;

    public VtlOperatorTokenType(@Nonnull @NonNls final String debugName, @Nonnull VtlExpressionTypeCalculator typeCalculator) {
        super(debugName);
        myTypeCalculator = typeCalculator;
    }

    public VtlExpressionTypeCalculator getTypeCalculator() {
        return myTypeCalculator;
    }
}


text:
package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import server.ServerMain;
import server.logica.CaricamentoMappa;
import server.logica.Cella;
import server.logica.Classifica;
import server.logica.GenerazioneMappa;
import server.logica.Isola;
import server.logica.Partita;
import server.logica.Turno;
import server.rmi.Implementazione;

/**
 * Classe per la gestione del Server.
 */
public class ServerMain {

	private int porta;
	private int portaRmi;
	private Partita partita;
	private GestioneGiocatori gestioneGiocatori;
	private Classifica classifica;

	/**
	 * Costruttore della classe ServerMultiClient che inizializza la mappa, la Partita, la Classifica ed il Turno.
	 * @param porta int che rappresenta la porta di comunicazione.
	 */
	public ServerMain(int porta, int portaRmi) {
		this.porta = porta;
		this.portaRmi = portaRmi;
		GenerazioneMappa gm = new GenerazioneMappa();
		CaricamentoMappa cm = new CaricamentoMappa();
		Cella[][] mappaCelle = cm.caricaMappa(gm.creaMappaCasuale());

//		Cella[][] mappaCelle = cm.caricaDaFile("mappaTestAcquaUovo.txt");
		this.partita = new Partita(new Isola(mappaCelle));
		Turno t = new Turno(partita);
		partita.setTurnoCorrente(t);
		this.gestioneGiocatori = new GestioneGiocatori();
		this.classifica = new Classifica(this.partita);
	}

	/**
	 * Metodo per la gestione delle connessioni.
	 * @throws IOException Eccezione duvuta ad un errore nell'apertura di una nuova connessione con un Client.
	 */
	public void runServer() throws IOException {

		//RMI
		//LocateRegistry viene usato per creare un riferimento al registro remoto su un host.
		//createRegistry crea ed esporta un'istaza del registro sul client (specificando la porta)
		//registry e' un'interfaccia remota usata in rmi
	    Registry reg = LocateRegistry.createRegistry(portaRmi);
	    reg.rebind("isola-rmi", new Implementazione());
	    //rebind: sostiuisce il legame per il nome specificato nel registro col riferimento remoto.
	    //La classe con l'implementazione viene registrata sul server RMI
	    System.out.println("RMI avviato su porta " + portaRmi);

		//socket
		ServerSocket serverSocket = new ServerSocket(porta);
		ServerSocket serverSocketTurno = new ServerSocket(5678);
		System.out.println("Server avviato. In attesa di connessioni...");
		while (true) {
			try {
				Socket socket = serverSocket.accept();
				Socket socketTurno = serverSocketTurno.accept();
				System.out.println("Client connesso, creazione di un nuovo client handler.");
				new GestoreClient(socket, socketTurno, partita,gestioneGiocatori,classifica).start();
			} catch (IOException e) {
				System.out.println("Errore durante l'apertura di una connessione.");
			}
			System.out.println("In attesa di una nuova connessione...");
		}
	}

	/**
	 * Metodo che avvia il Server.
	 */
	public static void main(String[] args) {
		ServerMain serverMultiClient = new ServerMain(1234,1099);
		try {
			serverMultiClient.runServer();
		} catch (IOException e) {
			System.out.println("Errore durante l'apertuta di socket.");
			System.out.println("Terminazione.");
		}

	}

}


text:
title: Changelog
hide_title: true
pagination_next: null
pagination_prev: null
---

import ChangeLog, {
toc as ChangeLogTOC
} from '@site/../packages/react-day-picker/CHANGELOG.md';

<ChangeLog />

export const toc = ChangeLogTOC;


text:
package com.github.rzykov.fastml4j.loss

import org.scalatest.Matchers._
import org.scalatest._

import math.random
import org.nd4j.linalg.api.ndarray.INDArray
import org.nd4j.linalg.dataset.DataSet
import com.github.rzykov.fastml4j.util.Implicits._
import com.github.rzykov.fastml4j.util.Intercept

class RegularisationSuite  extends FunSuite with BeforeAndAfter {

  class L2test extends Loss  {
    override def loss(weights: INDArray, dataSet: DataSet): Float = {
      0
    }
    override def gradient(weights: INDArray, dataSet: DataSet): INDArray =
      weights
  }

  private class L2testLoss(override val lambdaL2: Float, override val calcIntercept: Boolean)
    extends L2test with L2 with Intercept

  test("L2") {
    val l2WithIntercept = new L2testLoss(2, true)

    val l2WithoutIntercept = new L2testLoss(2, false)

    val weights = Array(1.0, 2.0, 3.0).toNDArray

    val trainData = Array(Array(-1,2,1)).toNDArray
    val labels = Array(Array(1.0)).toNDArray

    val dataSet = new DataSet(trainData, labels)

    assert(l2WithIntercept.loss(weights, dataSet) == 5.0f)
    assert(l2WithoutIntercept.loss(weights, dataSet) == 14.0f)

    assert(l2WithIntercept.gradient(weights, dataSet).toArray.deep == Array(Array(3.0f, 6.0f, 3.0f)).deep)
    assert(l2WithoutIntercept.gradient(weights, dataSet).toArray.deep == Array(Array(3.0f, 6.0f, 9.0f)).deep)
  }
}


text:
require_relative 'qiita_api_accesser'
require_relative 'qiita_api_accesser'

class MultiTagsSearcher

  def initialize(articles_data, tags)
    @articles = articles_data.map { |data| QiitaArticle.new(data) }
    @tags = tags
  end

  attr_reader :articles

  def group_by_relevance
    @articles.group_by do |article|
      @tags.count { |tag| article.has_tag?(tag) }
    end
  end

end


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

#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_PAINT_CONTROLLER_TEST_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_PAINT_CONTROLLER_TEST_H_

#include "base/dcheck_is_on.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/hit_test_data.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
#include "third_party/blink/renderer/platform/testing/fake_display_item_client.h"
#include "third_party/blink/renderer/platform/testing/paint_property_test_helpers.h"

namespace blink {

class GraphicsContext;

class PaintControllerCycleScopeForTest : public PaintControllerCycleScope {
 public:
  explicit PaintControllerCycleScopeForTest(PaintController& controller)
      : PaintControllerCycleScope(controller, /*record_debug_info*/ true) {}
};

class CommitCycleScope : public PaintControllerCycleScopeForTest {
 public:
  using PaintControllerCycleScopeForTest::PaintControllerCycleScopeForTest;
  ~CommitCycleScope() {
    for (auto* controller : controllers_)
      controller->CommitNewDisplayItems();
  }
};

class PaintControllerTestBase : public testing::Test {
 public:
  static void DrawNothing(GraphicsContext& context,
                          const DisplayItemClient& client,
                          DisplayItem::Type type) {
    if (DrawingRecorder::UseCachedDrawingIfPossible(context, client, type))
      return;
    DrawingRecorder recorder(context, client, type, gfx::Rect());
  }

  static void DrawRect(GraphicsContext& context,
                       const DisplayItemClient& client,
                       DisplayItem::Type type,
                       const gfx::Rect& bounds) {
    if (DrawingRecorder::UseCachedDrawingIfPossible(context, client, type))
      return;
    DrawingRecorder recorder(context, client, type, bounds);
    context.DrawRect(bounds, AutoDarkMode::Disabled());
  }

 protected:
  PaintControllerTestBase()
      : root_paint_property_client_(
            MakeGarbageCollected<FakeDisplayItemClient>("root")),
        root_paint_chunk_id_(root_paint_property_client_->Id(),
                             DisplayItem::kUninitializedType),
        paint_controller_(std::make_unique<PaintController>()) {}

  void SetUp() override {
    testing::FLAGS_gtest_death_test_style = "threadsafe";
  }

  void InitRootChunk() { InitRootChunk(GetPaintController()); }
  void InitRootChunk(PaintController& paint_controller) {
    paint_controller.UpdateCurrentPaintChunkProperties(
        root_paint_chunk_id_, *root_paint_property_client_,
        DefaultPaintChunkProperties());
    paint_controller.RecordDebugInfo(*root_paint_property_client_);
  }
  const PaintChunk::Id DefaultRootChunkId() const {
    return root_paint_chunk_id_;
  }

  PaintController& GetPaintController() { return *paint_controller_; }

  wtf_size_t NumCachedNewItems() const {
    return paint_controller_->num_cached_new_items_;
  }
  wtf_size_t NumCachedNewSubsequences() const {
    return paint_controller_->num_cached_new_subsequences_;
  }
#if DCHECK_IS_ON()
  wtf_size_t NumIndexedItems() const {
    return paint_controller_->num_indexed_items_;
  }
  wtf_size_t NumSequentialMatches() const {
    return paint_controller_->num_sequential_matches_;
  }
  wtf_size_t NumOutOfOrderMatches() const {
    return paint_controller_->num_out_of_order_matches_;
  }
#endif

  void InvalidateAll() { paint_controller_->InvalidateAllForTesting(); }

  using SubsequenceMarkers = PaintController::SubsequenceMarkers;
  const SubsequenceMarkers* GetSubsequenceMarkers(
      const DisplayItemClient& client) {
    return paint_controller_->GetSubsequenceMarkers(client.Id());
  }

  static bool ClientCacheIsValid(const PaintController& paint_controller,
                                 const DisplayItemClient& client) {
    return paint_controller.ClientCacheIsValid(client);
  }

  bool ClientCacheIsValid(const DisplayItemClient& client) const {
    return ClientCacheIsValid(*paint_controller_, client);
  }

 private:
  Persistent<FakeDisplayItemClient> root_paint_property_client_;
  PaintChunk::Id root_paint_chunk_id_;
  std::unique_ptr<PaintController> paint_controller_;
};

// Matcher for checking display item list. Sample usage:
// EXPECT_THAT(paint_controller.GetDisplayItemList(),
//             ElementsAre(IsSameId(client1, kBackgroundType),
//                         IsSameId(client2, kForegroundType)));
MATCHER_P(IsSameId, id, "") {
  return arg.GetId() == id;
}
MATCHER_P2(IsSameId, client_id, type, "") {
  return arg.GetId() == DisplayItem::Id(client_id, type);
}
MATCHER_P3(IsSameId, client_id, type, fragment, "") {
  return arg.GetId() == DisplayItem::Id(client_id, type, fragment);
}

// Matcher for checking paint chunks. Sample usage:
// EXPACT_THAT(paint_controller.PaintChunks(),
//             ELementsAre(IsPaintChunk(0, 1, id1, properties1),
//                         IsPaintChunk(1, 3, id2, properties2)));
inline bool CheckChunk(const PaintChunk& chunk,
                       wtf_size_t begin,
                       wtf_size_t end) {
  return chunk.begin_index == begin && chunk.end_index == end;
}
inline bool CheckChunk(const PaintChunk& chunk,
                       wtf_size_t begin,
                       wtf_size_t end,
                       const PaintChunk::Id& id,
                       const PropertyTreeStateOrAlias& properties,
                       const HitTestData* hit_test_data = nullptr,
                       const gfx::Rect* bounds = nullptr) {
  return chunk.begin_index == begin && chunk.end_index == end &&
         chunk.id == id && chunk.properties == properties &&
         ((!chunk.hit_test_data && !hit_test_data) ||
          (chunk.hit_test_data && hit_test_data &&
           *chunk.hit_test_data == *hit_test_data)) &&
         (!bounds || chunk.bounds == *bounds);
}
MATCHER_P2(IsPaintChunk, begin, end, "") {
  return CheckChunk(arg, begin, end);
}
MATCHER_P4(IsPaintChunk, begin, end, id, properties, "") {
  return CheckChunk(arg, begin, end, id, properties);
}
MATCHER_P5(IsPaintChunk, begin, end, id, properties, hit_test_data, "") {
  return CheckChunk(arg, begin, end, id, properties, hit_test_data);
}
MATCHER_P6(IsPaintChunk,
           begin,
           end,
           id,
           properties,
           hit_test_data,
           bounds,
           "") {
  return CheckChunk(arg, begin, end, id, properties, hit_test_data, &bounds);
}

// Shorter names for frequently used display item types in tests.
const DisplayItem::Type kBackgroundType = DisplayItem::kBoxDecorationBackground;
const DisplayItem::Type kForegroundType =
    static_cast<DisplayItem::Type>(DisplayItem::kDrawingPaintPhaseFirst + 5);
const DisplayItem::Type kClipType = DisplayItem::kClipPaintPhaseFirst;

#define EXPECT_SUBSEQUENCE(client, expected_start_chunk_index,     \
                           expected_end_chunk_index)               \
  do {                                                             \
    auto* subsequence = GetSubsequenceMarkers(client);             \
    ASSERT_NE(nullptr, subsequence);                               \
    EXPECT_EQ(static_cast<wtf_size_t>(expected_start_chunk_index), \
              subsequence->start_chunk_index);                     \
    EXPECT_EQ(static_cast<wtf_size_t>(expected_end_chunk_index),   \
              subsequence->end_chunk_index);                       \
  } while (false)

#define EXPECT_SUBSEQUENCE_FROM_CHUNK(client, start_chunk_iterator, \
                                      chunk_count)                  \
  EXPECT_SUBSEQUENCE(                                               \
      client, (start_chunk_iterator).IndexInPaintArtifact(),        \
      (start_chunk_iterator).IndexInPaintArtifact() + chunk_count)

#define EXPECT_NO_SUBSEQUENCE(client) \
  EXPECT_EQ(nullptr, GetSubsequenceMarkers(client))

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_PAINT_CONTROLLER_TEST_H_


text:
module.exports = {
  Greeting: require("./components/greeting.jsx")
};


text:
#ifndef CONSTS_H
#define CONSTS_H

// Current Version: 1.1.0
#define PHANTOMJS_VERSION_MAJOR  1
#define PHANTOMJS_VERSION_MINOR  1
#define PHANTOMJS_VERSION_PATCH  0
#define PHANTOMJS_VERSION_STRING "1.1.0"

#endif // CONSTS_H


text:
using System.Web.Mvc;
using OnLineShop.Web.Controllers;
using NUnit.Framework;

namespace OnLineShop.Web.Tests.Controllers.HomeControllerTests
{
    [TestFixture]
    public class HomeControllerTest
    {
        [Test]
        public void Index()
        {
            // Arrange
            HomeController controller = new HomeController();

            // Act
            ViewResult result = controller.Index() as ViewResult;

            // Assert
            Assert.IsNotNull(result);
        }

        [Test]
        public void About()
        {
            // Arrange
            HomeController controller = new HomeController();

            // Act
            ViewResult result = controller.About() as ViewResult;

            // Assert
            Assert.AreEqual("Your application description page.", result.ViewBag.Message);
        }

        [Test]
        public void Contact()
        {
            // Arrange
            HomeController controller = new HomeController();

            // Act
            ViewResult result = controller.Contact() as ViewResult;

            // Assert
            Assert.IsNotNull(result);
        }
    }
}


text:
package org.directwebremoting.convert;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.directwebremoting.ConversionException;
import org.directwebremoting.extend.AbstractConverter;
import org.directwebremoting.extend.InboundVariable;
import org.directwebremoting.extend.NonNestedOutboundVariable;
import org.directwebremoting.extend.OutboundContext;
import org.directwebremoting.extend.OutboundVariable;
import org.directwebremoting.util.LocalUtil;

/**
 * Used by {@link XmlBeanConverter}.
 * @author Joe Walker [joe at getahead dot ltd dot uk]
 * @author Matthew Young [matthew dot young at forsakringskassan dot se]
 */
public class StringEnumAbstractBaseConverter extends AbstractConverter
{
    /* (non-Javadoc)
     * @see org.directwebremoting.extend.Converter#convertInbound(java.lang.Class, org.directwebremoting.extend.InboundVariable, org.directwebremoting.extend.InboundContext)
     */
    public Object convertInbound(Class<?> paramType, InboundVariable data) throws ConversionException
    {
        if (data.isNull())
        {
            return null;
        }

        String value = LocalUtil.urlDecode(data.getValue());

        try
        {
            Method getter = paramType.getMethod("forString", String.class);
            Object bean = getter.invoke(paramType, value);

            if (bean == null)
            {
                throw new ConversionException(paramType, "unknown enum value (" + value + ")");
            }

            return bean;
        }
        catch (NoSuchMethodException e)
        {
            throw new ConversionException(paramType, e);
        }
        catch (IllegalArgumentException e)
        {
            throw new ConversionException(paramType, e);
        }
        catch (IllegalAccessException e)
        {
            throw new ConversionException(paramType, e);
        }
        catch (InvocationTargetException e)
        {
            throw new ConversionException(paramType, e);
        }
    }

    /* (non-Javadoc)
     * @see org.directwebremoting.extend.Converter#convertOutbound(java.lang.Object, org.directwebremoting.extend.OutboundContext)
     */
    public OutboundVariable convertOutbound(Object data, OutboundContext outctx)
    {
        return new NonNestedOutboundVariable('\'' + data.toString() + '\'');
    }
}


text:
<?php
return array (
  'Change E-mail' => 'Skift E-mail',
  'We´ve just sent an confirmation e-mail to your new address.
 Please follow the instructions inside.' => 'Vi har lige sendt dig en bekræftelses e-mail til din nye adresse.
 Venligst følg instruktioner i den.',
);


text:
(function () {

	"use strict";

    var orderController = function ($scope, $routeParams, customersFactory, $log) {

        customersFactory.getCustomer($routeParams.customerId)
            .success(function (customer) {
                $scope.customer = customer;
            })
            .error(function (data, status, headers, config) {
                $log.log(data.error + ' ' + status);
            });
    };

    //workaround so that we're still safe after JS minification for production.
    orderController.$inject = ['$scope', '$routeParams', 'customersFactory', '$log'];

    //register controller with angular
    angular.module('customersApp').controller('orderController', orderController);

}());


text:
/* $Id: ConstraintTag.java,v 1.1 2006/03/19 16:34:51 greese Exp $ */
/* Copyright (c) 2006 Valtira Corporation, All Rights Reserved */
package org.dasein.net.jsp.util;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.dasein.attributes.DataTypeFactory;
import org.dasein.net.jsp.ELParser;

/**
 *

 *   Provides JSTL-style access to enum values inside your JSP code. You can access
 *   the full set of values or a specific value.
 *

 *

 *   Last modified: $Date: 2006/03/19 16:34:51 $
 *

 * @version $Revision: 1.1 $
 * @author George Reese
 */
public class ConstraintTag extends TagSupport {
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -286391249683867555L;

    private String    type      = null;
    private String    typeInfo  = null;
    private String    var       = null;

    public int doEndTag() throws JspException {
        try {
            DataTypeFactory factory = DataTypeFactory.getInstance(type);

            if( typeInfo == null ) {
                pageContext.setAttribute(var, factory.getConstraint((String[])null));
            }
            else {
                String[] params = typeInfo.split(",");

                if( params == null || params.length < 1 ) {
                    params = new String[1];
                    params[0] = typeInfo;
                }
                pageContext.setAttribute(var, factory.getConstraint(params));
            }
            return EVAL_PAGE;
        }
        finally {
            type = null;
            typeInfo = null;
            var = null;
        }
    }

    public void setType(String t) throws JspException {
        type = (new ELParser(t)).getStringValue(pageContext);
    }

    public void setTypeInfo(String val) throws JspException {
        typeInfo = (new ELParser(val)).getStringValue(pageContext);
    }

    public void setVar(String v) {
        var = v;
    }
}


text:
//---------------------------------------------------------------------------
//	Greenplum Database
//	Copyright (C) 2012 EMC Corp.
//
//	@filename:
//		CParseHandlerPhysicalCTEProducer.cpp
//
//	@doc:
//		Implementation of the SAX parse handler class for parsing CTE producer
//		operators
//---------------------------------------------------------------------------

#include "naucrates/dxl/operators/CDXLOperatorFactory.h"
#include "naucrates/dxl/operators/CDXLPhysicalCTEProducer.h"
#include "naucrates/dxl/parser/CParseHandlerFactory.h"
#include "naucrates/dxl/parser/CParseHandlerPhysicalCTEProducer.h"
#include "naucrates/dxl/parser/CParseHandlerProperties.h"
#include "naucrates/dxl/parser/CParseHandlerUtils.h"
#include "naucrates/dxl/parser/CParseHandlerProjList.h"

using namespace gpdxl;

XERCES_CPP_NAMESPACE_USE

//---------------------------------------------------------------------------
//	@function:
//		CParseHandlerPhysicalCTEProducer::CParseHandlerPhysicalCTEProducer
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CParseHandlerPhysicalCTEProducer::CParseHandlerPhysicalCTEProducer
	(
	IMemoryPool *pmp,
	CParseHandlerManager *pphm,
	CParseHandlerBase *pphRoot
	)
	:
	CParseHandlerPhysicalOp(pmp, pphm, pphRoot)
{
}

//---------------------------------------------------------------------------
//	@function:
//		CParseHandlerPhysicalCTEProducer::StartElement
//
//	@doc:
//		Invoked by Xerces to process an opening tag
//
//---------------------------------------------------------------------------
void
CParseHandlerPhysicalCTEProducer::StartElement
	(
	const XMLCh* const, // xmlszUri,
	const XMLCh* const xmlszLocalname,
	const XMLCh* const, // xmlszQname
	const Attributes& attrs
	)
{
	if (0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenPhysicalCTEProducer), xmlszLocalname))
	{
		CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname);
		GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz());
	}

	// parse cteid and create cte operator
	ULONG ulId = CDXLOperatorFactory::UlValueFromAttrs
											(
											m_pphm->Pmm(),
											attrs,
											EdxltokenCTEId,
											EdxltokenPhysicalCTEProducer
											);

	DrgPul *pdrgpulColIds = CDXLOperatorFactory::PdrgpulFromAttrs(m_pphm->Pmm(), attrs, EdxltokenColumns, EdxltokenPhysicalCTEProducer);

	m_pdxln = GPOS_NEW(m_pmp) CDXLNode(m_pmp, GPOS_NEW(m_pmp) CDXLPhysicalCTEProducer(m_pmp, ulId, pdrgpulColIds));

	// create and activate the parse handler for the child expression node
	CParseHandlerBase *pphChild = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenPhysical), m_pphm, this);
	m_pphm->ActivateParseHandler(pphChild);

	// parse handler for the proj list
	CParseHandlerBase *pphPrL = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenScalarProjList), m_pphm, this);
	m_pphm->ActivateParseHandler(pphPrL);

	//parse handler for the properties of the operator
	CParseHandlerBase *pphProp = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenProperties), m_pphm, this);
	m_pphm->ActivateParseHandler(pphProp);

	// store parse handler
	this->Append(pphProp);
	this->Append(pphPrL);
	this->Append(pphChild);
}

//---------------------------------------------------------------------------
//	@function:
//		CParseHandlerPhysicalCTEProducer::EndElement
//
//	@doc:
//		Invoked by Xerces to process a closing tag
//
//---------------------------------------------------------------------------
void
CParseHandlerPhysicalCTEProducer::EndElement
	(
	const XMLCh* const, // xmlszUri,
	const XMLCh* const xmlszLocalname,
	const XMLCh* const // xmlszQname
	)
{
	if (0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenPhysicalCTEProducer), xmlszLocalname))
	{
		CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname);
		GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz());
	}

	GPOS_ASSERT(NULL != m_pdxln);

	CParseHandlerProperties *pphProp = dynamic_cast<CParseHandlerProperties *>((*this)[0]);
	CParseHandlerProjList *pphPrL = dynamic_cast<CParseHandlerProjList*>((*this)[1]);
	CParseHandlerPhysicalOp *pphChild = dynamic_cast<CParseHandlerPhysicalOp *>((*this)[2]);

	// set physical properties
	CParseHandlerUtils::SetProperties(m_pdxln, pphProp);

	// add constructed children
	AddChildFromParseHandler(pphPrL);
	AddChildFromParseHandler(pphChild);

#ifdef GPOS_DEBUG
		m_pdxln->Pdxlop()->AssertValid(m_pdxln, false /* fValidateChildren */);
#endif // GPOS_DEBUG

	m_pphm->DeactivateHandler();
}

// EOF