text:
Q: How to implement a TStringGrid using virtual tree view? How to implement a TStringGrid using virtual tree view? Does anyone have an example?

A: An example, though it does cater for a tree structure, can be found here:
http://www.bjmsoftware.com/delphistuff/virtualstringtreeexample.zip
It's something I have been playing with to start some new base frames, so there may be stuff in there you do not need. The BaseTree_fr unit contains the VirtualStringTree stuff from an old project. The Tree_fm.pas unit contains my new effort. Tree_fm.pas doesn't yet include dynamically adding new nodes and deleting existing ones, but you can find that in the BaseTree_fr unit.
To keep in the spirit of StackOverflow standing on its own two feet, I am including both units here.
The new effort
unit Tree_fm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, VirtualTrees, StdCtrls, DomainObject, DogBreed, ImgList;

type
  RTreeData = record
    CDO: TCustomDomainObject;
  end;
  PTreeData = ^RTreeData;

  TForm1 = class(TForm)
    VirtualStringTree1: TVirtualStringTree;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    Button5: TButton;
    HeaderImages: TImageList;
    TreeImages: TImageList;
    StateImages: TImageList;
    procedure VirtualStringTree1Checked(Sender: TBaseVirtualTree; Node:
        PVirtualNode);
    procedure VirtualStringTree1CompareNodes(Sender: TBaseVirtualTree; Node1,
        Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
    procedure VirtualStringTree1DblClick(Sender: TObject);
    procedure VirtualStringTree1FocusChanged(Sender: TBaseVirtualTree; Node:
        PVirtualNode; Column: TColumnIndex);
    procedure VirtualStringTree1GetImageIndex(Sender: TBaseVirtualTree; Node:
        PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted:
        Boolean; var ImageIndex: Integer);
    procedure VirtualStringTree1GetText(Sender: TBaseVirtualTree; Node:
        PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText:
        string);
    procedure VirtualStringTree1InitChildren(Sender: TBaseVirtualTree; Node:
        PVirtualNode; var ChildCount: Cardinal);
    procedure VirtualStringTree1InitNode(Sender: TBaseVirtualTree; ParentNode,
        Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
  private
    FIsLoading: Boolean;
    FCDO: TCustomDomainObject;
  protected
    procedure BeginLoad;
    procedure EndLoad;
    procedure ClearFrame;
    procedure ClearHeaders;
    procedure ShowColumnHeaders;
    procedure ShowDomainObject(aCDO, aParent: TCustomDomainObject);
    procedure ShowDomainObjects(aCDO, aParent: TCustomDomainObject);

    procedure AddColumnHeaders(aColumns: TVirtualTreeColumns); virtual;
    function GetColumnText(aCDO: TCustomDomainObject; aColumn: TColumnIndex;
      var aCellText: string): Boolean; virtual;
  protected
    property CDO: TCustomDomainObject read FCDO write FCDO;
  public
    constructor Create(AOwner: TComponent); override;
    procedure Load(aCDO: TCustomDomainObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.AddColumnHeaders(aColumns: TVirtualTreeColumns);
var
  Col: TVirtualTreeColumn;
begin
  Col := aColumns.Add;
  Col.Text := 'Breed(Group)';
  Col.Width := 200;

  Col := aColumns.Add;
  Col.Text := 'Average Age';
  Col.Width := 100;
  Col.Alignment := taRightJustify;

  Col := aColumns.Add;
  Col.Text := 'CDO.Count';
  Col.Width := 100;
  Col.Alignment := taRightJustify;
end;

procedure TForm1.BeginLoad;
begin
  FIsLoading := True;
  VirtualStringTree1.BeginUpdate;
end;

procedure TForm1.ClearFrame;
begin
  VirtualStringTree1.Clear;
//  FNodeList.Clear;
//  DoSelectionChanged(nil);
end;

procedure TForm1.ClearHeaders;
begin
  VirtualStringTree1.Header.Columns.Clear;
end;

constructor TForm1.Create(AOwner: TComponent);
begin
  inherited;

  VirtualStringTree1.DefaultText := '';
  VirtualStringTree1.NodeDataSize := SizeOf(RTreeData);

  VirtualStringTree1.Header.Options := VirtualStringTree1.Header.Options
    //- []
    + [hoDblClickResize, hoHotTrack, hoShowImages]
  ;
  VirtualStringTree1.Header.Style := hsXPStyle;

  VirtualStringTree1.TreeOptions.AnimationOptions := VirtualStringTree1.TreeOptions.AnimationOptions
    //- []
    //+ []
  ;
  VirtualStringTree1.TreeOptions.AutoOptions := VirtualStringTree1.TreeOptions.AutoOptions
    //- []
    // toAutoSort is (was once?) causing heavy recursions and InitNode executions!!!
    // It isn't now, but it does cause the entire tree to be loaded!
    + [{toAutoSort,}{ toAutoHideButtons}]
  ;
  //VirtualStringTree1.TreeOptions.ExportMode := emChecked;
  VirtualStringTree1.TreeOptions.MiscOptions := VirtualStringTree1.TreeOptions.MiscOptions
    - [toInitOnSave]
    + [toCheckSupport]
  ;
  VirtualStringTree1.TreeOptions.PaintOptions := VirtualStringTree1.TreeOptions.PaintOptions
    - [toShowTreeLines]
    + [toHotTrack, toGhostedIfUnfocused, toUseExplorerTheme]
  ;
  VirtualStringTree1.TreeOptions.SelectionOptions := VirtualStringTree1.TreeOptions.SelectionOptions
    //- []
    + [toExtendedFocus, toFullRowSelect, toMultiSelect]
  ;
  VirtualStringTree1.TreeOptions.StringOptions := VirtualStringTree1.TreeOptions.StringOptions
    //- []
    //+ []
  ;

  VirtualStringTree1.Header.Images := HeaderImages;
  VirtualStringTree1.CheckImageKind := ckXP;
  VirtualStringTree1.CustomCheckImages := nil;
  VirtualStringTree1.Images := TreeImages;
  VirtualStringTree1.StateImages := StateImages;

  //VirtualStringTree1.ClipboardFormats := ;
  //VirtualStringTree1.DragMode := dmAutomatic;
  VirtualStringTree1.DragOperations := [];
end;

procedure TForm1.EndLoad;
begin
  VirtualStringTree1.EndUpdate;
  FIsLoading := False;
end;

function TForm1.GetColumnText(aCDO: TCustomDomainObject; aColumn: TColumnIndex;
  var aCellText: string): Boolean;
begin
  if Assigned(aCDO) then begin
    case aColumn of
      -1, 0: begin
        aCellText := aCDO.DisplayString;
      end;
      1: begin
        if aCDO.InheritsFrom(TDogBreed) then begin
          aCellText := IntToStr(TDogBreed(aCDO).AverageAge);
        end;
      end;
      2: begin
        aCellText := IntToStr(aCDO.Count);
      end;
    else
//      aCellText := '';
    end;
    Result := True;
  end else begin
    Result := False;
  end;
end;

procedure TForm1.Load(aCDO: TCustomDomainObject);
begin
// This would be in a more generic ancestor.
  BeginLoad;
  try
    if Assigned(CDO) then begin
      ClearHeaders;
      ClearFrame;
    end;
    CDO := aCDO;
    if Assigned(CDO) then begin
      ShowColumnHeaders;
      ShowDomainObjects(CDO, nil);
    end;
  finally
    EndLoad;
  end;
end;

procedure TForm1.ShowColumnHeaders;
begin
  AddColumnHeaders(VirtualStringTree1.Header.Columns);
  if VirtualStringTree1.Header.Columns.Count > 0 then begin
    VirtualStringTree1.Header.Options := VirtualStringTree1.Header.Options
      + [hoVisible];
  end;
end;

procedure TForm1.ShowDomainObject(aCDO, aParent: TCustomDomainObject);
begin
// We are dealing with a virtual tree that asks for its data, and so we don't
// need to do anything here.
end;

procedure TForm1.ShowDomainObjects(aCDO, aParent: TCustomDomainObject);
begin
// We are dealing with a virtual tree that asks for its data, and so we only need
// to set the number of nodes under the root.

  if Assigned(aCDO) then begin
    VirtualStringTree1.RootNodeCount := aCDO.Count;
  end else begin
    VirtualStringTree1.RootNodeCount := 0;
  end;
end;

procedure TForm1.VirtualStringTree1Checked(Sender: TBaseVirtualTree; Node:
    PVirtualNode);
begin
(*
procedure TBaseTreeFrame.Frame_VstChecked(Sender: TBaseVirtualTree;
  Node: PVirtualNode);
var
  ACDO: TCustomDomainObject;
  NodeData: ^RTreeData;
begin
  inherited;
  NodeData := Sender.GetNodeData(Node);
  ACDO := NodeData.CDO;
  if ACDO <> nil then begin
    ACDO.Checked := (Node.CheckState in [csCheckedNormal, csCheckedPressed]);
  end;
end;
*)
end;

procedure TForm1.VirtualStringTree1CompareNodes(Sender: TBaseVirtualTree;
    Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
begin
  beep;
(*
procedure TBaseTreeFrame.Frame_VstCompareNodes(Sender: TBaseVirtualTree;
  Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
var
  Node1Data: ^RTreeData;
  Node2Data: ^RTreeData;
  Node1CDO: TCustomDomainObject;
  Node2CDO: TCustomDomainObject;
begin
  inherited;
  Node1Data := Frame_Vst.GetNodeData(Node1);
  Node2Data := Frame_Vst.GetNodeData(Node2);
  Node1CDO := Node1Data.CDO;
  Node2CDO := Node2Data.CDO;
//
  if (Node1CDO = nil) or (Node2CDO = nil) then begin
    Result := 0;
  end else if (Node1CDO is TDomainObjectList) <> (Node2CDO is TDomainObjectList) then begin
    if Node1CDO is TDomainObjectList then begin
      Result := -1;
    end else begin
      Result := 1;
    end;
  end else begin
    Result := AnsiCompareText(Node1CDO.SortString, Node2CDO.SortString);
  end;
end;
*)
end;

procedure TForm1.VirtualStringTree1DblClick(Sender: TObject);
begin
(*
procedure TBaseTreeFrame.Frame_VstDblClick(Sender: TObject);
var
  ACDO: TCustomDomainObject;
  NodeData: ^RTreeData;
  Tree: TBaseVirtualTree;
begin
  inherited;
  if Sender is TBaseVirtualTree then begin
    Tree := TBaseVirtualTree(Sender);
    if Tree.FocusedNode <> nil then begin
      NodeData := Tree.GetNodeData(Tree.FocusedNode);
      ACDO := NodeData.CDO;
      HandleDoubleClicked(ACDO);
    end;
  end;
end;

procedure TBaseTreeFrame.HandleDoubleClicked(ACDO: TCustomDomainObject);
begin
  DoDoubleClicked(ACDO);
end;

procedure TBaseTreeFrame.DoDoubleClicked(ACDO: TCustomDomainObject);
begin
  if assigned(FOnDoubleClicked) then begin
    FOnDoubleClicked(ACDO);
  end;
end;
*)
end;

procedure TForm1.VirtualStringTree1FocusChanged(Sender: TBaseVirtualTree; Node:
    PVirtualNode; Column: TColumnIndex);
begin
(*
procedure TBaseTreeFrame.Frame_VstFocusChanged(Sender: TBaseVirtualTree;
  Node: PVirtualNode; Column: TColumnIndex);
var
  ACDO: TCustomDomainObject;
  NodeData: ^RTreeData;
begin
  inherited;
  NodeData := Sender.GetNodeData(Node);
  ACDO := NodeData.CDO;
  HandleSelectionChanged(ACDO);
end;

procedure TBaseTreeFrame.HandleSelectionChanged(ACDO: TCustomDomainObject);
begin
  DoSelectionChanged(ACDO);
end;

procedure TBaseTreeFrame.DoSelectionChanged(ACDO: TCustomDomainObject);
begin
  if assigned(FOnSelectionChanged) then begin
    FOnSelectionChanged(ACDO);
  end;
end;
*)
end;

procedure TForm1.VirtualStringTree1GetImageIndex(Sender: TBaseVirtualTree;
    Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted:
    Boolean; var ImageIndex: Integer);
begin
(*
procedure TBaseTreeFrame.Frame_VstGetImageIndex(Sender: TBaseVirtualTree;
  Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
  var Ghosted: Boolean; var ImageIndex: Integer);
var
  ACDO: TCustomDomainObject;
  NodeData: ^RTreeData;
begin
  inherited;
  Case Column of
    -1, 0 : begin
      NodeData := Sender.GetNodeData(Node);
      ACDO := NodeData.CDO;
      case Kind of
        ikState: ImageIndex := -1;
        ikNormal: ImageIndex := GetImageIndexFor(ACDO, false);
        ikSelected: ImageIndex := GetImageIndexFor(ACDO, true);
        ikOverlay: ImageIndex := -1;
      else
        ImageIndex := -1;
      end;
    end;
  else
  end;
*)
end;

procedure TForm1.VirtualStringTree1GetText(Sender: TBaseVirtualTree; Node:
    PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText:
    string);
var
  NodeData: ^RTreeData;
begin
  NodeData := Sender.GetNodeData(Node);
  if GetColumnText(NodeData.CDO, Column, {var}CellText) then
  else begin
    if Assigned(NodeData.CDO) then begin
      case Column of
        -1, 0: CellText := NodeData.CDO.DisplayString;
      end;
    end;
  end;
end;

procedure TForm1.VirtualStringTree1InitChildren(Sender: TBaseVirtualTree; Node:
    PVirtualNode; var ChildCount: Cardinal);
var
  NodeData: ^RTreeData;
begin
// This is called when user has clicked on a plus sign.
// We only need to tell the tree for how many children to prepare.

  ChildCount := 0;

  NodeData := Sender.GetNodeData(Node);
  if Assigned(NodeData.CDO) then begin
    ChildCount := NodeData.CDO.Count;
  end;
end;

procedure TForm1.VirtualStringTree1InitNode(Sender: TBaseVirtualTree;
    ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
var
  ParentNodeData: ^RTreeData;
  ParentNodeCDO: TCustomDomainObject;
  NodeData: ^RTreeData;
begin
  if Assigned(ParentNode) then begin
    ParentNodeData := VirtualStringTree1.GetNodeData(ParentNode);
    ParentNodeCDO := ParentNodeData.CDO;
  end else begin
    ParentNodeCDO := CDO;
  end;

  NodeData := VirtualStringTree1.GetNodeData(Node);
  if Assigned(NodeData.CDO) then begin
    // CDO was already set, for example when added through AddDomainObject.
  end else begin
    if Assigned(ParentNodeCDO) then begin
      if ParentNodeCDO.Count > Node.Index then begin
        NodeData.CDO := ParentNodeCDO.CDO[Node.Index];
        if NodeData.CDO.Count > 0 then begin
          InitialStates := InitialStates + [ivsHasChildren];
        end;
//        FNodeList.Add(NodeData.CDO, Node);
      end;
    end;
  end;
  Sender.CheckState[Node] := csUncheckedNormal;
end;

end.

And the old one
Check in second answer, I exceeded the text character limit...

A: I exceeded the character limit on my original answer with this unit, so here it is in a separate answer.
{===============================================================================
  Copyright © BJM Software
  http://www.bjmsoftware.com
===============================================================================}
unit BaseTree_fr;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, ImgList, VirtualTrees, Contnrs
  , DomainObject_intf, Base_fr
  ;

type
  RTreeData = record
    CDO: TCustomDomainObject;
  end;
  PTreeData = ^RTreeData;

  TBaseTreeEvent = procedure of object;

  TCDONodeList = class(TObject)
  private
    FCDOs: TObjectList;
    FNodes: TList;
  protected
  public
    constructor Create;
    destructor Destroy; override;
    procedure Add(ACDO: TCustomDomainObject; ANode: PVirtualNode);
    procedure Clear;
    function IndexOfCDO(ACDO: TCustomDomainObject): Integer;
    function NodeOf(ACDO: TCustomDomainObject): PVirtualNode;
    procedure Remove(ACDO: TCustomDomainObject);
    procedure InvalidateNodeFor(ACDO: TCustomDomainObject; AEvent: TCDOEvent);
    function IndexOfNode(ANode: PVirtualNode): Integer;
    function CDOOf(ANode: PVirtualNode): TCustomDomainObject;
    procedure InvalidateNode(ANode: PVirtualNode);
  end;

  TBaseTreeFrame = class(TBaseFrame, ICDOObserver)
    Frame_Vst: TVirtualStringTree;
    procedure Frame_VstGetImageIndex(Sender: TBaseVirtualTree;
      Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
      var Ghosted: Boolean; var ImageIndex: Integer);
    procedure Frame_VstGetText(Sender: TBaseVirtualTree;
      Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
      var CellText: WideString);
    procedure Frame_VstFocusChanged(Sender: TBaseVirtualTree;
      Node: PVirtualNode; Column: TColumnIndex);
    procedure Frame_VstDblClick(Sender: TObject);
    procedure Frame_VstInitNode(Sender: TBaseVirtualTree; ParentNode,
      Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
    procedure Frame_VstInitChildren(Sender: TBaseVirtualTree;
      Node: PVirtualNode; var ChildCount: Cardinal);
    procedure Frame_VstCompareNodes(Sender: TBaseVirtualTree; Node1,
      Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
    procedure Frame_VstChecked(Sender: TBaseVirtualTree;
      Node: PVirtualNode);
  private
    FNodeCheckType: TCheckType;
    FOnCDOChanged: TCDONotifyEvent;
    FOnDoubleClicked: TCDONotifyEvent;
    FOnSelectionChanged: TCDONotifyEvent;
    FOnShowColumnHeaders: TBaseTreeEvent;
  protected
    FNodeList: TCDONodeList;
    procedure ClearFrame; override;
    procedure ClearHeaders; override;
    function FindParentNode(ACDO: TCustomDomainObject; AParent:
        TCustomDomainObject): PVirtualNode;
    function GetImageIndexFor(ACDO: TCustomDomainObject; Selected: boolean):
        Integer; virtual;
    procedure ShowDobs(ACDO: TCustomDomainObject; AParent: TCustomDomainObject); override;
    procedure ShowDomainObject(ACDO: TCustomDomainObject; AParent:
        TCustomDomainObject); override;
    procedure RemoveDomainObject(ACDO: TCustomDomainObject; AParent:
        TCustomDomainObject);
    procedure SetCDO(const Value: TCustomDomainObject); override;
    function ShowChildrenOfList(AFromCDO: TCustomDomainObject): TCustomDomainObject;
        virtual;
    procedure UpdateCDO(ACDO: TCustomDomainObject; AEvent: TCDOEvent);
    procedure HandleDoubleClicked(ACDO: TCustomDomainObject); virtual;
    procedure HandleSelectionChanged(ACDO: TCustomDomainObject); virtual;
    procedure DoCDOChanged(ACDO: TCustomDomainObject);
    procedure DoDoubleClicked(ACDO: TCustomDomainObject);
    procedure DoSelectionChanged(ACDO: TCustomDomainObject);
    procedure DoShowColumnHeaders;
    procedure BeginLoad; override;
    procedure EndLoad; override;
    procedure ShowColumnHeaders; override;
    procedure AddDomainObject(ACDO: TCustomDomainObject; AParent:
        TCustomDomainObject);
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure CheckAll;
    function CheckedCount: integer;
    procedure FocusOn(ACDO: TCustomDomainObject);
    function GetTree: TCustomDomainObject;
    function GetSelection: TCustomDomainObject;
    procedure UncheckAll;
    property NodeCheckType: TCheckType read FNodeCheckType write FNodeCheckType;
    property OnCDOChanged: TCDONotifyEvent read FOnCDOChanged write FOnCDOChanged;
    property OnDoubleClicked: TCDONotifyEvent read FOnDoubleClicked write
        FOnDoubleClicked;
    property OnSelectionChanged: TCDONotifyEvent read FOnSelectionChanged
        write FOnSelectionChanged;
    property OnShowColumnHeaders: TBaseTreeEvent read FOnShowColumnHeaders
        write FOnShowColumnHeaders;
  end;

implementation

{$R *.dfm}

uses
  BaseGUIApp_fm
  , DomainObject_cls
  , GUIApplication_cls
  ;

constructor TCDONodeList.Create;
begin
  FCDOs := TObjectList.Create( false );
  FNodes := TList.Create;
end;

destructor TCDONodeList.Destroy;
begin
  FCDOs.Free;
  FNodes.Free;
  inherited;
end;

procedure TCDONodeList.Add(ACDO: TCustomDomainObject; ANode: PVirtualNode);
begin
  FCDOs.Add( ACDO );
  FNodes.Add( ANode );
end;

function TCDONodeList.CDOOf(ANode: PVirtualNode): TCustomDomainObject;
var
  Idx: integer;
begin
  Idx := FNodes.IndexOf( ANode );
  if Idx = -1 then begin
    Result := nil;
  end else begin
    Result := TCustomDomainObject( FCDOs[Idx] );
  end;
end;

function TCDONodeList.IndexOfCDO(ACDO: TCustomDomainObject): Integer;
begin
  Result := FCDOs.IndexOf( ACDO );
end;

function TCDONodeList.IndexOfNode(ANode: PVirtualNode): Integer;
begin
  Result := FNodes.IndexOf( ANode );
end;

procedure TCDONodeList.InvalidateNode(ANode: PVirtualNode);
var
  Tree: TBaseVirtualTree;
begin
  Tree := TreeFromNode( ANode );
  Tree.InvalidateNode( ANode );
end;

procedure TCDONodeList.InvalidateNodeFor(ACDO: TCustomDomainObject; AEvent:
  TCDOEvent);
var
  Idx: integer;
  Node: PVirtualNode;
  Tree: TBaseVirtualTree;
begin
  Idx := FCDOs.IndexOf( ACDO );
  if Idx > -1 then begin  // Just in case
    Node := PVirtualNode( FNodes[Idx] );
    Tree := TreeFromNode( Node );
    Tree.InvalidateNode( Node );
  end;
end;

function TCDONodeList.NodeOf(ACDO: TCustomDomainObject): PVirtualNode;
var
  Idx: integer;
begin
  Idx := FCDOs.IndexOf( ACDO );
  if Idx = -1 then begin
    Result := nil;
  end else begin
    Result := PVirtualNode( FNodes[Idx] );
  end;
end;

procedure TCDONodeList.Remove(ACDO: TCustomDomainObject);
begin
  FNodes.Delete( FCDOs.Remove( ACDO ) );
end;

procedure TBaseTreeFrame.ClearFrame;
begin
  inherited;
  Frame_Vst.Clear;
  FNodeList.Clear;
  DoSelectionChanged( nil );
end;

constructor TBaseTreeFrame.Create(AOwner: TComponent);
begin
  FNodeList := TCDONodeList.Create;
  inherited;

  Frame_Vst.DefaultText := '';
  Frame_Vst.DragOperations := [];
  Frame_Vst.NodeDataSize := SizeOf( RTreeData );
//  // This is causing heavy recursions and InitNode executions!!!
//  Frame_Vst.TreeOptions.AutoOptions := Frame_Vst.TreeOptions.AutoOptions
//      + [toAutoSort];
  Frame_Vst.TreeOptions.MiscOptions := Frame_Vst.TreeOptions.MiscOptions
      - [toEditable]
      + [toCheckSupport{, toReadOnly}]
      ;
  Frame_Vst.TreeOptions.PaintOptions := Frame_Vst.TreeOptions.PaintOptions
      - [toHideFocusRect, toHideSelection];
  Frame_Vst.TreeOptions.SelectionOptions := Frame_Vst.TreeOptions.SelectionOptions
      // - []
      + [toFullRowSelect]
      ;
  Frame_Vst.Images := TBaseGUIAppForm( GUIApp.MainForm ).Images;
  Frame_Vst.Header.Images := TBaseGUIAppForm( GUIApp.MainForm ).HeaderImages;
  Frame_Vst.NodeDataSize := sizeof( RTreeData );
end;

destructor TBaseTreeFrame.Destroy;
begin
  FNodeList.Free;
  inherited;
end;

procedure TBaseTreeFrame.RemoveDomainObject(ACDO: TCustomDomainObject; AParent:
    TCustomDomainObject);
var
  Node: PVirtualNode;
begin
  Node := FNodeList.NodeOf( ACDO );
  if Node <> nil then begin
    FNodeList.Remove( ACDO );
    Frame_Vst.DeleteNode( Node );
  end;
end;

procedure TBaseTreeFrame.SetCDO(const Value: TCustomDomainObject);
begin
  if Value <> FCDO then begin
    if FCDO <> nil then begin
      FCDO.DetachObserver( self );
    end;
    inherited;
    if FCDO <> nil then begin
      FCDO.AttachObserver( self );
    end;
  end;
end;

procedure TBaseTreeFrame.ShowDomainObject(ACDO: TCustomDomainObject; AParent:
    TCustomDomainObject);
begin
// We are dealing with a virtual tree that asks for its data, and so we don't
// need to do anything here.
end;

procedure TBaseTreeFrame.UpdateCDO(ACDO: TCustomDomainObject; AEvent:
    TCDOEvent);
//var
//  Node: PVirtualNode;
begin
  if ACDO = CDO then begin // Root that isn't shown.
  end else begin
    case AEvent of
      ceAddedToList: begin
        AddDomainObject( ACDO, ACDO.Container );
        FocusOn( ACDO );
      end;
      ceSaved: begin
        FNodeList.InvalidateNodeFor( ACDO, AEvent );
        DoCDOChanged( ACDO );
      end;
      ceRemovedFromList: begin
        RemoveDomainObject( ACDO, ACDO.Container );
      end;
//      ceCheckStateChanged: begin
//        FNodeList.InvalidateNodeFor( ACDO, AEvent );
//      end;
(*
      ceListReloaded: begin
        Node := FNodeList.NodeOf( ACDO );
        Frame_Vst.ReInitNode( Node, true );
//        FNodeList.InvalidateNodeFor( ACDO, AEvent );
      end;
*)
    end;
  end;
end;

procedure TBaseTreeFrame.Frame_VstGetImageIndex(Sender: TBaseVirtualTree;
  Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
  var Ghosted: Boolean; var ImageIndex: Integer);
var
  ACDO: TCustomDomainObject;
  NodeData: ^RTreeData;
begin
  inherited;
  Case Column of
    -1, 0 : begin
      NodeData := Sender.GetNodeData( Node );
      ACDO := NodeData.CDO;
      case Kind of
        ikState: ImageIndex := -1;
        ikNormal: ImageIndex := GetImageIndexFor( ACDO, false );
        ikSelected: ImageIndex := GetImageIndexFor( ACDO, true );
        ikOverlay: ImageIndex := -1;
      else
        ImageIndex := -1;
      end;
    end;
  else
  end;
end;

procedure TBaseTreeFrame.Frame_VstGetText(Sender: TBaseVirtualTree;
  Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
  var CellText: WideString);
begin
  inherited;
// Should be abstract.
end;

procedure TBaseTreeFrame.Frame_VstFocusChanged(Sender: TBaseVirtualTree;
  Node: PVirtualNode; Column: TColumnIndex);
var
  ACDO: TCustomDomainObject;
  NodeData: ^RTreeData;
begin
  inherited;
  NodeData := Sender.GetNodeData( Node );
  ACDO := NodeData.CDO;
  HandleSelectionChanged( ACDO );
end;

procedure TBaseTreeFrame.HandleSelectionChanged(ACDO: TCustomDomainObject);
begin
  DoSelectionChanged( ACDO );
end;

function TBaseTreeFrame.GetSelection: TCustomDomainObject;
var
  Node: PVirtualNode;
  NodeData: ^RTreeData;
begin
  Node := Frame_Vst.FocusedNode;
  if Node = nil then begin
    Result := nil;
  end else begin
    NodeData := Frame_Vst.GetNodeData( Node );
    Result := NodeData.CDO;
  end;
end;

procedure TBaseTreeFrame.DoSelectionChanged(ACDO: TCustomDomainObject);
begin
  if assigned( FOnSelectionChanged ) then begin
    FOnSelectionChanged( ACDO );
  end;
end;

procedure TBaseTreeFrame.DoCDOChanged(ACDO: TCustomDomainObject);
begin
  if assigned( FOnCDOChanged ) then begin
    FOnCDOChanged( ACDO );
  end;
end;

procedure TBaseTreeFrame.Frame_VstDblClick(Sender: TObject);
var
  ACDO: TCustomDomainObject;
  NodeData: ^RTreeData;
  Tree: TBaseVirtualTree;
begin
  inherited;
  if Sender is TBaseVirtualTree then begin
    Tree := TBaseVirtualTree( Sender );
    if Tree.FocusedNode <> nil then begin
      NodeData := Tree.GetNodeData( Tree.FocusedNode );
      ACDO := NodeData.CDO;
      HandleDoubleClicked( ACDO );
    end;
  end;
end;

procedure TBaseTreeFrame.HandleDoubleClicked(ACDO: TCustomDomainObject);
begin
  DoDoubleClicked( ACDO );
end;

procedure TBaseTreeFrame.DoDoubleClicked(ACDO: TCustomDomainObject);
begin
  if assigned( FOnDoubleClicked ) then begin
    FOnDoubleClicked( ACDO );
  end;
end;

procedure TBaseTreeFrame.BeginLoad;
begin
  inherited;
  Frame_Vst.BeginUpdate;
end;

procedure TBaseTreeFrame.EndLoad;
begin
  Frame_Vst.EndUpdate;
  inherited;
end;

procedure TBaseTreeFrame.DoShowColumnHeaders;
begin
  if assigned( FOnShowColumnHeaders ) then begin
    FOnShowColumnHeaders;
  end;
end;

procedure TBaseTreeFrame.ShowColumnHeaders;
begin
  inherited;
  DoShowColumnHeaders;
end;

procedure TBaseTreeFrame.ClearHeaders;
begin
  inherited;
  Frame_Vst.Header.Columns.Clear;
end;

procedure TCDONodeList.Clear;
begin
  FCDOs.Clear;
  FNodes.Clear;
end;

function TBaseTreeFrame.GetImageIndexFor(ACDO: TCustomDomainObject;
  Selected: boolean): Integer;
begin
// Should be abstract.
  Result := -1;
end;

procedure TBaseTreeFrame.ShowDobs(ACDO, AParent: TCustomDomainObject);
begin
// We are dealing with a virtual tree that asks for its data, so we don't
// need to do anything here.
  inherited;
  if CDO <> nil then begin
    Frame_Vst.RootNodeCount := CDO.CDOCount;
  end else begin
    Frame_Vst.RootNodeCount := 0;
  end;
end;

procedure TBaseTreeFrame.Frame_VstInitNode(Sender: TBaseVirtualTree;
  ParentNode, Node: PVirtualNode;
  var InitialStates: TVirtualNodeInitStates);
var
  ParentNodeData: ^RTreeData;
  ParentNodeCDO: TCustomDomainObject;
  NodeData: ^RTreeData;
  ChildCDO: TCustomDomainObject;
  ChildCDOCount: Cardinal;
begin
// Attach CDO to Node, but wich CDO???
// And tell Node whether it can have children. We don't care yet how many.

  inherited;
  if ParentNode = nil then begin
    ParentNodeCDO := CDO;
  end else begin
    ParentNodeData := Frame_Vst.GetNodeData( ParentNode );
    ParentNodeCDO := ParentNodeData.CDO;
  end;

  NodeData := Frame_Vst.GetNodeData( Node );
  if NodeData.CDO = nil then begin
    ChildCDO := ShowChildrenOfList( ParentNodeCDO );
    if ( ChildCDO <> nil ) then begin
      // Prevent warning on comparing signed/unsiged types.
      ChildCDOCount := ChildCDO.CDOCount;
      if ( ChildCDOCount > Node.Index ) then begin
//      if ChildCDO is TDomainObject then begin
//        NodeData.CDO := ParentNodeCDO.CDO[Node.Index];
//      end else if NodeData.CDO is TDomainObjectList then begin
          NodeData.CDO := ChildCDO.CDO[Node.Index];
//      end;
        FNodeList.Add( NodeData.CDO, Node );
      end;
    end;
  end else begin
    // CDO is already set when node was added through AddDomainObject.
  end;

  Node.CheckType := NodeCheckType;
  Sender.CheckState[Node] := csUncheckedNormal;

end;

procedure TBaseTreeFrame.Frame_VstInitChildren(Sender: TBaseVirtualTree;
  Node: PVirtualNode; var ChildCount: Cardinal);
begin
  inherited;
// This is called when user has clicked on a plus sign.
// We only need to tell the tree for how many children to prepare.

{ TODO -cWishList : This could be defaulted to something like
var
  NodeData: ^RTreeData;
begin
  inherited;
  NodeData := Sender.GetNodeData( Node );
  ChildCount := 0;
  if NodeData.CDO is TCustomDomainObjectList then begin
    ChildCount := NodeData.CDO.CDOCount;
  end;
}
end;

procedure TBaseTreeFrame.AddDomainObject(ACDO: TCustomDomainObject; AParent:
    TCustomDomainObject);
var
  Node: PVirtualNode;
  NodeData: ^RTreeData;
  ParentNode: PVirtualNode;
begin
  inherited;
  Node := FNodeList.NodeOf( ACDO );
  ParentNode := FindParentNode( ACDO, AParent );

  if Node = nil then begin
    Frame_Vst.BeginUpdate;  // Prevent auto sorting
    try
      if ParentNode = nil then begin  // we need the tree's root
        ParentNode := Frame_Vst.RootNode;
        Frame_Vst.RootNodeCount := Frame_Vst.RootNodeCount + 1;
      end else begin
        Frame_Vst.ChildCount[ParentNode] := Frame_Vst.ChildCount[ParentNode] + 1;
      end;
      Node := Frame_Vst.GetLastChild( ParentNode );
    finally
      Frame_Vst.EndUpdate;
    end;
    NodeData := Frame_Vst.GetNodeData( Node );
    NodeData.CDO := ACDO;
    FNodeList.Add( ACDO, Node );
  end else begin
    // it exists, so nothing to do.
  end;
end;

procedure TBaseTreeFrame.Frame_VstCompareNodes(Sender: TBaseVirtualTree;
  Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
var
  Node1Data: ^RTreeData;
  Node2Data: ^RTreeData;
  Node1CDO: TCustomDomainObject;
  Node2CDO: TCustomDomainObject;
begin
  inherited;
  Node1Data := Frame_Vst.GetNodeData( Node1 );
  Node2Data := Frame_Vst.GetNodeData( Node2 );
  Node1CDO := Node1Data.CDO;
  Node2CDO := Node2Data.CDO;
//
  if ( Node1CDO = nil ) or ( Node2CDO = nil ) then begin
    Result := 0;
  end else if ( Node1CDO is TDomainObjectList ) <> ( Node2CDO is TDomainObjectList ) then begin
    if Node1CDO is TDomainObjectList then begin
      Result := -1;
    end else begin
      Result := 1;
    end;
  end else begin
    Result := AnsiCompareText( Node1CDO.SortString, Node2CDO.SortString );
  end;
end;

function TBaseTreeFrame.ShowChildrenOfList(AFromCDO: TCustomDomainObject):
    TCustomDomainObject;
begin
// Should be abstract?
  Result := AFromCDO;
end;

procedure TBaseTreeFrame.FocusOn(ACDO: TCustomDomainObject);
var
  FocusOnNode: PVirtualNode;
begin
  FocusOnNode := FNodeList.NodeOf( ACDO );
  if FocusOnNode <> nil then begin
    Frame_Vst.FocusedNode := FocusOnNode;
    Frame_Vst.ClearSelection;
    Frame_Vst.Selected[FocusOnNode] := true;
  end;
end;

function TBaseTreeFrame.FindParentNode(ACDO,
  AParent: TCustomDomainObject): PVirtualNode;
begin
  Result := FNodeList.NodeOf( AParent );
  if Result = nil then begin
    if AParent.Container <> nil then begin
      Result := FindParentNode( AParent, AParent.Container );
    end;
  end;
end;

function TBaseTreeFrame.GetTree: TCustomDomainObject;
begin
  Result := CDO;
end;

procedure TBaseTreeFrame.CheckAll;
var
  Run: PVirtualNode;
begin
  Frame_Vst.BeginUpdate;
  try
    Run := Frame_Vst.GetFirstVisible;
    while Assigned( Run ) do begin
      Run.CheckState := csCheckedNormal;
      Run := Frame_Vst.GetNextVisible( Run );
    end;
    GetTree.CheckAll;
  finally
    Frame_Vst.EndUpdate;
  end;
end;

procedure TBaseTreeFrame.UncheckAll;
var
  Run: PVirtualNode;
begin
  Frame_Vst.BeginUpdate;
  try
    Run := Frame_Vst.GetFirstVisible;
    while Assigned( Run ) do begin
      Run.CheckState := csUncheckedNormal;
      Run := Frame_Vst.GetNextVisible( Run );
    end;
    GetTree.UncheckAll;
  finally
    Frame_Vst.EndUpdate;
  end;
end;

function TBaseTreeFrame.CheckedCount: integer;
var
  Run: PVirtualNode;
begin
  Result := 0;
  Run := Frame_Vst.GetFirstVisible;
  while Assigned( Run ) do begin
    if Run.CheckState in [csCheckedNormal, csCheckedPressed] then begin
      inc( Result );
    end;
    Run := Frame_Vst.GetNextVisible( Run );
  end;
end;

procedure TBaseTreeFrame.Frame_VstChecked(Sender: TBaseVirtualTree;
  Node: PVirtualNode);
var
  ACDO: TCustomDomainObject;
  NodeData: ^RTreeData;
begin
  inherited;
  NodeData := Sender.GetNodeData( Node );
  ACDO := NodeData.CDO;
  if ACDO <> nil then begin
    ACDO.Checked := ( Node.CheckState in [csCheckedNormal, csCheckedPressed] );
  end;
end;

end.


text:
Q: Remote alternative to local storage for low-security user data? Suppose you're developing an independent, small sub-page for a big and well frequented web portal.
The sub-page shows entries from a public event calendar, and allows users to highlight those especially interesting to them. The highlighted events shall be highlighted (and maybe shown on a separate list) on each future visit of that user.
However, building a classical user registration system, or any other way of storing the user-highlighted event picks on the server, is not an option: The sub-module needs to be as self-contained and need as little maintenance as possible. It's one of the conditions of the project.
The only way to do this without building a login system of some sort (as far as I can see) is using cookies or some other local storage (Flash / HTML 5....) which has the obvious and big downside that it's tied to the computer, not the user.
Is there a way of storing a few kilobytes data on a per-person basis, but without having to utilize a login or openID, that I am overlooking? A reliable web service perhaps?
A "key/value" storage service, to which I pass a unique key (one that the user specified) and get the savedvalue in return, would be sufficient. There is no need for real security - the data in question is by no means confidential.
OpenID is not an option: It is not well known enough among the audience of the site.
Facebook would be an option, but I don't think they provide "storage" options like this.
As a workaround, I am contemplating offering the user their event picks as a text file download, that also can be uploaded and turned into cookies on another machine. But that is pretty complicated for the user, and thus not perfect.

A: We have a similar system on our site, where users can bookmark pages to a planner/wishlist function. The saved items are sent via a webservice and stored on our server, and there is a corresponding get webservice.
We have a 'lazy register' system. The first time a user saves an item, they are asked for their email (but no password, as nothing is confidential). This is hashed and saved locally using a cookie, then used to set/get the saved items. When the user uses a different computer they are again asked for their email.
The key is that a register and a login are the same operation, so there is no need for any password reminders or any reset functionality.

A: The Google Docs API provides programmatic access to Google Docs, where you can create and store documents and spreadsheets. Your application could have its own Google login, which it uses to create one or more documents per user.  These documents could be used to store the user settings.
Provided you can get a unique ID from each user (an email address, or something more secure, perhaps), this should be fairly simple.  You can even organize the files into folders—one per user.
Alternatively, you could combine Google Docs with the Google Spreadsheets API, where I have just noticed this rather handy feature:

Tables & Records
  Interact with spreadsheets as if they're a database
  using Tables and Records.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React Navigation: Screen not clickable after modal (EDIT: it's a bug) I'm using a transparent modal, but whenever I exit the modal (no matter if I go back or to another page) I can't click anything on the screen anymore. This only happens when I set presentation: 'transparentModal'.
I first thought it's a bug, but I can't find any other people with this issue, so I guess I'm doing something wrong. Do you see anything stupid I'm overlooking?
Navigator Screen:
<Screen
  name="Modal"
  component={Modal}
  options={{
    headerShown: false,
    cardStyle: {backgroundColor: 'rgba(0, 0, 0, 0.15)'},
    cardOverlayEnabled: true,
    presentation: 'transparentModal',
  }}
/>

Component:
const Modal = ({navigation}) => {
  return (
    <View style={styles.container}>
      <Button title="go back" onPress={() => navigation.goBack()} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    maxHeight: (height * 2) / 3,
    backgroundColor: '#30444E',
    borderRadius: 16,
    marginHorizontal: 24,
    marginTop: height * 0.1,
    padding: 24,
  },
});

EDIT: Nevermind, I'm apparently blind. Seems to be a library issue I just didn't look properly. But besides that, if somebody has a clever workaround, I'd appreciate the input.

A: I hope all well with you.
You can use https://www.npmjs.com/package/react-native-modal for this.


text:
Q: How can I force "update-database" when Asp.Net site starts Background
I am working on an existing Asp.Net site that uses Database Migrations and Asp.Net Identity.
The site has a folder "Migrations", with a few database migrations. A while ago, I created a "Seed_Only"-migration that doesn't do anything, but simply - as the name implies - executes the Seed method when called thus:
Update-Database -TargetMigration SeedOnly
Irrelevant of whether it's good practice or not, the Seed method creates new roles if the static helper class RolesName contains any new roles:
// Iterate all properties of RolesName and create roles if they don't exist
Type type = typeof(RolesName);
foreach (var p in type.GetFields())
{
    var v = p.GetValue(null).ToString(); // static classes cannot be instanced, so use null...
    if (!context.Roles.Any(x => x.Name.Equals(v)))
    {
        roleManager.Create(new IdentityRole() { Name = v });
    }
}

The Question
We are about to introduce a couple of new roles. I want to make sure each site that runs the app gets it's database updated upon deploy (we deploy using Octopus).
Goals
The following should happen:

*

*Create new roles if they don't already exist

*Add the new roles to existing users - if the users are member of a previously existing role

This related answer suggests I call Database.SetInitializer(new ApplicationDbInitializer()); from the Constructor of ApplicationDbContext. If I understand the answer correctly, this would solve my need to "continuously keeping the roles up to date", but it does not solve my need for adding existing users to the new roles, as stated in point 2.
How should I go about to achieve my goals?

A: I ended up using the solution suggested here. It consists of:
1. A static class that creates the data needed
public static class LocatorInitializationHandler
{
    public static void Initialize()
    {
        using (var db = new ApplicationDbContext())
        {
            CreateRoles(db);
        }
    }

    private static void CreateRoles(ApplicationDbContext context)
    {
        // iterate role names
        // and insert into db if not already exists
    }
}

2. Call the static class from global.asax.cs
protected void Application_Start()
{
    // Initialize database
    LocatorInitializationHandler.Initialize();
}


text:
Q: Draw grid of circles What would be the best way on iOS to achieve drawing a grid of circles with fixed columns and rows ?. I would want to identify each circle when the user taps on it.
I tried using collection views but it seems CoreGraphics is meant for tasks like these.

A: You can create buttons dynamically as follows :
- (void)drawSheet
{
    int numberOfRow=5;
    int numberOfColumn=4;
    float x = 1,
            y = 20,
            padding = 5,
            width = (self.view.frame.size.width-(padding*(numberOfColumn-1)))/numberOfColumn,
            height = (self.view.frame.size.height-(padding*(numberOfRow-1)))/numberOfRow;
    int counter = 0;
    for (int i=0; i<numberOfRow; i++) {
        for (int j=0; j<numberOfColumn; j++) {
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, 74, 74)];
            btn.layer.cornerRadius = btn.frame.size.width/2;
            btn.layer.borderColor = [UIColor grayColor].CGColor;
            btn.layer.borderWidth = 2.0;
            [btn addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
            btn.clipsToBounds = YES;
            btn.tag = counter;
            [self.view addSubview:btn];
            x = x + width + padding;
            counter = counter + 1;
        }
        x = 0;
        y = y + height + padding;
    }
}

When you tap on it, you will get tag of it :
- (IBAction)buttonPress:(UIButton *)sender{
    NSLog(@"%ld",sender.tag);
}

A: hi Please check the below code. i have added 3 circles in a row, you could use more if you want.
   - (void)viewDidLoad {
        [super viewDidLoad];
        UIView *circleView;
        int x = 10;
        int y = 20;
        static int tagNum = 0;
        for (int row=0; row < 5;) {
            for (int cirNum =0 ; cirNum <3;) {

                circleView = [[UIView alloc] initWithFrame:CGRectMake(x,y,100,100)];
                circleView.alpha = 0.5;
                circleView.layer.cornerRadius = 50;
                circleView.backgroundColor = [UIColor blueColor];
                circleView.tag = tagNum;
                NSLog(@"tagNum is %d", tagNum);
                [self.view addSubview:circleView];

                cirNum ++;
                x = x + 100;
                tagNum ++;
                //y = y + 20;

            }
            row++;
            y = y + 100;
            x = 10;
        }
        // Do any additional setup after loading the view, typically from a nib.
    }

    -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint location = [[touches anyObject] locationInView:self.view];
    CGRect fingerRect = CGRectMake(location.x-5, location.y-5, 10, 10);

    for(UIView *view in self.view.subviews){
        CGRect subviewFrame = view.frame;

        if(CGRectIntersectsRect(fingerRect, subviewFrame)){
            //we found the finally touched view
            //NSLog(@"Yeah !, i found it %@",view);
            NSLog(@"view tag touched is %ld",view.tag);

        }

    }

}

output would look like this


text:
Q: How to get the  separated? I need to split the
 from the rest of the html code to put it in a modal title. The other html part has to go to the modal-body.
I wrote a bootstrap modal and I get the href, but I don't know how to get the html of the href and split it into title and body.
$('.helpicon').click(function() {
    if( $("#helpModal").length == 0) {
        $('body').append('
' +
                '
' +
                    '
' +
                        '
' +
                            '

' +
                            '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
                                '×' +
                            '</button>' +
                        '
' +
                        '

' +
                        '
' +
                            '<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>' +
                        '
' +
                     '
' +
                '
' +
            '
');
        }
        var modalTitle=$(this).attr('href');
        alert (modalTitle);
        $("#helpModal .modal-title').load(    modal title here   )");
        $("#helpModal .modal-body').load(     modal body here    )");
        $("#helpModal").modal();
        return false;
});

I'm thankful for some tips


text:
Q: DocType not visible under Module view I have created two DocTypes inside the education module. I've unchecked the "custom" checkbox to build the js and py files. However, the two DocTypes have not listed inside the education module.
If I check the custom they return to list under setup so how I can list him inside the education module while the custom is unchecked?
another question: I have created a custom script for one of these DocTypes, will I lose the script after unchecked custom !!!
Note: I can find them in the global search

A: For version-12 you'll have to override the get_data under education of the config module. The file for that is here
If you are on the develop branch, as a consequence of the desk refactor you might have to update an additional file, specifically education.json file with your newly created modules.

A: Try Bench Migrate First for Standard DocType


text:
Q: Cost of the government I am supposed to solve the following problem.

The bank provides 1,000 dollars loans. Risk-free clients will repay the loan
  in full for a year, in addition to paying 4% interest. For a high-risk
  client, there is a 30% chance that he will not pay anything and an 70%
  chance that he will repay the loan in full and 30% interest.
Assume that the government has guaranteed to the bank that in the
  event of non-payment of the loan, it will repay the bank's principal,
  that means 1,000$.
What costs will the government have?

So I understand that the cost of the government will be 1,000 dollars, but I do not know with what probability. I should calculate the expected cost.
Can anyone help?

A: The expected cost is of $1000\$\times 0.3\times(\text{number of high-risk clients})$ per year.


text:
Q: Büchi automata with acceptance strategy I have already asked this question on cstheory.stackexchange, but without success. Maybe it is too close to an "open problem", although it is not a famous one. Anyway I try here, I can always remove it if it does not fit MO's policy.
The problem
Let $A=\langle \Sigma, Q, q_0,F,\Delta\rangle$ be a Büchi automaton, recognizing a language $L\subseteq\Sigma^\omega$.
We assume that $A$ has an acceptance strategy in the following sense : there is a function $\sigma:\Sigma^*\to Q$ which can be used to pilot runs of $A$. We formalize this by the following conditions :

*

*$\sigma(\epsilon)=q_0$

*for all $u\in\Sigma^*$ and $a\in\Sigma$, $(\sigma(u),a,\sigma(ua))\in\Delta$

*for all $w=a_0a_1a_2\dots\in L$, the run piloted by $\sigma$ on $w$ is accepting, i.e. the sequence $\sigma(\epsilon),\sigma(a_0),\sigma(a_0a_1),\sigma(a_0a_1a_2),\dots$ has infinitely many elements in $F$.
To subsume the conditions, $A$ can accept any word of its language without having to guess anything about the future.
Then, under these assumptions on $A$, is it true that $A$ can be determinized just by removing transitions ? In other words, can we always choose the next transition depending only on the current state and letter ? Is there any reference on this kind of subject ? The same question can then be asked on co-Büchi automata, and more generally on parity automata.
What is known
Here are some partial results.
First, we can restrict $\sigma$ to nondeterministic choices between states having the same residual. Indeed, if $L(q)$ is the language accepted from $q$, an accepting strategy cannot choose $q_1$ over $q_2$ at some point, if there is $w\in L(q_2)\setminus L(q_1)$.
Notice that the remaining choices do matter, so despite the intuition, this is not enough to get rid of the nondeterminism. This is because it is possible to stay ad infinitum in a good residual (i.e. the remaining of the word is in the residual), but reject the word because not infinitely many Büchi states are seen. This is the main difficulty of the problem : an infinite run can be wrong, without making any fatal mistake at some point.
Second, the problem is solved if $L=\Sigma^\omega$, i.e. all words are accepted by $A$. In this case, we can view $A$ as a Büchi game where Player I chooses input letters and Player II chooses transitions. Then we can use positional determinacy of Büchi games to extract a positional strategy for Player II. This arguments even works in the more general case of parity automata. The difficulty of this problem comes from the fact that some words are not in $L$, and in this case the strategy $\sigma$ can have any behaviour.
Third, here is a proof that under the assumptions, the language $L$ is in the class of deterministic Büchi languages, witnessed by an automaton with states $2^Q$.
Notice that this implies that $L$ cannot be any $\omega$-regular language, for instance  if $L=(a+b)^*a^\omega$, no strategy $\sigma$ matching the conditions can exist.
We start by restricting the transitions according to the first remark : the only choices we can make do not impact on the residual language. We only take successors with the maximum residual, they must exist because $\sigma$ exists.
Then, we build $A'=\langle \Sigma, 2^Q, \{ q_0\},F',\Delta'\rangle$ in the following way. $A'$ is the subset automaton of $A$, but every time a Büchi state $q$ appears in the component, all other states can be removed from the component, and we start again from the singleton $\{ q\}$. Then we can set $F'=\{\{ q\} : q\in F\}$. We can verify that $A'$ is a deterministic Büchi automaton for $L$.
Finally, by putting together the second and the third remarks, we can always obtain a finite-memory strategy $\sigma$, by using a positional strategy for Player II in the game $A\times A'$ where Player I chooses letters, Player II chooses transitions in $A$ and wins if $A$ accepts whenever $A'$ accepts. The goal is to show that there exists a memoryless strategy $\sigma$, instead of just finite-memory.


text:
Q: MySQL: Change compression on an existing InnoDB table Is there any way to turn on compression for an existing table? I don't care if there's downtime for this.
The docs only mention setting compression when the table is created.

A: ALTER TABLE xxx ROW_FORMAT=COMPRESSED


text:
Q: TableAPI SQL left join error "doesn't support consuming update and delete changes which is produced by node Join(joinType=[LeftOuterJoin]..." Need to left join 2 data streams and the Table API throws an exception during starting the Flink app.
It is needed to calculate based on 2 different windows on a same input stream. So eventually the 2 calculated tables/steams need to be joined.
If I use "join" instead of using "left join" the start-up error disappears. Any idea how I can solve it? Is "left join" not supported?
Below is the exception:

org.apache.flink.client.program.ProgramInvocationException: The main method caused an error: Table sink 'default_catalog.default_database.Unregistered_DataStream_Sink_1' doesn't support consuming update and delete changes which is produced by node Join(joinType=[LeftOuterJoin], where=[((userId = userId0) AND (eventEpoch = eventEpoch0))], select=[userId, eventEpoch, AVG_VALUE_A, FIRST_VALUE_B, LAST_VALUE_B, FIRST_EVENTTIME, LAST_EVENTTIME, userId0, eventEpoch0], leftInputSpec=[NoUniqueKey], rightInputSpec=[NoUniqueKey])\n\tat org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:372)\n\tat org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:222)\n\tat

Below is the code snippet.
Table inputTable = tableEnv.fromDataStream(
    inputStream,
  Schema.newBuilder()
      .columnByExpression("rowtime", "CAST(eventTime AS TIMESTAMP(3))")
      .watermark("rowtime", "rowtime - INTERVAL '" + WATERMARK_DELAY_IN_SECOND + "' SECOND")
      .build());

//Register the table for use in SQL queries
tableEnv.createTemporaryView("InputTable", inputTable);

Table resultTable = tableEnv.sqlQuery(
    "SELECT " +
    " userId," +
    " eventEpoch," +
    " AVG(valueA) OVER w1 AS AVG_VALUE_B" +
    " FROM InputTable " +
    " WINDOW w1 AS (" +
    " PARTITION BY userId ORDER BY rowtime" +
    " RANGE BETWEEN INTERVAL '" + INTERVAL_A + "' SECOND PRECEDING AND CURRENT ROW)"
);

Table resultTable2 = tableEnv.sqlQuery(
    "SELECT " +
    " FIRST_VALUE(valueB) OVER w1 AS FIRST_VALUE_B," +
    " LAST_VALUE(valueB) OVER w1 AS LAST_VALUE_B," +
    " FIRST_VALUE(eventEpoch) OVER w1 AS FIRST_EVENTTIME," +
    " LAST_VALUE(eventEpoch) OVER w1 AS LAST_EVENTTIME," +
    " userId, eventEpoch" +
    " FROM InputTable" +
    " WINDOW w1 AS (" +
    " PARTITION BY userId ORDER BY rowtime" +
    " RANGE BETWEEN INTERVAL '" + INTERVAL_B + "' SECOND PRECEDING AND CURRENT ROW)"
);

tableEnv.createTemporaryView("ResultTable1", resultTable);
tableEnv.createTemporaryView("ResultTable2", resultTable2);

Table resultTable3 = tableEnv.sqlQuery(
    "SELECT ResultTable1.*," +
    " ResultTable2.FIRST_VALUE_B," +
    " ResultTable2.LAST_VALUE_B," +
    " ResultTable2.FIRST_EVENTTIME," +
    " ResultTable2.LAST_EVENTTIME" +
    " FROM ResultTable1" +
    " LEFT JOIN ResultTable2" +
    " ON ResultTable1.userId = ResultTable2.userId" +
    " AND ResultTable1.eventEpoch = ResultTable2.eventEpoch"
);


text:
Q: How to modify this query so start/end dates go by days instead of exact times? I'm using the query below to get posts based on the start and end dates which use the UNIX timestamp.
Currently, it's only returning results if the start time occurred after today's time. For example, if it's 5:00 PM and the start date is 6:00 PM, it won't pick it up. I would like it to consider anytime during today (from midnight last night to midnight tonight) as being the start date.
Can someone tell me how to update my code to get this to work?
$current_time is equal to 1305132894, which is 5:54 EST today.
'meta_query'        => array(
    array(
        'key'       => 'start_date',
        'value'     => $current_time,
        'compare'   => '<'
    ),
    array(
        'key'       => 'end_date',
        'value'     => $current_time,
        'compare'   => '>'
    )
)

A: If you only need it to work for today, you can use:
$minDate = strtotime('midnight today');
$maxDate = strtotime('midnight tomorrow -1 second');

or alternatively
$minDate = mktime(0,0,0);
$maxDate = mktime(11,59,59);

Some combination of mktime() and strtotime() should work.

A: Considering your example: $current_time = 1305132894
This should answer your question:
$date_current = date("Y-m-d",1305132894);  //2011-05-11
$date_midnight = strtotime($date_current . "00:00:00"); //1305061200 that means: 2011-05-11 00:00:00

So replace $current time by $date_midnight and you'll have anytime during today from midnight last night.


text:
Q: Best way to modify objects in list using values from another list I have an entity Issue as following :
public class Issue{
    private IssueElementEnum issueElement;
    private IssueTypeEnum issueType;
    private String title;
}

And I have a list of Issue which I get from DAO:
List<Issue> issues = issueDAO.findAll();

In this list I have some Issue object where issue.getIssueElement() == IssueElementEnum.USER, I want to update these object by changing there title field, for that I have to filter the list of issues and create a list of type String from the result list, then I have to pass this list to a service that will return a list of new titles which will be used to replace the old titles.
This is what I tried :
List<Issue> issues = issueDAO.findAll();
List<Issue> userIssues = issues.stream().filter(a -> a.getIssueElement() == IssueElementEnum.USER).collect(Collectors.toList());
List<String> oldTitles = userIssues.stream().map(a -> a.getTitle()).collect(Collectors.toList());
List<User> users = userSVC.findByTitles(oldTitles);
for (User user : users) {
    for (Issue issue : issues) {
        if (user.getKey().equals(issue.getTitle())) {
            issue.setTitle(user.getFirstName() + " " + user.getLastName());
        }
    }
}

Is there any other way to write this ?

A: It's quite hard to follow exactly what's going on here, but there are 2 improvements I can spot.
Firstly, there is no point in userIssues at all (although it seems odd that in the last step you iterate over all issues rather than userIssues. Is this right?). Just do
List<String> oldTitles = issues
                            .stream()
                            .filter(a -> a.getIssueElement() == IssueElementEnum.USER)
                            .map(Issue::getTitle)
                            .collect(Collectors.toList());

Secondly, the nested loops appear unnecessary. I'm not 100% clear on your logic but something like this ought to work.
Map<String, User> usersByKey = new HashMap<>();
for (User user : users)
    usersByKey.put(user.getKey(), user);
for (Issue issue : issues) {
    User user = usersByKey.get(issue.getTitle());
    if (user != null)
        issue.setTitle(user.getFirstName() + " " + user.getLastName());
}


text:
Q: Missing required Permissions manifest attribute in Main JAR When I want to load an Applet on the server, the browser shows:
java.lang.SecurityException: Missing required Permissions manifest attribute in main jar: http://<my server>:9080/ram7.5.2.1/applets/lifecycle.jar
    at com.sun.deploy.security.DeployManifestChecker.verifyMainJar(Unknown Source)
    at com.sun.deploy.security.DeployManifestChecker.verifyMainJar(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager.isAppletTrusted(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager.initAppletAdapter(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:795)
Ignored exception: java.lang.SecurityException: Missing required Permissions manifest attribute in main jar: http://<my server>:9080/ram7.5.2.1/applets/lifecycle.jar

But the problem is I have already put the attribute in the manifest file,like this:
Manifest-Version: 1.0
Created-By: 1.6.0
Permissions: all-permissions
Application-Library-Allowable-Codebase: *
Application-Name: SearchApplet
Caller-Allowable-Codebase: *

I don't want to change the Java Security Level or put the site into the Exception site list.

A: problem solved.
It should add the tags to the manifest file first,but also should add the tags to the  html tag.


text:
Q: Break a string down to ASCII numbers I'm trying to find away to take a string and store it as an array of its ASCII values as ints
ie; string 1 = hello
array 72,69, etc

A: var arr = Encoding.ASCII.GetBytes("Hello");

A: To expand a bit on Henk's comment, a string is already an array of 16-bit integers (shorts), representing each character's Unicode code point (but see below). If your string is composed entirely of "ASCII" (code points below 128), then running the below will produce what you expect:
string s = "hello";
foreach (char c in s)
{
    Console.WriteLine((short)c);
}

104
  101
  108
  108
  111

Use s.ToCharArray() to extract that array and do with it what you will. Note that strings can contain any Unicode character, and your program needs to comprehend that (including the case where a single character needs more than one short to represent it).

A: Do you insist on ASCII encoding (what about all other possible characters)?. If not, i.e. if you want an array of unicode characters I'd suggest using
myString.ToCharArray();

or
myString.ToCharArray().Cast<int>().ToArray();

(the latter if you need int values)


text:
Q: How to load assembly correctly I develop a system with plugins, which loads assemblies at runtime. I have a common interface library, which i share between server and its plugins. But, when i perform LoadFrom for plugin folder and try to find all types, which implement common interface IServerModule i get runtime exception:

The type 'ServerCore.IServerModule' exists in both 'ServerCore.dll'
  and 'ServerCore.dll'

I load plugins like this:
foreach (var dll in dlls)
{
            var assembly = Assembly.LoadFrom(dll);
            var modules = assembly.GetExportedTypes().Where(
                type => (typeof (IServerModule)).IsAssignableFrom(type)
                && !type.IsAbstract &&
                !type.IsGenericTypeDefinition)
                .Select(type => (IServerModule)Activator.CreateInstance(type));
            result.AddRange(modules);
}

How can i deal with this trouble?
I'll be gratefull for any help

A: Inspect the problem DLL and its dependencies.  Chances are good that it is pulling in ServerCore.dll from a different version of .NET than your main application.
I recommend you use MEF if you want to do plugins.

A: Well, my solution is ugly, but works and i'll go forward for MEF in future (maybe). For now, i added such thing:
if(Path.GetFileNameWithoutExtension(dll)==Assembly.GetCallingAssembly().GetName().Name)
    continue;

Thanks everybody for awesome replies
EDIT: I came up to more elegant solution, here it is:
var frameworkAssemblies =
                from file in new DirectoryInfo(frameworkDirectory).GetFiles()
                where (file.Extension.ToLower() == ".dll" || file.Extension.ToLower() == ".exe")
                && !AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetName().Name).Contains(file.GetFileNameWithoutExtension())
                select Assembly.LoadFrom(file.FullName);


text:
Q: How to find distinct values of string columns in hive? HI I have the below scenario where in i have to find the distinct occurrences of a string in a delimited column. Could you please let me know how to do it.
E.g
Table :
Name String,
Email String,
Phone string
address string

Name : A
Email : A@gmail.com##B@gmail.com##A@gmail.com##C@gmail.com
Phone : 123##456##678
Address : 87P Plz##96C Blk##87P Plz

Expected output:
Name : A
Email : A@gmail.com##B@gmail.com##C@gmail.com
Phone : 123##456##678
Address : 87P Plz##96C Blk

Also kindly note that we have a different delimiter ## in our case as we cannot use , as the delimiter


text:
Q: Printing a NULL Terminated String (PCL 5) I have a PCL 5 (Print Command Language) file that I am reading into a textbox and then sending the contents of the textbox to a PCL 5 printer. This has been working great so far, but if the PCL 5 file contains raster data it will always contain a NULL value. When I read a string that contains a NULL character into a textbox, the string is terminated. Thus I end up sending an incomplete PCL file to the printer and it prints garbage print.
    public static class BinaryFile
    {
        private static string[] __byteLookup = new string[256];

        static BinaryFile()
        {
            //CHARACTERS: All Control ASCII Characters
            for (int i = 0x00; i < 0x20; i++) { __byteLookup[i] = ((char)i).ToString(); }

            // Display printable ASCII characters
            for (int i = 0x21; i < 0x7F; i++) { __byteLookup[i] = ((char)i).ToString(); }

            __byteLookup[0] = "\x00";
        }

I have tried changing the _byteLookup[0] to a literal by making it read @"\x00" or @"\0" but this causes the data not to be read by the printer. The printer literally prints out the \0 or \x00. I need to somehow maintain the NULL value without the string being terminated so the printer can properly interpret the data. Is this possible?


text:
Q: Set alternative URL link address I want to put a "short" URL (without http://) in my document: something like \url{google.com}. But if I do that, the link does not work (it tries to link locally, and does not recognize it as a web address).
I also tried \href{http://google.com}{google.com}, which links correctly, but shows "google.com" in standard font instead of the nice URL monospaced font. I could do \href{http://google.com}{\texttt{google.com}} to get the monospaced font, but other things like URL wrapping don't work.
Is there some way that I can have the link work, and have the URL formatted nicely?
Also, apologies if this has already been asked. It seems like it must have been asked before, but I couldn't find an answer anywhere.

A: The \nolinkurl command can be used to format a URL without creating a link. This can be combined with \href to get the desired effect:
\href{http://google.com}{\nolinkurl{google.com}}

This duplicate issue shows the specific case when only the "http://" has been omitted (thanks @Werner for finding this).


text:
Q: Writing values in serial fails to update immediately I am trying to write many values into the create-io DB using a python script.
Since crate does not support an auto-incrementer for fiels like ID, I query the last ID and use (+1) for the next one.
However, when I send a "insert into..." command, the data is not written immediately. So even if I close the connection and call

select count(id) from mytable

I still receive the old id counter.
For now, I am forced to use

time.sleep(0.5)

after each insert, which is "not good" .
Can someone guide me here into a direction?
Thanks alot!

A: CrateDB is eventual consistent (https://crate.io/docs/reference/en/0.54.4/storage_consistency.html) but provides e.g. read-after write consistency.
so if you query a document by its primary key - it will be immediately available.
if this is not enough or you can't query by primary key you can issue the REFRESH TABLEcommand - but this comes at a performance penalty.


text:
Q: hweb no templates found on Ubuntu I recently upgraded mercurial on my server and now I'm getting the following errors for my hgweb.cgi script. When I google for it I only find setup tutorial for windows machines talking about templates and even they don't specify where to get templates. Can someone help me get my server running again?
[Thu May 28 08:06:42 2015] [error] [client 213.135.239.28] (13)Permission denied: exec of '/var/www/mercurial/htdocs/hgweb.cgi' failed
[Thu May 28 08:06:42 2015] [error] [client 213.135.239.28] Premature end of script headers: hgweb.cgi
[Thu May 28 08:07:02 2015] [error] [client 213.135.239.28] (13)Permission denied: exec of '/var/www/mercurial/htdocs/hgweb.cgi' failed
[Thu May 28 08:07:02 2015] [error] [client 213.135.239.28] Premature end of script headers: hgweb.cgi
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28] Traceback (most recent call last):
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]   File "/var/www/mercurial/htdocs/hgweb.cgi", line 19, in <module>
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28] wsgicgi.launch(application)
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]   File "/usr/lib/pymodules/python2.6/mercurial/hgweb/wsgicgi.py", line 76, in launch
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28] content = application(environ, start_response)
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]   File "/usr/lib/pymodules/python2.6/mercurial/hgweb/hgwebdir_mod.py", line 153, in __call__
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28] return self.run_wsgi(req)
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]   File "/usr/lib/pymodules/python2.6/mercurial/hgweb/hgwebdir_mod.py", line 183, in run_wsgi
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28] tmpl = self.templater(req)
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]   File "/usr/lib/pymodules/python2.6/mercurial/hgweb/hgwebdir_mod.py", line 435, in templater
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28] style, mapfile = templater.stylemap(styles, self.templatepath)
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]   File "/usr/lib/pymodules/python2.6/mercurial/templater.py", line 761, in stylemap
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28] raise RuntimeError("No hgweb templates found in %r" % paths)
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28] RuntimeError
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28] :
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28] No hgweb templates found in []
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28]
[Thu May 28 08:10:01 2015] [error] [client 213.135.239.28] Premature end of script headers: hgweb.cgi

