text:
Q: How to store value in Global variable which is coming from OnChange to my AJAX script? I am trying to store this.value user wrote in eMailTxt box in a Global Variable and then let AJAX do the checking of User exists or not.
HTML
Passing value onChange to ValidUser
<input type="text" name="eMailTxt" id="eMailTxt" onChange="ValidUser(this.value)" />

AJAX##
Checks if value exists in database through php
function ValidUser(str)
{
   //Want to declare a global variable here
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            if (xmlhttp.responseText=="false")
            {
                $("#eMailTxt").css({'background-color':'#fed3da','color':'red'});
                $("#eMailTxt").val("[User Does Not Exist]"); //Changes text if user does not exist
  //Want to store str in global variable so that in $("#eMailTxt").focus function I can store back what was written earlier
            }
            else
            {
                $("#eMailTxt").css({'background-color':'#d3fef3'});
            }
        }
    }
    xmlhttp.open("GET","loginVerify.php?q="+str,true);
    xmlhttp.send();
}

A: Add this before your function
like,
var myStr=''
function ValidUser(str)
{
   myStr=str; //Add this for assigning previous value in myStr variable
   ....

Also , if you are using ajax then use $.ajax function for this,
var myStr='';
function ValidUser(str)
{
    myStr=str;
    $.ajax({
      url:'loginVerify.php',
      type:'GET',
      data:{q:str},
      success:function(response){
          $("#eMailTxt").css({'background-color':'#fed3da','color':'red'});
          $("#eMailTxt").val("[User Does Not Exist]");
      }
    });
}

A: Try this:
var eMailTxtVal = '';

function ValidUser(str)
{
    eMailTxtVal = str;

    $.get("loginVerify.php?q=" + str, function(data) {
        if (data == "false") {
            $("#eMailTxt").css({'background-color': '#fed3da', 'color': 'red'});
            $("#eMailTxt").val("[User Does Not Exist]"); //Changes text if user does not exist
        }
        else {
            $("#eMailTxt").css({'background-color': '#d3fef3'});
        }
    });
}

$("#eMailTxt").focus(function() {
    $(this).val(eMailTxtVal);
});

A: you might need this thing. not mentioning var will make it global
myStr='';
ValidUser = function(str)
{
myStr= str;
}

A: Just declare the variable "above" the scope of any of your functions. Set it before you change it and then recall it when you need it.


text:
Q: AngularJs textbox validation, restricting characters with regex negative lookahead Using angular js here:
I have a textbox where I want to apply certain regex and prevent the user with certain characters. Here is what I want:

*

*Prevent user to start and end with an underscore.

*No Special chars allowed

*Characters and numbers are allowed and can start or end with either

*Only underscore is allowed in between chars/digits and again not at
the start or end.

*Should not have consecutive underscore.

Below is code what I have:
TextBox:
 <input type="text" name="uname" ng-model="uname" required class="form-
  control input-medium" placeholder="Enter  name..." maxlength="20" restrict-
  field="alpha-numeric" ng-trim="false" />

Directive:
.directive("restrictField", function() {
return {
  require: "ngModel",
  restrict: "A",
  link: function(scope, element, attrs, ctrl) {
    var regReplace,
      preset = {
        "alphanumeric-spl": "\\w_./s/g",
        "alphanumeric-underscore": "\\w_",
        "numeric": "0-9",
        "alpha-numeric": "\\w"
      },
      filter = preset[attrs.restrictField] || attrs.restrictField;

    ctrl.$parsers.push(function(inputValue) {
      regReplace = new RegExp('[^' + filter + ']', 'ig');

      if (inputValue == undefined) return "";
      cleanInputValue = inputValue.replace(regReplace, "");
      if (cleanInputValue != inputValue) {
        ctrl.$setViewValue(cleanInputValue);
        ctrl.$render();
      }
      return cleanInputValue;
    });
  }
   };
  });

While the above works for the simple patterns that I have used in my directives but does not work for the pattern which I have described above. From my other post I have got the pattern to use for regex negative lookahead as below:
^(?!_)(?!.*_$)[a-zA-Z0-9_]+$

But this does not work if I try to include it in my directive.
Here is my sample Codepen that I have created:https://codepen.io/anon/pen/LJBbQd
How can I apply the above regex. If not this, is there a workaround or any other approach to restrict my textbox with this regex.
Thanks

A: I suggest to allow a _ at the end, and use an HTML5 pattern attribute with a regex that requires the last char to be any char but a _ with pattern=".*[^_]". If you need to allow an empty string, use pattern="(?:.*[^_])?".

var app = angular
  .module("myApp", ["ui.bootstrap"])
  .directive("restrictField", function() {
    return {
      require: "ngModel",
      restrict: "A",
      link: function(scope, element, attrs, ctrl) {
        var regReplace,
          preset = {
            'alphanumeric-spl': '[^\\w\\s./]+', // Removes all but alnum, _ . / whitespaces
            'alphanumeric-underscore': '^_+|_+(?=_)|\\W+', // Removes all _ at start and all _ before a _ and all but alnum and _
            'numeric': '[^0-9]+', // Removes all but digits
            'alpha-numeric': '[\\W_]+' // Removes all but alnum
          },
          filter = preset[attrs.restrictField] || attrs.restrictField;

        ctrl.$parsers.push(function(inputValue) {
          console.log(filter);
          regReplace = RegExp(filter, 'ig');

          if (inputValue == undefined) return "";
          cleanInputValue = inputValue.replace(regReplace, "");
          if (cleanInputValue != inputValue) {
            ctrl.$setViewValue(cleanInputValue);
            ctrl.$render();
          }
          return cleanInputValue;
        });
      }
    };
  });

// Define the `appController` controller on the `ReportsMockUpsApp` module
app.controller("ctrl", function($scope) {});
body {
  padding: 10px
}

input:valid {
  color: black;
  border: 5px solid #dadadada;
  border-radius: 7px;
}

input:invalid {
  color: navy;
  outline: .glowing-border:focus;
  border-color: #ff1050;
  box-shadow: 0 0 10px #ff0000;
}

    Wow
    <input type="text" pattern=".*[^_]" name="uname" ng-model="uname" required class="form-control input-medium" placeholder="Enter  name..." maxlength="20" restrict-field="alphanumeric-underscore" ng-trim="false" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get the tag name of a xml file Since one tag consist of numbers and changes each time I want to read it, but this code does not work and i get an error at StrMyXml.nodeName (invalid identifier).
Currently my code is this:
Sub Create_XSD()
   Dim StrMyXml As String, MyMap As XmlMap
   Dim StrMySchema As String
   Dim tempString As String
   StrMyXml = "<Translate>"
   StrMyXml = StrMyXml & "<Alarms>"
   tempString = StrMyXml.nodeName
   StrMyXml = StrMyXml & "<" & tempString & ">"
   StrMyXml = StrMyXml & "<Nummer>tempString</Nummer>"
   StrMyXml = StrMyXml & "<Nummer Diagnosename DE>tempString & Text</Nummer Diagnosename DE>"
   StrMyXml = StrMyXml & "<Nummer Diagnosename EN>tempString & Text</Nummer Diagnosename EN>"
   StrMyXml = StrMyXml & "</" & tempString & ">"
   StrMyXml = StrMyXml & "</Alarms>"
   StrMyXml = StrMyXml & "<Alarms></Alarms>"
   StrMyXml = StrMyXml & "</Translate>"
   ' Turn off async loading.
   Application.DisplayAlerts = False
   ' Add the string to the XmlMaps collection.
   Set MyMap = ThisWorkbook.XmlMaps.Add(StrMyXml)
   Application.DisplayAlerts = True

   ' Create an empty file and output the schema.
   StrMySchema = ThisWorkbook.XmlMaps(1).Schemas(1).XML
   Open "D:\Users\F512\Desktop\MySchema.xsd" For Output As #1
   Print #1, StrMySchema
   Close #1
End Sub

Every help is appreciated!
Laurenz

A: You have dimensioned StrMyXml as a String:
Dim StrMyXml As String
But then you try:
tempString = StrMyXml.nodeName
This does not work because Strings do not have such a property.

A: You have dimensioned StrMyXml as a String:
Dim StrMyXml As String

But then you try:
tempString = StrMyXml.nodeName

This does not work because Strings do not have such a property.


text:
Q: Tuple Equivalence in python
*

*What is the definition of tuple equivalence in python?

*If two tuples have the same element regardless of order, are they equivalent tuples?

I looked in python documentation on tuples equivalence, however, it was not very clear description.
http://docs.python.org/2/tutorial/datastructures.html

A: Two tuples are equal if the items in the tuples taken in order are equal.

A: Such things are defined in the language reference, not in the tutorial.

Tuples and lists are compared lexicographically using comparison of
  corresponding elements. This means that to compare equal, each element
  must compare equal and the two sequences must be of the same type and
  have the same length.


text:
Q: Rails 3 refuses to eager load I'm working in Rails 3.0.7.
I have some many-to-many and some one-to-many associations that fail to eager load.
My associations are:
Person has_many :friends
Person has_many :locations through=> :location_histories
Location belongs_to :location_hour
Location_hour has_many :locations

In my controller I have the following:
@people = Person.includes([[:locations=>:location_hour],:friends]).where("(location_histories.current = true) AND (people.name LIKE ? OR friends.first_name LIKE ? OR friends.last_name LIKE ? OR (friends.first_name LIKE ? AND friends.last_name LIKE ?))").limit(10).all

Then in my view I have:
<% @people.each do |person| %>

    <%= link_to person.name, person %>
    <%= link_to person.friends.collect {|s| [s.full_name]}.join(", "), person.friends.first %>
    <%= link_to person.locations.current.first.name, person.locations.current.first %>

<% end %>

locations.current is a scope defined as:
scope :current, lambda {
  where("location_histories.current = ?", true)
}

This works as expected and first generates 2 database calls: one to get a list of person ids and then a big database call where everything is properly joined. THE PROBLEM is that after that there are n database calls along the lines of:
SELECT 'friends'.* from 'friends' WHERE ('friends'.person_id = 12345)

So for each iteration of the loop in the view. Needless to say this takes a while.
I thought that .all would force eager loading. Anyone have an idea what's going on here?
This spends over 3 seconds on ActiveRecord. Way too long.
I would greatly appreciate any and all suggestions.
Thanks.

A: OK. Finally Solved.
I needed to call both joins and includes. I've also had to remove the :locations_current association from the join. It was creating some chaos by attempting to
... LEFT OUTER JOIN `locations` ON `location_histories`.current = 1 ...

Which of course is not a valid association. It seems that the 'current' clause was being carried over into the JOINS.
So now I have the following, which works.
@people = Person.joins([[:locations=>:location_hour],:friends]).includes([[:locations=>:location_hour],:friends]).where("(location_histories.current = true) AND (people.name LIKE ? OR friends.first_name LIKE ? OR friends.last_name LIKE ? OR (friends.first_name LIKE ? AND friends.last_name LIKE ?))")

IN SUMMARY:
1) I needed to use both Joins and Includes for eager loading and proper interpretation of the .while() conditions
2) I needed to keep associations with conditions (i.e. :current_locations) out of the joins clause.
Please correct me if this seems like a glaring mistake to you. It seems to work though. This brings down the Active Record time to just under 1 sec.
Is it common to combine joins and includes?
Thanks!

