text:
Q: VBA dialog boxes automatically answer solution I compiled and coded a macro for Outlook 2011. This macro for that it saves all the mails as word file.
The problem is that I couldn't close the dialog box automatically, I have so much signed message I couldn't solve this problem.
This is the message dialog:

And the code:
Option Explicit
       Dim StrSavePath     As String

Sub SaveAllEmails_ProcessAllSubFolders()

    Dim i               As Long
    Dim j               As Long
    Dim n               As Long
    Dim strSubject      As String
    Dim StrName         As String
    Dim StrFile         As String
    Dim StrReceived     As String
    Dim StrFolder       As String
    Dim StrSaveFolder   As String
    Dim StrFolderPath   As String
    Dim iNameSpace      As NameSpace
    Dim myOlApp         As Outlook.Application
    Dim SubFolder       As MAPIFolder
    Dim mItem           As Object
    Dim docItem         As Object
    Dim FSO             As Object
    Dim ChosenFolder    As Object
    Dim Folders         As New Collection
    Dim EntryID         As New Collection
    Dim StoreID         As New Collection
    Dim checkIfDigitallySigned As Long

    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set myOlApp = Outlook.Application

    Dim OLIns As Outlook.Inspector
    Set iNameSpace = myOlApp.GetNamespace("MAPI")
    Set ChosenFolder = iNameSpace.PickFolder

    Const olAlertsNone = 0
    If ChosenFolder Is Nothing Then
        GoTo ExitSub:
    End If

   Set docItem = Application.CreateItem(olMailItem)
  docItem.BodyFormat = olFormatRichText

    BrowseForFolder StrSavePath

    Call GetFolder(Folders, EntryID, StoreID, ChosenFolder)

    For i = 1 To Folders.Count
        StrFolder = StripIllegalChar(Folders(i))
        n = InStr(3, StrFolder, "\") + 1
        StrFolder = Mid(StrFolder, n, 256)
        StrFolderPath = StrSavePath & "\" & StrFolder & "\"
        StrSaveFolder = Left(StrFolderPath, Len(StrFolderPath) - 1) & "\"
        If Not FSO.FolderExists(StrFolderPath) Then
            FSO.CreateFolder (StrFolderPath)
        End If

        Set SubFolder = myOlApp.Session.GetFolderFromID(EntryID(i), StoreID(i))
        On Error Resume Next
        For j = 1 To SubFolder.Items.Count
            Set mItem = SubFolder.Items(j)
            StrReceived = Format(mItem.ReceivedTime, "YYYYMMDD-hhmm")
            strSubject = mItem.Subject
            StrName = StripIllegalChar(strSubject)
            StrFile = StrSaveFolder & StrReceived & "_" & StrName & ".doc"

            StrFile = Left(StrFile, 256)
            mItem.SaveAs StrFile, olRTF

        Next j
        On Error GoTo 0
    Next i
ExitSub:

End Sub

Some utility functions used by the macro:
Function StripIllegalChar(StrInput)
    Dim RegX            As Object

    Set RegX = CreateObject("vbscript.regexp")

    RegX.Pattern = "[\" & Chr(34) & "\!\@\#\$\%\^\&\*\(\)\=\+\|\[\]\{\}\`\'\;\:\<\>\?\/\,]"
    RegX.IgnoreCase = True
    RegX.Global = True

    StripIllegalChar = RegX.Replace(StrInput, "")

ExitFunction:
    Set RegX = Nothing

End Function

Sub GetFolder(Folders As Collection, EntryID As Collection, StoreID As Collection, Fld As MAPIFolder)
   Dim SubFolder       As MAPIFolder

    Folders.Add Fld.FolderPath
    EntryID.Add Fld.EntryID
    StoreID.Add Fld.StoreID
    For Each SubFolder In Fld.Folders
        GetFolder Folders, EntryID, StoreID, SubFolder
    Next SubFolder

ExitSub:

    Set SubFolder = Nothing

End Sub

    Function BrowseForFolder(StrSavePath As String, Optional OpenAt As String) As String
        Dim objShell As Object
        Dim objFolder '  As Folder
    Dim enviro
    enviro = CStr(Environ("USERPROFILE"))
    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.BrowseForFolder(0, "Please choose a folder", 0, enviro & "\Documents\")
    StrSavePath = objFolder.self.Path
        On Error Resume Next
        On Error GoTo 0

ExitFunction:

     Set objShell = Nothing

End Function

A: There is no way to turn that prompt off. You can try to use Redemption (I am its author) to bypass the prompts. Note that signed/encrypted messages are processed separately since they need to be decrypted first.
    set rSession = CreateObject("Redemption.RDOSession")
    rSession.MAPIOBJECT = myOlApp.Session.MAPIOBJECT
    set rFolder = rSession.GetRDOFolderFromOutlookObject(SubFolder)
    ser rItems = rFolder.Items
    For j = 1 To rItems.Count
      Set mItem = rItems(j)
      if TypeName(mItem) = "RDOEncryptedMessage" Then
        'process encrypted/signed messages separately
        mItem = mItem.GetDecryptedMessage
      Enf If
      StrReceived = Format(mItem.ReceivedTime, "YYYYMMDD-hhmm")
      strSubject = mItem.Subject
      StrName = StripIllegalChar(strSubject)
      StrFile = StrSaveFolder & StrReceived & "_" & StrName & ".doc"

      StrFile = Left(StrFile, 256)
      mItem.SaveAs StrFile, olRTF
    Next j


text:
Q: C# - From what collection size should I start using Dictionary I was surprised I couldn't find an answer to this.
So I know a Dictionary does look-ups in O(1) asymptotically but with a hashing overhead. Is there like a rule of thumb for a collection size under which a List is preferable to a Dictionary? Tens of items? hundreds? Thousands?

A: In my experience, tipping point is between 10 - 50 items, depending on usage pattern and complexity of your hash function. But you should do benchmark on your data, especially if your custom hash function can take a while to calculate cache.
You can also use HybridDictionary that is internally a List for small amount of entries and Hash table after that. .Net framework source shows cutover point at 9 items.
    public class HybridDictionary: IDictionary {

    // These numbers have been carefully tested to be optimal. Please don't change them
    // without doing thorough performance testing.
    private const int CutoverPoint = 9;
    private const int InitialHashtableSize = 13;
    private const int FixedSizeCutoverPoint = 6;

Update: as @Hans Passant pointed out in comment above, Hybrid dictionary doesn't have generic version which can affect performance for boxing/unboxing and overall usage. So, you should be careful and do benchmarks for your situation. My point was to show, that something about ~10 items can be a point to start using dictionary vs list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why the interval will become faster and faster if I keep setting new interval I am doing a very simple timer with two buttons: stop and set.
Here is the code:

0

   <button onclick = 'set()'>Set</button>
   <button onclick = 'stop()'>Stop</button>

     var click = false;
        let interval
    function set(){
        interval = setInterval(function(){
    document.querySelector('h1').textContent = parseFloat(document.querySelector('h1').textContent)+1
        },1000)
    }
    function stop(){
        window.clearInterval(interval)
    }

I found that if I keep pressing the set button which will set new interval, the speed of adding 1 to h1 will become faster and faster (which is much faster than 1000 ms).
I know I could gather the two buttons to one button, or make the set button become display: none or use other ways to prevent this situation.
But I just wonder why does this happens.
Could someone explain me a little bit about why this happens?
Thanks for any responds?

A: That's because you are not clearing the previous interval (simply reassigning it) on your set function, so if you click on set three times, you are running three intervals.
The proper code should be:
function set(){
  clearInterval(interval);

  interval = setInterval(function(){
    document.querySelector('h1').textContent = parseFloat(document.querySelector('h1').textContent)+1
  }, 1000)
}

A: an other way, more user friendly ?

const h1_element = document.querySelector('h1')
    , btSet      = document.querySelector('#bt-set')
    , btStop     = document.querySelector('#bt-stop')
    ;
var interval = 0
  , counter  = 0
  ;
btSet.onclick =()=>
  {
  btSet.disabled = true
  btStop.disabled = false
  interval = setInterval( ()=> { h1_element.textContent = ++counter }, 1000 )
  }
btStop.onclick =()=>
  {
  clearInterval(interval)
  btSet.disabled  = false
  btStop.disabled = true
  }

0

<button id="bt-set">Set</button>
<button id="bt-stop" disabled>Stop</button>

A: an other way ? More RELIABLE , More elegant
Leveraging OOP: where you guarantee a unique interval is running per instance

class IntervalManager {
   constructor(fn, delay){ this.fn= fn; this.delay= delay;}
   start() {this.stop(); this.id= setInterval(this.fn, this.delay);}
   stop() {if (this.id) clearInterval(this.id);}
}
//--- use it now

const counter = new IntervalManager(function(){
  let ui = document.querySelector('h1')
  ui.textContent = parseFloat(ui.textContent)+1
},1000);

0

<button onclick = 'counter.start()'>Set</button>
<button onclick = 'counter.stop()'>Stop</button>

Other examples below show the benefit of using this manager:

class IntervalManager {
   constructor(fn, i){ this.fn= fn; this.i= i;}
   start() {this.stop(); this.id= setInterval(this.fn, this.i);}
   stop() {if (this.id) clearInterval(this.id);}
}
//--- use it now
//-- example 1
const timer = new IntervalManager(() => {
  document.querySelector('#timer h4').textContent = new Date()
}, 1000)

//-- example 2
counterIncrem= 0
const counter = new IntervalManager(() => {
  counterIncrem++;
  document.querySelector('#counter h4').textContent = counterIncrem
}, 1000)

Timer

_

  <button onclick = 'timer.start()'>Start</button>
  <button onclick = 'timer.stop()'>Stop</button>

counter

_

  <button onclick = 'counter.start()'>Start</button>
  <button onclick = 'counter.stop()'>Stop</button>


text:
Q: Interpolation needed I have a series of datasets which I need to interpolate, I did this once in uni but that was a long time ago. I could use any pointers I can get.
So I have put the data up here in the hope that someone might be able to explain to me how I may resolve this. I realise that by posting my data here someone might do the interpolation for me and suck all the fun out of the exercise but I suppose this is a risk I am willing to take (wink, wink)
The data represents the "Power Curve" of some wind turbines, and is given by the respective manufacturers. A continuous function to represent this data would allow us to compute the power output for a given windspeed and vica-versa. In each case x represents wind speed measured in m/s and y represents power in kW. Leading to something like this:

Series 1            Series 2          Series 3     Series 4       Series 5
x    y            x      y           x   y        x      y       x      y

0    0            0      0           0   0        0      0       0      0
1    0            2.5    0           1   0        1.5    0       1      0
2    2            3.5    22          2   0        2.5    0       2      2
3    18           4.5    62          3   1,5      3.5    23      3      18
4    56           5.5    120         4   17       4.5    78      4      56
5    127          6.5    195         5   44,5     5.5    160     5      127
6    240          7.5    298         6   72       6.5    285     6      240
7    400          8.5    443         7   123,7    7.5    456     7      400
8    626          9.5    614         8   197      8.5    679     8      626
9    892          10.5   792         9   277      9.5    953     9      892
10  1223         11.5   962         10  364      10.5   1255    10     1223
11  1590         12.5   1093        11  445      11.5   1543    11     1590
12  1830         13.5   1190        12  533      12.5   1638    12     1900
13  1950         14.5   1253        13  583      13.5   1670    13     2310
14  2050         15.5   1284        14  618      14.5   1670    14     2310
15  2050         16.5   1298        15  620      15.5   1670    15     2310
16  2050         17.5   1295        16  618      16.5   1670    16     2310
17  2050         18.5   1276        17  580      17.5   1670    17     2310
18  2050         19.5   1245                     18.5   1670    18     2310
19  2050         20.5   1211                     19.5   1670    19     2310
20  2050         21.5   1174                     20.5   1670    20     2310
21  2050         22.5   1148                     21.5   1670    21     2310
22  2050         23.5   1128                     22.5   1670    22     2310
23  2050         24.5   1118                     23.5   1670    23     2310
24  2050                                         24.5   1670    24     2310
25  2050                                         24.5   1670    25     2310

A: Basically, interpolating a polynomial function amounts to solving a system of linear equations. If you have data $(x_1,y_1),(x_2,y_2),(x_3,y_3),\ldots,(x_n,y_n),$ you look for a polynomial of degree $n-1$ fitting the data. Say the polynomial is
$$p(x)=a_n x^{n-1} + a_{n-1} x^{n-2} + a_{n-2} x^{n-3} + \ldots + a_{2} x + a_1$$
Imposing that all your data points lie on the polynomial curve determines the coefficients $a_k$. Indeed, you get a set of equations
$$\left\{\begin{align}
p(x_1) & =  y_1 \\
p(x_2) & =  y_2 \\
\ldots\\
p(x_n) & =  y_n
\end{align}\right.$$
or more explicitly
$$\left\{\begin{align}
a_n x_1^{n-1} + a_{n-1} x_1^{n-2} + a_{n-2} x_1^{n-3} + \ldots + a_{2} x_1 + a_1 & =  y_1 \\
a_n x_2^{n-1} + a_{n-1} x_2^{n-2} + a_{n-2} x_2^{n-3} + \ldots + a_{2} x_2 + a_1 & =  y_2 \\
\ldots\\
a_n x_n^{n-1} + a_{n-1} x_n^{n-2} + a_{n-2} x_n^{n-3} + \ldots + a_{2} x_n + a_1 & =  y_n
\end{align}\right.$$
Solving these equations is then a problem in linear algebra which considering the small amount of points you have in your problems should be easy enough for a computer.
However, I have my doubts, looking at your data, about the value of a polynomial interpolation. For instance, most of your data sets seem to get into an asymptotic regime, i.e. the curve becomes flat for high values. I think that is important and polynomial functions don't exhibit that behaviour. Which means that while interpolating gives a good approximation of intermediate values as it is supposed to do, it doesn't capture the meaning of the data. I suspect that you must have a better curve that fits the data and is empirically or theoretically more valuable than a polynomial interpolation. In that case, fitting the curve would go through a least squares method or something similar. Which is indeed an appropriate question for Cross Validated.
Finally, assuming you still want to go with interpolation, there are other interpolation methods, many of which are implemented in mathematical programming packages. Among them, the famous spline interpolation method. Here are some other interpolation methods you might want to consider.


text:
Q: Content Block types kicking out code we're creating content block 'templates' which work fine when created as an html content block. However when we create as a free form content block it's kicking out some of our code.
Here's the code:

Left Title

Paragraph copy, try and keep roughly equal in both columns. Hit enter at the end of bullet point 3 to add another bullet. Delete any you don't need.

First bullet point with a link

Second bullet point with a link

Third bullet point with a link

Read more ›

Right Title

Paragraph copy, try and keep roughly equal in both columns. Hit enter at the end of bullet point 3 to add another bullet. Delete any you don't need.

First bullet point with a link

Second bullet point with a link

Third bullet point with a link

Read more ›

And the code that's being removed is some of the styles on this  under the Right title:

A: Despite its name, the free form block is not meant to preserve your content as is. It's actually the opposite: it uses CKEditor for a WYSIWYG experience, which some users less familiar with HTML/CSS will find helpful. There is additional processing and validation being done, by CKEditor, the block, the editor, that can impact and modify your code.
In your case, since you want to paste HTML, you want to stick to the html block.

A: We've been experiencing the same issue and have the same reasons for using free form blocks as you. I have an open ticket with Salesforce on the issue and have been told the fix is scheduled to be deployed in January 2018. I keep finding new examples of code being changed/deleted which is very frustrating. I don't know details on what the fix is or if it will actually fix all our problems but I have to be hopeful.
I didn't know the free form block wasn't meant to preserve content, that's a bummer as it seemed as if it could be the best of both worlds. In all my conversations with them over my issue, this intent was never brought up.


text:
Q: Modified react-datepicker not showing value I am using react v.15. Using the react-datepicker library is giving issues when using the default code. I've successfully modified the codes but whenever I click on the selected date, it's not showing any date at all. Here's what my code looks like:
import * as React from 'react';
let DatePicker = require('react-datepicker');
import 'react-datepicker/dist/react-datepicker.css';

export default class DtePicker extends React.Component<any, any> {
    constructor() {
        super()
        this.state = {
            startDate: new Date(),
        }
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange(date) {
        this.setState({
            startDate: date
        });
    };

    render() {
        return (

                <DatePicker
                    dateFormat='yyyy/MM/dd'
                    selected={this.state.startDate}
                    onChange={this.handleChange}
                />

        );
    }
}

Am I missing a code perhaps in my handleChange function? Also, it's a typescript file, using ASP.Net framework.

A: Try this. it's working properly
import React from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

    class DtePicker extends React.Component {
      constructor() {
        super();
        this.state = {
          startDate: new Date()
        };
        this.handleChange = this.handleChange.bind(this);
      }

      handleChange(date) {
        this.setState({
          startDate: date
        });
      }

      render() {
        return (

            <DatePicker
              dateFormat="yyyy/MM/dd"
              selected={this.state.startDate}
              onChange={this.handleChange}
            />

        );
      }
    }

Check this live demo

A: After specifying the versions I was seeing a "date.clone is not a function" error, so I suspected there was an issue with moment.
react-datepicker v0.40.0 uses moment under the hood
issue 1120: DatePicker breaks with "date.clone is not a function" when "selected" date is passed down as a prop
Selected date must be a moment object, so we save each date object as a moment date object.
class DtePicker extends Component {
  constructor(props) {
    super(props); // Don't forget to pass props to super constructor!
    this.state = {
      startDate: moment(new Date())
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(date) {
    this.setState({
      startDate: moment(date)
    });
  }

  render() {
    return (

        <DatePicker
          dateFormat="YYYY/MM/dd" // Also corrected date format
          selected={this.state.startDate}
          onChange={this.handleChange}
        />

    );
  }
}

*

*moment v2.24.0

*react v15.4.1

*react-datepicker v0.40.0

*react-dom v15.4.1


text:
Q: Extract data from the nested parenthesis in bash I'd need a way to extract certain data and store it in file for auditing and migration.
Here's my data look like.
network vlan internal-vlan {
    description "internal-use"
    interfaces {
        1.1 { }
        1.2 { }
    }
    MTU {
    1500
    }
}
network vlan external-vlan {
    description "external-use"
    interfaces {
       2.1 { }
       2.2 { }
    }
    MTU {
    1500
    }
}

I need to extract the vlan names and its descriptions and its interface details in a table format, something like below. If I could a bash script or maybe perl to run through this data file, I'll generate the output in a csv file and could open it for auditing.

Updating the input data & requirement (SORRY), if you notice there is a dummy vlan which does not have MTU, in that I want the MTU columns value to be none.
network vlan internal-vlan {
    description "internal-use"
    interfaces {
        1.1 { }
        1.2 { }
    }
    MTU {
    1500
    }
}
network vlan external-vlan {
    description "external-use"
    interfaces {
       2.1 { }
       2.2 { }
    }
    MTU {
    1500
    }
}
network vlan dummy-vlan {
    description "dummy-use"
    interfaces {
       1.1 { }
    }
}
network interface 1.1 {
    Status {
        UP
    }
}
network interface 1.2 {
    Status {
        UP
    }
}
network interface 2.1 {
    Status {
        DOWN
    }
}
network interface 2.2 {
    Status {
        UP
    }
}

A: This is actually a perfect use for Tcl -- that data is valid Tcl syntax, so we just need to define a network function and we have a valid DSL:
#!/usr/bin/env tclsh

proc network {_ name data} {
    set values [lmap val [concat $name [dict values $data]] {
        format {"%s"} [regsub -all {\s+} [string trim $val] " "]
    }]
    puts [join $values ,]
}

puts {"Vlan","Description","Interfaces","MTU"}
source [lindex $argv 0]

then
$ tclsh parse.tcl datafile
"Vlan","Description","Interfaces","MTU"
"internal-vlan","internal-use","1.1 { } 1.2 { }","1500"
"external-vlan","external-use","2.1 { } 2.2 { }","1500"

Or install tcllib to let it handle the CSV output:
#!/usr/bin/env tclsh
package require csv

proc network {_ name data} {
    puts [csv::join [lmap val [concat $name [dict values $data]] {
        regsub -all {\s+} [string trim $val] " "
    }]]
}

puts [csv::join {Vlan Description Interfaces MTU}]
source [lindex $argv 0]

$ tclsh parse.tcl datafile
Vlan,Description,Interfaces,MTU
internal-vlan,internal-use,1.1 { } 1.2 { },1500
external-vlan,external-use,2.1 { } 2.2 { },1500

For the older Tcl 8.5 version, add this proc to the top of the program:
proc lmap {varname list body} {
    upvar 1 $varname element
    set result {}
    foreach element $list {
        lappend result [uplevel 1 $body]
    }
    return $result
}

To handle different network types, as well as the "none" value, and also to ensure the fields are in the right order:
proc network {type name data} {
    if {$type ne "vlan"} {
        return
    }
    set values [list $name]
    foreach key {description interfaces MTU} {
        set val [expr {[dict exists $data $key] ? [dict get $data $key] : "none"}]
        lappend values [regsub -all {\s+} [string trim $val] " "]
    }
    puts [join $values ,]
}

A: If your input data are uniform, you can try something like the following:
#! /usr/bin/perl
use strict;
use warnings;
use feature qw{ say };

say 'Vlan,Description,Interfaces,MTU';
my @interfaces;
while (<>) {
    if (/(?|network vlan (.*) \{|description (".*"))/) {
        print "$1,";
    } elsif (/interfaces/) {
        @interfaces = ();
    } elsif (/ *(.* \{ \})/) {
        push @interfaces, "$1";
    } elsif (/MTU \{/) {
        my $next = <>;
        say "@interfaces,$1" if $next =~ /^ *(.*)/;
    }
}

If more variation in the data is allowed (i.e. the newlines are optional), you'll have to write a real parser.

A: Provided the configuration file format is similar for all configs :
Using awk :
$ awk '
BEGIN { printf "Vlan,descripton,interfaces,MTU\n" }
{
if ($1 ~ /^network/ ) { printf $3","; }
if ( $1 ~ /description/ ) { printf $2","; }
if ( $1 ~ /^[0-9]\.[0-9]/ ) { printf $1$2$3" "; }
if ( $1 ~ /^[0-9]{2,}/ ) { printf ","$1"\n"; }
} ' input.conf
Vlan,descripton,interfaces,MTU
internal-vlan,"internal-use",1.1{} 1.2{} ,1500
external-vlan,"external-use",2.1{} 2.2{} ,1500


text:
Q: Customize web site for Anonymous users and remember settings and information I have a E-Shop Site and I need some customization for my users like following :

*

*Store favorite products in their own basket.

*Customize products list in order to what are their favorite.

*It must remember their basket next time they want to visit our site.

my question is how I can store information for my customers who are new to my web site also most of customers don't like to have username and password then login first they like to buy during a week and at the end of week pay for them then we can send some products to their locations.
I have already written my application using asp.net with framework 4.0.
So what is the best solution ?

A: ASP.Net profile is an easiest way to implement it. Implementing a Profile Provider and Profile Example: how to use profile in asp.net  and ASP.NET Profile Properties Overview
The profile mapped automatically as you mentioned; anonymous users can add items to basket and their information persist and will be available when they next visit the site and when they logged in or get registered their basket information will be migrated to their account through code easily.

A: The problem is that you need some way to identify your users. You could try using OpenID or Facebook authentication, they won't need to have a username/password pair that way. However, without something like that, your best bet is probably cookies - I wouldn't go with that idea.

A: I can think of only one thing! cookies. But don't you think it will be a bad idea to use your website in a public computer?


text:
Q: Angular Observable HttpInterceptor ForkJoin Not Working I have seen multiple people mentioning issues about this but didn't find any solution for it.
I made a HttpInterceptor to add the token to my requests. Since I am using Firebase for authentication, retrieving the token requires an observable. Everything works fine and the token gets added but it doesn't work if I combine multiple requests with forkJoin.
HttpInterceptor:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.auth.idToken.pipe(
        mergeMap((token: any) => {
            if (token) {
                request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
            }
            return next.handle(request);
        })
    );
}

Some service:
forkJoin(
    this._dataService1.fetch(),
    this._dataService2.fetch(),
).subscribe(
    ([dataService1Data, dataService1Data]) => {
        alert("Completed");  // <-------- This line of code is never reached
    }
)

Unfortunately, the line above in code is never reached, even though I see both of the requests completing successfully in the network tab. Could someone please give me a solution? (Both of the fetch methods from above fire an Http GET request.)
Edit:
this._dataService1.fetch().subscribe(data => {
    console.log(data);
});
this._dataService2.fetch().subscribe(data => {
    console.log(data);
});

The above code works perfectly fine. As I mentioned it does work for individual request but not for forkJoin.

A: forkJoin only emits when the Observable complete. However, your Observable interceptor never completes. Add take(1) operator to your interceptor:
return this.auth.idToken.pipe(
        take(1),
        mergeMap((token: any) => {
            if (token) {
                request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
            }
            return next.handle(request);
        })
    );

A: The observables need to complete for the forkJoin to emit. If the observables are streams, you could use RxJS combineLatest and pipe in a take(1). Try the following
combineLatest(
  this._dataService1.fetch(),
  this._dataService2.fetch(),
).pipe(
  take(1)
).subscribe(
  ([dataService1Data, dataService1Data]) => {
    alert("Completed");  // <-------- This line of code is never reached
  }
);


text:
Q: What is the recomputation of residuals in the deepest descent method? From Jonathan Richard Shewchuk:

By using equation (13), we have lost track of $x_(i)$ in the process of
iteration. How is it possible to recompute the correct residual using
equation (10) ever again?

A: Of course, the algorithm computes both $x_i$ and $r_i$ in each step. The calculation (13) is only done to save one additional matrix vector multiplication: $Ar_i$ has to be computed to get the step size $\alpha_i$.


text:
Q: How to add headers above the columns of a table in python I just started working with Python for a programming class.
One of the problems states:
You have encountered the Stirling approximation
ln(n!) ≈ n ln(n) − n
in Statistical Thermodynamics and may wonder how good (or bad) this approximation is for
small numbers. This is easily verified by making use of the Python math library, which
provides access to the natural logarithm as well as the factorial function.
Write a small Python script to print n, ln(n!), n ln(n) – n, and the relative error:
error = (ln(n!) − (n ln(n) − n)) / ln(n!)
in a table for values of n from 2 up to 1000.
I am able to process the data itself (below presented for 2 to 9 for simplicity):
>>> for x in range(2,10):
...     a = math.log(math.factorial(x))
...     b = x*math.log(x) - x
...     c = (a-b)/a
...     print(x, '\t', a, '\t', b, '\t', c)

which results in:
2        0.6931471805599453      -0.6137056388801094     1.8853900817779268
3        1.791759469228055       0.2958368660043291      0.8348903013573665
4        3.1780538303479458      1.5451774444795623      0.5137975858922471
5        4.787491742782046       3.0471895621705016      0.3635102208239511
6        6.579251212010101       4.750556815368331       0.2779487114435725
7        8.525161361065415       6.621371043387192       0.2233142854483519
8        10.60460290274525       8.635532333438686       0.18568074517875863
9        12.801827480081469      10.775021196025975      0.15832163706385113

I would like to put headers above the column but I don't know how. I've tried putting another print command above the for x in range command but then it just prints the headers on their own first. There are plenty of tutorials explaining about headers but those do not concern tables containing formulas and generated data but instead fixed values that are manually put in the cells.
Hopefully someone can help me.

A: I suggest you to check libraries such as numpy and pandas to get the real potential in numerical computation with python. For example:
import numpy as np
import pandas as pd
import math

a = []
b = []
c = []
x = [i for i in range(2,10)]

for el in x:
    ac = math.log(math.factorial(el))
    a.append(ac)
    bc = el*math.log(el) - el
    b.append(bc)
    c.append((ac-bc)/ac)

array = np.vstack((x,a,b,c))

df = pd.DataFrame(array.T, columns=["x", "a", "b", "c"])

print(df.head())
df.to_excel("table.xlsx", index=False)


text:
Q: Изменяемый размер текста Появилась такая проблема, у меня есть TextView в котором текст имеет размер 24sp, на моём основном телефоне всё отлично помещается, а на втором телефоне из-за маленького экрана надпись не влезает. Так вот, можно ли как-то сделать так чтобы если надпись не влезала в бокс то автоматически менял размер текста с 24sp на 20sp.

A: Для таких целей можно использовать адаптивный размер текста в виджете. В xml добавляете такие поля:
android:autoSizeTextType="uniform"
android:autoSizeMinTextSize="12sp"
android:autoSizeMaxTextSize="100sp"
android:autoSizeStepGranularity="2sp"

устанавливаете максимальный и минимальный размер, а так же шаг (autoSizeStepGranularity) и текст будет подстраиваться под размер виджета и экрана соответственно. Вот документация

A: Вы можете использовать dimens, для этого даже есть готовые библиотеки: https://github.com/intuit/ssp. В проекте, все sp заменяются на кастомный тег, например, ssp. Приложение будет использовать подходящий размер из готовых dimen файлов, и в зависимости от расширения экрана.

A: Если вы думаете, что текст размером 24sp на вашем основном телефоне "хорошо помещается", то скорее всего вы ошибаетесь. Просто зайдите в глобальные настройки и увеличьте масштаб текста на максимально большой, с большой долей вероятности весь макет превратится в "нечто".
На англоязычном форуме уже давно обсуждается вопрос игнорировать или нет глобальную настройку пользователя по масштабу текста: окончательного ответа нет - это ваш выбор.
В SDK 26 появилась опция подстройки размера текста, но она бесполезна если пользователь хочет видеть на своем экране КРУПНЫЙ ТЕКСТ для удобства чтения.
В своих проектах, чтобы поддержать глобальную опцию масштабирования текста, я помещал TextView в ScrollView по месту как горизонтальную так и вертикальную.


text:
Q: Java code containing ! In for loop How does ! big in the for loop affects the program.Is there any checking done between i and big?
public int numberOfMoves(int size) {

    int power=2;
    int[] moves = new int[105];
    int pocet = 0;
    boolean big=false;
    for (int i=1;i<105&&!big;i++) {
        int num=1;
        for (int j=0;j<power;j++) num*=i;
        if (num>size) big=true; else {
            moves[pocet]=num;
            pocet++;
        }
    }
}

A: ! is a negation operator, this means that !true == false and !false == true.   In this case, the outer loop condition is "Loop while i<105 and big is false"

A: the ! operator is checking to see whether big is false. So as long big is false it will run.


text:
Q: Adjust jQuery word counter to count URLs as 3 words I am using a counter plugin for jquery (http://wplayground.comuv.com/counter/) and have it implemented successfully in our page.  But I need to make an adjustment to it and I'm not sure where it should go.
Basically, the script counts characters (or words, in our case) and stops input when the user has reached the goal.  This part is working fine.  Now, though, I need to make an adjustment so that if a user enters a URL like example.com, that word is counted as 3 words instead of 1.  On a previous incarnation of our website, the developer wrote custom javascript to accomplish the task, and to account for the URL thing, he made the following change:
 if(getWord.indexOf(".com")>=1 || getWord.indexOf(".net")>=1 || getWord.indexOf(".org")>=1 || getWord.indexOf(".biz")>=1 || getWord.indexOf(".gov")>=1 || getWord.indexOf(".edu")>=1 || getWord.indexOf(".mobi")>=1 || getWord.indexOf(".info")>=1 || getWord.indexOf(".ca")>=1 || getWord.indexOf(".us")>=1 || getWord.indexOf(".mil")>=1){///Email
    pk1 = pk1+3;

So, following is the new jquery counter.  How would I adjust it to do the same thing?
/*
   jQuery (character and word) counter
   Copyright (C) 2009  Wilkins Fernandez

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
(function($) {
    $.fn.extend({
        counter: function(options) {
            // Set the default values, use comma to separate the settings
            var defaults = {
                type: 'char',   // {char || word}
                count: 'down',  // count {up || down} from or to the goal number
                goal: 140       // count {to || from} this number
            };
            var options = $.extend({}, defaults, options);
            var flag = false;   // Set to true when goal is reached

            // Loop through each instance of the object that being is passed (the users selector).
            // Allows for multiple instances of the jQuery methods available to THIS (instance of the) object
            // (you can use this plug-in more than once on a page).
            return this.each(function() {
                var msg;
                var $obj = $(this);

                // Sets the appropriate message based on the options
                function get_msg_equation(objLength) {
                    // Make sure that the right values are set
                    if (typeof options.type !== 'string') {
                    } else {
                        switch (options.type) {
                            case 'char':
                                if (options.count === 'down') {
                                    msg = " character(s) left";
                                    return (options.goal - objLength);
                                }
                                else if (options.count === 'up') {
                                    msg = " characters (" + options.goal + " max)";
                                    return objLength;
                                }
                                break;
                            case 'word':
                                if (options.count === 'down') {
                                    msg = " word(s) left";
                                    return (options.goal - objLength);
                                }
                                else if (options.count === 'up') {
                                    msg = " words (" + options.goal + " max)";
                                    return objLength;
                                }
                                break;
                            default:
                        } //END switch
                    } // END if
                } // END function

                // * Initialize *: the bind event needs an object to bind to
                $('
' + get_msg_equation($($obj).val().length ) + '' + msg + '
').insertAfter($obj);

                // Cache the counter selector
                var $currentCount = $("#" + this.id + "_counter" + " span");

                // Bind events to a function that returns the length
                // of the characters || words in the given text field.
                $obj.bind('keyup click blur focus change paste', function(new_length) {
                    // Update characters depending on the option selected
                    switch (options.type) {
                        case 'char':
                            new_length = $($obj).val().length;
                            break;
                        case 'word':
                            if ($obj.val() === '') {
                                new_length = 0;
                            }
                            else {
                                new_length = $.trim($obj.val())
                                    .replace(/\s+/g, " ")
                                    .split(' ').length;
                            }
                            break;
                        default:
                    } // END switch

                    // Set flag TRUE when counter reaches goal
                    switch (options.count) {
                        case 'up':
                            if (get_msg_equation(new_length) >= options.goal && options.type === 'char') {
                                $(this).val($(this).val().substring(0, options.goal));
                                flag = true;
                                break;
                            }
                            if (get_msg_equation(new_length) === options.goal && options.type === 'word') {
                                flag = true;
                                break;
                            } else if (get_msg_equation(new_length) > options.goal && options.type === 'word') {
                                $(this).val("");
                                $currentCount.text("0");
                                flag = true;
                                break;
                            }
                            break;
                        case 'down':
                            if (get_msg_equation(new_length) <= 0 && options.type === 'char') {
                                $(this).val($(this).val().substring(0, options.goal));
                                flag = true;
                                break;
                            }
                            if (get_msg_equation(new_length) === 0 && options.type === 'word') {
                                flag = true;
                            } else if (get_msg_equation(new_length) < 0 && options.type === 'word') {
                                $(this).val("");
                                flag = true;
                                break;
                            }
                            break;
                        default:
                    } // END switch

                    // Listen on keydown to catch the last character or word typed
                    // and prevent the user from typing
                    $obj.keydown(function(event) {
                        if (flag) {
                            this.focus();
                            // Listen for delete & backspace
                            if ((event.keyCode !== 46 && event.keyCode !== 8)) {
                                if ($(this).val().length > options.goal && options.type === 'char') {
                                    $(this).val($(this).val().substring(0, options.goal));
                                    return false;   // Stop the default action (typing)
                                    // Listen for blank (spacebar) & return
                                } else if (event.keyCode !== 32 && event.keyCode !== 8 && options.type === 'word') {   //Allow to continue typing last word
                                    return true;
                                } else {
                                    return false;   // Stop the default action (typing)
                                }
                            } else {
                                flag = false;
                                return true;
                            }
                        }
                    }); // END keydown
                    $currentCount.text(get_msg_equation(new_length));
                }); // END Bind
            }); //END return
        } // END counter function
    }); // END extend
}) // END function
(jQuery); // Return jQuery object

A: In the middle of the counter plugin file, there is a line that looks like this:
else{
  new_length = $.trim($obj.val())
    .replace(/\s+/g, " ")
    .split(' ').length;
}

It seems like this is where it counts the words.  It's grabbing the text in the box, splitting on spaces, then counting the elements.
You could add some sort of check (regex) for URLs here, and then increment new_length accordingly.
Something like this (untested):
else{
  var str = $.trim($obj.val())
    .replace(/\s+/g, " ");
  new_length = str.split(' ').length;
  var URLs = str
    .match(/([^\s])+\.(com|net|org|biz|gov|edu|mobi|info|ca|us|mil)/g);
  if(URLs != null && URLs.length > 0){
    new_length += (URLs.length*2);
  }
}


text:
Q: TextView not hiding I have a TextView i want to hide, quite easy I thought. But this is giving me a headache. The www did as well not have an answer.
I "fixed" the problem by calling timer.setText("");, to the user it looks like it dissapred. I have many Views, so I have this int visibility = warmup ? View.GONE : View.VISIBLE; all the other controls hide perfect, except this one. I hard coded it as well to View.GONE, with the same result.
TextView timer = findViewById(R.id.timerTextView);
timer.setVisibility(visibility);
timer.setText("");

If I call .setVisibility() on a view, I excpect the normal behaviour.

A: timer.setVisibility(View.INVISIBLE) // This will hold the position and space but just hide the view.
timer.setVisibility(View.GONE) // This will not hold the position and space. It will disapear.

I guess you need to check what the warmup is. It should work if it works fine.
Otherwise, it'd be worth to apply databinding. And use that expression in the layout.
Like
visibility=""@{vm.hide ? View.GONE : View.VISIBLE}"

When hide which is the ViewModel's variable has the value of true. Then, all the views that is data bidden will work perfectly.

A: Actually thats not the case,
textView.setVisibility(View.GONE);

it always works perfectly. You need to check your other code, may be its made visible somewhere else. or you are trying to hide it through background thread. you can give a temporary background color to the TextView and then test and verify your code, its just an illusion to you, problem is somewhere else.


text:
Q: Error to updating EditText On some devices, with this code, the EditText to_quantity is not updated in real time during the insertion of the value to be converted in the EditText from_quantity. What can be the problem?
EDIT TEXT from_quantity:
from_quantity.setOnKeyListener(new OnKeyListener(){

    public boolean onKey(View v, int keyCode, KeyEvent event){

        try{
        if(!(Double.isNaN(Double.valueOf(from_quantity.getText().toString())))){
                                                  convert(from_quantity.getText().toString(), "to");
        }
        }catch(NumberFormatException e){
            Log.d("error", e.toString());
        }
            return false;
        }
        });

            from_quantity.setOnTouchListener(new OnTouchListener(){

                            public boolean onTouch(View v, MotionEvent event) {
                                    //Clear Quantities
                                    from_quantity.setText("");
                                    to_quantity.setText("");
                                    return false;
                            }

            });

EDIT TEXT to_quantity:
to_quantity.setOnKeyListener(new OnKeyListener() {
     public boolean onKey(View v, int keyCode, KeyEvent event) {
         try{
            if(!(Double.isNaN(Double.valueOf(to_quantity.getText().toString())))) {
                  convert(to_quantity.getText().toString(), "from");
            }
          } catch(NumberFormatException e) {
               Log.d("error", e.toString());
          }
          return false;
     }
});

to_quantity.setOnTouchListener(new OnTouchListener(){
      public boolean onTouch(View v, MotionEvent event) {
          //Clear Quantities
          from_quantity.setText("");
          to_quantity.setText("");
          return false;
      }

});

A: If you use the soft keyboard of your device, the OnKeyListener will not be called. You should use a TextWatcher.
onKeyListener not working with soft keyboard (Android)

A: Some software keyboards do not launch onKey() events. Create a TextWatcher and set it as a listener to the EditText instead:
to_quantity.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String text = s.toString() ;
        try{
            if(!(Double.isNaN(Double.valueOf(text)))) {
                convert(text, "from");
            }
        } catch(NumberFormatException e) {
            Log.d("error", e.toString());
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }
});

A: if you wanna use soft keyboard you need to setFocusable to target view:
setFocusableInTouchMode(true); //Enable soft keyboard on touch for target view

setFocusable(true); //Enable hard keyboard to target view


text:
Q: struts2 I have upgraded struts from 2.2.3 to 2.5.10.1. I have made appropriate changes in all jsp's. After upgrading, my JSPs that has <script type="text/javascript" src="<s:url value='/js/main.js' />"></script> throws following error
java.lang.NullPointerException
    at org.apache.struts2.components.ServletUrlRenderer.renderUrl(ServletUrlRenderer.java:80)
    at org.apache.struts2.components.URL.end(URL.java:145)
    at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
    at org.apache.jsp.WEB_002dINF.decorators.main1_jsp._jspx_meth_s_005furl_005f0(main1_jsp.java:285)
    at org.apache.jsp.WEB_002dINF.decorators.main1_jsp._jspService(main1_jsp.java:111)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
    at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:605)
    at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:544)
    at com.opensymphony.sitemesh.compatability.OldDecorator2NewDecorator.render(OldDecorator2NewDecorator.java:46)
    at com.opensymphony.sitemesh.webapp.decorator.BaseWebAppDecorator.render(BaseWebAppDecorator.java:33)
    at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:84)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:264)
    at org.acegisecurity.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:107)
    at org.acegisecurity.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:72)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.ui.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:110)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.wrapper.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:81)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:217)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.ui.logout.LogoutFilter.doFilter(LogoutFilter.java:106)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:229)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.util.FilterChainProxy.doFilter(FilterChainProxy.java:148)
    at au.org.standards.portal.system.util.MonitorFilter.doFilter(MonitorFilter.java:75)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)

Sep 05, 2018 9:19:00 PM org.apache.catalina.core.ApplicationContext log
SEVERE: Unhandled exception occurred whilst decorating page
java.lang.RuntimeException: org.apache.jasper.JasperException: java.lang.NullPointerException
    at com.opensymphony.sitemesh.webapp.decorator.BaseWebAppDecorator.render(BaseWebAppDecorator.java:39)
    at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:84)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:264)
    at org.acegisecurity.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:107)
    at org.acegisecurity.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:72)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.ui.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:110)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.wrapper.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:81)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:217)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.ui.logout.LogoutFilter.doFilter(LogoutFilter.java:106)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:229)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.util.FilterChainProxy.doFilter(FilterChainProxy.java:148)
    at au.org.standards.portal.system.util.MonitorFilter.doFilter(MonitorFilter.java:75)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)

Sep 05, 2018 9:19:00 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [default] in context with path [/sapc] threw exception
java.lang.RuntimeException: org.apache.jasper.JasperException: java.lang.NullPointerException
    at com.opensymphony.sitemesh.webapp.decorator.BaseWebAppDecorator.render(BaseWebAppDecorator.java:39)
    at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:84)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:264)
    at org.acegisecurity.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:107)
    at org.acegisecurity.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:72)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.ui.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:110)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.wrapper.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:81)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:217)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.ui.logout.LogoutFilter.doFilter(LogoutFilter.java:106)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:229)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:274)
    at org.acegisecurity.util.FilterChainProxy.doFilter(FilterChainProxy.java:148)
    at au.org.standards.portal.system.util.MonitorFilter.doFilter(MonitorFilter.java:75)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)

Not able to identify what the issue is. I have done a similar activity for my another application and it didn't have any issues. Not sure what the issue here is. If I replace that with normal HTML script tag, it works fine. It is not feasible for me to go on changing all JSPs from struts to HTML tag. Even if I change, there may be some other issues popping up soon related to struts. So it is better to find the root cause and fix it than changing it.
PN: I have sitemesh in the application. I don't think this should be an issue because the other application I upgraded had the same stack.
Can some help me out?
EDIT - 08-Sep-2018:
I was able to solve the <s:urlissue by re-arranging the struts and sitemesh filters in web.xml. I re-arranged the filter mappings in below order

*

*struts-prepare

*sitemesh

*struts-execute

Now I am facing css issues in <s:a tag. If I change it to HTML <a> tag, css works fine, else it fails.
Will raise it a as separate post.

A: The issue was with the order of filter mappings in my web.xml. I was able to resolve it by re-arranging filter mappings in below order

*

*struts-prepare

*sitemesh

*struts-execute


text:
Q: Heroku, Github, & Rails: How to copy an entire webapp so a 3rd party can make changes and then A/B test original vs new app We have a live rails web app on Heroku. There's a group of students who want to work on making an improved version for us.
Rather than give them access to our live rails app & DB, I'd prefer to have them work on their own separate version, push changes to their app, and then just A/B test our users/traffic against their new app.
Basically I want to A/B test two completely separate apps with one shared DB. A user who views one version of the app should continue to see that version of the app moving forward.
What are my next steps?

A: *

*Create a new Heroku application

*Add them as a collaborator

*set the new apps DATABASE_URL to that in your original application

The problem will come with DNS (unless you're happy to give it a new URL like new.mydomain.com but also remembering which site to serve. You'd have to introduce a router above the two apps to remember and that's just going to get complicated.

A: *

*will need to share session data, if sessions storage is filesystem based, you will be change it to redis or memcache

*consider using https://www.cloudflare.com to simplify DNS management


text:
Q: Static / global variables in shared library in C language
Possible Duplicate:
Is global variable in a shared library / dll, shared across process

Hi stackoverflow,
I have just a little question about using .so in C programming.
I want to use static and global variables in a shared library.
If this library is loaded and used by several processes, will these processes share the global variables (i.e. will a process be able to modify variables used by an other process)?
Anyone got an idea about the behavior of these variables ?

A:
will these processes share the global variables

No.

A: No, global variables are global inside a process. If you want to share data among processes you have to use specific IPC (inter-process communication) mechanisms.


text:
Q: Scala implementation of startsWith on Streams It should check if one Stream (that) is a prefix of another (this).
For instance, Stream(1,2,3) startsWith Stream(1,2) would be true.
This is my implementation, but it always returns false!
Can anyone please tell me why and maybe also post the correction?
def startsWith[B >: A](that: Stream[B]): Boolean = (this, that) match {
  case (_,Empty) => true
  case (Cons(h,t),Cons(h2,t2)) if h == h2 => t().startsWith(t2())
  case _ => false
}

A:   stream1.zip(stream2).dropWhile { case (a,b) => a == b }.isEmpty

A: I am not sure how your stream is implemented but if everything is lazy I think the problem is in your second case:
   case (Cons(h,t),Cons(h2,t2)) if h == h2 => t().startsWith(t2())

should be
   h() == h2()

otherwise you are comparing two unevaluated functions

A: def startsWith[B >: A](that: Stream[B]): Boolean = (this, that) match {
   case (_,Empty) => true
   case (Cons(h,t),Cons(h2,t2)) if h() == h2 => t().startsWith(t2())
   case _ => false


text:
Q: PHP APIs for Hotmail, Gmail and Yahoo? I am a PHP developer who is kind of in a pickle. I'm trying to locate and/or build an API capable of speaking to Hotmail, Yahoo and GMAIL in order to retrieve contact lists (with the user's consent, of course). The one I'm having the most trouble finding is a Hotmail API.
Where would I start to look as far as finding either a working, stable API or the steps I could take to developing one for hotmail? Is there one that covers all of these bases that I could implement? Any help would be greatly appreciated!
Thanks!
EDIT:
I did manage to get a few services up, however, I've been using Open Inviter for at least one client project, and it seems to perform well.

A: Plaxo has an API widget to import contacts from Gmail, Yahoo, AOL and Hotmail. You can view a demo of it in action here. It previously had a small issue with IE7 (last checked half a year ago), but if its resolved it might suite your needs.

A: Some pointers:

*

*Gmail: Google Contacts Data API

*Yahoo:

*

*Address Book API (deprecated)

*Contacts API

*Hotmail: Windows Live Contacts API
Most of the scripts, etc. I found didn't really work. There's a commercial one which uses scraping to retrieve the contacts but I think those attempts are rather flawed. The above links should give you an example of how to access the address books on each service.

A: Rapleaf might have something for you:
http://www.phpclasses.org/browse/package/4436.html
It appears that this service plays cat and mouse with some providers, as not all e-mail providers offer a stable API for communicating with their services.  (It would undermine their business model.)  So, if you use these and the e-mail provider breaks the chain somehow, you're broken until Rapleaf catches up.


text:
Q: TFDQuery and TFUpdate to Insert and Update a SQLite3 table I am using Windows 10, Delphi 10.1, SQLite3, Woll2Woll DBGid and DataSource.  The SQL query Is the following:
SELECT ID, Cast(Name AS CHAR(30)) FROM Cuisine ORDER BY Name
The SQLite3 Data Definition is ID: Integer and Name: Text.  Deletes works fine but insert and edits work locally but they are not stored in the DB.  I expect that the problem is caused by CAST(Name AS CHAR(30)) but I cannot figure out if this is the problem and in any event get the actual updates to the DB.  I have used TFDQuery alone and with a TFDUpdateSQL component  ID is an AutoIncrement Key

A: I used a workaround by creating a calculated string field: NameStr  I populated this field via a get text on the calculated field and then in a before post-event assigned the calculated field value to the SQL field: Name.
procedure TdmRecipe.qryCuisineBeforePost(DataSet: TDataSet);
begin
qryCuisineName.AsString := qryCuisineNameStr.AsString;
end;
PROCEDURE TdmRecipe.qryCuisineNameStrGetText(Sender: TField; VAR Text: STRING; DisplayText: BOOLEAN);
BEGIN
Text := qryCuisineName.AsString;
END;


text:
Q: Is there a method to look inside at the internal code of Built-In functions? How can I look at the code of built-in functions?
Is there something like this:
LookInsideFunction[SubsetQ]

RETURNS
SubsetQ[list1_,list2_]:= stuff...

is it possible to know how these functions are implemented in the Global Rule Base?

A: There isn't always a good way to do it.  There is Simon's Spelunking function, which Szabolcs has put on github, but in this case it doesn't help much:
Spelunk[SubsetQ]

There is also Trace, which is a bit more helpful here,
Trace[SubsetQ[{1, 2, 3}, {3, 1}]]
(* {HoldForm[SubsetQ[{1, 2, 3}, {3, 1}]],
  {HoldForm[Internal`ConditionalValueBody[SubsetQ[{1, 2, 3}, {3, 1}],
     {GeneralUtilities`Predicates`PackagePrivate`CompoundQ[{1, 2, 3}],
      GeneralUtilities`Predicates`PackagePrivate`CompoundQ[{3, 1}],
      Head[{1, 2, 3}] === Head[{3, 1}]},
     {{"normal", 1, Internal`ConditionalValueLHS},
      {"normal", 2, Internal`ConditionalValueLHS}, {"heads", Head[{1, 2, 3}],
       Head[{3, 1}], 1, 2}},
     Length[Complement[GeneralUtilities`Predicates`PackagePrivate`values[
         {3, 1}], GeneralUtilities`Predicates`PackagePrivate`values[
         {1, 2, 3}]]] === 0]],
   {{{{HoldForm[GeneralUtilities`Predicates`PackagePrivate`values[{3, 1}]],
       HoldForm[If[AssociationQ[{3, 1}], Values[{3, 1}], {3, 1}]],
       {HoldForm[AssociationQ[{3, 1}]], HoldForm[False]},
       HoldForm[If[False, Values[{3, 1}], {3, 1}]], HoldForm[{3, 1}]},
      {HoldForm[GeneralUtilities`Predicates`PackagePrivate`values[{1, 2, 3}]],
       HoldForm[If[AssociationQ[{1, 2, 3}], Values[{1, 2, 3}], {1, 2, 3}]],
       {HoldForm[AssociationQ[{1, 2, 3}]], HoldForm[False]},
       HoldForm[If[False, Values[{1, 2, 3}], {1, 2, 3}]], HoldForm[{1, 2, 3}]},
      HoldForm[Complement[{3, 1}, {1, 2, 3}]], HoldForm[{}]},
     HoldForm[Length[{}]], HoldForm[0]}, HoldForm[0 === 0], HoldForm[True]},
   HoldForm[True]}, HoldForm[True]} *)

You might be best served by TracePrint in this case,
TracePrint[SubsetQ[{1, 2, 3}, {3, 1}]]
(*
 SubsetQ[{1,2,3},{3,1}]
  SubsetQ
  {1,2,3}
  {3,1}
  Internal`ConditionalValueBody[SubsetQ[{1,2,3},{3,1}],{GeneralUtilities`Predicates`PackagePrivate`CompoundQ[{1,2,3}],GeneralUtilities`Predicates`PackagePrivate`CompoundQ[{3,1}],Head[{1,2,3}]===Head[{3,1}]},{{normal,1,Internal`ConditionalValueLHS},{normal,2,Internal`ConditionalValueLHS},{heads,Head[{1,2,3}],Head[{3,1}],1,2}},Length[Complement[GeneralUtilities`Predicates`PackagePrivate`values[{3,1}],GeneralUtilities`Predicates`PackagePrivate`values[{1,2,3}]]]===0]
   Internal`ConditionalValueBody
   Length[Complement[GeneralUtilities`Predicates`PackagePrivate`values[{3,1}],GeneralUtilities`Predicates`PackagePrivate`values[{1,2,3}]]]===0
    SameQ
    Length[Complement[GeneralUtilities`Predicates`PackagePrivate`values[{3,1}],GeneralUtilities`Predicates`PackagePrivate`values[{1,2,3}]]]
     Length
     Complement[GeneralUtilities`Predicates`PackagePrivate`values[{3,1}],GeneralUtilities`Predicates`PackagePrivate`values[{1,2,3}]]
      Complement
      GeneralUtilities`Predicates`PackagePrivate`values[{3,1}]
       GeneralUtilities`Predicates`PackagePrivate`values
       {3,1}
      If[AssociationQ[{3,1}],Values[{3,1}],{3,1}]
       If
       AssociationQ[{3,1}]
        AssociationQ
        {3,1}
       False
      If[False,Values[{3,1}],{3,1}]
      {3,1}
      GeneralUtilities`Predicates`PackagePrivate`values[{1,2,3}]
       GeneralUtilities`Predicates`PackagePrivate`values
       {1,2,3}
      If[AssociationQ[{1,2,3}],Values[{1,2,3}],{1,2,3}]
       If
       AssociationQ[{1,2,3}]
        AssociationQ
        {1,2,3}
       False
      If[False,Values[{1,2,3}],{1,2,3}]
      {1,2,3}
     Complement[{3,1},{1,2,3}]
     {}
    Length[{}]
    0
    0
   0===0
   True
  True
 True
*)


text:
Q: How to install WebSphere MQ resource adapter (wmq.jmsra.rar) in JBoss 6.2 EAP? Design: I have a queue manager (EXAMPLE.QM) with Server-connection channel (EXAMPLE.CHANNEL), request queue (EXAMPLE.TEST.QUEUE), and reply queue (EXAMPLE.TEST.REPLY).  My application will be using a message driven bean (MDB) to listen on EXAMPLE.TEST.QUEUE.  When message arrives an instance of MDB is created and business logic is done which includes quering databases and then the reply is put on the EXAMPLE.TEST.REPLY queue.  This is one transaction.  In the event of crashes or any failure the exception will be caught and everything will be rolled back.  I wanted to do the connection pooling for both MQ and Databases on the server side.
Setup: WebSphere MQ 7.0.1, JBoss 6.2 EAP, Java 1.7.0_21, IBM DB2 9.7
I obtained the wmq.jmsra.rar from the MQ_INSTALLATION_PATH\java\lib\jca
 and I also got the com.ibm.mqetclient.jar
As per Redhat installation guide in order to support XATransactions I repackaged the wmq.jmsra.rar to include com.ibm.mqetclient.jar using command jar -uf wmq.jmsra.rar com.ibm.mqetclient.jar
You can skip the next paragraph and look at the xml snippet provided below for same information.
After doing so instead manually dropping the wmq.jmsra.rar into JBoss deployment directory I used the management console.  I then went ahead and added in profile view under Resource adapters. I set Archive to wmq.jmsra.rar and TX to XATransaction.  I then set the properties to the following: logWriterEnabled - true, maxConnections - 10, reconnectionRetryCount - 5, traceLevel - 6, traceEnabled - true, reconnectionRetryInterval - 300000, and connectionConcurrency - 5.  After doing so I added a connection definition.  I named it WMQ_ConnectionFactory, JNDI - java:jboss/WMQ_ConnectionFactory, and Connection Class - com.ibm.mq.connector.outbound.ManagedConnectionFactoryImpl.  I set the properties as follow: port - 1414, hostName - localhost, channel - EXAMPLE.CHANNEL, transportType - BINDINGS_THEN_CLIENT, failIfQuiesce - true, and queueManager - EXAMPLE.QM. I then went on to add 2 Admin Objects.  1st I named EXAMPLE_REQ_Queue, JNDI - java:jboss/EXAMPLE_REQ_Queue, and Class name - com.ibm.mq.connector.outbound.MQQueueProxy.  I have it the following properties: useJNDI - true, readAheadClosePolicy - ALL, startTimeout - 10000, destination - EXAMPLE.TEST.REQUEST, and destinationType - javax.jms.Queue.  The 2nd admin object I named EXAMPLE_REP_Queue, JNDI - java:jboss/EXAMPLE_REP-Queue, and class name - com.ibm.mq.connector.outbound.MQQueueProxy.  I gave it the following properties: failifQuiesce - true, baseQueueManagerName - EXAMPLE.QM, persistence - HIGH, encoding - NNN, baseQueueName - EXAMPLE.TEST.REPLY, targetClient - MQ, and expiry 300000.
Here is a snippet from the standalone.xml file
<subsystem xmlns="urn:jboss:domain:resource-adapters:1.1">
        <resource-adapters>
            <resource-adapter id="wmq.jmsra.rar">
                <archive>
                    wmq.jmsra.rar
                </archive>
                <transaction-support>XATransaction</transaction-support>
                <config-property name="logWriterEnabled">
                    true
                </config-property>
                <config-property name="maxConnections">
                    10
                </config-property>
                <config-property name="traceEnabled">
                    true
                </config-property>
                <config-property name="traceLevel">
                    6
                </config-property>
                <config-property name="reconnectionRetryCount">
                    5
                </config-property>
                <config-property name="reconnectionRetryInterval">
                    300000
                </config-property>
                <config-property name="connectionConcurrency">
                    5
                </config-property>
                <connection-definitions>
                    <connection-definition class-name="com.ibm.mq.connector.outbound.ManagedConnectionFactoryImpl" jndi-name="java:jboss/WMQ_ConnectionFacotry" enabled="true" pool-name="WMQ_ConnectionFactory">
                        <config-property name="port">
                            1414
                        </config-property>
                        <config-property name="hostName">
                            localhost
                        </config-property>
                        <config-property name="channel">
                            EXAMPLE.CHANNEL
                        </config-property>
                        <config-property name="failIfQuiesce">
                            true
                        </config-property>
                        <config-property name="transportType">
                            BINDINGS_THEN_CLIENT
                        </config-property>
                        <config-property name="queueManager">
                            EXAMPLE.QM
                        </config-property>
                        <security>
                            <application/>
                        </security>
                        <validation>
                            <background-validation>false</background-validation>
                        </validation>
                    </connection-definition>
                </connection-definitions>
                <admin-objects>
                    <admin-object class-name="com.ibm.mq.connector.outbound.MQQueueProxy" jndi-name="java:jboss/EXAMPLE_REQ_Queue" enabled="true" use-java-context="false" pool-name="EXAMPLE_REQ_Queue">
                        <config-property name="useJNDI">
                            true
                        </config-property>
                        <config-property name="startTimeout">
                            10000
                        </config-property>
                        <config-property name="destination">
                            EXAMPLE.TEST.REQUEST
                        </config-property>
                        <config-property name="readAheadClosePolicy">
                            ALL
                        </config-property>
                    </admin-object>
                    <admin-object class-name="com.ibm.mq.connector.outbound.MQQueueProxy" jndi-name="java:jboss/EXAMPLE_REP_Queue" enabled="true" use-java-context="false" pool-name="EXAMPLE_REP_Queue">
                        <config-property name="failIfQuiesce">
                            true
                        </config-property>
                        <config-property name="baseQueueManagerName">
                            EXAMPLE.QM
                        </config-property>
                        <config-property name="persistence">
                            HIGH
                        </config-property>
                        <config-property name="encoding">
                            NNN
                        </config-property>
                        <config-property name="baseQueueName">
                            EXAMPLE.TEST.REPLY
                        </config-property>
                        <config-property name="targetClient">
                            MQ
                        </config-property>
                        <config-property name="expiry">
                            300000
                        </config-property>
                    </admin-object>
                </admin-objects>
            </resource-adapter>
        </resource-adapters>
    </subsystem>

The problem:
I get the following exception:

15:54:53,325 ERROR [org.jboss.msc.service.fail] (ResourceAdapterDeploymentService Thread Pool -- 1) MSC000001: Failed to start service jboss.ra.deployment."wmq.jmsra.rar": org.jboss.msc.service.StartException in service jboss.ra.deployment."wmq.jmsra.rar": JBAS010446: Failed to start RA deployment [wmq.jmsra]
      at org.jboss.as.connector.services.resourceadapters.deployment.AbstractResourceAdapterDeploymentService$1.run(AbstractResourceAdapterDeploymentService.java:279) [jboss-as-connector-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_21]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_21]
      at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_21]
      at org.jboss.threads.JBossThread.run(JBossThread.java:122) [jboss-threads-2.1.1.Final-redhat-1.jar:2.1.1.Final-redhat-1]
  Caused by: org.jboss.jca.deployers.common.DeployException: IJ020060: Unable to inject: com.ibm.mq.connector.outbound.MQQueueProxy property: destination value: EXAMPLE.TEST.REQUEST
      at org.jboss.jca.deployers.common.AbstractResourceAdapterDeployer.initAdminObject(AbstractResourceAdapterDeployer.java:907) [ironjacamar-deployers-common-1.0.23.Final-redhat-1.jar:1.0.23.Final-redhat-1]
      at org.jboss.jca.deployers.common.AbstractResourceAdapterDeployer.createObjectsAndInjectValue(AbstractResourceAdapterDeployer.java:2382) [ironjacamar-deployers-common-1.0.23.Final-redhat-1.jar:1.0.23.Final-redhat-1]
      at org.jboss.as.connector.services.resourceadapters.deployment.ResourceAdapterXmlDeploymentService$AS7RaXmlDeployer.doDeploy(ResourceAdapterXmlDeploymentService.java:185) [jboss-as-connector-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
      at org.jboss.as.connector.services.resourceadapters.deployment.ResourceAdapterXmlDeploymentService.start(ResourceAdapterXmlDeploymentService.java:106) [jboss-as-connector-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
      at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.4.GA-redhat-1.jar:1.0.4.GA-redhat-1]
      at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.4.GA-redhat-1.jar:1.0.4.GA-redhat-1]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_21]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_21]
      at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_21]
  15:54:53,343 INFO  [org.jboss.as.server] (Controller Boot Thread) JBAS018559: Deployed "wmq.jmsra.rar" (runtime-name : "wmq.jmsra.rar")
  15:54:53,344 INFO  [org.jboss.as.controller] (Controller Boot Thread) JBAS014774: Service status report
  JBAS014777:   Services which failed to start:      service jboss.ra.deployment."wmq.jmsra.rar": org.jboss.msc.service.StartException in service jboss.ra.deployment."wmq.jmsra.rar": JBAS010446: Failed to start RA deployment [wmq.jmsra]

I guess the main part is Caused by: org.jboss.jca.deployers.common.DeployException: IJ020060: Unable to inject: com.ibm.mq.connector.outbound.MQQueueProxy property: destination value: EXAMPLE.TEST.REQUEST  Prior to this I had the same error and instead it said destinationType value: javax.jms.Queue.  I then went ahead and removed that property and tried again and now I got this error. I am not certain what to do next.
Tutorials I have been following:
IBM - The WebSphere MQ resource adapter, Redhat Jboss Documentation - JCA Architecture Chapter, and Oracle - Message Driven Beans Java EE6 tutorial
My rep only allows me to post 2 links so the last two tutorials are not linked. Any help will be greatly appreciated.

A: I had slightly different issues deploying the MQ RAR to JBoss, but the solution and procedure outlined here should work for you. The specific files to look at are here. The files are iron-jacamar (the jboss as JCA provider) descriptors.

*

*ra.xml: The WMQ RAR descriptor

*ironjacamar.xml: Defines the WMQ connection parameters and admin objects.

A: I eventually ended up removing all the properties that were causing the exception to pop up.  The properties I was trying to set were for inbound communication and it turns out this wasn't really the appropriate place to set them.  Instead these should be set in the deployment descriptor of the Message Drive Bean (MDB).  The file is called ejb-jar.xml.  The content are as follow:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
     version="3.0"
>
<enterprise-beans>
     <message-driven>
          <ejb-name>MyMDB</ejb-name>
          <ejb-class>com.foo.MyMDB</ejb-class>
          <messaging-type>javax.jms.MessageListener</messaging-type>
          <transaction-type>Container</transaction-type>
          <activation-config>
               <activation-config-property>
                    <activation-config-property-name>
                         destinationType
                    </activation-config-property-name>
                    <activation-config-property-value>
                         javax.jms.Queue
                    </activation-config-property-value>
               </activation-config-property>
               <activation-config-property>
                    <activation-config-property-name>
                         destination
                    </activation-config-property-name>
                    <activation-config-property-value>
                         EXAMPLE.TEST.REQUEST
                    </activation-config-property-value>
                </activation-config-property>
                <!--SET OTHER PROPERTIES-->
          </activation-config>
     </message-driven>
</enterprise-beans>
</ejb-jar>

Hope this helps.


text:
Q: Sort columns in the 'Pages' dashboard overview I would like to alphabetically order pages in the 'Pages' dashboard either by 'title' or a custom column ('hierarchy'). Basically all pages are assigned a hierarchy code (1, 1.1, 1.1.01, 1.1.02, etc.). When I click on 'hierarchy' sort button, the result is incorrect.
Can someone give me a hint or point me to a resource that discusses this issue? My code is listed below.

// (Works.) Make custom columns 'prod-hierar' and 'slug' sortable
add_filter( 'manage_edit-page_sortable_columns', 'wms_sort_cust_cols', 10, 2 );

function wms_sort_cust_cols( $col ) {
    // Make column 'hierarchy' sortable ie add sorting icon

    $col[ 'hierarchy' ] = 'prod_hierar';

    return  $col;
}

// (Does not work.) Order column 'hierarchy' alphabetically via meta_key 'prod_hier'.
add_filter( 'request', 'wms_hierarchy_col_orderby' );

function wms_hierarchy_col_orderby( $vars ) {
    PC::debug('wms_hierarchy_col_orderby() hit');
    if ( isset( $vars['orderby'] ) && 'prod_hier' == $vars['orderby'] ) {
        $vars = array_merge( $vars, array(
            'meta_key' => 'prod_hier',
            'orderby' => 'meta_value'

            //$query->set( 'meta_key', 'prod_hier' );
            //$query->set( 'orderby', 'meta_value' );
        ) );
    }
    return $vars;
}

A: I just realized that there was a typo in the code. The meta-tag should read 'prod_hierar' instead of 'prod-hier'. This fixes the issue. (Too much experimenting, I guess ..).
Function 'wms_hierarchy_col_orderby()' thus becomes:
function wms_hierarchy_col_orderby( $vars ) {
    if ( isset( $vars['orderby'] ) && 'prod_hierar' == $vars['orderby'] ) {
        $vars = array_merge( $vars, array(
            'meta_key' => 'prod_hierar',
            'orderby' => 'meta_value'
        ) );
    }
    return $vars;
}


text:
Q: Google Cloud Function Error: Exception: Bad response from application: 500 I was running a cloud function to trigger a DAG on composer. After deploy GCF and dropping a file to trigger the function, the #500 error is showing up in log, however when I call the function in "test function" it was successful - finished with status: 'ok'.
I am new to GCF, I couldn't understand what causing the error and need some help on the error log message for trouble shooting.
this is the Main.PY I use (Got it from Cloud doc, I put xxx replacing the actual value on client_ID & server_ID):
import google.auth
import google.auth.compute_engine.credentials
import google.auth.iam
from google.auth.transport.requests import Request
import google.oauth2.credentials
import google.oauth2.service_account
import requests

IAM_SCOPE = 'https://www.googleapis.com/auth/iam'
OAUTH_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token'

def trigger_dag(data, context=None):
    """Makes a POST request to the Composer DAG Trigger API
    When called via Google Cloud Functions (GCF),
    data and context are Background function parameters.
    For more info, refer to
    https://cloud.google.com/functions/docs/writing/background#functions_background_parameters-python

    To call this function from a Python script, omit the ``context`` argument
    and pass in a non-null value for the ``data`` argument.
    """

    # Fill in with your Composer info here
    # Navigate to your webserver's login page and get this from the URL
    # Or use the script found at
    # https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/composer/rest/get_client_id.py
    client_id = 'xxxxxxxxxxxx-l1sqmeccbhj607i99su1uavn0l8jcgbk.apps.googleusercontent.com'
    # This should be part of your webserver's URL:
    # {tenant-project-id}.appspot.com
    webserver_id = 'xxxxxxxxxxxxxxxxx-tp'
    # The name of the DAG you wish to trigger
    dag_name = 'DAG_Dev_cf_trigger_test'
    webserver_url = (
        'https://'
        + webserver_id
        + '.appspot.com/api/experimental/dags/'
        + dag_name
        + '/dag_runs'
    )
    # Make a POST request to IAP which then Triggers the DAG
    make_iap_request(webserver_url, client_id, method='POST', json={"conf":data})

# This code is copied from
# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/iap/make_iap_request.py
# START COPIED IAP CODE
def make_iap_request(url, client_id, method='GET', **kwargs):
    """Makes a request to an application protected by Identity-Aware Proxy.

    Args:
      url: The Identity-Aware Proxy-protected URL to fetch.
      client_id: The client ID used by Identity-Aware Proxy.
      method: The request method to use
              ('GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE')
      **kwargs: Any of the parameters defined for the request function:
                https://github.com/requests/requests/blob/master/requests/api.py
                If no timeout is provided, it is set to 90 by default.

    Returns:
      The page body, or raises an exception if the page couldn't be retrieved.
    """
    # Set the default timeout, if missing
    if 'timeout' not in kwargs:
        kwargs['timeout'] = 540

    # Figure out what environment we're running in and get some preliminary
    # information about the service account.
    bootstrap_credentials, _ = google.auth.default(
        scopes=[IAM_SCOPE])

    # For service account's using the Compute Engine metadata service,
    # service_account_email isn't available until refresh is called.
    bootstrap_credentials.refresh(Request())

    signer_email = bootstrap_credentials.service_account_email
    if isinstance(bootstrap_credentials,
                  google.auth.compute_engine.credentials.Credentials):
        # Since the Compute Engine metadata service doesn't expose the service
        # account key, we use the IAM signBlob API to sign instead.
        # In order for this to work:
        # 1. Your VM needs the https://www.googleapis.com/auth/iam scope.
        #    You can specify this specific scope when creating a VM
        #    through the API or gcloud. When using Cloud Console,
        #    you'll need to specify the "full access to all Cloud APIs"
        #    scope. A VM's scopes can only be specified at creation time.
        # 2. The VM's default service account needs the "Service Account Actor"
        #    role. This can be found under the "Project" category in Cloud
        #    Console, or roles/iam.serviceAccountActor in gcloud.
        signer = google.auth.iam.Signer(
            Request(), bootstrap_credentials, signer_email)
    else:
        # A Signer object can sign a JWT using the service account's key.
        signer = bootstrap_credentials.signer

    # Construct OAuth 2.0 service account credentials using the signer
    # and email acquired from the bootstrap credentials.
    service_account_credentials = google.oauth2.service_account.Credentials(
        signer, signer_email, token_uri=OAUTH_TOKEN_URI, additional_claims={
            'target_audience': client_id
        })
    # service_account_credentials gives us a JWT signed by the service
    # account. Next, we use that to obtain an OpenID Connect token,
    # which is a JWT signed by Google.
    google_open_id_connect_token = get_google_open_id_connect_token(
        service_account_credentials)

    # Fetch the Identity-Aware Proxy-protected URL, including an
    # Authorization header containing "Bearer " followed by a
    # Google-issued OpenID Connect token for the service account.
    resp = requests.request(
        method, url,
        headers={'Authorization': 'Bearer {}'.format(
            google_open_id_connect_token)}, **kwargs)
    if resp.status_code == 403:
        raise Exception('Service account {} does not have permission to '
                        'access the IAP-protected application.'.format(
                            signer_email))
    elif resp.status_code != 200:
        raise Exception(
            'Bad response from application: {!r} / {!r} / {!r}'.format(
                resp.status_code, resp.headers, resp.text))
    else:
        return resp.text

def get_google_open_id_connect_token(service_account_credentials):
    """Get an OpenID Connect token issued by Google for the service account.

    This function:

      1. Generates a JWT signed with the service account's private key
         containing a special "target_audience" claim.

      2. Sends it to the OAUTH_TOKEN_URI endpoint. Because the JWT in #1
         has a target_audience claim, that endpoint will respond with
         an OpenID Connect token for the service account -- in other words,
         a JWT signed by *Google*. The aud claim in this JWT will be
         set to the value from the target_audience claim in #1.

    For more information, see
    https://developers.google.com/identity/protocols/OAuth2ServiceAccount .
    The HTTP/REST example on that page describes the JWT structure and
    demonstrates how to call the token endpoint. (The example on that page
    shows how to get an OAuth2 access token; this code is using a
    modified version of it to get an OpenID Connect token.)
    """

    service_account_jwt = (
        service_account_credentials._make_authorization_grant_assertion())
    request = google.auth.transport.requests.Request()
    body = {
        'assertion': service_account_jwt,
        'grant_type': google.oauth2._client._JWT_GRANT_TYPE,
    }
    token_response = google.oauth2._client._token_endpoint_request(
        request, OAUTH_TOKEN_URI, body)
    return token_response['id_token']
# END COPIED IAP CODE

Requirements.txt
requests
requests_toolbelt==0.9.1
google-auth==1.14.1
google-api-python-client==1.7.4
oauth2client==3.0.0
google-cloud-storage

Also like to enclose the error log message: (showing "TypeError: expected string or buffer" at the end)
Exception: Bad response from application: 500 / {'Date': 'Mon, 25 May 2020 02:18:10 GMT', 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': '3356', 'Server': 'gunicorn/19.9.0', 'Via': '1.1 google', 'Alt-Svc': 'h3-27=":443"; ma=2592000,h3-25=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"'} / '\n\n \n <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">\n \n \n
\n
 Ooops.
\n
\n
\n\n ____/ ( ( ) ) \\___\n /( ( ( ) _ )) ) )\\\n (( ( )( ) ) ( ) )\n ((/ ( _( ) ( _) ) ( () ) )\n ( ( ( (_) (( ( ) .((_ ) . )_\n ( ( ) ( ( ) ) ) . ) ( )\n ( ( ( ( ) ( _ ( _) ). ) . ) ) ( )\n ( ( ( ) ( ) ( )) ) _)( ) ) )\n ( ( ( \\ ) ( (_ ( ) ( ) ) ) ) )) ( )\n ( ( ( ( (_ ( ) ( _ ) ) ( ) ) )\n ( ( ( ( ( ) (_ ) ) ) _) ) _( ( )\n (( ( )( ( _ ) _) _(_ ( (_ )\n (_((__(_(__(( ( ( | ) ) ) )_))__))_)___)\n ((__) \\\\||lll|l||/// \\_))\n ( /(/ ( ) ) )\\ )\n ( ( ( ( | | ) ) )\\ )\n ( /(| / ( )) ) ) )) )\n ( ( ((((_(|)_))))) )\n ( ||\\(|(|)|/|| )\n ( |(||(||)|||| )\n ( //|/l|||)|\\\\ \\ )\n (/ / // /|//||||\\\\ \\ \\ \\ _)\n-------------------------------------------------------------------------------\nNode: 6003c629d1dc\n-------------------------------------------------------------------------------\nTraceback (most recent call last):\n File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app\n response = self.full_dispatch_request()\n File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1614, in full_dispatch_request\n rv = self.handle_user_exception(e)\n File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1517, in handle_user_exception\n reraise(exc_type, exc_value, tb)\n File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1612, in full_dispatch_request\n rv = self.dispatch_request()\n File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1598, in dispatch_request\n return self.view_functions[rule.endpoint](**req.view_args)\n File "/usr/local/lib/airflow/airflow/api/auth/backend/default.py", line 32, in decorated\n return function(*args, **kwargs)\n File "/usr/local/lib/airflow/airflow/www/api/experimental/endpoints.py", line 78, in trigger_dag\n dr = trigger.trigger_dag(dag_id, run_id, conf, execution_date)\n File "/usr/local/lib/airflow/airflow/api/common/experimental/trigger_dag.py", line 98, in trigger_dag\n replace_microseconds=replace_microseconds,\n File "/usr/local/lib/airflow/airflow/api/common/experimental/trigger_dag.py", line 62, in _trigger_dag\n run_conf = json.loads(conf)\n File "/usr/lib/python2.7/json/__init__.py", line 339, in loads\n return _default_decoder.decode(s)\n File "/usr/lib/python2.7/json/decoder.py", line 364, in decode\n obj, end = self.raw_decode(s, idx=_w(s, 0).end())\nTypeError: expected string or buffer\n
\n
\n
\n \n'
at make_iap_request (/user_code/main.py:125)
at trigger_dag (/user_code/main.py:45)
at call_user_function (/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py:214)
at invoke_user_function (/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py:217)
at run_background_function (/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py:383)

Cheers