A: After a lot of searching:
Add the following to your hgweb.config file:
[web]
templates = /usr/share/mercurial/templates


text:
Q: Tried to import _mysql through MySQLdb and get the error I'm trying to use MySQLdb and when I try to import it I get the following error. Any thoughts? I'm currently using an ubuntu instance on aws.
 >>> import MySQLdb
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/pymodules/python2.6/MySQLdb/__init__.py", line 19, in <module>
        import _mysql
    ImportError: libmysqlclient_r.so.16: cannot open shared object file: No such file or directory
 >>>

A: Is libmysqlclient-dev installed? Package might not be exact, but thats the general idea.

A: Is this comment thread of any help?
Try updating /etc/ld.so.conf so as to include the directory in which you've installed this.

A: After struggling with this same issue myself (on the AWS Linux I AMI), I found the answer
here:
While the comment thread already posted was helpful, Apache was clearing my environment variables, so setting LD_RUN_PATH and/or LD_LIBRARY_PATH was not effective.
What ended up working was adding a new include statement to /etc/ld.so.conf and running ldconfig.


text:
Q: Components I used to draw a form won't appear after compile I'm trying to create a chat program in java but I had a problem when I run the server form, that the components I used to draw won't appear.
this is the code I used in the run of the form :
public void run() {

                Server s = new Server();
                s.setVisible(true);

                // Etablir la connexion
                try
        {
            ServerSocket ecoute;
            ecoute = new ServerSocket(1111);
            Socket service = null;
            System.out.println("Serveur en attente d'un client !");
            while(true)
            {

                service = ecoute.accept();
                System.out.println("Client connécté !");
                DataInputStream is = new DataInputStream(service.getInputStream());
                                s.jTextArea1.setText("Client dit : " + is.readUTF().toUpperCase());
                service.close();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();

        }
            }

A: You said nothing happens when this code is ran. The presence of a public void run() method tells me that this is a thread, or at least a Runnable.
Because of the while(true), if this thread is not started in the proper manner, it will not run independently; that is it will hold up the entire program.
Instead of calling thread.run();, call thread.start();. This will call the run method for you, after starting a new thread that will run in parallel to the main thread.
If this code is not in a thread, and you just used public void run() by chance, then it will still provide the same problem for you.
For more information, refer to the Documentation on Threads


text:
Q: You must supply a layout_height attribute error in android listview i have an adapter for list view . every row in it has two textview , my problem when compile the project  this error appear to me in log cat
java.lang.RuntimeException: Binary XML file line #8: You must supply a layout_height attribute.
this is my adapter
 public class ArticlesAdapter extends BaseAdapter {

    private ArrayList<ArticlesBean> arr;
    private LayoutInflater inflater;
    private ImageLoader mImageLoader;
    private String mytitle, myldesc;

    public ArticlesAdapter(Context context, ArrayList<ArticlesBean> arraylist) {
        this.arr = arraylist;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        mImageLoader = new ImageLoader(context);

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return arr.size();

    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return arr.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View v, ViewGroup parent) {

        ViewHolder holder = null;
        if (v == null) {

            v = inflater.inflate(R.layout.list_items, null);
            holder = new ViewHolder();

            holder.title = (TextView) v.findViewById(R.id.ltitle);
            holder.ldesc = (TextView) v.findViewById(R.id.ldesc);

            v.setTag(holder);

        } else {
            holder = (ViewHolder) v.getTag();
        }

        v = inflater.inflate(R.layout.list_items, null);
        holder.title = (TextView) v.findViewById(R.id.ltitle);
        holder.ldesc = (TextView) v.findViewById(R.id.ldesc);

        mytitle = arr.get(position).getTitle();
        myldesc = arr.get(position).getBody().substring(0, 45)
                .replace("\n", " ");

        Log.e("myldesc", myldesc);
        Log.e("mytitle", mytitle);

        holder.title.setText(mytitle);
        holder.ldesc.setText(myldesc);

        return v;
    }

    static class ViewHolder {

        public TextView title;
        public TextView ldesc;

    }

    public void refresh(ArrayList<ArticlesBean> items) {
        // TODO Auto-generated method stub
        arr.addAll(items);
        notifyDataSetChanged();
        // notifyDataSetChanged();
    }

}

this is my xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/ltitle"
        android:layout_width="match_parent" />

    <TextView
        android:id="@+id/ldesc"
        android:layout_width="match_parent" />

</LinearLayout>

A: Try this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/ltitle"
        android:layout_width="match_parent"
        android:layout_height ="wrap_content" />

    <TextView
        android:id="@+id/ldesc"
        android:layout_width="match_parent"
        android:layout_height ="wrap_content" />

</LinearLayout>

You forgot to add a layout_height in your xml.


text:
Q: psql login issues in docker entrypoint.sh script #!/bin/sh

until nc -vz postgresql 5432 &>/dev/null; do
    sleep 1
done

if [ "$( psql -h postgresql -U postgres -w -tAc "SELECT 1 FROM pg_database WHERE datname='devdb'" )" = '1' ]
then
    echo "Database already exists"
else
     echo "Running db creation & init routines"
fi

exec "$@"

I have two containers 1. postgresql 2. graphql service (both are alpine based)
I have the above script (shortened) in my entrypoint.sh which is called as part of the graphql service's dockerfile. When I run the container in docker-compose, I get the error as
dss-graphql                 | psql: fe_sendauth: no password supplied

I have set the PGPASSWORD in the postgresql container. (also set the POSTGRES_PASSWORD just and added measure).
I can run the command psql command inside the container and get the result as 1. When the same is run from entry point script it says psql: fe_sendauth: no password supplied
Any ideas about this behavior ? copying/including the postgresql docker image entrypoint.sh is not something I want to do.
version: "3.7"
services:

  # postgresql
  postgresql        :
    container_name  : postgresql
    hostname        : postgresql
    image           : postgres:10-alpine
    volumes         :
                    - /var/lib/postgres/data
    networks        :
                    - backend
    ports           :
                    - 5432:5432
    restart         : on-failure
    env_file        :
                    - database.env
  # dss-graphql
  dss-graphql             :
    container_name        : dss-graphql
    hostname              : dss-graphql
    build                 :
      dockerfile          : dss-graphql.dev.dockerfile
      context             : ${PWD}/dss-graphql
    image                 : dss-graphql
    volumes               :
                          - ${PWD}/dss-graphql:/dss-graphql
                          - /usr/local/bundle
    networks              :
                          - backend
    ports                 :
                          - 3016:3000
    tty                   : true
    stdin_open            : true
    depends_on            :
                          - postgresql
networks  :
  backend :
    driver: bridge

database.env contains
POSTGRES_DB=devdb
PGUSER=postgres
PGPASSWORD=secret
POSTGRES_USER=postgres
POSTGRES_PASSWORD=secret
``

A: You may want to try to add an environment section in your dss-graphql container, and include - PGPASSWORD: "secret"
Another option would be to create a .pgpass file and have it copied to your dss-graphql container
In short, you define the user/password in your postgresql container, but you don't seem to tell the dss-graphql container how to log in to the database, so it seems that you need to add that either as 1) an environment variable, 2) a password file (.pgpass), or 3) a parameter in some dss-graphql config (which I'm not very familiar with--sorry!)
More information about .pgpass can be found in the documentation