A: I've figured out PART of the problem (though there is still some unintended behavior).
I had several scopes such as locations.current, defined as indicated above.
I have moved this logic to the association. So in my Person model I now have
has_many :current_locations, :source => :location, :through => :location_histories, :conditions => ["`location_histories`.current = ?", true]

And I call
Person.current_locations.first

instead of
Person.locations.current.first.

So now the includes do eager load as expected.
The problem is that this messed up the search. For some reason now everything seems to hang when I include a where clause. Things first get dramatically slower with each table that I add to the include and by the time I've included all the necessary tables it just hangs. No errors.
I do know this: when I add symbols to the where clause Rails does an outer join during the query (as explained here), which is what's expected. But why does this cause the whole thing to collapse?
(A minor problem here is that I need string comparisons. In order to get a proper join I call .where as
.where(:table =>{:column=> 'string'})

which is equivalent to
table.column = 'string'

in SQL but I need
table.column LIKE '%string%'

A: Oddly, for me, I get the following behavior:
# fails to eager load tags--it only loads one of the tags for me, instead of all of them.
Product.find(:all, :conditions => ["products_tags.tag_id IN (?)", 2], :include => [:tags])

but this succeeds
Product.find(:all, :conditions => ["products_tags.tag_id IN (?)", 2], :include => [:tags], :joins => [:tags])

It's like the query on the inner join table is messing up the eager loading somehow.  So your answer may be right.  But there may be something odd going on here. (Rails 2.3.8 here).


text:
Q: Does context decide a subject and an object of an infinitive phrase when it is omitted? or is there any grammar rule about this? first, sorry for my poor English and I hope you can understand what I'm asking. It seems a subject of an infinitive phrase usually appears to be the same as that of a sentence.
For example
"I went to get help and by the time I got back he had stopped breathing." from lexico
"Sadly, she didn't live to see her grandchildren" from cambridge dictionary
but there are other cases like
when a subject of a sentence is an object of an infinitive phrase and a subject of it doesn't appear in the sentence:
"The plant is relatively easy to identify." from oxford learner's dictionary
"The sauce takes 25 minutes to prepare and cook." from collins dictionary
when a subject of a sentence is not a subject or an object of an infinitive phrase:
"The show may sound like one for the tourists, but passports are not required to get a ticket at the Olympia box office." from lexico
"A lot of patience is required to look after a disabled child." from longman dictionary
" It's too hot to go for a bike ride." from longman dictionary
when an object of a sentence is a subject of an infinitive phrase:
"The same lawyers told him to bring charges to a civil court and the sports court of arbitrage." from lexico
"Do you want me to take you to the airport?" from cambridge dictionary
So what makes it happen? Am I right to understand that context decides a subject and an object of an infinitive phrase when it is omitted? or is there any grammar rule about this?

A: There are two ways of identifying the understood subject: syntactic and non-syntactic.
In the former case, the subject can be identified by looking at a linguistic antecedent that appears in some particular function in the matrix (overall) construction, such as subject or object of a preposition. In the case of non-syntactic determination the meaning depends on other factors. It may be someone or something mentioned earlier in the discourse, or perhaps it applies quite generally. Compare:

[1] Ed promised [to resign from the board].
[2] It is unwise [to go swimming straight after a meal].

In [1] Ed did the promising, he is the subject of the verb "promise", and this is enough to tell us that "Ed" is also the subject of the verb "resign".
In [2], however, there is non-syntactic determination. The meaning depends heavily on inference. The salient interpretation is that it applies quite generally: "It is unwise for anyone to go swimming straight after a meal".
Objects are generally overt, but sometimes they are missing and have to be recovered from an antecedent expression. For example:

[3] You can inspect the house in a few days time.
[4] The house will be ready [for you to inspect ___] in a few fays time.

In [3] the object of "inspect" is clearly stated as "the house". But  in [4] the object (shown as ___) is missing. However, it is recoverable from earlier in the sentence, where it is obvious that what you will be inspecting is the house.


text:
Q: Adding object to hash/array using a object's property as a key var generated_Obj= {
              id: 'unqiue',
              ....
              some other properties
            }

            var hash = {};

I would be grateful to know how to add generated_Obj to hash using generated_Obj.id as a key.
If a solution with push() method is possible I would like to learn about it either, ofcourse if there's approach that is efficent it's better
10x for your kind help :)

A: You can add things to an object (what you called a hash) using the [] operator:
hash[generatedObject.id] = generatedObject;


text:
Q: Apache Commons Lang 2 vs 3 In my application I'm using apache commons Lang v.3.
A requried library give my a
java.lang.ClassNotFoundException: org.apache.commons.lang.StringUtils

Is there a build translation between commmon.lang to commons.lang3 or I have to add both lang libraries?

A: You can have both Lang2 and Lang3 in your classpath.  Due to incompatibility of Lang2 and Lang3, the package is intentionally changed from com.apache.commons.lang to com.apache.commons.lang3 so that you can have both version in classpath without conflict


text:
Q: ¿Cómo recobrar un arreglo para usarlo en otra clase, dentro de una función en esa clase? Me gustaría saber como puedo recobrar el arreglo bidimensional cosas declarado en el código para usarlo en la función drawAgeGroup1 la cual tengo declarada en una clase diferente pero que esta dentro del mismo paquete.
En la clase de lectura se lee un archivo y voy guardando los datos en el arreglo cosas, y en la función drawAgeGroup1 quiero obtener todos los valores de cosas[i][1] para generar un contador de los niveles de edad que esta leyendo la clase lectura.
La variable r la estaría usando rutinariamente pero cambiando el indice de la fila del arreglo cosas, pero no tengo idea de como poder mandarla a llamar o usarla.
Soy nueva en esto.
Les dejo el código:
public class lectura {
    public static String leer(String nombre) {
        try {
            File f;
            FileReader lectorArchivo;
            f= new File(nombre);
            lectorArchivo = new FileReader(f);
            BufferedReader br = new BufferedReader(lectorArchivo);
            String l = "";
            String aux = "";
            int cuentolinea = 0;
            while(true) {
                aux = br.readLine();
                int numTokens = 0;
                if(aux!=null) {
                    l = l + aux;
                    StringTokenizer st = new StringTokenizer (aux);
                    while (st.hasMoreTokens()) {
                        String s2 = st.nextToken();
                        String cosas [][] = new String [1088][5];
                        cosas [cuentolinea][numTokens] = s2;
                        numTokens++;
                    }
                } else {
                    break;
                }
                cuentolinea++;
            }
            br.close();
            lectorArchivo.close();
            return l;
        } catch (IOException e) {
            System.out.println("Error:"+e.getMessage());
        }
        return null;
    }

}

