text:
Q: Promise returns undefined despite receiving valid data 'use strict';

let mongodb = require('mongodb')
let mongoose = require('mongoose')
const fetch = require("node-fetch");

module.exports = function (app) {

  mongoose.connect(process.env.DB, { useNewUrlParser: true, useUnifiedTopology: true })

  let stockSchema = new mongoose.Schema({
    name: { type: String, required: true},
    likes: { type: Number, default: 0},
    ips: [String]
  })

  let Stock = mongoose.model('Stock', stockSchema)

  app.route('/api/stock-prices')
    .get(function (req, res){

      let responseObject = {}

      let getPrice = (stock) => {
        let api = `https://stock-price-checker-proxy.freecodecamp.rocks/v1/stock/${stock}/quote`
        return fetch(api)
          .then(response => response.json())
          .then(data => {
            return data['latestPrice']
          })
      }

      let findStock = (stock) => {
        return Stock.findOne({name: stock}, (err, stockDoc) => {
          if (!err && stockDoc){
            return stockDoc
          }
        })
      }

      let findStockAndUpdate = (stock, update) => {
        return Stock.findOneAndUpdate({name: stock}, update, {new: true, upsert: true}, (err, updatedStock) => {
          if (!err && updatedStock){
            return updatedStock
          }
        })
      }

      let assign = (stockData, total_stock_num) => {
        if (total_stock_num === 1){
          responseObject['stockData'] = stockData
        } else {
          if (!responseObject['stockData']){
            responseObject['stockData'] = []
          }
          responseObject['stockData'].push(stockData)
        }
        return responseObject
      }

      let buildResponse = (stock_name, total_stock_num, like_bool) => {
        return findStock(stock_name).then(stockDoc => {
          let stockData = {}
          // if stock was liked
          if (like_bool){
            // if stock is found in DB and IP hasn't already liked stock
            if (!stockDoc || !stockDoc['ips'].includes(req.ip)){
              let update = { $inc: {likes: 1}, $push: {ips: req.ip} }
              findStockAndUpdate(stock_name, update).then(updatedStock => {
                getPrice(stock_name).then(price => {
                  stockData['stock'] = updatedStock['name']
                  stockData['price'] = price
                  stockData['likes'] = updatedStock['likes']
                  return assign(stockData, total_stock_num)
                })
              })
            }
          }
          // if stock wasn't liked, or IP has already liked stock
          if (!like_bool || (stockDoc && stockDoc['ips'].includes(req.ip))){
            getPrice(stock_name).then(price => {
              stockData['stock'] = stock_name
              stockData['price'] = price
              stockData['likes'] = stockDoc ? stockDoc['likes'] : 0
              return assign(stockData, total_stock_num)
            })
          }
        })
      }

      // if string, then only one stock was submitted
      if (typeof (req.query.stock) === 'string'){
        buildResponse(req.query.stock, 1, req.query.like).then(data => {
          console.log(data) // returns undefined
        })
      // if array, both stocks were submitted
      } else if (Array.isArray(req.query.stock)){
        let stockArr = req.query.stock

        buildResponse(stockArr[0], 2, req.query.like)
        buildResponse(stockArr[1], 2, req.query.like)
      }
    });

};

Hi everyone,
Would anyone be able to explain to me why my console.log returns "undefined" instead of the object that was received from the buildResponse() function? If I log "assign(stockData, total_stock_num)" to the console from within the buildResponse() function, the response object appears fine, but it seems to get lost when I return it from buildResponse() to access it in the main part of my code.


text:
Q: List View / Details View without Entity Framework I have a MVC view that has a table that contains a list of all users within a specific OU within Active Directory. I am trying to add a column to the table that takes you to a Details view that shows the details of the user (shows additional details) but I am having a hard time figuring out how to do this without using Entity Framework and passing the id of the object to the details view. Any thoughts on how I could accomplish this? Right now when I click on the Details actionlink, I am taken to the Details view but there is no data being passed. Any help would be greatly appreciated!
public ActionResult NonComputerUsers(User model)
    {

        List<User> user = new List<User>();

        using (var context = new PrincipalContext(ContextType.Domain, "XXX", "OU=XXX,DC=XXX,DC=com"))
        {
            using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
            {
                foreach (var result in searcher.FindAll())
                {
                    DirectoryEntry entry = result.GetUnderlyingObject() as DirectoryEntry;
                    user.Add(new User()
                    {
                        FirstName = (String)entry.Properties["givenName"].Value,
                        LastName = (String)entry.Properties["sn"].Value,
                    });
                }
            }
        }

        return View(user.ToList());
    }

 public ActionResult Details(User model)
    {
        ?????????

        return View(model);
    }

**List View**
@model ADUserManagement.Models.User

        First Name

        Last Name

@foreach (var item in Model)
{

            @Html.DisplayFor(modelItem => item.FirstName)

            @Html.DisplayFor(modelItem => item.LastName)

           @Html.ActionLink("Details", "Details", "Users", new { item = item.FirstName })

    }

**Details View**
@model ADUserManagement.Models.User

@{
ViewBag.Title = "Details";
}

Details

    First Name
    @Model.FirstName

    Last Name
    @Model.LastName

    SAM Account Name
    @Model.SamAccountName