text:
Q: How to get List as parameter in action in ASP.NET Core MVC I have a class which its name is "Question.cs" and I have another one that its name is "Answer.cs".
I want to send List of Questions to my action instead of one Question and I don't know how can I do it.
In fact, I don't know how to get the Questions as parameter. Can anyone tell me how I can receive the Questions in the action?
Here are my classes:
public class Question
{
    [Key]
    public int QuestionId { get; set; }

    [Required]
    [MaxLength(500)]
    public string QuestionTitle { get; set; }

    [Required]
    [MaxLength(500)]
    public string QuestionAnswer { get; set; }

    //property
    public List<Answer> Answers { get; set; }
}

public class Answer
{
    [Key]
    public int AnswerId { get; set; }
    [Required]
    public int QuestionId { get; set; }
    [Required]
    [MaxLength(500)]
    public string AnswerTitle { get; set; }

    //property
    [ForeignKey("QuestionId")]
    public Question Question { get; set; }
}

This is my Razor View (Question.cshtml) :
@using GameShop.Data.Domain.QuestIonsAnswers
@model List<GameShop.Data.Domain.QuestIonsAnswers.Question>
@{
    Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
}
<form asp-action="Index" method="POST">
    @foreach (var item in Model)
    {

@item.QuestionTitle

        <input asp-for="@item.QuestionAnswer" Value="@item.QuestionId" />

    }
    <input type="submit" class="btn btn-primary" value="ثبت">
