text:
namespace llvm {
namespace yaml {

/// A wrapper around std::string which contains a source range that's being
/// set during parsing.
struct StringValue {
  std::string Value;
  SMRange SourceRange;

  StringValue() {}
  StringValue(std::string Value) : Value(std::move(Value)) {}

  bool operator==(const StringValue &Other) const {
    return Value == Other.Value;
  }
};

template <> struct ScalarTraits<StringValue> {
  static void output(const StringValue &S, void *, llvm::raw_ostream &OS) {
    OS << S.Value;
  }

  static StringRef input(StringRef Scalar, void *Ctx, StringValue &S) {
    S.Value = Scalar.str();
    if (const auto *Node =
            reinterpret_cast<yaml::Input *>(Ctx)->getCurrentNode())
      S.SourceRange = Node->getSourceRange();
    return "";
  }

  static bool mustQuote(StringRef Scalar) { return needsQuotes(Scalar); }
};

struct FlowStringValue : StringValue {
  FlowStringValue() {}
  FlowStringValue(std::string Value) : StringValue(Value) {}
};

template <> struct ScalarTraits<FlowStringValue> {
  static void output(const FlowStringValue &S, void *, llvm::raw_ostream &OS) {
    return ScalarTraits<StringValue>::output(S, nullptr, OS);
  }

  static StringRef input(StringRef Scalar, void *Ctx, FlowStringValue &S) {
    return ScalarTraits<StringValue>::input(Scalar, Ctx, S);
  }

  static bool mustQuote(StringRef Scalar) { return needsQuotes(Scalar); }
};

struct BlockStringValue {
  StringValue Value;
};

template <> struct BlockScalarTraits<BlockStringValue> {
  static void output(const BlockStringValue &S, void *Ctx, raw_ostream &OS) {
    return ScalarTraits<StringValue>::output(S.Value, Ctx, OS);
  }

  static StringRef input(StringRef Scalar, void *Ctx, BlockStringValue &S) {
    return ScalarTraits<StringValue>::input(Scalar, Ctx, S.Value);
  }
};

/// A wrapper around unsigned which contains a source range that's being set
/// during parsing.
struct UnsignedValue {
  unsigned Value;
  SMRange SourceRange;

  UnsignedValue() : Value(0) {}
  UnsignedValue(unsigned Value) : Value(Value) {}

  bool operator==(const UnsignedValue &Other) const {
    return Value == Other.Value;
  }
};

template <> struct ScalarTraits<UnsignedValue> {
  static void output(const UnsignedValue &Value, void *Ctx, raw_ostream &OS) {
    return ScalarTraits<unsigned>::output(Value.Value, Ctx, OS);
  }

  static StringRef input(StringRef Scalar, void *Ctx, UnsignedValue &Value) {
    if (const auto *Node =
            reinterpret_cast<yaml::Input *>(Ctx)->getCurrentNode())
      Value.SourceRange = Node->getSourceRange();
    return ScalarTraits<unsigned>::input(Scalar, Ctx, Value.Value);
  }

  static bool mustQuote(StringRef Scalar) {
    return ScalarTraits<unsigned>::mustQuote(Scalar);
  }
};

template <> struct ScalarEnumerationTraits<MachineJumpTableInfo::JTEntryKind> {
  static void enumeration(yaml::IO &IO,
                          MachineJumpTableInfo::JTEntryKind &EntryKind) {
    IO.enumCase(EntryKind, "block-address",
                MachineJumpTableInfo::EK_BlockAddress);
    IO.enumCase(EntryKind, "gp-rel64-block-address",
                MachineJumpTableInfo::EK_GPRel64BlockAddress);
    IO.enumCase(EntryKind, "gp-rel32-block-address",
                MachineJumpTableInfo::EK_GPRel32BlockAddress);
    IO.enumCase(EntryKind, "label-difference32",
                MachineJumpTableInfo::EK_LabelDifference32);
    IO.enumCase(EntryKind, "inline", MachineJumpTableInfo::EK_Inline);
    IO.enumCase(EntryKind, "custom32", MachineJumpTableInfo::EK_Custom32);
  }
};

} // end namespace yaml
} // end namespace llvm

LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::StringValue)
LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(llvm::yaml::FlowStringValue)
LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(llvm::yaml::UnsignedValue)

namespace llvm {
namespace yaml {

struct VirtualRegisterDefinition {
  UnsignedValue ID;
  StringValue Class;
  StringValue PreferredRegister;
  // TODO: Serialize the target specific register hints.
};

template <> struct MappingTraits<VirtualRegisterDefinition> {
  static void mapping(IO &YamlIO, VirtualRegisterDefinition &Reg) {
    YamlIO.mapRequired("id", Reg.ID);
    YamlIO.mapRequired("class", Reg.Class);
    YamlIO.mapOptional("preferred-register", Reg.PreferredRegister,
                       StringValue()); // Don't print out when it's empty.
  }

  static const bool flow = true;
};

struct MachineFunctionLiveIn {
  StringValue Register;
  StringValue VirtualRegister;
};

template <> struct MappingTraits<MachineFunctionLiveIn> {
  static void mapping(IO &YamlIO, MachineFunctionLiveIn &LiveIn) {
    YamlIO.mapRequired("reg", LiveIn.Register);
    YamlIO.mapOptional(
        "virtual-reg", LiveIn.VirtualRegister,
        StringValue()); // Don't print the virtual register when it's empty.
  }

  static const bool flow = true;
};

/// Serializable representation of stack object from the MachineFrameInfo class.
///
/// The flags 'isImmutable' and 'isAliased' aren't serialized, as they are
/// determined by the object's type and frame information flags.
/// Dead stack objects aren't serialized.
///
/// The 'isPreallocated' flag is determined by the local offset.
struct MachineStackObject {
  enum ObjectType { DefaultType, SpillSlot, VariableSized };
  UnsignedValue ID;
  StringValue Name;
  // TODO: Serialize unnamed LLVM alloca reference.
  ObjectType Type = DefaultType;
  int64_t Offset = 0;
  uint64_t Size = 0;
  unsigned Alignment = 0;
  StringValue CalleeSavedRegister;
  Optional<int64_t> LocalOffset;
  StringValue DebugVar;
  StringValue DebugExpr;
  StringValue DebugLoc;
};

template <> struct ScalarEnumerationTraits<MachineStackObject::ObjectType> {
  static void enumeration(yaml::IO &IO, MachineStackObject::ObjectType &Type) {
    IO.enumCase(Type, "default", MachineStackObject::DefaultType);
    IO.enumCase(Type, "spill-slot", MachineStackObject::SpillSlot);
    IO.enumCase(Type, "variable-sized", MachineStackObject::VariableSized);
  }
};

template <> struct MappingTraits<MachineStackObject> {
  static void mapping(yaml::IO &YamlIO, MachineStackObject &Object) {
    YamlIO.mapRequired("id", Object.ID);
    YamlIO.mapOptional("name", Object.Name,
                       StringValue()); // Don't print out an empty name.
    YamlIO.mapOptional(
        "type", Object.Type,
        MachineStackObject::DefaultType); // Don't print the default type.
    YamlIO.mapOptional("offset", Object.Offset);
    if (Object.Type != MachineStackObject::VariableSized)
      YamlIO.mapRequired("size", Object.Size);
    YamlIO.mapOptional("alignment", Object.Alignment);
    YamlIO.mapOptional("callee-saved-register", Object.CalleeSavedRegister,
                       StringValue()); // Don't print it out when it's empty.
    YamlIO.mapOptional("local-offset", Object.LocalOffset);
    YamlIO.mapOptional("di-variable", Object.DebugVar,
                       StringValue()); // Don't print it out when it's empty.
    YamlIO.mapOptional("di-expression", Object.DebugExpr,
                       StringValue()); // Don't print it out when it's empty.
    YamlIO.mapOptional("di-location", Object.DebugLoc,
                       StringValue()); // Don't print it out when it's empty.
  }

  static const bool flow = true;
};

/// Serializable representation of the fixed stack object from the
/// MachineFrameInfo class.
struct FixedMachineStackObject {
  enum ObjectType { DefaultType, SpillSlot };
  UnsignedValue ID;
  ObjectType Type = DefaultType;
  int64_t Offset = 0;
  uint64_t Size = 0;
  unsigned Alignment = 0;
  bool IsImmutable = false;
  bool IsAliased = false;
  StringValue CalleeSavedRegister;
};

template <>
struct ScalarEnumerationTraits<FixedMachineStackObject::ObjectType> {
  static void enumeration(yaml::IO &IO,
                          FixedMachineStackObject::ObjectType &Type) {
    IO.enumCase(Type, "default", FixedMachineStackObject::DefaultType);
    IO.enumCase(Type, "spill-slot", FixedMachineStackObject::SpillSlot);
  }
};

template <> struct MappingTraits<FixedMachineStackObject> {
  static void mapping(yaml::IO &YamlIO, FixedMachineStackObject &Object) {
    YamlIO.mapRequired("id", Object.ID);
    YamlIO.mapOptional(
        "type", Object.Type,
        FixedMachineStackObject::DefaultType); // Don't print the default type.
    YamlIO.mapOptional("offset", Object.Offset);
    YamlIO.mapOptional("size", Object.Size);
    YamlIO.mapOptional("alignment", Object.Alignment);
    if (Object.Type != FixedMachineStackObject::SpillSlot) {
      YamlIO.mapOptional("isImmutable", Object.IsImmutable);
      YamlIO.mapOptional("isAliased", Object.IsAliased);
    }
    YamlIO.mapOptional("callee-saved-register", Object.CalleeSavedRegister,
                       StringValue()); // Don't print it out when it's empty.
  }

  static const bool flow = true;
};

struct MachineConstantPoolValue {
  UnsignedValue ID;
  StringValue Value;
  unsigned Alignment = 0;
};

template <> struct MappingTraits<MachineConstantPoolValue> {
  static void mapping(IO &YamlIO, MachineConstantPoolValue &Constant) {
    YamlIO.mapRequired("id", Constant.ID);
    YamlIO.mapOptional("value", Constant.Value);
    YamlIO.mapOptional("alignment", Constant.Alignment);
  }
};

struct MachineJumpTable {
  struct Entry {
    UnsignedValue ID;
    std::vector<FlowStringValue> Blocks;
  };

  MachineJumpTableInfo::JTEntryKind Kind = MachineJumpTableInfo::EK_Custom32;
  std::vector<Entry> Entries;
};

template <> struct MappingTraits<MachineJumpTable::Entry> {
  static void mapping(IO &YamlIO, MachineJumpTable::Entry &Entry) {
    YamlIO.mapRequired("id", Entry.ID);
    YamlIO.mapOptional("blocks", Entry.Blocks);
  }
};

} // end namespace yaml
} // end namespace llvm

LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::MachineFunctionLiveIn)
LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::VirtualRegisterDefinition)
LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::MachineStackObject)
LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::FixedMachineStackObject)
LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::MachineConstantPoolValue)
LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::yaml::MachineJumpTable::Entry)