A: There are a couple ways to do this. One of which is the way you are already doing it. You can add all the properties you want to display on your details page to your User model. Use that list to build your table, then pass the applicable User object back to your Details view to display the extra details.
That method is good because it saves you having to do a second lookup to AD for your Details view (essentially, your ????????? can be removed - you don't need any code there).
I was going to say that the down side is that, in your search, you're asking for more details for most of the accounts than you'd actually use, but the UserPrincipal objects that PrincipalSearcher returns already pulls in all the AD attributes for each user account anyway. If you used DirectorySearcher directly, you'd have more control of that. But that's probably not a big deal, unless you have performance problems with that search.
The other way to do it, which I think is unnecessary in your current example, is to store some unique identifier from AD (e.g. distinguishedName, sAMAccountName, userPrincipalName, objectGuid, objectSid) and pass just that back to your Details action where you can look up just that account again and get all the details you need for your Details view.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multi-Line Visual Studio conditional prebuild event returns 255 I've been running a prebuild event every time I do a build. It works perfectly:
"$(MSBuildProjectDirectory)\..\..\..\Tools\SubWCRev\SubWCRev" "$(MSBuildProjectDirectory)\..\..\.." "$(MSBuildProjectDirectory)\Utilities\Revision\Revision.txt" "$(MSBuildProjectDirectory)\Utilities\Revision\Revision.cs"

Now I'd like it to be only done if not DEBUG
if $(ConfigurationName) != Debug (
"$(MSBuildProjectDirectory)\..\..\..\Tools\SubWCRev\SubWCRev" "$(MSBuildProjectDirectory)\..\..\.." "$(MSBuildProjectDirectory)\Utilities\Revision\Revision.txt" "$(MSBuildProjectDirectory)\Utilities\Revision\Revision.cs"
)

But, VS2010 is telling me it exited with code 255. I can't figure out what that code means or why I'm having an issue.
I've tried adding double quotes around $(ConfigurationName) and Debug, tried playing around with new lines, etc, and even checking to see if it was Debug and doing exit0.
It seems my If is being ignored or trashed. How can I get this to run only if Non-Debug?


text:
Q: Monit can't detect MySQL The Monit webinterfcae is showing: Execution failed | Does not exist
netstat is giving me:
sudo netstat -lnp | grep mysql
tcp        0      0 127.0.0.1:33060         0.0.0.0:*               LISTEN      4643/mysqld
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      4643/mysqld
unix  2      [ ACC ]     STREAM     LISTENING     90220    4643/mysqld          /var/run/mysqld/mysqlx.sock
unix  2      [ ACC ]     STREAM     LISTENING     90222    4643/mysqld          /var/run/mysqld/mysqld.sock

And monit -v (if this helps):
Process Name          = mysqld
 Group                = mysql, database
 Pid file             = /var/run/mysqld/mysqld.pid
 Monitoring mode      = active
 On reboot            = start
 Start program        = '/etc/init.d/mysql start' timeout 30 s
 Stop program         = '/etc/init.d/mysql stop' timeout 30 s
 Existence            = if does not exist then restart
 Depends on Service   = mysql_rc
 Depends on Service   = mysql_bin
 Port                 = if failed [localhost]:3306 type TCP/IP protocol MYSQL with timeout 15 s for 3 times within 4 cycles then restart
 Unix Socket          = if failed /var/run/mysqld/mysqld.sock type TCP protocol MYSQL with timeout 5 s for 3 times within 4 cycles then restart
 Timeout              = If restarted 5 times within 5 cycle(s) then unmonitor

File Name             = mysql_bin
 Group                = mysql
 Path                 = /usr/sbin/mysqld
 Monitoring mode      = active
 On reboot            = start
 Existence            = if does not exist then restart
 Checksum             = if failed defc97a98deb37905c97d9b5a09f9f13(MD5) then unmonitor
 Permission           = if failed 0755 then unmonitor
 UID                  = if failed 0 then unmonitor
 GID                  = if failed 0 then unmonitor

File Name             = mysql_rc
 Group                = mysql
 Path                 = /etc/init.d/mysql
 Monitoring mode      = active
 On reboot            = start
 Existence            = if does not exist then restart
 Checksum             = if failed 89a1a5b6ad710389112802fc3fbb81e1(MD5) then unmonitor
 Permission           = if failed 0755 then unmonitor
 UID                  = if failed 0 then unmonitor
 GID                  = if failed 0 then unmonitor

So even if mysql is running and active Monit can't detect it. I set the symlink with:
sudo ln -s /etc/monit/conf-available/mysql /etc/monit/conf-enabled/
Using Ubuntu 20.04
EDIT :
monit status:
Process 'mysqld'
  status                       Not monitored
  monitoring status            Not monitored
  monitoring mode              active
  on reboot                    start
  data collected               Sun, 20 Dec 2020 00:00:29

File 'mysql_bin'
  status                       OK
  monitoring status            Monitored
  monitoring mode              active
  on reboot                    start
  permission                   755
  uid                          0
  gid                          0
  size                         63.7 MB
  access timestamp             Mon, 21 Dec 2020 11:53:36
  change timestamp             Thu, 17 Dec 2020 11:52:00
  modify timestamp             Thu, 26 Nov 2020 12:03:42
  checksum                     defc97a98deb37905c97d9b5a09f9f13 (MD5)
  data collected               Mon, 21 Dec 2020 16:32:35

File 'mysql_rc'
  status                       OK
  monitoring status            Monitored
  monitoring mode              active
  on reboot                    start
  permission                   755
  uid                          0
  gid                          0
  size                         5.5 kB
  access timestamp             Mon, 21 Dec 2020 11:53:37
  change timestamp             Thu, 17 Dec 2020 11:52:05
  modify timestamp             Wed, 06 Nov 2019 18:34:43
  checksum                     89a1a5b6ad710389112802fc3fbb81e1 (MD5)
  data collected               Mon, 21 Dec 2020 16:32:35

The monit logs show as follows, nothing irregular to me. Ignore the mail error:
[UTC Dec 21 16:37:10] info     : 'apache' monitor on user request
[UTC Dec 21 16:37:10] info     : 'mysqld' monitor on user request
[UTC Dec 21 16:37:10] info     : 'nginx' monitor on user request
[UTC Dec 21 16:37:10] info     : 'inf-education-67' monitor on user request
[UTC Dec 21 16:37:10] info     : 'apache_rc' monitor on user request
[UTC Dec 21 16:37:10] info     : 'apache_bin' monitor on user request
[UTC Dec 21 16:37:10] info     : 'mysql_rc' monitor on user request
[UTC Dec 21 16:37:10] info     : 'mysql_bin' monitor on user request
[UTC Dec 21 16:37:10] info     : 'nginx_rc' monitor on user request
[UTC Dec 21 16:37:10] info     : 'nginx_bin' monitor on user request
[UTC Dec 21 16:37:10] info     : Monit daemon with PID 900 awakened
[UTC Dec 21 16:37:10] info     : Awakened by User defined signal 1
[UTC Dec 21 16:37:10] error    : Mail: Mailserver response error -- 535-5.7.8 Username and Password not accepted. Learn more at
[UTC Dec 21 16:37:10] error    : SMTP: Mailserver response error -- 535 5.7.8  https://support.google.com/mail/?p=BadCredentials f77sm22188901wmf.42 - gsmtp
[UTC Dec 21 16:37:10] error    : Alert handler failed, retry scheduled for next cycle
[UTC Dec 21 16:37:10] info     : 'nginx_bin' monitor action done
[UTC Dec 21 16:37:11] error    : Mail: Mailserver response error -- 535-5.7.8 Username and Password not accepted. Learn more at
[UTC Dec 21 16:37:11] error    : SMTP: Mailserver response error -- 535 5.7.8  https://support.google.com/mail/?p=BadCredentials y63sm24571380wmd.21 - gsmtp
[UTC Dec 21 16:37:11] error    : Event queue is full
[UTC Dec 21 16:37:11] error    : Aborting event - queue over quota
[UTC Dec 21 16:37:11] info     : 'nginx_rc' monitor action done
[UTC Dec 21 16:37:11] error    : Mail: Mailserver response error -- 535-5.7.8 Username and Password not accepted. Learn more at
[UTC Dec 21 16:37:11] error    : SMTP: Mailserver response error -- 535 5.7.8  https://support.google.com/mail/?p=BadCredentials o125sm24541891wmo.30 - gsmtp
[UTC Dec 21 16:37:11] error    : Event queue is full
[UTC Dec 21 16:37:11] error    : Aborting event - queue over quota
[UTC Dec 21 16:37:11] info     : 'mysql_bin' monitor action done
[UTC Dec 21 16:37:11] error    : Mail: Mailserver response error -- 535-5.7.8 Username and Password not accepted. Learn more at
[UTC Dec 21 16:37:11] error    : SMTP: Mailserver response error -- 535 5.7.8  https://support.google.com/mail/?p=BadCredentials m2sm22734832wml.34 - gsmtp
[UTC Dec 21 16:37:11] error    : Event queue is full
[UTC Dec 21 16:37:11] error    : Aborting event - queue over quota
[UTC Dec 21 16:37:11] info     : 'mysql_rc' monitor action done
[UTC Dec 21 16:37:11] error    : Mail: Mailserver response error -- 535-5.7.8 Username and Password not accepted. Learn more at
[UTC Dec 21 16:37:11] error    : SMTP: Mailserver response error -- 535 5.7.8  https://support.google.com/mail/?p=BadCredentials s3sm2848477wmc.44 - gsmtp
[UTC Dec 21 16:37:11] error    : Event queue is full
[UTC Dec 21 16:37:11] error    : Aborting event - queue over quota
[UTC Dec 21 16:37:11] info     : 'apache_bin' monitor action done
[UTC Dec 21 16:37:12] error    : Mail: Mailserver response error -- 535-5.7.8 Username and Password not accepted. Learn more at
[UTC Dec 21 16:37:12] error    : SMTP: Mailserver response error -- 535 5.7.8  https://support.google.com/mail/?p=BadCredentials 125sm22297314wmc.27 - gsmtp
[UTC Dec 21 16:37:12] error    : Event queue is full
[UTC Dec 21 16:37:12] error    : Aborting event - queue over quota
[UTC Dec 21 16:37:12] info     : 'apache_rc' monitor action done
[UTC Dec 21 16:37:12] error    : Mail: Mailserver response error -- 535-5.7.8 Username and Password not accepted. Learn more at
[UTC Dec 21 16:37:12] error    : SMTP: Mailserver response error -- 535 5.7.8  https://support.google.com/mail/?p=BadCredentials o23sm30549332wro.57 - gsmtp
[UTC Dec 21 16:37:12] error    : Event queue is full
[UTC Dec 21 16:37:12] error    : Aborting event - queue over quota
[UTC Dec 21 16:37:12] info     : 'inf-education-67' monitor action done
[UTC Dec 21 16:37:12] error    : Mail: Mailserver response error -- 535-5.7.8 Username and Password not accepted. Learn more at
[UTC Dec 21 16:37:12] error    : SMTP: Mailserver response error -- 535 5.7.8  https://support.google.com/mail/?p=BadCredentials v20sm28999905wra.19 - gsmtp
[UTC Dec 21 16:37:12] error    : Event queue is full
[UTC Dec 21 16:37:12] error    : Aborting event - queue over quota
[UTC Dec 21 16:37:12] info     : 'nginx' monitor action done
[UTC Dec 21 16:37:12] error    : Mail: Mailserver response error -- 535-5.7.8 Username and Password not accepted. Learn more at
[UTC Dec 21 16:37:12] error    : SMTP: Mailserver response error -- 535 5.7.8  https://support.google.com/mail/?p=BadCredentials k1sm27935712wrn.46 - gsmtp
[UTC Dec 21 16:37:12] error    : Event queue is full
[UTC Dec 21 16:37:12] error    : Aborting event - queue over quota
[UTC Dec 21 16:37:12] info     : 'mysqld' monitor action done

A: Tyler answers on another question about this:

On Ubuntu 20.04 LTS, I found that pid-file and socket were commented
out in /etc/mysql/mysql.conf.d/mysqld.cnf. I uncommented those two
lines then restarted mysql with service mysql restart and monit with
service monit restart and monit was successfully able to monitor the
mysqld process.

It's worked for me, BTW Thank you @Tyler (I can't upvote and comment there)


text:
Q: Get which capture group matched a result using Delphi's TRegex I've written a regex whose job is to return all matches to its three alternative capture groups. My goal is to learn which capture group produced each match. PCRE seems able to produce that information. But I haven't yet been able coerce the TRegEx class in Delphi XE8 to yield meaningful capture group info for matches. I can't claim to be at the head of regex class, and TRegEx is new to me, so who knows what errors I'm making.
The regex (regex101.com workpad) is:
(?'word'\b[a-zA-Z]{3,}\b)|(?'id'\b\d{1,3}\b)|(?'course'\b[BL]\d{3}\b)

This test text:
externship L763 clinic 207 B706 b512

gives five matches in test environments. But a simple test program that walks the TGroupCollection of each TMatch in the TMatchCollection shows bizarre results about groups: all matches have more than one group (2, 3 or 4) with each group's Success true, and often the matched text is duplicated in several groups or is empty. So this data structure (below) isn't what I'd expect:
Using TRegEx
Regex: (?'word'\b[a-zA-Z]{3,}\b)|(?'id'\b\d{1,3}\b)|(?'course'\b[BL]\d{3}\b)
Text: externship L763 clinic 207 B706 b512

5 matches
 'externship' with 2 groups:
    length 10 at 1 value 'externship' (Sucess? True)
    length 10 at 1 value 'externship' (Sucess? True)
 'L763' with 4 groups:
    length 4 at 12 value 'L763' (Sucess? True)
    length 0 at 1 value '' (Sucess? True)
    length 0 at 1 value '' (Sucess? True)
    length 4 at 12 value 'L763' (Sucess? True)
 'clinic' with 2 groups:
    length 6 at 17 value 'clinic' (Sucess? True)
    length 6 at 17 value 'clinic' (Sucess? True)
 '207' with 3 groups:
    length 3 at 24 value '207' (Sucess? True)
    length 0 at 1 value '' (Sucess? True)
    length 3 at 24 value '207' (Sucess? True)
 'B706' with 4 groups:
    length 4 at 28 value 'B706' (Sucess? True)
    length 0 at 1 value '' (Sucess? True)
    length 0 at 1 value '' (Sucess? True)
    length 4 at 28 value 'B706' (Sucess? True)

My simple test runner is this:
program regex_tester;
{$APPTYPE CONSOLE}
{$R *.res}
uses
  System.SysUtils,
  System.RegularExpressions,
  System.RegularExpressionsCore;

var
  Matched     : Boolean;
  J           : integer;
  Group       : TGroup;
  Match       : TMatch;
  Matches     : TMatchCollection;
  RegexText,
  TestText    : String;
  RX          : TRegEx;
  RXPerl      : TPerlRegEx;