</form>

As you see, I used a foreach loop which is give me all of the "Questions". So I can't receive just one "Question" in my action. These are my actions:
public IActionResult Index()
{
    return View(_context.Questions.ToList());
}

[HttpPost]
public IActionResult Index(Question question)
{
    foreach (var item in question)
    {
        var ans=new Answer(){
            QuestionId=item.QuestionId,
            AnswerTitle=item.QuestionAnswer
        };
        _context.Answers.Add(ans);
        _context.SaveChanges();
    }
    return View(_context.Questions.ToList());
}

I think I have to get List<Question> in my second action but I don't know how?
Can anyone help me step by step?

A: Please refer to the following steps to modify your code:

*

*In the View page, use for loop to loop through the Model and display the value. code like this:
 @model List<WebApplication6.Models.Question>

 @{
     ViewData["Title"] = "Index";
     Layout = "~/Views/Shared/_Layout.cshtml";
 }

Index

 <form asp-action="Index" method="POST">
         @for (var i = 0; i < Model.Count(); i++)
         {

@Model[i].QuestionTitle

             <input asp-for="@Model[i].QuestionId" type="hidden" />
             <input asp-for="@Model[i].QuestionTitle" type="hidden" />
             <input asp-for="@Model[i].QuestionAnswer" />

         }
     <input type="submit" class="btn btn-primary" value="ثبت">
 </form>

