text:
Q: Как по клику перезагрузить страницу? У меня есть страница на которой имеется блок сразными чекбоксами
и у меня возникает иногда необходимость сбросить чекбоксы, и я решил чтобы не искать все включенные чекбоксы и не снимать галки можно просто перезагрузить страницу.
Я подумал что мне нужна кнопка по клику на которую страница перезагружалась
Но не пойму как прописать код, единственное что смог это добавить кнопку
document.querySelectorAll('.woosb-products').forEach(n => {
  n.insertAdjacentHTML('afterend', '<button id="my_s" >click me</button>');
});

а как вот сделать чтоб страница перезагружалась ПРИ КЛИКЕ, ..... неразберусь, непойму, гуглиние чето мне не помогло, найденые примеры не работают..
Как по клику перезагрузить  страницу полностью разобрался
document.querySelectorAll('.woosb-products').forEach(n => {
  n.insertAdjacentHTML('afterend','<button id="something" >Перезагрузить</button>');
});
$('#something').click(function() { location.reload();
});

... а  как перезагрузить только блок class="myDiv" без полной перезагрузки страницы -если это возможно...?

ПО КЛИКУ ...

A: Все куда проще, даже без js можна сделать:

<form id="form" action="">
    <input id="checkbox1" type="checkbox">
    <input id="checkbox2" type="checkbox">
    <input id="checkbox3" type="checkbox">
    <input id="checkbox4" type="checkbox">
    <input id="checkbox5" type="checkbox">
    <input id="checkbox6" type="checkbox">
    <input id="checkbox7" type="checkbox">
    <input id="checkbox8" type="checkbox">

    <input id="reset__button" type="reset">
</form>

A:
И я решил чтобы не искать все включенные чекбоксы и не снимать галки можно просто перезагрузить страницу.

Зря,

let cb = document.querySelectorAll('#your-box [type="checkbox"]');

document.querySelector("#btn").addEventListener("click", function() {
  cb.forEach(e => e.checked = false);
});
<button id="btn">reset</button>

  <input type="checkbox">
  <input type="checkbox" checked>
  <input type="checkbox" checked>
  <input type="checkbox">
  <input type="checkbox" checked>
  <input type="checkbox">
  <input type="checkbox">
  <input type="checkbox" checked>

Чудо-метода перезагрузки конкретного блока не существует (кажется о_О).
Также, можно заключить всё в тег <form> и воспользоваться его встроенным методом form.reset(). Только, он приводит форму в исходное состояние, а не отключает чекбоксы. Т.е. если какие-то были включены по умолчанию, они останутся включенными.


text:
Q: restricting user to go back after logout not working I have created webapplication using JSF 2.0 where I want to restrict user to go back after logout.
For solution I looked at Great BalusC answer and tried something else, however it is not working.
What I tried is as below.
<h:commandLink value="logout" action="#{bean.makeMeLogut()}" />

in bean I have
public void makeMeLogut() {
    try {
        // get response from JSF itself instead of coming from filter.
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("isLoggedIn", "false");
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        HttpServletResponse hsr = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        hsr.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        hsr.setHeader("Pragma", "no-cache"); // HTTP 1.0.
        hsr.setDateHeader("Expires", 0); // Proxies.
        FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
    } catch (IOException ex) {
        System.out.println("can't logut...");
    }
}

As per BalusC answer, I need to create filter, however I thought to use JSF response and set header into it. However it is not working.
Any idea where I am going wrong?

A: You're not setting those headers on the response of the restricted page itself, but you're only setting those headers on the response of the logout action. So the restriced page itself is still in the browser cache, only the logout action is not in the browser cache. However, the back button does not go to the logout action, it goes to the restricted page (which is thus still served up from the browser cache).
You really need a filter on all requests to those restriced pages, exactly as outlined in the answer you found.
See also:

*

*Avoid back button on JSF web application

*javax.faces.application.ViewExpiredException: View could not be restored

Unrelated to the concrete problem, manipulating the session map right before invalidate makes no sense. The session invalidation would implicitly already clear out the entire map (as it basically refers to the attributes of the session). Just remove the line wherein you manpulate the session map.
Also the catch on IOException which does only a stdout is extremely poor. Remove the whole try-catch and add throws IOException to the method. The container will handle it with an error page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I fix this problem where my "delete_at" dosen't work on numbers above 20 (or 20)? The problem I have is that the "delete_at" method dosen't remove numbers over 20. Why I think it's especially over 20 is because of the troubleshooting I did below. I'm trying to make a sorting algorithm that sort an array of numbers from smallest to biggest. I want to do it without premade methods.
What my code look like
unsorted_list = [20, 21, 40, 10, 18, -20, 100]
sorted_list = []

def index_of_smallest(array)
    i = 0
    small = array[0]
    while i < array.length
        if array[i] < small
            small = i
        end
        i += 1
    end
    return small
end

while unsorted_list.length > 0
    sorted_list << unsorted_list.delete_at(index_of_smallest(unsorted_list))
end

TroubleShooting
    unsorted_list = [20, 21, 40, 10, 18, -20, 100]
sorted_list = []

def index_of_smallest(array)
    i = 0
    small = array[0]
    while i < array.length
        if array[i] < small
            small = i
        end
        i += 1
    end
    return small
end
puts "Before: #{unsorted_list.length}"

unsorted_list.delete_at(index_of_smallest(unsorted_list))

puts "After: #{unsorted_list.length}"

puts "--------------------------------------------------------------"

puts "Before: #{unsorted_list.length}"

unsorted_list.delete_at(index_of_smallest(unsorted_list))

puts "After: #{unsorted_list.length}"

puts "--------------------------------------------------------------"

puts "Before: #{unsorted_list.length}"

unsorted_list.delete_at(index_of_smallest(unsorted_list))

puts "After: #{unsorted_list.length}"

puts "--------------------------------------------------------------"

puts "Before: #{unsorted_list.length}"

unsorted_list.delete_at(index_of_smallest(unsorted_list))

puts "After: #{unsorted_list.length}"

puts "--------------------------------------------------------------"

puts "Before: #{unsorted_list.length}"

unsorted_list.delete_at(index_of_smallest(unsorted_list))

puts "After: #{unsorted_list.length}"

puts "--------------------------------------------------------------"

puts "Before: #{unsorted_list.length}"

unsorted_list.delete_at(index_of_smallest(unsorted_list))

puts "After: #{unsorted_list.length}"

puts "--------------------------------------------------------------"

puts "Before: #{unsorted_list.length}"

unsorted_list.delete_at(index_of_smallest(unsorted_list))

puts "After: #{unsorted_list.length}"

puts "--------------------------------------------------------------"

puts unsorted_list

Result
Before: 7
After: 6
--------------------------------------------------------------
Before: 6
After: 5
--------------------------------------------------------------
Before: 5
After: 4
--------------------------------------------------------------
Before: 4
After: 4
--------------------------------------------------------------
Before: 4
After: 4
--------------------------------------------------------------
Before: 4
After: 4
--------------------------------------------------------------
Before: 4
After: 4
--------------------------------------------------------------
20
21
40
100

Note
Sorry for bad format and layout are new to stackoverflow.

A: small in  your code is supposed to be the position of the smallest element, not the element itself.
So change the initialization of small from...
small = array[0]

to...
small = 0

And change the comparison from...
    if array[i] < small

to...
    if array[i] < array[small]

A: The method 'deleted_at' is working properly as below.
> 2.4.1 :007 > arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]  => [0,
> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
> 21, 22]
> 2.4.1 :008 > arr.delete_at(22)  => 22
> 2.4.1 :009 > arr  => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
> 2.4.1 :010 >

There is an issue with your code. Please go with each stage(mentioned in below code), you can find at stage 3 we are trying to sort unsorted_list which is already sorted.Hence the value of small from index_of_smallest is nil from stage 3. We need to merge sorted_list + unsorted_list after stage 2 and you will get the sorted array.
Please refere below code for better understanding:
unsorted_list = [20, 21, 40, 10, 18, -20, 100]
# As lenght of unsorted_list is going to change every time after deleting element
unsorted_list_length = unsorted_list.length
sorted_list = []

def index_of_smallest(array)
  i = 0
  small = array[i]
  #checking array is already sorted or not??
  small_element_found = false
  while i < array.length
    p "array[i] < small-----#{array[i]} < #{small}--#{array[i] < small}"
    if array[i] < small
      small = i
      small_element_found = true
    end
    i += 1
  end
  return [small,small_element_found]
end

j = 0
while j < unsorted_list_length
  puts "******STAGE #{j}******"
  puts "unsorted_list------#{unsorted_list}"

  small_ele_index, arr_sorted = index_of_smallest(unsorted_list)
  sorted_list << unsorted_list.delete_at(small_ele_index) if arr_sorted
  puts "sorted_list------#{sorted_list}"

  j += 1
end

puts "Final Sorted List----------#{sorted_list + unsorted_list}"