namespace llvm {
namespace yaml {

template <> struct MappingTraits<MachineJumpTable> {
  static void mapping(IO &YamlIO, MachineJumpTable &JT) {
    YamlIO.mapRequired("kind", JT.Kind);
    YamlIO.mapOptional("entries", JT.Entries);
  }
};

/// Serializable representation of MachineFrameInfo.
///
/// Doesn't serialize attributes like 'StackAlignment', 'IsStackRealignable' and
/// 'RealignOption' as they are determined by the target and LLVM function
/// attributes.
/// It also doesn't serialize attributes like 'NumFixedObject' and
/// 'HasVarSizedObjects' as they are determined by the frame objects themselves.
struct MachineFrameInfo {
  bool IsFrameAddressTaken = false;
  bool IsReturnAddressTaken = false;
  bool HasStackMap = false;
  bool HasPatchPoint = false;
  uint64_t StackSize = 0;
  int OffsetAdjustment = 0;
  unsigned MaxAlignment = 0;
  bool AdjustsStack = false;
  bool HasCalls = false;
  StringValue StackProtector;
  // TODO: Serialize FunctionContextIdx
  unsigned MaxCallFrameSize = 0;
  bool HasOpaqueSPAdjustment = false;
  bool HasVAStart = false;
  bool HasMustTailInVarArgFunc = false;
  StringValue SavePoint;
  StringValue RestorePoint;
};

template <> struct MappingTraits<MachineFrameInfo> {
  static void mapping(IO &YamlIO, MachineFrameInfo &MFI) {
    YamlIO.mapOptional("isFrameAddressTaken", MFI.IsFrameAddressTaken);
    YamlIO.mapOptional("isReturnAddressTaken", MFI.IsReturnAddressTaken);
    YamlIO.mapOptional("hasStackMap", MFI.HasStackMap);
    YamlIO.mapOptional("hasPatchPoint", MFI.HasPatchPoint);
    YamlIO.mapOptional("stackSize", MFI.StackSize);
    YamlIO.mapOptional("offsetAdjustment", MFI.OffsetAdjustment);
    YamlIO.mapOptional("maxAlignment", MFI.MaxAlignment);
    YamlIO.mapOptional("adjustsStack", MFI.AdjustsStack);
    YamlIO.mapOptional("hasCalls", MFI.HasCalls);
    YamlIO.mapOptional("stackProtector", MFI.StackProtector,
                       StringValue()); // Don't print it out when it's empty.
    YamlIO.mapOptional("maxCallFrameSize", MFI.MaxCallFrameSize);
    YamlIO.mapOptional("hasOpaqueSPAdjustment", MFI.HasOpaqueSPAdjustment);
    YamlIO.mapOptional("hasVAStart", MFI.HasVAStart);
    YamlIO.mapOptional("hasMustTailInVarArgFunc", MFI.HasMustTailInVarArgFunc);
    YamlIO.mapOptional("savePoint", MFI.SavePoint,
                       StringValue()); // Don't print it out when it's empty.
    YamlIO.mapOptional("restorePoint", MFI.RestorePoint,
                       StringValue()); // Don't print it out when it's empty.
  }
};

struct MachineFunction {
  StringRef Name;
  unsigned Alignment = 0;
  bool ExposesReturnsTwice = false;
  // GISel MachineFunctionProperties.
  bool Legalized = false;
  bool RegBankSelected = false;
  bool Selected = false;
  // Register information
  bool TracksRegLiveness = false;
  std::vector<VirtualRegisterDefinition> VirtualRegisters;
  std::vector<MachineFunctionLiveIn> LiveIns;
  Optional<std::vector<FlowStringValue>> CalleeSavedRegisters;
  // TODO: Serialize the various register masks.
  // Frame information
  MachineFrameInfo FrameInfo;
  std::vector<FixedMachineStackObject> FixedStackObjects;
  std::vector<MachineStackObject> StackObjects;
  std::vector<MachineConstantPoolValue> Constants; /// Constant pool.
  MachineJumpTable JumpTableInfo;
  BlockStringValue Body;
};

template <> struct MappingTraits<MachineFunction> {
  static void mapping(IO &YamlIO, MachineFunction &MF) {
    YamlIO.mapRequired("name", MF.Name);
    YamlIO.mapOptional("alignment", MF.Alignment);
    YamlIO.mapOptional("exposesReturnsTwice", MF.ExposesReturnsTwice);
    YamlIO.mapOptional("legalized", MF.Legalized);
    YamlIO.mapOptional("regBankSelected", MF.RegBankSelected);
    YamlIO.mapOptional("selected", MF.Selected);
    YamlIO.mapOptional("tracksRegLiveness", MF.TracksRegLiveness);
    YamlIO.mapOptional("registers", MF.VirtualRegisters);
    YamlIO.mapOptional("liveins", MF.LiveIns);
    YamlIO.mapOptional("calleeSavedRegisters", MF.CalleeSavedRegisters);
    YamlIO.mapOptional("frameInfo", MF.FrameInfo);
    YamlIO.mapOptional("fixedStack", MF.FixedStackObjects);
    YamlIO.mapOptional("stack", MF.StackObjects);
    YamlIO.mapOptional("constants", MF.Constants);
    if (!YamlIO.outputting() || !MF.JumpTableInfo.Entries.empty())
      YamlIO.mapOptional("jumpTable", MF.JumpTableInfo);
    YamlIO.mapOptional("body", MF.Body);
  }
};

} // end namespace yaml
} // end namespace llvm

#endif