*In the Post method, change the parameter data type to List<Question>.
 [HttpPost]
 public IActionResult Index(List<Question> questions)
 {
     foreach (var item in questions)
     {
         //var ans = new Answer()
         //{
         //    QuestionId = item.QuestionId,
         //    AnswerTitle = item.QuestionAnswer
         //};
         //_context.Answers.Add(ans);
         //_context.SaveChanges();
     }
     return View(_context.Questions.ToList());
 }

Then, the result like this:


text:
Q: restrict duplicate entry,iphone HI All,
i am inserting , say name to sqlite, than showing it on tableview.
But i want say restrict user to insert duplicate name.
for first time  data gets inserted perfectly, but when i insert it on second time, it again get inserted, thats what i want to prevent.
HOw can i check if the value 'name' already exist in sqlite and show alert to tell user that this value already exist.
edited
i have an array abc , having few values., values in array i am adding from another view, now say if abc contains value "a1", now if i again inserting "a1", it should not except "a1", in a way how i can restrict an array to add duplicate value.
regards

A: Use unique constraint in your SQL database.  Here's a link with some basics on it.  Here's some specifics on how to create table with unique contraints with SQLite.
To alert users, just capture the error message from your SQL query and then output as needed.
Edited (for new question):
Easiest way is to parse through the array and do duplicate checks.  There's logic out there for faster searching but if you have a small array, then all you really need is a for loop that iterates through each array element and checks that the new value you are adding is not already there.