y la otra clase es la siguiente:
public class SimulatorY {
private void drawAgeGroup1(){
        double r = ?? //aqui debo recobrar el cosas[i][1]
        if(r >= Pr_CHILD & r <= Pr_YOUNG){Age_Group = "young"; youngCount++;}
        else if(r > Pr_YOUNG & r <= Pr_ADULT){Age_Group = "adult"; adultCount++;}
        else{Age_Group = "old"; oldCount++;}
    }

A: cambia el tipo del método leer de String a [][] String así en lugar de hacer un return null escribe un return cosas;
public class lectura {
public static String [] [] leer(String nombre) {
    try {
        File f;
        FileReader lectorArchivo;
        f= new File(nombre);
        lectorArchivo = new FileReader(f);
        BufferedReader br = new BufferedReader(lectorArchivo);
        String l = "";
        String aux = "";
        int cuentolinea = 0;
        while(true) {
            aux = br.readLine();
            int numTokens = 0;
            if(aux!=null) {
                l = l + aux;
                StringTokenizer st = new StringTokenizer (aux);
                while (st.hasMoreTokens()) {
                    String s2 = st.nextToken();
                    String cosas [][] = new String [1088][5];
                    cosas [cuentolinea][numTokens] = s2;
                    numTokens++;
                }
            } else {
                break;
            }
            cuentolinea++;
        }
        br.close();
        lectorArchivo.close();
        return cosas;
    } catch (IOException e) {
        System.out.println("Error:"+e.getMessage());
    }
    return null;
}

y en la clase SimulatorY antes de usar el double r recibe el arreglo de la otra clase
public class SimulatorY {
private void drawAgeGroup1(){
        //aquí obtendrás la matriz cosas completa de esta manera podrás manipularla según tus necesidades
        String [][] cosas = lectura.leer(nombre)
        double r = ?? //aqui debo recobrar el cosas[i][1]
        if(r >= Pr_CHILD & r <= Pr_YOUNG){Age_Group = "young"; youngCount++;}
        else if(r > Pr_YOUNG & r <= Pr_ADULT){Age_Group = "adult"; adultCount++;}
        else{Age_Group = "old"; oldCount++;}
    }

asi de esta manera podras iterar el contenido del arreglo bidimensional y podras usarlo de acuerdo a tus necesidades, espero haber sido de ayuda. saludos.


text:
Q: How do you output an attribute using Perl and XML::Simple sub parse_xml{
    my $xml_link = $_[0];
    my $xml_content = get($xml_link) or warn "Cant get XML page of " . $xml_link . "\n";
    if(!$xml_content){
        return;
    }
    my $xml =  XML::Simple->new(KeepRoot => 1);
    my $xml_data = $xml->XMLin($xml_content);
    my @items = $xml_data->{rss}{channel}->{item};
   # print Dumper($xml_data);
    foreach my $item (@items) {
        if($item){
             print Dumper($item);             //This is the dump output
             print $item->{author};
             #print $item . "\n";
        }
    }
}

When I try to output the item's author I just get either HASH(Memory Address) or not a hash reference at ... line ...
Am I doing this incorrectly? Why is it producing this error?
Here is the dumper output.
$VAR1 = [
          {
            'link' => 'http://***.com/article/news/betty-white-credits-snickers-golden-opportunities/144290/#comments-67229',
            'author' => {},
            'title' => 'By: ',
            'pubDate' => 'Tue, 08 Jun 2010 12:47 EDT',
            'description' => 'Interesting. At least SHE remembered the product that propelled her to recent recognition. When many people I know have commented on how they loved that Betty White Super Bowl spot, they can't recall the product. Ah, advertising.'
          },
          {
            'link' => 'http://***.com/article/news/betty-white-credits-snickers-golden-opportunities/144290/#comments-67167',
            'author' => {},
            'title' => 'By: ',
            'pubDate' => 'Mon, 07 Jun 2010 13:26 EDT',
            'description' => 'Fun, fun, fun. A great attitude for all of us to take into our careers.'
          },
          {
            'link' => 'http://****.com/article/news/betty-white-credits-snickers-golden-opportunities/144290/#comments-67164',
            'author' => 'username',
            'title' => 'By: username',
            'pubDate' => 'Mon, 07 Jun 2010 12:23 EDT',
            'description' => 'Her appearance of the Comedy Central roast of William Shattner a couple of years ago was great... it seems like her willingness to be irreverent makes her more appealing to us all!

www.adverspew.com'
          },
          {
            'link' => 'http://****.com/article/news/betty-white-credits-snickers-golden-opportunities/144290/#comments-67142',
            'author' => {},
            'title' => 'By: ',
            'pubDate' => 'Mon, 07 Jun 2010 09:50 EDT',
            'description' => 'Solid interview. I will definitely be tuning into "Hot in Cleveland" next week. We ought to enjoy Ms. White's talents for as long as we have her. She's great!'
          }
        ];

A: You're very much on the right track. I've used your code on the newsfeed linked from this StackOverflow page, and adapted it very slightly.
use LWP::Simple;
use XML::Simple;
use Data::Dumper;
sub parse_xml{
    my $xml_link = $_[0];
    my $xml_content = get($xml_link) or warn "Cant get XML page of " . $xml_link . "\n";
    if(!$xml_content){
        return;
    }
    my $xml =  XML::Simple->new(KeepRoot => 1);
    my $xml_data = $xml->XMLin($xml_content,ForceArray =>'entry');
    foreach my $item ($xml_data->{'feed'}[0]->{'entry'}) {
        foreach my $entry (@{$item}){
            if($entry){
                print $entry->{'author'}[0]->{'name'}[0]."\n";
                print $entry->{'author'}[0]->{'uri'}[0]."\n";
            }
        }

    }

}
parse_xml('http://stackoverflow.com/feeds/question/10906521');

Works fine on that example. I suspect that you might be trying to print out something that isn't a plain value  -- in the example of the stackoverflow page, you can see that the 'author' actually contains some child nodes, so that if you try printing $item->{'author'} in the foreach loop you will get the 'HASH' result you describe.
Looking at your dump and Borodin's wise comment, this ought to work for you:
   my $xml_data = $xml->XMLin($xml_content,ForceArray =>'entry');
    my $item = $xml_data->{'rss'}[0]->{'channel'}[0]->{'item'};
    foreach my $entry (@{$item}){
        if($entry){
            if(!ref $entry->{'author'}[0]){
                    print $entry->{'author'}[0]."\n";
            }
            if(!ref $entry->{'description'}[0]){
                    print $entry->{'description'}[0]."\n";
            }
            if(!ref $entry->{'pubDate'}[0]){
                    print $entry->{'pubDate'}[0]."\n";
            } # etc.
        }

A: This RSS feed may or may not have <author> information for each item.
If there is no author then the element still appears in the XML but it has no content. It appears as <author></author>.
XML::Simple will represent this as an empty anonymous hash.
So, if there is author information for an item, $item->{author} will be a simple text string. Otherwise it will be a hash reference.
You can code for this by writing
foreach my $item (@items) {
  my $author = $item->{author};
  $author = '' if ref $author;
  print "$item\n";
}


text:
Q: Append multiple script tags to head that execute synchronously in React I'm trying to add multiple script tags to the head of a page in React using react-helmet. I want these scripts to execute in the order they're included, as one would normally expect in regular HTML. But it seems there is a known bug in react-helmet which makes the scripts load asynchronously and they get executed in a random order which messes up the intended use since some scripts are dependent on other ones.
Is there a way to append multiple script tags to the <head> of a page in react so they execute in order?
Here's my code:
    <Helmet>
      {isPermissionAllowed && (
        <script type="text/javascript" src={getFirstEndpoint()}></script>
      )}
      {isPermissionAllowed && (
        <script type="text/javascript">{`window.sample = "${getSample()}";`}</script>
      )}
      {isPermissionAllowed && (
        <script type="text/javascript" src={getSecondEndpoint()}></script>
      )}
      {isPermissionAllowed && (
        <script type="text/javascript">window.example.text["app.sample"] = "sample";</script>
      )}
    </Helmet>

A: You could try this way inside your app.jsx:
const script = document.createElement("script");
script.src = 'Script source';
// script.[add attributes requires to you]
document.head.appendChild(script);


text:
Q: Finding transformation to meet linearity and homoscedasticity In the picture below, what transformation on the response, just the predictor or both should be used to achieve  linearity and homoscedasticity.

they are plots of response(gestation period in weeks) vs predictor1(age of mother) and response vs predictor2(weight of mother)


text:
Q: Promise is not executing succesfully within a recursively called parent function I have the function attemptSearch() which is first ivoked and then it is supposed to call itself recursively until a certain condition is met. The code is only partially working right now.  The second console.log() is being called with each iteration, but the console.log() within the function searchForPostcodes() is only called once, during the initial invocation of attemptSearch(), which would suggest none of searchForPostcodes() code is being executed in the following iterations. Not quite sure what I'm doing wrong here.
Just for added context, I have confirmed that the Postcode.find method is functioning fine in isolation. It is a method that belongs to mongoDB->Mongoose Modal
let latMin = lat - 0.0005;
let latMax = lat + 0.0005;
let longMin = long - 0.0005;
let longMax = long + 0.0005;

const searchForPostcodes = new Promise((resolve, reject) => {
  console.log('test')
  Postcode.find({
    lat: {
      $gte: latMin,
      $lte: latMax
    },
    long: {
      $gte: longMin,
      $lte: longMax
    }
  }, (err, postcodes) => {
    if (err) {
      reject(err);
    } else {
      resolve(postcodes);
    }
  });
});
let searchAttempts = 0;

function attemptSearch() {
  latMin = latMin - 0.0005;
  latMax = latMax + 0.0005;
  longMin = longMin - 0.0005;
  longMax = longMax + 0.0005;

  searchForPostcodes
    .then(postcodes => {
      if (postcodes.length > 0) {
        res.json(postcodes);
      } else {
        if (searchAttempts < 100) {
          console.log(searchAttempts, latMin);
          searchAttempts++;
          attemptSearch();
        } else {
          res.status(400).send('No postcodes found');
        }
      }
    })
    .catch(err => {
      res.status(400).send(err);
    });
}
attemptSearch();

A: There are multiple problems here.   First off, inside of attemptSearch(), you must return the promise inside so you chain them all together.  Then, your additional calls to attemptSearch() don't actually do anything new with searchForPostcodes because that's a static promise, not a newly generated one.  You don't call your database again, you're just using the previous promise.
So, I implemented the following changes:

*

*Changed searchForPostcodes into a function that can be executed each time through the recursion.

*Switched to use the native promises in your database.

*Add return to return SearchForPostcodes().then().catch() so it's linked into the same promise chain.

*Add return to return attemptSearch() so the recursive call is linked into the same promise chain.

Here's the modified code:
let latMin = lat - 0.0005;
let latMax = lat + 0.0005;
let longMin = long - 0.0005;
let longMax = long + 0.0005;

const searchForPostcodes = function() {
    return Postcode.find({
        lat: {
            $gte: latMin,
            $lte: latMax
        },
        long: {
            $gte: longMin,
            $lte: longMax
        }
    });
}

let searchAttempts = 0;

function attemptSearch() {
    latMin = latMin - 0.0005;
    latMax = latMax + 0.0005;
    longMin = longMin - 0.0005;
    longMax = longMax + 0.0005;

    return searchForPostcodes().then(postcodes => {
        if (postcodes.length > 0) {
            res.json(postcodes);
        } else {
            if (searchAttempts < 100) {
                console.log(searchAttempts, latMin);
                searchAttempts++;
                return attemptSearch();
            } else {
                res.status(400).send('No postcodes found');
            }
        }
    }).catch(err => {
        res.status(400).send(err);
    });
}
attemptSearch();

FYI, if this were my code, I would pass the latXX variables to searchForPostcodes() as function arguments rather than make them higher scoped variables.


text:
Q: Pasting external PDF vector graphics without losing ability to export them Update: Problem persists in version 10.2 on Mac OS X 10.9.5
As in previous versions, Mathematica 9 on Mac OS X (10.7.5 here) still has a problem with pasted PDF graphics that were copied from external applications such as Preview.app or Skim.app (I usually use the latter).
To see the problem (this is only supposed to work on Mac), try the following:
Export["t.pdf", "Hello"];

SystemOpen["t.pdf"]

In the PDF viewer, activate the select tool, select all or part of the image and copy it to the clipboard (this is automatically copied in PDF format).
Now in Mathematica, type the line
Export["t1.pdf",  ];

and insert the copied PDF directly in the slot for the second argument by performing a paste from the clipboard.
Evaluate the cell and then look at the result:
First@Import["t1.pdf"]

The result is empty. One can also observe that the pasted PDF in the above example looks like it's been rasterized and is being displayed at the wrong resolution. It actually isn't rasterized, but the display looks ugly and the export of such pasted PDF simply doesn't work. To fix this, I had written the following palette some time ago:
CreatePalette[Column[{Button["Convert PDF on clipboard",
     Module[{pdf, out = "/tmp/MathematicaOutput.pdf",
       prog = "from AppKit import *\nboard=NSPasteboard.generalPasteboard()\nresult = board.dataForType_(NSPDFPboardType)\nif result:\n\tresult.writeToFile_atomically_('**FILENAME**',1)\n\" | /usr/bin/python"},
            Run["printf \"" <>
        StringReplace[prog, {"**FILENAME**" -> out}]];
      CopyToClipboard[If[FileExistsQ[out], pdf = Import[out, "PDF"];
        (*DeleteFile[out]*);
        pdf[[1]], "No PDF"]];
      ], Appearance -> "Palette"],
    "Click before pasting externally generated PDF"}],
  WindowTitle -> "Convert External PDF"];

After evaluating this, a palette is created that you have to click right after copying a PDF from an external application. If you then do the paste operation again in the following line:
Export["t2.pdf",   ];

First@Import["t2.pdf"]

$\mathtt{Hell}$

The result is the expected PDF. There is another issue related to cropping of the PDF. The above results are obtained using Skim, but when using Preview the crop box is lost and the original bounding box is used.
My question is: Is there a simpler way to get pasted PDF from external applications on Mac to display properly in the notebook and then export correctly?

A: This is a possible solution that I came up with after looking at another answer by @Ragfield: Encoding format used by GraphicsData?
I had to modify the function decodePICT in that post to cut out the leading zero bytes:
DecodePDF[data_String] :=
  Module[{slash, backslash, zero, LF, CR, decode, codes, len,
    i}, {slash, backslash, zero, LF, CR} = ToCharacterCode["/\\0\n\r"];
   decode[char_] := If[char == slash, backslash - zero, char - zero];
   len = Length[codes = ToCharacterCode[data]];
   i = 1;
   Last@Last@
     Reap@While[i <= len - 1,
       Which[codes[[i]] == LF || codes[[i]] == CR, i++,
        codes[[i]] == backslash, i += 4, True,
        Sow@BitAnd[
          BitOr[BitShiftLeft[decode[codes[[i]]], 2],
           BitShiftRight[decode[codes[[i + 1]]], 4]], 255];
        i++;
        If[i <= len - 1,
         Sow@BitAnd[
           BitOr[BitShiftLeft[decode[codes[[i]]], 4],
            BitShiftRight[decode[codes[[i + 1]]], 2]], 255]];
        i++;
        If[i <= len - 1,
         Sow@BitAnd[
           BitOr[BitShiftLeft[decode[codes[[i]]], 6],
            BitShiftRight[decode[codes[[i + 1]]], 0]], 255]];
        i += 2;]]];

convertPDF[badPDF_RawBoxes] := Module[
  {
   str = First@
     Cases[InputForm[badPDF], GraphicsData["PDF", dat_] :> dat,
      Infinity],
   out = "/tmp/MathematicaOutput.pdf"
   },
  Export[out, DecodePDF[str], "Binary"];
  First@Import[out]
  ]

Now if you type
convertPDF[   ]

and paste the externally generated PDF into the space above, then the result will be the "fixed" PDF which satisfies both requirements: it looks smooth and it can be exported as usual, with no apparent problem.
The next step is to put this into a Palette again. I'll do that after testing this approach some more (unless someone comes up with a better idea).
Edit
The above was exposition to explain what I did; you don't need to copy that code
Here is the final result: a Palette that implements the above conversion for a PDF on the clipboard. It's a drop-in replacement for the Palette I posted in the question, but it doesn't require python and it doesn't run any external commands. It's also faster than the python-based conversion:
CreatePalette[Column[{Button["Convert PDF on clipboard",
     Module[
      {
       str,
       out = "/tmp/MathematicaOutput.pdf",
       decodePDF
       },
      decodePDF[data_String] :=
       Module[{slash, backslash, zero, LF, CR, decode, codes, len,
         i}, {slash, backslash, zero, LF, CR} =
         ToCharacterCode["/\\0\n\r"];
        decode[char_] :=
         If[char == slash, backslash - zero, char - zero];
        len = Length[codes = ToCharacterCode[data]];
        i = 1;
        Last@
         Last@Reap@
           While[i <= len - 1,
            Which[codes[[i]] == LF || codes[[i]] == CR, i++,
             codes[[i]] == backslash, i += 4, True,
             Sow@BitAnd[
               BitOr[BitShiftLeft[decode[codes[[i]]], 2],
                BitShiftRight[decode[codes[[i + 1]]], 4]], 255];
             i++;

             If[i <= len - 1,
              Sow@BitAnd[
                BitOr[BitShiftLeft[decode[codes[[i]]], 4],
                 BitShiftRight[decode[codes[[i + 1]]], 2]], 255]];
             i++;

             If[i <= len - 1,
              Sow@BitAnd[
                BitOr[BitShiftLeft[decode[codes[[i]]], 6],
                 BitShiftRight[decode[codes[[i + 1]]], 0]], 255]];
             i += 2;]]];
      str = First@Append[
         Cases[NotebookGet[
                     ClipboardNotebook[]],
          GraphicsData["PDF", dat_] :> dat, Infinity], ""]
      ;
      CopyToClipboard[
       If[str =!= "",
        Export[out, decodePDF[str], "Binary"];
        First@Import[out],
        "No PDF"
        ]
       ];
      ], Appearance -> "Palette"],
    "Click before pasting externally generated PDF"}],
  WindowTitle -> "Convert External PDF"];

There are some things that don't work correctly with this PDF conversion, but that was the same in my original approach: when copying from multipage PDF documents, some color and background information can be lost. However, the main reason why PDF copy and paste on the Mac is nice (as opposed to bitmaps which are always a viable alternative) is that it produces resolution independent outlines for fonts, lines and shapes - and those properties are definitely preserved with this Palette.
Edit 2
The remaining problems mentioned above imply that this solution doesn't produce a better outcome than my original one, but this answer does run faster because it doesn't have to initialize python and the AppKit module every time.
To fix the problems that remain, I have always been using an additional intermediate step that uses ghostscript. The Mac Application for this is called FontBegone and can be downloaded from my web site. It requires ghostscript, which can be obtained conveniently as part of a $\TeX$ installation.
With this, my personal workflow for copying PDF is: highlight the desired crop area in Skim and copy. Tap the FontBegone icon, then tap the button for the Palette in this answer. Now paste into Mathematica, and you're done.
Having this ability to paste PDF into a notebook completes the circle in a workflow that is quite unique to Mac OS X. The other half of the circle is the ability to copy as PDF from Mathematica into other applications such as LyX to create $\LaTeX$ documents with vector graphics produced in Mathematica (see this answer). We can move PDF graphics around freely in both directions via the clipboard.
More discussion (currently based on my original solution) can be found here.

A: This isn't exactly what you want, but if you File > Print > Save as PDF then the content will appear correctly. It's only Export where it doesn't appear.


text:
Q: How do I tar the certain files of a directory without retaining the directory structure? I typically do :
tar czf $directory_path/file_${1}.tar.gz --directory=$specified_path/ *${1}.csv .
What if I just want to include only certain files of a directory, but not the directory itself?

A: cd [dir]; tar cz ./* >x.tgz

or
cd [dir]; tar cz file1 file2 >x.tgz


text:
Q: Get all the diagonals in a matrix(nested list) from any position in Python I'm looking a way to get all the diagonals of field 8x8, represented as a list of lists
I have the following matrix:
field = [
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0]
]

How can i diagonaly change the values of the field cells from any posytion
for example:(start position is field[3][4])
field = [
  [0, x, 0, 0, 0, 0, 0, x],
  [0, 0, x, 0, 0, 0, x, 0],
  [0, 0, 0, x, 0, x, 0, 0],
  [0, 0, 0, 0, x, 0, 0, 0],
  [0, 0, 0, x, 0, x, 0, 0],
  [0, 0, x, 0, 0, 0, x, 0],
  [0, x, 0, 0, 0, 0, 0, x],
  [x, 0, 0, 0, 0, 0, 0, 0]
]

A: I haven't tested this yet, but try this:
def change_diag(mat, x, y):
    pointer_x_less = x
    pointer_x_more = x
    pointer_y_less = y
    pointer_y_more = y

    while pointer_x_less >= 0 or pointer_x_more < len(mat[0]) or pointer_y_less >= 0 or pointer_y_more < len(mat):
        try:
            mat[pointer_x_more][pointer_y_more] = 'x'
            mat[pointer_x_more][pointer_y_less] = 'x'
            mat[pointer_x_less][pointer_y_more] = 'x'
            mat[pointer_x_less][pointer_y_less] = 'x'
        except:
            pass

        pointer_x_less -= 1
        pointer_x_more += 1
        pointer_y_less -= 1
        pointer_y_more += 1

    return mat


text:
Q: Validating `DefaultAzureCredential()` using Python SDK? What are some example methods for logging and handling exceptions using try/except and DefaultAzureCredential()?
Example:
When DefaultAzureCredential() is used in a Python Azure Function, it generates a few WARNING messages and one of the .get_token methods in the credential chain succeeds.
I want to log which one succeeded and which ones failed.
WARNING:azure.identity._internal.decorators:EnvironmentCredential.get_token failed: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.

WARNING:azure.identity._internal.decorators:ManagedIdentityCredential.get_token failed: ManagedIdentityCredential authentication unavailable, no managed identity endpoint found.

WARNING:azure.identity._internal.decorators:SharedTokenCacheCredential.get_token failed: SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.

WARNING:azure.identity._internal.decorators:VisualStudioCodeCredential.get_token failed: Failed to get Azure user details from Visual Studio Code.

And then it just succeeds, but there is no message indicating which one succeeded. In this case, running snippets in a .ipynb file in VS Code).
How do I log and handle errors when using DefaultAzureCredential() in production?
Looking for an example of something like:
try:
    credentials = DefaultAzureCredential()
    logging.info(f'<whichever>.get_token succeeded')
except Error1 as e1:
    logging.error(f'EnvironmentCredential.get_token failed: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.', e1)
except Error2 as e2:
    logging.error(f'ManagedIdentityCredential.get_token failed: ManagedIdentityCredential authentication unavailable, no managed identity endpoint found.', e2)
...<etc>

A: Just to supplement the accepted answer with some more details, let me add that DefaultAzureCredential does log this information. For example, if you enable INFO-level logging:
import logging
from azure.identity import DefaultAzureCredential

logger = logging.getLogger('azure.identity')
logger.setLevel(logging.INFO)

handler = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter('[%(levelname)s %(name)s] %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

You'll see log messages like these from DefaultAzureCredential:
[INFO] DefaultAzureCredential - EnvironmentCredential is unavailable
[INFO] DefaultAzureCredential - ManagedIdentityCredential is unavailable
[INFO] DefaultAzureCredential - SharedTokenCacheCredential is unavailable
[INFO] DefaultAzureCredential acquired a token from VisualStudioCodeCredential

You'll see the failed attempts logged only the first time the DefaultAzureCredential instance acquires a token. Once one of its constituent credentials provides a token, it uses that credential exclusively. So this particular DefaultAzureCredential will always authenticate through Visual Studio Code, and in the logs you'll see this message whenever it does so:
[INFO] DefaultAzureCredential acquired a token from VisualStudioCodeCredential

A: There are a few ways I might approach this but none are particularly pretty.  At the risk of a naive suggestion, if you want a fine-grained understanding of what worked in sequence, you could take an approach similar to what your example sketched out using the components credentials listed here:
for credential in [EnvironmentCredential, ManagedIdentityCredential, ...]:
  try:
    credentials = credential()
    # Validate credential functionality...
    logging.info('{}.get_token succeeded'.format(credential))
  except Error1 as e1:
    logging.error('{} failed due to {}'.format(credential, e1))

I suggest this because it does not seem like what you want is exposed in an easily accessible manner, looking at the ChainedCredential source here (history is built up but only used in the log message).
More "self-contained" approaches might involve creating a custom wrapper that basically does what ChainedCredential does for DefaultAzureCredential in running the list of get_token calls, but with more ability to export the success history, you could likely hack that off of the code I linked in 2 and do something directly comparable to the DefaultAzureCredential logic, but at the end of the day it's all isomorphisms of the sample above.
Don't hesitate to shout if I've misunderstood some aspect of the question or your requirements/constraints; and as always feel free to reach out if you need to get in touch with us on our github (full disclosure, am a maintainer for some of the other Python Azure SDKs)


text:
Q: Excel - Power Query - fill imported columns with formulas I have a Query in place, which imports some empty columns. I want those columns to be filled with some formulas, referencing other columns (from the same query).
I tried:

*

*"Replace Values" option, but that does not work for formulas.

*Removing the empty columns and adding them as new (non-query) columns works, but messes up the order of the columns, which needs to be the same as it is now (this is a request from the users of the file). So this was also a dead end.

*of course, I tried to enter the formula manually into the empty columns, but on refresh, the formulas were overwritten by the imported blanks (no surprise here)

Is this even possible ?

A: Power Query supports adding "Custom Columns" which are similar to adding a formula column in excel. You can add a column in any sequence you may want and also change the sequence if required.
To help with this there is also a "Create Column from Example" where you can enter a sample output in few rows and it will automatically calculate the formula for you.
Additional resources:

*

*Column from Example - with a example video

*Custom Column


text:
Q: Is a normal subgroup of a finitely presented group finitely generated or normal finitely genrated? Let $G$ be a finitely presented group and $N$ a normal subgroup. Is $N$ finitely generated or normally finitely generated? Here normally finitely generation means that for some finite set $S$ of elements in $N$, every element of $N$ can be writen as a product of $G$-conjugation of elements in $S$. Thanks.

A: If $G$ is the free group on two generators, then $N$ the commutator subgroup is not finitely generated.
If $H$ is any finitely generated, but not finitely presented group, then $H$ is the quotient of a finitely generated free group $G$, with kernel $N$ which is not normally finitely generated.
Steve


text:
Q: function not getting called in javascript. bundled by WebPack I am facing an issue with JS function. I am able to open search bar but when i try to close it. The code is not getting triggered (My first event is getting called but anything after that is not getting called/triggered)
I am using WebPack which bundle the javascript into one bundle.js file
The code
html file

          <input type="text" name="" class="search-term " id="" placeholder="What are you looking for">

js file
import $ from 'jquery';

class Search {
   constructor() {
        this.openScreen = $(".js-search-trigger");
        this.closeScreen = $(".search__close");
        this.searchOverlay = $(".search-overlay");
        this.events();
    }

    // 2. Events
    events() {
        this.openScreen.on("click", this.openOverlay.bind(this));
        this.closeScreen.on("click", this.closeOverlay.bind(this));
    }

     // 3. Methods
     openOverlay() {
         this.searchOverlay.addClass("search-overlay--active");
         $("body").addClass("body-no-scroll");
    }

    closeOverlay(){
        this.searchOverlay.removeClass("search-overlay--active");
        $("body").removeClass("body-no-scroll");
    }
  }

export default Search

A: On your code the error was the timing, probably you are doing that to fast.
What I mean is, when you call to close de overlay, i'll probably does not have the class yet.
Another theory is that you have more than one .search-overlay on the scream and the removeClass function was trying to remove a class from another element.
Try to execute the selector on console to see how much elements you select with this selector. Then, try to execute your code, step by step, on console too.


text:
Q: Asp.net webform error while building I have to work on old asp.net website project and after compiling the source code i get following error

Error  378 Cannot implicitly convert type 'PagerControl.LinkType [c:\Site1\images\en\UserControls\PagerControl.ascx.cs(174)]' to 'PagerControl.LinkType [c:\Users\user1\AppData\Local\Temp\Temporary ASP.NET Files\root\9aba16fa\a35916ab\App_Web_2ndhi1qd.dll]'. An explicit conversion exists (are you missing a cast?)  C:\Site1\images\en\UserControls\Featured-Video.ascx 33

This has a user control for Pager which works fine for ENglish Version for Arabic version it generates error while both codes are same with different class name
I am able to run this project without any issue paging working fine of related pages so not sure why this error is being generated
Code of User control

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PagerControl.ascx.cs" Inherits="AR_PagerControlArabic" %>

Codebehind
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class AR_PagerControlArabic : System.Web.UI.UserControl
{

    ///
    /// Occurs when the pager linkbutton is clicked.
    ///
    public event EventHandler PagerControl_PageIndexChanged;

    protected void Page_Load(object sender, EventArgs e)
    {
        /// since the pagination link buttons are dynamic controls we need to recreate them after postback
        if (IsPostBack)
        {
            if (PageMode == LinkType.LinkButton)
            {
                CreateLinkButtonPagination();
            }
        }
    }

    #region Public Properties

    ///
    /// Gets or sets the offset of the pagination number
    ///
    public int IndexDisplayOffset
    {
        get { return ViewState["IndexDisplayOffset"] == null ? 1 : (int)ViewState["IndexDisplayOffset"]; }
        set { ViewState["IndexDisplayOffset"] = value; }
    }

    ///
    /// Gets or sets the mode of pagination buttons to render
    ///
    public LinkType PageMode
    {
        get { return ViewState["PageMode"] == null ? LinkType.HyperLink : (LinkType)ViewState["PageMode"]; }
        set { ViewState["PageMode"] = value; }
    }

    ///
    /// Gets or sets the total number of rows in the datasource
    ///
    public int TotalItems
    {
        get { return ViewState["TotalItems"] == null ? 0 : (int)ViewState["TotalItems"]; }
        set { ViewState["TotalItems"] = value; }
    }

    ///
    /// The number of items per page. The maximum number of pages is calculated by
    /// dividing the number of items by items_per_page (rounded up, minimum 1). Default: 10
    ///
    public int PageSize
    {
        get { return ViewState["PageSize"] == null ? 10 : (int)ViewState["PageSize"]; }
        set { ViewState["PageSize"] = value; }
    }

    ///
    /// The page that is selected when the pagination is initialized. Default: 0
    ///
    public int CurrentPageIndex //made the paginator with start index from 0 and later changed to 1 - with this simple patch ;)
    {
        get { return _CurrentPageIndex + 1; }
        set { _CurrentPageIndex = value - 1; }
    }
    private int _CurrentPageIndex
    {
        get { return ViewState["CurrentPageIndex"] == null ? 0 : (int)ViewState["CurrentPageIndex"]; }
        set { ViewState["CurrentPageIndex"] = value; }
    }

    ///
    /// Maximum number of pagination links that are visible. Set to 0 to display a
    /// simple "Previous/Next"-Navigation. Default: 10
    ///
    public int DisplayEntriesCount
    {
        get { return ViewState["DisplayEntriesCount"] == null ? 10 : (int)ViewState["DisplayEntriesCount"]; }
        set { ViewState["DisplayEntriesCount"] = value; }
    }

    ///
    /// If this number is set to 1, links to the first and the last page are always shown
    /// , independent of the current position and the visibility constraints set by num_display_entries
    /// . You can set it to bigger numbers to show more links. Default is 2
    ///
    public int EdgeEntriesCount
    {
        get { return ViewState["EdgeEntriesCount"] == null ? 2 : (int)ViewState["EdgeEntriesCount"]; }
        set { ViewState["EdgeEntriesCount"] = value; }
    }

    ///
    /// Link target of the pagination links when the PageMode = HyperLink. Default: ?p=
    /// Priority goes for TargetLinkFormatString
    ///
    public string TargetLink
    {
        get { return ViewState["TargetLink"] == null ? "?p=" : ViewState["TargetLink"].ToString(); }
        set { ViewState["TargetLink"] = value; }
    }

    ///
    /// SEO friendly link target of the pagination links when the PageMode = HyperLink. Default is empty
    ///
    public string TargetLinkFormatString
    {
        get { return ViewState["TargetLinkFormat"] == null ? string.Empty : ViewState["TargetLinkFormat"].ToString(); }
        set { ViewState["TargetLinkFormat"] = value; }
    }

    ///
    /// Text for the "Previous"-link that decreases the current page number by 1.
    /// Leave blank to hide the link. Default: « prev
    ///
    public string PreviousPageText
    {
        //get { return ViewState["PreviousPageText"] == null ? "« prev" : ViewState["PreviousPageText"].ToString(); }
       // get { return ViewState["PreviousPageText"] == null ? " « " : ViewState["PreviousPageText"].ToString(); }
        get { return ViewState["PreviousPageText"] == null ? " < " : ViewState["PreviousPageText"].ToString(); }
        set { ViewState["PreviousPageText"] = value; }
    }

    ///
    /// Text for the "Next"-link that increases the current page number by 1.
    /// Leave blank to hide the link. Default: next »
    ///
    public string NextPageText
    {
        //get { return ViewState["NextPageText"] == null ? "next »" : ViewState["NextPageText"].ToString(); }
        //get { return ViewState["NextPageText"] == null ? " » " : ViewState["NextPageText"].ToString(); }
        get { return ViewState["NextPageText"] == null ? " > " : ViewState["NextPageText"].ToString(); }
        set { ViewState["NextPageText"] = value; }
    }

    ///
    /// When there is a gap between the numbers created by EdgeEntriesCount and the displayed number interval
    /// , this text will be inserted into the gap (inside a Label/span tag).
    ///
    public string EllipseText
    {
        get { return ViewState["EllipseText"] == null ? "..." : ViewState["EllipseText"].ToString(); }
        set { ViewState["EllipseText"] = value; }
    }

    ///
    /// Get or set the css class name for the pagination div. Default: 'pagination'
    ///
    public string CssClass
    {
        get { return pnlPager.Attributes["class"]; }
        set { pnlPager.Attributes["class"] = value; }
    }

    #endregion

    #region enums
    ///
    /// Specifies the types of buttons to render
    ///
    public enum LinkType
    {
        HyperLink, LinkButton
    }
    #endregion

    #region Public Functions
    ///
    /// Bind the data to a control and generate the pagination.
    ///
    /// <param name="bindControl">Type of DataList, Repeater, DataGrid or GridView</param>
    /// <param name="data">The datatable to bind</param>
    public void BindDataWithPaging(Control bindControl, DataTable data)
    {
        DataView dv = data.DefaultView;

        //saving the total items count in Viewstate for later use
        TotalItems = data.Rows.Count;

        PagedDataSource dsP = new PagedDataSource();
        dsP.AllowPaging = true;
        dsP.PageSize = PageSize;
        dsP.DataSource = dv;

        //current page index shld be set before calling this function - especially in the case of HyperLinks
        //if the current pagfe index is greater than the number of pages availanble. make the current page index as the last page
        if (_CurrentPageIndex > dsP.PageCount - 1)
            _CurrentPageIndex = dsP.PageCount - 1;
        else if (_CurrentPageIndex < 0)
            _CurrentPageIndex = 0;
        dsP.CurrentPageIndex = _CurrentPageIndex;

        //Binding data to the controls
        if (bindControl is DataList)
            ((DataList)bindControl).DataSource = dsP;
        else if (bindControl is Repeater)
            ((Repeater)bindControl).DataSource = dsP;
        else if (bindControl is DataGrid)
            ((DataGrid)bindControl).DataSource = dsP;
        else if (bindControl is GridView)
            ((GridView)bindControl).DataSource = dsP;

        bindControl.DataBind();

        CreatePagination();
    }

    ///
    /// Create the pagination as per the TotalItems available and the PageSize
    /// Call this function directly after setting TotalItems and PagSize if you want to generate the pagination without binding data to a specific control
    ///
    public void CreatePagination()
    {
        if (TotalPages() > 1)
        {
            this.Visible = true;
            if (PageMode == LinkType.HyperLink)
                CreateHyperLinkPagination();
            else
                CreateLinkButtonPagination();
        }
        else
        {
            this.Visible = false;
        }
    }

    ///
    /// Function to calculate the total number of pages depending on TotalItems and PageSize
    ///
    public int TotalPages()
    {
        return int.Parse(Math.Ceiling(decimal.Parse(TotalItems.ToString())
            / decimal.Parse(PageSize.ToString())).ToString());
    }

    #endregion

    #region CreateHyperLinkPagination
    //create the pagination as Hyperlinks
    private void CreateHyperLinkPagination()
    {
        string ellipses = "
" + EllipseText + "
";

        //this string builder will hold the pagination string and later we will add this to a div
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        //finidng the central postion of display entries. The current page will be shown in the center
        int ne_half = int.Parse(Math.Ceiling(decimal.Parse(DisplayEntriesCount.ToString()) / 2).ToString());

        //retrieving the number of pages
        int np = TotalPages();

        int upper_limit = np - DisplayEntriesCount;

        //finding the start position
        int start = _CurrentPageIndex > ne_half ? Math.Max(Math.Min(_CurrentPageIndex - ne_half, upper_limit), 0) : 0;

        //finding the end position
        int end = _CurrentPageIndex > ne_half ? Math.Min(_CurrentPageIndex + ne_half, np) : Math.Min(DisplayEntriesCount, np);

        // Begin by creating the 'Previous' Link
        if (PreviousPageText.Length > 0)
        {
            sb.Append(CreateLink(_CurrentPageIndex - 1, PreviousPageText, _CurrentPageIndex == 0 ? "disabled" : "")).Append(System.Environment.NewLine);
        }

        // Generate begining edge entries - The first EdgeEntriesCount of page links will be generated
        if (start > 0 && EdgeEntriesCount > 0)
        {
            //till where the edge entries created
            int edgeEnd = Math.Min(EdgeEntriesCount, start);
            for (int i = 0; i < edgeEnd; i++)
            {
                sb.Append(CreateLink(i, (i + 1).ToString(), "")).Append(System.Environment.NewLine);
            }
            //if there is a gap between edge entries and start,, ellipse text will be shown bw them
            if (EdgeEntriesCount < start && EllipseText.Length > 0)
            {
                sb.Append(ellipses).Append(System.Environment.NewLine);
            }
        }

        // Generate interval links - the pagination links based on DisplayEntriesCount will generated here
        //links will be printed from the calculated start and end values
        for (int i = start; i < end; i++)
        {
            sb.Append(CreateLink(i, (i + 1).ToString(), "")).Append(System.Environment.NewLine);
        }

        // Generate ending edge entries - The final EdgeEntriesCount of page links will be generated
        if (end < np && EdgeEntriesCount > 0)
        {
            //if there is a gap between end link and edge entries the EllipseText will be shown
            if (np - EdgeEntriesCount > end && EllipseText.Length > 0)
            {
                sb.Append(ellipses).Append(System.Environment.NewLine);
            }

            //from where the edge entries should start
            int begin = Math.Max(np - EdgeEntriesCount, end);
            for (int i = begin; i < np; i++)
            {
                sb.Append(CreateLink(i, (i + 1).ToString(), "")).Append(System.Environment.NewLine);
            }
        }

        // Finish the pagination with 'Next' Link
        if (NextPageText.Length > 0)
        {
            sb.Append(CreateLink(_CurrentPageIndex + 1, NextPageText, _CurrentPageIndex == end - 1 ? "disabled" : "")).Append(System.Environment.NewLine);
        }

        pnlPager.InnerHtml = sb.ToString();
    }

    // Helper function for generating a single link (or a span tag if it's the current page)
    string CreateLink(int pageNumber, string displayText, string className)
    {
        string link = "";
        //retrive total number of pages available
        int np = TotalPages();

        //if the passed value is < 0 set it as zero.. else if the passed value is greater than total pages set it as total pages - 1
        pageNumber = pageNumber < 0 ? 0 : (pageNumber < np ? pageNumber : np - 1);

        //if its the current page make it a span
        if (pageNumber == _CurrentPageIndex)
        {
            //if no class name is passed, set current as class name
            link = string.Format("
{1}
"
                , className.Length > 0 ? className : "current"
                , displayText);
        }
        else //make it as a link
        {
            if (TargetLinkFormatString.Length > 0) //if SEO friendly page target is specified - use it
            {
                link = string.Format(TargetLinkFormatString, pageNumber + IndexDisplayOffset);
                link = string.Format("
{1}
  ", link, displayText);
            }
            else
                link = string.Format("
{2}
 ", TargetLink, pageNumber + IndexDisplayOffset, displayText);

        }

        return link;
    }
    #endregion

    #region CreateLinkButtonPagination

    //create the pagination as LinkButtons
    private void CreateLinkButtonPagination()
    {
        pnlPager.Controls.Clear();

        //finidng the central postion of display entries. The current page will be shown in the center
        int ne_half = int.Parse(Math.Ceiling(decimal.Parse(DisplayEntriesCount.ToString()) / 2).ToString());

        //retrieving the number of pages
        int np = TotalPages();

        int upper_limit = np - DisplayEntriesCount;

        //finding the start position of the main pager strip
        int start = _CurrentPageIndex > ne_half ? Math.Max(Math.Min(_CurrentPageIndex - ne_half, upper_limit), 0) : 0;

        //finding the end position of the main pager strip
        int end = _CurrentPageIndex > ne_half ? Math.Min(_CurrentPageIndex + ne_half, np) : Math.Min(DisplayEntriesCount, np);

        // Begin by creating the 'Previous' Link
        if (PreviousPageText.Length > 0)
            CreateButton(_CurrentPageIndex - 1, PreviousPageText, _CurrentPageIndex == 0 ? "disabled" : "");

        // Generate begining edge entries - The first EdgeEntriesCount of page links will be generated
        if (start > 0 && EdgeEntriesCount > 0)
        {
            //till where the edge entries created
            int edgeEnd = Math.Min(EdgeEntriesCount, start);
            for (int i = 0; i < edgeEnd; i++)
            {
                CreateButton(i, (i + 1).ToString(), "");
            }
            //if there is a gap between edge entries and start,, ellipse text will be shown bw them
            if (EdgeEntriesCount < start && EllipseText.Length > 0)
            {
                CreateLabel(EllipseText, "plain");
            }
        }

        // Generate interval links - the pagination links based on DisplayEntriesCount will generated here
        //links will be printed from the calculated start and end values
        for (int i = start; i < end; i++)
        {
            CreateButton(i, (i + 1).ToString(), "");
        }

        // Generate ending edge entries - The final EdgeEntriesCount of page links will be generated
        if (end < np && EdgeEntriesCount > 0)
        {
            //if there is a gap between end link and edge entries the EllipseText will be shown
            if (np - EdgeEntriesCount > end && EllipseText.Length > 0)
            {
                CreateLabel(EllipseText, "plain");
            }

            //from where the edge entries should start
            int begin = Math.Max(np - EdgeEntriesCount, end);
            for (int i = begin; i < np; i++)
            {
                CreateButton(i, (i + 1).ToString(), "");
            }
        }

        // Finish the pagination with 'Next' Link
        if (NextPageText.Length > 0)
            CreateButton(_CurrentPageIndex + 1, NextPageText, _CurrentPageIndex == end - 1 ? "disabled" : "");

    }

    private void CreateButton(int pageNumber, string displayText, string className)
    {
        //retrive total number of pages available
        int np = TotalPages();

        //if the passed value is < 0 set it as zero.. else if the passed value is greater than total pages set it as total pages - 1
        pageNumber = pageNumber < 0 ? 0 : (pageNumber < np ? pageNumber : np - 1);

        //if its the current page make it a Label
        if (pageNumber == _CurrentPageIndex)
        {
            //if no class name is passed, set current as class name
            CreateLabel(displayText, className.Length > 0 ? className : "current");
        }
        else //make it as a linkbutton
        {
            CreateLinkButton(displayText, pageNumber);
        }
    }

    private void CreateLinkButton(string title, int index)
    {
        Literal litNewLine = new Literal();
        litNewLine.Text = System.Environment.NewLine;
        pnlPager.Controls.Add(litNewLine);

        LinkButton lnk = new LinkButton();

        if (title == PreviousPageText)
            lnk.ID = "-1";
        else if (title == NextPageText)
            lnk.ID = TotalItems.ToString();
        else
            lnk.ID = index.ToString();

        lnk.Text = title;
        lnk.CommandArgument = index.ToString();
        lnk.Click += new EventHandler(lnkPager_Click);
        HtmlGenericControl li = new HtmlGenericControl("li");
        li.Controls.Add(lnk);

        pnlPager.Controls.Add(li);
    }

    private void CreateLabel(string title, string cssClass)
    {
        Literal litNewLine = new Literal();
        litNewLine.Text = System.Environment.NewLine;
        pnlPager.Controls.Add(litNewLine);

        Label lbl = new Label();
        lbl.ID = System.Guid.NewGuid().ToString("N");
        lbl.Text = title;
        HtmlGenericControl li = new HtmlGenericControl("li");
        li.Attributes.Add("class", cssClass);
        li.Controls.Add(lbl);

        pnlPager.Controls.Add(li);
    }

    protected void lnkPager_Click(object sender, EventArgs e) //Page index changed function
    {
        LinkButton lnk = (LinkButton)sender;
        _CurrentPageIndex = int.Parse(lnk.CommandArgument);

        if (PagerControl_PageIndexChanged != null)
            PagerControl_PageIndexChanged(this, e);

    }

    #endregion
}

A: Issue was solved as i noticed the some of the USer Control files where accidentally copied into image folder also resulting in duplicate class which was creating this problem, after removing these duplicate files from image folder issue is resolved.


text:
Q: Why won't work my Javascript invites Tag Game firebase

/**
 * The Runnerscreen Page
 */

import App from '../lib/App';
import BasicTools from '../lib/basicTools';
import Firestore from '../lib/firestore';

// classes used
const basic = new BasicTools();
const firestore = new Firestore();
// zeker
const runnerscreenTemplate = require('../templates/runnerscreen.hbs');

export default () => {
  // set the title of this page (defineren pagina)
  const title = 'YOURTAG';
  const message = 'Geef  de volgende code in die je krijgt van de tagger.';

  // render the template (sure) duidelijk maken voor de hbs
  App.render(runnerscreenTemplate({
    title, message, loginbackpage: true,
  }));

  // users in lobby
  App.firebase.getAuth().onAuthStateChanged((currentUser) => {
    const code = basic.Selector('.a-runnercode');

    const joinBtn = basic.Selector('.a-button__start');

    // functie van snapshot user

    if (currentUser) {
      joinBtn.addEventListener('click', () => {
        // storage the code in the localstorage

        const codeinput = code.value;
        // localStorage.setItem('code', codeinput);
        // const code2 = localStorage.getItem('code');
        // console.log(code2);
        firestore.GetData('user').get().then((snapshot) => {
          snapshot.docs.forEach((doc) => {
            const runners = [];
            const runner = doc.data().displayName;
            runners.push(runner);
            if (currentUser.uid === doc.id) {
              firestore.UserDb(currentUser.uid).update({
                currentGame: code.value,
              });
            }

            // localStorage('profiles', JSON.stringify(runners));
          });
        });

        firestore.GetData('game').get().then((gamesnap) => {
          if (gamesnap.docs.filter((doc) => doc.id === codeinput)) {
            console.log(gamesnap.docs.filter((doc) => console.log(doc.id)));
            // console.log(codeinput);
            firestore.GetData('Gamehistory').get().then((snapshot) => {
              const gamehistory = snapshot.docs.filter((doc) => doc.gameId);

              if ((gamehistory === codeinput)) {
                // user id already existes?
                // console.log('test');
                const results = snapshot.docs.filter((doc) => doc.uid !== currentUser.uid);
                // console.log(results);
                if (results.length > 0) {
                  const games = results.filter((result) => result.gameId === codeinput);
                  console.log(games);
                  if (games.length > 0) {
                    firestore.Gamehistory().set({
                      gameId: codeinput.toString(),
                      userId: currentUser.uid,
                    });
                  } else {
                    App.router.navigate('/roomTaggerscreen');
                    console.log('game already made');
                  }
                } else {
                  firestore.Gamehistory().set({
                    gameId: codeinput.toString(),
                    userId: currentUser.uid,
                  });
                }
              }
            });
          } else {
            console.log('Game does not existes');
          }
        });
      });
    }
  });
};

I have tried already a lot you see it in my code below. But somehow my invites won't work yet. Maybe some of you have a good solution or bring me on the right track with this. It is for a school project and I have to make a tag game.  I make his self again and again even the code doesn't exist. The gamehistory database is fulfilled with the code I putted in.


text:
Q: Select last value and totalcount from joined table I made two tables in my database;

*

*todo_list

*todo_list_item
Now,
The todo_list table contains

*

*id

*name
But has childs called list items, hence the 2nd table;
This table todo_list_item contains

*

*id

*list_id

*name

*status_id
What i'm trying to achieve, is:

*

*Listing all todo_lists

*Show how many todo_list_items they contain

*Get the last status_id from the todo_list_item table, per todo_list
Can i achieve this with one join, or do i really have to join the todo_list_item table twice, to get the count of items, and the last status_id seperately?

A: You can use the following which will get the status depending on the max(id) from todo_list_item
select
td.*,
x.total,
tdi.status_id
from todo_list td
left join todo_list_item tdi on td.id = tdi.list_id
join (
 select max(id) as id ,count(*) as total, list_id from todo_list_item group by list_id
)x
on x.id = tdi.id and x.list_id = tdi.list_id


text:
Q: Conditional concatenation of a string only if a subquery was found in mysql? So I have this select statement that I am trying to make more responsive.
I'm selecting products (items table) that got hit on a website that were listed as unavailable.
I then take the name of the product hit and see if there is any similar product in the database, and subselect the info for any similarly named products, to use as suggested alternates.
My problem is that now I want to display a url for any valid alternates, by concating a standard url with the alternate product id at the end.  Unfortunately, I can't concat said url because alt_id is a field created by a subselect and doesn't exactly exist in the table itself, so I get the error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'alt_id' in 'field list'' in /blah/ on line 34

Here is the starting query, which works:
$data = query_array(
"select unavailable_item_hits.itemid, items.Name as unavail_name,

(select max(items.ItemId) from items join products on items.itemid = products.itemid join brands on items.brandcode = brands.code where items.name = unavail_name and items.flagstatus != 'U' and products.flagstatus != 'U' and brands.flagstatus != 'I' and items.ItemId !=unavailable_item_hits.ItemId) as alt_id,

 unavailable_item_hits.url as url_hit, unavailable_item_hits.marketer_tag, unavailable_item_hits.count as hit_count, unavailable_item_hits.datestatus as last_date_hit from unavailable_item_hits join items on unavailable_item_hits.ItemId = items.itemid order by alt_id is not null, hit_count desc;");

Which returns this data:
itemid  unavail_name    alt_id  url_hit     marketer_tag    hit_count   last_date_hit
7615    3602 Oxford         sb.local/product.php?ItemId=7615&ProductId=55555555555555555&ref=lsf    lsf     1   2012-02-02 18:53:37
9621    McTavish    10259   sb.local/product.php?ItemId=9621&ProductId=17246&ref=lsf    lsf     2   2012-02-02 18:53:59

Now, the part that I'd like to add is something like this:
select concat('http://example.com/products.php?ItemId=', alt_id), null) as alt_url, ...

But that doesn't work because alt_id isn't defined yet.  I don't know what to do from here, how to be able to use the data from that subselect in the final result.  Maybe the only way is to do two different selects or something, but that will mean pulling the data out into an array in memory and then performing the subselect, which I'd like to avoid.  Or maybe I have to perform the subselect again on the field that I want to manipulate like a string?
So any suggestions on clean ways to manipulate the results of a subselect?

A: First, I wouldn't bother the database server with things like string concatenation. Just append the alt_id to your url in the host language (PHP). Databases are good in storing and fetching large amounts of data, not calculating or string manipulation.
If you really need to do this in the database, you can just repeat the subquery for your concat-call like
select
    [...]
    concat('http://example.com/products.php?ItemId=', (select
        max(items.ItemId)
     from items
     join products on items.itemid = products.itemid
     join brands on items.brandcode = brands.code
     where
        items.name = unavail_name
        and items.flagstatus != 'U'
        and products.flagstatus != 'U'
        and brands.flagstatus != 'I'
        and items.ItemId !=unavailable_item_hits.ItemId)) as alt_url
     [...]

It's not a pretty query but that doesn't really matter to the database server. SQL is a declarative language. You just specify what you want to have not how it should be produced. MySQL will (hopefully) see the repeated subquery and only execute it once for every tuple, or, even better, transform it into some join.


text:
Q: Create date with 15th of month from Month name in Excel I have the month names in the A - column, like "January" in cell A1.
Furthermore I have the year in the B - column like "2019" in cell B1.
How can I now create a formula to get a result of 15/1/2019 for each row in the C - column?
Thank you in advance
A

A: Use DATEVALUE() and CONCATENATE the date:
=DATEVALUE("15"&A1&B1)

Then format as desired:

We can leave off the "" and use -- instead of DATEVALUE: =--(15&A1&B1)


text:
Q: C# - Complex variable-assignment i have a class Row.
This class should have a Content-property. Currently the content is of type: List<IRowContent>
(IRowContent is a interface)
Other classes Column and TextContent, ImageContent implements the interface IRowContent.
I can add now some Columns to the list or real "content" (Text or a image).
But you can also add columns and text/image. But if a row contains text/image it should not contain another item.
How can i design my class-structure to support this?
Edit: some additionals infos:
I want to build a layout with "fluent interfaces" http://en.wikipedia.org/wiki/Fluent_interface
And my idee is to prevent wrong use by intellisense of VisualStudio.
Here my classes:
The Layout have a column-list.
class Layout
   {
      //Attributes
      public Color Background { get; set; }
      public List<Column> Columns { get; set; }
      public uint Margin { get; set; }

      public Layout AddColumn(Column c)
      {
         return null;
      }

      public Layout SetColumnList(List<Column> c)
      {
         return null;
      }
   }

The column has a list of content (IColumnContent). The column itself is from IRowContent.
class Column : IRowContent
   {
      public List<IColumnContent> Content { get; private set; }

      public Column AddToContent(IColumnContent obj)
      {
         return null;
      }

      public Column SetContent(List<IColumnContent> objs)
      {
         return null;
      }
   }

Same for Row with IRowContent:
   class Row : IColumnContent
   {
      public List<IRowContent> Content { get; private set; }

      //...
   }

ImageContent and TextContent implements both interfaces:
class TextContent : IRowContent, IColumnContent

class ImageContent : IRowContent, IColumnContent

A: If you declare the interface
interface IRowContent
{
    bool SupportsOtherChildren{ get; }
    ...
}

class ImageContent : IRowContent
{
    public bool SupportsOtherChildren
    {
        get { return false; }
    }
}

class Column : IRowContent
{
    public bool SupportsOtherChildren
    {
        get { return true; }
    }
}

You can override a collection's insert and remove methods to support this behavior:
 class RowContentCollection : Collection<IRowContent>
    {
        bool containsSingleItem = false;
        protected override void InsertItem(int index, IRowContent item)
        {
            if (containsSingleItem)
                throw new InvalidOperationException("Collection contains an item that doesnt allow other items.");

            containsSingleItem = !item.SupportsOtherChildren;

            base.InsertItem(index, item);
        }

        protected override void RemoveItem(int index)
        {
            if (!this[index].SupportsOtherChildren)
                containsSingleItem = false;

            base.RemoveItem(index);
        }
    }

A: Just to summarize and to make sure I understand you correctly:
The Row class should contain a list of columns. Every column can be an object of type Column, TextContent or ImageContent. All three of these classes implement the RowContent interface (which in my opinion should be named IColumnContent...).
If that is correct, the restriction you're trying to impose (which I don't fully understand, to be honest) is not a matter of class design, but a matter of add/remove logic. I'd declare the Content property as
private List<RowContent> m_internalColumns;

public RowContent[] Columns { get { return m_internalColumns.ToArray(); }}

and create Add and Remove methods like the following (pseudo-code):
public void Add(RowContent column)
{
    if (adding column of type <typeof(column)> is allowed)
        m_internalColumns.Add(column);
}

public void Remove(RowContent column)
{
    m_internalColumns.Remove(column);
}

A: You could make your Row class generic:
class Row<T : IRowContent> {
    public List<T> Content { ... }
}

Then you can have a Row<Column>, which can only contain columns, or a Row<TextContent>, which can contain only text content. You can even have a Row<IRowContent> which allows for mixed content.
If you want a row that can only contain text and image content (but no columns), add an interfance IRealContent : IRowContent and have TextContent  and ImageContent implement IRealContent. Then, a Row<IRealContent> can only contain text and images.

A: Abstract the details about the problem to the interface itself.
public interface IRowContent
{
      bool SupportsChildren { get; }