begin
  try
    RegexText:='(?''word''\b[a-zA-Z]{3,}\b)|(?''id''\b\d{1,3}\b)|(?''course''\b[BL]\d{3}\b)';
    TestText:='externship L763 clinic 207 B706 b512';

    RX:=TRegex.Create(RegexText);

    Matches:=RX.Matches(TestText);

    Writeln(Format(#10#13#10#13'Using TRegEx'#10#13'Regex: %s'#10#13'Text: %s'#10#13,[RegexText, TestText]));

    Writeln(Format('%d matches', [Matches.Count]));
    for Match in Matches do
    begin
      Writeln(Format(' ''%s'' with %d groups:', [Match.Value,Match.Groups.Count]));

      for Group in Match.Groups do
        Writeln(Format(#9'length %d at %d value ''%s'' (Sucess? %s)', [Group.Length,Group.Index,Group.Value,BoolToStr(Group.Success, True)]));
    end;

    RXPerl:=TPerlRegEx.Create;
    RXPerl.Subject:=TestText;
    RXPerl.RegEx:=RegexText;

    Writeln(Format(#10#13#10#13'Using TPerlRegEx'#10#13'Regex: %s'#10#13'Text: %s'#10#13,[RXPerl.Regex, RXPerl.Subject]));

    Matched:=RXPerl.Match;
    if Matched then
    repeat
      begin
        Writeln(Format(' ''%s'' with %d groups:', [RXPerl.MatchedText,RXPerl.GroupCount]));
        for J:=1 to RXPerl.GroupCount do
          Writeln(Format(#9'length %d at %d, value ''%s''',[RXPerl.GroupLengths[J],RXPerl.GroupOffsets[J],RXPerl.Groups[J]]));

        Matched:=RXPerl.MatchAgain;
      end;
    until Matched=false;

  except
      on E: Exception do
          Writeln(E.ClassName, ': ', E.Message);
  end;
end.

I'd certainly appreciate a nudge in the right direction. If TRegEx is broken, I can of course use an alternative -- or I can let go of the perceived elegance of the solution, instead using three simpler tests to find the bits of info I need.
Added Information and Interpretation
As @andrei-galatyn notes, TRegEx uses TPerlRegEx for its work. So I added a section to my testing program (output below) where I experiment with that, too. It isn't as convenient to use as TRegEx, but its result is what it should be -- and without the problems of TRegEx's broken TGroup data structures. Whichever class I use, the last group's index (less 1 for TRegEx) is the capturing group I want.
Along the way I was reminded that Pascal arrays are often based on 1 rather than 0.
Using TPerlRegEx
Regex: (?'word'\b[a-zA-Z]{3,}\b)|(?'id'\b\d{1,3}\b)|(?'course'\b[BL]\d{3}\b)
Text: externship L763 clinic 207 B706 b512

 'externship' with 1 groups:
    length 10 at 1, value 'externship'
 'L763' with 3 groups:
    length 0 at 1, value ''
    length 0 at 1, value ''
    length 4 at 12, value 'L763'
 'clinic' with 1 groups:
    length 6 at 17, value 'clinic'
 '207' with 2 groups:
    length 0 at 1, value ''
    length 3 at 24, value '207'
 'B706' with 3 groups:
    length 0 at 1, value ''
    length 0 at 1, value ''
    length 4 at 28, value 'B706'

A: Internally Delphi uses class TPerlRegEx and it has such description for GroupCount property:
Number of matched groups stored in the Groups array. This number is the number of the highest-numbered capturing group in your regular expression that actually participated in the last match. It may be less than the number of capturing groups in your regular expression.
E.g. when the regex "(a)|(b)" matches "a", GroupCount will be 1. When the same regex matches "b", GroupCount will be 2.
TRegEx class always adds one more group (for whole expression i guess).
In your case it should be enough to check every match like this:
case Match.Groups.Count-1 of
  1: ; // "word" found
  2: ; // "id" found
  3: ; // "course" found
end;

It doesn't answer why Groups are filled with strange data, indeed it seems to be enough to answer your question. :)

A: I realize this is 4 years too late, but for others who may search for this, here's what I found (in Delphi RIO at least, I have not tested earlier versions, however the source URL below says as of XE), however:
From https://www.regular-expressions.info/delphi.html (important bit is bold italic)

The TMatch record provides several properties with details about the
  match. Success indicates if a match was found. If this is False, all
  other properties and methods are invalid. Value returns the matched
  string. Index and Length indicate the position in the input string and
  the length of the match. Groups returns a TGroupCollection record that
  stores a TGroup record in its default Item[] property for each
  capturing group. You can use a numeric index to Item[] for numbered
  capturing groups, and a string index for named capturing groups.

So, if you NAME your matching group like this for example:
(?'MatchName'[^\/\?]*)

Which would match a string up until a / or ? character, you can then reference that capture group by name like this:
Matches := TRegEx.Matches(StrToMatch, RegexString, [ roExplicitCapture ] );
for Match in Matches do begin
  // ... maybe some logic here to determine if this is the match you want ...
  try
    whatGotMatched := Match.Groups['MatchName'].Value;
  except
    whatGotMatched := '';
  end;
end;

How exactly you get to your match groups in the Matches is dependent on how you structure your RegEx etc, how many matches you create, etc.  I surround the Match.Groups['MatchName'].Value in a try-except block because if the match wasn't found, you will generate an index out of bounds error when accessing .Value since it will still say the match would have been at character X, for 0 characters. You could also check Match.Groups['MatchName'].Length for 0 before trying to access .Value to probably better results...but if you reference it by name, you don't have to decipher specifically what groups matched what, etc ... just ask for the named match you wanted, and if it matched, you will get it.
Edit: they reference to .Length to help verify before throwing an error about index out of bounds. However, if your search is constructed where a named search is not matched, and therefore not returned at all, you will get an error thrown for an invalid match name, so you may still may need to capture for that.


text:
Q: Relationship between Spin(3), SU(2), unit quaternions, and SO(3) There may be some short-hand / informal statements that are tripping me up, but I am getting confused trying to understand the relationship between Spin(3), SU(2), SO(3), and the unit quaternions.
Trying to find information online, many discussions seem to say SO(3) and SU(2) are isomorphic (for example wikipedia). Mathworld says SU(2) is isomorphic to $O^+_3(2)$ which I'm not quite sure how that relates to SO(3) (I have not seen that notation before). While others state SU(2) is isomorphic to the unit quaternions which are in turn a double cover of SO(3). Which seems to suggest there is a lot of "short-hand" discussion going on and sometimes people say isomorphic ignoring a double cover? Or maybe I just misunderstand, and a double cover doesn't really matter for some reason?
My best effort of trying to figure out what is going on seems to suggest:
$$Spin(3) \cong SU(2) \cong \{q \in \mathbb{H} | q\bar{q}=1 \} \not \cong SO(3)$$
Is that close, or are even more of those actually double covers?
What is the correct relationship between these groups? (and what does $O^+_3(2)$ denote?)

A: $Spin(3), SU(2)$, and the unit quaternions $Sp(1)$ are all isomorphic; this Lie group is also sometimes referred to simply as its underlying manifold $S^3$. $SO(3)$ is diffeomorphic to $\mathbb{RP}^3$ and so is not diffeomorphic to $S^3$, although its double cover is $Spin(3)$ (and hence also $SU(2)$ and $Sp(1)$).
One possible source of confusion is that all of the corresponding Lie algebras are isomorphic, and some sources (especially from physics) do not closely distinguish between Lie groups and their Lie algebras.


text:
Q: error "gatsby-transformer-cloudinary" threw an error while running the onCreateNode lifecycle I am interacting with a MongoDB backend with gatsby. There is a node which sometimes has images and sometimes doesn't so each of these nodes has a child node within it called cloudinary. I get an error from gatsby-transformer-cloudinary appearing when trying to automatically create nodes as documented here: https://www.npmjs.com/package/gatsby-transformer-cloudinary in the "Use images already on Cloudinary" section.
our node structure is a bit like this:
artwork: {
   mediaItems: {
      cloudinary: {
         cloudinaryAssetData: true,
         ... other relevant stuff
      }
   }
   mediaItems: {
      ... this one doesn't contain a cloudinary image node
   }

sometimes a mediaItem would have the above node in the MongoDB structure, sometimes not. I then got the error below
cannot convert undefined or null to object

  53 |   const currentNode = basePath === '' ? node : get(node, basePath);
  54 |
> 55 |   const directAssetDataPaths = Object.keys(currentNode)
     |                                       ^
  56 |     .filter(key => {
  57 |       return currentNode[key] && currentNode[key].cloudinaryAssetData === true;
  58 |     })

  TypeError: Cannot convert undefined or null to object

  - Function.keys

  - create-asset-nodes-from-data.js:55 getAssetDataPaths
    [rca-wip-2021-public]/[gatsby-transformer-cloudinary]/gatsby-node/create-asset-nodes-from-data.js:55:39

  - create-asset-nodes-from-data.js:72
    [rca-wip-2021-public]/[gatsby-transformer-cloudinary]/gatsby-node/create-asset-nodes-from-data.js:72:12

  - _arrayMap.js:16 arrayMap
    [rca-wip-2021-public]/[gatsby-transformer-cloudinary]/[lodash]/_arrayMap.js:16:21

I have tried adding otherwise empty nodes in the database with cloudinaryAssetData: false wherever there isn't an image, to try to remedy this, but that hasn't worked so far. As below:
mediaItems: {
cloudinary: {
cloudinaryAssetData: false
}
}
It does seem that gatsby automatically creates null data for any empty fields/nodes, this might be the problem. If anyone has any insight into this i'd be grateful. It might be something i can solve my end by setting defaults, or modifying the data at the gatsby, or changing the way MongoDB is structured perhaps (but that's much harder to modify).

A: Gatsby is able to automatically infer a GraphQL Schema from your data, and in many cases, this is really all you need. There are however situations when you either want to explicitly define the data shape or add custom functionality to the query layer by adding nullability property to some fields.
Of course with this customization, you are diving into the GraphQL schema creation and maybe, it's easier to change the MongoDB structure to add some empty or dummy fields and trim them once queried if you are not comfortable customizing the schema.


text:
Q: Simple C++ ofstream project not working when deployed I made a very simple C++ program that creates a .sav file with "Hey" written in it. The program works perfectly when I run it in Visual Studio 2019, but, after deploying my program on my computer, when I launch the deployed .exe file, it doesn't do anything.
I'm using Visual Studio 2019 on Windows 10. My program and my Setup file are both set in release and in x86 mode, my program is set to be statically linked(I changed my program's Runtime Library to Multi-threaded(/MT)).
I deployed my project by following this article's instructions: https: //learn.microsoft.com/en-us/cpp/ide/walkthrough-deploying-your-program-cpp?view=vs-2019
After building the setup file, and launching the .msi installer created, the program installed does not even create the .sav file once launched.
Here's my code:
#include <fstream>

int main()
{

std::ofstream Yes;
Yes.open("Sc.sav");
Yes << "Hey" << std::endl;
Yes.close();

return 0;
}

What am I doing wrong?
Thanks in advance.

A: So, I found out what it was thanks to your comments:
my application needed administrator rights to create the file, so I had to either ask the user for administrator rights, or save my file where I didn't need to have these rights.
I chose the second solution and saved my file in the C:\AppData\Roaming directory, where programs can save their files without asking the permission.
Thanks again for your help and attention.


text:
Q: What's wrong with sequental consistency here? I'm playing with lock-free algorithms in C and C++ and recently stumbled upon a behavior I don't quite understand. If you have the following code, running it will give you something like

reader started
writer started
iters=79895047, less=401131, eq=48996928, more=30496988

Aren't std::atomics are expected to be sequentially-consistent? If so, why does the reader sometimes see b being updated before a? I also tried to do various tricks involving memory fences with no success. The full compilable code can be seen at https://github.com/akamaus/fence_test
What's wrong with the example?
std::atomic<uint> a(0);
std::atomic<uint> b(0);

volatile bool stop = false;

void *reader(void *p) {
    uint64_t iter_counter = 0;
    uint cnt_less = 0,
         cnt_eq = 0,
         cnt_more = 0;

    uint aa, bb;

    printf("reader started\n");

    while(!stop) {
        iter_counter++;
        aa = a.load(std::memory_order_seq_cst);
        bb = b.load(std::memory_order_seq_cst);
        if (aa < bb) {
            cnt_less++;
        } else if (aa > bb) {
            cnt_more++;
        } else {
            cnt_eq++;
        }
    }
        printf("iters=%lu, less=%u, eq=%u, more=%u\n", iter_counter, cnt_less, cnt_eq, cnt_more);

    return NULL;
}

void *writer(void *p) {
    printf("writer started\n");
    uint counter = 0;
    while(!stop) {
        a.store(counter, std::memory_order_seq_cst);
        b.store(counter, std::memory_order_seq_cst);
        counter++;
    }
}

A: Sequentially consistent memory ordering implies that the modification order (of the atomic objects manipulated with seq cst) observed by all threads is consistent. The program behaves as if all those operations happen interleaved in a single total order. Consider the following cases:

Writer Reader
       a == 0
a = 1
b = 1
       b == 1

Result: aa < bb.

Writer Reader
a = 1
       a == 1
       b == 0
b = 1
Result: aa > bb

With a lock, e.g. a mutex, you can make sure that the operations don't interleave.


text:
Q: web.config Vs App.config for Assemblies I have a web application and in the Web.Config I am adding the assemblies as shown below
    <compilation debug="true">
        <assemblies>
            <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="CrystalDecisions.CrystalReports.Engine, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
            <add assembly="CrystalDecisions.ReportSource, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
            <add assembly="CrystalDecisions.Shared, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
            <add assembly="CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
            <add assembly="CrystalDecisions.ReportAppServer.ClientDoc, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
            <add assembly="CrystalDecisions.Enterprise.Framework, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
            <add assembly="CrystalDecisions.Enterprise.InfoStore, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/></assemblies>
    </compilation>

In the .cs file I include the namespaces and use it in my code.
How do I do this in App.config page in a WCF service application?
Please help

A: In Visual Studio, in Solution Explorer, right-click References and select Add Reference...
This should take care of everything else for you.


text:
Q: Unit Testing With/Without hardward in the loop Background
I am working on a project that interfaces with various cameras and their unique APIs. All cameras are abstracted into one interface, and the camera-specific API calls are contained within their own implementing classes.
Problem Explanation
I am trying to test a factory method that parses a form of configuration, and returns a pointer to the newly created camera. Here is a high-level view of what that looks like:
// camerafactory.cpp

Camera* make_camera(Config& config) {
    switch (config.type) {
        case CameraTypes.A : {
            int paramInt = config.paramInt;
            return new CameraA(paramInt);
        }
        case CameraTypes.B : {
            string paramString = config.paramString;
            return new CameraB(paramString);
        }
        case CameraTypes.C : {
            float param1 = config.param1;
            float param2 = config.param2;
            return new CameraC(param1, param2);
        }
        default: {
            throw std::invalid_argument("Invalid configuration!");
        }

    }
}

I want to test that these constructors are getting called correctly, however this would require the cameras to be physically connected to the computer to allow for the camera API's within the camera constructors to work. This does make sense for some testing situations, i.e. demonstrating hardware in the loop, however in my specific case, it is unrealistic to have all types of cameras connected at a single time.
I would like to test that these constructors are at least getting called with the correct parameters, demonstrating that the parsing is working correctly. I have considered abstracting out the parsing and testing that separately, but technically there is still the constructor call that is not being tested. I was also always told that adding functionality for the sake of testing is usually something that should be avoided, so that is another thing I am considering with my solution. It would also be interesting to find a solution that allows easy compile-time switching between mocks/concrete implementations to test hardware in the loop.
Versions
Note, I am using C++ 17, CMake, and the latest version of gtest.
Solutions being considered
Using macros to change the constructor calls to Mock constructor calls.
At the top of camerafactory.cpp, adding something like:
// camerafactory.cpp

#ifndef PRODUCTION
#include "MockCamera.hpp"
#define CameraA MockCameraA
#define CameraB MockCameraB
#define CameraC MockCameraC
#endif

Where MockCameraN are defined in a separate hpp/cpp file with identical constructors, and also implement the same Camera Interface, which I can then use to test correct construction.
This would allow me to test that the constructors are getting called correctly, but does feel like it goes against a cleaner solution that could be done with a language like Java.
Using GMock
I have not looked too deeply into it yet, but GMock seems to be promising: http://google.github.io/googletest/gmock_cook_book.html

A: My advice with and without gmock is to use virtual methods that can be overridden in test code.
First, convert your factory funciton, make_camera, into its own class with virtual methods for things you want to validate.   For brevity, I'm using an inline approach. In production code, you would probably want to separate this out into its own .h file for the class declaration and .cpp file for the implementation.
class CameraFactory
{
public:

    virtual Camera* make_camera_a(int param) {
        return new CameraA(param);
    }

    virtual Camera* make_camera_b(const string& param) {
        return new CameraB(param);
    }

    virtual Camera* make_camera_c(double param1, param2) {
        return new CameraC(param1, param2);
    }

    virtual Camera* make_camera(const Config& config) {
        switch (config.type) {
            case CameraTypes::A: {
                return make_camera_a(config.intParam);
            }
            case CameraTypes::B: {
                return make_camera_b(config.strParam);
            }
            case CameraTypes::C: {
                return make_camera_c(config.param1, config.param2);
            }
            default: {
                throw std::invalid_argument("Invalid configuration!");
            }
        }
    }
};

In your product code, where you would ordinarily invoke make_camera, you can just use a CameraFactory off the stack:
Replace lines like this in your product code:
Camera* cam = make_camera(config); // old code

With this:
CameraFactory factory;
Camera* cam = factory.make_camera(config);

Testing without gmock:
Old way of testing this would be for your unit test to override the individual make functions in a class that partially mocks out the virtual methods you want to validate getting called correctly.
class MockCamera : public Camera
{
};

class MockCameraFactory : public CameraFactory
{
    virtual Camera* make_camera_a(int param) {
        _camera_a_created = true;
        _intParm = param;
        return new MockCamera();
    }

    virtual Camera* make_camera_b(const string& param) {
        _camera_b_created = true;
        _strParam = param;
        return new MockCamera();
    }

    virtual Camera* make_camera_c(double param1, param2) {
        _camera_c_created = true;
        _param1 = param1;
        _param2 = param2;
        return new MockCamera();
    }

    bool _camera_a_created;
    bool _camera_b_created;
    bool _camera_c_created;
    int _intParam;
    string _strParam;
    double _param1;
    double _param2;

    CameraFactoryTest() {
        resetState();
    }
    void resetState() {
        _camera_a_created = false;
        _camera_b_created = false;
        _camera_c_created = false;
        _intParam = 0;
        _strParam = "";
        _param1 = 0;
        _param2 = 0;
    }
};

Notice that CameraFactoryTest doesn't override make_camera, but it does inherit from it.
Then your unit test code can validate that the right parameters are getting passed to your constructors.  I'm just guessing your ut framework has some validation macro called UNIT_TEST_ASSERT. I'm sure you have something equivalent.
void test_make_camera()
{
    MockCameraFactory factory;
    Config config;

    // test camera A
    config.type=CameraConfig::A;
    config.intParam = 42;
    factory.make_camera(config);
    UNIT_TEST_ASSERT(factory._camera_a_created == true);
    UNIT_TEST_ASSERT(factory._camera_b_created == false);
    UNIT_TEST_ASSERT(factory._intParam == 42);

    // test camera B
    factory.resetState();
    config = {};
    config.type=CameraConfig::B;
    config.strPara = "USB1";
    factory.make_camera(config);
    UNIT_TEST_ASSERT(factory._camera_b_created == true);
    UNIT_TEST_ASSERT(factory._strParam == "USB1");

    ...

}

With Google Test (GMock)
It's even easier with gmock and enables your mock class to be more usable in other tests.  Instead of explicitly coding up a MockCameraFactory class, you use the GMock way.
Start by declaring a mock class that inherits from your actual class.
class MockCameraFactory : public CameraFactory
{
public:
    MOCK_METHOD1(make_camera_a, Camera*(int param));
    MOCK_METHOD1(make_camera_b, Camera*(const string& param));
    MOCK_METHOD2(make_camera_c, Camera*(const string& param));
};

Then your test code can do something like this:
class test_make_camera()
{
    MockCameraFactoryTest factory;
    MockCamera cameramock;

    EXPECT_CALL(factory, make_camera_a(42)).WillOnce(Return(&cameramock));

    Config config = {};
    config.type = CameraType::A;
    config.intParam = 42;

    factory.make_camera(config);

    Mock::VerifyAndClearExpectations(&factory);

}

I'm skimming over the details of how to setup Google Test such that it asserts through your own unit test framework.  But you get the idea.
Also of note - I originally declared make_camera to be virtual in the CameraFactory class. It doesn't actually have to be virtual since your tests are only validating that the make_camera_x methods are getting called correctly.


text:
Q: jq is reordering keys within my JSON For some reason, and I have no idea why, when I test out formatting of the following lines on jqplay it comes out looking different than when I run it on the command line.
My original data looks as such:
{"type":"user.list","users":[{"type":"user","id":"57db1b1b9jdjd84f99b977785ba","user_id":"janwjf3sqdditwn7c7","anonymous":false,"email":"test@diversifiedventures.net","phone":null,"name":"Joe Smith","pseudonym":null,"avatar":{"type":"avatar","image_url":null},"app_id":"b5vkddxvop","companies":{"type":"company.list","companies":[]},"location_data":{"type":"location_data","city_name":"Murfreesboro","continent_code":"NA","country_name":"United States","latitude":35.8896,"longitude":-86.3166,"postal_code":"37130","region_name":"Tennessee","timezone":"America/Chicago","country_code":"USA"},"last_request_at":1478624249,"last_seen_ip":"69.139.122.123","created_at":1473977115,"remote_created_at":1466313380,"signed_up_at":1466313380,"updated_at":1480970142,"session_count":1,"social_profiles":{"type":"social_profile.list","social_profiles":[]},"unsubscribed_from_emails":false,"user_agent_data":"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko","tags":{"type":"tag.list","tags":[{"type":"tag","id":"587061","name":"Mixpanel Import - 2016-09-15 21:25:08 UTC"}]},"segments":{"type":"segment.list","segments":[{"type":"segment","id":"581a048c4ad88d6b458198d7"},{"type":"segment","id":"5845cd57c91b1fe3e440032b"},{"type":"segment","id":"5845cab9d951b43e7d33d2f7"}]},"custom_attributes":{"mixpanel_id":"1556710d919339-0beb72f2966b408-69581467-cff8c-1556710d91a54b","claimCount":"2","memberType":"claimant"}}],"scroll_param":"56386a4d-743b-470a-ae9f-848b991e0ccc"}

If you dump that into the jq playground, it formats it exactly how it should be and how I want it, which looks like this:
{"type":"user","id":"57db1b1b9jdjd84f99b977785ba","user_id":"janwjf3sqdditwn7c7","anonymous":false,"email":"test@diversifiedventures.net","phone":null,"name":"Joe Smith","pseudonym":null,"avatar":{"type":"avatar","image_url":null},"app_id":"b5vkddxvop","companies":{"type":"company.list","companies":[]},"location_data":{"type":"location_data","city_name":"Murfreesboro","continent_code":"NA","country_name":"United States","latitude":35.8896,"longitude":-86.3166,"postal_code":"37130","region_name":"Tennessee","timezone":"America/Chicago","country_code":"USA"},"last_request_at":1478624249,"last_seen_ip":"69.139.122.123","created_at":1473977115,"remote_created_at":1466313380,"signed_up_at":1466313380,"updated_at":1480970142,"session_count":1,"social_profiles":{"type":"social_profile.list","social_profiles":[]},"unsubscribed_from_emails":false,"user_agent_data":"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko","tags":{"type":"tag.list","tags":[{"type":"tag","id":"587061","name":"Mixpanel Import - 2016-09-15 21:25:08 UTC"}]},"segments":{"type":"segment.list","segments":[{"type":"segment","id":"581a048c4ad88d6b458198d7"},{"type":"segment","id":"5845cd57c91b1fe3e440032b"},{"type":"segment","id":"5845cab9d951b43e7d33d2f7"}]},"custom_attributes":{"mixpanel_id":"1556710d919339-0beb72f2966b408-69581467-cff8c-1556710d91a54b","claimCount":"2","memberType":"claimant"}}

That is precisely how I want the data to be restructured.
Go to the link for jqplay and see for yourselft, by simply typing this into the filter and clicking the compact output:
.users[]

But for some reason when I run this in the command line:
curl https://api.example.com/users/scroll -u 'dG9rOjg4YmUxMzr4XzJmNzZfNDkwY3934jU2X2mrM2MxZGEzYWI2MzoxOjA=': -H 'Accept:application/json'| jq -c '.users[]'

It spits out a result that is totally not formmated how it is suppose to come out, despite using the exact same filter:
{"custom_attributes":{"memberType":"claimant","claimCount":"2","mixpanel_id":"1556710d919339-0beb72f2966b408-69581467-cff8c-1556710d91a54b"},"segments":{"segments":[{"id":"581a048c4ad88d6b458198d7","type":"segment"},{"id":"5845cd57c91b1fe3e440032b","type":"segment"},{"id":"5845cab9d951b43e7d33d2f7","type":"segment"}],"type":"segment.list"},"tags":{"tags":[{"name":"Mixpanel Import - 2016-09-15 21:25:08 UTC","id":"587061","type":"tag"}],"type":"tag.list"},"user_agent_data":"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko","unsubscribed_from_emails":false,"social_profiles":{"social_profiles":[],"type":"social_profile.list"},"session_count":1,"updated_at":1480970142,"signed_up_at":1466313380,"pseudonym":null,"name":"Joe Smith","phone":null,"email":"test@diversifiedventures.net","anonymous":false,"user_id":"janwjf3sqdditwn7c7","id":"57db1b1b9jdjd84f99b977785ba","type":"user","avatar":{"image_url":null,"type":"avatar"},"app_id":"b5vkddxvop","companies":{"companies":[],"type":"company.list"},"location_data":{"country_code":"USA","timezone":"America/Chicago","type":"location_data","city_name":"Murfreesboro","continent_code":"NA","country_name":"United States","latitude":35.8896,"longitude":-86.3166,"postal_code":"37130","region_name":"Tennessee"},"last_request_at":1478624249,"last_seen_ip":"69.139.122.123","created_at":1473977115,"remote_created_at":1466313380}

Which as you can tell, is nothing like how it turns out in the jqplayground feature. To make matters even more confusing, someone else ran it and it formatted it correctly. On top of that, about a week ago, it worked fine for me.
I've also tried removing jq and reinstalling it with no success. I'm running it on Ubuntu 14.04.2 LTS (GNU/Linux 3.13.0-51-generic x86_64) if that somehow helps.
Any help would be greatly appreciated!

A: jq 1.3 does not always respect the ordering of keys within JSON objects.  Assuming you are using jq 1.3 (or earlier), the solution would be to upgrade to a later version (1.4, 1.5, or the "master" version).


text:
Q: Integer Problem in MIPS assembly Using MIPS assembly if I prompt a user to input an integer how can I then take that integer and break it up into it's requisite parts?
Example:
                 # User inputs a number
li  $v0, 5      # read value of n
    syscall

I then store the value in $v0 in a temporary register, say $t0, and need to break it up into each part that makes it up.  So, 308 has to be broken up into: 3, 0, and 8.  I need to do this so that I can then square each of these parts and add them together.
The input value from the user has to be input as an integer.
thanks,
nmr

A: Divide by 10, use the remainder to get the 8, if quotient is non-zero, divide by 10 again and use then remainder to to the zero, if quotient is non-zero repeat.

A: This is @Don's answer, with a twist
$t0 contains the user input. (asume unsigned)
li   $t1,10
DIVU $t0,$t1 //divide by 10

mfhi $t2 //t2 contains the division result
mflo $t3 //t3 containts the division remainder

use beq, bgt to do the comparisons.
Some help
http://www.mrc.uidaho.edu/mrc/people/jff/digital/MIPSir.html


text:
Q: Reassigning Parent Nodes and Child Nodes in Changing Binary Tree to Heap I am working on a homework assignment for my class and I am trying to change a balanced binary tree into a heap using code that the professor provided.
His basic instructions were to create a method called rebuildTree, and this method would take the newly added node and swap the parent for the new node if the new node is greater than the parent.
I have a test method of rebuildTree so far that is semi-working when I do a Sysout to check what my values are, but it does not seem to change the parent and child to what I want them to be.
/* This is the BalancedBTree class that the professor provided */

import java.util.Queue;
import java.util.LinkedList;

public class BalancedBTree {
    private Node firstNode = null;
    private Node currentParent = null;

    public void addNode(int n) {
        if(firstNode == null) {
            firstNode = new Node(n);
            currentParent = firstNode;
        } else {
            createNextNode(n);
        }
    }

    public void createNextNode(int n) {
        Node nextNode = new Node(n);
        if(currentParent.getLeftNode() == null) {
            nextNode.setParentNode(currentParent);
            currentParent.setLeftNode(nextNode);
            rebuildTree(nextNode,currentParent);
        } else {
            currentParent.setRightNode(nextNode);;
            nextNode.setParentNode(currentParent);
            rebuildTree(nextNode,currentParent);
        }
    }

/* --This is my rebuildTree method that I am trying to implement-- */
    public void rebuildTree(final Node compareNode, final Node currentParent) {
            Node nextNode = compareNode;
            Node tempNode = currentParent;
            int nxtNode = nextNode.getPayload();
            int currParent = currentParent.getPayload();
            if(nextNode.getParentNode() != null){
                if(nxtNode > currParent){
                    currentParent.setParentNode(nextNode);
                    System.out.println(currentParent.getParentNode().getPayload());
                    nextNode.setLeftNode(currentParent);
                    System.out.println(nextNode.getLeftNode().getPayload());
                }
            } else {
                System.out.println("false");
            }
    }

    public void updateCurrentParent() {
        if(currentParent == firstNode)
            currentParent =  currentParent.getLeftNode();
        else {
            // This code works only when called from a right child
            // While you are a right child, move up a parent
            while(currentParent.getParentNode().getRightNode() == currentParent) {
                currentParent = currentParent.getParentNode();
                // Check for first node which has no parent
                if(currentParent.getParentNode() == null)
                    currentParent = currentParent.getLeftNode();
            }

            // Once you are a left hand child, move over to the right hand child.
            currentParent = currentParent.getParentNode().getRightNode();

            // Go down left hand side until left hanbd side is null
            while(currentParent.getLeftNode() != null) {
                currentParent = currentParent.getLeftNode();
            }
            // The currentParent pointer has now been updated
        }
    }

    public void printBalancedBTree() {
        Queue<Node> leftQ = new LinkedList<>();
        Queue<Node> rightQ = new LinkedList<>();

        if(firstNode != null)
            leftQ.offer(firstNode);
        while(!leftQ.isEmpty() || !rightQ.isEmpty()) {
            if(!leftQ.isEmpty()) {
                printLeftQ(leftQ,rightQ);
            }
            System.out.println();
            if(!rightQ.isEmpty()) {
                printRightQ(leftQ,rightQ);
            }
            System.out.println();
            break;
        }
    }

    public void printLeftQ(Queue<Node> leftQ, Queue<Node> rightQ) {
        Node printNode = null;
        while(!leftQ.isEmpty()) {
            printNode = leftQ.poll();
            System.out.print(printNode.getPayload() + "\t");
            if(printNode.getLeftNode() != null)
                rightQ.offer(printNode.getLeftNode());
            if(printNode.getRightNode() != null)
                rightQ.offer(printNode.getRightNode());
        }
    }

    public void printRightQ(Queue<Node> leftQ, Queue<Node> rightQ) {
        Node printNode = null;
        while(!rightQ.isEmpty()) {
            printNode = rightQ.poll();
            System.out.print(printNode.getPayload() + "\t");
            if(printNode.getLeftNode() != null)
                leftQ.offer(printNode.getLeftNode());
            if(printNode.getRightNode() != null)
                leftQ.offer(printNode.getRightNode());
        }
    }

}

/*This is the main method that I am testing with*/

public class TestBalancedBTree
{

    public static void main(String[] args)
    {
        BalancedBTree bbt = new BalancedBTree();
        bbt.addNode(5);
        bbt.addNode(10);
        bbt.printBalancedBTree();
    }

}

/* Adding Node Class */

public class Node {
    private int payload;
    private Node parentNode = null;
    private Node leftNode = null;
    private Node rightNode = null;

    public Node(int n) {
        payload = n;
    }

    public int getPayload() {
        return payload;
    }

    public void setPayload(int payload){
        this.payload = payload;
    }

    public Node getParentNode() {
        return parentNode;
    }

    public void setParentNode(Node parentNode) {
        this.parentNode = parentNode;
    }

    public Node getLeftNode() {
        return leftNode;
    }

    public void setLeftNode(Node leftNode) {
        this.leftNode = leftNode;
    }

    public Node getRightNode() {
        return rightNode;
    }

    public void setRightNode(Node rightNode) {
        this.rightNode = rightNode;
    }
}

My output when I do my rebuildTree method provides me with:
10
5
But then the printBalancedTree method shows:
5
10
I am not sure where I am going wrong with this, but any help is greatly appreciated.

A: Hope this helps. I did some changes to rebuildTree API with the input specified. If doesn't help comment so that will try to optimize. However, this is a good starting point in case if we have more than 2 elements.
public void rebuildTree(final Node compareNode, final Node currentParent) {

    Node nextNode = compareNode;
        Node tempNode = currentParent;
        int nxtNode = nextNode.getPayload();
        int currParent = currentParent.getPayload();
        if(nextNode.getParentNode() != null){
            if(nxtNode > currParent){
                currentParent.setParentNode(nextNode);
                currentParent.setLeftNode(null);
                System.out.println(currentParent.getParentNode().getPayload());
                nextNode.setLeftNode(currentParent);
                nextNode.setParentNode(null);
                firstNode=nextNode;
                System.out.println(nextNode.getLeftNode().getPayload());
            }
        } else {
            System.out.println("false");
        }
}


text:
Q: What is $\operatorname{Aut}(\mathbb{R},+)$? I was solving some exercises about automorphisms. I was able to show that $\operatorname{Aut}(\mathbb{Q},+)$ is isomorphic to $\mathbb{Q}^{\times}$. The isomorphism is given by $\Psi(f)=f(1)$, but when I try to do the same thing with $\operatorname{Aut}(\mathbb{R},+)$ I got stuck.
My question is: What is  $\operatorname{Aut}(\mathbb{R},+)$?
I would appreciate your help.

A: First note that for every $\alpha\in\mathbb R^\times$ we have that $x\mapsto\alpha\cdot x$ is an automorphism of $(\mathbb R,+)$.
Also note that if $f(x+y)=f(x)+f(y)$ then $f(2)=f(1)+f(1)$, and by induction $f(n)=n\cdot f(1)$ for $n\in\mathbb N$, equally $f(k)=k\cdot f(1)$ for $k\in\mathbb Z$. This carries to rationals as well, so $f\left(\frac{p}{q}\right)=\frac{p}{q}\cdot f(1)$.
Now, if $f$ is continuous then for every $x\in\mathbb R$ we have $f(x)=x\cdot f(1)$. So setting $\alpha=f(1)$ gives us that the continuous solutions are the solutions defined by $\mathbb R^\times$, therefore $\mathrm{Aut}(\mathbb R,+)\cap\{f\in\mathbb R^\mathbb R\mid f\text{ continuous}\}\cong(\mathbb R^\times,\cdot\ )$.
The existence of non-continuous solutions requires some axiom of choice, since such solutions generate Lebesgue non-measurable sets. So if we assume that every set is Lebesgue measurable (e.g. Solovay's model of models of Determinacy) then indeed there are no other solutions.
However, assuming the axiom of choice we can generate a basis for the vector space $\mathbb R$ over $\mathbb Q$. Note that every permutation of this basis can be extended to an automorphism of the vector space, namely $(\mathbb R,+)$.
The cardinality of such basis (known as Hamel basis) is $2^{\aleph_0}$, we have $2^{2^{\aleph_0}}$ many non-continuous solutions if we assume that such basis exists.
For further reading:

*

*Is there a non-trivial example of a $\mathbb Q-$endomorphism of $\mathbb R$?

*Horst Herrlich, The Axiom of Choice. Springer, 2006. (In particular section 5.1)


text:
Q: Fatal error: Call to a member function prepare() on a non-object PDO I am trying to move the my sql working to PDO but it showing the following
 Fatal error: Call to a member function prepare() on a non-object in /home/content/58/9508458/html/pa/test. php on line 12
orginal code
<?php
$pdfreq=$_GET['dadi'];
include('config.php');
require('fpdf.php');
$link =mysql_connect($db_host,$username,$password);
mysql_select_db($db_name);

$update = "UPDATE mastertable SET pdfstatus =1 WHERE id_pk = $pdfreq";
mysql_query($update, $link);

Replaced with
<?php
$pdfreq=$_GET['dadi'];
include('config.php');
require('fpdf.php');
$link =mysql_connect($db_host,$username,$password);
mysql_select_db($db_name);

$sql = "UPDATE mastertable SET pdfstatus=?, WHERE id_pk=?";
$q = $link->prepare($sql);
$q->execute(array(1,$pdfreq));

A: Your $link variable is not a PDO object.  You should replace:
$link = mysql_connect($db_host,$username,$password);
mysql_select_db($db_name);

With:
$link = new PDO("mysql:dbname=$db_name;host=$db_host",$username,$password);

A: You are using MySQL helper functions, not PDO or MySQLi.
Prepare will not work with what you are doing
You need to change your syntax to, note the trailing i in MySQLi
<?php
$pdfreq=$_GET['dadi'];
$id = 1;
include('config.php');
require('fpdf.php');
$link = new mysqli($db_host,$username,$password, $db_name);

$sql = "UPDATE mastertable SET pdfstatus=? WHERE id_pk=?";
$q = $link->prepare($sql);

$q->bind_param("is", $id, $pdfreq);
$q->execute();

Since MySQL does not have a prepare method, your value will never get set to 1, and you will fail with Fatal error: Call to a member function prepare() on a non-object
If you wish to use PDO see the PDO Documentation on PHP.Net


text:
Q: Using chrome.storage.get to get a variable I'm making a little Chrome extension and I have successfully used the options page to use chrome.storage.sync.set to set the variable pws. However, on the pop-up page I cannot successfully retrieve the variable and use it in the string. Here is the code where it goes:
weather.open("GET", "http://api.wunderground.com/api/"+WU_API_KEY+"/conditions/q/CA/pws:"+pws+".json", true);
weather.send()

})

How do I get pws in there as a variable from chrome.sync.storage.get?
I tried something like
chrome.storage.sync.get(pws, function(result){

var pws = result.pws
console.debug('result:',pws);

});

but no avail.

A: If you use "pws" as a key to store pws, then you could:
chrome.storage.sync.get("pws", function(result) {
    var pws = result.pws;
    console.log("result:", pws);
});


text:
Q: Jquery load only elements that end with a certain string First off I am pretty new to jquery.. I want to use the .load() feature but this same file is used for several places on one page. Ideally I would like to have the #element a variable, but from playing around with it myself I don't know that I can do that. I was wondering if there is a way to have this load function apply to all elements that end with a certain string, or if you need to give it the full exact element id? I'm having a hard time putting this into words what I mean but my code may help clear it up.
function RateItem(varItemId, varRate)
{
$.ajax({
url:"ajax.rate.item.php",
type:"POST",
data:{item:varItemId,rating:varRate},
success:function(ReloadRating){
$("#stars").load("index.php #stars")
alert(ReloadRating);
}
});
}

This is for a star rating system. I have several div elements that will be using this same code, all which have an id that ends with '_stars'. In place of the #stars element I would like to have a way of calling all div elements that end with that, or ideally have something like:
$("varItemId + _stars").load("index.php varItemId + _stars");

Playing around with this for a while I didn't have any luck in getting this to work unless I specified an exact div Id. Does anyone have ideas on how to somehow make this work into a .load statement:
[div$='_stars']

Above is from here

A: What you'd need to do is first select the elements via that ends-with selector, for the id attribute:
$('[id$="_stars"]')

and then use that to load each url:
$('[id$="_stars"]').each(function() {
    $(this).load("index.php #"+this.id);
});

That will go through each of the elements with an ID ending with _stars, and for each of those elements it will load the index.php with the URL fragment set to be the same as the defined ID for the element.


text:
Q: I use Xcode distributing app to App Store Connect. Xcode upload fail and show "ERROR ITMS-90037" I distribute my app to App Store Connect. Xcode run some process. Then Xcode upload fail and show ERROR ITMS-90037.
This project developed using Objective-C. I used Sublime Text finding following regular expression [\x00-\x08\x0b-\x1f\x7f]. I didn't find anything in my Info.plist.
This is my Info.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>LSApplicationCategoryType</key>
    <string></string>
    <key>CFBundleDevelopmentRegion</key>
    <string>$(DEVELOPMENT_LANGUAGE)</string>
    <key>CFBundleDisplayName</key>
    <string>My App Name</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>${PRODUCT_NAME}</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>sina</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>str</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>wx</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>str</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>qq</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>str</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>tencent</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>str</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>lineredsport</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>com.myteam.myapp</string>
            </array>
        </dict>
    </array>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        ...
    </array>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoadsInWebContent</key>
        <true/>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    <key>NSAppleMusicUsageDescription</key>
    <string>访问媒体资料库</string>
    <key>NSBluetoothPeripheralUsageDescription</key>
    <string>访问蓝牙</string>
    <key>NSCalendarsUsageDescription</key>
    <string>访问日历</string>
    <key>NSCameraUsageDescription</key>
    <string>访问相机</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>始终访问位置</string>
    <key>NSLocationUsageDescription</key>
    <string>访问位置</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>试用期间访问位置</string>
    <key>NSMicrophoneUsageDescription</key>
    <string>访问麦克风</string>
    <key>NSMotionUsageDescription</key>
    <string>访问运动与健康</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>滚球体育会在修改头像和发布推荐时使用您的相机,是否允许?</string>
    <key>NSRemindersUsageDescription</key>
    <string>访问提醒事项</string>
    <key>UIAppFonts</key>
    <array>
        <string>DIN-Bold.TTF</string>
    </array>
    <key>UIBackgroundModes</key>
    <array>
        <string>remote-notification</string>
    </array>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UIStatusBarStyle</key>
    <string>UIStatusBarStyleDefault</string>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <true/>
</dict>
</plist>

following is full error message

ERROR ITMS-90037: "This bundle is invalid. The Info.plist file is missing or could not be parsed. Please check it for embedded control characters."

A: Here are the ITMS-90037 upload error stack overflow notes.
https://www.e-learn.cn/content/wangluowenzhang/1116413


text:
Q: Explain why this algorithm does not guarantee mutual exclusion Consider the following 'busy waiting' attempt for a mutual exclusion algorithm.
Explain why this does not guarantee mutual exclusion.  I can't figure out why it doesn't, to me it looks like it should can anyone explain why it doesn't?
/*Process0 */
while (flag[1]) do {/* nothing */}
flag[0] = true;
/*critical section */
flag[0] = false;

/*Process1 */
while (flag[0]) do {/* nothing */}
flag[1] = true;
/*critical section */
flag[1] = false;

A: It doesn't work because things you're apparently thinking of as atomic (i.e., inseperable) aren't anything of the sort.
Right now, you seem to assume that as soon as the while loop in one process exits, execution will continue through at least the entirety of the assignment to flag[N] without any context switches.
This simply isn't true. For the sake of argument, let's break each process into part A (the while loop) and B (the critical section). It's entirely possible to have a sequence like:
1A
2A
1B [for a while, then interrupted by context switch]
2B [for a while, then interrupted by context switch]
1B [resumes after context switch]
2B [resumes after context switch]

This is exactly the sort of code that works 99.9% of the time. You can probably test it like crazy for months on end, and it'll seem like it works perfectly--then you demo it in front of a customer, it crashes, burns, and destroys its surroundings. Then you send it back to the lab, and try though they will, they can't duplicate the problem.

A: Two things can happen here.

*

*You can have two (or more) processes running concurrently. Either one may grab
while (flag[1]) do {/* nothing */}
     // Both processes may see the flag cleared at the same time
 flag[0] = true;  // Two process set the flag

*You could have a context switch
while (flag[1]) do {/* nothing */}
     // Process gets blocked here
    // Some other process sets flag [0]

 flag[0] = true;  // Gets set for a second time


text:
Q: Trait 'Carbon\Traits\ObjectInitialisation' not found laravel5.8 Getting this error when i run project on local
tried -composer update, composer update --no-scripts

A: Solved this issue by deleting vendor folder from project and the using composer update solved my problem


text:
Q: ec2 ami for rails 3.1 apache passenger Is there an ec2 ami available with

*

*apache

*passenger

*rails 3.1

preferably ubuntu or fedora.

A: Rather than look for an AMI with the software pre-installed, simply run an official Ubuntu server AMI and install the standard Ubuntu packages for the software you want.
It's probably as simple as:
sudo apt-get update &&
sudo apt-get upgrade &&
sudo apt-get install apache2 ...

Then tweak configuration and add your content / application.
If you are trying to run a version of software more recent than the one provided with the official release, then you may need to do a bit more work.
Remember to document / script exactly how you create the instance so that you can do it again in the future when you need to.


text:
Q: How to use AuthenticationManager SignIn when using OpenId We have a need to provide Mixed Mode Authentication and we've spent weeks chasing down samples, and bits and pieces and finally we have our ClaimsIdentity properly built, we just need to figure out a way to have OWIN recognize our ClaimsIdentity as the logged in user.
Everything we've found thus far is defining app.UseCookieAutentication in Startup.Auth.ConfigureAuth().  Set AuthenticationType = "Cookies", then set a login path.
However, we use a custom version of Identity Server 3 and in addition to UseCookieAuthentication, we also use app.UseOpenIdConnectAuthentication.
We've had issues with setting the UseCookieAuthentication LoginPath.  We've tried putting something in it and leaving it empty.
Code we use to login our Windows users, we make calls to IdentityServer, get our tokens and claims.
We then use UserManager.CreateIdentityAsync as follows.
var _identity = await _userManager.CreateIdentityAsync(_slUser, DefaultAuthenticationTypes.ApplicationCookie);
Everything appears good here.
Then we use that Identity with the following code:
var _ctx = HttpContext.Current.GetOwinContext();
var _authenticationManager = _ctx.Authentication;
_authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, _identity);
The code runs but when we check _ctx.Authentication.User, the identity we created still isn't showing up which results in a user getting redirected to the login page on the Identity Server.
So in summary, we're trying to figure out how to take a ClaimsIdentity we've authenticated and built up in code and have it become of apart of the OwinContexts Authentication.User.Identities so it will be available throughout our application.


text:
Q: using Matlab, how to find the maximum value over a certain range? i want to know the coding to find the maximum value, over a certain range.
i already coded like below.
f=f'
ac_yyyy_f=ac_yyyy_f'
[row,col] = ind2sub(size(ac_yyyy_f),find(ac_yyyy_f==max(ac_yyyy_f)))

but the problem is, sometimes the maximum value of Y axis choosen by my code is not what i want.
the X axis has the range of 0 to 100000 and i want the maximum between 20000 to 100000. the problem is sometimes the max value show up at the range of 0 to 20000.
How can i figure this out?

A: Use the max() function:
%let R be your range of values
R = [2 1 7 4];
[value, index] = max(R);

In the above example, value will be 7 and index will be 3
For more info: http://fr.mathworks.com/help/matlab/ref/max.html

A: I'm using a vector of random integers to stand in for your function output.
a = floor(rand(1,100000)*100);
[val, idx] = max(a(20000:100000));

You want to use the max function here to find the maximum value rather than find.
Now, the other part of the task is getting the max value from a certain part of your matrix. You can pass just a subset of a vector or matrix to a function by indexing it with a range of values. Note that idx gives you the position of val within a(20000:100000). If you need the position within a, you need to use idx+19999.
Also, you should take a look at the matrix indexing reference—there are many different and fun ways to index a matrix—because indexing is one of the most important features of matlab.
Here's the reference for the max function:
http://www.mathworks.com/help/matlab/ref/max.html
And the reference for indexing:
http://www.mathworks.com/help/matlab/math/matrix-indexing.html

A: You can use the max function with a subset of your array. It will return the maximum value, as well as the index where it is located. Be sure to correct the index it returns you based on your desired range. Like this:
%//create an array of 100,000 values to play with.
f=floor(rand(100000,1).*100);

%//find the max between f(20000) and f(100000)
[myMax, I] = max( f(20000:100000) );

%//correct the index based on where we started looking
%//for the max. Subtract 1 because it's MATLAB!
myIndex = I+20000-1;

This results in:
>> myMax
myMax =
    99
>> myIndex
myIndex =
       20045
>> f(myIndex)
ans =
    99


text:
Q: I have no idea how to solve this There are $14$ more cookies than biscuits in a jar of $38$ cookies and biscuits. How many cookies are in the jar?

A: Solve the following system. $$x-y=14$$ and $$x+y=38$$

A: Think of starting with a jar of $38$ cookies and no biscuits, and  turning cookies into biscuits one by one.  Each time you do this you reduce the excess of cookies over biscuits by $2$.  How many times would you have to do it to make that excess be $14$?

A: A non algebraic technique useful for simpler word problems: hypothesise, i.e. start with Suppose...
Suppose you removed those "extra" $14$ cookies.
What's the total number of snacks now?
Can you see that the remaining biscuits and cookies are now equal in number?
Can you figure out how many cookies you have now?
Can you work out how many you started with before you removed $14$?


text:
Q: Extracting geographic coordinates/numerics from webpage I have some code to try to collect some information from a website:
I can connect and read in the HTML data using (thanks to this post):
library(RSelenium)
library(rvest)
rD <- rsDriver(browser="firefox", port=4536L)
remDr <- rD[["client"]]
#navigate
url = 'https://www.fotocasa.es/es/comprar/viviendas/a-bana/todas-las-zonas/l'
remDr$navigate(url)
#accept cookies
remDr$findElement(using = "xpath",'/html/body/div[1]/div[4]/div/div/div/footer/div/button[2]')$clickElement()

#click on Zona
remDr$findElement(using = "xpath", '//*[@id="App"]/div[2]/div/div[2]/div[3]/div/div[1]/div')$clickElement()

# read html page
html_full_page = remDr$getPageSource()[[1]] %>% read_html()

I am a little stuck on trying to collect one piece of data. I run the following and want to extract the numeric results from:
html_full_page %>%
  html_nodes('.re-GeographicSearchNext-checkboxItem') %>%
  html_nodes('label')

{xml_nodeset (4)}
[1] <svg viewbox="0 0 24 24"><path d="M19.2 5.4a1 1 0 0 1 1.669 1.095L ...
[2] A Baña<span class="re-GeographicSearchNext-ch ...
[3] <input type="checkbox" id="geoSearch-724,12,15,487,0,15056,0,0,0" name="geoSearch-724,12,15,487,0,15056,0,0,0" intermediate="">
[4] Negreira     [1] " href=\"/es/comprar/viviendas/a-bana/todas-las-zonas/l\">
 class=\"sui-MoleculeCheckboxField\">
 sui-MoleculeField--inline sui-MoleculeField--inline-reverse
> sui-MoleculeField--fullWidth\">\n
 class=\"sui-MoleculeField-labelContainer\">\n class=\"sui-AtomCheckbox sui-AtomCheckbox--medium\"><input
> type=\"checkbox\" id=\"geoSearch-724,12,15,487,0,15007,0,0,0\"
> name=\"geoSearch-724,12,15,487,0,15007,0,0,0\"
> intermediate=\"\">
 class=\"sui-MoleculeField-nodeLabelContainer\"> class=\"re-GeographicSearchNext-checkboxItem-label\"
> name=\"geoSearch-724,12,15,487,0,15007,0,0,0\"> class=\"re-GeographicSearchNext-checkboxItem-literal\">A
> Baña re-GeographicSearchNext-checkboxItem-count-is-child\">17
\n
\n
 class=\"sui-MoleculeField-inputContainer
> sui-MoleculeField-inputContainer--aligned\">
\n

"
>
>     [2] " title=\"Negreira\"
> href=\"/es/comprar/viviendas/negreira/todas-las-zonas/l\">
 class=\"sui-MoleculeCheckboxField\">
 sui-MoleculeField--inline sui-MoleculeField--inline-reverse
> sui-MoleculeField--fullWidth\">\n
 class=\"sui-MoleculeField-labelContainer\">\n class=\"sui-AtomCheckbox sui-AtomCheckbox--medium\"><input
> type=\"checkbox\" id=\"geoSearch-724,12,15,487,0,15056,0,0,0\"
> name=\"geoSearch-724,12,15,487,0,15056,0,0,0\"
> intermediate=\"\">
 class=\"sui-MoleculeField-nodeLabelContainer\"> class=\"re-GeographicSearchNext-checkboxItem-label\"
> name=\"geoSearch-724,12,15,487,0,15056,0,0,0\"> class=\"re-GeographicSearchNext-checkboxItem-literal\">Negreira re-GeographicSearchNext-checkboxItem-count-is-child\">52
\n
\n
 class=\"sui-MoleculeField-inputContainer
> sui-MoleculeField-inputContainer--aligned\">
\n

"

A: This should do it:
html_full_page %>%
  html_nodes('.re-GeographicSearchNext-checkboxItem') %>%
  html_nodes('label') %>%
  html_attr("name") %>%
  gsub("geoSearch-", "", .) %>%
  na.omit()

# [1] "724,12,15,487,0,15007,0,0,0" "724,12,15,487,0,15056,0,0,0"
# attr(,"na.action")
# [1] 1 3
# attr(,"class")
# [1] "omit"


text:
Q: Speed up declaring variables? I have a bunch of Variables I need to declare and was wondering if there's any way to shorten the amount of lines needed to do so.  Here's the code:
Sub test()
dim comps as New Collection
dim noOfCompanies as Integer: noOfCompanies = 25
dim c1 as New Names 'Names is a class I have made
dim c2 as New Names
... ' in this gap is c3 to c29
dim c30 as New Names
End Sub

I don't know that you can create a variable and do something like the following, can you? (Note: Psuedocode)
dim i as Integer
for i = 1 to 30
    Dim "c" & i as New Names
next i

edit:
@rene mentioned using an array - how would I do so, if later I'm going to set parts of the class properties (sorry, I'm learning classes and don't know the proper terms):
c1.companyCode = 10: c1.companyCountry = "USA": c1.companyName = "Batman LTD"
c2.companyCode = 13: c2.companyCountry = "Krypton": c2.companyName = "Superman LLC"
... 'etc until c30.

Here's what I'm trying so far, but to no avail:
Dim tempC As String, tempN As String
For i = 1 To noOfCompanies
     c(i) = "c" & i
     tempC = c(i)

     Debug.Print tempC 'This will correctly print "c1", "c2", "c3", etc.

     Dim c(i) As New Names 'This is where I can't figure out how to declare the different array parts as an individual "new Names" class part.
     Debug.Print tempN
Next i

edit2:
Here's why I'm trying to create 30 variables.  I get a spreadsheet every week that has a column of codes (the codes being that companyCode I am initializing above).  If I find a row with any of the 30 codes I am trying to declare, then I need the companyName and companyCountry to be placed in some other cells on that row.  My idea was to be able to just do something like this (psuedocode):
dim rng as Range
rng = Range("A1:A30") 'this has the codes in it, i.e. 13, 10, 11, 20...
for each cel in Rng
   'here would be code where I just check for IF the cel.Value is anywhere in companyCode,
   'return its equivalent companyCountry and companyName
    next cel

So, would a dictionary be best? I could do like
if dict.exists(cel.value)

BUT how could I store the companyCountry and companyName in the same dictionary entry, AFAIK I can only store one key per entry?
...of course, if just saving this info in an excel table somewhere (xlsx or csv) and just opening/using that then closing would be best practice, just let me know!

A: Dim arrNames(1 to 30) as Names, n

for n=1 to 30
    Set arrNames(n)=new Names
next n

arrNames(5).companyCountry = "USA"

EDIT: I think storing your code information on a worksheet and accessing it directly is the "best" approach unless you need high-volume/high-performance lookups (even then it will not be bad...)
For example here's a pretty simple function you can call from VBA:
Function CompanyInfo(companyCode, infoType As String)

    Dim rng As Range, colNum As Long, rv

    Select Case infoType
        Case "Country": colNum = 2
        Case "Name": colNum = 3
        Case Else
            CompanyInfo = "InfoType?"
            Exit Function
    End Select

    rv = Application.VLookup(companyCode, _
                           ThisWorkbook.Sheets("Codes").Range("A2:C100"), _
                           colNum, False)

    CompanyInfo = IIf(IsError(rv), "???", rv)

End Function

Usage:
Dim v, v2
v = CompanyInfo(10,"Country")
v2 = CompanyInfo(10,"Name")

A: Why don't you store your c1, ... c30 objects properties in a table, an xml file, a csv file, or any other of the multiple types of files? That can store data and be read via VBA.
So, when needed, you can just open the table, and populate an array of your object's properties with the values in the table? If your table/file contains 30 lines, an array of 30 objects will then be created.
By doing this, you will also separate your code from your data, which is usually considered as a best practise.

A: I'm not sure if I like the use of "Names" as a class name since "Names" already has an Excel VBA meaning, but if that's what you want.
As others have pointed out, an array is probably the way to go. But if you really want to have 30 variables and you don't want to do a lot of typing, you can do something like this:
Sub DeclareVars()
    Dim i As Long, v As Variant
    ReDim v(1 To 30)
    For i = 1 To 30
        v(i) = "c" & i & " As New Names"
    Next i
    Debug.Print "Dim " & Join(v, ", ")
End Sub

Run it once and copy the result from the immediate window into your code. If you know Python you can use a 1-liner in the Python shell and type even less. Just evaluate:
"Dim " + ", ".join('c' + str(i) + " As New Names" for i in range(1,31))

A: Example using a collection to create 30 instances of a class containing the name.
If it is imperative that they be able to be retrieved using "c1-c30", then you can either use that as a variable in the class (like Name) or as the collection index/key.
For example:
Names Class:
Private pName As String
Private pOther As Integer

Public Property Get Name() As String
    Name = pName
End Property
Public Property Let Name(Value As String)
    pName = Value
End Property

Assigning and Printing our 30 Names:
Sub Test()

Dim MyNames As Collection
Set MyNames = New Collection
Dim x
For x = 1 To 30
    Dim t As Names
    Set t = New Names
    t.Name = "c" & x
    MyNames.Add t
Next x

Dim y
For Each y In MyNames
    MsgBox (y.Name)
Next y

End Sub

In closing, I think your problem is that you want to be able to reference these 30 cnames in your code by name later after having assigned them. That's not going to work and it's a bad coding practice. You shouldn't do:
Dim c1
Set c1 = new Names
c1.Name = "Bob"
Dim c2 '...

There's a reason people don't typically declare 30 variables with incremental numbers. The reason is because there is a better way. That way is typically using a collection of variable types or an array of variable types that you can reference using an index or a loop.
If you're creating 30 instances of a certain data type, and you want to give them each unique values, create a table or even a static array to hold their values and assign them in a loop.
To follow up, if you want to reference them using c & x then add a variable to your class called ID and assign to that.
You might want to look into using a dictionary if you would like to be able to quickly retrieve the ID without looping through and checking ID's.
Edit:
I'm glad you explained your end game. You are absolutely over-complicating this scenario.
A simple VLOOKUP formula and a lookup table would save you from having to code anything in VBA at all.
Example:
Create a named range called LookupTable that contains the company ID's on the far left:

Then, use these formulas to search your table for the ID, and give you the name/location.
Parameter 1 is the value to Lookup
Parameter 2 is our LookupTable
Parameter 3 is the column from our table to return
(1 = ID, 2 = Company Name, 3 = City)
Parameter 4 says we want an exact match only.
=VLOOKUP(A1,LookupTable,2,FALSE)


text:
Q: Form breaks page I coded a website, and am currently in the process of re-coding it. On my contact page, I have a form for questions, comments, etc. On the original website, the page works fine - however on the recode, the form breaks the page. I was wondering if someone could help me figure out why.
Original page found here: http://path-to-truth.org/contact/
Recode found here: http://path-to-truth.org/Recode/contact/

A: ul#nav has a margin-right of 7% in your style.css file. When I remove that, it looks normal. The margin is added to the right of the navigation. Because that make the block too large for the header, it moves down. Because you have float:right on that element also, it is put to the right of the h1.
Another option would be to remove the float: right on the navigation and put float: left on the image (or the a tag). At the bottom of your div#header, insert (inside the div) a new div with clear: both to pull the header region down.


text:
Q: In an eclipse plugin: How can I programmatically highlight lines of codes in the java editor? I am trying to develop an eclipse plugin that does some documentation check on java code and highlights some lines of code in the editor.
To achieve my goal, I DON'T want to create a new editor in eclipse, I simply want to extend the default java editor to draw a line under (or highlight) the methods that do not satisfy some set of predetermined requirements.
Do I need to create a PresentationReconciler? If yes, how do I make the JDT or workbench use my reconciler.
I have never done plugin development and this is my first attempt.

A: Several starting points for you:

*

*Annotations are an UI feature of JFace's text editor that allows you to visually mark some places in an open editor.

*Markers are a Workbench feature, more high-level. They are generic "objects that may be associated with Workbench resources", and they can display in several places: in text editors (as annotations) or in the Problems view, for example.
Depending on what you want to do, you would plug in your plug-in into extension points related to either of those.

A: The Eclipse Java editor is located in the org.eclipse.jdt.internal.ui.javaeditor.JavaEditor package.
The "internal" in the package name means that the Eclipse development team can change how the Java editor works with new revisions.

A: Try this help page: Juno Help on syntax highlighting
At the end of the page, it describes how to dynamically add a PresentationReconciler, which is used for syntax highlighting. See if that fits the problem that you want to solve.

A: I assume you already have a plugin project.
In your plugin.xml, open the tab Extensions, click Add..., search for org.eclipse.ui.editors, then you should see a template named Editor, which will produce a simple xml editor to experiment and play with. Also, you will be able to see the needed structure to define a custom editor.
Hope this helps...

A: I don't know if you still have a need for this, but you are going to want to use Annotations to keep track of what parts of the editor you need to highlight.
For actually doing the graphical effect of highlighting, you could do syntax highlighting via a PresentationReconciler, but I have no experience with that.
We used a technique we borrowed from http://editbox.sourceforge.net/, replacing the background image of the editor Shell.  Its open source, so check it out.  (Our code might also help -- its at https://github.com/IDE4edu/EclipseEditorOverlay )


text:
Q: Loading a bundle from Objective C class public func dataFromFile(_ filename: String) -> Data? {
   @objc class TestClass: NSObject { }
   let bundle = Bundle(for: TestClass.self)
   if let path = bundle.path(forResource: filename, ofType: "json") {
      return (try? Data(contentsOf: URL(fileURLWithPath: path)))
   }
   return nil
}

I found this code in a tutorial and am confused on what these two lines do:
@objc class TestClass: NSObject { }
let bundle = Bundle(for: TestClass.self)

I know we have the main bundle for the app but why is it creating a bundle for an objective c class called TestClass?

A:
I know we have the main bundle for the app but why is it creating a bundle for an objective c class called TestClass?

The second bundle is usually a framework. Since the code is from a tutorial, likely the author wants to explain, what bundles are and how you access them.
Having a class you do not need to do that, because the runtime environment searches for the right bundle of a class. But if you want to load other resources (videos, images, sounds, and so on), you have to do it you own. To get the right bundle, you can ask a class residing there for its bundle.


text:
Q: Obtaining a Pool ID to deploy OpenShift Origin I'm trying to automate the deployment of OpenShift Origin into AWS, because it's a dependency of another product which I also need to deploy on demand. There are various solutions for this, but they all require a Pool ID at some point in the process. What is a Pool ID? I realise it's associated with a Redhat subscription, but can I script the generation of a Pool ID? And if so, is it necessary to treat it as a secret?

A: You can obtain the subscriptions available pool with :
subscription-manager list --available --pool-only

If you are many subscription, you can filter the result with --matches option (filter can contain regex)  :
  --matches=FILTER_STRING
                    lists only subscriptions or products containing the
                    specified expression in the subscription or product
                    information, varying with the list requested and the
                    server version (case-insensitive).


text:
Q: How to create attribute in flexcontainer in oneM2M? I am trying to create attribute in flexcontainer in oneM2M, i have created container and contentinstance in oneM2M. Now I need to use flexcontainer.

A: I guess from your question that you try to directly create a <flexContainer> resource. That is not possible. The <flexContainer> can be viewed as an "abstract base class" that needs to be further specified. In oneM2M these derived resource types are called specialisations. A specialisation takes all the resource specific attributes from the <flexContainer> and adds the custom attributes that actually represent the functional part. This specialisation can now be created, retrieved etc like any other resource.
Take, for example, the clock specialisation that is defined in oneM2M's TS-0023 document. It adds three new custom attributes, namely currentTime, currentDate, and currentTimeZone in order to represent a clock functionality.
Please note that the CSE implementation you are using needs to support the <flexContainer> resource type in general, and the specific specialisations you want to use. If you want to create your own specialisations then the CSE must support user-defined specialisations and their validations as well.
The oneM2M specifications are available here: https://www.onem2m.org/technical/published-specifications


text:
Q: Numbers formed from all the digits $1113333344455678$ so that $6$ and $8$ are on dofferent sides from $7$
How many numbers formed from all the digits $1113333344455678$ are there if the digits $6$ and $8$ have to appear from the different sides of the digit $7$?

My thoughts:
I thought I should first find how many numbers are formed from all the $14$ digits $11133333444557,$ which is $$\binom{14}3\binom{11}5\binom63\binom32=\frac{14!}{3!5!3!2!},$$and, then, analyze the possibilies given a position of the digit $7,$ but then, I lose the track and I only tell for sure $6$ and $8$ can be first and last digits in every situation, so there are strictly more numbers than $2\frac{14!}{3!5!3!2!}=\frac{14!}{(3!)^25!}.$
Then, I thought, I should first consider the position $p, 1<p<16$ among $16$ overall places for $7$ and choose the positions in $p-1$ and $16-p$ ways for $6$ and $8$ and multiply the result by $2$ for each $p,$ but this didn't lead me anywhere.
How should I approach this problem?

A: One of the approaches is to see that once three  positions are decided for $6, 7$ and $8$, you can arrange them within, in $3! = 6$ ways but here instead of $6$, there are only $2$ ways to arrange them as $7$ must be in between $6$ and $8$.
So we first find all possible arrangements of $1113333344455678$ and then divide by $3$ to get all favorable arrangements.
So the answer is $ ~ \displaystyle \frac{1}{3} \cdot \frac{16!}{3! \cdot 5! \cdot 3! \cdot 2!}$

Also sharing a longer approach - first arrange $13$ numbers other than $6, 7$ and $8$. Then there are $14$ places between them (including the ends). We can choose three places, two places or one place out of $14$ places for $6, 7$ and $8$. That leads to,
$ \displaystyle \frac{13!}{3! \cdot 5! \cdot 3! \cdot 2!} \left[2 \cdot {14 \choose 1} + 4 \cdot {14 \choose 2} + 2 \cdot {14 \choose 3}\right]$
Note that when we choose two places, if the first place from the left has two numbers then it must have $67$ or $87$ and if the second place has two numbers then it must have $76$ or $78$. That is why we multiply second term by $4$.