text:
Q: Calculate avg in MongoDB with missing values I'm currently developing an node application that gathers information in intervals and saves them in MongoDB. Not every data set is received for each interval run, thats why only some of the data sets will get a new entry.
I have data that is structured like so:
{
  dataSet1: {
    entries: [
      {run: 3, score: 5},
      {run: 4, score: 3},
      {run: 7, score: 11},
      {run: 10, score: 4},
    ]
  },
  dataSet2: {...}
}

I want to get the average score for each data set. The run attribute is auto incremented and indicates in which iteration the score was taken. Missing runs shall count as 0 score. I also have the information about the last run number, so there can also be 0 score values after the last entry of a data set. For example if the current run is 12 then two 0 score values for run 11 and 12 need to be additionally considered for dataSet1.
Of course I could store such missing values as 0 in MongoDB. But every run might only have few data sets to update. Updating all data sets with empty values increases storage and performance a lot.
Is there any way to let MongoDB calculate the average score considering the missing entries?


text:
Q: Initializing generics in Java Suppose I have a class called NodeList with two fields, called value (type Object) and index (type int). NodeList implements an interface called Copiable, with a single method called copyNotSyncronized().
I want the NodeList version of copyNotSincronyzed() to recognize if this.value implements Copiable and, if that happens:

*