      // other properties
}

I would also introduce custom Add and Remove methods to the Row class that determine if the content being added can support additional content.

A: I would probably do one of 2 things. Either:
Instead of using Row.Content.Add() to add items, add a method to Row for adding content. Row.AddContent(iRowContent content); and put your 'logic' in that method for determining if whatever item can be added or not.
Or, instead of using a List, implement your own collection that inplements IList and write the Add() method in a way that contains your logic.


text:
Q: How to set Cron Job using phpseclib?         set_include_path(get_include_path() . PATH_SEPARATOR . 'C:\wamp\www\Web Apps\backend\phpsec');
        include ('phpsec/Net/SSH2.php');
        $ssh = new Net_SSH2('www.example.com');
        if (!($ssh->login('userlogin', 'password'))) {
            exit('Login Failed');
        }

        echo "Login Success<br>";

        $output=$ssh->exec('crontab -e;30 17 * * 1 /path/to/command')

        echo "$output";

Here I am trying to set cron job. But it gives following error "Error opening terminal: unknown. /usr/bin/crontab.cagefs: "pico" exited with status 1 bash: 30: command not found" So how to set cron job using phpseclib?

A: Write the following command in exec() function
  $ssh->exec('crontab -l | { cat; echo "* * * * * /path/to/command/"; } | crontab -');


text:
Q: Python - Getting user data using regex So, I'm still a newbie with regex and python. I've been searching for some time but don't know how to ask what I'm looking for.
I need to get data from a formatted string into a list of lists, or dictionary.
-------------------------------------------------------------------
Frank         114      0         0         0          0         114
Joe           49       1         0         0          0         50
Bob           37       0         0         0          0         37
Sally         34       2         0         0          0         36

This is the output of a script. Currently I have:
match_list = []
match = re.search('\n(\w+)\s+(\d*)\s+(\d*)', output)
  if match:
    match_list.append([match.group(1),
                       match.group(2),
                       match.group(3)])
>>>print match_list
[['frank', '114', '0']]

This is perfect, except that I need to have match_list return:
[['frank', '114', '0'],
 ['Joe', '49', '1'],
 ['Bob', '37', '0'],
 ['Sally', '34', '2']]

My initial thought was to for loop, and check if the match.group(1) was already listed, and if so move to the next, but then I realized I didn't know how to do that.  But there you have it. I am having a hard time figuring this out. Any help would be fantastic!  :)
Oh also. The list size changes. Sometimes there may only be one user, other times there may be 20 users. So I can just set up a giant static regex. (that I know of...)

A: You can use re.findall:
match_list = []
match = re.findall('\n(\w+)\s+(\d*)\s+(\d*)', output)
for k in match:
    #k will be a tuple like this: ('frank', '114', '0')
    match_list.append(list(k))

or
Same solution as an oneliner:
match_list = map(list, re.findall('\n(\w+)\s+(\d*)\s+(\d*)', output))

A: You don't need a regex:
table="""\
-------------------------------------------------------------------
Frank         114      0         0         0          0         114
Joe           49       1         0         0          0         50
Bob           37       0         0         0          0         37
Sally         34       2         0         0          0         36"""

print [line.split() for line in table.splitlines()[1:]]

Or, if you want a regex:
print [list(t) for t in re.findall(r'^(\w+)'+r'\s+(\d+)'*6,table,re.MULTILINE)]

Either case, prints:
[['Frank', '114', '0', '0', '0', '0', '114'],
 ['Joe', '49', '1', '0', '0', '0', '50'],
 ['Bob', '37', '0', '0', '0', '0', '37'],
 ['Sally', '34', '2', '0', '0', '0', '36']]


text:
Q: Removing panels from an array I have created a 10 by 10 array of Jpanels and I have to remove a square from them. The square that is clicked must be removed and so do all of the squares below it and to the right of it.
currently, when I click a square it only deletes one square.
http://imgur.com/a/6wZYA - this is what the grid looks like and then the desired outcome.
Attached below is the code I am currently using. any help is welcome. Please let me know if I need to attach any more code, thank you.
    for (int x = 0; x < 10; x++) {
        playingGrid[x] = new JPanel[10];
        for (int y = 0; y < 10; y++) {
            playingGrid[x][y] = new JPanel();
            playingGrid[x][y]= new ImagePanel(Toolkit.getDefaultToolkit()
                                  .getImage("rock.jpg"));
            pcenter.add(playingGrid[x][y]);
            playingGrid[x][y].addMouseListener(new Rockbreaker());
        }

    }
    f.getContentPane().add(pcenter, BorderLayout.CENTER);

}
public class Rockbreaker implements MouseListener{