text:
Q: how to convert jason file data into csv file in python I have .json file which have this type of data ,the name of universities of the world
[
  {
    "web_pages": [
      "https://www.cstj.qc.ca",
      "https://ccmt.cstj.qc.ca",
      "https://ccml.cstj.qc.ca"
    ],
    "name": "Cégep de Saint-Jérôme",
    "alpha_two_code": "CA",
    "state-province": null,
    "domains": [
      "cstj.qc.ca"
    ],
    "country": "Canada"
  },
  {
    "web_pages": [
      "http://www.lindenwood.edu/"
    ],
    "name": "Lindenwood University",
    "alpha_two_code": "US",
    "state-province": null,
    "domains": [
      "lindenwood.edu"
    ],
    "country": "United States"
  },
  {
    "web_pages": [
.......
.....
....
...
Continue......

I want to convert this .json file into CSV using Python, What will be its solution to make the CSV file?

A: This solution uses Pandas.
import json
from pandas.io.json import json_normalize

with open('infile.json') as json_data:
    d = json.load(json_data)

df = json_normalize(d)
df.to_csv('outfile.csv', index=False)

Also, as @LucaBezerra has mentioned in the comments, the current text has some encoding problem which you might want to fix (look at the first "name").


text:
Q: File readeable on computer, but not on USB I just have A REALLY BIG PROBLEM. I've made a pdf file, and on my pc is readeable, and on others pc (I've send link to download to others) but, when i put it on my USB flashdrive it's not readeable anymore.
Please, what`s the matter...?
Thank you!


text:
Q: View the character unicode values of a word document I want to view a word document along with the unicode representation of the special characters.
For example, I want to a word doc containing :
Hi,
How are you ?

As ,
Hi \r\n How are you ?

Is there any way to do this?
Not programatically. Any software or software mode would suffice.

A: If you want to see format control characters as visible symbols, which is what your example is about, then there does not seem to be any direct way. But if you click on the "¶" button (in the Start pane, Paragraph group in new versions of Word), Word adds symbols at ends of visible lines to indicate presence of such controls, e.g.
Hi,·¶
How·are·you?·¶

Here "¶" indicates the presence of CR (U+000D CARRIAGE RETURN, "\r"), whereas a symbol resembling "⤶" would indicate LF (U+000A LINE FEED, "\n"), which indicates a forced line break without paragraph break in Word. And "·" indicates a normal space (U+0020 SPACE), whereas "°" would indicate a no-break space (U+00A0 NO-BREAK SPACE).
For visible characters, the AltX method described by @JasonPlutext works well. You don't even need to select the character. You can just click between it and the next character, to place the cursor there, and then press AltX.

A: In Word, select the character and press "alt-x".
This appears to be unavailable in Word for Mac version 2016 (according to Microsoft Answers), or in Office 365's version 16.


text:
Q: Retorno de SQL em PHP converte acentuação para '?' Estou com um problema de encode, o meu retorno do Banco Oracle está fazendo os acentos em ? alguém consegui me ajudar?
Detalhe preciso converter na variável não só no Browser, porque vou usar para um outro select.
       $sqlIn = "SELECT  distinct(LOCALIDADE_NOME) , COUNT(LOCALIDADE_NOME) FROM TBL_TA
            INNER JOIN TBL_TA_EQUIPAMENTO ON CODIGO=AEQ_TA WHERE TQA_ORIGEM IN ($listaIn)
            GROUP BY LOCALIDADE_NOME";
    $RESP_QUERYa = oci_parse($SS, $sqlIn);
    oci_execute($RESP_QUERYa);
    $afetacaolista = new ArrayObject();
    while (($row = oci_fetch_array($RESP_QUERYa, OCI_BOTH)) != false) {
        $afetacao = new afetacaoBean();
        echo $teste = utf8_encode($row['LOCALIDADE_NOME']) . "<br>";
        }

A Saida é:
RIBEIR?O PIRES
VARZEA PAULISTA
FRANCO DA ROCHA
S?O PAULO
JUNDIAI
FRANCISCO MORATO

Já tentei varias coisas como :
    mb_internal_encoding("UTF-8");
    mb_http_output("iso-8859-1");
    ob_start("mb_output_handler");
    header("Content-Type: text/html; charset=ISO-8859-1", true);

Não Tenho como mudar a configuração do Banco nem de Tabelas.

A: Pelo que entendi pode ser o próprio encode da conexão com o Oracle.
Você pode tentar forçar a codificação na própria conexão dessa forma:
$conn = oci_connect( $username, $pass, $conn_string, 'UTF8' );


text:
Q: "Cannot create a method for an unnamed component" The following code (when registered in a package) gives us a component called TParentComponent registered in the pallet Test.
However, when you create a Child object using the Property Editor (provided in the same code), the IDE displays the error message Cannot create a method for an unnamed component.
What's strange is that the Child object does indeed have a name.
Here's the source:
unit TestEditorUnit;

interface

uses
  Classes, DesignEditors, DesignIntf;

type
  TParentComponent = class;

  TChildComponent = class(TComponent)
  private
    FParent: TParentComponent;
    FOnTest: TNotifyEvent;
    procedure SetParent(const Value: TParentComponent);
  protected
    procedure SetParentComponent(AParent: TComponent); override;
  public
    destructor Destroy; override;
    function GetParentComponent: TComponent; override;
    function HasParent: Boolean; override;
    property Parent: TParentComponent read FParent write SetParent;
  published
    property OnTest: TNotifyEvent read FOnTest write FOnTest;
  end;

  TParentComponent = class(TComponent)
  private
    FChilds: TList;
  protected
    procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    property Childs: TList read FChilds;
  end;

  TParentPropertyEditor = class(TPropertyEditor)
  public
    function GetAttributes: TPropertyAttributes; override;
    function GetValue: string; override;
    procedure Edit; override;
  end;

procedure Register;

implementation

uses
  ColnEdit;

type
  TChildComponentCollectionItem = class(TCollectionItem)
  private
    FChildComponent: TChildComponent;
    function GetName: string;
    function GetOnTest: TNotifyEvent;
    procedure SetName(const Value: string);
    procedure SetOnTest(const Value: TNotifyEvent);
  protected
    property ChildComponent: TChildComponent read FChildComponent write FChildComponent;
    function GetDisplayName: string; override;
  public
    constructor Create(Collection: TCollection); override;
    destructor Destroy; override;
  published
    property Name: string read GetName write SetName;
    property OnTest: TNotifyEvent read GetOnTest write SetOnTest;
  end;

  TChildComponentCollection = class(TOwnedCollection)
  private
    FDesigner: IDesigner;
  public
    property Designer: IDesigner read FDesigner write FDesigner;
  end;

procedure Register;
begin
  RegisterClass(TChildComponent);
  RegisterNoIcon([TChildComponent]);
  RegisterComponents('Test', [TParentComponent]);
  RegisterPropertyEditor(TypeInfo(TList), TParentComponent, 'Childs', TParentPropertyEditor);
end;

{ TChildComponent }

destructor TChildComponent.Destroy;
begin
  Parent := nil;
  inherited;
end;

function TChildComponent.GetParentComponent: TComponent;
begin
  Result := FParent;
end;

function TChildComponent.HasParent: Boolean;
begin
  Result := Assigned(FParent);
end;

procedure TChildComponent.SetParent(const Value: TParentComponent);
begin
  if FParent <> Value then
  begin
    if Assigned(FParent) then
      FParent.FChilds.Remove(Self);
    FParent := Value;
    if Assigned(FParent) then
      FParent.FChilds.Add(Self);
  end;
end;

procedure TChildComponent.SetParentComponent(AParent: TComponent);
begin
  if AParent is TParentComponent then
    SetParent(AParent as TParentComponent);
end;

{ TParentComponent }

constructor TParentComponent.Create(AOwner: TComponent);
begin
  inherited;
  FChilds := TList.Create;
end;

destructor TParentComponent.Destroy;
var
  I: Integer;
begin
  for I := 0 to FChilds.Count - 1 do
    TComponent(FChilds[0]).Free;
  FChilds.Free;
  inherited;
end;

procedure TParentComponent.GetChildren(Proc: TGetChildProc; Root: TComponent);
var
  i: Integer;
begin
  for i := 0 to FChilds.Count - 1 do
    Proc(TComponent(FChilds[i]));
end;

{ TChildComponentCollectionItem }

constructor TChildComponentCollectionItem.Create(Collection: TCollection);
begin
  inherited;
  if Assigned(Collection) then
  begin
    FChildComponent := TChildComponent.Create(TComponent(TOwnedCollection(Collection).Owner).Owner);
    FChildComponent.Name := TChildComponentCollection(Collection).Designer.UniqueName(TChildComponent.ClassName);
    FChildComponent.Parent := TParentComponent(TComponent(TOwnedCollection(Collection).Owner));
  end;
end;

destructor TChildComponentCollectionItem.Destroy;
begin
  FChildComponent.Free;
  inherited;
end;

function TChildComponentCollectionItem.GetDisplayName: string;
begin
  Result := FChildComponent.Name;
end;

function TChildComponentCollectionItem.GetName: string;
begin
  Result := FChildComponent.Name;
end;

function TChildComponentCollectionItem.GetOnTest: TNotifyEvent;
begin
  Result := FChildComponent.OnTest;
end;

procedure TChildComponentCollectionItem.SetName(const Value: string);
begin
  FChildComponent.Name := Value;
end;

procedure TChildComponentCollectionItem.SetOnTest(const Value: TNotifyEvent);
begin
  FChildComponent.OnTest := Value;
end;

{ TParentPropertyEditor }

procedure TParentPropertyEditor.Edit;
var
  LCollection: TChildComponentCollection;
  i: Integer;
begin
  LCollection := TChildComponentCollection.Create(GetComponent(0), TChildComponentCollectionItem);
  LCollection.Designer := Designer;
  for i := 0 to TParentComponent(GetComponent(0)).Childs.Count - 1 do
    with TChildComponentCollectionItem.Create(nil) do
    begin
      ChildComponent := TChildComponent(TParentComponent(GetComponent(0)).Childs[i]);
      Collection := LCollection;
    end;
  ShowCollectionEditorClass(Designer, TCollectionEditor, TComponent(GetComponent(0)), LCollection, 'Childs');
end;

function TParentPropertyEditor.GetAttributes: TPropertyAttributes;
begin
  Result := [paDialog];
end;

function TParentPropertyEditor.GetValue: string;
begin
  Result := 'Childs';
end;

end.

The above source was adapated from another answer here on StackOverflow.
Any ideas why I cannot create a method for OnTest?
Thanks in advance!

A: Design time requirement summary

*

*You want or need a custom component that is capable of holding multiple child components.

*Those child components are to be created by that custom component.

*The child components need to be able to be referenced in code by their name as any normal component that is placed design time; thus not Form.CustomComponent.Children[0], but Form.Child1 instead.

*Therefore, the child components need to be declared in - and thus added to - the source file of the module (a Form, Frame or DataModule).

*The child components are to be managed by the default IDE collection editor.

*Therefore, a child needs to completely be wrapped into a TCollectionItem.

Evaluation of current code
You are going quite well already, but besides your question, the code has a few points for improvement:

*

*The collections you create are never freed.

*A new collection is created every time you show the collection editor.

*If you delete a child from the TreeView, then the old corresponding CollectionItem stays, resulting in an AV.

*The design time and run time code is not split.

Solution
Here is a rewritten, working version of your code, with the following changes:

*

*The special component is called Master, because Parent confuses too much with Delphi's Parent (there are two kind already). Therefore a child is called Slave.

*Slaves are held in a TComponentList (unit Contnrs) to automatically update the list in case of individual slave destruction. The ComponentList owns the slaves.

*For every single Master, only one Collection is created. These Master-Collection-combinations are held in a separate TStockItems ObjectList. The List owns the stock items, and the list is freed in the Finalization section.

*GetNamePath is implemented so that a slave is shown as Slave1 in the Object Inspector, instead of as SlaveWrappers(0).

*An extra property editor is added for the event of the TSlaveWrapper class. Somehow GetFormMethodName of the default TMethodProperty results in the error you are getting. The cause will ly in Designer.GetObjectName, but I do not know exactly why. Now GetFormMethodName is overriden, which solves the problem from your question.

Remarks
Changes made in the order of the items in the collection (with the arrow buttons of the collection editor) are not preserved yet. Try yourself to get that implemented.
In the TreeView, each Slave is now an immediate child of the Master, instead of being child of the Slaves property, as normally seen with collections:

For this to happen, I think TSlaves should descend from TPersistent, and the ComponentList would be wrapped inside it. That sure is another nice tryout.
Component code
unit MasterSlave;

interface

uses
  Classes, Contnrs;

type
  TMaster = class;

  TSlave = class(TComponent)
  private
    FMaster: TMaster;
    FOnTest: TNotifyEvent;
    procedure SetMaster(Value: TMaster);
  protected
    procedure SetParentComponent(AParent: TComponent); override;
  public
    function GetParentComponent: TComponent; override;
    function HasParent: Boolean; override;
    property Master: TMaster read FMaster write SetMaster;
  published
    property OnTest: TNotifyEvent read FOnTest write FOnTest;
  end;

  TSlaves = class(TComponentList)
  private
    function GetItem(Index: Integer): TSlave;
    procedure SetItem(Index: Integer; Value: TSlave);
  public
    property Items[Index: Integer]: TSlave read GetItem write SetItem; default;
  end;

  TMaster = class(TComponent)
  private
    FSlaves: TSlaves;
  protected
    procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    property Slaves: TSlaves read FSlaves;
  end;

implementation

{ TSlave }

function TSlave.GetParentComponent: TComponent;
begin
  Result := FMaster;
end;

function TSlave.HasParent: Boolean;
begin
  Result := FMaster <> nil;
end;

procedure TSlave.SetMaster(Value: TMaster);
begin
  if FMaster <> Value then
  begin
    if FMaster <> nil then
      FMaster.FSlaves.Remove(Self);
    FMaster := Value;
    if FMaster <> nil then
      FMaster.FSlaves.Add(Self);
  end;
end;

procedure TSlave.SetParentComponent(AParent: TComponent);
begin
  if AParent is TMaster then
    SetMaster(TMaster(AParent));
end;

{ TSlaves }

function TSlaves.GetItem(Index: Integer): TSlave;
begin
  Result := TSlave(inherited Items[Index]);
end;

procedure TSlaves.SetItem(Index: Integer; Value: TSlave);
begin
  inherited Items[Index] := Value;
end;

{ TMaster }

constructor TMaster.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FSlaves := TSlaves.Create(True);
end;

destructor TMaster.Destroy;
begin
  FSlaves.Free;
  inherited Destroy;
end;

procedure TMaster.GetChildren(Proc: TGetChildProc; Root: TComponent);
var
  I: Integer;
begin
  for I := 0 to FSlaves.Count - 1 do
    Proc(FSlaves[I]);
end;

end.

Editor code
unit MasterSlaveEdit;

interface

uses
  Classes, SysUtils, MasterSlave, Contnrs, DesignEditors, DesignIntf, ColnEdit;

type
  TMasterEditor = class(TComponentEditor)
  private
    function Master: TMaster;
  public
    procedure ExecuteVerb(Index: Integer); override;
    function GetVerb(Index: Integer): String; override;
    function GetVerbCount: Integer; override;
  end;

  TMasterProperty = class(TPropertyEditor)
  private
    function Master: TMaster;
  public
    procedure Edit; override;
    function GetAttributes: TPropertyAttributes; override;
    function GetValue: String; override;
  end;

  TOnTestProperty = class(TMethodProperty)
  private
    function Slave: TSlave;
  public
    function GetFormMethodName: String; override;
  end;

  TSlaveWrapper = class(TCollectionItem)
  private
    FSlave: TSlave;
    function GetName: String;
    function GetOnTest: TNotifyEvent;
    procedure SetName(const Value: String);
    procedure SetOnTest(Value: TNotifyEvent);
  protected
    function GetDisplayName: String; override;
  public
    constructor Create(Collection: TCollection); override;
    constructor CreateSlave(Collection: TCollection; ASlave: TSlave);
    destructor Destroy; override;
    function GetNamePath: String; override;
  published
    property Name: String read GetName write SetName;
    property OnTest: TNotifyEvent read GetOnTest write SetOnTest;
  end;

  TSlaveWrappers = class(TOwnedCollection)
  private
    function GetItem(Index: Integer): TSlaveWrapper;
  public
    property Items[Index: Integer]: TSlaveWrapper read GetItem; default;
  end;

implementation

type
  TStockItem = class(TComponent)
  protected
    Collection: TSlaveWrappers;
    Designer: IDesigner;
    Master: TMaster;
    procedure Notification(AComponent: TComponent; Operation: TOperation);
      override;
  public
    destructor Destroy; override;
  end;

  TStockItems = class(TObjectList)
  private
    function GetItem(Index: Integer): TStockItem;
  protected
    function CollectionOf(AMaster: TMaster; Designer: IDesigner): TCollection;
    function Find(ACollection: TCollection): TStockItem;
    property Items[Index: Integer]: TStockItem read GetItem;
      default;
  end;

var
  FStock: TStockItems = nil;

function Stock: TStockItems;
begin
  if FStock = nil then
    FStock := TStockItems.Create(True);
  Result := FStock;
end;

{ TStockItem }

destructor TStockItem.Destroy;
begin
  Collection.Free;
  inherited Destroy;
end;

procedure TStockItem.Notification(AComponent: TComponent;
  Operation: TOperation);
var
  I: Integer;
begin
  inherited Notification(AComponent, Operation);
  if Operation = opRemove then
    for I := 0 to Collection.Count - 1 do
      if Collection[I].FSlave = AComponent then
      begin
        Collection[I].FSlave := nil;
        Collection.Delete(I);
        Break;
      end;
end;

{ TStockItems }

function TStockItems.CollectionOf(AMaster: TMaster;
  Designer: IDesigner): TCollection;
var
  I: Integer;
  Item: TStockItem;
begin
  Result := nil;
  for I := 0 to Count - 1 do
    if Items[I].Master = AMaster then
    begin
      Result := Items[I].Collection;
      Break;
    end;
  if Result = nil then
  begin
    Item := TStockItem.Create(nil);
    Item.Master := AMaster;
    Item.Designer := Designer;
    Item.Collection := TSlaveWrappers.Create(AMaster, TSlaveWrapper);
    for I := 0 to AMaster.Slaves.Count - 1 do
    begin
      TSlaveWrapper.CreateSlave(Item.Collection, AMaster.Slaves[I]);
      Item.FreeNotification(AMaster.Slaves[I]);
    end;
    Add(Item);
    Result := Item.Collection;
  end;
end;

function TStockItems.GetItem(Index: Integer): TStockItem;
begin
  Result := TStockItem(inherited Items[Index]);
end;

function TStockItems.Find(ACollection: TCollection): TStockItem;
var
  I: Integer;
begin
  Result := nil;
  for I := 0 to Count - 1 do
    if Items[I].Collection = ACollection then
    begin
      Result := Items[I];
      Break;
    end;
end;

{ TMasterEditor }

procedure TMasterEditor.ExecuteVerb(Index: Integer);
begin
  case Index of
    0: ShowCollectionEditor(Designer, Master,
      Stock.CollectionOf(Master, Designer), 'Slaves');
  end;
end;

function TMasterEditor.GetVerb(Index: Integer): String;
begin
  case Index of
    0: Result := 'Edit slaves...';
  else
    Result := '';
  end;
end;

function TMasterEditor.GetVerbCount: Integer;
begin
  Result := 1;
end;

function TMasterEditor.Master: TMaster;
begin
  Result := TMaster(Component);
end;

{ TMasterProperty }

procedure TMasterProperty.Edit;
begin
  ShowCollectionEditor(Designer, Master,
    Stock.CollectionOf(Master, Designer), 'Slaves');
end;

function TMasterProperty.GetAttributes: TPropertyAttributes;
begin
  Result := [paDialog];
end;

function TMasterProperty.GetValue: String;
begin
  Result := Format('(%s)', [Master.Slaves.ClassName]);
end;

function TMasterProperty.Master: TMaster;
begin
  Result := TMaster(GetComponent(0));
end;

{ TOnTestProperty }

function TOnTestProperty.GetFormMethodName: String;
begin
  Result := Slave.Name + GetTrimmedEventName;
end;

function TOnTestProperty.Slave: TSlave;
begin
  Result := TSlaveWrapper(GetComponent(0)).FSlave;
end;

{ TSlaveWrapper }

constructor TSlaveWrapper.Create(Collection: TCollection);
begin
  CreateSlave(Collection, nil);
end;

constructor TSlaveWrapper.CreateSlave(Collection: TCollection; ASlave: TSlave);
var
  Item: TStockItem;
begin
  inherited Create(Collection);
  if ASlave = nil then
  begin
    Item := Stock.Find(Collection);
    FSlave := TSlave.Create(Item.Master.Owner);
    FSlave.Name := Item.Designer.UniqueName(TSlave.ClassName);
    FSlave.Master := Item.Master;
    FSlave.FreeNotification(Item);
  end
  else
    FSlave := ASlave;
end;

destructor TSlaveWrapper.Destroy;
begin
  FSlave.Free;
  inherited Destroy;
end;

function TSlaveWrapper.GetDisplayName: String;
begin
  Result := Name;
end;

function TSlaveWrapper.GetName: String;
begin
  Result := FSlave.Name;
end;

function TSlaveWrapper.GetNamePath: String;
begin
  Result := FSlave.GetNamePath;
end;

function TSlaveWrapper.GetOnTest: TNotifyEvent;
begin
  Result := FSlave.OnTest;
end;

procedure TSlaveWrapper.SetName(const Value: String);
begin
  FSlave.Name := Value;
end;

procedure TSlaveWrapper.SetOnTest(Value: TNotifyEvent);
begin
  FSlave.OnTest := Value;
end;

{ TSlaveWrappers }

function TSlaveWrappers.GetItem(Index: Integer): TSlaveWrapper;
begin
  Result := TSlaveWrapper(inherited Items[Index]);
end;

initialization

finalization
  FStock.Free;

end.

Registration code
unit MasterSlaveReg;

interface

uses
  Classes, MasterSlave, MasterSlaveEdit, DesignIntf;

procedure Register;

implementation

procedure Register;
begin
  RegisterClass(TSlave);
  RegisterNoIcon([TSlave]);
  RegisterComponents('Samples', [TMaster]);
  RegisterComponentEditor(TMaster, TMasterEditor);
  RegisterPropertyEditor(TypeInfo(TSlaves), TMaster, 'Slaves',
    TMasterProperty);
  RegisterPropertyEditor(TypeInfo(TNotifyEvent), TSlaveWrapper, 'OnTest',
    TOnTestProperty);
end;

end.

Package code
requires
  rtl,
  DesignIDE;

contains
  MasterSlave in 'MasterSlave.pas',
  MasterSlaveEdit in 'MasterSlaveEdit.pas',
  MasterSlaveReg in 'MasterSlaveReg.pas';

A: A sufficient "workaround" was found on About.com's "Creating Custom Delphi Components, Part 2, Page 4 of 5" article.
Full sample source is on their article, and works (seemingly) with all versions of Delphi.
However, it should be noted that this solution isn't perfect as it doesn't allow you to separate the Collection Editor from the Parent and Child components (meaning you have to produce the source for both components to enable the Collection Editor to work, and place that in your runtime package).
For my needs right now, this will do... but if anyone can find a better solution based directly on the example code posted in my question, that'd be great (and I'll mark that answer as Correct should anyone provide it).


text:
Q: Distribute large Tikz image on two A4 landscape
How do I distribute the following picture in such a way that

*

*it is printed on two A4 landscape

*1cm in the centre repeat itself (that is, the right most cm on the first page is equal to the left most cm on the second page)

\documentclass{article}
\usepackage[a4paper,margin=.5cm,landscape]{geometry}
\usepackage{etex}
\usepackage{tikz}
\usepackage{musixtex}
\def\threedp#1{\pgfmathparse{#1}\expandafter\Threedp\pgfmathresult0000@}
\def\Threedp#1.#2#3#4#5@{#1.#2#3#4}
\begin{document}
\pgfdeclarelayer{blacknotes}
\pgfsetlayers{main,blacknotes}
\tikzset{tight fit/.style={inner sep=0pt, outer sep=0pt}}

\begin{tikzpicture}
\def\lastnotenodename{clefs}
\node [text width=1cm, tight fit] (clefs) at (0,0) {
    \begin{music}
        \instrumentnumber{1}
        \instrumentnumber{2}
        \nostartrule
        \setstaffs1{1}
        \setstaffs2{1}
        \setclef1{\bass}
        \setclef2{\treble}
        \startextract
        \hskip2.0\elemskip
        \zendextract
    \end{music}
};

\foreach \note [
    evaluate={
        \n=int(mod(\note-1, 12));
        \octave=int((\note+8)/12);
        \t=int(floor((\note-1)/12)*7-7);
        \notename={"A","","B","C","","D","","E","F","","G",""}[\n];
        \tonicsolfa={"la","","si","so","","r\`e","","mi","fa","","sol",""}[\n];
        \blacknote={0,1,0,0,1,0,1,0,0,1,0,1}[\n];
        \frequency=(2^((\note-49)/12))*440;}
] in {1,...,88}{

    \ifnum\octave>3
        \tikzset{extract anchor/.style={anchor=south west, at=(\lastnotenodename.south east)}}
    \else
        \tikzset{extract anchor/.style={anchor=north west, at=(\lastnotenodename.north east)}}
    \fi
    \ifnum\blacknote=0
        \edef\notenodename{\notename_\octave}
        \node (\notenodename) [tight fit,text width=1cm, extract anchor/.try]  {%
            \begin{music}
                \instrumentnumber{1}
                \instrumentnumber{2}
                \nostartrule
                \setstaffs1{1}
                \setstaffs2{1}
                \setclefsymbol1{\empty}
                \setclefsymbol2{\empty}
                \setclef1{\bass}
                \setclef2{\treble}
                \startextract
                \transpose\t
                \hskip-1.5\elemskip
                \ifnum\octave>3
                    \ifnum\octave>4
                        \Notes \nextinstrument \ql{\notename} \en
                    \else
                        \Notes \nextinstrument \qu{\notename} \en
                    \fi
                \else
                    \ifnum\octave>2
                        \Notes \ql{\notename} \en
                    \else
                        \Notes \qu{\notename} \en
                    \fi
                \fi
                \zendextract
            \end{music}
        };
        \xdef\lastnotenodename{\notenodename}
        \node [anchor=base] (sol-fa)  at (\notenodename |- 0,-3) {\tonicsolfa$_\octave$};

        \draw (\notenodename.south west |- 0,-4) rectangle ++(1, -4);
        \node [rotate=90, font=\footnotesize, anchor=east]
            at (\notenodename.north |- 0,-4) {\threedp\frequency};
        \node [font=\footnotesize, anchor=south]
            at (\notenodename.south |- 0,-8) {\note};
        \node [font=\footnotesize, anchor=south]
            at (\notenodename.south |- 0,-8.5)  {\notename$_\octave$};
        \draw (\notenodename.south west |- sol-fa.south)
            rectangle (\notenodename.south east |- 0,1.125); %0.125 by trial and error
    \else
        \begin{pgfonlayer}{blacknotes}
        \fill ([xshift=-0.25cm]\lastnotenodename.north east |- 0,-4) rectangle ++(0.5, -2.5);
        \node  [rotate=90, text=white, font=\footnotesize, anchor=east]
            at (\lastnotenodename.north east |- 0,-4) {\threedp\frequency};
        \end{pgfonlayer}
    \fi
}
\node [rotate=90] at (0,-6) {Fr\`equency (Hz)};
\end{tikzpicture}

\end{document}

At the moment only one page is printed with a part of the picture:

The code is from Range of a piano: keyboard vs staves .

A: Using collectbox and trimclip we can realize what you want in a more general way, that is, for any box.
I added some optional arguments for additional clipping (e.g. for dealing with content that exceeds its bounding box).
\documentclass{scrbook}

\usepackage{mwe}
\usepackage{trimclip}
\usepackage{xparse}

\makeatletter
  \newcommand\doublepagesplitoverlap{1cm}
  \NewDocumentCommand\doublepagesplit{
    O{\doublepagesplitoverlap}    % overlap
    D||{0pt}  % clip left
    D||{#2}   % clip right
    D!!{0pt}  % clip top
    D!!{#4}   % clip bottom
  }{%
    \cleardoubleevenpage\leavevmode\vfil
    \flushright
    \collectbox{%
      \@doublepagesplit
        {#2}{#4}%
        {\dimexpr (\width - #1) / 2\relax}%
        {#4}{#5}%
    }%
  }
  \newcommand\@doublepagesplit[5]{%
    \clipbox{{#1} {#2} {#3} {#5}}{\BOXCONTENT}%
    \clearpage\leavevmode\vfil
    \flushleft
    \clipbox{{#3} {#2} {#4} {#5}}{\BOXCONTENT}%
    \clearpage
  }
\makeatother

\begin{document}

\doublepagesplit{\includegraphics{example-image}\relax}

\end{document}

Putting this into your document (and copying KOMA-Script's \cleardoubleevenpage) we get
\documentclass{article}

\usepackage[a4paper,margin=.5cm,landscape]{geometry}
\usepackage{tikz}
\usepackage{musixtex}
\usepackage{trimclip}
\usepackage{xparse}

\def\threedp#1{\pgfmathparse{#1}\expandafter\Threedp\pgfmathresult0000@}
\def\Threedp#1.#2#3#4#5@{#1.#2#3#4}

\makeatletter
  \newcommand*\cleardoubleevenpage{%
    \clearpage
    \if@twoside\ifodd\c@page
        \hbox{}\newpage\if@twocolumn\hbox{}\newpage\fi
    \fi\fi
  }
  \newcommand\doublepagesplitoverlap{1cm}
  \NewDocumentCommand\doublepagesplit{
    O{\doublepagesplitoverlap}    % overlap
    D||{0pt}  % clip left
    D||{#2}   % clip right
    D!!{0pt}  % clip top
    D!!{#4}   % clip bottom
  }{%
    \cleardoubleevenpage\leavevmode\vfil
    \flushright
    \collectbox{%
      \@doublepagesplit
        {#2}{#4}%
        {\dimexpr (\width - #1) / 2\relax}%
        {#4}{#5}%
    }%
  }
  \newcommand\@doublepagesplit[5]{%
    \clipbox{{#1} {#2} {#3} {#5}}{\BOXCONTENT}%
    \clearpage\leavevmode\vfil
    \flushleft
    \clipbox{{#3} {#2} {#4} {#5}}{\BOXCONTENT}%
    \clearpage
  }
\makeatother

\pgfdeclarelayer{blacknotes}
\pgfsetlayers{main,blacknotes}
\tikzset{tight fit/.style={inner sep=0pt, outer sep=0pt}}

\begin{document}

\doublepagesplit|-.5cm|{%
\begin{tikzpicture}
\def\lastnotenodename{clefs}
\node [text width=1cm, tight fit] (clefs) at (0,0) {
    \begin{music}
        \instrumentnumber{1}
        \instrumentnumber{2}
        \nostartrule
        \setstaffs1{1}
        \setstaffs2{1}
        \setclef1{\bass}
        \setclef2{\treble}
        \startextract
        \hskip2.0\elemskip
        \zendextract
    \end{music}
};

\foreach \note [
    evaluate={
        \n=int(mod(\note-1, 12));
        \octave=int((\note+8)/12);
        \t=int(floor((\note-1)/12)*7-7);
        \notename={"A","","B","C","","D","","E","F","","G",""}[\n];
        \tonicsolfa={"la","","si","so","","r\`e","","mi","fa","","sol",""}[\n];
        \blacknote={0,1,0,0,1,0,1,0,0,1,0,1}[\n];
        \frequency=(2^((\note-49)/12))*440;}
] in {1,...,88}{

    \ifnum\octave>3
        \tikzset{extract anchor/.style={anchor=south west, at=(\lastnotenodename.south east)}}
    \else
        \tikzset{extract anchor/.style={anchor=north west, at=(\lastnotenodename.north east)}}
    \fi
    \ifnum\blacknote=0
        \edef\notenodename{\notename_\octave}
        \node (\notenodename) [tight fit,text width=1cm, extract anchor/.try]  {%
            \begin{music}
                \instrumentnumber{1}
                \instrumentnumber{2}
                \nostartrule
                \setstaffs1{1}
                \setstaffs2{1}
                \setclefsymbol1{\empty}
                \setclefsymbol2{\empty}
                \setclef1{\bass}
                \setclef2{\treble}
                \startextract
                \transpose\t
                \hskip-1.5\elemskip
                \ifnum\octave>3
                    \ifnum\octave>4
                        \Notes \nextinstrument \ql{\notename} \en
                    \else
                        \Notes \nextinstrument \qu{\notename} \en
                    \fi
                \else
                    \ifnum\octave>2
                        \Notes \ql{\notename} \en
                    \else
                        \Notes \qu{\notename} \en
                    \fi
                \fi
                \zendextract
            \end{music}
        };
        \xdef\lastnotenodename{\notenodename}
        \node [anchor=base] (sol-fa)  at (\notenodename |- 0,-3) {\tonicsolfa$_\octave$};

        \draw (\notenodename.south west |- 0,-4) rectangle ++(1, -4);
        \node [rotate=90, font=\footnotesize, anchor=east]
            at (\notenodename.north |- 0,-4) {\threedp\frequency};
        \node [font=\footnotesize, anchor=south]
            at (\notenodename.south |- 0,-8) {\note};
        \node [font=\footnotesize, anchor=south]
            at (\notenodename.south |- 0,-8.5)  {\notename$_\octave$};
        \draw (\notenodename.south west |- sol-fa.south)
            rectangle (\notenodename.south east |- 0,1.125); %0.125 by trial and error
    \else
        \begin{pgfonlayer}{blacknotes}
        \fill ([xshift=-0.25cm]\lastnotenodename.north east |- 0,-4) rectangle ++(0.5, -2.5);
        \node  [rotate=90, text=white, font=\footnotesize, anchor=east]
            at (\lastnotenodename.north east |- 0,-4) {\threedp\frequency};
        \end{pgfonlayer}
    \fi
}
\node [rotate=90] at (0,-6) {Fr\`equency (Hz)};
\end{tikzpicture}
}

\end{document}


text: Q: How to figure out whether PCA can be performed on a data set or not? I do have idea on the way PCA works but I do not know how to figure out whether a high dimensional data set is suited for PCA compression. I googled for some algorithms but could find any. Are there some algorithms that help us to decide whether PCA can be performed in a data set or not?


text:
Q: How does calling "setState" as a callback in a function, without any new state value, successfully update the state? I saw this code snippet recently, and am wondering how the state variable actually gets updated here. This is the authentication state observer used in firebase authentication to determine if a user is signed in (docs reference).
Normally, this is how it functions:
const [userData, setUserData] = useState(null)
firebase.auth().onAuthStateChanged(user => {
  if (user) {
    // User is signed in.
    setUserData(user); // can now access properties of user
  }
});

However, this code updates userData in the exact same way by placing setUserData in place of the callback in the function:
const [userData, setUserData] = useState(null)
firebase.auth().onAuthStateChanged(setUserData);

Both of these functions set userData as the same object. How does this work, in the second snippet, where the state is updated by not using a tangible value to update the state?

A: The second call uses a function that is defined elsewhere as the callback, while the first uses a newly defined function.
See example below:

function log(data) {
  console.log(data);
}

function someFunction(callback) {
  setTimeout(()=>{ callback("my data")}, 1000);
}

someFunction( (data)=> console.log(data) ); // use new function
someFunction( log ); // reuse a defined function

A: That's simply the way it works in javascript. Functions are a first class citizens which you can assign to variables and pass as an arguments. Here, setUserData is passed as a first argument of onAuthStateChanged. For a better understanding, consider something like this:
const [userData, setUserData] = useState(null)

const handleAuth = user => {
  if (user) {
    setUserData(user);
  }
}

firebase.auth().onAuthStateChanged(handleAuth);

Both setUserData and handleAuth expects user as a first argument, so both functions are ok to pass as a callback to onAuthStateChanged.

A: Both of the following way is same:
firebase.auth().onAuthStateChanged(user => setUserData(user))
// OR,
firebase.auth().onAuthStateChanged(setUserData)

So, when you use arrow function you explicitly set user as parameter to setUserData and when you use it as callback it implicitly sets user parameter to it.


text:
Q: Why can't I make jQuery calls like $.whatever()? A question in which I probably demonstrate how little I know about jQuery:
I was working up some jQuery (1.4.4) code today that (I thought) was just like some other code I've written before. In it, I called $.ajax(arguments), which promptly produced the error

Uncaught TypeError: Cannot call method ajax of undefined

When I changed the call to jQuery.ajax(arguments), all was well.  Methods other than .ajax() were similarly affected.
What's up -- I thought the two notations were equivalent?  I'm obviously doing something wrong/stupid/ignorant, but I just don't see it.  Surely somebody out there can clear this up?  Thanks!

A: Are you using any other JS libraries? Prototype for instance?
The safest way to run jQuery code using the $ shortcut is like this
jQuery(function($){
    // jQuery code here using $
});

This is equivalent to
jQuery(document).ready(function($){
    // jQuery code here using $
});

Edit: For running code outside of the document ready context, see Alex's answer.

A: It could be that '$' has been used by other code as a variable or function. Prototype library is using '$' as well.

A: As well the other suggestions, you could wrap your code in a structure like this...
(function($) {

   // $ will point to jQuery here, guaranteed.

})(jQuery);

This function self invokes (defining an anonymous function and then calling it with ()), where  jQuery becomes the first argument of the anonymous function, which is $. It's a handy trick.

A: Most likely you have a conflict with the name $. This is often caused by using another library on the page that also makes use of the same character as a variable name. Try using the jQuery noConflict.


text:
Q: what it gets called method overriding? or duplicating? Senario 1:
updateQuery = (query) => {
   this.setState({query: query.trim()})
 }

    updateQuery = (query) => {
   this.setState({query: query.splice()})
 }

Senario 2:
clearQuery() {
   this.setState({ query : ''})
 }

    clearQuery() {
   this.setState({ query : 'veeru'})
 }

here are two Scenarios for #1 we are overriding the updateQuery value and for #2 we have two methods with the same name clearQuery only method body is different, in this case, what it gets called method overriding? or duplicating?

A: If you launch this test:
let test = () => {
  console.log('first');
};

test = () => {
  console.log('second');
};

test = () => {
  console.log('last');
};

test();

The result:
last
As you can see, the last function overwrites the previous.


text:
Q: Override previous Console Output is it possible to override the last System.out.println output, so i can for example visualize changes in a array or create a progessbar?
For example if i have this class:
class Main{
  public static void main(String[] args){
    for(int i = 0; i < 10; i++){
      for(int j = 0; j < i; j++){
        System.out.print("#");
      }
      System.out.println("");
    }
  }
}

What do i have to do to create this simple progressbar which is shown in a single line and not in 10 seperate lines?

A: This works on my particular console (Windows) but it's not terribly portable...
public class Test {
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 100; i++) {
            System.out.print("#");
            if (i % 20 == 0) {
                System.out.print("\r                    \r");
            }
            System.out.flush();
            Thread.sleep(100);
        }
    }
}

There's also the Console class, but that doesn't actually buy you very much as far as I can see...


text:
Q: Add 15 days to selected date in bootstrap datepicker I am using bootstrap datepicker. I want to add 15 days to selected date.

$("#invoice_date").datepicker({
    format: 'yyyy-mm-dd',
}).on('changeDate', function(selected) {
    var minDate = new Date(selected.date.valueOf());
    var new_date = new Date(selected.date);
    new_date.setDate(new_date.getDate() + 15);
    $("#due_date").val(new_date);
    $('#due_date').datepicker('setStartDate', minDate);
});

<input type="text" name="invoice_date" id="invoice_date" value="2021-05-11" readonly>

<input type="text" name="due_date" id="due_date" value="2021-05-26" readonly>

When invoice date is selected, I want to add 15 days to the selected date in due date value

A: You can use .format() to get date in format of yyyy-mm-dd and then set this inside your input-box .
Demo Code:

$("#due_date").datepicker({
  format: 'yyyy-mm-dd'
})
$("#invoice_date").datepicker({
  format: 'yyyy-mm-dd',
}).on('changeDate', function(selected) {
  var new_date = new Date(selected.format());
  new_date.setDate(new_date.getDate() + 15);
  $("#due_date").val(new_date.toISOString().slice(0, 10));
  $('#due_date').datepicker('setStartDate', selected.format());
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>

<input type="text" name="invoice_date" id="invoice_date" value="2021-05-11" readonly>

<input type="text" name="due_date" id="due_date" value="2021-05-26" readonly>

A: You need to change the selected date format. use,
new Date(your date).toISOString().slice(0,10);

to get yyyy-mm-dd format.

$("#invoice_date").datepicker({
    format: 'yyyy-mm-dd',
}).on('changeDate', function(selected) {
    var new_date = new Date(selected.format());
    new_date.setDate(new_date.getDate() + 15);
    // custom formatting
    $("#due_date").val(new_date.toISOString().slice(0, 10));
    $('#due_date').datepicker(
        'setStartDate',
        selected.format()
    );
});
<input type="text" name="invoice_date" id="invoice_date" value="2021-05-11" readonly>

<input type="text" name="due_date" id="due_date" value="2021-05-26" readonly>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>


text:
Q: Using flags to remove repeated items in a table I am currently working on an email project using Apache Velocity. In the email, I have a table where each row is a persons name followed by a value.  Each person can have multiple rows, but the name should only display the first time it appears in the table. I am currently using flags to toggle whether the name has been shown or not. My question is if there is a better way to accomplish this than by using flags. Here is my current code, a bit watered down:

        Name
        Value

    #foreach( $person in $view.people )
        #set($nameDisplayed = false)
        #foreach($personInfo in $person.infos)
            #if($personInfo.value1 > 0)

                    #if(!$nameDisplayed) $person.name #end
                    1

                #set($nameDisplayed = true)
            #end
        #end

        #if($person.value2 > 0)

                #if(!$nameDisplayed) $person.name #end
                2

            #set($nameDisplayed = true)
        #end

        #if($person.value3 > 0)

                #if(!$nameDisplayed) $person.name  #end
                3

            #set($nameDisplayed = true)
        #end
    #end

Here is a sample of possible outcomes:
Name  Value
Rick    1
        2
Morty   1
        1
        3
Filipe  2
        3
Jose    3

Thanks for any suggestions!

A: I think $velocityCount will do the trick. Like:
#foreach( $person in $view.people )
    #foreach($personInfo in $person.infos)

                #if($velocityCount == 1)
                    $person.name
                #end

            [value]</td

    #end
#end

This example most probably won't work as I can't test it and some fiddling has to be done, but it should illustrate the idea alright.
Every for-each-loop has its own $velocityCount. So if necessary you can place another one in the outer loop and do some calculation (I'm saying that, because I couldn't figure out how the values are made and you don't read'em from an object).


text:
Q: unable to send post request using angular I am sending a form data using HTTP post where it will be like this
     saveDataFile(mutlidata,id,value): Observable<Response> {

        var _url = 'http://xxxx.xxx.xxx';
        var saveDataURL = _url + '/' + id;
        var _this = this;

        let headers = new Headers();
        headers.append('Content-Type', 'multipart/form-data');
        let options = new RequestOptions({ headers: headers });
        const frmData = new FormData();
        frmData.append("file",JSON.stringify(mutlidata),'sample.json');
        frmData.append("dataCheck",value);

        return this.http.post(saveDataURL,frmData, options).pipe(
            map((res: Response) => {
                 return res;
            }),
            catchError(this.handleError),);

    }

here multidata will have
    [["fakepath/test1.JPG","ea305e-be9d"],["fakepath/test2.JPG","489ce580-c50e-40e6-b1ab-71c7827f636c"]]

    id will have 15asdas6asd6

    value will have  either true / false

here it is not sending the form data I guess and when I debug and checking the frmdata in return this.http.post(saveDataURL,frmData, options) here it is display form.entries, values, etc
in the sample.json file I'm appending the formdata
frmData.append("file",JSON.stringify(mutlidata),'sample.json');

and here file means I will have to send the data to the API using that key word

A: There is no need to append the Content-Type, as the browser will handle it for you. The last time I tried manually adding it to my post request, it has caused my HTTP request to fail. You can just remove the part of the code.
saveDataFile(mutlidata,id,value): Observable<Response> {

  var _url = 'http://xxxx.xxx.xxx';
  var saveDataURL = _url + '/' + id;
  var _this = this;

  const frmData = new FormData();
  frmData.append("file",JSON.stringify(mutlidata),'sample.json');
  frmData.append("dataCheck",value);

  return this.http.post(saveDataURL, frmData, options).pipe(
    map((res: Response) => {
         return res;
    }),
    catchError(this.handleError),);
}


text:
Q: Using pugixml in Visual C++ .NET 2010 I am building a GUI for my final project. This project uses pugixml as xml parser for reading some data. Everything works in console mode.
So I started a new windows form project and I added all the headers files I wrote. I desgined my GUI etc. When I try to compile everything compiles but this:
pugixml.cpp(5627): error C2440: 'return' : cannot convert from 'System::String ^' to 'const pugi::char_t *'
          No user-defined-conversion operator available, or
          Cannot convert a managed type to an unmanaged type
Here is the code where the error comes from:
const char_t* convert_number_to_string_special(double value)
    {
    #if defined(_MSC_VER) || defined(BORLANDC)
        if (_finite(value)) return (value == 0) ? PUGIXML_TEXT("0") : 0;
        if (_isnan(value)) return PUGIXML_TEXT("NaN");
This line---->       return PUGIXML_TEXT("-Infinity") + (value > 0);
I tried to change the configuration of the project but I didn't get anything straight.
Any clue? I'd appreciate very much!
Thanks in advance!

A: This is the compatibility bug; unfortunately, pugixml 1.0 was not fully tested with C++/CLI (as far as I'm aware, this is the only problem with C++/CLI, so after fixing this you can use pugixml safely).
You can either get the most recent version from the repository (http://pugixml.googlecode.com/svn/trunk/)
or manually apply the patch: replace the line
return PUGIXML_TEXT("-Infinity") + (value > 0);
with
return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");


text:
Q: FBSDK Login Error Code: 308 in Objective-C I keep getting

"Error Domain=com.facebook.sdk.login Code=308 "The operation couldn't
  be completed. (com.facebook.sdk.login error 308.)""

upon trying to login with Facebook from my device.
My code works on the simulator, but not on an actual device. Has anyone ran into this error code before? I'll be more than happy to share code upon request.

A: My solution on Xcode7.1, Swift2.0
Step 1. Clean your build folder: option + command + K
or: Choose Product > Clean

Step 2. Clean your derived data: Choose Window > Projects:

and then choose Delete:

A: The solution below works for iOS9 + running on Xcode 8, for Swift3.0
The steps are

*

*Setup Facebook Launch

FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

*Setup Open Url
guard let source = options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String else { return false }
    let annotation = options[UIApplicationOpenURLOptionsAnnotationKey] as? String
    return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: source, annotation: annotation)

*Fix Keychain permission issue as shown in the image below

A: One solution, at least for me, is to not run on device via the Xcode debugger. If I run the app on device outside the debugger the Facebook login works fine. If I run the app in the sim via the debugger the Facebook login works fine.
Only if I run the app on device via the Xcode debugger do I get the com.facebook.sdk.login error 308 every time.

A: You should enable Keychain Sharing on the Capabilities tab.

A: I had the same problem and fixed it refreshing the system credentials
[FBSDKLoginManager renewSystemCredentials:^(ACAccountCredentialRenewResult result, NSError *error) {

    [[[YourAuthManager manager] facebookLoginManager] logInWithReadPermissions:@[@"email"] fromViewController:nil handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {

        if (error) {
            // Handle error
        } else if (result.isCancelled) {
            // Handle cancellations
        } else {
            // If you ask for multiple permissions at once, you
            // should check if specific permissions missing
            if ([result.grantedPermissions containsObject:@"email"]) {
                // Do work
            }
        }
    }];
}];

This solution is less radical than reinstalling and you assure your users won't have to do it. My guess is that FBSDK 4.6 has some conflicts with iOS 9 system FB authentication credentials.
Edited: After some time testing it kept happening, not as often as before but it was still an issue, so we downgraded to a previous version of FB SDK. Hopefully someone finds a better solution.

A: Did some digging around in FBs code and it looks like this is simply an entitlements issue.
FB uses the keychain to store an authorization challenge during login. When returning it attempts to get the value from the keychain and fails. See this SO answer for more info.
Security entitlements can change between provisioning profiles, and as we all know, keeping our profiles and build configurations and devices/sims straight is like herding cats. This could explain why people experience such inconsistent behavior.
So it might be safe to assume that in a production environment, everything will work fine, and if things aren't working during testing then you need to double-check the entitlements on your provisioning profiles.

A: I had exactly the same problem and was able to find the solution by modifying the Info.plist
I've added all the possible schemes to LSApplicationQueriesSchemes
The complete list looks like this:
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fbapi</string>
    <string>fbapi20130214</string>
    <string>fbapi20130410</string>
    <string>fbapi20130702</string>
    <string>fbapi20131010</string>
    <string>fbapi20131219</string>
    <string>fbapi20140410</string>
    <string>fbapi20140116</string>
    <string>fbapi20150313</string>
    <string>fbapi20150629</string>
    <string>fbauth</string>
    <string>fbauth2</string>
    <string>fb</string>
    <string>fb-messenger-api20140430</string>
    <string>fb-messenger-platform-20150128</string>
    <string>fb-messenger-platform-20150218</string>
    <string>fb-messenger-platform-20150305</string>
    <string>fb-messenger-api</string>
    <string>fbshareextension</string>
</array>

A: I'm getting the exact same thing FB SDK 4.6.0 Xcode 7.0 iOS9. All the setup & instructions on the facebook developer site were followed to the letter.
None of the above solutions worked for me. I'm finding that the behaviour is worse when you're deploying to the device live and feeding back to the Xcode console while doing the login procedure. It's really pot luck if it actually logs you in or not. It seems to behave in a more predictable way when you just re-launch your app cold after deployment. -Yes this is in fact the case!
When it decides to fail to login it results in the following error:
Error Domain=com.facebook.sdk.login Code=308 "(null)"

A: In my case it was fixed by updating to latest FB SDK. 4.10 at the moment.

A: I fixed the problem by uninstalling the app and re-installing and it worked right away.
The error is probably related to iOS 9. Since iOS 9, I think the SDK uses SafariViewController and it seems to create issues when you are already logged.

A: I was able to get login working again on iOS9 with SDK 4.6.0 by adding the new plist key/value
<key>FacebookDisplayName</key>
<string>{Your App Name}</string>

Source code.
I also took the steps in some other answers here to implement a shared FBSDKLoginManager() instance.

A: I was getting the same error on xcode 7.1 ios 9.1 FB SDK 4.7.1. .
Uninstalling, installing and testing without xcode works fine for the first time.
This will allow you to plug back in the device and run it at least a couple of times (it seems to be a bit inconsistent...)

A: Same problem FB SDK 4.5.1 and none of the above solutions worked for me.
I solved this by adding Bolts framework to project by drag & drop (from FacebookSDK directory)
and then adding bolts framework to appDelegate
    #import <bolts/bolts.h>

A: In the FBSDKDelegate Method loginButtonWillLogin put this
- (BOOL) loginButtonWillLogin:(FBSDKLoginButton *)loginButton{
[FBSDKAccessToken setCurrentAccessToken:nil];
return YES;}

A: Updating to the latest (4.11) FB SDK fixed this for me as well.  Don't forget to clean your project after updating to see if it works for you!

A: To Resolve this issue you needs to just enable "Keychain Sharing" in capabilities.

A: I followed Suraj Pathak with Xcode 9.4.1 and Swift 4.2

*

*Add to AppDelegate didFinishLaunchingWithOptions
SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

*Add to AppDelegate delegate function
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    return SDKApplicationDelegate.shared.application(app, open: url, options: options)
}

*Allow Keychain in Capabilities.

A: If you are using FBSDK 4.38 there is a bug with the parsing of challengeExpected in FBSDKLoginManager.m.
I found a hot fix of rinat-enikeev for it:
https://github.com/facebook/facebook-sdk-swift/issues/286
https://github.com/facebook/facebook-objc-sdk/pull/922/commits/bcf7f787e92320a6322fb3f6130fdc3815bbafb7
Just change
NSString *challengeExpected = [self loadExpectedChallenge];

to
NSString *challengeExpected = [[self loadExpectedChallenge] stringByReplacingOccurrencesOfString:@"+" withString:@" "];

Thats solved the issue for me.


text:
Q: How to change the innerText of an  using javascript When I click on the "show details" link it should change to "hide details". I tried the following code but it's not working:
out.print("show details");

function showHideDetails(id,obj) {
    try
    {

        alert(obj.innerText);
        obj.innerText = 'hide details';
    }
    catch (err)
    {
        alert(err);
    }

}

A: The details in your question are sparse. Here are a few possibilities:
Remove parent. from the inline handler, and change it to an onclick:
"show details"

Perhaps the showHideDetails() function isn't global
Perhaps innerText isn't supported in the browser you're using. Try innerHTML instead.
obj.innerHTML = 'hide details';

A: The problem is that this in your href attribute doesn't point to the anchor. You could pass an identifier there, and give the anchor element the same identified as id attribute; and then use document.getElementById to get the anchor.
Example:
out.print("show details");

function showHideDetails(id,identifier) {
    try
    {
        var obj = document.getElementById(identifier);
        alert(obj.innerText);
        obj.innerText = 'hide details';
    }
    catch (err)
    {
        alert(err);
    }
}

A: InnerText is one of those browser finicky ones that are named differently in different browsers.  If you are just getting started with javascript I would recommend using a framework like jQuery because it's far simpler to call a function like:
$('#linkID').text('show');

Than it is to get each browser variant set properly.  The framework does all that for you.

A: this will point to DOM window and not the  tag. So use onclick attribute to execute.
out.print("
show details");


text:
Q: onclick event on radioButton not working I have a list on which i Want to give on-click event on radio-button of each row in the list.But this code is not working. Giving force close.Please can anyone me help out.I am new to this.
 package com.example.radiogroup;

    import java.util.ArrayList;
    import java.util.HashMap;

    import android.support.v7.app.ActionBarActivity;
    import android.support.v7.app.ActionBar;
    import android.support.v4.app.Fragment;
    import android.app.Activity;
    import android.content.Context;
    import android.database.DataSetObserver;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.BaseAdapter;
    import android.widget.Checkable;
    import android.widget.ImageView;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.RadioButton;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.os.Build;

    public class MainActivity extends Activity implements Checkable
{

    private ArrayList<HashMap<String,Object>> data;
    private ListAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView lv=(ListView)findViewById(R.id.listView1);
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        data=new ArrayList<HashMap<String, Object>>();
        prepareListData();
        adapter = new ListAdapter(this,data);
        lv.setAdapter(adapter);

    /*  lv.setOnItemClickListener(new OnItemClickListener()
        {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id)
            {

            {
                if(position==0)
                {
                    Toast.makeText(getApplicationContext(), "Move forward",
      Toast.LENGTH_SHORT).show();
                }

            }
            }

        }); */

    }
    private void prepareListData()
    {
        HashMap<String,Object> row1=new HashMap<String,Object>();
        row1.put("ID",1 );
        row1.put("NAME","Taj Mahal");
        data.add(row1);

        HashMap<String,Object> row2=new HashMap<String,Object>();
        row2.put("ID",2 );
        row2.put("NAME","Agra Fort");
        data.add(row2);

        HashMap<String,Object> row3=new HashMap<String,Object>();
        row3.put("ID",3 );
        row3.put("NAME","Ram Baugh");
        data.add(row3);

        HashMap<String,Object> row4=new HashMap<String,Object>();
        row4.put("ID",4 );
        row4.put("NAME","Panch Mahal");
        data.add(row4);

        HashMap<String,Object> row5=new HashMap<String,Object>();
        row5.put("ID",5 );
        row5.put("NAME","Musamman Burj");
        data.add(row5);

    }
    class ListAdapter extends BaseAdapter
    {
        private Context context;
        private ArrayList<HashMap<String,Object>> list;
         ViewHolder holder;

         public ListAdapter(Context context,ArrayList<HashMap<String,Object>> list){
                this.context = context;
                this.list = list;
                holder.rb.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v)
                    {
                        Toast.makeText(getApplicationContext(), "Move forward", Toast.LENGTH_SHORT).show();

                    }
                });
         }

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

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

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

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

                if(convertView == null){
                    holder = new ViewHolder();
                    convertView = LayoutInflater.from(context).inflate(R.layout.row,null,false);
                    holder.rb = (RadioButton) convertView.findViewById(R.id.radioButton1);

                    convertView.setTag(holder);
                }else{
                    holder = (ViewHolder) convertView.getTag();
                }

                holder.rb.setText(list.get(position).get("NAME").toString());

            return convertView;
        }
         class ViewHolder
            {
                RadioButton rb;
            }

    }
    @Override
    public void setChecked(boolean checked) {
        // TODO Auto-generated method stub

    }
    @Override
    public boolean isChecked() {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public void toggle() {
        // TODO Auto-generated method stub

    }

}

A: USe it on getview Methed on Adapter
 holder.rb.setOnClickListener(new OnClickListener()
{

            @Override
            public void onClick(View v)
            {
                Toast.makeText(getApplicationContext(), "Move forward",        Toast.LENGTH_SHORT).show();

            }
        });

Use it on OnCreate Methed
 lv.setOnItemClickListener(new OnItemClickListener()
{

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id)
    {

    {
        if(position==0)
        {
            Toast.makeText(getApplicationContext(), "Move forward "+position, Toast.LENGTH_SHORT).show();
        }
  else
   if(position==1)
        {
            Toast.makeText(getApplicationContext(), "Move forward "+position,
       Toast.LENGTH_SHORT).show();
        }

    }
    }

});

A: in constructor of ListAdapter  class you have not  initialize ViewHolder object so you cann't access member of that class.
remove
 holder.rb.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v)
                {
                    Toast.makeText(getApplicationContext(), "Move forward", Toast.LENGTH_SHORT).show();

                }
            });

from ListAdapter constructor and put it in getView() after class and member initialise.
after
 if(convertView == null){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.row,null,false);
                holder.rb = (RadioButton) convertView.findViewById(R.id.radioButton1);

                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }

in getView method.


text:
Q: Java Deprecated Class using a Deprecated Class -- Can I turn off the compiler warning? I am working on deprecating a set of Java classes so they aren't used anymore. I don't want to turn off the compiler warnings for deprecated usage, but I'm finding that if one of my deprecated classes imports another deprecated class I get a warning on that, too. I don't want to modify the code I'm deprecating, but I also don't want the warning for those cases. Is there a way to (a) annotate / comment the code to disable the warning (b) turn off compiler warnings in these cases? I'm using NetBeans, so if there is a NetBeans specific way, that works, too.
Here is a quick example:
First class:
/**
 * @deprecated No longer in use.
 **/
@Deprecated
public class OldSubClass {
}

Second class:
import com.old.package.OldSubClass; // Don't want this to create a warning

/**
 * @deprecated No longer in use.
 **/
@Deprecated
public class OldClass {
       // code that makes use of OldSubClass that I don't want to change ...
       // Any methods that use OldSubClass are also deprecated ...
}

Okay, this is the bare minimum that allows me to reproduce the problem (even with @SupressWarnings turned on:
Mother class:
import another.pack.ChildClass;

@SuppressWarnings("deprecation")
public class MotherClass {
}

Child class:
package another.pack;

/**
 * @deprecated
 */
public class ChildClass {
}

Note that it is the JavaDoc @deprecated tag that even allows the compiler to throw the warning. If I only use the @Deprecated annotation, I never get the warning (even without the supress).

A: You can use this other annotation :

@SuppressWarnings("deprecation")

You place this annotation in the mother class only. You will keep the warning when importing the OldClass but the "recursive warning" for the OldSubClass will be ignored.

A: NetBeans uses javac (from JDK 7) to determine when and where to show warnings like this, so anything that works with jdk7/bin/javac should work in the IDE's editor just the same way.


text:
Q: How do Graviton-based theories of gravity explain the expansion of the universe? In General Relativity, the expansion of the universe is modeled using the Friedmann–Lemaître–Robertson–Walker metric, and the expansion itself is a metric expansion by which the scale of space itself changes over time. Using the Einstein field equations you can derive the Friedmann equations then solve for the scale factor, $a(t)$.
However in recent history there have be many attempts to model a quantum theory of gravity in terms of a graviton which mediates the force of gravity, often in background-dependent theories such as string theory.
My question is, how could a theory like this, especially a background dependant one, model the expansion of the universe? If gravity is modeled as a result of a spin-2 particle and not the curvature of spacetime, how can the metric expansion of space occur?
Any answers, especially pertaining to Quantum Gravity as an Effective Field Theory, or String Theory, would be much appreciated.
EDIT: I have found an article that states that gravitons are fluctuations of the geometry around flat space-time. Perhaps my mistake was assuming that gravitons and space-time curvature are mutually exclusive. As i do not have a great understanding of QFT, this would not be surprising.

A: This is not an exact duplicate of this previous question because it is asking about the connection with the expansion of the universe.
Already in the present model of the expansion of the universe an effective quantum mechanical theory is invoked in order to model the cosmic microwave background (CMB)observations and the horizon problem.. In the quantum mechanical model there are no gravitons, but inflatons that are homogenizing the very early universe to the level observed. This gives a brief but very large expansion of the unviverse at that time:

Graviton based theories of gravity are models relevant after the inflation period, when particles as we know them form from the primal energy. Gravitons have no role in the expanding of the universe at the rate of the simple Big Bang to which it returns after inflation. There are observations of an accelerated expansion rate, and there it is an open research problem, whether inflatons continue to have a role, or what model fits the observations.

My question is, how could a theory like this, especially a background dependant one, model the expansion of the universe? If gravity is modeled as a result of a spin-2 particle and not the curvature of spacetime, how can the metric expansion of space occur?

One must not confuse frameworks in physics. For example, the complete thermodynamic theory framework  emerges from the underlying statistical mechanics , with completely different variables, but it has been shown that this emergence is compatible with the data.
There are only effective quantum mechanical models for quantization of gravity. The expectation is that the definitive model will reproduce the macroscopic frame of General Relativity . (otherwise it would not be a correct quantum mechanical underlying framework). Here is an answer on how general relativity can emerge from string theory, which has gravitons. All this is a matter of current research.
The  expansion  of the universe itself is an emergent effect using   the mathematical framework of General Relativity. The expectation is that this emergence will be proven rigorously once a definitive model of the quantization of gravity is found.

A: Gravitons are fluctuations of the gravitational field, just as photons are fluctuations of the electromagnetic field. Thus the field can still be warped in the GR sense.


text:
Q: I want to go to last record of access database without using ID I have been trying to find this. I am using access 2010 and I have some data in a few tables and I want to select the last row from each one and add them to a new database. All the databases have random ID so I can't use the Sort by ID function.

A: If the table is small, you can pass it to a datatable in the frontend and use something like this,
lastRow = datatable.rows(datatable.rows.count-1)

Else, You can add a 'created_datetime' field in database which holds the inserted datetime and retrieve its maximum date since your ID field has random number...

A: open vba (alt + F11)
dim rst as recordset
set rst = docmd.runsql (sql statement here) e.g. (select * from tablename)
rst.movelast

you've gotten to your last record in vba
you can add it to a new table database by using an insert statement.


text:
Q: When there is no entry in database, if (dataSnapshot.getValue() == null) returns true but also run the else part after finishing the "if" part I have a register page in my app, and while registering, i check if the name is already registered or not in firebase. And if the name is already present, I am getting the toast message("user already exist") as required, but if there is a new entry, I am able to register perfectly but I am also getting the toast message after registration.
Please refer the below code:
mFirebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Registration");

mFirebaseDatabase.orderByChild("uname").
equalTo(name.getSelectedItem().toString().trim()).addValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (dataSnapshot.getValue() == null) {
            if (TextUtils.isEmpty(userId)) {
                createUser(name.getSelectedItem().toString().trim(),
                           designation.getSelectedItem().toString().trim(),
                           phone.getText().toString().trim(),
                           email.getText().toString().trim(),
                           password.getText().toString().trim(),
                           email1.getText().toString().trim(),
                           phone1.getText().toString().trim(),
                           telephone.getText().toString().trim());
                 Intent login = new Intent(Register.this, Login.class);
                 startActivity(login);
             }
         } else {
             Toast.makeText(Register.this, "User already Registered", Toast.LENGTH_SHORT).show();
         }
     }

     @Override
     public void onCancelled(@NonNull DatabaseError databaseError) {}
 });

So After registration, I am getting the message "user already registered"

A: This is a normal behavior.
From the docs:

Important: The onDataChange() method is called every time data is changed at the specified database reference, including changes to children. To limit the size of your snapshots, attach only at the highest level needed for watching changes. For example, attaching a listener to the root of your database is not recommended.

So the first time it checks the user is not there and therefore it creates it. But by creating it you're probably pushing it to firebase which triggers the onDataChanged again and you see the toast.
If you want to execute it only one time change addValueEventListener to addListenerForSingleValueEvent (check specifically the section Listen for value events)

A: What you are doing wrong is that you are checking for the dataSnapshot.getValue() == null everytime
 @Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

if (dataSnapshot.getValue() == null) {
  ....
 }else{
      Toast.makeText(Register.this, "User already Registered",
      Toast.LENGTH_SHORT).show();

 }
}

In this case what happens when you came for the first time there is no user data  dataSnapshot.getValue() was null and then you created a user using your method createUser() and just after you create your user firebase triggers a callback in your onDataChange( DataSnapshot dataSnapshot) method and this time dataSnapshot.getValue() is having your user data and the condition you are checking take control to else part and toast appears.
OnDataChanged is called every time you change a value in your firebase on that reference.
You need to change the if and else condition to check whether a user is registered or not if registered show a toast else register them.

A: I think when you create new user and add to firebase database the onDataChange listener have been triggered one more time.
You can try this code maybe help you:
boolean isUserCreated = false;
mFirebaseDatabase....addValueEventListener(new ValueEventListener() {

@Override
public void onDataChange(...) {
    if (dataSnapshot.getValue() == null) {
        if (TextUtils.isEmpty(userId)) {
            isUserCreated = true;
            createUser(...)
         }
     } else if (!isUserCreated) {
         Toast.makeText(Register.this, "User already Registered", Toast.LENGTH_SHORT).show();
     }
 }
...
});

Note: This code is concise. You must notice to isUserCreated variable and usage of that.


text:
Q: Java ArrayList search using the first letter I have an ArrayList in java with a bunch of string items inside it, I want to be able to specify a single letter and in return get all of the strings that begun with the single letter that was specified.
Is there a method I can call upon which makes this process easy? or would I just have to iterate through each item in the array list at index 0?
I dont know a lot about Array Lists but the assignment I am working on requires me to use them, I hope someone can shed some light on this for me! :-)
Also I know there are similar questions on here that tell you how to search an array list, I just want to know how to do it whilst looking for the first letter of each item in the array list to see if the letter matches the letter that the user gives to it.

A: Perhaps, something like this:
public static List<String> getPossibleStrings(List<String> strings, String query) {
        List<String> result = new ArrayList<String>();
        for (String s: strings) {
            if (s.startsWith(query))
             result.add(s);
        }

        return result;
 }

A: As far as I know, there is no java method that, given a character, will search an ArrayList and return all Strings that begin with that letter. I believe you need to  loop through the ArrayList and for each String, see if it starts with the character that you are looking for. You can get the first character of a String using the substring method:
myString.substring(0,1);

A: If you are viewing this a few years later and startsWith isn't working or you don't wanna use it, try something like this.
public static int findAmount(ArrayList<String> items, String letter) {

    int count = 0;

    for (int i = 0; i < items.size(); i++) {

        if (items.get(i).substring(0, 1).equals(letter)) {

            count++;

        }
    }
    return count;
}

(As per substring, you will be comparing only the first char in the items.get(i) with the single char letter)

A: Could use Java 8 streams.
List<String> myList = Arrays.asList("apple", "grape");
String start = "a";
myList.stream()
    .filter(x -> x.startsWith(start))
    .forEach(System.out::println);

Outputs apple


text:
Q: QDK file not found error in LiH Simulation I am on MacOS.  While "dotnet run" on unmodified version of "LithiumHydrideGUI" I am getting the following unhandled exception as

File Not Found for
  'Quantum-release-v0.3.1810/Chemistry/LithiumHydrideGUI/..\IntegralData\YAML\LiHData\integrals_lih_sto-3g_0.800.nw.out.yaml'.

I do see that the file is very much present in the directory one level up that is at "Chemistry" folder.  Please let me know how to fix this.

A: You need to switch the direction of the slashes from "\" to "/". You will find the line for this in the "Program" file.


text:
Q: How to fix cfchartseries in coldfusion 11? I'm trying to fix my cfchart in CF11 to look some similar like in previous CF9. I converted my .xml files and instead I use JSON to style my elements. Problem that I can not fix is cfchartseries. My data that i'm passing in my chartseries looks good, I tried to output everything on the screen before I tested my chart. In CF9 my Time records were displayed on the screen from the first value all the way up to the last value. Here is my screen shot of my chart in CF9:
As you can see on the picture above all my time slots are displayed on the screen in order from the lowest to the highest. Also my record for 2015 is displayed with the bar in blue color, 2016 in pink color. Now I will show you my chart with the exact same code in CF11:
You can see thatmy chart in CF11 starts with the blue bar that present year 2015 and time slot that should not be on the first spot 1415. Also my other time slots are not displayed on the screen. I have tried so hard to get this done but still did not find any solutions. I'm wondering if anyone can help with this problem. Below is my code and I will show you both codes for CF9 and CF11.
Code for chart in CF9:
<cfchart format="#ffPrint#" xaxistitle="#desc#" yaxistitle="#yTitle#" style="ChartStyle.xml"
  chartheight="700" chartwidth="#graphWidth#" title="#title#"  showlegend="#theLegend#" >

  <cfchartseries type="bar" itemcolumn="Spacer" valuecolumn="" seriescolor="white"  >
  <cfoutput>
  <cfloop list="#dataList#" index="i">
  <cfchartdata item="#i#" value="0">
  </cfloop>
  </cfoutput>
  </cfchartseries>

  <cfoutput query="getRecords" group="theYear">
  <cfchartseries type="bar" itemcolumn="#theYear#" valuecolumn="theCount" seriescolor="#listGetAt(theColors,colorIndex)#" >
  <cfset colorIndex++>
  <cfoutput>
  <cfchartdata item="#Description#" value="#theCount#">
  </cfoutput>
  </cfchartseries>
  </cfoutput>
  </cfchart>

Code for my chart in CF11:
<cfchart format="html" xaxistitle="#desc#" yaxistitle="#yTitle#" style="#cStyle#"
  chartheight="700" chartwidth="#graphWidth#" title="#newTitle2#"  showlegend="#theLegend#">

  <cfoutput query="getRecords" group="theYear">
  <cfchartseries type="bar" itemcolumn="#theYear#" valuecolumn="theCount" seriescolor="#listGetAt(theColors,colorIndex)#" serieslabel="#theYear#">
  <cfset colorIndex++>
  <cfoutput>
  <cfchartdata item="#Description#" value="#theCount#">
  </cfoutput>
  </cfchartseries>
  </cfoutput>
  </cfchart>

In order to get any records in CF11 I had to remove my first CFCHARTSERIES, still if I have combination of 2015 and 2016 years records my chart does not display values on the screen. I think that problem is in CFCHARTSERIES but I do not what should be changed to fix this issue. If anyone can help please let me know.
Thanks in advance!


text:
Q: Fetch values from multiple lines and combine We forwarded app logs to splunk from different host and different sources.
Thread1 requestId=aUniqueID1 table=Table1

Thread1 size=2gb

Thread2 requestId=aUniqueID5 some other log

Thread1 requestId=aUniqueID1 some other log

Thread2 size=5gb

Thread1 requestId=aUniqueID2 table=Table2

Thread1 size=4gb

Thread1- requestId=aUniqueID3 table=Table3

Here I want to a table of request Id and size
aUniqueId1  2gb

aUniqueId2  4gb

aUniqueID5 5gb

Basically, thread name stays the same per host, but the same thread will be reused once a request is completed.
Can someone help write a Splunk query?
When a request comes, a log can be identified with thread name (Thread1,Thread2,etc)
Basically for a transaction, most log statements have requestId and I know the start and end times, thus I know the size within that time range (by host and sourcetype and thread name)

A: Here is a run-anywhere example of how to do that.
| makeresults | eval data="Thread1 requestId=aUniqueID1 table=Table1
Thread1 size=2gb
Thread1 requestId=aUniqueID1 some otherlog
Thread1 requestId=aUniqueID2 table=Table2
Thread1 size=4gb
Thread1 requestId=aUniqueID3 table=Table3" | eval data=split(data,"
") | mvexpand data | eval _raw=data
```Everything above sets up test data.  Omit when using live data```
```Combine requestId and size lines```
| transaction startswith="requestId" endswith="size"
```Parse the results```
| extract kvdelim=" ", pairdelim="="
```Display request ID and corresponding size```
| table requestId size


text:
Q: (NestJS, TypeORM) Javascript promises : Finally block is called before then I am creating an API with CRUD operations for User resource. Because TypeORM doesn't return the created user after inserting it to the database, I perform a 'findOne' request to get it back providing the userName.
In order to do this I created a transaction in my UserService using QueryRunner. It looks like this :
Controller
@Post()
  create(@Body() user: User) {
    return this.userService
      .createUser(user)
      .then((user) => {
        return user;
      })
      .catch(() => {
        throw new InternalServerErrorException('Could not create user');
      });
  }

Service
createUser(user: User): Promise<User | void> {
    const queryRunner = this.connection.createQueryRunner();

    return queryRunner
      .connect()
      .then(() => {
        queryRunner
          .startTransaction()
          .then(() => {
            queryRunner.manager
              .save(User, user)
              .then((user) => {
                queryRunner.manager
                  .findOne(User, {
                    username: user.username,
                  })
                  .then((user) => {
                    queryRunner
                      .commitTransaction()
                      .then(() => {
                        return Promise.resolve(user);
                      })
                      .catch((error) => {
                        console.log('Could not commit transaction : ', error);
                        return Promise.reject();
                      });
                  })
                  .catch((error) => {
                    console.log(
                      `Could not get user after insert, username : ${user.username}, error : ${error}`,
                    );
                    return Promise.reject();
                  });
              })
              .catch((error) => {
                console.log(
                  'Could not insert user into the database : ',
                  error,
                );
                queryRunner
                  .rollbackTransaction()
                  .then(() => {
                    console.log('Rolled back transaction');
                    return Promise.resolve();
                  })
                  .catch((error) => {
                    console.log('Could not rollback transaction : ', error);
                    return Promise.reject();
                  });
              });
          })
          .catch((error) => {
            console.log('Could not start transaction : ', error);
            return Promise.reject();
          });
      })
      .catch((error) => {
        console.log('Could not connect to database : ', error);
        return Promise.reject();
      })
      .finally(() => {
        queryRunner
          .release()
          .then((user) => {
            console.log('Released query runner for User transaction');
            return Promise.resolve(user);
          })
          .catch((error) => {
            console.log('Could not release queryRunner : ', error);
            return Promise.reject();
          });
      });
  }

There are many issues in this code and I am aware of it, but I am new to the javascript world and don't know how to do better:

*

*I looked on the internet and some people call what I am doing (nesting promises) a pyramid of doom and that it is an anti-pattern, but I don't know how to do otherwise.

*When I run my code and do a request to create the user, the finally() block is being called before then() and thus release my queryRunner before I do my transaction. Can anyone tell me why?

*In order to fix the issue I removed the finally() and did the release inside then() and catch() but what happened then is that my function returned after calling "startTransaction" and didn't do the then() before, so what happens is that I get back to the controller and return a response to the user before finishing my UserService function (createUser).

I hope that you have enough information to help me, but I will be glad to add more details if needed.
Thank you,

A: regards your questions
1- try to convert your function to async and use async/await this will give you a clearer look to the logic you are trying to implement
2- finally being called before then probably means an error has occurred, try logging the error in the catch and debug it
this is not the answer, I'm just showing you an alternative way to the promises pyramid, I hope I got your logic right
async function createUser(user): Promise<any> {
    const queryRunner =  this.connection.createQueryRunner();

    await queryRunner.connect().catch(throwErr("couldn't connect") )

    await  queryRunner.startTransaction().catch(throwErr('could not start transaction'))

    const  User = await queryRunner.manager.save(user).catch(throwErr("could not save user") )

    await queryRunner.commitTransaction().catch(throwErr("could not complete transaction"))

    await queryRunner.release().catch(throwErr('Could not release queryRunner'))

    const foundedUser = await queryRunner.manager.findOne(User, {
        username: user.username,
    }).catch(throwErr("Could not connect to database"))

    return foundedUser
}

function throwErr(message){
    return (err)=> {throw new Error(message)}
}

A: Thanks to scr2em and David Callanan I changed my code from nested promises to async/await and now it's working, this is what I did:
async createUser(user: User): Promise<User | void> {
    const action = `(Create user : ' ${user.username}) `;
    const queryRunner = this.connection.createQueryRunner();

    await queryRunner.connect().catch((error) => {
      console.log(action + 'Could not connect to database : ', error);
      return Promise.reject();
    });
    await queryRunner.startTransaction().catch((error) => {
      console.log(action + 'Could not start transaction : ', error);
      return Promise.reject();
    });
    await queryRunner.manager.save(User, user).catch(async (error) => {
      console.log(action + 'Could not insert user into the database : ', error);
      await queryRunner.rollbackTransaction().catch((error) => {
        console.log(action + 'Could not rollback transaction : ', error);
        return Promise.reject();
      });
      return Promise.reject();
    });
    const userResult = await queryRunner.manager
      .findOne(User, { username: user.username })
      .catch(async (error) => {
        console.log(
          action +
            `Could not get user after insert, username : ${user.username}, error : ${error}`,
        );
        await queryRunner.rollbackTransaction().catch((error) => {
          console.log(action + 'Could not rollback transaction : ', error);
          return Promise.reject();
        });
        return Promise.reject();
      });
    await queryRunner.commitTransaction().catch((error) => {
      console.log(action + 'Could not commit transaction : ', error);
      return Promise.reject();
    });
    await queryRunner.release().catch((error) => {
      console.log(action + 'Could not release queryRunner : ', error);
      return Promise.reject();
    });
    return Promise.resolve(userResult);
  }

Hope that it will help someone else.