*Use copyNotSincronyzed() on this.value and...

*...build a new NodeList object that have this.value.copyNotSincronyzed() as field value.

I tried to write the code and drown in red underlining. After that I know two things: my Eclipse really hate me and I still have to undestand how to use generics in Java.
What mistakes did I do?
public class NodeList implements Copiable {

    int index;
    Object value;

public NodeList(Object value, int index){
[...]
}

NodeList copyNotSincronyzed(){
  NodeList copied;
  if(  onArray.findPositionsOfElement(this.value.getClass().getInterfaces() , this.getClass().getInterfaces()[0])[0] !=-1   )
     // aka if this.value implements the same interface of this class (aka Copiable)
     {
// Following line features three errors:
   // Incorrect number of arguments for type Class<T>; it cannot be parameterized with arguments <T, Copiable>
   // T cannot be resolved to a type
   // Syntax error on token "implements", , expected
     Class<T implements Copiable> copiedObject = this.value;

     copiedObject=copiedObject.copyNotSincronyzed();
     copied = new NodeList( copiedObject , this.index );
     }
   else copied = new NodeList(this.value, this.index);

   }

}

A: this.value is of type Object. And you are trying to put it into a type Class<T implements Copiable>. The compiler does not know how to do that so you are getting a compilation error.
In order to make this check you should use the instanceof operator, combine with a cast, like this:
if (this.value instanceof Copiable){ // check that the instance implements an interface
    Copiable asCopiable = (Copiable)this.value; // safely cast to the appropriate type
}

Note that your problem does not have anything to do with generics.

A: An interface is a type, like a class. Therefore, when another class implements it, any object of that class can be used polymorphically as that interface.
Which means that you can check if that object implements that interface simply by using x instanceof Y. It's an operator that tells you whether x "is a" Y, and Y can be either a class or an interface.
Once you established that your object implements the type, you can cast it into the type of the interface using parentheses.
For the code itself I refer you to the answer given by Vitaliy.