    public void mouseClicked(MouseEvent e) {
         //sets all columns greater than one clicked to invisible
        for (int x = 0; x < 10; x++) {
            for (int y = 0; y < 10; y++) {
                if(playingGrid[x][y]== e.getSource()){
                        for (int c=0;c<100;c++){
                            if(c>x){
                                playingGrid[x][y].setVisible(false);
                            }
                        }

A: There is a flaw on your logic. I'm not sure what you were trying to do in the if (c>x) block, but you could easily rewrite it to
public void mouseClicked(MouseEvent e) {
    int selectedX = -1;
    int selectedY = -1;
    for (int x = 0; x < 10; x++) {
        for (int y = 0; y < 10; y++) {
            if(playingGrid[x][y]== e.getSource()){
                playingGrid[x][y].setVisible(false);
                selectedX = x;
                selectedY = y;
            } else if (selectedX > 0 && selectedY > 0 && selectedX <= x && selectedY <= y) {
                playingGrid[x][y].setVisible(false);
            }
        }
    }
}


text:
Q: Adding certificates to Azure VM Scale Set Basically I'm trying to follow this guide..
http://ronaldwildenberg.com/custom-domain-name-and-certificate-for-your-azure-service-fabric-cluster/
It says here (regarding Resource Explorer):

If you save (PUT) the updated VM Scale Set resource description, the certificate will be installed to all VMs in the scale set.

I've done this (adding my new cert to the key vault, then referencing it in the template), upon saving, the portal says provisioning, and completes, but rdp'ing into the VM's the certificate isn't there! And thus my service fails (error given in event viewer is HttpCertCfg returned errorcode 0x80070520)
What's going wrong? :(

A: Here's a walkthrough on MSDN. It deploys a secondary cert, then swaps.


text:
Q: Why don't arrow keys work with Sweetalert2? I made an alert box using Sweetalert2, however the arrow keys do not work. I want to be able to use the arrow keys to choose between yes and no. It works on the site using their demos, but not with my code. Here is the snippet:

    Swal.fire({
    width: '32rem',
  title: ' Incoming Call!',
  text: "Take it?",
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes',
  cancelButtonText: 'No'
}).then((result) => {
  if (result.isConfirmed) {

  }
})
<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8">
    <!-- <meta name="viewport" content="width=1980, height=1080"> -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Title</title>

    <script
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.0/dist/sweetalert2.all.min.js"></script>

Fixed it :
Changed the CancelButton to DenyButton. For some weird reason it works with Deny button but not with the cancel button.

A: This was actually a bug in the library and I fixed it in the latest release: https://github.com/sweetalert2/sweetalert2/releases/tag/v11.4.2
Please update your dependency and arrow keys will work properly with Confirm and Cancel buttons.


text:
Q: Why does a thermocouple have two outputs (V+ and V-)?
Does that mean that there is two different voltages?
The potential is used to determine the temperature. (?)
I understand it's the seebeck effect  dictates how the thermocouple works.
Apologies if I'm missing a simple concept.
I have had no experience with thermcouples prior to my current thermopile project.
Thanks!

A: ALL voltage sources have at least two terminals.
Voltage is ALWAYS specified relative to some reference value (often "ground").
The concept of a single terminal voltage source makes no sense.
So, a thermocouple is a voltage source with an output voltage measured on one lead relative to the other lead.

A: Really there is only one output, which is the voltage difference between the two terminals (V+, V-). The V- is used as the reference going into the multimeter/circuitry. On your diagram, Tv is simply V+ minus V-. In other terms, you don't measure the voltage referenced to ground, something you'd normally do for a power supply or amplifier output.
Yes the voltage difference is used to determine the relative temperature. Be warned that the voltage difference may be quite small (uV - mV range), so if you have a cheap multimeter you will likely need to amplify the voltage with an instrumentation amplifier.
Here is a quick reading:
https://www.analog.com/en/analog-dialogue/articles/measuring-temp-using-thermocouples.html

A: It's effectively a voltage source, a bit like a battery (given fixed thermal conditions). So, of course, it has two terminals.
The potential between the two terminals, measured at the meter, is a nonlinear function of the temperatures at Th and the temperature at T0, so if you want the temperature at Th you must measure the temperature at T0 using some method other than a thermocouple (or, as they did in the days of yore, place the two junctions at T0 in an ice-water slurry to control the temperature at 0°C).
Very roughly, the voltage output is proportional to the temperature difference between Th and T0. To get a more accurate measurement you can calculate the thermocouple voltage equivalent to the temperature T0 if it was compared to a reference junction of, say 0°C, and then add that voltage to the measured voltage at the meter to get a new voltage, then find the temperature corresponding to that voltage with a 0°C reference junction (if T0 was 0°C rather than whatever it really is). If T0 happens to be 0°C (perhaps due to that ice-water bath)  the voltage will be 0uV.


text:
Q: How do planets prevent a Gravity-type event? Lots of things blow up near planets in Star Wars (Coruscant in Episode III being an obvious example). Why doesn't this end up more like the movie Gravity?

A: In Star Wars, Millennium Falcon emerged from hyperspace in the middle of the shattered remains of an entire planet, Alderaan, which the Death Star had just obliterated.  Other than a few bumps similar to turbulence on an airliner, the Falcon's passengers were unmussed.  So while orbits may well be full of debris, the standard shield technology is good enough that no one has to worry about it.


text:
Q: Add an extra point to a single facet in ggplot I want to add a single point to only one facet. I tried to set the group in geom_point:
ggplot(data=mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~class) + geom_point(aes(x=5, y=25, group = "pickup"), colour="blue")

But that put a blue dot in all facets. Is there any way to constrain the point to only one?

A: You could achieve your desired result by putting the information for your point in a dataframe which you pass to the data argument of your second geom_point:
library(ggplot2)

ggplot(data=mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~class) +
  geom_point(data = data.frame(displ = 5, hwy = 25, class = "pickup"), colour="blue")


text:
Q: How to use ColdFusion MySQL 5 spy log? I dumped the output of getDatasources() from cfide.adminapi.datasource component and I see two keys:
<cfscript>

isLoggedIn=createObject("component", "cfide.adminapi.administrator").login("x");
datasourceAPI=createObject("component","cfide.adminapi.datasource");

datasource = datasourceAPI.getDatasources(
        dsnname = 'mydsn'
    );

writedump(datasource);

</cfscript>

spylogfile=""
and
usespylog=false
Are they JDBC driver variable that coldfusion uses for MySQL5? How can I use them?
I can't find any documentation info for the usage. I tried usespylog=true and provided a full path for spylogfile="/tmp/test_spylog.log"
No file was created. Can anyone shed some light on this? seems interesting. Might be useful for debugging.


text:
Q: Is there a good way to build a DIY LCD KVM? I've wondered for some time whether it would be possible to build an LCD KVM. My server room has two KVM switches with CRTs, and I really don't want to shell out $1000+ on one of the nice 1U rackmount pull-out KVMs just for a bit more rack space. Is there any to use a laptop, or something similar to build a 1U rackmount KVM?

A: By the time you pay for a laptop, a multi-port KVM and a drawer you're at least 3/4 of the way (if not 100%) to the cost of a ready-to-use unit.

A: Use a laptop and add a Startech USB Crash Cart to provide KVM functionality.


text:
Q: What is the benefit of mongodb connection pooling in a single-threaded environment like node? Given a scenario with a single node process connecting to a single mongodb server, is there a reason to use connection pooling over a single persistent connection?
From what I understand, connection pooling is done so as to not create new connections all the time as well as to spread out the load with multiple operations. But if a single persistent connection works, and node is a single-threaded runtime by design, whats the point in having the default (5 connection) pool?
There's no more processing that can be done since its single-threaded. And the logic in the mongodb driver is able to multiplex multiple ongoing database operations on a single connection so it can't be that.
There must be some case that I'm missing that would warrant the use of multiple connections in a single-threaded environment. Is there some node-specific networking logic that I'm unaware of? Does it help out the database if there are more connections?
Edit:
The "duplicate" Q/As do not answer my question. I'm all too aware of the nodejs event loop and the answers to the other only address how to set up pooling and advocate against remaking connections, which my question isn't about. My question is, put more simply: why is 5 connections better than 1?