text:
Q: How to store visited states in iterative deepening / depth limited search? Update: Search for the first solution.
for a normal Depth First Search it is simple, just use a hashset
    bool DFS (currentState) =
    {
          if (myHashSet.Contains(currentState))
          {
               return;
          }
          else
          {
                myHashSet.Add(currentState);
          }
          if (IsSolution(currentState) return true;
          else
          {
              for (var nextState in GetNextStates(currentState))
                   if (DFS(nextState)) return true;
          }
          return false;
     }

However, when it becomes depth limited, i cannot simply do this
    bool DFS (currentState, maxDepth) =
    {
          if (maxDepth = 0) return false;
          if (myHashSet.Contains(currentState))
          {
               return;
          }
          else
          {
                myHashSet.Add(currentState);
          }
          if (IsSolution(currentState) return true;
          else
          {
              for (var nextState in GetNextStates(currentState))
                   if (DFS(nextState, maxDepth - 1)) return true;
          }
          return false;
     }

Because then it is not going to do a complete search (in a sense of always be able to find a solution if there is any) before maxdepth
How should I fix it? Would it add more space complexity to the algorithm?
Or it just doesn't require to memoize the state at all.
Update:
for example, a decision tree is the following:
   A - B - C - D - E - A
                   |
                   F - G (Goal)

Starting from state A. and G is a goal state. Clearly there is a solution under depth 3.
However, using my implementation under depth 4, if the direction of search happens to be
A(0) -> B(1) -> C(2) -> D(3) -> E(4) -> F(5) exceeds depth, then it would do back track to A, however E is visited, it would ignore the check direction A - E - F - G

A: I had the same problem as yours, here's my thread Iterative deepening in common lisp
Basically to solve this problem using hashtables, you can't just check if a node was visited before or not, you have to also consider the depth at which it was previously visited. If the node you're about to examine contains a state that was not previously seen, or it was seen before but at a higher depth, then you should still consider it since it may lead to a shallower solution which is what iterative deepening supposed to do, it returns the same solution that BFS would return, which would be the shallowest. So in the hashtable you can have the state as the key, and the depth as the value. You will need to keep updating the depth value in the hashtable after finding a shallower node though.
An alternative solution for cycle checking would be to backtrack on the path from the current node up to the root, if the node you're about to examine already appears on the path, then it will lead to a cycle. This approach would be more generic, and can be used with any search strategy. It is slower than the hashtable approach though, having O(d) time complexity where d is the depth, but the memory complexity will be greatly reduced.

A: In each step of IDFS, you are actually searching for a path which is shortest, you can't simple use hashSet. HashSet helps only when you are searching for the existence of a path where the length is unlimited.
In this case, you should probably use hashMap to store the minimum step to reach the state and prune the branch only if the map value can't be updated. The time complexity may changed in correspond.
But in fact, IDFS is used in place of BFS when the space is limited. As hashing the state may take almost as many space as BFS, usually you can't store the all the state in IDFS trivially.
The IDFS in wiki dose not have a hash neither. http://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search
So let's drop out the hash and trade time for space!
Update
It's worthwhile to store the state in the current dfs stack, then the search path would not result into a trivial circle. The psudocode implementing this feature would be:
bool DFS (currentState, maxDepth) =
{
      if (maxDepth = 0) return false;
      if (myHashSet.Contains(currentState))
      {
           return;
      }
      else
      {
            myHashSet.Add(currentState);
      }
      if (IsSolution(currentState) return true;
      else
      {
          for (var nextState in GetNextStates(currentState))
               if (DFS(nextState, maxDepth - 1)) return true;
      }
      myHashSet.Remove(currentState); //the state is pop out from the stack
      return false;
 }

A: The solution you show is perfectly fine and works for DFSID(depth-first search with iterative deepening). Just do not forget to clear myHashSet before increasing the depth.


text:
Q: Execute js function using websocket and wait to return value to python code and vice versa I am trying to build application that uses browser as the user interface, and python as the backend. The idea here is that I want to use something like websocket so send message to js code to execute some function and return its value back to python and vice versa. but the problem is that websocket is asynchronous and I don't get anything back except "undefined", how can I solve this problem or is there any idea other than that?
what I want to do is something like that:
socket= new WebSocket('ws://127.0.0.1:8765');
socket.onopen = function(){
    console.log("Server is open")
}

function exec_py(){
    socket.send("hi");
    // I want to wait for the message and take it as the return of the exec_py()
    socket.onmessage = function(s) {
      response = s
    }

    return response
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: React - use window.open to open a URL from a variable Sorry, if this is a stupid question, but I'm just trying to have a URL entered into a field and then a button that, when clicked, will take the value in that field and open a new tab to that URL.
If I do this:
    onClick={event => {
                      event.preventDefault();
                      window.open('https://www.google.com/', '_blank');
    }}

Then it works just fine and opens a new tab with the specified url.
But if I set urlText = "https://www.google.com/" and do this:
onClick={event => {
                   event.preventDefault();
                   window.open({urlText},'_blank');
}}

Then it opens a new tab, but it goes to this instead:
http://theCurrentWebsiteDomain/[object%20Object]
I assume it's trying to add the urlText to the end of the current domain, like it's a page that I'm specifying instead of a whole new URL.
I added a console.log and it displays urlText just fine. If I click on it from the console, it goes right to the expected website.
What am I doing wrong?

A: There is no need to add the curly braces around your urlText variable since it's within the event callback function. If it were to be used in the JSX then curly braces would be required (like <div>{urlText}</div> or <input type="text" value={urlText} />) - but since you're calling a function there is no need to wrap the variable name in curly braces.
The error is caused because by wrapping the urlText variable in curly braces, you are converting urlText to an object: { urlText: "foo" } and thus it appears as [object%20Object] in the URL bar since any object converted to a string will be literally '[object Object]'.
onClick={(event) => {
  event.preventDefault();
  window.open(urlText, "_blank");
}}

A: Simply pass the string urlText directly into the function: window.open(urlText, '_blank') without curly brackets.
The curly brackets is syntax to create an object, this function takes in a string argument as its first parameter. So javascript parses your argument into a string [object%20Object], and due to there being no protocol in that it recognises it as a local path.


text:
Q: How to compare two values in formBuilder? I have the form builder as follows,
this.feedbackForm = new FormGroup({
  figure: new FormControl('', Validators.pattern(/^[0-9]+$/)),
  maxVal: new FormControl(''),
  minVal: new FormControl('', Validators.max(feedbackForm.values.maxVal - 1)),
});

I want to compare minVal such that it is less than max value, but from the above code it shows the error as follows,

ERROR TypeError: Cannot read property 'values' of undefined

A: You're referencing your form in your form definition. Meaning you're referencing feedbackForm before it is defined.
There are many ways to accomplish what you're going for. One way would be to add the validator to your form control after you define your form.
this.feedbackForm = new FormGroup({
  figure: new FormControl('', Validators.pattern(/^[0-9]+$/)),
  mixVal: new FormControl(''),
  maxVal: new FormControl('', Validators.pattern(/^[0-9]+$/)),
});

this.feedbackForm.get('minVal')
    .setValidators(Validators.max(this.feedbackForm.get('maxVal').value - 1))

A: marcusshep mentioned there are several possible ways and provided a good one. I figured I'd add another. It might be overkill for what you want, though.
You could make it a form-level, custom validator.
static minLessThanMax(control: AbstractControl): ValidationErrors {
    const value: formValue = (control as FormGroup).getRawValue();
    if (value) {
        const minValue = formValue.minValue;
        const maxValue = formValue.maxValue;

        if (minValue > maxValue) {
            control.get('min').setErrors({ minMoreThanMax: true });
        } else {
            control.get('end').setErrors(null);
        }
    }
    return null;
}

And then when you new up your FormGroup:
this.feedbackForm = new FormGroup({
  figure: new FormControl('', Validators.pattern(/^[0-9]+$/)),
  mixVal: new FormControl(''),
  maxVal: new FormControl('', Validators.pattern(/^[0-9]+$/)),
}, { validator: minLessThanMax });


text:
Q: Summing together 2 or more VLOOKUPs in Excel I have a cell which needs to sum together 3 different values, but I don't want to use relative/absolute cell references because the source data changes every year so the cell references would need re-pointing every year.
I've used VLOOKUPs for cells which only need to show 1 value and that's all fine, but I cannot find a way to add together the outcomes of 2 or more VLOOKUPs.  Also, each of the 3 values have different criteria, and I think I therefore need 3 separate VLOOKUP functions.
Is there a way of doing this?
This is the formula I've used, which returns a '#N/A' error:
=vlookup("10000",datatable,3,false)+vlookup("10001",datatable,3,false)+vlookup("10002"),datatable,3,false)+...etc etc etc.
Many thanks in advance
Rob

A: Here is a simple example of summing 3 VLOOKUPs:
=SUM(VLOOKUP("A",A1:B3,2,FALSE),VLOOKUP("E",A5:B7,2,FALSE),VLOOKUP("I",A9:B11,2,FALSE))

I put 3 simple tables, each 3 rows and 2 columns, and added the lookup values together. So I look up A and return 1, E and return 5, I and return 9. Then I sum them and return 15. :-)

A: Providing the only part to vary is the lookup_value (as appears to be so in your case) then, instead of writing multiple distinct VLOOKUP clauses followed by summing them (which could result in an extremely long construction indeed), you can use a single, equivalent VLOOKUP set-up.
So instead of, for example:
=VLOOKUP("X",DataTable,3,FALSE)+VLOOKUP("Y",DataTable,3,FALSE)+VLOOKUP("Z",DataTable,3,FALSE)
we can use the shorter:
=SUM(VLOOKUP(T(IF(1,{"X","Y","Z"})),DataTable,3,FALSE))
or, for more flexibility, if we have "X", "Y" and "Z" within a contiguous range somewhere within the worksheet, e.g. H1:H3, then:
=SUM(VLOOKUP(T(IF({1},H1:H3)),DataTable,3,FALSE))
If the criteria are not text strings, but numerics, then we can use N instead of T: for example, if we were looking for, not "X", "Y" and "Z", but 1, 2 and 3, then we would use:
=SUM(VLOOKUP(N(IF(1,{1,2,3})),DataTable,3,FALSE))
or:
=SUM(VLOOKUP(N(IF({1},H1:H3)),DataTable,3,FALSE))
If our criteria comprise a mixture of text and numerics, e.g. "X", 2 and "Z", then we need a slightly different approach, though I will leave that to another post!
References:
https://excelxor.com/2014/09/05/index-returning-an-array-of-values/
Regards

A: Good heavens. Stop using VLOOKUP, everyone. INDEXtogether with MATCH is cleaner, neater and less prone to errors.
Now, for what you are doing, you don't need either. Why not check out SUMIFS
In your case it would look something like this
=SUMIFS(Sumcolumn;Criteriacolumn;10000;Criteriacolumn2;10001,...)

And, even if your sumcolumns are different from each other - it is still easier to sum several sumifs than it is to sum several vlookups, since vlookup will throw a #N/A if empty reference, whereas sumifs will return 0. If you have a desire to be extra efficient with just one formula, use SUMPRODUCT - however that is a formula that needs some practice to write.


text:
Q: Increase amount of numbers for picking randomly There is a batch file that looks for Pen=n in the list.txt and changes its value (n) randomly from the given row of ten numbers (set "var[pen]=1 2 3 4 5 6 7 8 9 10"). But if there are more than ten numbers say twenty (set "var[pen]=1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20") or hundred, it is still picking a number from first ten ones ignoring the rest.
@echo off
setlocal EnableDelayedExpansion

set "file=D:\list.txt"
set "temp=D:\temp.txt"
set "var[pen]=1 2 3 4 5 6 7 8 9 10" &

for /L %%i in (1,10,1%time:~-2%) do set "rand=!random!"

(for /F "usebackq tokens=1,2 delims==" %%a in ("%file%") do (
   if defined var[%%a] (
      call :getRandomValue var="!var[%%a]!"
      echo %%a=!var!
   ) else if "%%b" neq "" (
      echo %%a=%%b
   ) else (
      echo %%a
   )
)) > "%temp%"

move /Y "%temp%" "%file%"

pause > nul && pause > nul
goto :EOF

:getRandomValue value="list"
set /A "rand=!random:~-1!+1"
for /F "tokens=%rand%" %%v in (%2) do set "%1=%%v"

Any help would be appreciated.
edit:
the list.txt contains a list of stuff like pen paper rubber etc. with the corresponding value next to it.
pen=5
pencil=43
paper=0
rubber=22

what the bat file does is just putting random number picking in up from the row of numbers provided. in the following case it would change the value of pen to a random number from 1 to 10. but if I add some extra numbers more than ten it will then just ignore them.

A: What you are aiming to do is to randomly index from a list, which requires you to first determine the number of items in the list.
one method of doing so:
@Echo off

 Set "var[pen]=a b c d e f g h i"

Rem enable enviroment for !expanison!
 Setlocal EnableDelayedExpansion

Rem Build 'array', splitting string on spaces and incrementing array size count
 Set _i=1& Set "item[1]=%var[pen]: =" & Set /A "_i+=1" & Set "item[!_i!]=%"

Rem index randomly from known array size [one indexed]
 For /f delims^= %%i in ('Set /A !random! %%!_i! + 1')Do Echo(Item:%%i = !Item[%%i]!
 Pause

A: You forgot to specify the origin post of this problem. In such a post, there is not any specification about how the probabilities must be given, but all the 3 examples provided have 10 probable values, so I assumed that all probabilities have 10 values. The fix is add the number of probabilities each value can have:
@echo off
setlocal EnableDelayedExpansion

rem Define the probabilities for new values
set "value[apple]=0 0 0 0 0 0 0 1 1 1" & set "num[apple]=10" & rem 0 (70%) or 1 (30%)
set "value[peach]=0 0 0 0 0 1 2 3 4 5" & set "num[peach]=10" & rem from 0 (50%) to 5 (the rest 50%)
set "value[banana]=54 68 82 96" & set "num[banana]=4" & rem each 25%

rem Randomize
for /L %%i in (1,10,1%time:~-2%) do set "ran=!random!"

(for /F "tokens=1,2 delims==" %%a in (input.ini) do (
   if defined value[%%a] (
      call :getRandomValue value=%%a
      echo %%a=!value!
   ) else if "%%b" neq "" (
      echo %%a=%%b
   ) else (
      echo %%a
   )
)) > output.ini

move /Y output.ini input.ini
goto :EOF

:getRandomValue value=item
set /A "ran=%random%%%num[%2]+1"
for /F "tokens=%ran%" %%v in ("!value[%2]!") do set "%1=%%v"
exit /B

You also forget (again) to provide the real format of the input file, that include [headers]:
[Berries]
Strawberry=1
Blackberry=-13
Blueberry=100
Cherry=6
[Fruits]
apple=0
peach=4
banana=18
orange=-2.5
[Vegetables]
Potato=44
Tomato=2
Onion=0
Garlic=17

EDIT 2022/01/08: New method added as requested in comment
As I already said, you have not specified the rules to define the probable values. I proposed a method that works correctly based on your first example, but then you define values that does not conform with my proposed method (10 possible values, like in your first example). I modified the method and then you invented values that does not conform either: "Why 100 values?" "Because any number above 31 will make the method fail..."
I modified the method (again) so you can define the probabilities via value:percent pairs. Here it is:
@echo off
setlocal EnableDelayedExpansion

rem Define the probabilities for new values as value:percent pairs
set "value[apple]=23:17 68:83"                    & rem 23 at 17%, 68 at 83%
set "value[peach]=0:50 1:10 2:10 3:10 4:10 5:10"  & rem from 0 (50%) to 5 (the rest 50%)
set "value[banana]=54:25 68:25 82:25 96:25"       & rem each 25%

rem Randomize
for /L %%i in (1,10,1%time:~-2%) do set "ran=!random!"

(for /F "tokens=1,2 delims==" %%a in (input.ini) do (
   if defined value[%%a] (
      call :getRandomValue %%a
      echo %%a=!value!
   ) else if "%%b" neq "" (
      echo %%a=%%b
   ) else (
      echo %%a
   )
)) > output.ini

move /Y output.ini input.ini
goto :EOF

:getRandomValue item
set /A "ran=%random%%%100+1, val=0"
for %%a in (!value[%1]!) do for /F "tokens=1,2 delims=:" %%x in ("%%a") do (
   if %ran% gtr !val! set "value=%%x"
   set /A val+=%%y
)
exit /B


text:
Q: When will a dev container be released with .NET SDK 6.0.400? https://github.com/microsoft/vscode-dev-containers/tree/main/containers/dotnet shows latest available is 6.0.301.
How long until 6.0.400 is available?

A: So solution was to  switch the tag on the image to use 6.0, which will be latest.
Also added to devcontainer.json:
 "features": {
    "dotnet": {
      "version": "latest",
    },
}


text:
Q: Email is getting null after login with facebook in flutter I am trying to facebook signin by using this library flutter_facebook_auth. I followed all the necessary steps to add the code in android and ios based on the documentation of that library. When i try to signin i get all the data like name, photo etc but email i am getting null. I tried with multiple facebook account but still user email i am getting null. What is the reason email is not showing? Below is the code of facebook signin
  Future<UserCredential> signInWithFacebook() async {
    // Trigger the sign-in flow
    final LoginResult loginResult = await FacebookAuth.instance.login();

    // Create a credential from the access token
    final OAuthCredential facebookAuthCredential =
        FacebookAuthProvider.credential(loginResult.accessToken!.token);
    final userData = await FacebookAuth.instance.getUserData();
    print(userData);
    // Once signed in, return the UserCredential
    return FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);
  }


text:
Q: Why isn't querySelectorAll working with my ID values? I use this piece of code for a live searching and for calculate the "Total" :
$('#search').keyup(function () {
    var x = [];
    var y = [];
    var $total = 0;
    var inputString = $("#search").val();

    var act = document.getElementById("labdb").value;

    $('td:first-child').parent().show();
    $('td:first-child').parent().addClass("notHide");
    $('td:first-child').parent().removeClass("toHide");

    $var = $('td:first-child').parent('tr:not(:icontains(' + inputString + ')):not(:contains("Total"))');

    $var.hide();
    $var.addClass('toHide');
    $var.removeClass('notHide')

    for (var price of document.querySelectorAll('tr.notHide td.price')) {
           x.push(parseFloat(price.innerText));
    }
    for (var cantidad of document.querySelectorAll('tr.notHide td.quantity')) {
        y.push(parseFloat(cantidad.innerText));
    }
    for(var i = 0; i <= x.length-1; i++){
        $total += x[i] * y[i];

    }
    document.getElementById("total"+act).innerText = $total.toFixed(2);
});

I have various tables, with differents ID's, first is id='0', second is id='1', etc.
I use collapse ('show') or ('hide') for show the selected table with a selector.
So, the problems comes when I try to calculate the "Total", It's calculated with the value of the  class "notHide" and "price/quantity".
And all the tables get this Class, so the price got crazy if there is more than 1 table with "Total"
I KNOW, that I need to specify the ID of the table to work around, but I cant.
I have tested with:
var act = document.getElementById("labdb").value;
var actHTML = document.getElementById("labdb");

It get the ID from the selected table, and then, in this part of code include it:
for (var price of actHTML.document.querySelectorAll('tr.notHide td.price')) {
       x.push(parseFloat(price.innerText));
}
for (var cantidad of actHTML.document.querySelectorAll('tr.notHide td.quantity')) {
    y.push(parseFloat(cantidad.innerText));
}

But that, dont work, Im all the time thinking about other solutions and trying it, but I cant.
Its the final part of that page. Only need to specify the ID of the "Total" calculator.
I had tried to with:
for (var price of document.querySelectorAll('#'+act+' tr.notHide td.price')) {
           x.push(parseFloat(price.innerText));
    }
    for (var cantidad of document.querySelectorAll('#'+act+' tr.notHide td.quantity')) {
        y.push(parseFloat(cantidad.innerText));
    }

For be more specific, I need that document.querySelectorAll('tr.notHide td.quantity') comes from a specific ID. For the rest, works perfectly, inclusive deleting the others tables with the parameter Total
EDIT_0:
I have do that:
let myTable = document.querySelector("#"+act);
let all = myTable.querySelectorAll('tr.notHide td.price');

for (var price of all) {
    x.push(parseFloat(price.innerText));
}
for (var cantidad of all) {
    y.push(parseFloat(cantidad.innerText));
}
for (var i = 0; i <= x.length - 1; i++) {
    $total += x[i] * y[i];

}

from here: LINK
And that is the console error:
scripts.js:57 Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#0' is not a valid selector.
at changePrice (https://neutrino.ugr.es/js/scripts.js:57:28)
at HTMLSelectElement. (https://neutrino.ugr.es/js/scripts.js:15:5)
at HTMLSelectElement.dispatch (https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js:2:43336)
at y.handle (https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js:2:41320)

A: Well I found the error. The method document.querySelectorAll('') doesn't work if the ID starts with a digit. Like said in an article on the subject:

The spec defines identifiers using a token diagram. They may contain
the symbols from a to z, from A to Z, from 0 to 9, underscores (_),
hyphens -, non-ASCII symbols or escape sequences for any symbol.
They cannot start with a digit, or a hyphen (-) followed by a digit. Identifiers require at least one symbol (i.e. the empty
string is not a valid identifier).

This is the final code:
$('#search').keyup(function () {

    var inputString = $("#search").val();

    $('td:first-child').parent().show();
    $('td:first-child').parent().addClass("notHide");
    $('td:first-child').parent().removeClass("toHide");

    $var = $('td:first-child').parent('tr:not(:icontains(' + inputString + ')):not(:contains("Total"))');

    $var.hide();
    $var.addClass('toHide');
    $var.removeClass('notHide')

    changePrice();
});

function changePrice() {
    var x = [];
    var y = [];
    var $total = 0;
    var act = document.getElementById("labdb").value;
    actt="t"+act+act;
    //alert(act);

    var myTable = document.querySelector("#"+actt);
    var allx = myTable.querySelectorAll('tr.notHide td.price');
    var ally = myTable.querySelectorAll('tr.notHide td.quantity');
    //alert(all)

    for (var price of allx) {
        x.push(parseFloat(price.innerText));
    }
    for (var cantidad of ally) {
        y.push(parseFloat(cantidad.innerText));
    }
    for (var i = 0; i <= x.length - 1; i++) {
        $total += x[i] * y[i];

    }
    //alert(x.length)
    document.getElementById("total" + act).innerText = $total.toFixed(2);
}

I changed the ID to start with a t: actt="t"+act+act;
(act+act is because id is 00, not 0)


text:
Q: Manually put Image Data to Plist file using Xcode I want to put an Image in a plist file. Programmatically it is easy to save images as data in plist files, but I want to preset the data entry manually.
How can I put these data with my xcode plist editor in the data field?

A: Since you know how to do it in code, write some temporary code to write the desired image to a temp plist file. Then you can copy the entry into the real plist file.
However, I'd suggest a different approach. Store the actual image in the app's resource bundle and put the filename in the plist file. This will be so much easier to maintain and update.

A: You would have to get the binary data of the image you want to have in the property list, and then input it in the file.
I wouldn't recommend it though. You can easily achieve this programmatically, if you need help with the code, i can help you


text:
Q: qlpreviewcontroller in ios6 By using qlpreviewcontroller getting the output in ios 4.3. i am showing the documents from the remote url.
In ios 6 it shows the empty view of the qlpreviewcontroller. Need to fix this issue .  Any tutorials for the qlpreviewcontroller in ios 6.
need to develop the application in the xcode 3.6 to overcome this issue is this possible to fix this issue.
thanks in advance.

A: QLPreviewController will only load files from a file URL. You have to load them from disk, so if you want to use QLPreviewController, you have to download the file and cache it on disk first.
I'm not completely sure what you mean when referring to Xcode 3.6, but you won't be able to create iOS6 apps using it.


text:
Q: PHP BackedEnum interface fails the instanceof operator Given:
enum TestEnum: string
{
  case CASE_1 = "first case";
  case CASE_2 = "Second case";
}

This is supposed to return true:
TestEnum::class instanceof \BackedEnum

But I get false
I tried the following from this post (it fails to run in Laravel Tinker REPL, but runs as a script?):
interface TestEnumInterface extends \BackedEnum
{
    public function foo(): string;
}

enum TestEnum: string implements TestEnumInterface
{
    case CASE_1 = 'case 1';
    case CASE_2 = 'case 2';

    public function foo(): string
    {
        return 'bar';
    }
}

TestEnum::class instanceof \BackedEnum //false
TestEnum::class instanceof \TestEnumInterface //false

What am I missing?
Running PHP v8.1.13
Thanks

UPDATE:
Indeed, as per SomeOne1 reply, the following returns true:
TestEnum::CASE_1 instanceof \BackedEnum

Then I'll try to be more specific.
I have to test a variable $list which could be a number of different enums (like $list = TestEnum::class or $list = AnotherEnum::class), or a Laravel collection, or an array.
  //if ($list instanceof \BackedEnum) {
  if (isset($isEnum)) { // I want to get rid of this
    // do stuff
  }
  else if ($list instanceof \Illuminate\Database\Eloquent\Collection || $list instanceof \Illuminate\Support\Collection) {
    // do stuff differently
  }
  else if (is_array($list)) {
    // do stuff differently
  }
  else {
    var_dump($list);
    dd('invalid list');
  }

Then how can I test if this variable is of enum type?

A: TestEnum::class is not an instanceof an object, it is an 'instanceof' a string.
TestEnum::CASE_1 is instanceof of TestEnum or TestEnumInterface

A: solution:
if (is_string($list) && enum_exists($list)) {
  // do stuff
}

tests:
$list = TestEnum::class; //true
$list = [0, 1]; //false
$list = "ciao"; //false
$list = collect([0, 1]); //false


text:
Q: C - Reading unknown formatted input I have a text file as input that has an unknown number of lines and a semi-unknown format. An example would be:
p1 a x1 300
p2 b x3 200 c x2 x1 500
p3 c x1 x3 1500 b x2 100 a x3 800

Where the 'c' operations involve two 'x' objects and the others involve one. The order of the operations can be random, and the amount of operations is also random. I need to store the 'p' number, operation type, associated 'x' object(s) and the integer at the end of the operation.
I don't know how to go about storing this data as scanf() only works with formatted input that is known. I've tried to traverse each line character-by-character using getc() but I can't detect the end of a file this way while also trying to grab and check multiple characters.
If anyone could help me figure out a way to store this data I would appreciate it.

EDIT:
My text file has other lines, too, but the final portion is the one I've specified. Currently this only grabs the first operation in the line 'n' times, where 'n' is the total number of operations in the line.
    for (i = 0; i < lines; i++) {
    if(fgets(line, MAXCHAR, fp)) {
        if (line[0] == 'p' && isdigit(line[1])) { // Check if we are interested in parsing the line
            k = opCount(line); // Amount of operations in line - Working
            data[c_count].t_num = k;
            data[c_count].trans = calloc(data[c_count].t_num, sizeof(clients));
            for (j = 0; j < k; j++) {
                tempBuf = strdup(line);
                if(tempBuf) {
                    token = strtok(tempBuf, delim);
                    if(token) {
                        //1st of n sections = p1 a x1 300
                        token = strtok(NULL, " ");//parsing on space now
                        if(token) {
                            strcpy(data[c_count].trans[j].lineNum, token);
                            //2nd section is opType
                            token = strtok(NULL, " ");
                            if (token) {
                                data[c_count].trans[j].op_type = atoi(token);
                                token = strtok(NULL, " ");
                                if (token) {
                                    data[c_count].trans[j].val = atoi(token);
                                }
                            }
                        }
                    }
                }
                free(tempBuf);
            }
            c_count++;
        }
    }

I'm also not sure this accounts for the 'c' case, where two objects are involved...

A: ...don't know how to go about storing this data as scanf()....
From what you have described in your post, the syntax of your input is actually known well enough to parse it.  Here are some suggestions, and some pseudo code to get you started:
Note:  scanf is not the best choice for parsing strings, even if there is some predictability to their syntax.  I suggest learning to use fgets in conjunction with strtok (or strtok_r) as an alternative.
const char filespec[] = {"C:\\dev\\play\\data.txt"};

typedef struct { //container for operation/line
    char lineNum[10];
    char opType;
    char op[2];
    int val; //you did not describe this in question
}OP;

typedef struct { //container for each line
     int opsCountOnLine;
     OP *section;
 }LINE;

const char *subs[] = {" a ", " b ", " c "};

int getLineCount(const char *filespec);//Counts '\n'.  Adjust function if other criteria
int countOfOpsPerLine(const char line);//Counts occurances of 'a', 'b', 'c', ... on a line

     int main(void)
     {
        int lineCount = getLineCount(filespec);
        int i;
        char line[280]; //adjust as necessary
        FILE *fp = NULL;

        LINE *lines = calloc(lineCount, sizeof(*lines));
        if(lines)
        {
            fp = fopen(filespec, "r");
            if(fp)
            {
                for(i=0;i<lineCount;i++)
                {
                    if(fgets(line, 280, fp))
                    {
                       //here is where LINE can be populated with content of each line
                       //1. determine operations in 'line'.
                       lines[i].opsCountOnLine = countOfOpsPerLine(line);
                       //2. allocate memory for sections.
                       lines[i].section = calloc(lines[i].opsCountOnLine, sizeof(OP));
                       for(j=0;j<lines[i].opsCountOnLine;j++)
                       {

                           tempBuf = strdup(line);
                           if(tempBuf)
                           {
                               //SEE EDIT below for suggested content in this inner loop.
                               //3. Parse line into lines[i].section[0].line, lines[i].section[0].opType, etc.
                               //   using delimiter of "abc" (...def...) with strtok()
                               //4. Other steps???
                               //then free tempBuf so you can use it again in the loop
                               free(tempBuf);
                        }

                    }
                    else
                    {
                        //notify user of error, exit
                        free(lines);
                    }
                }
                fclose(fp);
            }
        }
         return 0;
     }

    int countOfOpsPerLine(const char *line) //Counts occurances of 'a', 'b', 'c', ... on a line
    {
        int count=0, i;
        char *tok;
        // Parse line to find number of sections
        for(i=0;i<sizeof(subs)/sizeof(subs[0]);i++)
        {
            tok = strstr(line,subs[i]);
            if(tok != NULL) count++;
        }

        return count;
    }

int getLineCount(const char *filespec)
{
    int c=0, count=0;
    FILE *fp = fopen(filespec, "r");
    if(fp)
    {
        for (c = getc(fp); c != EOF; c = getc(fp))
        {
            if (c == '\n') // Increment count if this character is newline
            {
                count = count + 1;
            }
        }
        fclose(fp);
    }
    return count;
}

EDIT to include suggestion for inner loop  (and edited main struct above)
Since your input text seems to use a or b or c for opType, you  can use them as the delimiteror...
you can use
const char delim[] = {"abc"};

char *tok;

tok = strtok(tempBuf, delim);
if(tok)
{
    //1st of n sections = p1 a x1 300
    tok = strtok(NULL, " ");//parsing on space now
    {
        if(tok)
        {
            strcpy(lines[i].section[j].lineNum, tok);
            //2nd section is opType
            tok = strtok(NULL)
            if(tok)
            {
                lines[i].section[j].opType = atoi(tok);
                //3rd section is op (and so on...)
                //repeat the same process here until you
                //parsed and placed all members
            }
        }

    }
}


text:
Q: How to Mask Text into an Imageview in Android? I have been trying to get the desired result as below but in-vain. I need to mask an imageview into text so that the imageview looks like text but still works as an imageview such that i can use zoom functionality in it.

The image should not overflow beyond the text border. I have out Glide-Transformations and some others but it didn't workout.The text is dynamic and can be replaced by any letters or words.

EDIT

Here's a code snippet:
Glide.with(this).load(R.drawable.eagle).override(width, height).bitmapTransform(new CenterCrop(this),

new MaskTransformation(mContext, R.drawable.mask_e)).into(Imageview);

A: To add a text to your ImageView you can do this:
<RelativeLayout>
    <ImageView
        android:id="@+id/myImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/myImageSouce" />

    <TextView
        android:id="@+id/myImageViewText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/myImageView"
        android:layout_alignTop="@+id/myImageView"
        android:layout_alignRight="@+id/myImageView"
        android:layout_alignBottom="@+id/myImageView"
        android:layout_margin="1dp"
        android:gravity="center"
        android:text="Hello"
        android:textColor="#000000" />
 </RelativeLayout>

PS. Only works inside a RelativeLayout


text:
Q: cakephp only one model get validates I have a form that save to two models. In the controller I call the validate. But it only checks the first model. It will save without validating the second.
It saves to both models fine. Cant see what is wrong, I have used the validate first as recommended.
Controller:
        if ($this->Company->saveAll($this->request->data, array('validate'=>'first'))) {  // Should ensure both sets of model data get validated
            $this->Session->setFlash(__('The company has been saved'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The company could not be saved. Please, try again.'));
        }
    }

View:
    echo $this->Form->input('name');
    echo $this->Form->input('address1');
    echo $this->Form->input('address2');

    echo $this->Form->input('Umuser.username');
    echo $this->Form->input('Umuser.password');

first model:
/**
* Display field
*
* @var string
*/
public $displayField = 'name';
var $actsAs = array('Containable');
/**
* Validation rules
*
* @var array
*/
public $validate = array(
    'neci_member_number' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'numeric' => array(
            'rule' => array('numeric'),
            'message' => 'Members number should only contain numbers',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'length' => array(
            'rule' => array('maxLength', 11),
            'message' => 'No more than 11 digits',
        ),
    ),

    'name' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'address1' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'address2' => array(
    ),
    'county' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'limited' => array(
        'boolean' => array(
            'rule' => array('boolean'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'tax_number' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'contact_name' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'phone' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'numeric' => array(
            'rule' => array('alphanumeric'),
            'message' => 'Phone number should only contain numbers, no spaces or other characters',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'email' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Please complete this field',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'email' => array(
            'rule' => array('email'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
    'payment_start' => array(
        'date' => array(
            'rule' => array('date'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
);

//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
* hasMany associations
*
* @var array
*/
public $hasMany = array(
    'Employee' => array(
        'className' => 'Employee',
        'foreignKey' => 'company_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    ),
    'MonthlyReturn' => array(
        'className' => 'MonthlyReturn',
        'foreignKey' => 'company_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    )
);

public $hasOne = 'Umuser';

Second model:
    class Umuser extends UserminAppModel {
public function beforeSave() {

    if (isset($this->data[$this->alias]['password'])) {

        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
    return true;
}

/**
 * Validation rules
 *
 * @var array
 */
public $validate = array(
    "username" => array(
        'mustUnique' => array(
            'rule' => array('isUnique'),
            'message' => 'That username is already taken.'),
        'mustBeLonger' => array(
            'rule' => array('minLength', 3),
            'message' => 'Username is required and must have a minimum of 3 alphanumeric characters.',
            'last' => true),
    ),
    'email' => array(
        'mustBeEmail' => array(
// code borrowed from here http://fightingforalostcause.net/misc/2006/compare-email-regex.php
// thanks to James Watts and Francisco Jose Martin Moreno
            'rule' => '/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i',
// end of borrowed code
            'message' => 'Please supply a valid email address.',
            'last' => true),
        'mustUnique' => array(
            'rule' => 'isUnique',
            'message' => 'That email is already registered.',
        )
    ),
    'confirm_password' => array(
        'mustBeLonger' => array(
            'rule' => array('minLength', 4),
            'message' => 'Your password is too short, please provide 4 characters minimum.',
        ),
        'mustMatch' => array(
            'rule' => array('verifies', 'password'),
            'message' => 'You must fill in the password field and must match with confirm.'
        )
    ),
    'captcha' => array(
        'rule' => 'notEmpty',
        'message' => 'This field cannot be left blank'
    )
);

//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * belongsTo associations
 *
 * @var array
 */
public $belongsTo = array(
    'Company'=> array(
        'className' => 'Company',
        'foreignKey' => 'company_id'
        ),
    'Umrole' => array(
        'className' => 'Umrole',
        'foreignKey' => 'umrole_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

A: if you use the AuthComponent, the posted passwords will be automatically hashed. That may explain why you see that dots when the form is reloaded (probably 40 dots btw). What you can do is specify that you want the password field to remain empty :
    echo $this->Form->input('password', array(
        'label' => 'password',
        'value' => ''
    ));


text:
Q: Single Photon Hits A Linear Polarizer, What Happens? If a linear polarized single photon strikes a linear polarizer such that its polarization is at 45 degrees to the polarization axis of the polarizer, what happens?
There is a nearly 50% chance that the photon is transmitted, and assuming it is transmitted, it somehow rotates its polarization to match that of the polarizer axis. But the photon has energy defined by E=hv before and after it encounters the polarizer.  So it cannot lose energy by projecting its amplitude onto the polarization axis, as per the normal explanation.
Also assuming the linear polarizer is a dichroic type, then I understand that this means the long molecules in the film have their long axis aligned perpendicular to the polarization axis - so how does the photon encounter the molecules.  Is it absorbed and then re-emitted orthogonal to the molecular axis somehow?

A: Since you are talking about photons, you are also talking about quantum mechanics.  In the language of QM, the incoming photon induces a transition to a virtual state of a molecule in the polarizer.  When the molecule returns to the ground state, a photon of rotated polarization is emitted.
This transition to a virtual state is not absorption.  The energy of the photon does not have to be anywhere near the energy of a molecular transition.  The photon and the molecule find themselves in a state of mixed photon and molecule character.  This state retains its coherence properties, and the phase of the outgoing photon is related to the phase of the incoming photon, and its frequency is identical to that of the incoming photon.
In real absorption, something (like a collision) interrupts the coherence of the mixed state, which could lead to the molecule finding itself in a true excited state.  This can only happen if the energy of the photon matches the energy of the excited state.  In that case, we say the photon has been absorbed.  The molecule will eventually spontaneously drop back to the ground state emitting a photon, but that photon will have no fixed phase relationship with the original, and might not have the same frequency.


text:
Q: When I use group_concat on two fields, can I count on the two concatenations having the same order? If I have a table like this:
  bagid  fruit  color
  -----  -----  -----
  1      apple  red
  1      banana yellow

and I select bagid,GROUP_CONCAT(fruit),GROUP_CONCAT(color) grouped by bagid, can I count on the results looking like this:
1 apple,banana red,yellow

or will they sometimes look like this:
1 apple,banana yellow,red

In other words, will the two concatenations always be ordered in the same way? That seems to be the case, but I'd like to be sure.  For what it's worth, I'm using Mariadb 10.3.

A: You are not guaranted that they will be in the same order, eventhogh it likely will happen. Not even adding an ORDER BY at the end of your query will guarantee it, since that is logically evaluated after the aggregate functions.
You can however get the same order if you add the same order by to both GROUP_CONCAT:
SELECT bagid
     , GROUP_CONCAT(fruit ORDER BY fruit)
     , GROUP_CONCAT(color ORDER BY fruit)
FROM t
GROUP BY bagid


text:
Q: Get index value of an array by it's value in PHP from JSON file I have this array structure i want to get the hour which have 14 value after finding that i need to get the index of that array which i need to filter other element please help.
$string = file_get_contents("http://api.wunderground.com/api/aa433737d95d5869/hourly/q/US/Los%20Angeles%20International.json");
$json = json_decode($string, true);
foreach ($json as  $value) {
    echo "<pre>";
    print_r($value);
    echo "</pre>";
    print_r(search($value, 'hour', '14'));
    echo find_parent($value, '14');
}

A: Here you go:
$json = json_decode($string, true);
foreach ($json['hourly_forecast'] as $key => $val) {
    if ($val['FCTTIME']['hour'] == 14) {
        die('The key is where hour is 14 is: ' . $key);
    }
}

A: You can use foreach like this to get each key => value pair and do whatever you want:
<?php
foreach ($json  as $key => $value) {
    if ($key === "hour") {
        if ($value === "14") {
            // do whatever
        }
    }
}
?>

From the api you showed, it looks like you'd have to dig a bit deeper into the array though, but this is how you'd achieve what you want.

A: I'm not sure I understand the question, but if you would like to pick out the FCTTIME item where hour is equal to 14 you could do like this:
$json = file_get_contents("http://api.wunderground.com/api/aa433737d95d5869/hourly/q/US/Los%20Angeles%20International.json");

// decode the json string
$object = json_decode($json);

// loop through each `hourly_forecast` item and check if `FCTTIME->hour` is equal to 14
foreach ($object->hourly_forecast as $index => $forecast) {
  if($forecast->FCTTIME->hour == 14) {
     // the $index contains the items position in the `hourly_forecast` array
  }
}


text:
Q: javascript object undefined under anonymous function Let's first take a look at JavaScript code =>
function ConstructNodes(className,hiddenId,alertMsg,formName){
    this.className = className;
    this.hiddenId  = hiddenId;
    this.alertMsg  = alertMsg;
    this.formName  = formName;
}

ConstructNodes.prototype.getId = function(){
    var nodes = document.getElementsByClassName(this.className);
    for (var i=0;i<nodes.length;i++){
        nodes[i].onclick = function(){
            var r = confirm(this.alertMsg);
            if (r==true){
                alert(this.hiddenId); // undefined
            } else {
                return;
            }
        };
    }
};

var obj = new ConstructNodes("className","hiddenId","Are you sure ?","formName");
obj.getId();

My problem in this situation is that defined objects are undefined under getId's anonymous function , how can I solve this situation ? thanks

A: Your code is incorrectly assuming that this will refer to a "ConstructNodes" object inside the event handlers. It won't; it'll be the element.  Instead, store this in an object, and things will be better:
ConstructNodes.prototype.getId = function(){
    var nodes = document.getElementsByClassName(this.className), obj = this;
    for (var i=0;i<nodes.length;i++){
        nodes[i].onclick = function(){
            var r = confirm(obj.alertMsg);
            if (r==true){
                alert(obj.hiddenId); // undefined
                document.getElementById(obj.hiddenId).value = this.id;
                alert(obj.hiddenId);
            } else {
                return;
            }
        };
    }
};

(It's not at all clear what you're trying to do, so there may be some issues still.)

A: It took me a minute to understand your question.
You cannot refer to this in an anonymous function in getId.
you must save this into a variable for example var me = this outside the anonymous function, and then use me.hiddenId.
Here is a JSFiddle to demonstrate that.

A: It's undefined because you can not access this in that function just like that.
Any function is called with it's own execution context, thus the this in that case is something different than outside of the function.
You can solve that by defining a var in the outer scope and access it in the inner, like this:
function ConstructNodes(className,hiddenId,alertMsg,formName){
  this.className = className;
  this.hiddenId  = hiddenId;
  this.alertMsg  = alertMsg;
  this.formName  = formName;
}

ConstructNodes.prototype.getId = function() {
  var _this = this; // a reference that will be known in your closure/function
  var nodes = document.getElementsByClassName(this.className);
  for (var i = 0; i < nodes.length; i++) {
    nodes[i].onclick = function(){
      if (confirm(_this.alertMsg)) {
        alert(_this.hiddenId); // no longer undefined
      } else {
        return;
      }
    };
  }
};

var obj = new ConstructNodes("className", "hiddenId", "Are you sure?", "formName")
obj.getId();


text:
Q: Save me from IE6 I'm getting ready to start work on a new web project for a fairly large corporation.
For all their users, something like 17,000 people, they are all stuck with IE6. They plan to have everyone transitioned to IE7 by the end of the year, however the IT department is starting to push this promise back.
What I've been asked to do is to give the project sponsor some more ammo push back on this. However, my charismatic politician button seems to be broken. I've only been unable to come up with simple phrases, such as "IE6 is teh suck" or "it will take me a million more hours to make it work in IE6 too" and all of this may be true but it doesn't really feel like a very mature statement to be making.
I guess what I'm looking for, is some kind of laymen's way of explaining that yes we can support IE6 but I'm going to need some hazard pay, and support that fact with some kind of hard evidence it does indeed take many more hours to make something look right and work in both IE6 and IE7.

A: What I have gone with an been successful with is the following.
IE 6 is an application that is almost 8 years old, and as part of this doesn't support current technologies as easily as most others.  Creating AJAX enabled rich UI's with IE6 is a very tedious task, and typically requires substantial, browser specific work to accomplish as it carries its own level of "Standards".
In addition to all of this there are security and performance implications.

A: We often have the need to persuade non technical users that IE6 is a very bad idea for any company to be still running and so have a document we are working on to educate home and corporate users here is a summary if it helps:
Why is IE 6 a problem?
Much less secure than other browsers
The internet has changed a lot since IE 6 was released and there are more threats to data security than ever before including phishing scams, script injection attacks, key logging viruses, identity theft and bot-nets (machines which have been taken over for criminal activity).
It is well documented that IE6 is less secure than modern browsers when surfing the internet:
"..the most compelling reason to upgrade is the improved security. The Internet of today is not the Internet of five years ago. There are dangers that simply didn't exist back in 2001, when Internet Explorer 6 was released to the world."
Sandi Hardmeier, Microsoft MVP
"Older browsers are a swiss-cheese of security holes, allowing black-hats out there to take over computers, construct bot-nets, and even steal their victim's identity, most of the time without their knowledge."
www.joelevi.com
IE 6 poses a security risk to any computer that it is used on for web browsing.
Any responsible IT team will upgrade to IE7 or later on all machines within a corporate network. Many now install the Firefox browser in order to increase security further.
It is not standards compliant
IE 6 does not render web pages in the same way that most browsers do as it uses a proprietary engine which ignores many of the standards set by the W3C (the World Wide Web Consortium). This leads some web pages to be displayed incorrectly in IE 6 and some not to display at all.
This also means that while web developers have to support IE 6 much of their work is taken up by fixing pages rather than developing better content and features. In short IE 6 is holding back the web's development for all users.
Slower
During the last 8 years of browser development as well as improved security browsers have been tuned for better performance on all fronts including download speed, rendering speed and JavaScript/AJAX performance which is a technology used on most major sites to give a better end user experience (sometimes know as Web 2.0 technology).
Memory Usage
Internet Explorer 7 actually uses less memory than IE6 and uses less overall resources on a machine. So upgrading can improve the performance of older computers.
Upgrading to Firefox or Chrome
Firefox
http://en-us.www.mozilla.com/en-US/firefox/firefox.html
Chrome
http://www.google.co.uk/chrome
Upgrading to IE 7 / 8
Home users
Internet Explorer 7 http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=9ae91ebe-3385-447c-8a30-081805b2f90b
Internet Explorer 8
http://www.microsoft.com/downloads/details.aspx?familyid=341C2AD5-8C3D-4347-8C03-08CDECD8852B&displaylang=en
Corporate Users
Internet Explorer 7 Resource Page
http://technet.microsoft.com/en-gb/ie/bb381619.aspx
Internet Explorer 7 Deployment Guide
http://www.microsoft.com/downloads/details.aspx?FamilyID=e41d8800-d134-4356-a2e7-c01bee790908&DisplayLang=en
Internet Explorer 8 Resource Page
http://technet.microsoft.com/en-us/ie/bb219517.aspx
Internet Explorer 8 Deployment Guide
http://technet.microsoft.com/en-us/library/cc985339.aspx

A: On the whole topic of IE6, whenever you get to that point of moving IT out of the past, you could use this:
http://code.google.com/p/ie6-upgrade-warning/

A: http://www.stopie6.org/
make them read it

A: Quite a difficult task to do, as there might be other reasons why they are using IE6 until this date (other, conflicting software which relies on IE6).
The first thing to do would be to identfy the problem that stops IT from doing the migration - if it's not lazyness.

*

*Maybe it is easier to ask them whether they would consider an "alternative browser" to be installed (which wouldn't affect the IE6 installs). But most administrators don't like that idea, because Firefox doesn't share data/configs with Windows Servers, but trade-offs might be made in favor of money.

*Should there be no real obstacle, you might show them a real-life example how an average day for an IE6 developer would look like.

*

*Choose an UI-feature (combine all merits of IE6 to create one) that will work to cause the required issues for the next few steps.

*Show them how everything looks fine in ALL Browsers.

*Show them how it doesn't look fine at all in IE6.

*Make it IE6 compatible.

*Show them how every other browser now produces a different/unwanted result.

*Fix it (with heavy workarounds) so that it now looks "ok" in most of the browsers.

*Tell them that you will have to put this effort into ALL of your components/features and that they will have much higer production costs.

Make sure to point out, that this would even happen if you would just compare IE6 to IE7. They may not ever switch to Safari.

A: All the IE6 experts are out of work and enjoying their pension.

A: It's 8 years old and two versions behind the times. What are people afraid of?

A: I do work for an unnamed company with 160000 employees where IE6 is the only company approved browser.   For me, to suggest they "just switch browsers" is futile, since I realize they have millions of dollars worth of applications now working with IE6, and that to port these apps would cost tens of thousands of dollars and many thousands more in fixing the ported versions.  I typically add 5-10% to web development just to address IE6 issues, depending on the interface.


text: Q: C/C++ Library for Performance Counters on Linux I have the source code to a collector program in Windows which records data from ~20 different counters (cpu usage, L2 cache misses, etc) every 500ms for two hours. I need to adapt this code to Linux and have no knowledge of how write hardware counter code. Is there/what is the best library in C/C++ for pulling data such as this off a Linux machine? I appreciate any help!


text:
Q: CentOS 6.3 server - questions regarding drives and partitions I have a CentOS 6.3 with Lighttpd and MySQL installed. I'm using Amazon Cloud (EC2) and I have no idea how to properly mount permanently another drive, so I can move DB to it.
I'm really lost in LINUX os-es, please help!
[root@ip-10-246-135-238 ec2-user]# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/xvde1            5.0G  1.5G  3.3G  32% /
tmpfs                 828M     0  828M   0% /dev/shm
/dev/xvde2            5.0G  1.5G  3.3G  32% /media/ephemeral0
/dev/xvde2            5.0G  1.5G  3.3G  32% /
/dev/xvdj             5.0G  1.5G  3.3G  32% /
/dev/xvde2            147G  3.3G  137G   3% /mnt/driveb

A: When you add anouther volume to the instance (using amazon's web gui "attach volume") it's as if you plugged it into the machine. You should see the new drive using fdisk -l
You'll need a filesystem on it. Lets say the new volume appears as /dev/xvdg, so mkfs.ext4 /dev/xvdg - (this is assuming you don't want to upt partitions on that volume, that's a whole other topic).
You'll then need to mount it, either once off or long term. To do it long term, make a directory, and put an entry (a new line) in /etc/fstab. It'll look something like:
/dev/xvdg /mnt/point/you/made ext4 defaults 0 0
save the file, then try mounting with mount /mnt/point/you/made - doing it in this order makes sure the mount command uses the fstab file for its information, which ensures the fstab file is ok.
It goes without saying, don't mess these steps up (like formatting the wrong disk!), or you can lose data. In particular, don't reboot until you've made sure your fstab file is ok, or your machine may not reboot properly. (you can fix it, but it's a real pain, particually in amazon ec2).


text:
Q: Using domain user in PSCP command? I use this command to copy file from Window to Linux with user "fred", it is successful
pscp  c:\temp\example-hosts.txt fred@10.53.x.x:/etc/hosts

But if my user name is domain user, such as: domain\fred. I got the error: More than remote source not supported
pscp c:\temp\example-hosts.txt domain\fred@10.53.x.x:/etc/hosts

Do you know how to fix this?

A: Add the -l flag for user
pscp -l domain\fred c:\temp\example-hosts.txt 10.53.x.x:/etc/hosts


text:
Q: Robust outlier detection in financial timeseries I'm looking for some robust techniques to remove outliers and errors (whatever the cause) from financial time-series data (i.e. tickdata).
Tick-by-tick financial time-series data is very messy. It contains huge (time) gaps when the exchange is closed, and make huge jumps when the exchange opens again. When the exchange is open, all kinds of factors introduce trades at price levels that are wrong (they did not occur) and/or not representative of the market (a spike because of an incorrectly entered bid or ask price for example). This paper by tickdata.com (PDF) does a good job of outlining the problem, but offers few concrete solutions.
Most papers I can find online that mention this problem either ignore it (the tickdata is assumed filtered) or include the filtering as part of some huge trading model which hides any useful filtering steps.
Is anybody aware of more in-depth work in this area?
Update: this questions seems similar on the surface but:

*

*Financial time series is (at least at the tick level) non-periodic.

*The opening effect is a big issue because you can't simply use the last day's data as initialisation even though you'd really like to (because otherwise you have nothing). External events might cause the new day's opening to differ dramatically both in absolute level, and in volatility from the previous day.

*Wildly irregular frequency of incoming data. Near open and close of the day the amount of datapoints/second can be 10 times higher than the average during the day. The other question deals with regularly sampled data.

*The "outliers" in financial data exhibit some specific patterns that could be detected with specific techniques not applicable in other domains and I'm -in part- looking for those specific techniques.

*In more extreme cases (e.g. the flash crash) the outliers might amount to more than 75% of the data over longer intervals (> 10 minutes). In addition, the (high) frequency of incoming data contains some information about the outlier aspect of the situation.

A: I'll add some paper references when I'm back at a computer, but here are some simple suggestions:
Definitely start by working with returns. This is critical to deal with the irregular spacing where you can naturally get big price gaps (especially around weekends). Then you can apply a simple filter to remove returns well outside the norm (eg. vs a high number of standard deviations). The returns will adjust to the new absolute level so large real changes will result in the loss of only one tick. I suggest using a two-pass filter with returns taken from 1 step and n steps to deal with clusters of outliers.
Edit 1: Regarding the usage of prices rather than returns: asset prices tend to not be stationary, so IMO that can pose some additional challenges. To account for the irregularity and power law effects, I would advise some kind of adjustment if you want to include them in your filter. You can scale the price changes by the time interval or by volatility.  You can refer to the "realized volatility" literture for some discussion on this.  Also discussed in Dacorogna et. al.
To account for the changes in volatility, you might try basing your volatility calculation from the same time of the day over the past week (using the seasonality).

A: I have (with some delay) changed my answer to reflect your concern about the lack of 'adaptability' of the unconditional mad/median.
You can address the problem of time varying volatility with the robust statistics framework. This is done by using a robust estimator of the conditional variance (instead of the robust estimator of the unconditional variance I was suggesting earlier): the M-estimation of the GARCH model. Then you will have a robust, time varying estimate of $(\hat{\mu}_t,\hat{\sigma}_t)$ which are not the same as those
produced by the usual GARCH fit. In particular, they are not driven by a few far away outliers. Because these estimate are not driven by them, you can use them to reliably flag the outliers using the historical distribution of the
$$\frac{x_t-\hat{\mu}_t}{\hat{\sigma}_t}$$
You can find more information (and a link to an R package) in this paper:

Boudt, K. and Croux, C. (2010). Robust M-Estimation of Multivariate
  GARCH Models.

A: The problem is definitely hard.
Mechanical rules like the +/- N1 times standard deviations, or +/ N2 times MAD,  or +/- N3 IQR or ... will fail because there are always some series that are different as for example:

*

*fixings like interbank rate may be constant for some time and then jump all of a sudden

*similarly for e.g. certain foreign exchanges coming off a peg

*certain instrument are implicitly spreads; these may be near zero for periods and all of a sudden jump manifold

Been there, done that, ... in a previous job.  You could try to bracket each series using arbitrage relations ships (e.g. assuming USD/EUR and EUR/JPY are presumed good, you can work out bands around what USD/JPY should be; likewise for derivatives off an underlying etc pp.
Commercial data vendors expand some effort on this, and those of use who are clients of theirs know ... it still does not exclude errors.


text:
Q: What are hash keys and range keys in dynamodb and how to use them I was currently looking into dynamodb documentation and it is not clear about what hash keys and range keys are and how should they be used.
I just need a basic explanation of what they are and how I am supposed to use them so that I can move forward with using it.

A: I like to think of it like this:

*

*Every item (row) in a table needs to have a Unique ID (Primary Key)

*A Primary Key is either:

*

*Partition Key, or

*Partition Key + Sort Key
For example, if you had an Invoices table, then the primary key would the Invoice Number. If you had a Login table, then the primary key would be User ID + Timestamp because one user could have multiple logins.
Behind-the-scenes, the Partition Key is also used to distribute data amongst servers. This is how DynamoDB assures its high speed — when there's more data, it is distributed across more servers.
If a table (such as the Login table) has multiple entries for a given Partition Key (eg User ID), then the addition of the Sort Key ensures the uniqueness of the Primary Key so that the Item can be stored and retrieved quickly.
Hash Key = Partition Key
Range Key = Sort Key

A: From DynamoDB Documentation
Hash key is your Partition key (Similar to a Primary Key in SQL). In a table that has only a partition key, no two items can have the same partition key value. - True in the absence of a Sort key
Range key is your Sort key (Referred to as a Composite Key) - makes possible to have the combination of Hash Key + Range Key. The first attribute is the partition key, and the second attribute is the sort key
E.g.:
H1 + R1 -> H1R1 is one Composite Key.
H1 + R2 -> H1R2 is another Composite Key.
For a real world scenario, consider a case where there is one user but has multiple roles.
User Id itself can't be used for all the cases. User-Id + Role-Id makes for a unique composite key.

A: The hash key and range key (a.k.a. sort key) together form the key for each of the items in your database. But what's the difference between the two key parts?
A "hash key" is mandatory. DynamoDB is a distributed table, and uses the hash key to decide on which of the cluster's node(s) to put this item. In particular, all items with the same hash key end up in the same node.
They don't just end up in the same node - they actually are store there contiguously on disksorted in the order of the second part of the key of the item, which is why this part is called the sort key - or the range key because it can be used to read a range of items between two values of the range key.
Having both parts of the key gives you powerful ways to model your data in a way it can be efficiently retrieved. It is efficient to retrieve a specific item with a specific key (the GetItem operation), or all items that have a specific hash key but a range of range keys (the Query operation). There are a lot of examples in the DynamoDB documentation in how to use both parts of the key.


text:
Q: бинаризация в OpenCV если провести для изображения размытие по Гауссу (OpenCV, функция - GaussianBlur()), это будет считаться как провести бинаризацию изображения? То есть можно сказать, что GaussianBlur() == бинаризация? Или нет?
(извините за глупый вопрос)

A: Нет, не будет. Бинаризация - это вполне конкретный результат, когда в каждом пикселе изображения есть только бинарное значение 1 или 0.
Результатом же размытия по Гауссу будет все то же изображение, с теми же каналами, только размытое по Гауссу.


text:
Q: iOS static library does not work I followed the instructions in this article to create a static library:
http://developer.apple.com/library/ios/#technotes/iOSStaticLibraries/Articles/creating.html
I built it for iPhone simulator target. It built successfully, then I imported into a new project where I wanted to use it. It imported fine and there are no problems, but the library doesn't work. There are no library methods that I'm calling; rather the purpose of the library is to swizzle the UIViewController viewDidAppear method so that a piece of code gets executed every time a UIViewController appears. This piece of code is not getting called, despite my library being included in the "Link Binary With Libraries" build phase.
I know the problem isn't with the code itself because if I import the raw .m and .h source files not as a library, everything works fine.

A: Did your library contain any categories?
If so, I think you should follow these steps to get it work:

*

*In Xcode, double-click the target's name under "Targets" in the Project window.

*Choose the Build Settings panel.

*Scroll down to the "Other Linker Flags" build setting under the Linking collection and set its value to "-all_load -ObjC".

Please refer to corresponding Apple Documentation
Here is a related question: Objective-C categories in static library


text:
Q: Extracting nested function names from a JavaScript function Given a function, I'm trying to find out the names of the nested functions in it (only one level deep).
A simple regex against toString() worked until I started using functions with comments in them. It turns out that some browsers store parts of the raw source while others reconstruct the source from what's compiled; The output of toString() may contain the original code comments in some browsers. As an aside, here are my findings:
Test subject
function/*post-keyword*/fn/*post-name*/()/*post-parens*/{
    /*inside*/
}

document.write(fn.toString());

Results

Browser      post-keyword  post-name  post-parens  inside
-----------  ------------  ---------  -----------  --------
 Firefox      No            No         No           No
 Safari       No            No         No           No
 Chrome       No            No         Yes          Yes
 IE           Yes           Yes        Yes          Yes
 Opera        Yes           Yes        Yes          Yes

I'm looking for a cross-browser way of extracting the nested function names from a given function. The solution should be able to extract "fn1" and "fn2" out of the following function:
function someFn() {
    /**
     * Some comment
     */
     function fn1() {
         alert("/*This is not a comment, it's a string literal*/");
     }

     function // keyword
     fn2 // name
     (x, y) // arguments
     {
         /*
         body
         */
     }

     var f = function () { // anonymous, ignore
     };
}

The solution doesn't have to be pure regex.
Update: You can assume that we're always dealing with valid, properly nested code with all string literals, comments and blocks terminated properly. This is because I'm parsing a function that has already been compiled as a valid function.
Update2: If you're wondering about the motivation behind this: I'm working on a new JavaScript unit testing framework that's called jsUnity. There are several different formats in which you can write tests & test suites. One of them is a function:
function myTests() {
    function setUp() {
    }

    function tearDown() {
    }

    function testSomething() {
    }

    function testSomethingElse() {
    }
}

Since the functions are hidden inside a closure, there's no way for me invoke them from outside the function. I therefore convert the outer function to a string, extract the function names, append a "now run the given inner function" statement at the bottom and recompile it as a function with new Function(). If the test function have comments in them, it gets tricky to extract the function names and to avoid false positives. Hence I'm soliciting the help of the SO community...
Update3: I've come up with a new solution that doesn't require a lot of semantic fiddling with code. I use the original source itself to probe for first-level functions.

A: Cosmetic changes and bugfix
The regular expression must read \bfunction\b to avoid false positives!
Functions defined in blocks (e.g. in the bodies of loops) will be ignored if nested does not evaluate to true.
function tokenize(code) {
    var code = code.split(/\\./).join(''),
        regex = /\bfunction\b|\(|\)|\{|\}|\/\*|\*\/|\/\/|"|'|\n|\s+/mg,
        tokens = [],
        pos = 0;

    for(var matches; matches = regex.exec(code); pos = regex.lastIndex) {
        var match = matches[0],
            matchStart = regex.lastIndex - match.length;

        if(pos < matchStart)
            tokens.push(code.substring(pos, matchStart));

        tokens.push(match);
    }

    if(pos < code.length)
        tokens.push(code.substring(pos));

    return tokens;
}

var separators = {
    '/*' : '*/',
    '//' : '\n',
    '"' : '"',
    '\'' : '\''
};

function extractInnerFunctionNames(func, nested) {
    var names = [],
        tokens = tokenize(func.toString()),
        level = 0;

    for(var i = 0; i < tokens.length; ++i) {
        var token = tokens[i];

        switch(token) {
            case '{':
            ++level;
            break;

            case '}':
            --level;
            break;

            case '/*':
            case '//':
            case '"':
            case '\'':
            var sep = separators[token];
            while(++i < tokens.length && tokens[i] !== sep);
            break;

            case 'function':
            if(level === 1 || (nested && level)) {
                while(++i < tokens.length) {
                    token = tokens[i];

                    if(token === '(')
                        break;

                    if(/^\s+$/.test(token))
                        continue;

                    if(token === '/*' || token === '//') {
                        var sep = separators[token];
                        while(++i < tokens.length && tokens[i] !== sep);
                        continue;
                    }

                    names.push(token);
                    break;
                }
            }
            break;
        }
    }

    return names;
}

A: The academically correct way to handle this would be creating a lexer and parser for a subset of Javascript (the function definition), generated by a formal grammar (see this link on the subject, for example).
Take a look at JS/CC, for a Javascript parser generator.
Other solutions are just regex hacks, that lead to unmaintainable/unreadable code and probably to hidden parsing errors in particular cases.
As a side note, I'm not sure to understand why you aren't specifying the list of unit test functions in your product in a different way (an array of functions?).

A: Would it matter if you defined your tests like:
var tests = {
    test1: function (){
        console.log( "test 1 ran" );
    },

    test2: function (){
        console.log( "test 2 ran" );
    },

    test3: function (){
        console.log( "test 3 ran" );
    }
};

Then you could run them as easily as this:
for( var test in tests ){
    tests[test]();
}

Which looks much more easier.
You can even carry the tests around in JSON that way.

A: I like what you're doing with jsUnity. And when I see something I like (and have enough free time ;)), I try to reimplement it in a way which better suits my needs (also known as 'not-invented-here' syndrome).
The result of my efforts is described in this article, the code can be found here.
Feel free to rip-out any parts you like - you can assume the code to be in the public domain.

A: The trick is to basically generate a probe function that will check if a given name is the name of a nested (first-level) function. The probe function uses the function body of the original function, prefixed with code to check the given name within the scope of the probe function. OK, this can be better explained with the actual code:
function splitFunction(fn) {
    var tokens =
        /^[\s\r\n]*function[\s\r\n]*([^\(\s\r\n]*?)[\s\r\n]*\([^\)\s\r\n]*\)[\s\r\n]*\{((?:[^}]*\}?)+)\}\s*$/
        .exec(fn);

    if (!tokens) {
        throw "Invalid function.";
    }

    return {
        name: tokens[1],
        body: tokens[2]
    };
}

var probeOutside = function () {
    return eval(
        "typeof $fn$ === \"function\""
        .split("$fn$")
        .join(arguments[0]));
};

function extractFunctions(fn) {
    var fnParts = splitFunction(fn);

    var probeInside = new Function(
        splitFunction(probeOutside).body + fnParts.body);

    var tokens;
    var fns = [];
    var tokenRe = /(\w+)/g;

    while ((tokens = tokenRe.exec(fnParts.body))) {
        var token = tokens[1];

        try {
            if (probeInside(token) && !probeOutside(token)) {
                fns.push(token);
            }
        } catch (e) {
            // ignore token
        }
    }

    return fns;
}

Runs fine against the following on Firefox, IE, Safari, Opera and Chrome:
function testGlobalFn() {}

function testSuite() {
    function testA() {
        function testNested() {
        }
    }

    // function testComment() {}
    // function testGlobalFn() {}

    function // comments
    testB /* don't matter */
    () // neither does whitespace
    {
        var s = "function testString() {}";
    }
}

document.write(extractFunctions(testSuite));
// writes "testA,testB"

Edit by Christoph, with inline answers by Ates:
Some comments, questions and suggestions:

*

*Is there a reason for checking
typeof $fn$ !== "undefined" && $fn$ instanceof Function

instead of using
typeof $fn$ === "function"

instanceof is less safe than using typeof because it will fail when passing objects between frame boundaries. I know that IE returns wrong typeof information for some built-in functions, but afaik instanceof will fail in these cases as well, so why the more complicated but less safe test?

[AG] There was absolutely no legitimate reason for it. I've changed it to the simpler "typeof === function" as you suggested.

*How are you going to prevent the wrongful exclusion of functions for which a function with the same name exists in the outer scope, e.g.
function foo() {}

function TestSuite() {
    function foo() {}
}

[AG] I have no idea. Can you think of anything. Which one is better do you think? (a) Wrongful exclusion of a function inside. (b) Wronfgul inclusion of a function outside.
I started to think that the ideal solution will be a combination of your solution and this probing approach; figure out the real function names that are inside the closure and then use probing to collect references to the actual functions (so that they can be directly called from outside).

*It might be possible to modify your implementation so that the function's body only has to be eval()'ed once and not once per token, which is rather inefficient. I might try to see what I can come up with when I have some more free time today...

[AG] Note that the entire function body is not eval'd. It's only the bit that's inserted to the top of the body.
[CG] Your right - the function's body only gets parsed once during the creation of probeInside - you did some nice hacking, there ;). I have some free time today, so let's see what I can come up with...
A solution that uses your parsing method to extract the real function names could just use one eval to return an array of references to the actual functions:
return eval("[" + fnList + "]");

[CG] Here is with what I came up. An added bonus is that the outer function stays intact and thus may still act as closure around the inner functions. Just copy the code into a blank page and see if it works - no guarantees on bug-freelessness ;)

Not as elegant as LISP-macros, but still nice what JAvaScript is capable of ;)

A:

I'm sure I missed something, but from your requirements in the original question, I think I've met the goal, including getting rid of the possibility of finding the function keyword in string literals.
One last point, I don't see any problem with mangling the string literals in the function blocks. Your requirement was to find the function names, so I didn't bother trying to preserve the function content.


text:
Q: Varnish waits for the complete page load before sending response to browser I've setup varnish to sit in front of a tomcat server. What I've noticed is that Varnish seems to wait for the complete page to load (all css, js, etc) before it sends any response to the browser.
This causes a huge lag before the user sees anything. If I bypass Varnish and go directly to the site, it responds immediately.
While the total page load time might be similar, the perception is that the site is slow.
Has anyone faced this?

A: Unless you have JS and CSS inline in your HTML, the behavior you describe is simply technically impossible.
Your browser will need to receive and parse the HTML to extract <script> and <link> tags and send separate HTTP requests; even if they get to the same Varnish server, it will have no idea they are part of the same "page".
Try changing the HTML to load static (JS, CSS and images) from a different hostname that doesn't go to Varnish; that should make things easier to debug.
You could get the same result by using a command-line HTTP client, e.g. curl.
If you still see the same slow performance in this scenario, look at the Varnish logs, it will likely give you quite a few ideas for more stuff to check. Feel free to add that as a comment, that way we'll be able to help you better.

A: With the complete page to load (all css, js, etc) you mean only embedded js and css resources, am I right? Varnish will buffer (and hopefully store) a response as a whole, before sending it to the client. If your back-end sends a response incrementally (e.g. chunked), a non-cached page might appear slower because it's only delivered by varnish after the back-end has sent its last piece.
If this is a problem, change the technical design of your application. Make sure most requests can be served from cache (these pages will be really fast) and externalize js & css resources (browser cache avoids doing requests at all). If there's only a small portion of your page that's slow and badly cacheable, load it asynchronously (e.g. Ajax).
There's also the concept of incremental rendering (a browser re-rendering pages as more resources become available), but I don't see how Varnish would change this behavior.

A: I think you were getting confused by varnish's response buffering. Let's say the fastest your backend can respond with a 100k page for a given request is 10 seconds, sending 10k each second. Without varnish in your stack, the client connection gets tunneled directly to the back end, and the browser starts receiving data in 1 second (the first 10k, and starts to parse, render, follow <link> tags, etc).
With varnish in your stack, it waits for the back end to send the entire page before sending the first byte to the client. So the client has to wait 10 seconds until it can start rendering the page, following <link> tags, etc. Believe it or not, this is a good thing for two main reasons. One, if that response is cacheable, the next client won't have to wait 10 seconds for the back end to generate the response, varnish will serve it quite quickly (ms, not s). If your hit rate is high, which you should optimize for, the initial cost of having to wait for the first byte of the response pays many dividends in future cache hits. Two, let's say a mobile phone on a spotty cell signal requests that same 100k page, but it can't download the page as fast as the backend can generate it, it needs a full minute to receive the 100k page. With varnish in place, apache doesn't have to waste a connection and thread for an entire minute (mostly idle, mind you) while it slowly transmits the data to the client. It sends the data as fast as it can to varnish, and then moves on to the next request while varnish sends the data slowly to the client.
For requests that are known not to be cacheable, you can configure varnish via VCL, if you desire, to return (pipe) which will result in no response buffering. It will send data directly from your back end to the client as soon as it receives it. But in the default.vcl pipe is not used.


text:
Q: highchart threshold color with live updating series I'm trying to apply the new threshold/negativeColor features of Highcharts v3.0.2 to essentially the 'spline updating each second' example.
During the animation of the chart updating, I'm seeing weird artifacts in the series line - it looks like it's animating to a different set of control points.. and then it snaps back to the correct configuration when the animation (of the new data point coming in) is done.
Commenting out the threshold/negativeColor features makes this visual artifact go away.
Am I seeing a bug?
UPDATE: I'm posting the following code as an example, which is the stock highcharts demo (my local jquery is v1.10.2) with the threshold/color/negativeColor lines (first lines under series) added by me. This code seemingly misbehaves.

A: Indeed it looks like a bug, reported here. At this moment you can only disable animations.


text:
Q: ID for tags in tag systems I'm implementing a tag system similar to StackOverflow tag system. I was thinking about when storing the tags and relating to a question, that relationship will be directly with the tag name or it's better create a field tagID to "link" the question with the tag? Looks that linking directly to tag name is easier, but it doesn't look good, mainly why when working with statistics and/or tag categorization (IMHO) can be hard to manage this. Another problem is when one admin decides "fix" a tag name. If there isn't a tagID separated from tag name, then I will be changing the key of the table...
What's your thoughts?
Thanks for all replies. I will delete this post since there is another posts with the same subject. I wonder why the search and the suggestion doesn't show it results for me...

A: Have a look at these related earlier SO questions:

*

*What is the most efficient way to
store tags in a
database

*Database design for
tagging

*How to design a database schema to
support tagging with
categories

*Is there an ideal schema for
tagging?

A: Your last sentence in your question seems to answer it.  Assuming the tags are stored in a tag table, I would always have an ID column (int or GUID) and the varchar/string column for the tag name.  The many-to-many (junction table) that would relate some other entity to one or more tags would have two columns containing the ID's the "other entity" and the tag's ID.
It's then easy to edit a tag (to correct a mis-spelling for example) without touching the key.  You should get much better performance when using queries that include joins with your junction table and it also means you're normalizing your data better.
Remember, "the key, the whole key and nothing but the key, so help me codd"!  :)

A: If you foresee many tags, and are using a relational database, using an ID that the database supports natively (e.g. RID) internally may just give you better performance.
If that's not a concern:  go by simple short tag names.  You can give the tags long names which will be displayed in the user interface too where it makes sense (e.g. ask the user for one when creating a new tag).  You are more likely to have to edit the long names, which nothing refers to directly, so this is not a problem.
Aside, if you are using a relational database, it is probably not very difficult to change a tag name together with all its references with a simple query, it may just be a slightly more expensive operation, but it is probably not going to be done frequently enough that you need to optimize for it.  And consider that you may have duplicate tags that you will want to merge too, so you might want to be able to do that anyway.


text:
Q: Rails 4 / Koala: how to refresh long access token? Using Rails 4 and Koala gem version 2.
I have my personal Facebook page (not profile).
When I am publishing a new post in my website I want to automatically publish it on my facebook page as well.
I am using Koala gem but I have some problem with access tokens.
Visiting  https://developers.facebook.com/tools/explorer/ I get a short-live token. This token expires after only 2 hours.
My goal is to obtain a long-live token.
I have created a new Facebook app and I have obtained a client-id and client-secret.
Visiting this https://graph.facebook.com/oauth/access_token?client_id=MY-CLIENT-ID&client_secret=MY-CLIENT-SECRET&grant_type=fb_exchange_token&fb_exchange_token=MY-SHORT-LIVE-TOKEN I get long-live token.
Now I can use my long-live token to publish on my page:
user = Koala::Facebook::API.new long_live_access_token
page_access_token = user.get_connections('me', 'accounts').first['access_token']
page = Koala::Facebook::API.new page_access_token
page.put_connections("me", "feed", message: "I am posting on my page!ok!")

It seems to work, but my problems is that the long-live token expires in 60 days so I need to refresh it.
I have found no solution to refresh a long-live token. It is clear that I can't repeat the entire procedure every 60 days!
Ideas?

A: From the official docs:

These tokens (long-lived) will be refreshed once per day when the
  person using your app makes a request to Facebook's servers. If no
  requests are made, the token will expire after about 60 days and the
  person will have to go through the login flow again to get a new
  token.

The token that never expires is a page token.


text:
Q: Is it possible find the probability that $\cos(\pi t)\leq 1/2$?, with $t\geq0$? If $P(\cos(\pi t)\leq 1 )=1$ and $P(\cos(\pi t)\leq -1 )=0$.
Is it possible to intuit that $\cos (t \pi)$ has a uniform distribution?, How can I find $P(\cos(\pi t)\leq 1/2)$?

A: $\cos{(t\pi)}$ is not uniformally distributed unless $t$ is distributed in a non standard way. If $t\sim U(0,1)$ for example, then $X=\cos{(t\pi)}$ is distributed such that
$$\begin{align}
P(X\le x)
&=P(\cos{(t\pi)}\le x)\\
&=P(t\le1-\frac{\arccos{(x)}}\pi)\\
&=\begin{cases}
      0 &x\lt-1\\
      1-\frac{\arccos{(x)}}\pi & -1\leq x\leq 1 \\
      1 & x\gt1
   \end{cases}\\
\end{align}$$
So the answer would be
$$P(\cos{(t\pi)}\le \frac12)=1-\frac{\arccos{(\frac12})}{\pi}=1-\frac13=\frac23$$

A: I'll obtain Peter Foreman's result in a slightly different way.
Let's split the circle in quadrants.

*

*In the first quadrant, for angles in $[0; \pi /2]$, or for $t \in [0; 1/2]$, the cosine is less than $1/2$ for $t \in [1/3; 1/2]$, since the cosine is a decreasing function in the first quadrant and $\cos \frac{\pi}{3} = \frac{1}{2}$.

*In the second quadrant, for angles in $[\pi /2; \pi]$, or for $t \in [1/2; 1]$, the cosine is negative.

*The third quadrant is like the second.

*And the fourth quadrant is like the first for $t \in [3/2; 5/3]$.
So, for the angles in $[0; 2\pi[$, i.e., for $t \in [0; 2[$, we have that $\cos (\pi t) \leq 1/2$ for $t \in [1/3; 5/3]$.
If $t$ were uniformly distributed in $[0; 2[$ the probability would be
$$\frac{\frac{5}{3} - \frac{1}{3}}{2-0} = \frac{\frac{4}{3}}{2} = \frac{2}{3} $$

Now we can expand this reasoning to an arbitrary interval.
Let $T$ be some positive number, i.e., $T>0$, and we want the probability of $\cos (\pi t) \leq 1/2$ for $t \in [0; T]$ obtained with uniform probability.
We will need two auxiliary numbers $R$ which is the largest even number less than or equal to $T$, i.e., $R = 2 \lfloor T/2 \rfloor$ and $S = T - R \in [0; 2)$. And let $C \in [0; 4/3]$ be
$$
C = \left\{
\begin{array}{ll}
 0               & \  \textrm{if} \ S \in \left[ 0; \frac{1}{3} \right] \\
 S - \frac{1}{3} & \  \textrm{if} \ S \in \left( \frac{1}{3}; \frac{5}{3} \right) \\
 \frac{4}{3}     & \  \textrm{if} \ S \in \left[ \frac{5}{3}; 2 \right)
\end{array}
\right.
$$
The probability is
$$\frac{\frac{2}{3} R + C}{T}$$
which approaches $\frac{2}{3}$ when $T \to +\infty$.


text:
Q: Error on copying subversion folder to another repository I have Project A checked into one subversion repository.
I have Project B checked into a different repository.
Not thinking, I copied several subdirectories on my local machine from Project A to Project B (some image/css/js directories).  I work on Mac OSX and the copy included the hidden subversion files.
Now when I checkin my entire Project B I get prompted for the login information for Project A.  The login always fails (since it's a different repository).  I've tried a cleanup but that didn't help.  I can't checkout a clean copy of Project B because I had files in it that weren't checked in prior to copying the new subfolders.
What are my options to fix the problem?

A: Subversion stores its information is .svn directories. In pre-1.7, these were in each folder. In 1.7 and above, they are in the root folder.  Once all the .svn files are deleted, the folder will contain absolutely no Subversion information. However, these .svn folders tend to be invisible in the Finder.
If you want to see the .svn folders in Finder, open the Terminal app, and type in the following commands:
$ defaults write com.apple.finder AppleShowAllFiles TRUE
$ killall Finder

This will restart Finder, and show you the .svn files.
If you are familiar with the command line, you can use the find command to find the folders and delete them:
$ find . -name ".svn" -type d -exec rm -rf {} \;

If you don't know Unix and BASH, you should get a good book on Unix command line commands and BASH. The Mac is a true Unix system and has all of the power of Unix. If you install the Command Line Utilities, you will get all of the most popular open source tools. I also recommend learning VIM. It's a bit archaic, but is probably the most powerful programming editor out there. And, it's a standard editor on Linux, Unix, and Mac.

*

*Learning the bash Shell 3rd edition

*Learning Unix for OS X

*Learning the VI and VIM Editors 7th Edition. This will put hair on your chest.