A: Java has an interface Clonable that lets you clone unlinked (unsynchronized) objects through a method Object clone(). There is a lot of controversy around this and the bottomline is that it's discouraged.
A widely accepted way of creating copies of objects is by using a copy-constructor. This will not work for general Object since you don't know the run-time class in advance. In this case Clonable-like structure may still prove useful.
Because Clonable is legacy, it doesn't have generics. Let's make Copyable as a replacement for Clonable (and rename clone() as copyNotSyncronyzed())
public interface Copyable<T> {
    T copyNotSyncronyzed();
}

public class NodeList implements Copyable<NodeList> {
    private int     index; // make final too unless you plan to change it at some point
    private Object  value; // make final too unless you plan to change it at some point

    public NodeList(final Object value, final int index) {
        this.value = value;
        this.index = index;
    }

    @Override
    public NodeList copyNotSyncronyzed() {
        if (value instanceof Copyable) {
            Object copiedObject = ((Copyable<?>)this.value).copyNotSyncronyzed();

            return new NodeList(copiedObject, this.index);
        } else
            return new NodeList(this.value, this.index);
    }
}

The last question is if you are really happy with this structure, as it copies linked value instances if they are not Copyable. This can potentially create dangerous situations since code calling copyNotSyncronyzed() may expect it to be comppletely unrelated to the original.
For example, if value is an int[]. You create a copy using copyNotSyncronyzed(), then you change some values in the array, and lo and behold, the values in the array of the original object are changed too.


text:
Q: Exec_bad iphone..program terminates I developed one small application in objective c++ program uses socket connection from server.so I performed status of socket like(connecting , connected,failed to make connection). In that I have 2 display option onw with activity indicator another with uilabel to tell what happen to socket or status of socket but only uiactivity indicator is working well.If I put label.text=@"something",it just goes error.

A: Have you made sure that you've hooked up all the Interface Builder things correctly with the label?


text:
Q: Multiple arguments not working I am trying to make a simple function which is supposed to create 3 directories. It only creates one and i do not understand why it is so.
The code i wrote is:
#!/usr/bin/env python
# -*- coding: utf-8

import os
from os.path import exists, splitext

def make_dir(*dirs):
    for directory in dirs:
        if not os.path.exists(directory):
            return os.makedirs(directory)
        else:
            print "la carpeta %s ya existe" %(directory)

make_dir("hola", "que", "tal")

When running the function it returns only the first directory "hola"
Any help?

A: you return from the function, thus it never goes on to create the subsequent files. remove the return statement


text:
Q: No ICE candidates generated when I run my local webRTC application on google chrome browser I have a basic webRTC application that supports video/audio communication and file sharing between two peers, The app runs as intended when I open it on Mozilla Firefox but when I run it on Google Chrome the onicecandidate returns null
My RTCPeerConnection
        myConnection = new RTCPeerConnection();

Setting up the peer connection
myConnection.createOffer().then(offer => {
    currentoffer = offer
    myConnection.setLocalDescription(offer);
})
    .then(function () {
        myConnection.onicecandidate = function (event) {
            console.log(event.candidate);

            if (event.candidate) {
                send({
                    type: "candidate",
                    candidate: event.candidate
                });
            }
        };
        send({
            type: "offer",
            offer: currentoffer
        });
    })
    .catch(function (reason) {
        alert("Problem with creating offer. " + reason);
    });

On Mozilla Firefox you can see in the console log all the ICE candidates that are collected on each "onicecandidate" event

On Chrome the output is null

A: You should pass options object when calling createOffer() method, e.g.:
myConnection = new RTCPeerConnection();

var mediaConstraints = {
    'offerToReceiveAudio': true,
    'offerToReceiveVideo': true
};

myConnection.createOffer(mediaConstraints).then(offer => {
        currentoffer = offer
        myConnection.setLocalDescription(offer);
    })
    ...// the rest of you code goes here

Alternatively, you can specify RTCRtpTransceiver before creating an offer:
myConnection = new RTCPeerConnection();

myConnection.addTransceiver("audio");
myConnection.addTransceiver("video");

myConnection.createOffer().then(offer => {
        currentoffer = offer
        myConnection.setLocalDescription(offer);
    })
    ...// the rest of you code goes here

Sources:WebRTC 1.0MDN RTCPeerConnection.createOffer()MDN RTCPeerConnection.addTransceiver()Example -- GitHub

A: You have to pass STUN/TURN servers when create a peer connection.
Otherwise you will only local candidates and hence will be able to connect locally only
var STUN = {
    'url': 'stun:stun.l.google.com:19302',
};

var iceServers =
{
    iceServers: [STUN]
};

var pc = new RTCPeerConnection(iceServers);


text:
Q: turn this jquery into an if/else statement I have this snippet below and I';m trying to make it an if/else statement and I'm getting syntax errors...
<!--script for changing Number of Columns-->
$(window).load(function(){
var idx = $('select[name="numNames"]').children('option:selected').index();
if (idx < 7){
$('.oneColumn').click(function() {
$('.IH_pINameRow').removeClass("floatLeft ");
$('.IH_pINameRow').addClass("floatNone ");
$('.odd').removeClass("leftMargin");
$('.even').removeClass("rightMargin ");
$('.pI_nameText').removeClass("textAlignLeft textAlignRight");
$('.pI_nameText').css('font-size', '2em');
$('.pI_nameText').addClass("1col");
$('.pI_nameText').removeClass("2col");
$('label.twoColumn').css('background-position', '-104px -52px');
$('label.oneColumn').css('background-position', '-104px -26px');
} else {
    return false;
}
}); //error is here//
if (idx > 3){
$('.twoColumn').click(function() {
$('.IH_pINameRow').removeClass("floatNone ");
$('.IH_pINameRow').addClass("floatLeft ");
$('.odd').addClass("leftMargin");
$('.even').addClass("rightMargin ");
$('.pI_nameText').css('font-size', '1em');
$('.pI_nameText').removeClass("1col");
$('.pI_nameText').addClass("2col");
$('.odd').removeClass("textAlignLeft");
$('.even').removeClass("textAlignRight");
$('.even, .odd').addClass("textAlignCenter");
$('label.twoColumn').css('background-position', '-104px -26px');
$('label.oneColumn').css('background-position', '-104px -52px');
$('label.leftAlignment').css('background-position', '-104px -52px');
$('label.centerAlignment').css('background-position', '-104px -26px');
} else {
    return false;
}
});
});

I'm also not sure if the code scope is correct such that the idx variable is available to the second function...

A: Let's break this into bare parts, and fix the indentation. Then use some static analysis to compact the if statements.
<!--script for changing Number of Columns-->
$(window).load(function(){

  function oneColumnClick() {
    $('.IH_pINameRow').removeClass("floatLeft ");
    $('.IH_pINameRow').addClass("floatNone ");
    $('.odd').removeClass("leftMargin");
    $('.even').removeClass("rightMargin ");
    $('.pI_nameText').removeClass("textAlignLeft textAlignRight");
    $('.pI_nameText').css('font-size', '2em');
    $('.pI_nameText').addClass("1col");
    $('.pI_nameText').removeClass("2col");
    $('label.twoColumn').css('background-position', '-104px -52px');
    $('label.oneColumn').css('background-position', '-104px -26px');
  }

  function twoColumnClick() {
    $('.IH_pINameRow').removeClass("floatNone ");
    $('.IH_pINameRow').addClass("floatLeft ");
    $('.odd').addClass("leftMargin");
    $('.even').addClass("rightMargin ");
    $('.pI_nameText').css('font-size', '1em');
    $('.pI_nameText').removeClass("1col");
    $('.pI_nameText').addClass("2col");
    $('.odd').removeClass("textAlignLeft");
    $('.even').removeClass("textAlignRight");
    $('.even, .odd').addClass("textAlignCenter");
    $('label.twoColumn').css('background-position', '-104px -26px');
    $('label.oneColumn').css('background-position', '-104px -52px');
    $('label.leftAlignment').css('background-position', '-104px -52px');
    $('label.centerAlignment').css('background-position', '-104px -26px');
  }

  var idx = $('select[name="numNames"]').children('option:selected').index();
  if (idx < 7){
    $('.oneColumn').click(oneColumnClick);
    if (idx > 3){
      $('.twoColumn').click(twoColumnClick);
    }
  }
});

A: First of all: Please indent your code, otherwise it's really hard to find any errors.
Where is the error?
You have to close $('.twoColumn').click(function() { before the if (idx > 3){, but if opens before the click function.
Why did you make that error?
You do not make these kinds of errors when you indent your code correctly. I was so kind and did this for you: http://jsfiddle.net/7snmR/ < Looks weird, right?


text:
Q: where i miss the semicolon? I have this code:
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        WebView webview=(WebView) findViewById(R.id.webView);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("file:///android_asset/1.html");
        @JavascriptInterface
                public void showToast(String areaName){
            Toast.makeText(mContext, "You clicked on "+areaName, Toast.LENGTH_SHORT).show();
        }
    }

and when I run my code, i get 2 error:

Error:(25, 38) java: ';' expected
Error:(25, 54) java: ';' expected

and when i click on the errors, courser goes on this parts:
        public void showToast(String areaName){

but i cant find out where i miss semicolon.
can some one give me a light?:)

A: Use this
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    WebView webview=(WebView) findViewById(R.id.webView);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.loadUrl("file:///android_asset/1.html");

}

@JavascriptInterface
            public void showToast(String areaName){
        Toast.makeText(mContext, "You clicked on "+areaName, Toast.LENGTH_SHORT).show();
    }

You can't create method within another method

A: You are declaring a method inside of another one.  Separate the two like so:
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        WebView webview=(WebView) findViewById(R.id.webView);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("file:///android_asset/1.html");
    }

  @JavascriptInterface
                public void showToast(String areaName){
            Toast.makeText(mContext, "You clicked on "+areaName, Toast.LENGTH_SHORT).show();
        }

A: You are trying to define method within a method which is not allowed.
So if you close onCreate method just before your annotation @JavascriptInterface and remove ending brace bracket it would work.


text:
Q: Is there a way to use Mapbox GL JS for Free? I am hosting my own map tiles on my server. Is there a way to use Mapbox GL JS completely for free or do I have to pay for it anyway, when I am using the framework? Their website is a bit contradictive, on the one hand they have a pricing on the other hand they say it is an open source project, which is free. So I am confused.

A: Since version 2.0, Mapbox gl js is no longer open source
However there are two open source forks of Mapbox GL libraries:

*

*For javascript Maplibre GL JS

*For Android and iOS Maplibre GL Native

A: Mapbox-GL-JS is completely free, up to version 1.13 (as in free beer, and also as in free speech). However, the Mapbox styles (and their associated resources, such as glyphs and sprites) are not, so you will need to find an alternative source, such as Maptiler for those.
From version 2.0 it is different. Any use of the Mapbox GL JS library consumes API credits, which are "free as in beer" up to a certain point, then paying. The source code is proprietary, open source (as in you can browse it) but not free (you are very limited in what you can do with it).


text:
Q: Count spaces for each line Hi I'm writing a program in which the program reads lines from a text file and then it outputs the size of each line and also how many spaces are in every line. I'm having trouble with the second part with spaces, when it finds a space it just keeps that number and outputs it for every line below. So I would like to know how can I set the counter back to 0. This is my code:
if(myfile.is_open()) {
    while(!myfile.eof()) {

        i++;
        getline(myfile,line);
        strcpy(ch, line.c_str());
        r=r+line.length();

        for(int j=0; j<line.size(); j++) {
            if(line[j]==' ') {
                status = true;
                n++;
            } else {
                n = 0;
            }
        }

        std::cout << i << ". " << ch << " -- " << " (" << line.size() << ") " << " number of spaces: " << n << std::endl;
    }
}

A: Well, just change your for-loop:
n = 0; // After each line
for(int j=0; j<line.size(); j++)
{
    if (line[j] == ' ') n++;
}