text:
.ant-timeline {
  list-style: none;
  margin: 0;
  padding: 0;
}
.ant-timeline-item {
  position: relative;
  padding: 0 0 12px 0;
  list-style: none;
  margin: 0;
}
.ant-timeline-item-tail {
  position: absolute;
  left: 5px;
  top: 0;
  height: 100%;
  border-left: 2px solid #e9e9e9;
}
.ant-timeline-item-pending .ant-timeline-item-tail {
  display: none;
}
.ant-timeline-item-head {
  position: absolute;
  width: 12px;
  height: 12px;
  background-color: #fff;
  border-radius: 100px;
  border: 2px solid transparent;
}
.ant-timeline-item-head-blue {
  border-color: #108ee9;
  color: #108ee9;
}
.ant-timeline-item-head-red {
  border-color: #f50;
  color: #f50;
}
.ant-timeline-item-head-green {
  border-color: #87d068;
  color: #87d068;
}
.ant-timeline-item-head-custom {
  position: absolute;
  text-align: center;
  width: 40px;
  left: -14px;
  line-height: 1;
  margin-top: 6px;
  border: 0;
  height: auto;
  border-radius: 0;
  padding: 3px 0;
  font-size: 12px;
  -webkit-transform: translateY(-50%);
      -ms-transform: translateY(-50%);
          transform: translateY(-50%);
}
.ant-timeline-item-content {
  padding: 0 0 10px 24px;
  font-size: 12px;
  position: relative;
  top: -3px;
}
.ant-timeline-item-last .ant-timeline-item-tail {
  border-left: 2px dotted #e9e9e9;
  display: none;
}
.ant-timeline-item-last .ant-timeline-item-content {
  min-height: 48px;
}
.ant-timeline.ant-timeline-pending .ant-timeline-item-last .ant-timeline-item-tail {
  display: block;
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  My article published on TAUR!
date: March 19th, 2016
---

    Before the end of 2015 I submitted a story to
    trailandultrarunning.com. They were having a contest
    and I thought I'd take a crack at it. I ended up winning the grand prize!

    Grief is a hard thing to understand and articulate and in my situation I've always
    felt it too dark to explain to those unaware of it - but, here I explain how I've traveled
    through it. Check it out, The Parallels Between Grief, Life, and Long Distance Running


text:
class HTTPServerMarlin;

class HTTPSiteMarlin : public HTTPSite
{
public:
  HTTPSiteMarlin(HTTPServerMarlin*  p_server
                ,int                p_port
                ,XString            p_site
                ,XString            p_prefix
                ,HTTPSite*          p_mainSite = nullptr
                ,LPFN_CALLBACK      p_callback = nullptr);

  // MANDATORY: Explicitly starting after configuration of the site
  virtual bool StartSite();

  // OPTIONAL: Set the webroot of the site
  virtual bool SetWebroot(XString p_webroot);

protected:
  // Initialize the site from automatic settings in the config
  void         InitSite(MarlinConfig& p_config);
};


text:
package sample.jpa;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.ToString;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;

@Embeddable
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class TextValue implements Serializable {
    @Column(name="text_value")
    private String value;

    @Override
    public boolean equals(Object obj) {
        System.out.println("TextValue.equals(" + obj + ")");
        return (obj instanceof TextValue)
                && ((TextValue) obj).value.equals(this.value);
    }

    @Override
    public int hashCode() {
        return this.value.hashCode();
    }
}


text:
PrisonVisits2::Application.configure do
  config.action_mailer.smtp_settings = {
    user_name: ENV['SMTP_USERNAME'],
    password: ENV['SMTP_PASSWORD']
  }
  config.cache_classes = false
  config.eager_load = false
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false
  config.action_mailer.raise_delivery_errors = false
  config.assets.debug = true
  config.action_mailer.default_url_options = {
    host: "localhost",
    protocol: "http",
    port: "3000"
  }
  config.action_mailer.preview_path = "#{Rails.root}/test/mailers/previews"
  config.active_job.queue_adapter = :sidekiq
  config.smoke_test_email_local_part = ENV['SMOKE_TEST_EMAIL_LOCAL_PART']
  config.smoke_test_email_domain = ENV['SMOKE_TEST_EMAIL_DOMAIN']
  config.session_expire_after = 24.hours
end


text:
Dockerfiles for building with g++/gcc on Ubuntu with valgrind and gdb

Getting Valgrind to work is a pain on non-Linux systems like Windows and MacOS. dliu/ubuntu-gcc-valgrind is an image that combines Valgrind with the normal build chains for C/C++ including gdb, gcc, g++, etc.

Usage:

Open a terminal into your container to use gcc/valgrind, you can do:

	docker run --rm -it -v `pwd`:/app dliu/ubuntu-gcc-valgrind /bin/bash
	root@xxxx# <enter commands here>

You can also directly invoke commands (gcc, valgrind, etc) like this:

	docker run --rm -it -v `pwd`:/app dliu/ubuntu-gcc-valgrind gcc -c hello.c
	docker run --rm -it -v `pwd`:/app dliu/ubuntu-gcc-valgrind valgrind ./a.out


text:
using System.Collections.Generic;
using UML = TSF.UmlToolingFramework.UML;

namespace TSF.UmlToolingFramework.UML.CommonBehaviors.BasicBehaviors
{
    //A behavioral feature is implemented (realized) by a behavior. A behavioral feature specifies that a classifier will respond
    //to a designated request by invoking its implementing method.
	public interface  BehavioralFeature {

        //If true, then the behavioral feature does not have an implementation, and one must be supplied by a more specific
        //element. If false, the behavioral feature must have an implementation in the classifier or one must be inherited
        //from a more general element. Default value is false.
		 bool isAbstract{ get; set; }

        //A behavioral description that implements the behavioral feature. There may be at most one behavior for a particular
        //pairing of a classifier (as owner of the behavior) and a behavioral feature (as specification of the behavior).
		 HashSet<Behavior> methods{ get; set; }

	}
}


text:
#pragma once
#include <aws/opensearch/OpenSearchService_EXPORTS.h>
#include <aws/opensearch/OpenSearchServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/opensearch/model/OpenSearchPartitionInstanceType.h>
#include <utility>

namespace Aws
{
namespace Http
{
    class URI;
} //namespace Http
namespace OpenSearchService
{
namespace Model
{

  /**
   *
 Container for the parameters to the  DescribeInstanceTypeLimits
   *  operation.

See Also:
   AWS
   * API Reference

   */
  class AWS_OPENSEARCHSERVICE_API DescribeInstanceTypeLimitsRequest : public OpenSearchServiceRequest
  {
  public:
    DescribeInstanceTypeLimitsRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DescribeInstanceTypeLimits"; }

    Aws::String SerializePayload() const override;

    void AddQueryStringParameters(Aws::Http::URI& uri) const override;

    /**
     *
 The name of the domain you want to modify. Only include this value if you're
     * querying OpenSearch  Limits  for an existing domain.

     */
    inline const Aws::String& GetDomainName() const{ return m_domainName; }

    /**
     *
 The name of the domain you want to modify. Only include this value if you're
     * querying OpenSearch  Limits  for an existing domain.

     */
    inline bool DomainNameHasBeenSet() const { return m_domainNameHasBeenSet; }

    /**
     *
 The name of the domain you want to modify. Only include this value if you're
     * querying OpenSearch  Limits  for an existing domain.

     */
    inline void SetDomainName(const Aws::String& value) { m_domainNameHasBeenSet = true; m_domainName = value; }

    /**
     *
 The name of the domain you want to modify. Only include this value if you're
     * querying OpenSearch  Limits  for an existing domain.

     */
    inline void SetDomainName(Aws::String&& value) { m_domainNameHasBeenSet = true; m_domainName = std::move(value); }

    /**
     *
 The name of the domain you want to modify. Only include this value if you're
     * querying OpenSearch  Limits  for an existing domain.

     */
    inline void SetDomainName(const char* value) { m_domainNameHasBeenSet = true; m_domainName.assign(value); }

    /**
     *
 The name of the domain you want to modify. Only include this value if you're
     * querying OpenSearch  Limits  for an existing domain.

     */
    inline DescribeInstanceTypeLimitsRequest& WithDomainName(const Aws::String& value) { SetDomainName(value); return *this;}

    /**
     *
 The name of the domain you want to modify. Only include this value if you're
     * querying OpenSearch  Limits  for an existing domain.

     */
    inline DescribeInstanceTypeLimitsRequest& WithDomainName(Aws::String&& value) { SetDomainName(std::move(value)); return *this;}

    /**
     *
 The name of the domain you want to modify. Only include this value if you're
     * querying OpenSearch  Limits  for an existing domain.

     */
    inline DescribeInstanceTypeLimitsRequest& WithDomainName(const char* value) { SetDomainName(value); return *this;}

    /**
     *
 The instance type for an OpenSearch cluster for which OpenSearch
     * Limits  are needed.

     */
    inline const OpenSearchPartitionInstanceType& GetInstanceType() const{ return m_instanceType; }

    /**
     *
 The instance type for an OpenSearch cluster for which OpenSearch
     * Limits  are needed.

     */
    inline bool InstanceTypeHasBeenSet() const { return m_instanceTypeHasBeenSet; }

    /**
     *
 The instance type for an OpenSearch cluster for which OpenSearch
     * Limits  are needed.

     */
    inline void SetInstanceType(const OpenSearchPartitionInstanceType& value) { m_instanceTypeHasBeenSet = true; m_instanceType = value; }

    /**
     *
 The instance type for an OpenSearch cluster for which OpenSearch
     * Limits  are needed.

     */
    inline void SetInstanceType(OpenSearchPartitionInstanceType&& value) { m_instanceTypeHasBeenSet = true; m_instanceType = std::move(value); }

    /**
     *
 The instance type for an OpenSearch cluster for which OpenSearch
     * Limits  are needed.

     */
    inline DescribeInstanceTypeLimitsRequest& WithInstanceType(const OpenSearchPartitionInstanceType& value) { SetInstanceType(value); return *this;}

    /**
     *
 The instance type for an OpenSearch cluster for which OpenSearch
     * Limits  are needed.

     */
    inline DescribeInstanceTypeLimitsRequest& WithInstanceType(OpenSearchPartitionInstanceType&& value) { SetInstanceType(std::move(value)); return *this;}

    /**
     *
 Version of OpenSearch for which  Limits  are needed.
     *

     */
    inline const Aws::String& GetEngineVersion() const{ return m_engineVersion; }

    /**
     *
 Version of OpenSearch for which  Limits  are needed.
     *

     */
    inline bool EngineVersionHasBeenSet() const { return m_engineVersionHasBeenSet; }

    /**
     *
 Version of OpenSearch for which  Limits  are needed.
     *

     */
    inline void SetEngineVersion(const Aws::String& value) { m_engineVersionHasBeenSet = true; m_engineVersion = value; }

    /**
     *
 Version of OpenSearch for which  Limits  are needed.
     *

     */
    inline void SetEngineVersion(Aws::String&& value) { m_engineVersionHasBeenSet = true; m_engineVersion = std::move(value); }

    /**
     *
 Version of OpenSearch for which  Limits  are needed.
     *

     */
    inline void SetEngineVersion(const char* value) { m_engineVersionHasBeenSet = true; m_engineVersion.assign(value); }

    /**
     *
 Version of OpenSearch for which  Limits  are needed.
     *

     */
    inline DescribeInstanceTypeLimitsRequest& WithEngineVersion(const Aws::String& value) { SetEngineVersion(value); return *this;}

    /**
     *
 Version of OpenSearch for which  Limits  are needed.
     *

     */
    inline DescribeInstanceTypeLimitsRequest& WithEngineVersion(Aws::String&& value) { SetEngineVersion(std::move(value)); return *this;}

    /**
     *
 Version of OpenSearch for which  Limits  are needed.
     *

     */
    inline DescribeInstanceTypeLimitsRequest& WithEngineVersion(const char* value) { SetEngineVersion(value); return *this;}

  private:

    Aws::String m_domainName;
    bool m_domainNameHasBeenSet;

    OpenSearchPartitionInstanceType m_instanceType;
    bool m_instanceTypeHasBeenSet;

    Aws::String m_engineVersion;
    bool m_engineVersionHasBeenSet;
  };

} // namespace Model
} // namespace OpenSearchService
} // namespace Aws


text:
Microsoft is releasing security advisories for .NET Core and ASP.NET Core. Issues addressed by this update are summarized in the [fixes](#fixes) section below. Details can be found in corresponding announcements in the [.NET Core](https://github.com/dotnet/announcements/issues?q=is%3Aopen+is%3Aissue+label%3ASecurity) and [ASP.NET Core](https://github.com/aspnet/announcements/issues?q=is%3Aopen+is%3Aissue+label%3ASecurity) repos.

.NET Core 2.0.5 and SDK 2.1.4 are available for download and usage in your environment.

* [Announcement](https://blogs.msdn.microsoft.com/dotnet/2018/01/09/net-core-january-2018-update/)
* [Getting Started](https://dotnet.microsoft.com/download)
* [Downloads](https://github.com/dotnet/core/blob/main/release-notes/download-archives/2.0.5-download.md)

The .NET Core SDK 2.1.4 includes .NET Core 2.0.5 Runtime so downloading the runtime packages separately is not needed when installing the SDK. After installing the .NET Core SDK 2.1.4, the following command will show that you're running version `2.1.4` of the tools.

`dotnet --version`

Your feedback is important and appreciated. We've created an issue at [dotnet/core #1199](https://github.com/dotnet/core/issues/1199) for your questions and comments.

## Docker Images

The [.NET Core Docker images](https://hub.docker.com/r/microsoft/dotnet/) have been updated for this release. Look for the 2.0.5 images.

## Azure AppServices

Deployment of this update to Azure AppServices is in process. Because AppServices is a high availability service, the deployment is carfully staged across regions over a period of time. Deployment will begin in the West US 2 and North Central US regions with remaining regions following over a few days.

## Known Issues

### Using Linux package managers to update `dotnet-host.x86_64` breaks .NET Core

**Issue:** Running the package manager `update` command on Linux systems where .NET Core has been previously installed may offer an update for `dotnet-host.x86_64`. If the update is allowed to proceed, .NET Core could be in a broken state as only the dotnet host is updated.

**Resolution:** To install the update, either the Runtime or SDK must be explicitly installed. e.g. `sudo [apt-get, yum, dnf, zypper] install dotnet-runtime-2.0.5`, if you only need the runtime or `sudo [apt-get, yum, dnf, zypper] dotnet-sdk-2.1.4`, to install both the SDK and Runtime.

We are working to improve our Linux packages to enable correct package manager update behavior. This work is being tracked in the following issues:

* [dotnet/core-setup/issues/3556](https://github.com/dotnet/core-setup/issues/3556)
* [dotnet/cli/issues/8209](https://github.com/dotnet/cli/issues/8209)

## Package and Binary updates

The following packages and binaries are updated by the January 2018 update:

### System.Private.Corelib.dll

Microsoft.NETCore.App

### System.Private.ServiceModel

* System.ServiceModel.Primitives
* System.ServiceModel.Http
* System.ServiceModel.NetTcp
* System.ServiceModel.Security
* System.ServiceModel.Duplex

### System.Private.Xml.dll

* System.Xml.ReaderWriter
* System.Xml.XmlDocument
* System.Xml.XmlSerializer
* System.Xml.XPath
* System.Xml.XPath.XDocument

## Notable Fixes and Commits

### CVE-2018-0786 - Security Feature Bypass in X509 Certificate Validation

Microsoft is aware of a security vulnerability in the public versions of .NET Core where an attacker could present a certificate that is marked invalid for a specific use, but a component uses it for that purpose. This action disregards the Enhanced Key Usage tagging.

The security update addresses the vulnerability by ensuring that .NET Core components completely validate certificates.

[CVE-2018-0786](https://github.com/dotnet/announcements/issues/51)

### CVE-2018-0764 - Denial of Service when parsing XML documents

Microsoft is aware of a Denial of Service vulnerability in all public versions of .NET core due to improper processing of XML documents. An attacker who successfully exploited this vulnerability could cause a denial of service against a .NET application. A remote unauthenticated attacker could exploit this vulnerability by issuing specially crafted requests to a .NET Core application.

The update addresses the vulnerability by correcting how .NET core handles XML document processing.

[CVE-2018-0764](https://github.com/dotnet/announcements/issues/52)

### Commits

#### CoreFX

* [`[3f1155b]`](https://github.com/dotnet/corefx/commit/3f1155b) Merged PR 94589: Harden hashing in Xml NameTable

#### CoreCLR

* [`[8ce622d]`](https://github.com/dotnet/coreclr/commit/8ce622d) Merged PR 95709: Fix validating RegionInfo names with long string

#### CLI

* [`[1c5b49b]`](https://github.com/dotnet/cli/commit/1c5b49b) 2017-12-04 Nuget.config update to align with CLI:master - add comments in DependencyVersions.prop
* [`[11d9413]`](https://github.com/dotnet/cli/commit/11d9413) 2017-12-04 Updating the websdk version to 2.0.0-rel-20171110-671
* [`[902904c]`](https://github.com/dotnet/cli/commit/902904c) 2017-12-07 Updating the msbuild version for Microsoft.Build.Runtime.
* [`[ed91673]`](https://github.com/dotnet/cli/commit/ed91673) 2017-12-13 Updating the runtime to 2.0.5.
* [`[8c93b6d]`](https://github.com/dotnet/cli/commit/8c93b6d) 2017-12-20 Update to consume aspnetcore 2.0.5-155

#### WCF

* [`[c3182d4]`](https://github.com/dotnet/wcf/commit/c3182d46f45780e52a393aee30ff48e57dbc53ae) 2017-12-13 X509 Certificate Validation fix-up


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="info.hxq.androidrecyclerviewdemo.RecyclerViewList" >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

</RelativeLayout>


text:
local stringy = require "stringy"
local utils = require "kong.tools.utils"
local cache = require "kong.tools.database_cache"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local timestamp = require "kong.tools.timestamp"

local _M = {}

local CONTENT_LENGTH = "content-length"
local RESPONSE_TYPE = "response_type"
local STATE = "state"
local CODE = "code"
local TOKEN = "token"
local REFRESH_TOKEN = "refresh_token"
local SCOPE = "scope"
local CLIENT_ID = "client_id"
local CLIENT_SECRET = "client_secret"
local REDIRECT_URI = "redirect_uri"
local ACCESS_TOKEN = "access_token"
local GRANT_TYPE = "grant_type"
local GRANT_AUTHORIZATION_CODE = "authorization_code"
local GRANT_CLIENT_CREDENTIALS = "client_credentials"
local GRANT_REFRESH_TOKEN = "refresh_token"
local GRANT_PASSWORD = "password"
local ERROR = "error"
local AUTHENTICATED_USERID = "authenticated_userid"

local AUTHORIZE_URL = "^%s/oauth2/authorize(/?(\\?[^\\s]*)?)$"
local TOKEN_URL = "^%s/oauth2/token(/?(\\?[^\\s]*)?)$"

-- TODO: Expire token (using TTL ?)
local function generate_token(conf, credential, authenticated_userid, scope, state, expiration, disable_refresh)
  local token_expiration = expiration or conf.token_expiration

  local token, err = dao.oauth2_tokens:insert({
    credential_id = credential.id,
    authenticated_userid = authenticated_userid,
    expires_in = token_expiration,
    scope = scope
  })

  if err then
    return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
  end

  local refresh_token = token_expiration > 0 and token.refresh_token or nil
  if disable_refresh then
    refresh_token = nil
  end

  return {
    access_token = token.access_token,
    token_type = "bearer",
    expires_in = token_expiration > 0 and token.expires_in or nil,
    refresh_token = refresh_token,
    state = state -- If state is nil, this value won't be added
  }
end

local function get_redirect_uri(client_id)
  local client
  if client_id then
    client = cache.get_or_set(cache.oauth2_credential_key(client_id), function()
      local credentials, err = dao.oauth2_credentials:find_by_keys { client_id = client_id }
      local result
      if err then
        return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
      elseif #credentials > 0 then
        result = credentials[1]
      end
      return result
    end)
  end
  return client and client.redirect_uri or nil, client
end

local HTTPS = "https"

local function is_https(conf)
  local result = ngx.var.scheme:lower() == HTTPS
  if not result and conf.accept_http_if_already_terminated then
    local forwarded_proto_header = ngx.req.get_headers()["x-forwarded-proto"]
    result = forwarded_proto_header and forwarded_proto_header:lower() == HTTPS
  end
  return result
end

local function retrieve_parameters()
  ngx.req.read_body()
  -- OAuth2 parameters could be in both the querystring or body
  return utils.table_merge(ngx.req.get_uri_args(), ngx.req.get_post_args())
end

local function retrieve_scopes(parameters, conf)
  local scope = parameters[SCOPE]
  local scopes = {}
  if conf.scopes and scope then
    for v in scope:gmatch("%S+") do
      if not utils.table_contains(conf.scopes, v) then
        return false, {[ERROR] = "invalid_scope", error_description = "\""..v.."\" is an invalid "..SCOPE}
      else
        table.insert(scopes, v)
      end
    end
  elseif not scope and conf.mandatory_scope then
    return false, {[ERROR] = "invalid_scope", error_description = "You must specify a "..SCOPE}
  end

  return true, scopes
end

local function authorize(conf)
  local response_params = {}

  local parameters = retrieve_parameters()
  local state = parameters[STATE]
  local redirect_uri, client

  if not is_https(conf) then
    response_params = {[ERROR] = "access_denied", error_description = "You must use HTTPS"}
  else
    if conf.provision_key ~= parameters.provision_key then
      response_params = {[ERROR] = "invalid_provision_key", error_description = "Invalid Kong provision_key"}
    elseif not parameters.authenticated_userid or stringy.strip(parameters.authenticated_userid) == "" then
      response_params = {[ERROR] = "invalid_authenticated_userid", error_description = "Missing authenticated_userid parameter"}
    else
      local response_type = parameters[RESPONSE_TYPE]
      -- Check response_type
      if not ((response_type == CODE and conf.enable_authorization_code) or (conf.enable_implicit_grant and response_type == TOKEN)) then -- Authorization Code Grant (http://tools.ietf.org/html/rfc6749#section-4.1.1)
        response_params = {[ERROR] = "unsupported_response_type", error_description = "Invalid "..RESPONSE_TYPE}
      end

      -- Check scopes
      local ok, scopes = retrieve_scopes(parameters, conf)
      if not ok then
        response_params = scopes -- If it's not ok, then this is the error message
      end

      -- Check client_id and redirect_uri
      redirect_uri, client = get_redirect_uri(parameters[CLIENT_ID])
      if not redirect_uri then
        response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..CLIENT_ID}
      elseif parameters[REDIRECT_URI] and parameters[REDIRECT_URI] ~= redirect_uri then
        response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..REDIRECT_URI.." that does not match with the one created with the application"}
      end

      -- If there are no errors, keep processing the request
      if not response_params[ERROR] then
        if response_type == CODE then
          local authorization_code, err = dao.oauth2_authorization_codes:insert({
            authenticated_userid = parameters[AUTHENTICATED_USERID],
            scope = table.concat(scopes, " ")
          })

          if err then
            return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
          end

          response_params = {
            code = authorization_code.code,
          }
        else
          -- Implicit grant, override expiration to zero
          response_params = generate_token(conf, client, parameters[AUTHENTICATED_USERID],  table.concat(scopes, " "), state, 0)
        end
      end
    end
  end

  -- Adding the state if it exists. If the state == nil then it won't be added
  response_params.state = state

  -- Sending response in JSON format
  return responses.send(response_params[ERROR] and 400 or 200, redirect_uri and {
    redirect_uri = redirect_uri.."?"..ngx.encode_args(response_params)
  } or response_params, false, {
    ["cache-control"] = "no-store",
    ["pragma"] = "no-cache"
  })
end

local function retrieve_client_credentials(parameters)
  local client_id, client_secret
  local authorization_header = ngx.req.get_headers()["authorization"]
  if parameters[CLIENT_ID] then
    client_id = parameters[CLIENT_ID]
    client_secret = parameters[CLIENT_SECRET]
  elseif authorization_header then
    local iterator, iter_err = ngx.re.gmatch(authorization_header, "\\s*[Bb]asic\\s*(.+)")
    if not iterator then
      ngx.log(ngx.ERR, iter_err)
      return
    end

    local m, err = iterator()
    if err then
      ngx.log(ngx.ERR, err)
      return
    end

    if m and table.getn(m) > 0 then
      local decoded_basic = ngx.decode_base64(m[1])
      if decoded_basic then
        local basic_parts = stringy.split(decoded_basic, ":")
        client_id = basic_parts[1]
        client_secret = basic_parts[2]
      end
    end
  end

  return client_id, client_secret
end

local function issue_token(conf)
  local response_params = {}

  local parameters = retrieve_parameters() --TODO: Also from authorization header
  local state = parameters[STATE]

  if not is_https(conf) then
    response_params = {[ERROR] = "access_denied", error_description = "You must use HTTPS"}
  else
    local grant_type = parameters[GRANT_TYPE]
    if not (grant_type == GRANT_AUTHORIZATION_CODE or
            grant_type == GRANT_REFRESH_TOKEN or
            (conf.enable_client_credentials and grant_type == GRANT_CLIENT_CREDENTIALS) or
            (conf.enable_password_grant and grant_type == GRANT_PASSWORD)) then
      response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..GRANT_TYPE}
    end

    local client_id, client_secret = retrieve_client_credentials(parameters)

    -- Check client_id and redirect_uri
    local redirect_uri, client = get_redirect_uri(client_id)
    if not redirect_uri then
      response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..CLIENT_ID}
    elseif parameters[REDIRECT_URI] and parameters[REDIRECT_URI] ~= redirect_uri then
      response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..REDIRECT_URI.." that does not match with the one created with the application"}
    end

    if client and client.client_secret ~= client_secret then
      response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..CLIENT_SECRET}
    end

    if not response_params[ERROR] then
      if grant_type == GRANT_AUTHORIZATION_CODE then
        local code = parameters[CODE]
        local authorization_code = code and dao.oauth2_authorization_codes:find_by_keys({code = code})[1] or nil
        if not authorization_code then
          response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..CODE}
        else
          response_params = generate_token(conf, client, authorization_code.authenticated_userid, authorization_code.scope, state)
        end
      elseif grant_type == GRANT_CLIENT_CREDENTIALS then
        -- Only check the provision_key if the authenticated_userid is being set
        if parameters.authenticated_userid and conf.provision_key ~= parameters.provision_key then
          response_params = {[ERROR] = "invalid_provision_key", error_description = "Invalid Kong provision_key"}
        else
          -- Check scopes
          local ok, scopes = retrieve_scopes(parameters, conf)
          if not ok then
            response_params = scopes -- If it's not ok, then this is the error message
          else
            response_params = generate_token(conf, client, parameters.authenticated_userid, table.concat(scopes, " "), state, conf.token_expiration, true)
          end
        end
      elseif grant_type == GRANT_PASSWORD then
        -- Check that it comes from the right client
        if conf.provision_key ~= parameters.provision_key then
          response_params = {[ERROR] = "invalid_provision_key", error_description = "Invalid Kong provision_key"}
        elseif not parameters.authenticated_userid or stringy.strip(parameters.authenticated_userid) == "" then
          response_params = {[ERROR] = "invalid_authenticated_userid", error_description = "Missing authenticated_userid parameter"}
        else
          -- Check scopes
          local ok, scopes = retrieve_scopes(parameters, conf)
          if not ok then
            response_params = scopes -- If it's not ok, then this is the error message
          else
            response_params = generate_token(conf, client, parameters.authenticated_userid, table.concat(scopes, " "), state)
          end
        end
      elseif grant_type == GRANT_REFRESH_TOKEN then
        local refresh_token = parameters[REFRESH_TOKEN]
        local token = refresh_token and dao.oauth2_tokens:find_by_keys({refresh_token = refresh_token})[1] or nil
        if not token then
          response_params = {[ERROR] = "invalid_request", error_description = "Invalid "..REFRESH_TOKEN}
        else
          response_params = generate_token(conf, client, token.authenticated_userid, token.scope, state)
          dao.oauth2_tokens:delete({id=token.id}) -- Delete old token
        end
      end
    end
  end

  -- Adding the state if it exists. If the state == nil then it won't be added
  response_params.state = state

  -- Sending response in JSON format
  return responses.send(response_params[ERROR] and 400 or 200, response_params, false, {
    ["cache-control"] = "no-store",
    ["pragma"] = "no-cache"
  })
end

local function retrieve_token(access_token)
  local token
  if access_token then
    token = cache.get_or_set(cache.oauth2_token_key(access_token), function()
      local credentials, err = dao.oauth2_tokens:find_by_keys { access_token = access_token }
      local result
      if err then
        return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
      elseif #credentials > 0 then
        result = credentials[1]
      end
      return result
    end)
  end
  return token
end

local function parse_access_token(conf)
  local found_in = {}
  local result = retrieve_parameters()["access_token"]
  if not result then
    local authorization = ngx.req.get_headers()["authorization"]
    if authorization then
      local parts = {}
      for v in authorization:gmatch("%S+") do -- Split by space
        table.insert(parts, v)
      end
      if #parts == 2 and (parts[1]:lower() == "token" or parts[1]:lower() == "bearer") then
        result = parts[2]
        found_in.authorization_header = true
      end
    end
  end

  if conf.hide_credentials then
    if found_in.authorization_header then
      ngx.req.clear_header("authorization")
    else
      -- Remove from querystring
      local parameters = ngx.req.get_uri_args()
      parameters[ACCESS_TOKEN] = nil
      ngx.req.set_uri_args(parameters)

      if ngx.req.get_method() ~= "GET" then -- Remove from body
        ngx.req.read_body()
        parameters = ngx.req.get_post_args()
        parameters[ACCESS_TOKEN] = nil
        local encoded_args = ngx.encode_args(parameters)
        ngx.req.set_header(CONTENT_LENGTH, string.len(encoded_args))
        ngx.req.set_body_data(encoded_args)
      end
    end
  end

  return result
end

function _M.execute(conf)
  -- Check if the API has a request_path and if it's being invoked with the path resolver
  local path_prefix = (ngx.ctx.api.request_path and stringy.startswith(ngx.var.request_uri, ngx.ctx.api.request_path)) and ngx.ctx.api.request_path or ""
  if stringy.endswith(path_prefix, "/") then
    path_prefix = path_prefix:sub(1, path_prefix:len() - 1)
  end

  if ngx.req.get_method() == "POST" then
    if ngx.re.match(ngx.var.request_uri, string.format(AUTHORIZE_URL, path_prefix)) then
      authorize(conf)
    elseif ngx.re.match(ngx.var.request_uri, string.format(TOKEN_URL, path_prefix)) then
      issue_token(conf)
    end
  end

  local accessToken = parse_access_token(conf);
  if not accessToken then
    return responses.send_HTTP_UNAUTHORIZED({}, false, {["WWW-Authenticate"] = 'Bearer realm="service"'})
  end

  local token = retrieve_token(accessToken)
  if not token then
    return responses.send_HTTP_UNAUTHORIZED({[ERROR] = "invalid_token", error_description = "The access token is invalid"}, false, {["WWW-Authenticate"] = 'Bearer realm="service" error="invalid_token" error_description="The access token is invalid"'})
  end

  -- Check expiration date
  if token.expires_in > 0 then -- zero means the token never expires
    local now = timestamp.get_utc()
    if now - token.created_at > (token.expires_in * 1000) then
      return responses.send_HTTP_UNAUTHORIZED({[ERROR] = "invalid_token", error_description = "The access token expired"}, false, {["WWW-Authenticate"] = 'Bearer realm="service" error="invalid_token" error_description="The access token expired"'})
    end
  end

  -- Retrive the credential from the token
  local credential = cache.get_or_set(cache.oauth2_credential_key(token.credential_id), function()
    local result, err = dao.oauth2_credentials:find_by_primary_key({id = token.credential_id})
    if err then
      return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
    end
    return result
  end)

  -- Retrive the consumer from the credential
  local consumer = cache.get_or_set(cache.consumer_key(credential.consumer_id), function()
    local result, err = dao.consumers:find_by_primary_key({id = credential.consumer_id})
    if err then
      return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
    end
    return result
  end)

  ngx.req.set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
  ngx.req.set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
  ngx.req.set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
  ngx.req.set_header("x-authenticated-scope", token.scope)
  ngx.req.set_header("x-authenticated-userid", token.authenticated_userid)
  ngx.ctx.authenticated_credential = credential
end

return _M


text:
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_timm_available, is_vision_available

_import_structure = {
    "configuration_conditional_detr": [
        "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "ConditionalDetrConfig",
        "ConditionalDetrOnnxConfig",
    ]
}

try:
    if not is_vision_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _import_structure["feature_extraction_conditional_detr"] = ["ConditionalDetrFeatureExtractor"]

try:
    if not is_timm_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _import_structure["modeling_conditional_detr"] = [
        "CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST",
        "ConditionalDetrForObjectDetection",
        "ConditionalDetrForSegmentation",
        "ConditionalDetrModel",
        "ConditionalDetrPreTrainedModel",
    ]

if TYPE_CHECKING:
    from .configuration_conditional_detr import (
        CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP,
        ConditionalDetrConfig,
        ConditionalDetrOnnxConfig,
    )

    try:
        if not is_vision_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor

    try:
        if not is_timm_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_conditional_detr import (
            CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST,
            ConditionalDetrForObjectDetection,
            ConditionalDetrForSegmentation,
            ConditionalDetrModel,
            ConditionalDetrPreTrainedModel,
        )

else:
    import sys

    sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)


text:
#import "CatalyzeQuery.h"

@implementation CatalyzeQuery
@synthesize catalyzeClassName = _catalyzeClassName;
@synthesize pageNumber = _pageNumber;
@synthesize pageSize = _pageSize;
@synthesize queryValue = _queryValue;
@synthesize queryField = _queryField;

+ (CatalyzeQuery *)queryWithClassName:(NSString *)className {
    return [[CatalyzeQuery alloc] initWithClassName:className];
}

- (id)initWithClassName:(NSString *)newClassName {
    self = [super init];
    if (self) {
        _catalyzeClassName = newClassName;
    }
    return self;
}

- (id)init {
    self = [self initWithClassName:@"object"];
    return self;
}

- (void)setValue:(id)value forKey:(NSString *)key {
    @try {
        [super setValue:value forKey:key];
    } @catch (NSException *e) {}
}

#pragma mark -
#pragma mark Retrieve

- (void)retrieveAllEntriesInBackgroundWithSuccess:(CatalyzeArraySuccessBlock)success failure:(CatalyzeFailureBlock)failure {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@(_pageSize) forKey:@"pageSize"];
    [params setValue:@(_pageNumber) forKey:@"pageNumber"];
    [params addEntriesFromDictionary:[self constructQueryFieldParam]];
    [params addEntriesFromDictionary:[self constructQueryValueParam]];
    [CatalyzeHTTPManager doGet:[NSString stringWithFormat:@"/classes/%@/query",[CatalyzeHTTPManager percentEncode:[self catalyzeClassName]]] withParams:params success:^(id result) {
        if (success) {
            NSArray *array = (NSArray *)result;
            NSMutableArray *entries = [NSMutableArray array];
            for (id dict in array) {
                CatalyzeEntry *entry = [CatalyzeEntry entryWithClassName:_catalyzeClassName];
                [entry setValuesForKeysWithDictionary:dict];
                entry.content = [NSMutableDictionary dictionaryWithDictionary:entry.content]; // to keep mutability
                [entries addObject:entry];
            }
            success(entries);
        }
    } failure:failure];
}

- (void)retrieveAllEntriesInBackgroundWithTarget:(id)target selector:(SEL)selector {
    [self retrieveAllEntriesInBackgroundWithSuccess:^(NSArray *result) {
        [target performSelector:selector onThread:[NSThread mainThread] withObject:result waitUntilDone:NO];
    } failure:^(NSDictionary *result, int status, NSError *error) {
        [target performSelector:selector onThread:[NSThread mainThread] withObject:result waitUntilDone:NO];
    }];
}

- (void)retrieveInBackgroundWithSuccess:(CatalyzeArraySuccessBlock)success failure:(CatalyzeFailureBlock)failure {
    [self retrieveInBackgroundForUsersId:[[CatalyzeUser currentUser] usersId] success:success failure:failure];
}

- (void)retrieveInBackgroundWithTarget:(id)target selector:(SEL)selector {
    [self retrieveInBackgroundWithSuccess:^(NSArray *result) {
        [target performSelector:selector onThread:[NSThread mainThread] withObject:result waitUntilDone:NO];
    } failure:^(NSDictionary *result, int status, NSError *error) {
        [target performSelector:selector onThread:[NSThread mainThread] withObject:result waitUntilDone:NO];
    }];
}

- (void)retrieveInBackgroundForUsersId:(NSString *)usersId success:(CatalyzeArraySuccessBlock)success failure:(CatalyzeFailureBlock)failure {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@(_pageSize) forKey:@"pageSize"];
    [params setValue:@(_pageNumber) forKey:@"pageNumber"];
    [params addEntriesFromDictionary:[self constructQueryFieldParam]];
    [params addEntriesFromDictionary:[self constructQueryValueParam]];
    [CatalyzeHTTPManager doGet:[NSString stringWithFormat:@"/classes/%@/query/%@",[CatalyzeHTTPManager percentEncode:[self catalyzeClassName]], usersId] withParams:params success:^(id result) {
        if (success) {
            NSArray *array = (NSArray *)result;
            NSMutableArray *entries = [NSMutableArray array];
            for (id dict in array) {
                CatalyzeEntry *entry = [CatalyzeEntry entryWithClassName:_catalyzeClassName];
                [entry setValuesForKeysWithDictionary:dict];
                entry.content = [NSMutableDictionary dictionaryWithDictionary:entry.content]; // to keep mutability
                [entries addObject:entry];
            }
            success(entries);
        }
    } failure:failure];
}

- (void)retrieveInBackgroundForUsersId:(NSString *)usersId target:(id)target selector:(SEL)selector {
    [self retrieveInBackgroundForUsersId:usersId success:^(NSArray *result) {
        [target performSelector:selector onThread:[NSThread mainThread] withObject:result waitUntilDone:NO];
    } failure:^(NSDictionary *result, int status, NSError *error) {
        [target performSelector:selector onThread:[NSThread mainThread] withObject:result waitUntilDone:NO];
    }];
}

#pragma mark -
#pragma mark Helpers

- (NSDictionary *)constructQueryFieldParam {
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    if (_queryField) {
        if (![_queryField isKindOfClass:[NSString class]] || ([_queryField isKindOfClass:[NSString class]] && ![_queryField isEqualToString:@""])) {
            [dictionary setValue:[CatalyzeHTTPManager percentEncode:_queryField] forKey:@"field"];
        }
    }
    return dictionary;
}

- (NSDictionary *)constructQueryValueParam {
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    if (_queryValue) {
        if (![_queryValue isKindOfClass:[NSString class]] || ([_queryValue isKindOfClass:[NSString class]] && ![_queryValue isEqualToString:@""])) {
            [dictionary setValue:[CatalyzeHTTPManager percentEncode:_queryValue] forKey:@"searchBy"];
        }
    }
    return dictionary;
}

@end


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Typedef Index</title>
<link rel="stylesheet" href="../../multiprecision.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Multiprecision">
<link rel="up" href="../indexes.html" title="Indexes">
<link rel="prev" href="s02.html" title="Class Index">
<link rel="next" href="s04.html" title="Index">

Home
Libraries
People
FAQ
More

Typedef Index

Copyright © 2002-2020 John
      Maddock and Christopher Kormanyos

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
'use strict';

const _ = require('lodash');
const ScrollableList = require('nodeca.core/lib/app/scrollable_list');

// Page state
//
// - hid:              current section hid
// - current_offset:   offset of the current topic (first in the viewport)
// - topic_count:      total amount of topics
// - selected_topics:  array of selected topics in current topic
// - mark_cut_ts:      date when topic list was last fetched (required for mark all read)
//
let pageState = {};
let scrollable_list;

let $window = $(window);

function load(start, direction) {
  return N.io.rpc('forum.section.list.by_range', {
    section_hid:  pageState.hid,
    last_post_id: start,
    before:       direction === 'top' ? N.runtime.page_data.pagination.per_page : 0,
    after:        direction === 'bottom' ? N.runtime.page_data.pagination.per_page : 0
  }).then(res => {
    pageState.mark_cut_ts = res.mark_cut_ts;
    pageState.topic_count = res.pagination.total;

    return N.wire.emit('common.blocks.navbar.blocks.page_progress:update', {
      max: pageState.topic_count
    }).then(() => {
      // data needed to display separator on the border between pages
      if (direction === 'top')    res.next_last_ts = $('.forum-topicline:first').data('last-ts');
      if (direction === 'bottom') res.prev_last_ts = $('.forum-topicline:last').data('last-ts');

      let $html = $(N.runtime.render('forum.blocks.topics_list', res));

      // if separator already exists, leave its position as is
      if ($('.forum-topiclist__separator').length) $html = $html.not('.forum-topiclist__separator');

      return {
        $html,
        locals: res,
        offset: res.pagination.chunk_offset,
        reached_end: res.topics.length !== N.runtime.page_data.pagination.per_page
      };
    });
  }).catch(err => {
    // User deleted, refreshing the page so user can see the error
    if (err.code === N.io.NOT_FOUND) return N.wire.emit('navigate.reload');
    throw err;
  });
}

let update_url;

function on_list_scroll(item, index, item_offset) {
  // Use a separate debouncer that only fires when user stops scrolling,
  // so it's executed a lot less frequently.
  //
  // The reason is that `history.replaceState` is very slow in FF
  // on large pages: https://bugzilla.mozilla.org/show_bug.cgi?id=1250972
  //
  update_url = update_url || _.debounce((item, index, item_offset) => {
    let href, state;

    if (item) {
      state = {
        hid:    $(item).data('topic-hid'),
        offset: item_offset
      };
    }

    // save current offset, and only update url if offset is different,
    // it protects url like /f1/topic23/page4 from being overwritten instantly
    if (pageState.current_offset !== index) {
      /* eslint-disable no-undefined */
      href = N.router.linkTo('forum.section', {
        section_hid: pageState.hid,
        topic_hid:   item ? $(item).data('topic-hid') : undefined
      });

      if ((pageState.current_offset >= 0) !== (index >= 0)) {
        $('meta[name="robots"]').remove();

        if (index >= 0) {
          $('head').append($('<meta name="robots" content="noindex,follow">'));
        }
      }

      pageState.current_offset = index;
    }

    N.wire.emit('navigate.replace', { href, state })
          .catch(err => N.wire.emit('error', err));
  }, 500);

  N.wire.emit('common.blocks.navbar.blocks.page_progress:update', {
    current: index + 1 // `+1` because offset is zero based
  }).catch(err => N.wire.emit('error', err));

  update_url(item, index, item_offset);
}

/////////////////////////////////////////////////////////////////////
// init on page load
//
N.wire.on('navigate.done:' + module.apiPath, function page_setup(data) {
  let pagination     = N.runtime.page_data.pagination,
      last_topic_hid = $('.forum-section-root').data('last-topic-hid');

  pageState.hid             = data.params.section_hid;
  pageState.current_offset  = -1;
  pageState.topic_count     = pagination.total;
  pageState.selected_topics = [];
  pageState.mark_cut_ts     = N.runtime.page_data.mark_cut_ts;

  let navbar_height = parseInt($('body').css('margin-top'), 10) + parseInt($('body').css('padding-top'), 10);

  // account for some spacing between posts
  navbar_height += 32;

  let scroll_done = false;

  // If user returns from a topic page back to section, highlight a linked topic
  //
  // TODO: check if we can parse anchor more gently
  //
  let anchor = data.anchor || '';
  let el;

  if (!scroll_done && anchor.match(/^#cat\d+$/)) {
    el = $(anchor);

    if (el.length && el.hasClass('forum-section')) {
      $window.scrollTop(el.offset().top - navbar_height);
      el.addClass('forum-section__m-highlight');
      scroll_done = true;
    }
  }

  if (!scroll_done && data.state && typeof data.state.hid !== 'undefined' && typeof data.state.offset !== 'undefined') {
    el = $('#topic' + data.state.hid);

    if (el.length) {
      $window.scrollTop(el.offset().top - navbar_height + data.state.offset);
      scroll_done = true;
    }
  }

  if (!scroll_done && data.params.topic_hid) {
    el = $('#topic' + data.params.topic_hid);

    if (el.length) {
      $window.scrollTop(el.offset().top - navbar_height);
      el.addClass('forum-topicline__m-highlight');
      scroll_done = true;
    }
  }

  // If we're on the first page, scroll to the top;
  // otherwise, scroll to the first topic on that page
  //
  if (!scroll_done) {
    if (pagination.chunk_offset > 1 && $('.forum-topiclist').length) {
      $window.scrollTop($('.forum-topiclist').offset().top - navbar_height);

    } else {
      $window.scrollTop(0);
    }

    scroll_done = true;
  }

  // disable automatic scroll to an anchor in the navigator
  data.no_scroll = true;

  scrollable_list = new ScrollableList({
    N,
    list_selector:               '.forum-topiclist',
    item_selector:               '.forum-topicline',
    placeholder_top_selector:    '.forum-section__loading-prev',
    placeholder_bottom_selector: '.forum-section__loading-next',
    get_content_id:              topic => $(topic).data('last-post'),
    load,
    reached_top:                 pagination.chunk_offset === 0,
    reached_bottom:              last_topic_hid === $('.forum-topicline:last').data('topic-hid'),
    index_offset:                pagination.chunk_offset,
    navbar_height,
    // whenever there are more than 600 topics, cut off-screen topics down to 400
    need_gc:                     count => (count > 600 ? count - 400 : 0),
    on_list_scroll
  });
});

N.wire.on('navigate.exit:' + module.apiPath, function page_teardown() {
  scrollable_list.destroy();
  scrollable_list = null;

  if (update_url) update_url.cancel();

  pageState = {};
});

/////////////////////////////////////////////////////////////////////
// Update section state
//
function updateSectionState() {
  // Need to re-render reply button and dropdown here
  let templateParams = {
    section:      N.runtime.page_data.section,
    settings:     N.runtime.page_data.settings,
    subscription: N.runtime.page_data.subscription,
    selected_cnt: pageState.selected_topics.length
  };

  // render dropdown in menu
  $('.page-actions__dropdown').replaceWith(
    N.runtime.render(module.apiPath + '.blocks.page_actions.dropdown', templateParams));

  // render buttons+dropdown in page head
  $('.page-actions').replaceWith(
    N.runtime.render(module.apiPath + '.blocks.page_actions', templateParams));
}

N.wire.once('navigate.done:' + module.apiPath, function page_once() {

  // Section subscription handler
  //
  N.wire.on(module.apiPath + ':subscription', function section_subscription(data) {
    let hid = data.$this.data('section-hid');
    let params = { subscription: data.$this.data('section-subscription') };

    return Promise.resolve()
      .then(() => N.wire.emit('forum.section.subscription', params))
      .then(() => N.io.rpc('forum.section.change_subscription', { section_hid: hid, type: params.subscription }))
      .then(() => {
        N.runtime.page_data.subscription = params.subscription;
      })
      .then(updateSectionState);
  });

  // Show list of section moderators
  //
  N.wire.on(module.apiPath + ':show_moderators', function show_moderators(data) {
    let hid = data.$this.data('section-hid');

    return Promise.resolve()
      .then(() => N.io.rpc('forum.section.show_moderators', { section_hid: hid }))
      .then(res => N.wire.emit('forum.section.moderator_info_dlg', res));
  });

  // Click topic create
  //
  N.wire.on(module.apiPath + ':create', function reply(data) {
    return N.wire.emit('forum.topic.create:begin', {
      section_hid: data.$this.data('section-hid'),
      section_title: data.$this.data('section-title')
    });
  });

  // Click mark all read
  //
  N.wire.on(module.apiPath + ':mark_read', function reply(data) {
    return N.io.rpc('forum.section.mark_read', {
      hid: data.$this.data('section-hid'),
      ts: pageState.mark_cut_ts
    })
      .then(() => {
        $('.forum-topicline.forum-topicline__m-new, .forum-topicline.forum-topicline__m-unread')
          .removeClass('forum-topicline__m-new')
          .removeClass('forum-topicline__m-unread');
        $('.forum-section.forum-section__m-unread').removeClass('forum-section__m-unread');
        $('.forum-topiclist__separator').remove();
      });
  });

  // User presses "home" button
  //
  N.wire.on(module.apiPath + ':nav_to_start', function navigate_to_start() {
    // if the first topic is already loaded, scroll to the top
    if (scrollable_list.reached_top) {
      $window.scrollTop(0);
      return;
    }

    return N.wire.emit('navigate.to', {
      apiPath: 'forum.section',
      params: {
        section_hid: pageState.hid
      }
    });
  });

  // User presses "end" button
  //
  N.wire.on(module.apiPath + ':nav_to_end', function navigate_to_end() {
    if (scrollable_list.reached_bottom) {
      $window.scrollTop($(document).height());
      return;
    }

    return N.wire.emit('navigate.to', {
      apiPath: 'forum.section',
      params: {
        section_hid: pageState.hid,
        topic_hid:   $('.forum-section-root').data('last-topic-hid')
      }
    });
  });
});

///////////////////////////////////////////////////////////////////////////////
// Many topics selection
//

const bkv = require('bkv').shared();
let selected_topics_key;
// Flag shift key pressed
let shift_key_pressed = false;
// DOM element of first selected post (for many check)
let $many_select_start;

// Handle shift keyup event
//
function key_up(event) {
  // If shift still pressed
  if (event.shiftKey) return;

  shift_key_pressed = false;
}

// Handle shift keydown event
//
function key_down(event) {
  if (event.shiftKey) {
    shift_key_pressed = true;
  }
}

// Save selected topics + debounced
//
function save_selected_topics_immediate() {
  if (pageState.selected_topics.length) {
    // Expire after 1 day
    bkv.set(selected_topics_key, pageState.selected_topics, 60 * 60 * 24);
  } else {
    bkv.remove(selected_topics_key);
  }
}
const save_selected_topics = _.debounce(save_selected_topics_immediate, 500);

function update_selection_state(container) {
  pageState.selected_topics.forEach(topicHid => {
    container.find(`#topic${topicHid}`).addBack(`#topic${topicHid}`)
      .addClass('forum-topicline__m-selected')
      .find('.forum-topicline__select-cb')
      .prop('checked', true);
  });
}

N.wire.on('navigate.content_update', function update_selected_topics(data) {
  if (!pageState.hid) return; // not on section page

  $('.forum-section-root').toggleClass('forum-section-root__m-first-page', scrollable_list.reached_top);
  update_selection_state(data.$);
});

// Load previously selected topics
//
N.wire.on('navigate.done:' + module.apiPath, function section_load_previously_selected_topics() {
  selected_topics_key = `section_selected_topics_${N.runtime.user_hid}_${pageState.hid}`;

  $(document)
    .on('keyup', key_up)
    .on('keydown', key_down);

  // Don't need wait here
  bkv.get(selected_topics_key, [])
    .then(hids => {
      pageState.selected_topics = hids;
      update_selection_state($(document));

      return hids.length ? updateSectionState() : null;
    });
});

// Init handlers
//
N.wire.once('navigate.done:' + module.apiPath, function section_topics_selection_init() {

  // Update array of selected topics on selection change
  //
  N.wire.on(module.apiPath + ':topic_check', function section_topic_select(data) {
    let topicHid = data.$this.data('topic-hid');

    if (data.$this.is(':checked') && pageState.selected_topics.indexOf(topicHid) === -1) {
      // Select
      //
      if ($many_select_start) {

        // If many select started
        //
        let $topic = data.$this.closest('.forum-topicline');
        let $start = $many_select_start;
        let topicsBetween;

        $many_select_start = null;

        // If current after `$many_select_start`
        if ($start.index() < $topic.index()) {
          // Get topics between start and current
          topicsBetween = $start.nextUntil($topic, '.forum-topicline');
        } else {
          // Between current and start (in reverse order)
          topicsBetween = $topic.nextUntil($start, '.forum-topicline');
        }

        topicsBetween.each(function () {
          let hid = $(this).data('topic-hid');

          if (pageState.selected_topics.indexOf(hid) === -1) {
            pageState.selected_topics.push(hid);
          }

          $(this)
            .addClass('forum-topicline__m-selected')
            .find('.forum-topicline__select-cb').prop('checked', true);
        });

        pageState.selected_topics.push(topicHid);
        $topic.addClass('forum-topicline__m-selected');

      } else if (shift_key_pressed) {
        // If many select not started and shift key pressed
        //
        let $topic = data.$this.closest('.forum-topicline');

        $many_select_start = $topic;
        $topic.addClass('forum-topicline__m-selected');
        pageState.selected_topics.push(topicHid);

        N.wire.emit('notify.info', t('msg_multiselect'));

      } else {
        // No many select
        //
        data.$this.closest('.forum-topicline').addClass('forum-topicline__m-selected');
        pageState.selected_topics.push(topicHid);
      }

    } else if (!data.$this.is(':checked') && pageState.selected_topics.indexOf(topicHid) !== -1) {
      // Unselect
      //
      data.$this.closest('.forum-topicline').removeClass('forum-topicline__m-selected');
      pageState.selected_topics = pageState.selected_topics.filter(x => x !== topicHid);
    }

    save_selected_topics();
    return updateSectionState();
  });

  // Unselect all topics
  //
  N.wire.on(module.apiPath + ':topics_unselect', function section_topic_unselect() {
    pageState.selected_topics = [];

    $('.forum-topicline__select-cb:checked').each(function () {
      $(this)
        .prop('checked', false)
        .closest('.forum-topicline')
        .removeClass('forum-topicline__m-selected');
    });

    save_selected_topics();
    return updateSectionState();
  });

  // Delete topics
  //
  N.wire.on(module.apiPath + ':delete_many', function section_topic_delete_many() {
    let params = {
      canDeleteHard: N.runtime.page_data.settings.forum_mod_can_hard_delete_topics
    };

    return Promise.resolve()
      .then(() => N.wire.emit('forum.section.topic_delete_many_dlg', params))
      .then(() => {
        let request = {
          section_hid: pageState.hid,
          topics_hids: pageState.selected_topics,
          method: params.method
        };

        if (params.reason) request.reason = params.reason;

        return N.io.rpc('forum.section.topic.destroy_many', request);
      })
      .then(() => {
        pageState.selected_topics = [];
        save_selected_topics_immediate();

        return N.wire.emit('notify.info', t('many_topics_deleted'));
      })
      .then(() => N.wire.emit('navigate.reload'));
  });

  // Undelete topics
  //
  N.wire.on(module.apiPath + ':undelete_many', function section_topic_undelete_many() {
    let request = {
      section_hid: pageState.hid,
      topics_hids: pageState.selected_topics
    };

    return Promise.resolve()
      .then(() => N.wire.emit('common.blocks.confirm', t('many_undelete_confirm')))
      .then(() => N.io.rpc('forum.section.topic.undelete_many', request))
      .then(() => {
        pageState.selected_topics = [];
        save_selected_topics_immediate();
      })
      .then(() => N.wire.emit('notify.info', t('many_topics_undeleted')))
      .then(() => N.wire.emit('navigate.reload'));
  });

  // Close topics
  //
  N.wire.on(module.apiPath + ':close_many', function section_topic_close_many() {
    let request = {
      section_hid: pageState.hid,
      topics_hids: pageState.selected_topics
    };

    return Promise.resolve()
      .then(() => N.wire.emit('common.blocks.confirm', t('many_close_confirm')))
      .then(() => N.io.rpc('forum.section.topic.close_many', request))
      .then(() => {
        pageState.selected_topics = [];
        save_selected_topics_immediate();
      })
      .then(() => N.wire.emit('notify.info', t('many_topics_closed')))
      .then(() => N.wire.emit('navigate.reload'));
  });

  // Open topics
  //
  N.wire.on(module.apiPath + ':open_many', function section_topic_open_many() {
    let request = {
      section_hid: pageState.hid,
      topics_hids: pageState.selected_topics
    };

    return Promise.resolve()
      .then(() => N.wire.emit('common.blocks.confirm', t('many_open_confirm')))
      .then(() => N.io.rpc('forum.section.topic.open_many', request))
      .then(() => {
        pageState.selected_topics = [];
        save_selected_topics_immediate();
      })
      .then(() => N.wire.emit('notify.info', t('many_topics_opened')))
      .then(() => N.wire.emit('navigate.reload'));
  });

  // Move topics
  //
  N.wire.on(module.apiPath + ':move_many', function section_topic_move_many() {
    let params = {
      section_hid_from: pageState.hid
    };

    return Promise.resolve()
      .then(() => N.wire.emit('forum.section.topic_move_many_dlg', params))
      .then(() => {
        let request = {
          section_hid_from: params.section_hid_from,
          section_hid_to: params.section_hid_to,
          topics_hids: pageState.selected_topics
        };

        return N.io.rpc('forum.section.topic.move_many', request);
      })
      .then(() => {
        pageState.selected_topics = [];
        save_selected_topics_immediate();
      })
      .then(() => N.wire.emit('notify.info', t('many_topics_moved')))
      .then(() => N.wire.emit('navigate.reload'));
  });
});

// Teardown many topics selection
//
N.wire.on('navigate.exit:' + module.apiPath, function section_topic_selection_teardown() {
  $(document)
    .off('keyup', key_up)
    .off('keydown', key_down);
});


text:
#ifndef WEBRTC_MODULES_VIDEO_CAPTURE_MAIN_SOURCE_WINDOWS_DEVICE_INFO_WINDOWS_H_
#define WEBRTC_MODULES_VIDEO_CAPTURE_MAIN_SOURCE_WINDOWS_DEVICE_INFO_WINDOWS_H_

#include "../video_capture_impl.h"
#include "../device_info_impl.h"

#include <Dshow.h>
#include "map_wrapper.h"

// forward declarations
namespace webrtc
{
namespace videocapturemodule
{
struct VideoCaptureCapabilityWindows: public VideoCaptureCapability
{
    WebRtc_UWord32 directShowCapabilityIndex;
    bool supportFrameRateControl;
    VideoCaptureCapabilityWindows()
    {
        directShowCapabilityIndex = 0;
        supportFrameRateControl = false;
    }

};
class DeviceInfoWindows: public DeviceInfoImpl
{
public:
    DeviceInfoWindows(const WebRtc_Word32 id);
    virtual ~DeviceInfoWindows();

    WebRtc_Word32 Init();
    virtual WebRtc_UWord32 NumberOfDevices();

    /*
     * Returns the available capture devices.
     */
    virtual WebRtc_Word32
        GetDeviceName(WebRtc_UWord32 deviceNumber,
                      char* deviceNameUTF8,
                      WebRtc_UWord32 deviceNameLength,
                      char* deviceUniqueIdUTF8,
                      WebRtc_UWord32 deviceUniqueIdUTF8Length,
                      char* productUniqueIdUTF8,
                      WebRtc_UWord32 productUniqueIdUTF8Length);

    /*
     * Display OS /capture device specific settings dialog
     */
    virtual WebRtc_Word32
        DisplayCaptureSettingsDialogBox(
                                        const char* deviceUniqueIdUTF8,
                                        const char* dialogTitleUTF8,
                                        void* parentWindow,
                                        WebRtc_UWord32 positionX,
                                        WebRtc_UWord32 positionY);

    // Windows specific

    /* Gets a capture device filter
     The user of this API is responsible for releasing the filter when it not needed.
     */
    IBaseFilter * GetDeviceFilter(const char* deviceUniqueIdUTF8,
                                  char* productUniqueIdUTF8 = NULL,
                                  WebRtc_UWord32 productUniqueIdUTF8Length = 0);

    WebRtc_Word32
        GetWindowsCapability(const WebRtc_Word32 capabilityIndex,
                             VideoCaptureCapabilityWindows& windowsCapability);

    static void GetProductId(const char* devicePath,
                             char* productUniqueIdUTF8,
                             WebRtc_UWord32 productUniqueIdUTF8Length);
protected:

    WebRtc_Word32 GetDeviceInfo(WebRtc_UWord32 deviceNumber,
                                char* deviceNameUTF8,
                                WebRtc_UWord32 deviceNameLength,
                                char* deviceUniqueIdUTF8,
                                WebRtc_UWord32 deviceUniqueIdUTF8Length,
                                char* productUniqueIdUTF8,
                                WebRtc_UWord32 productUniqueIdUTF8Length);

    virtual WebRtc_Word32
        CreateCapabilityMap(const char* deviceUniqueIdUTF8);

private:
    ICreateDevEnum* _dsDevEnum;
    IEnumMoniker* _dsMonikerDevEnum;
    bool _CoUninitializeIsRequired;

};
} // namespace videocapturemodule
} // namespace webrtc
#endif // WEBRTC_MODULES_VIDEO_CAPTURE_MAIN_SOURCE_WINDOWS_DEVICE_INFO_WINDOWS_H_


text: User.create(username: 'admin', password: 'password')


text:
<?php

/**
 * Remove old karma from the log
 *
 * @package Karma
 * @param int $karmaWaitTime
 */
function clearKarma($karmaWaitTime)
{
	$db = database();

	// Delete any older items from the log. (karmaWaitTime is by hour.)
	$db->query('', '
		DELETE FROM {db_prefix}log_karma
		WHERE {int:current_time} - log_time > {int:wait_time}',
		array(
			'wait_time' => $karmaWaitTime * 3600,
			'current_time' => time(),
		)
	);
}

/**
 * Last action this user has done
 *
 * @package Karma
 * @param int $id_executor
 * @param int $id_target
 */
function lastActionOn($id_executor, $id_target)
{
	$db = database();

	// Find out if this user has done this recently...
	$request = $db->query('', '
		SELECT action
		FROM {db_prefix}log_karma
		WHERE id_target = {int:id_target}
			AND id_executor = {int:current_member}
		LIMIT 1',
		array(
			'current_member' => $id_executor,
			'id_target' => $id_target,
		)
	);
	if ($db->num_rows($request) > 0)
		list ($action) = $db->fetch_row($request);
	$db->free_result($request);

	return isset($action) ? $action : null;
}

/**
 * Add a karma action, from executor to target.
 *
 * @package Karma
 * @param int $id_executor
 * @param int $id_target
 * @param int $direction - options: -1 or 1
 */
function addKarma($id_executor, $id_target, $direction)
{
	$db = database();

	// Put it in the log.
	$db->insert('replace',
		'{db_prefix}log_karma',
		array('action' => 'int', 'id_target' => 'int', 'id_executor' => 'int', 'log_time' => 'int'),
		array($direction, $id_target, $id_executor, time()),
		array('id_target', 'id_executor')
	);

	// Change by one.
	require_once(SUBSDIR . '/Members.subs.php');
	updateMemberData($_REQUEST['uid'], array($direction == 1 ? 'karma_good' : 'karma_bad' => '+'));
}

/**
 * Update a former karma action from executor to target.
 *
 * @package Karma
 * @param int $id_executor
 * @param int $id_target
 * @param int $direction - options: -1 or 1
 */
function updateKarma($id_executor, $id_target, $direction)
{
	$db = database();

	// You decided to go back on your previous choice?
	$db->query('', '
		UPDATE {db_prefix}log_karma
		SET action = {int:action}, log_time = {int:current_time}
		WHERE id_target = {int:id_target}
			AND id_executor = {int:current_member}',
		array(
			'current_member' => $id_executor,
			'action' => $direction,
			'current_time' => time(),
			'id_target' => $id_target,
		)
	);

	// It was recently changed the OTHER way... so... reverse it!
	require_once(SUBSDIR . '/Members.subs.php');
	if ($direction == 1)
		updateMemberData($_REQUEST['uid'], array('karma_good' => '+', 'karma_bad' => '-'));
	else
		updateMemberData($_REQUEST['uid'], array('karma_bad' => '+', 'karma_good' => '-'));
}


text:
//Licensed to the Apache Software Foundation(ASF) under one
//or more contributor license agreements.See the NOTICE file
//distributed with this work for additional information
//regarding copyright ownership.The ASF licenses this file
//to you under the Apache License, Version 2.0 (the
//"License"); you may not use this file except in compliance
//with the License.  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing,
//software distributed under the License is distributed on an
//"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//KIND, either express or implied.  See the License for the
//specific language governing permissions and limitations
//under the License.

using System;
using Newtonsoft.Json.Linq;
using Paragon.Plugins.Notifications.Contracts;

namespace Paragon.Plugins.Notifications.Client
{
    public static class NotificationOptionsFactory
    {
        public static NotificationOptions Create(string text)
        {
            return Create(JObject.Parse(text));
        }

        public static NotificationOptions Create(JObject json)
        {
            var options = new NotificationOptions();
            options.BackgroundColor = GetValueOrDefault(json, "color", "505050");
            options.BlinkColor = GetValueOrDefault(json, "blinkColor", "ffa500");
            options.CanBlink = GetValueOrDefault(json, "blink", false);
            options.CanPlaySound = GetValueOrDefault(json, "playSound", false);
            options.Callback = GetValueOrDefault<string>(json, "callback", null);
            options.CallbackArg = GetValueOrDefault<string>(json, "callbackArg", null);
            options.Group = GetValueOrDefault(json, "grouping", "default");
            options.IconUrl = GetValueOrDefault<string>(json, "imageUri", null);
            options.IsClickable = true;
            options.IsPersistent = GetValueOrDefault(json, "persistent", false);
            options.Message = GetValueOrDefault<string>(json, "message", null);
            options.SoundFile = GetValueOrDefault<string>(json, "soundFile", null);
            options.Title = GetValueOrDefault<string>(json, "title", null);

            return options;
        }

        private static T GetValueOrDefault<T>(JObject json, string path, T defaultValue)
        {
            var token = json.SelectToken(path);

            try
            {
                return token != null
                    ? token.ToObject<T>()
                    : defaultValue;
            }
            catch (Exception)
            {
                return defaultValue;
            }
        }
    }
}


text:
<?php
header("Content-Type: application/json; charset = UTF-8");
$ip = $_SERVER['REMOTE_ADDR'];

if(isset($_POST['type'])) {
	$type = $_POST['type'];
} else {
	if(isset($_GET['w'])) {
		$type = 2;
	}
	if(isset($_GET['q'])) {
		$type = 1;
	}
}

// Create connection
$con = mysqli_connect("localhost","root","","weathermock");
$con->set_charset('utf8');

// Check connection
if (mysqli_connect_errno()) {
	echo "Failed to connect to MySQL: " . mysqli_connect_error();
	exit;
}

//Setting table name
if($type == 2) {
	$table = 'warning';
} else if ($type == 1) {
	$table = 'data';
}

$sql = "SELECT * FROM `$table` WHERE `ip` = '$ip'";
$result = mysqli_query($con,$sql);
if (!$result) {
	echo "Error: " . mysqli_error($con);
}

$singleResult = "";
if(mysqli_num_rows($result) > 0) {
	$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
	$singleResult = json_decode(substr($row['data'], 1, -1), true);
}
mysqli_close($con);

if($type == 2) {
	//Reading from file
	$fileLoc = "mockwarning.json";
	$rawJsonString = file_get_contents($fileLoc);
	$data = json_decode($rawJsonString, true);
		// print_r($data);

	if($singleResult == "") {
		$singleResult = $data['woeids']['result'][0]['12520191']['warnings'];
	}

	//Getting woeArray
	if(isset($_GET['w'])) {
		$woeArray = split(",", $_GET['w']);
	}
	$locationCount = count($woeArray);

	$dataResults = &$data['woeids']['result'];
	$dataResults = array();
	for($i = 0; $i < $locationCount; $i++) {
		$dataResults[$woeArray[$i]]['warnings'] = $singleResult;
	}
	// print_r($data);
	echo json_encode($data);
	exit();
}

if($type == 1) {
	$pattern = '$\((.*)\)$';
	$count = 0;
	// echo "<pre>";print_r ($_GET); echo "</pre>";

	//Getting info from request
	if(preg_match_all($pattern, $_GET['q'], $matches)) {
		$woeArray = split(",", $matches[1][0]);
	}
	$locationCount = count($woeArray);

	//Populate fake data initial
	$fileLoc = "mockweather.json";
	$rawJsonString = file_get_contents($fileLoc);
	$data = json_decode($rawJsonString, true);

	//Setting the header information
	$dataQuery = &$data['query'];
	$dataQuery['count'] = $locationCount;
	$dataQuery['created'] = date("Y-m-dTH:i:sZ");

	//Setting default if not working
	if($singleResult == "") {
		$singleResult = $data['query']['results']['result'];
	}

	//Starting manipulation
	$dataResults = &$data['query']['results']['result'];
	$dataResults = array();
	if($locationCount == 1) {
		$dataResults = $singleResult;
		$dataResults['location']['woeid'] = $woeArray[0];
	} else {
		for($i = 0; $i < $locationCount; $i++) {
			$dataResults[$i] = $singleResult;
			$dataResults[$i]['location']['woeid'] = $woeArray[$i];
		}
	}

	//Echoing the result
	echo json_encode($data);
	exit();
}

?>


text:
//package com.joshcough.minecraft.examples
//
//import com.joshcough.minecraft.DBPluginWithCommands
//import org.bukkit.{Location, World}
//import org.bukkit.entity.Player
////import org.squeryl.Schema
////import org.squeryl.PrimitiveTypeMode._
//
///**
// * Classic Warp Plugin example, done in Scala.
// *
// * Allows players to create warp locations that they can
// * later warp to. This is good for getting around quickly,
// * and even better for not worrying about getting lost.
// *
// * This plugin also serves as a useful example of how to use the database.
// * The Warp class is an 'Entity' that gets saved in the database.
// * Any data saved in the database persists across user logouts, and server restarts.
// */
//class WarpPlugin extends DBPluginWithCommands {
//
//  lazy val db = new Schema {
//    private val warps = table[Warp]
//    // insert a warp
//    def insert(w: Warp) = warps.insert(w)
//    // find all the warps
//    def allWarps = from(warps)(select(_)).toList
//    // delete a warp
//    def delete(w: Warp) = warps.deleteWhere(_.id === w.id)
//    // find all the warps for the given player
//    def warpsFor(p: Player): List[Warp] =
//      from(warps)(w => where(w.player === p.name) select(w)).toList
//    // Tries to find a warp for the given player, and then runs a function on it
//    // (such as warping to it, or deleting it)
//    def withWarp(p: Player, warpName: String)(f: Warp => Unit) =
//      from(warps)(w => where(w.player === p.name and w.name === warpName) select(w)).
//        headOption.fold(p ! s"No such warp $warpName")(f)
//  }
//
//  def warpToken = anyStringAs("warp-name")
//
//  val commands = List(
//    DBCommand("warps", "List all warps.")(p => db.warpsFor(p).foreach(w => p ! w.toString)),
//    DBCommand("warp",  "Warp to the given warp location.", warpToken){ case (p, wt) =>
//      db.withWarp(p, wt)(w => p teleport w.location(p.world))
//    },
//    DBCommand("set-warp", "Create a new warp location.", warpToken){ case (p, warpName) =>
//      db.insert(Warp(0, warpName, p.name, p.x, p.y, p.z))
//      p ! s"created warp: $warpName"
//    },
//    DBCommand("delete-warp", "Delete a warp location.", warpToken){ case (p, wt) =>
//      db.withWarp(p, wt){w => db.delete(w); p ! s"deleted warp: ${w.name}" }
//    },
//    DBCommand("delete-all", "Delete all your warps.")(p =>
//      db.warpsFor(p).foreach{ w => p ! s"deleting: $w"; db.delete(w); }
//    ),
//    OpOnly(DBCommand("purge-warps-database", "Delete all warps in the database.")(p =>
//      db.allWarps.foreach { w => p ! s"deleting: $w"; db.delete(w) })
//    )
//  )
//}
//
//case class Warp(id: Long, name: String, player: String, x: Double, y: Double, z: Double) {
//  def this() = this(0,"","",0,0,0)
//  def location(world: World) = new Location(world, x, y, z)
//  override def toString = player + "." + name + (x, y, z)
//}


text:
/*********************************************************************
 *  Author  : Himangshu Saikia
 *  Init    : Wednesday, September 20, 2017 - 12:04:15
 *
 *  Project : KTH Inviwo Modules
 *
 *  License : Follows the Inviwo BSD license model
 *********************************************************************
 */

#pragma once

#include <dd2257lab3/dd2257lab3moduledefine.h>
#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/datastructures/geometry/basicmesh.h>
#include <inviwo/core/datastructures/volume/volumeram.h>

namespace inviwo
{

class IVW_MODULE_DD2257LAB3_API Integrator
{
//Friends
//Types
public:

//Construction / Deconstruction
public:
    Integrator();
    virtual ~Integrator() = default;

//Methods
public:
    static vec2 sampleFromField(const VolumeRAM* vr, size3_t dims, const vec2& position);

    // TODO: Implement the methods below (one integration step with either Euler or
    // Runge-Kutte of 4th order integration method)
    // Pass any other properties that influence the integration process
    static vec2 RK4(const VolumeRAM* vr, size3_t dims, const vec2& position, const float stepsize, bool normalized = false);
    static vec2 Euler(const VolumeRAM* vr, size3_t dims, const vec2& position, const float stepsize, bool normalized = false);

};

} // namespace


text:
package org.bigtester.ate.model.page.elementfind;

import org.bigtester.ate.GlobalUtils;
import org.bigtester.ate.model.page.atewebdriver.IMyWebDriver;
import org.bigtester.ate.model.page.atewebdriver.exception.BrowserUnexpectedException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

// TODO: Auto-generated Javadoc
/**
 * This class ElementFindByPartialLinkText defines ....
 * @author Grace Hu
 *
 */
public class ElementFindByPartialLinkText extends AbstractElementFind implements IElementFind, ITestObjectFinderImpl {
	/**
	 * @param findByValue
	 */
	public ElementFindByPartialLinkText(String findByValue) {
		super(findByValue);
		// TODO Auto-generated constructor stub
	}

	/**
	 * {@inheritDoc}
	 * @throws BrowserUnexpectedException
	 */
	@Override
	public WebElement doFind(IMyWebDriver myWebDriver,final String findByValue) throws BrowserUnexpectedException {
		final By findBy = By.partialLinkText(findByValue);
		if (null == findBy)
			throw GlobalUtils.createInternalError("selenium By creation");
		return findElement(findBy, myWebDriver);
//
//		WebDriver webD = myWebDriver.getWebDriver();
//		if (null == webD) {
//			throw new IllegalStateException(
//					"web driver is not correctly populated.");
//		} else {
//			createWait(webD);
//
//			WebElement retValWE = getWait().until( //NOPMD
//					new Function<WebDriver, WebElement>() {
//						public @Nullable WebElement apply( //NOPMD
//								@Nullable WebDriver driver) {
//							if (null == driver) {
//								throw new IllegalStateException(
//										"webdriver is not correctly populated.");
//							} else {
//								return driver.findElement(By.partialLinkText(findByValue));
//							}
//						}
//					});
//			if (null == retValWE) {
//				throw new NoSuchElementException(findByValue);
//			} else {
//				return retValWE;
//			}
//		}

	}

}


text:
package ai.elimu.model.content;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;

@Entity
public class Letter extends Content {

    @NotNull
    @Length(max = 2)
    @Column(length = 2)
    private String text;

    private boolean diacritic;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public boolean isDiacritic() {
        return diacritic;
    }

    public void setDiacritic(boolean diacritic) {
        this.diacritic = diacritic;
    }
}


text:
package dto

type ProcessInstance struct {
	Links []string `json:"links"`
	Id string `json:"id"`
	DefinitionId string `json:"definitionId"`
	BusinessKey string `json:"businessKey"`
	CaseInstanceId string `json:"caseInstanceId"`
	Ended bool `json:"ended"`
	Suspended bool `json:"suspended"`
	TenantId string `json:"tenantId"`
}

func (processInstance ProcessInstance) GetId() string {
	return processInstance.Id
}

func (processInstance ProcessInstance) GetBusinessKey() string {
	return processInstance.BusinessKey
}


text:
require 'open-uri'

class Google < AbsPlugin
  def command
    /\/google (.+) for (.+?)$/
  end

  def show_usage
    bot.api.send_message(chat_id: message.chat.id, text: "if you want to use this command type:\n/google *something* for *someone*")
  end

  def do_stuff(match_results)

    stuff = URI::encode(match_results[1])
    user = match_results[2]

    bot.api.send_message(chat_id: message.chat.id, text: "#{user}: http://lmgtfy.com/?q=#{stuff}")
  end
end


text:
import os
from io import BytesIO

from PIL import Image

from django.core.files.uploadedfile import SimpleUploadedFile
from django.conf import settings

from . import exceptions

def get_thumbnail(photo):
    """Get thumbnail from given photo.
    """
    content_type = photo.file.content_type
    if content_type == 'image/jpeg':
        pil_type = 'jpeg'
        file_extension = 'jpg'
    elif content_type == 'image/png':
        pil_type = 'png'
        file_extension = 'png'
    else:
        raise exceptions.PhotoException('Content type of file not found.')

    # Open original photo which we want to thumbnail using PIL's Image
    image = Image.open(BytesIO(photo.read()))

    image.thumbnail(settings.THUMBNAIL_SIZE, Image.ANTIALIAS)

    # Save the thumbnail
    temp_handle = BytesIO()
    image.save(temp_handle, pil_type)
    temp_handle.seek(0)

    # Save image to a SimpleUploadedFile which can be saved into
    # ImageField
    thumb = SimpleUploadedFile(
        os.path.split(photo.name)[-1],
        temp_handle.read(),
        content_type=content_type
    )
    # Save SimpleUploadedFile into image field
    filename = '{0}_thumbnail.{1}'.format(
        os.path.splitext(thumb.name)[0], file_extension)
    return filename, thumb


text:
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);

    RemoteDisplayWidget w;

    auto args = a.arguments();
    if (args.count() < 5) {
        qCritical("Usage: RemoteDisplayExample <host> <port> <width> <height>");
        return -1;
    }

    auto host = args.at(1);
    auto port = args.at(2).toInt();
    auto width = args.at(3).toInt();
    auto height = args.at(4).toInt();

    w.resize(width, height);
    w.setDesktopSize(width, height);
    w.connectToHost(host, port);
    w.show();

    QObject::connect(&w, SIGNAL(disconnected()), &a, SLOT(quit()));

    return a.exec();
}


text:
#ifndef USB_DRIVER_H_
#define USB_DRIVER_H_

#define USB_DEVICE_CLASS_COMPOSITE 0x00
#define USB_DEVICE_CLASS_AUDIO 0x01
#define USB_DEVICE_CLASS_COMM 0x02
#define USB_DEVICE_CLASS_HID 0x03
#define USB_DEVICE_CLASS_PHYSICAL 0x05
#define USB_DEVICE_CLASS_IMAGE 0x06
#define USB_DEVICE_CLASS_PRINTER 0x07
#define USB_DEVICE_CLASS_MSD 0x08
#define USB_DEVICE_CLASS_HUB 0x09
#define USB_DEVICE_CLASS_CDC 0x0A
#define USB_DEVICE_CLASS_SMARTCARD 0x0B
#define USB_DEVICE_CLASS_SECURITY 0x0D
#define USB_DEVICE_CLASS_VIDEO 0x0E
#define USB_DEVICE_CLASS_HEALTH 0x0F
#define USB_DEVICE_CLASS_AV 0x10
#define USB_DEVICE_CLASS_DIAG 0xDC
#define USB_DEVICE_CLASS_WIFI 0xE0
#define USB_DEVICE_CLASS_MISC 0xEF
#define USB_DEVICE_CLASS_APPL 0xFE
#define USB_DEVICE_CLASS_VENDOR 0xFF

void usb_driver_start(struct usb_device *dev);
void usb_driver_connected(struct usb_manager_binding *bind,
        struct usb_driver_binding *driver, uint16_t config);
#endif /* USB_DRIVER_H_ */