text:
Q: ssh expect command with variables I am planning to take password from file instead of passing parameter to the script
set cmd1 {`cat passwdfile.txt | grep -w pj |  cut -d";" -f5`}
spawn ssh username@servername

expect "password: "
send "$cmd1\r"
expect "$ "
send "ps -ef |grep planning1\r"
expect "$ "
send "exit\r"

Error
    username@servername's password:
    Permission denied, please try again.

Why it is not taking password from the file ??

A: At the point where ssh is asking for a password, you don't have access to a shell, so the backticks and all the rest will be sent as plain characters as the password.
Assuming that file exists on your local machine, get the password before you spawn:
set pw [exec grep -w pj passwdfile.txt | cut -d\; -f5]
spawn ssh ...
expect "password: "
send "$pw\r"

Of course it's terribly insecure to store passwords in plain text. You should set up ssh keys to allow you to log in without having to type a password.


text:
Q: Loop and Combine Time Ranges in an Array I am trying to read through an array of objects (that are start/end times) and combine two (or more) of those times if they are back to back.
ie. the first objects end time is the same as the next objects start time. If they are, combine them. Then check the newly combined objects end time with the next object in the array
Here is a simplified array of times:
var times = [
             {
              start: 1,
              end: 2
             },{
              start: 2,
              end: 3
             },{
              start: 4,
              end: 5
             },{
              start: 6,
              end: 7
             },
            ]

I would like that (or have a diff Array) to output like the below:
var newTimes = [
             {
              start: 1,
              end: 3
             },{
              start: 4,
              end: 5
             },{
              start: 6,
              end: 7
             },
            ]

It gets trickier if there are 3 times in a row.
var threeTime = [
             {
              start: 1,
              end: 2
             },{
              start: 2,
              end: 3
             },{
              start: 3,
              end: 5
             },{
              start: 6,
              end: 7
             },
            ]

The above should turn into:
var newThreeTimes = [
             {
              start: 1,
              end: 5
             },{
              start: 6,
              end: 7
             },
            ]

The original array of times will always be sorted from oldest (smallest start time) to newest (largest start time). The output does not need to be in any specific order. All time objects will be moment times.
Can someone help me solve this?

A: This is the code i have come up with
function mergeArr(arr) {

    // Sort the array in descending order
    arr.sort(function(a, b) {
        return b.start - a.start;
    });

    // Traverse from the top as you will need to remove the elements
    // Merge the elements based on start of one and end of the previous
    for (var i = arr.length - 1; i > 0; i--) {
        if (arr[i].end == arr[i - 1].start) {
            arr[i].end = arr[i - 1].end;
            arr.splice(i - 1, 1);
        }
    }

    // Sort it again in reverse order.
    return arr.sort(function(a, b) {
        return a.start - b.start;
    });
}

Comments are making the code self explanatory.
Working Fiddle

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is my computer having more fun than I am? Need tool to see what it's doing while locked
Possible Duplicate:
What applications are exactly reading/writing my HDD in a given period? Application for statistics?

I can leave my computer for an hour and come back and the disk light is running full-bore.  I sign on and the Process Explorer icon shows the CPU running about 30%.  But of course, before I can actually check to see what it's doing the activity stops (other than the interminable paging activity needed to make the system "live" again).  (It's like the teenager who hides the page he's viewing when you walk into the room.)
Is there a (free) tool (for Windows Vista) that maintains a circular journal of what's going on -- say, a snapshot taken once a minute for several hours -- so I can figure out what it's doing. (And, no, this isn't to monitor what my teenagers are doing -- they're both in their 30s now.)

A: Do you have Skype running?  It can become a "supernode" and that will create a great deal of traffic.  Torrent clinets could also do this.  Backup utilities like WD Smartware are a possibility as well. Malware infection?
3D screen savers can use a great deal of resources as well
You can start resource monitor(Perfmon.exe) and record some activity to identify the app.


text:
Q: Is there any way to use inline styles to define a:visited link style? So instead doing it using css:

Could it be done using inline code. Something like this doesn't work:
Google.com

A: You can't do this, the specification (CSS2 here) covers it briefly here:

Neither pseudo-elements nor pseudo-classes appear in the document source or document tree.

:visited along with the others modifiers are all pseudo-classes, and there was never a standard syntax setup to do what you're trying.  Honestly this is the first time I've ever seen it requested, so I don't think it'll be added to the specification anytime soon...sorry that answer sucks, but it is what it is :)

A: Just to add one motivation to achieve this inline style for the various a href states:
in some page it could appear text with link in one are where the background is different from the overall background.
The main CSS for the "a" gives them one color that is not good on that particular and singular area.
For this reason, to give the user the idea that the link is a link, you need to color that link differently from the others.
For me it worked to set some style="color: #5070BB;" inside the <a href=".." tag, but maybe that neither the a:visited nor the a:hover colors are good for that background and it would be useful to set them inline.
Yes, it is definitely a singular and lonely situation, but that is a real case.
Ciao!

A: Sure you can....

           some link

jfiddle

A: No, that's not how inline styles work. It is in the specification, however browsers don't seem to support it.

A: No. Pseduoclasses (e.g :first-child, :hover) are used as selectors based on behavior and relation to other DOM elements. Inline styles contain rules. Even if at some point browsers do support this, it'll feel weird.

A: As far as I know, it isn't supported ... but to add some clarification for the reason for wanting to do this, since it would definitely be the sub-optimal way to do it on a regular web page, the reason would be to use in HTML email, which, except for certain good email clients, does not support regular style sheets, so it's necessary to define all styles inline to ensure good support across email clients (Gmail and Outlook (ugh) come to mind.)
Of course, it's possible to use some other program that lets you import a stylesheet and automatically convert it to inline styles, which is much easier to manage (that's what I do), but you're still using inline styles in the end-analysis.


text:
Q: How can I stop my script from going back to the top of the page? I'm testing some Jquery Ajax scripts and one of them is actually quite nice. The only problem I have with it, is that when it refreshes my div, it takes you back to the top of the div.
The div loads MYSQL results from an outside php script. So if the user is halfway down the page reading, when the ajax call goes out, it takes them to the top of the div.
It's important for them to be able to read uninterrupted.
Here's my code:

So would it be possible to have just a stack effect by modifying the code, or would I need to look at a completely different option?
Also I would like to note that after so long, this script starts to fail. It gets to the point where it's constantly refreshing the div. No 20 second wait, just again and again.

A: This should stop it from going to the top:

This will make it just load instead of fading the element out and then back in.
I hope this helps.

A: You can use jQuery's .scrollTop() and .scrollLeft() to save the scroll position before loading your content and then set the scroll position back to those values after loading the content.  If the content has changed significantly above the reading position, it won't necessarily go back to the exact same position, but if the content hasn't changed significantly or if the place that it changed is below what was being viewed, it should restore back to the exact same spot.
A more complicated approach would involve identifying a marker object that's on screen and visible and using jQuery .offset() and position(), you obtain that objects location on screen and then after loading the new content, you adjust the scroll position until that marker object is again positioned in the same place.  This approach is a lot more work, but would give better results if the content changes significantly.

A: The effect occur because when the content is loaded the div probably is recreated, and that makes the browser go to the top of the div.
You can save the scroll position and try to restore it after.
But depending on what you're doing, if you're loading new content probably it will be helpfull to load the content into another hidden div and then append the new content to the visible div using the effects u want.
Hope it helps.


text:
Q: question related to number theory/algebra, a problem Let a and b be integers and n positive integer. Proof that a and b has the same remainder when divided by n if and only if there is integer k such that a-b=kn
I tried like this by contradiction:
a and b are integers and n is positive interger.
Assuming there is no integer k such that a - b = kn (If a and b has the same remainder, a - b = kn which means a is congruent to b modulo n, where k is integer.), then a - b = kn + r , where r is integer more than 0, and less than n. (if r is 0 or n, a - b = kn) If a - b = kn + r, then a is not congruent to b mod n and therefore a and b doesnt have the same remainder.
              ¬∃k∈Z(a-b=kn -> a-b=kn+r) , 1 <= r < n
              ->a-b/n = k+r
              ∴ a ≡ b (mod n) ⇔ ∃k∈Z: a-b=kn

Is it correct? I know there is different ways to solve this but I wanted to try by contradiction for a practice and also for translating it for symbols. If it doesn't make sense, I would like to know how to do it as contradiction proof.

A: I'm afraid your collection of symbols makes little sense. Mathematical proofs are not sequences of symbols where it's very easy to get lost.
Write the proof in plain language and only after you're sure it works, translate it in stenography, if you are required to.

There's no need to use contradiction.
Suppose $a$ and $b$ have the same remainder when divided by $n$, that is,
$$
a=nx+r,\qquad b=ny+r
$$
Then $a-b=(nx+r)-(ny+r)=n(x-y)$. So we can take $k=x-y$.
Conversely, suppose $a-b=nk$. Write $b=nq+r$, with $0\le r<n$. Then
$$
a=nk+b=n(k+q)+r
$$
and uniqueness of remainder ends the proof.


text:
Q: 50 === 50: false. 50 == 50: true? I'm at a total loss.
I have a function..
Number.prototype.abs = function () {
    return this >= 0 ? this : this * -1;
};

..that returns the absolute value of a number..
(50).abs(); // 50
(-50).abs(); // 50

..but that doesn't compare correctly..
(50).abs() === 50; // False

..sometimes.
(50).abs() == 50; // True
(-50).abs() === 50; // True

The thing about it, is that it works in Chrome 12, and Firefox 4, but not in IE 9, Safari 5, or Opera 11.
I don't see anything wrong with the code, and since it works in Chrome and Firefox, it's something browser specific but I don't know what.
Update: The browser specific difference is strict mode support. I run my code in strict mode, which introduces some changes that make my code work. The reason it failed in the browsers it did, is because they have an incomplete or missing strict mode.
Why is it returning false?

A: Triple equals (===) checks type as well as value to ensure they are equal. It fails for the same reason that new Number(5) !== 5 and new String("Text") !== "Text", in that they're different types. However, when you're using your negative absolute value, you're performing a mathematical computation which is outputting a raw number, and not a number object. Due to this, the type check matches and it's true.

A: Math.abs(-50) === 50 works everywhere. So you could rewrite Number.prototype.abs to:
Number.prototype.abs = function () {
    return Math.abs(this);
};

I suppose. Tested Math.abs(50) === 50 in IE9 and Chrome 11, both: true
Other ways to make (50).abs() === 50 using your method may be:
return this >= 0 ? this.valueOf() : this * -1;
return this >= 0 ? this * 1 : this * -1;

So you extension doesnt return an object (this) when > 0, but a number value.
But I would advise to just use the already available Math.abs method, in which case you can be sure that Math.abs(50) === 50; returns true and you avoid an unnecessary monkey patch.
For completeness: from the selected answer it follows that using strict would be a solution too.

A: Even though Jeremy Heiler is correct, his justification is misconstrued. Why you're getting object instead of number has nothing to do with constructors.
The problem here is the this keyword. You need to understand what happens whenever you use this. A little bit of digging through the ECMA draft will show you that

The this keyword evaluates to the value of the ThisBinding of the current execution context.

(I would change the above. The this keyword doesn't evaluate to the value of anything as we'll soon see.) Hmm, okay, but how exactly does ThisBinding work? Read on!

The following steps are performed when
  control enters the execution context
  for function code contained in
  function object F, a caller provided
  thisArg, and a caller provided
  argumentsList:

*

*If the function code is strict code, set the ThisBinding to thisArg.

*Else if thisArg is null or undefined, set the ThisBinding to the
  global object.

*Else if Type(thisArg) is not Object, set the ThisBinding to
ToObject(thisArg).

*Else set the ThisBinding to thisArg.

*Let localEnv be the result of calling NewDeclarativeEnvironment
  passing the value of the [[Scope]]
  internal property of F as the
  argument.

*Set the LexicalEnvironment to localEnv.

*Set the VariableEnvironment to localEnv.

*Let code be the value of F's [[Code]] internal property.

*Perform Declaration Binding Instantiation using the function code
  code and argumentList as described in 10.5

And therein lies the rub (look at the bolded part). If a function is ever called from a non-object context, ThisBinding (aka using this) always returns the value of the context wrapped inside an object. The easiest way to fix it would be to do:
Number.prototype.abs = function () {
    "use strict"; // if available
    // * 1 implicitly coerces 'this' to a number value
    return this >= 0 ? this * 1 : this * -1;
    //... or Number(this) explicitly coerces 'this' to its toNumber value
    return Number(this >= 0 ? this : this * -1);
};

...to coerce the this object (or to force strict mode). But I think it's important to understand how this works, and this question is a great example of that.

A: This is because 50 by itself is a Number value, whereas you are returning a Number object.
alert(typeof 50); // number
alert(typeof (50).abs()); // object

http://jsfiddle.net/Pkkaq/
Section 4.3.21 of the ECMAScript reference:

A Number object is created by using
  the Number constructor in a new
  expression, supplying a Number value
  as an argument. The resulting object
  has an internal property whose value
  is the Number value. A Number object
  can be  coerced to a Number value by
  calling the Number constructor as a
  function.

In other words, a Number value cannot be strictly equal to a Number object.
typeof 50 === typeof new Number(50) //--> false; number != object

The reason why (-50).abs() works as expected is because it is being multiplied by -1. When a Number object is multiplied by a Number value it becomes a Number value. In this case, if the parameter is positive, the object is simply returned untouched, causing an object to be returned.
Here is a fix for your method, according to the quoted reference above:
Number.prototype.abs = function () {
    return Number(this >= 0 ? this : this * -1);
};

A: The === returns true if both operands are of the same TYPE and equal in value as well.  I'll bet the implementations where it's returning false are returning a float instead of an int.

A: There is a problem is your abs method. "this" in your function is an object, so when you return "this" it is a type of object. "this"* -1 is converted to number by javascript.
As people have suggested, using Math.abs() is probably the best way to go.
If you really want your function to work then do this:
Number.prototype.abs = function () {
    return this >= 0 ? parseInt(this) : this * -1;
};

Of course, this is assuming you're working with integers only.


text:
Q: What does the error rate mean in Naive Bayes. Can anyone explain what the Bayes error rate is in Naive Bayes, for instance in matlab:
[class, err]  = classify(UnseenTestdata, training_data, target_class,'diaglinear')

I get an error rate (err) of 0.5040 what does this mean? Im not a math orientated person so plain english would help. Is this good, bad or very ugly?

A: From the matlab help function:

Err is  an estimate of the
      misclassification error rate that is based on the training data.
      CLASSIFY returns the apparent error rate, i.e., the percentage of
      observations in the TRAINING that are misclassified, weighted by the
      prior probabilities for the groups.

So, if 0.5 is close to your guessing rate you are doing poorly, otherwise it's not bad.


text:
Q: Regular Expressions (.NET) - How can I match a pattern that contains a variable number of digits at the end of the string? string src = "portfolio1, portfolio2, portfolio20, portfolio300";

I'd like to match all strings that are of the pattern @"portfolio\d"
where \d can be anywhere from 1-3 digits in length. I have read that the use of {a, b} should work, so I tried:
pattern = @"portfolio\d{1, 3}"

Searching in the string, src, for this pattern returned an empty set. the following patterns worked partially:
pattern = @"portfolio\d"
pattern = @"portfolio\d{1}"

A: Try this:
pattern = @"portfolio\d{1,3}"

Note that you should not put a space in between the brackets, as you have in your example.  That's why it didn't work right.

A: Running pattern "portfolio\d{1,3}" in Expresso, I get 4 matches on each of the portfolios. The space did it was the key.

A: String pattern = @"^(?:(?:portfolio\d{1,3})(?:\x2C\s)*)+$";

My attempt. Will match any number of comma-seperated portfolio\d{1,3}'s


text:
Q: I have a Strange output i do not expect. its similar but.. well odd So ive taken up Prolog and im trying to learn the ropes of it. Right now im working on a assignment set by the book and ive come quite far. My output nearly matches that which is required but somehow its makes the last few lests that come out come out in a head|tail format in which the tail is a row of dots?
The code ive written looks like this:
%prefix methode. E1 + L = L1
% It takes L, adds E1 in front of it and makes it L1.
prefix(_,[],[]).
prefix(El,[LHead|LTail],[Q|L1]) :- Q = [El|LHead], prefix(El,LTail,L1).

gray(0,[[]]).
gray([],[]).

% this should generate a list of all the gray
% code possibilities with the defined length

gray(N,Lijst) :-  N > 0, X is N - 1, gray(X,Prevlist),
reverse(Prevlist, RevPrevlist), prefix(0,Prevlist,Deel1),
prefix(1,RevPrevlist,Deel2), append(Deel1,Deel2,Lijst).

Now the thing it should do is if I give him for example -?gray(3,List).
It should tell me:
List = [[0,0,0],[0,0,1],[0,1,1],[0,1,0],[1,1,0],[1,1,1],[1,0,1],[1,0,0]].

However what it tells me instead is:
List = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0], [1, 1, 0], [1, 1, 1], [1, 0|...], [1|...]].

As you can see with the output I get my last two lasts have a head|tail construction with a tail consisting of dots. However I do not know what this means or what I did wrong in my code.
Can anybody elaborate why I am getting the dots, and maybe steer me in the right direction to help me solve the problem?
P.S. my apologies if I might've been unclear on certain parts. If I've been so, please say so and I'll try to edit/elaborate.

A: I just ran this through on swi-prolog:
2 ?- grey(3, List).
Correct to: "gray(3,List)"? yes
List = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0], [1, 1, 0], [1, 1, 1], [1, 0|...], [1|...]] [write]
List = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0], [1, 1, 0], [1, 1, 1], [1, 0, 1], [1, 0, 0]]

Notice where it said [write].. I press the 'w' button at that point which forces swi-prolog to dump out the whole list, not just appreviate it with the ...
Not sure if that helps, or if the answer is correct.
If not, suggest explaining the problem/assignment itself in a bit more detail. You've explained your solution in some detail, but it's not clear what the problem is ?  To me, anyway.
Edit I see you have edited to clarify.. yep, just looks like prolog was abbreviating the results visually, but was actually holding the correct result. A 'display only' issue.


text:
Q: Regular Expression alternation in conditional statement Is there anyway in php to use alternation in a condition as part of a conditional statement? For example:
Imagine I had two backreferences "1" and "2" and needed to check whether either of them existed in order to carry out one of two patterns, like so
(?(1|2)foo|bar)

I'm using php 5.2.14 so don't have the benefit of escaping backreferences. Everytime I try anything remotely like this I get a compile error...
Is there any possible work-around or is it a case of doing a conditional within a conditional?
Regards
Chris

A: There is no syntax for this I know of. All you can do is:
(?(1)foo|(?(2)foo|bar))


text:
Q: Delaying header view rendering until model loaded to prevent flicker My page has header, content and footer.

I have binding in header section, how can I delay header view rendering until model loaded to prevent flicker ? I do not want the user to see this while ajax data is loading.

I have checked this post, it only will works for the ng-view.
My page header and footer are part of the master page, they are not governed by $routeprovider

A: Try ng-cloak. It will hide the page until angularJS is ready.

A: Try adding a conditional attribute in the header tag.


text:
Q: Saving in mongoDb with Mongoose, unexpected elements saved When I write in my mongoDB with mongoose the operation is treated with success, my document is saved, but there is also all kind of weird other sutff written down. It seems to be mongoose code. What could cause this?
I add stuff in a specific array with:
resultReference.ref[arrayLocation].allEvents.push(theEvent);

{id: 11, allEvents: [] } is the structure of a ref element, and I push theEvent in the allEvents array. I then resultReference.save()
I use express, mongoose and mongoHQ for database. I tried on a local mongo server, and this annoyance is still there. I've print in my console the document to write before save() and non of this weird code is there.
{
id  11
allEvents
[
0
{
_events
{
maxListeners    0
}
_doc
{
_id {"$oid": "4eb87834f54944e263000003"}
title   "Test"
allDay  false
start   2011-11-10 13:00:00 UTC
end 2011-11-10 15:00:00 UTC
url "/test/4eb87834f54944e263000002"
color   "#99CCFF"
ref "4eb87834f54944e263000002"
}
_activePaths
{
paths
{
title   "modify"
allDay  "modify"
start   "modify"
end "modify"
url "modify"
color   "modify"
ref "modify"
}
states
{
init
{ }
modify
{
title   true
allDay  true
start   true
end true
url true
color   true
ref true
}
require
{ }
}
stateNames
[
0   "require"
1   "modify"
2   "init"
]
}
_saveError  null
_validationError    null
isNew   true
_pres
{
save
[
0
function (next) {
    // we keep the error semaphore to make sure we don't
    // call `save` unnecessarily (we only need 1 error)
    var subdocs = 0
      , error = false
      , self = this;

    var arrays = this._activePaths
    .map('init', 'modify', function (i) {
      return self.getValue(i);
    })
    .filter(function (val) {
      return (val && val instanceof DocumentArray && val.length);
    });

    if (!arrays.length)
      return next();

    arrays.forEach(function (array) {
      subdocs += array.length;
      array.forEach(function (value) {
        if (!error)
          value.save(function (err) {
            if (!error) {
              if (err) {
                error = true;
                next(err);
              } else
                --subdocs || next();
            }
          });
      });
    });
  }
1   "function checkForExistingErrors(next) {
if (self._saveError){
next(self._saveError);
self._saveError = null;
} else {
next();
}
}"
2   "function validation(next) {
return self.validate.call(self, next);
}"
]
}
_posts
{
save
[ ]
}
save
function () {
      var self = this
        , hookArgs // arguments eventually passed to the hook - are mutable
        , lastArg = arguments[arguments.length-1]
        , pres = this._pres[name]
        , posts = this._posts[name]
        , _total = pres.length
        , _current = -1
        , _asyncsLeft = proto[name].numAsyncPres
        , _next = function () {
            if (arguments[0] instanceof Error) {
              return handleError(arguments[0]);
            }
            var _args = Array.prototype.slice.call(arguments)
              , currPre
              , preArgs;
            if (_args.length && !(arguments[0] === null && typeof lastArg === 'function'))
              hookArgs = _args;
            if (++_current < _total) {
              currPre = pres[_current]
              if (currPre.isAsync && currPre.length < 2)
                throw new Error("Your pre must have next and done arguments -- e.g., function (next, done, ...)");
              if (currPre.length < 1)
                throw new Error("Your pre must have a next argument -- e.g., function (next, ...)");
              preArgs = (currPre.isAsync
                          ? [once(_next), once(_asyncsDone)]
                          : [once(_next)]).concat(hookArgs);
              return currPre.apply(self, preArgs);
            } else if (!proto[name].numAsyncPres) {
              return _done.apply(self, hookArgs);
            }
          }
        , _done = function () {
            var args_ = Array.prototype.slice.call(arguments)
              , ret, total_, current_, next_, done_, postArgs;
            if (_current === _total) {
              ret = fn.apply(self, args_);
              total_ = posts.length;
              current_ = -1;
              next_ = function () {
                if (arguments[0] instanceof Error) {
                  return handleError(arguments[0]);
                }
                var args_ = Array.prototype.slice.call(arguments, 1)
                  , currPost
                  , postArgs;
                if (args_.length) hookArgs = args_;
                if (++current_ < total_) {
                  currPost = posts[current_]
                  if (currPost.length < 1)
                    throw new Error("Your post must have a next argument -- e.g., function (next, ...)");
                  postArgs = [once(next_)].concat(hookArgs);
                  return currPost.apply(self, postArgs);
                }
              };
              if (total_) return next_();
              return ret;
            }
          };
      if (_asyncsLeft) {
        function _asyncsDone (err) {
          if (err && err instanceof Error) {
            return handleError(err);
          }
          --_asyncsLeft || _done.apply(self, hookArgs);
        }
      }
      function handleError (err) {
        if ('function' == typeof lastArg)
          return lastArg(err);
        if (errorCb) return errorCb.call(self, err);
        throw err;
      }
      return _next.apply(this, arguments);
    }
errors  null
}
]
}
]

A: The reason this happened is because I didnt save my schema in mongoose in the proper order. This would mean declaring your child schema before a parent to get proper behavior.


text:
Q: C# additional threads decreases efficiency of application I wanted to stress test my new cpu. I made this in about 2 mins.
When I add more threads to it, the efficiency of it decreases dramatically. These are results: (Please note I set the Priority in the taskmanager to High)
1 Thread: After one minute on 1 thread(s), you got to the number/prime 680263811
2 Threads: After one minute on 2 thread(s), you got to the number/prime 360252913
4 Threads: After one minute on 4 thread(s), you got to the number/prime 216150449
There are problems with the code, I just made it as a test. Please don't bash me that it was written horribly... I've kinda had a bad day
    static void Main(string[] args)
    {
        Console.Write("Stress test, how many OS threads?: ");
        int thr = int.Parse(Console.ReadLine());
        Thread[] t = new Thread[thr];
        Stopwatch s = new Stopwatch();
        s.Start();
        UInt64 it = 0;
        UInt64 prime = 0;
        for (int i = 0; i < thr; i++)
        {

            t[i] = new Thread(delegate()
            {

                while (s.Elapsed.TotalMinutes < 1)
                {
                    it++;
                    if (it % 2 != 0)// im 100% sure that x % 2 does not give primes, but it uses up the cpu, so idc
                    {
                        prime = it;
                    }
                }
                Console.WriteLine("After one minute on " + t.Length + " thread(s), you got to the number/prime " + prime.ToString());//idc if this prints 100 times, this is just a test

            });
            t[i].Start();

        }

        Console.ReadLine();

    }

Question: Can someone explain these unexpected results?

A: Your threads are incrementing it without any synchronization, so you're going to get weird results like this. Worse, you're also assigning prime without any synchronization.

*

*thread 1: reads 0 from it, then gets unscheduled by the OS for whatever reason

*thread 2: reads 0 from it, then increments to 1

*thread 2: does work, assigns 1 to prime

*... thread 2 repeats for awhile. thread 2 is now up to 7, and is about to check if (it % 2 != 0)

*thread 1: regains the CPU

*thread 1: increments it to 1

*thread 2: assigns 1 to prime --- wat?

The possibilities get even worse as you get to the point where a bit in the high half of it is changing because 64-bit reads and writes are not atomic either although these numbers are a little larger than in the question, after running for longer, wildly variable would be possible ... consider
After some time it = 0x00000000_FFFFFFFF

*

*thread 1 reads reads it (both words)

*thread 2 reads the higher word 0x0000000_????????

*thread 1 calculates it + 1 0x00000001_00000000

*thread 1 writes it (both halves)

*thread 2 reads the lower word (and puts this with the already read half) 0x00000000_00000000
While thread 1 was incrementing to 4294967296, thread 2 managed to read 0.

A: You should apply keyword volatile to variable it and prime.


text:
Q: How to make bootstrap button dropdown menu selectable by keyboard Bootstrap button dropdown: http://twitter.github.com/bootstrap/components.html#buttonDropdowns
When i select a button dropdown, i would like to use keyboard up/down to navigate between menu items and press enter to select one, just like http://twitter.github.com/bootstrap/javascript.html#dropdowns
Any ideas?

A: Possible reasons that this may not work in some cases:

*

*Because you use a
 or a  for .dropdown-toggle. Make it a <button> and it will work. Strange enough, not even this kind of element works: span.btn.btn-default.

*Make sure your  element inside each
 have an attribute of href="#" or href="" or generally has the attribute defined.

*Make sure you have the role="menu" on the .dropdown-menu element.

A: Bootstrap has native support for keyboard navigation.
Just add role="menu" to your dropdown-menu
Here is an example, just save as .html and take a test

  <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

    <button class="btn btn-default">1</button>
    <button class="btn btn-default">2</button>
    <button class="btn btn-default">3</button>

    <button class="btn btn-default dropdown-toggle" data-toggle="dropdown">menu</button>

 one

 two

 three

http://jsfiddle.net/damphat/WJS9p/


text:
Q: Maven dependency scope change from Compile to Provided not working I have a following dependency in maven pom.xml:
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxb-provider</artifactId>
        <version>3.0.9.Final</version>
        <scope>provided</scope>
    </dependency>

Maven 3 build shows:
[DEBUG]    org.jboss.resteasy:resteasy-jaxb-provider:jar:3.0.9.Final:provided
[DEBUG]       com.sun.xml.bind:jaxb-impl:jar:2.2.7:compile

According to the table in Dependency Scope maven docs the Compile scope in transitive dependency should change to Provided.
Can somebody explain why the scope of jaxb-impl is Compile (and it is added to the lib directory of a war module)?


text:
Q: C++: Passing a linked list to a static function I have written a set of functions which together build a list of "Hubs" from a .csv file. I wish to generate a linked-list of these hubs in my main function I have a "head" pointer that I can pass to other functions in main.
The code in main:
HubNode *hh = NULL;
HubNode **head;
*head = hh;
Tools::loadHubs(head);
cout << hh->name; /* HubNodes have a string called "name" */

The code in Tools:
void Tools::loadHubs(HubNode **head)
{
  string line, name, location;
//  headFlights = currFlights = prevFlights = NULL;

  ifstream myfile("Hub.csv");
  if (myfile.is_open())
  {
    while (getline(myfile, line)) {// Omit the Caption Line.
      while (getline(myfile, name, ','))//Get every value in order.
      {
        getline(myfile, location, '\n');
//        cout << line << "\n";
//        cout << name << "\n";
//        cout << location << "\n";
        HubNode::AddHub(name, location, head);
      }
    }
    myfile.close();
  }
  else { cout << "\nUnable to open file\n"; }
}

The code in HubNode:
void HubNode::AddHub(string sname, string slocation, HubNode **head)
{
  HubNode* newNode = new HubNode;
  HubNode *point;

  newNode->next = NULL;
  newNode->name = sname;
  newNode->location = slocation;

  if (*head != NULL)
  {
    HubNode *curr = *head;
    while (curr->next != NULL)
    {
      curr = curr->next;
    }
    curr->next = newNode;
  }
  else
  {
    point = newNode;
    *head = point;
  }
}

I thought that using a double pointer to the head of the list in this way would work, so that from "hh" in main, I would have access to the whole linked-list.
When I compile and start debugging, I can see that AddHubs is successfully creating the HubNodes in its scope, But when I try to access any of the elements from main (e.g. by cout << hh->name), I get a segmentation fault.
What have I done wrong? (Let me know if I need to post more code...)

A: You wouldn't do this:
int value = 10;
int *p;
*p = value;

So why would you think this would work:
HubNode *hh = NULL;
HubNode **head;
*head = hh;

The indirection is the same, only the type has changed. And both snippets invoke undefined behavior. This code should do this:
HubNode *hh = NULL;
Tools::loadHubs(&hh);
cout << hh->name;

Further, your add function should be:
void HubNode::AddHub(const string& sname, const string& slocation, HubNode **head)
{
  HubNode* newNode = new HubNode;
  newNode->next = NULL;
  newNode->name = sname;
  newNode->location = slocation;

  while (*head)
      head = &(*head)->next;

  *head = newNode;
}

It gets even more straight forward if you provide a proper constructor for HubNode that takes the sname and slocation as construction parameters and initializes the node next member to NULL. if you code that, the add becomes simply:
void HubNode::AddHub(const string& sname, const string& slocation, HubNode **head)
{
  while (*head)
      head = &(*head)->next;
  *head = new HubNode(sname, slocation);
}


text:
Q: Export IIS in-process session data while debugging I have production IIS server with some ASP.NET MVC app. I got some tricky bug which I can't capture. It's linked to session data. How can I export/see/view such user session? There is default IIS configuration for session storing -- in-process.

EDIT
By the way I have necessary appropriate user session ID.

EDIT2
Ok, guys, so even if I can't export that data right now, could you please point me at some session state server or something similar, which I can use for storing session data and view it further?
I kniw SQL Server can, but it is very heavy for such issue.

A: Chris is right following on his Idea, you could write a routine that would output the content of your session objects to a file (a kind of a custom log).
//Controller Action where you store some objects in session
public ActionResult Index()
{
    var myObj = new { strTest = "test string", dtTestValue = DateTime.Now, listTest = new List<string>() { "list item 1", "list item 2", "list item 3"  }};
    Session["test1"] = "Test";
    Session["test2"] = myObj;

    return View();

}

//Controller Action where you output session objects to a file
[HttpPost]
public ActionResult Index(FormCollection form)
{
    //Routine to write each sessionObject serialized as json to a file
    foreach (string key in Session.Keys)
    {
        var obj = Session[key];
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\CustomAspNetLog.txt", true))
        {
            file.WriteLine(DateTime.Now.ToString() + "\t" + serializer.Serialize(obj));
        }
    }
    return View();
}

If you need to call that routine often, you can put it in some helper class and call it whenever you want in your controller actions. Then you are able to inspect true data inside Session at every step you find necessary.

A: No, you will need to write a routine to export the session data as and when required.

A: KSeen
There is a better option to store sessions than a StateServer i.e Distributed Cache provider.
Alachisoft provides NCache Express which is totally free.You can use it to store your sessions.Here is how you do it.
Install NCache on each web server.
Define a distributed cache: Make sure you test the distributed cache to ensure it is properly working.
Modify web.config file: to add the SessionState Provider information and the name of the cache you've just created.

  <sessionState cookieless="false" regenerateExpiredSessionId="true"
   mode="Custom"
                customProvider="NCacheSessionProvider" timeout="1">
        <providers>
              <add name="NCacheSessionProvider"
                    type="Alachisoft.NCache.Web.SessionState.
                    NSessionStoreProvider"
                    cacheName="myreplicatedcache"
        writeExceptionsToEventLog="false"
                    AsyncSession="false"/>
        </providers>
  </sessionState>

Please note that Version=3.2.1.0 should match the specific NCache Express version you've downloaded. Once you do this, you're ASP.NET application is ready to start using distributed sessions.


text:
Q: Why am I getting a "call to member function null" in my logs when file uploading? I'm not sure why I'm getting Call to a member function photos() on null error in the logs with the current code in my controller.  I'm calling it correctly but for some reason, it can't read my photos() function.  I've tried many ways to fix this but to no avail and hit a wall I just can't climb over.
I've tried inside my controller but still getting the aforementioned error.
$user = $request->session()->get("user");
$request->$user->photos()->create([
       'file_path' => $request->file('fileToUpload')->getClientOriginalName()
]);

return response()->json($user);

Can anyone spot what I'm doing wrong?
Here's my controller:
if(Auth::user()) {
        $request->user()->photos()->create([
            'file_path' => $request->file('fileToUpload')->getClientOriginalName()
        ]);

        return response()->json($request->session()->get("user"));
    }
}

Here's my User model:
public function photos() {
    return $this->hasMany(Photo::class,'user_id');
}

Here's my Photo model
protected $fillable = ['file_path'];

public function user() {
    return $this->belongsTo(User::class,'user_id');
}

Here's my migration table:
public function up() {
    Schema::create('photos', function (Blueprint $table) {
        $table->id();
        $table->string('file_path', 200);
        $table->unsignedBigInteger("user_id");
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

A: The error is telling you that the $request object has a null value for user.  The code looks correct, and looks like it should be checking to see if there is an Auth::user()... but there is a weird gotcha that might be interfering.
I've seen times in logging where the $request object doesn't run a query to get the user.  Instead, it may have stale data. Whereas Auth::user() does query the database on every request, and thus you may have a non-null user in Auth::user(), but possibly nothing in the $request object.  Therefore, the if-check succeeds, but the call to $request->user() fails.
As a test, give this a try to see if it is any different:
if(Auth::user()) {
    Auth::user()->photos()->create([
        'file_path' => $request->file('fileToUpload')->getClientOriginalName()
    ]);

    //etc -- see if it breaks here as well using Auth::user()
  }
}


text:
Q: shopware Controller does not get the template i am trying to create a controller and show something on a view however it ooks like something is wrong. i created a plugin with the following files
SwagStartup/Controllers/Frontend/RoutingDemonstration.php
<?php
class Shopware_Controllers_Frontend_RoutingDemonstration extends Enlight_Controller_Action
{
    public function preDispatch(){
      $this->view->addTemplateDir(_DIR_.'/../../Resources/views');
    }

    public function indexAction()
    {
        //die('Hello world test !');
    }
}

SwagStartup/Resources/views/frontend/routing_demonstration/index.tpl
{extends file="parent:frontend/index/index.tpl"}

{block name="frontend_index_content"}

Hello World

{/block}

i also have the config.xml,plugin.xml and
SwagStartup.php in there right places.
when i uncomment the hello world i will see the text in the browser when i call the controller however when i comment it out then
Oops! An error has occurred!
We have been informed about the problem and try to solve it. Please try again within a short time.

so what could be the issue and am i missing anything?
i am using shopware version 5.4.6
and following this did not help either

A: Just to update incase someone gets the same issue. my problem was here, i think its because i was tired i could not see it.
$this->view->addTemplateDir(_DIR_.'/../../Resources/views');

that should have been
$this->view->addTemplateDir(__DIR__.'/../../Resources/views');

it should be __DIR__ and not _DIR_

A: Can you please add a detailed error message? The message "Oops!..." is only user output, not the technical error message.
https://en-community.shopware.com/Debugging-in-Shopware_detail_1912.html
I did the same in my testplugin: https://github.com/mnaczenski/ControllerTest/blob/master/Controllers/Frontend/Testcontroller.php
This works fine and renders the template of the plugin.


text:
Q: Persist value across multiple views in mvc I have multiple tabs in an MVC page. Each tab is a seperate view aspx with same controller. I have a common master page.
On saving the data on 1st tab I get an ID which I want to use in other tabs of the page.
User can click any tab after saving data in 1st tab.
Currently I am using TempData to persist ID across tabs. I want to persist data without using TempData or cookies.
Is it possible to persist value in master page? Is there any other approach better than this?

Note: We have load balancer for the application.

A: I'd recommend ViewData rather than TempData as TempData disappears the first time it is used.
Based on your question though, I assume if you don't like TempData, than ViewData won't be what you're looking for anyway, but I do think it's the best solution for your scenario.

A: Create one page with several tabs on it, visible part you can manage by jquery tab plugin (eg. http://jqueryui.com/tabs/), you won't need to persist it on server side.

A: If you need this id as a part of your model, you can include it into the other view's routes like ../tab/<Your_Id>/. You would not have to persist its value in ViewData or Session or Cookie.


text:
Q: Black Holes and QED So, in quantum electrodynamics (at least to my rudimentary knowledge), the electromagnetic force is mediated by photons.
On the other hand, in classical general relativity, the Kerr Black Hole solutions, are a family parametrized by 3 numbers, one of which is $Q$, which is interpreted as the charge of the body.
Now, light cannot escape from a black hole, so if a charged particle enters the black hole, how could a particle outside of the black hole sense the charge (since no exchange of photons can occur)?
One possibility is that the charge (or at least the information about it) remains on the surface of the black hole. But matter is supposed to reach the singularity at the center of the black hole in finite proper time.
So, what actually happens? It is hard for me to imagine that, say, a proton that enters the black hole "separates" from its charge while the "rest" of it continues moving to the singularity. If this was to happen, something far more interesting than spaghettification would occur! Indeed, moving past the event horizon of a super massive black hole would be impossible, since the electostatic forces holding us together would disappear.
Or it could be that this is not a well posed question. After all, quantum field theories deal with fields not "particles".
I'm in the math department, so I was just curious what the physicists thought of this situation, and if there is some standard explanation given for this.

A:
I'm in the math department, so I was just curious what the physicists thought of this situation, and if there is some standard explanation given for this.

This particle physicist ( experimental) knows that quantization of gravity and unification of all four forces is still in the future. One needs to be able to write down rigorously the feynman diagrams of the interaction of a photon ( quantum mechanics) and a black hole ( classical general relativity) and that can only be guesses till a definitive model is found.
String theories are attractive candidates but at the moment there is no phenomenological validation for choosing one as a standard model where such questions can be answered. There are guesses as Fuzzball(string theory) :

Fuzzball theory replaces the singularity at the heart of a black hole by positing that the entire region within the black hole's event horizon is actually a ball of strings, which are advanced as the ultimate building blocks of matter and energy. Strings are thought to be bundles of energy vibrating in complex ways in both the three physical dimensions of space as well as in compact directions—extra dimensions interwoven in the quantum foam (also known as spacetime foam).

This link may give an insight to the research going on in the unification of forces through string theories. As an example of research , this was written  in 1996 by a now  well known string theory physicist ( the mills of God grind slowly). String theorists are working on charged black holes .
Until the holy grail of unification is reached one uses effective field theories for specific problems, as the Big Bang model of the history of the universe,which has a fuzzy region in the place of the original singularity so that the framework of quantum mechanics can fit the astrophysical observations ( cosmic microwave background for one).


text:
Q: How to use detach and re-attach with chaining methods in JQuery I am using jQuery filter function to search through HTML list. I use show and hide methods to show the results. Now I would like to use detach and re-attach methods instead of show and hide.
Here is what I achieved with Show() and hide() methods.
$("#myList"+ list + " li").show().filter(function() {
   return $(this).text().toLowerCase().trim().indexOf(value) == -1;
}).hide();

The codes above hide list element if does not match with input value and show the list item if search value matches with the list item. I would like to use detach() method to remove list item if does not match with value and reattach the stored data from detach method to the list if search value matches with the list item.
$("#myList"+ list + " li").prepend().filter(function() {
     return $(this).text().toLowerCase().trim().indexOf(value) == -1;
}).detach();

But I don't know how to prepend the element since I can't access detach value because I am unable to assign variable in detach() since it's chained with another methods


text:
Q: R code error "Assigned data `TL$x[TL$products == products$product]` must be compatible with existing data." Am trying to calculate an indicator called "pesticide load index" using the package of the same name available on R. Everything goes well until I get to the
products$TL <- TL$x[TL$products==products$product]
products$FL <- FL$x[FL$products==products$product]

part. There i get the error msg :

Error:
! Assigned data TL$x[TL$products == products$product] must be compatible with existing data.
x Existing data has 6 rows.
x Assigned data has 0 rows.
i Only vectors of size 1 are recycled.
Run rlang::last_error() to see where the error occurred.

Here is the code used for that:
# Read-in data on Products (Fill out Table_R_substances.xlsx) ####

products <- read_excel("./Table_R_products.xlsx")

####### Health Load Computation #####

products$HL <- products$formula*(products$sum.risk.score/products$reference.sum.risk.scores)

###### Output: Load Indicator Values ######

substances$TL.products <- substances$concentration*substances$Environmental.Toxicity.Substance
substances$FL.products <- substances$concentration*substances$Fate.Load.substances

TL <- aggregate(substances$TL.products, by=list(products=substances$product), FUN=sum)
FL <- aggregate(substances$FL.products, by=list(products=substances$product),FUN=sum)

products$TL <- TL$x[TL$products==products$product]
products$FL <- FL$x[FL$products==products$product]

products$L <- products$HL + products$TL + products$FL

###### Output: Load Index Values #######

# caculate STI-Quotient

products$STI <- products$amount.applied/products$standard.doses

Any chance on how to fix this? Thanks in advance


text:
Q: how to color input fields chrome I want to add a little something to my chrome extension. What I want to do, is everytime I click in an input field in chrome I want the color (background) to change, Only for that period of viewing the page. I only want to do this when my extension is turned on.
how can I do this?

A: If you know how to do it in javascript then converting it into an extension is very easy.
You need two files:

*

*Your js file where you do all the work (exactly as if you did it on a regular page). This is called a "content script".

*Manifest file where you describe on which domains your content script should run:
{
  "name": "My extension",
  ...
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "css": ["mystyles.css"],
      "js": ["jquery.js", "myscript.js"]
    }
  ],
  ...
}

You can read more about content scripts here and about extension structure in general here.


text:
Q: How to set a remote using libgit2sharp? I'm trying to do something like this:
var origin = repository.Network.Remotes["origin"];
repository.Head.Remote = origin;

The only problem is that "Remote" is readonly (I'm using 0.14.1.0). How do i set a default remote for HEAD?

A: Although I'd greatly recommend to update your version, the code below should get your started and work in v0.14.1.
Remote remote = repo.Network.Remotes["origin"];

Branch branch = repo.Head;
Branch updatedBranch = repo.Branches.Update(branch,
    b => b.Remote = remote.Name,
    b => b.UpstreamBranch = branch.CanonicalName);

See also this SO answer which provides some explanation about the branch tracking configuration.


text:
Q: How to retrieve html form elements and display the values elsewhere on the page I am inexperienced so sorry if this is a dumb question but I'm looking around and I haven't found an answer that works for me. I am using JavaScript and I have an html form with one text input. When someone enters a value for that input and submits the form I want to return to the same HTML page but with what they entered displayed elsewhere on the page. Here is my form:
<form name="chatInput" action="index.html"  method="get">
        chat:<input type="text" name="chat"/>
</form>

I saw something about having:
var chatText = document.forms[0].elements[0];

But when I try to use this I get [object HTMLInputElement]
Also I would only want to create that variable if the form has been entered once already but not initially. How would I check for this?
Thanks for any info.

A: var chatText = document.forms[0]['chat'].value;

http://jsfiddle.net/XLeAn/

A: Try this:
var chatText = document.forms[0].elements[0].value;

A: If you don't want to re-update the html, I'd recommend not using the form tag.
Instead, I'd create a button with the onclick attribute.
<input type="button" value="Update" onclick="someFunction()">

Then in the JS portion, have something like this.
var someFunction = function(){
    var chatText = document.getElementById("this-is-the-element-I-want").value;
}

Of course, make sure that the element you are trying to retrieve info from has an id.
<input type="text" name="chat" id="this-is-the-element-I-want">

EDIT: Code indents and clarity


text:
Q: Compare every last two records inside ng repeat Below are the records :
$scope.myArray =
  [
    {
      "id": 100,
      "child": [
        {
          "id": 77,
          "part": 33,
          "name" : 16
          "subName": 16.1,
        },
        {
          "id": 76,
          "part": 30,
          "name" : 14,
          "subName": 14.3,
        },
       {
        "id": 75,
        "part": 29,
        "name" : 12,
        "subName": 12.1,
       }
      ]
    }
  ]

Now in above records,16.1 belongs to part = 33 and 14.3 belongs to part = 30 so as both the Subname belongs to different parts so I would like to display name 16 and 14.
So expected output for above records are like below which I am getting:
16
14
12

Problem comes when i have below records :
$scope.myArray =
  [
    {
      "id": 100,
      "child": [
        {
          "id": 76,
          "part": 30,
          "name" : 14,
          "subName": 14.3,
        },
        {
          "id": 71,
          "part": 30,
          "name" : 14,
          "subName": 14.2,
        },
        {
          "id": 70,
          "part": 30,
          "name" : 14,
          "subName": 14.1,
        }
      ]
    }
  ]

Here child contains all subname for same part ie 30 so now I want to display Subname.So expected output in this case will be Subname like below :
14.3
14.2
14.1

Records will be compare from 0 - 1,1 - 2, 2 - 3 but here I am not getting how to compare records if child array contains more than two records.
Note: I will not have duplicate part in child array if any of the two records contains different part. For example, I will not have Subname like 16.1,14.3,14.2 as because here I have 16.1 which belongs to different part. But if 16.1 is not there then I can have 14.3,14.2 which are of same part.

var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
          $scope.myArray =
  [
    {
      "id": 100,
      "child": [
        {
          "id": 77,
          "part": 33,
          "name" : 16,
          "subName": 16.1,
        },
        {
          "id": 76,
          "part": 30,
          "name" : 14,
          "subName": 14.3,
        },
        {
          "id": 75,
          "part": 29,
          "name" : 12,
          "subName": 12.1,
        }
      ]
    }
  ]
        });
<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8" />

       {{ item.name }}

A: Please see below controller code. I tried to implement what you want.
$scope.myArray = [ {
        "id" : 100,
        "child" : [ {
            "id" : 76,
            "part" : 30,
            "name" : 14,
            "subName" : 14.3,
        }, {
            "id" : 71,
            "part" : 30,
            "name" : 14,
            "subName" : 14.2,
        }, {
            "id" : 70,
            "part" : 30,
            "name" : 14,
            "subName" : 14.1,
        } ]
    }, {
        "id" : 101,
        "child" : [ {
            "id" : 77,
            "part" : 33,
            "name" : 16,
            "subName" : 16.1,
        }, {
            "id" : 76,
            "part" : 30,
            "name" : 14,
            "subName" : 14.3,
        }, {
            "id" : 75,
            "part" : 29,
            "name" : 12,
            "subName" : 12.1,
        } ]
    } ]

HTML code:

            ============

                {{(item1.part==item.child[$index+1].part ||
                    ($index==item.child.length-1 &&
                    item1.part==item.child[$index-1].part))?item1.subName:item1.name}}

Here I am checking that, if current item and next item's part are same or not and if it is last item then current item and previous item's part are same or not and based on that I am displaying subName or name. I hope this solution will work for you.
Updated:

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.myArray = [{
            "id": 100,
            "child": [{
                "id": 76,
                "part": 30,
                "name": 14,
                "subName": 14.3,
            }, {
                "id": 71,
                "part": 30,
                "name": 14,
                "subName": 14.2,
            }, {
                "id": 70,
                "part": 30,
                "name": 14,
                "subName": 14.1,
            }]
        }, {
            "id": 101,
            "child": [{
                "id": 77,
                "part": 33,
                "name": 16,
                "subName": 16.1,
            }, {
                "id": 76,
                "part": 30,
                "name": 14,
                "subName": 14.3,
            }, {
                "id": 75,
                "part": 29,
                "name": 12,
                "subName": 12.1,
            }]
        }]
    });

      <title></title>
      <meta charset="utf-8" />

         ============

            {{(item1.part==item.child[$index+1].part ||
            ($index==item.child.length-1 &&
            item1.part==item.child[$index-1].part))?item1.subName:item1.name}}


text:
Q: How to use event.preventDefault() when function have arguments i have a code like this:
const upListCandy = (candy) => {
      /* How i add event.preventDefault() and it word*/
      axios.post("example.com", {
         candyName: candy.name
       }).then().catch()
    }

here is my button:
dataCandy?.map((item, index) => {
   return(

        <button onClick = {() => upListCandy(item)}>{item.name}</button>

    )
 })

And my question is how add parameter of event then event.preventDefault() work?

A: modify your onclick like so
<button onClick = {(e) => upListCandy(item,e)}>{item.name}</button>

and then
const upListCandy = (candy,event) => {
      event.preventDefault();
      axios.post("example.com", {
         candyName: candy.name
       }).then().catch()
    }

A: I think you can change it like this
dataCandy?.map((item, index) => {
   return(

        <button onClick = {(e) => upListCandy(e,item)}>{item.name}</button>

    )
 })

const upListCandy = (e,ceandy) => {
      e.preventDefault()
      axios.post("example.com", {
         candyName: candy.name
       }).then().catch()
    }


text:
Q: C#: String Variable Not Passing Value to Parameter This is probably a simple fix, however I've spent a few hours trying to get this code to work.  For my homework assignment, I have to open a text file and place it's data in an ArrayList.  I did just that, but then I realized that I am required to do so but creating a method called ReadFileAndStoreInArrayList.  Now here is where I am having trouble.
{
    class Program
    {
        static void Main(string[] args)
        {
            *//This string variable "file" is saying it has been
            //assigned but never used.*
            string file = @"C:\Users\Latoy\Documents\Schoolwork\IT 232\Unit 5\FamousWords.txt";

        }
        *//Here is where I attempted to pass the variable by value*.
        public void ReadFileAndStoreInArrayList(string file)
        {
            ArrayList FamousWords = new ArrayList();

            using (StreamReader path = new StreamReader(file))
            {
                string line;
                while ((line = path.ReadLine()) != null)
                {
                    FamousWords.Add(line);
                }
            }
            foreach (string line in FamousWords)
            {
                Console.Write(line);
            }
        }
   }
}

I am fairly new to this, and I have done my research and still can not find what I am doing wrong. Is it the way I called the method? Note: The code works when placed in one method, however I am required to create a method.  I attempted to use just the ReadFileAndStoreInArrayList method but the compiler is making me use the main method as well.

A: Use static keyword for the method you want to call from your main function, or else you won't be able to call it.
    public static void ReadFileAndStoreInArrayList(string file)
    {
        ArrayList FamousWords = new ArrayList();

        using (StreamReader path = new StreamReader(file))
        {
            string line;
            while ((line = path.ReadLine()) != null)
            {
                FamousWords.Add(line);
            }
        }
        foreach (string line in FamousWords)
        {
            Console.Write(line);
        }
    }

And then you can call it just like:
ReadFileAndStoreInArrayList(file);

in your main function which should look like:
static void Main(string[] args)
        {
            *//This string variable "file" is saying it has been
            //assigned but never used.*
            string file = @"C:\Users\Latoy\Documents\Schoolwork\IT 232\Unit 5\FamousWords.txt";
            ReadFileAndStoreInArrayList(file);
        }

A: You're not actually calling your method anywhere.  You're missing a call to:
ReadFileAndStoreInArrayList(file);


text:
Q: Magento Custom page - Ajax Contact I want to have an Ajax Contact form at a Magento custom page (accessed from the menu) and want a mail be sent to the owner whenever anyone fills in the details. Is there a module for this? If not, what's the best way of building this?
Thanks.

A: Follow steps -
1)Create module by Magento module creater. or just call below ajax from your phtml file button action.
2)Write a Controller action in InexController.php file.
 public function saveContactDetailsAction() {
    //get details
     $postData  = $this->getRequest()->getParam('data');
   //save data......
    return  "sucess"
   }

3) Write ajax code  in your phtml file.
   var reloadurl = '<?php echo $this->getUrl('module/index/saveContactDetails'); ?> ';
    new Ajax.Request(reloadurl, {
        method: 'POST',
        parameters:id='paramater list with &',

        onComplete: function(transport)
        { //write sucess code here },
        onFailure: function()
        {
           //write error code here
        }});

Hope this help


text:
Q: Option values inside a select with React I'm noobie on React and I want to fill a <select>
The problem that I have is when I want to click one of my items... dropdown only show different options if I put my items harcoded. Here's my code
Parent component
import React, { Fragment, useState, useEffect } from "react";
import Country from "./Country";
const CountriesList = ({ handleOnChange }) => {
  const [countriesLoaded, setCountriesLoaded] = useState(false);
  const [countriesList, setCountriesList] = useState([]);

  const getCountries = async () => {
    const api = "https://restcountries.eu/rest/v2/all";
    const response = await fetch(api);
    const countrieslst = await response.json();
    setCountriesList(countrieslst);
    setCountriesLoaded(true);
  };

  useEffect(() => {
    getCountries();
  }, [countriesList]);

  return (
    <Fragment>
      <select id="country" name="country" onChange={handleOnChange}>
        <option value="">-- Select a country --</option>

        {countriesLoaded
          ? countriesList.map((country) => (
              <Country key={country.alpha2Code} countryItem={country} />
            ))
          : null}
      </select>
    </Fragment>
  );
};

export default CountriesList;

child component
import React from "react";
const Country = ({ country }) => {
  return <option value={country.alpha2Code}>{country.name}</option>;
};
export default Country;

If I check DOM it's ok but only shows my first option

Thnx 4 support and have a nice day!

A: [Edit]
just add       <select id="country" name="country" onChange={handleOnChange} style={{display: 'block'}}> in your code. you will be able to view a select box rendering data
here is the link i made few changes in your code as well but this is optional:

https://codesandbox.io/s/nd58i?file=/src/components/Form.jsx


text:
Q: photoshop - export file simultaeously in multiple jpeg qualities or file formats In photoshop I need to export files in both 100% and 10%. is there a simple way i can do this in one go instead of having to do this twice? thanks

A: Let's assume you're talking about jpeg quality.
With a bit of digging you can find a function to save as an image as jpg.
// Path to the two images, named appropriately
// NOTE change to suit your needs
var myFileA = "C:\\myfolder\\myjpeg_high_quality.jpg";
var myFileB = "C:\\myfolder\\myjpeg_low_quality.jpg";

// Jpeg quality used to be from 1-10 in the old days.
// Now it's from 1-12, Let's save out the best and the worst.
jpeg_it(myFileA, 12);
jpeg_it(myFileB, 1);

// function JPEG IT (file path + file name, quality)
// ----------------------------------------------------------------
function jpeg_it(filePath, jpgQuality)
{
  if(! jpgQuality) jpgQuality = 12;

  // jpg file options
  var jpgFile = new File(filePath);
  jpgSaveOptions = new JPEGSaveOptions();
  jpgSaveOptions.formatOptions = FormatOptions.OPTIMIZEDBASELINE;
  jpgSaveOptions.embedColorProfile = true;
  jpgSaveOptions.matte = MatteType.NONE;
  jpgSaveOptions.quality = jpgQuality;

  activeDocument.saveAs(jpgFile, jpgSaveOptions, true, Extension.LOWERCASE);
}


text:
Q: Why did changing the language of my project cause the error "Missing required parameters for [Route: cars.show] [URI: {language}/cars/{car}]"? I want to change the language of my website.
I have an error that I have a missing parameter while I think my parameters are fine.
Missing required parameters for [Route: cars.show] [URI: {language}/cars/{car}].
language and id of car ...
web.php file
Route::redirect('/','/en');
Route::group(['prefix' => '{language}'], function () {

Route::resource('/cars','CarController');
});

blade file
getLocale(),$car->id) }}" class="show">more details

A: You type it wrong.
getLocale(),$car->id) }}"> Your Link

This will Fix it
 app()->getLocale(), 'car' => $car->id]) }}"> Your Link

Laravel Routing Docs


text:
Q: RSS and Atom framework and Extensions We have many nice RSS and Atom frameworks. Personally I like Argotic Framework from CodePlex.
But the problem is in diversity of extensions (see http://rss-extensions.org/wiki/Main_Page).
First feed may be created without extensions, second with only iTunes, and third with iTunes, media and so on. Sometimes an item can consist of short description and full story at the same time.
I want to reduce this Zoo just to single <description> tag without data loss (e.g. by putting together description and content of media extension from Youtube feed)
Argotic framework has GenericFeed, but it useless for me because it just ignores extensions at all.
The system works as follows: a server application loads the contents of the feed and transforms it to the general form and saves in a database. Then, in response to a request from a client ASP.NET web site loads this generalized content from database and sends to the client in JSON format.
What is the best way to generalize or distill such a kind of feeds (with many different extensions) on server side so that I can send to client javascripts just simple object in JSON format {title: "title", description: "description" ..}?

A: I wrote my own layer (one item-class one feed class and also a funnel-class for merged feeds) on top of Argotic to handle extensions and other exceptions from the feed format "standards". Pubdates are particularly bad.
First i get the genereic feed. Then, based on feed type and origin i process the feed-formad specifiv argotic objects (Rssfeed Atomfeed), and finally, if necessary, i extract data from the xml source itself.
If you know your sources, this is the way to go since you can get what you expect.
I hope this will get you moving.


text:
Q: php , replace code with php 5.3 compatible code i need to rewrite this function to be compatible with php 5.3
function fns_data($address)
{
if (ereg("^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$", $address))
{return true;}
return false;
}

anyone can help?
thanks

A: Check out filter_var(), new to PHP at version 5.2.0:
function fns_data($address)  {
    return filter_var($address, FILTER_VALIDATE_EMAIL);
}

A: In general, changing ereg to preg is (usually) as simple as renaming it to "preg_match" and adding a / to the start and end of the pattern. Since your pattern is (relatively) simple:
function fns_data($address) {
   if (preg_match('/^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/', $address)) {
       return true;
   }
   return false;
}

A: First of all, don't use ereg, but preg_replace, and use a correct email regex, like this one :
function fns_data($address) {
    if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $address))
        return true;

    return false;
}

even better, you can now use filters :
function fns_data($address) {
    return filter_var($address, FILTER_VALIDATE_EMAIL);
}


text:
Q: Is there any way to receive List by Spring Boot JPA Repository Im trying to receive the LocalDate attribute of an entity. But I got a cannot convert type exception. And Im trying search answers by Spring Boot JPA document, but nothing helpful.
Gradle Config
plugins {
    id 'org.springframework.boot' version '2.2.0.RELEASE'
    id 'io.spring.dependency-management' version '1.0.7.RELEASE'
    id 'java'
}

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

dependencies {
    implementation group: 'com.h2database', name: 'h2', version: '1.4.200'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test')
}

Configuration
spring:
  datasource:
    driver-class-name: org.h2.Driver
    username: sa
    password: sa
    type: com.zaxxer.hikari.HikariDataSource
    url: jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
    hikari:
      maximum-pool-size: 100

  jpa:
    generate-ddl: true
    show-sql: true
    hibernate:
      ddl-auto: create-drop

Entity
@Getter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Entity
@Table(name = "db_test")
public class TestEntity {
    @Id
    private String id;
    private Integer age;
    private LocalDate birthday;
}

Repository
@Repository
public interface TestRepository extends JpaRepository<TestEntity, String> {

    @Query(nativeQuery = true, value = "SELECT DISTINCT birthday from db_test")
    List<LocalDate> findAllBirthday();

}

Test Method
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestRepositoryTest {

    @Autowired
    private TestRepository testRepository;

    @Test
    public void findAllBirthday() {
        TestEntity entity = new TestEntity("OK", 1, LocalDate.parse("2019-01-01"));
        testRepository.save(entity);

        List<LocalDate> result = testRepository.findAllBirthday();
        Assert.assertEquals(1, result.size());
    }
}

Exception
org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.util.ArrayList<?>] to type [@org.springframework.data.jpa.repository.Query java.util.List<java.time.LocalDate>] for value '[2019-01-01, 2019-01-02, 2019-01-03]'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.sql.Date] to type [@org.springframework.data.jpa.repository.Query java.time.LocalDate]
    at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:47)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:191)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:212)
    at org.springframework.data.repository.core.support.QueryExecutionResultHandler.postProcessInvocationResult(QueryExecutionResultHandler.java:166)
    at org.springframework.data.repository.core.support.QueryExecutionResultHandler.postProcessInvocationResult(QueryExecutionResultHandler.java:77)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:605)

Additional information:
Maybe Im not express my thought well. Here is my operation:

*

*using H2 as default database.

*writing JUnit4 test method.

*running test under spring boot test environment.

*hoping there will return List, BUT ONLY GOT EXCEPTION.

A: How do you create fields in the database? If you're using MySQL your birthday field data type must as DATE!
otherwise, this is expected because of casting.

A: IT IS WILL NOT FIXED BY YOUR SELF!
Spring JPA convert database data by converters. And when you are querying for Timestamp data, there is no such convert for Timestamp to LocalDate as default.
Also JPA's converters not like Spring MVC's, custom converts will not added to JPA converts, it always using system default static ones.


text:
Q: Starting any Partition (WIN- Vista - Linux UBUNTU and and Mint- Debian) is only possible with CD -Grub2) My problem is, that Grub does not start Partitions using listed Partitions! My question is how to delete Grub2 loader functions and installing grub function new, so that the listed table of all Systems (installed) will be shown again!!! May be the problem started after update to UBUNTU 15-04!!!!
Thanks for giving me an answer! Where Grub starts is Gru Err 17 to see!!!
yours harryxy12345


text:
Q: A) How many license plates are possible in Massachusetts, if the format must be 0-9, A-Z, A-Z ,0-9, 0-9, 0-9? A) How many license plates are possible in Massachusetts, if the format must be 0-9, A-Z, A-Z ,0-9, 0-9, 0-9?
B) How many are possible if the format is the same, but the last three cannot all be the same number?
For part A, I have $26^2*10^4= 6,760,000$ because for 0-9 there are 10 options and for A-Z there are 26 options.
For part B, since the last three cannot all be the same, I have 0-9, A-Z, A-Z, but I'm not sure how to get the last three. Would it be $\frac{n_i}{10}$?

A: The number of plate codes with last three digits the same is $10×26×26×10$ where the last factor represents the digit that gets repeated. So the answer for (b) is $10×26^2×999$.
(Of course, the rules for licence plates are more complicated in real life...)


text:
Q: Makefile: Why command sequece is executed before call it? Below makefile, ${PATH}/CMD0.log is generated by CMD0.
check_file is command sequence to check warnings from CMD0.log. First it will check if CMD0.log exists.
When run make clean; make, it shows CMD0.log doesn't exist.
Since the log is generated by CMD0, not sure why check_file is executed before CMD0.
...
define check_file =
    if test -f ${PATH}/CMD0.log; then
        $(eval WARNING = $(shell grep "WARNING.*" ${PATH}/file.log))
    fi
endef
...
${OUTPUTS0}: ${INPUTS0}
   @echo ""
   @echo "[INFO] STEP0";
   @date '+%Y_%m%d_%H%M'
   ... CMD0 -log CMD0.log ...
   @$(check_file)

Screen print
-> make clean ; make
grep: ./log/CMD0.log: No such file or directory

[INFO] STEP0
2021_0303_0025

make -d | tee make.log screen print
     Finished prerequisites of target file `target'.
    Must remake target `target'.
grep: ./log/CMD0.log: No such file or directory
Invoking recipe from makefile:137 to update target `target'.
Putting child 0x26490c0 (target) PID 18792 on the chain.
Live child 0x26490c0 (target) PID 18792

Reaping winning child 0x26490c0 PID 18792
Live child 0x26490c0 (target) PID 18793
[INFO] STEP0
Reaping winning child 0x26490c0 PID 18793
Live child 0x26490c0 (target) PID 18810
2021_0303_0957


text:
Q: VS2010 _DELETE_CRT macro in STL How do I turn off "support for debug heap" in VS2010's STL implementation? I wrote a memory tracker which overloads new and delete and adds a tracking node in front of allocations. Sadly some STL objects use my operator new and then try to delete with the below macro instead of my operator delete. That means they try to free an address that wasn't returned by malloc. Because of the below macros my code crashes in debug but not in release (hah).
From <xdebug>:
// SUPPORT FOR DEBUG HEAP
#if defined(_DEBUG)
     #define _DELETE_CRT(ptr) _STD _DebugHeapDelete(ptr)

    template<class _Ty>
    void __CLRCALL_OR_CDECL _DebugHeapDelete(_Ty *_Ptr)
    {   //  delete from the debug CRT heap even if operator delete exists
    if (_Ptr != 0)
        {   // worth deleting
        _Ptr->~_Ty();
        // delete as _NORMAL_BLOCK, not _CRT_BLOCK, since we might have
        // facets allocated by normal new.
        free(_Ptr);
        }
    }

#else /* defined(_DEBUG) */
    #define _DELETE_CRT(ptr)        delete (ptr)

For reference, the exact crash is in locale operator=:
locale& operator=(const locale& _Right) _THROW0()
    {   // assign a locale
if (_Ptr != _Right._Ptr)
    {   // different implementation, point at new one
    _DELETE_CRT(_Ptr->_Decref());
    _Ptr = _Right._Ptr;
    _Ptr->_Incref();
    }
return (*this);
}

I don't even see what _DebugHeapDelete is buying them - it looks identical to what operator delete would do in any configuration.

A: Set _NO_DEBUG_HEAP=1 in your environment.
(That's an environment variable, not a #define, by the way)


text:
Q: Ruby on Rails - Accessing data in :has_many => :through association I'm trying to get to grips with this type of association in Rails
I have the following three models:
User

has_many: 'memberships'
has_many: groups, :through => 'memberships'

Membership

belongs_to: 'user'
belongs_to 'group'

Group

has_many: 'memberships'
has_many: 'users', :through => 'memberships'

I have a before_create method which adds a new user to a default user group.
user.rb

  attr_accessor :group_ids

  before_create :add_user_to_default_group
  after_save :update_groups

  def add_user_to_default_group
      self.group_ids = [1]
  end

 #after_save callback to handle group_ids
  def update_groups
    unless group_ids.nil?
      self.memberships.each do |m|
        m.destroy unless group_ids.include?(m.group_id.to_s)
        group_ids.delete(m.group_id.to_s)
      end
      group_ids.each do |g|
        self.memberships.create(:group_id => g) unless g.blank?
      end
      reload
      self.group_ids = nil
    end
  end

I'm trying to write a test to ensure this is happening correctly.
user = User.new
user.username = 'testuser'
user.email = 'testuser@testdomain.co.uk'
user.password = 'testpass'
user.password_confirmation = 'testpass'
assert user.save
assert user.errors.empty?
assert !user.memberships.empty?

The test passes if I use user.memberships.empty, but not if I use user.groups.empty?.  I was under the impression I should be able to access the groups through .groups?
How would I test that the user belongs to a default group called 'Active Users'?
Any advice would be greatly appreciated.
Thanks

A: You might be overcomplicating the default group.  Here's what I came up with.  Users and Groups only have a name attribute in my examples, to keep it simple.
# app/models/user.rb
class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, :through => :memberships

  before_create :add_default_group

  protected

  def add_default_group
    self.groups << Group.find_by_name('Active Users')
  end
end

# app/models/group.rb
class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :memberships
end

# app/models/membership.rb
class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end

You only need one callback, before_create.  And now for the test:
# test/unit/user_test.rb
require 'test_helper'

class UserTest < ActiveSupport::TestCase
  def test_user_gets_default_group
    group = Group.create(:name => 'Active Users')
    user = User.new(:name => 'Test')

    assert user.save
    assert_equal [group], user.groups
  end
end

This test is not just checking that the user has some groups, but the exact group you're expecting, which is a tighter check.


text:
Q: How to add cookie while Submitting on contact form 7 In my wordpress, i have contact form 7..
i want my users to enter the information to form and after submitting it will redirect to another subdomain (demo.xyz.com).
I got redirect code for contact form 7.
I want to add cookie to the form submitter browser. so he will be allowed inside the sub domain (demo.xyz.com) only with that cookie. otherwise it will be redirected back to the formh
I got redirect code. But i want here is to add cookie to the user browser while submitting and redirect to another page.
How to create cookie in contact form 7. THanks

A: Use DOM events:
document.addEventListener( 'wpcf7mailsent', function( event ) {
    if ( event.detail.contactFormId == '1234' ) {
        document.cookie = 'foo=bar';
    }
}, false );

on_sent_ok is deprecated since Contact Form 7 5.0, see https://contactform7.com/2017/06/07/on-sent-ok-is-deprecated/.

A: try this
  $hour =time()+3600*24; // 1 day
  setcookie("ID", $id, $hour,"/", ".sitename.com");
  setcookie("Key", $key, $hour,"/", ".sitename.com");

A: This Code solved the issue.
Insert this in Additional settings of Contact Form 7
This will create cookie and redirect to another page.
on_sent_ok: "document.cookie ='axdemo=allow;expires=Tue, 27 Sep 2015 10:40:41 UTC;
path=/'; location = 'http://example.com';"


text:
Q: Recognise Malformed XML file I am building a python script to run nightly, part of which involves invoking a drupal bulk operation to export an XML file. Since the process takes a number of hours, and the next step is to automatically import it to another source, I would like to perform some level of integrity checking.
My first thought would be to simply make sure that the XML is not malformed. I don't particularly want to start inspecting the data, I just want to make sure it's not truncated.
What process might I use to perform this malformed check. Is there an applicable XML library built into Python? I would prefer to keep the script as portable as possible, so if possible a built-in solution would be the most preferable.
Thanks for any advice.

A: If you want use python, you can consider using element tree
Load your .xml and try to parse. Any Exception means XML is malformed.


text:
Q: Ansible Role Not Found I'm running ansible(2.8.4) on a playbook built largely by operator-sdk on WSL(Ubuntu 18.04).  I am receiving the following error.
ERROR! the role 'DistZilla' was not found in /home/####/projects/dist-zilla-operator/roles/roles:/home/####/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles:/home/####/projects/dist-zilla-operator/roles
This is the contents of the roles/playbook.yml file and a tree of the roles dir:
---
- hosts: localhost
  roles:
    - DistZilla

$ tree roles
roles
├── distzilla
│   ├── defaults
│   │   └── main.yml
│   ├── handlers
│   │   └── main.yml
│   ├── meta
│   │   └── main.yml
│   ├── README.md
│   ├── tasks
│   │   ├── base.yml
│   │   ├── _grant_image_puller.yml
│   │   ├── main.yml
│   │   └── _stage.yml
│   ├── templates
│   │   ├── buildConfig.yml.j2
│   │   ├── imageStream.yml.j2
│   │   ├── roleBinding.yml.j2
│   │   └── role.yml.j2
│   └── vars
│       └── main.yml
├── playbook.retry
└── playbook.yml

An strace shows that it is looking for roles/DistZilla, but refuses to look for roles/distzilla, though this doesn't appear to be a problem for other users of ansible.  It seems to get past this error if I force the role to be lowercase in the playbook.yml, but, in theory, it should be able to accept the Pascal Case just fine.
I've tried with python 2.7.15 and 3.7.3.  I've tried with and without the basic config file.  Tried with and without a host file.  Tried with and without '-c local'.  I've even added a bunch of debugging prints to ansible/playbook/role/definition.py _load_role_path, but haven't seen any obvious cause.
Any insight with regards to how ansible-playbook interprets roles and looks for the path is greatly welcome.

A: This interaction depends on the underlying filesystem. If it's case insensitive (HFS+ on MacOSX) you can ignore casing in the roles directive. Most Linux filesystems are case sensitive by default so you need to write the correct casing.
On WSL it's less clear. It could be case insensitive or not depending on your settings and where the file is located. I think anyting in /mnt/c/ is case insensitive by default:
cd /mnt/c/test && echo lower > test && echo UPPER > TEST && ls -lah
-rwxrwxrwx 1 XXX XXX    6 Sep 11 11:27  test

Compared to:
cd ~ && echo lower > test && echo UPPER > TEST && ls -lah
-rw-rw-rw- 1 XXX XXX    6 Sep 11 11:29 test
-rw-rw-rw- 1 XXX XXX    6 Sep 11 11:29 TEST

In general I would recommend full lower case names for roles (with underscores for clarity). This is what happens when you download a role through Ansible Galaxy ( https://galaxy.ansible.com/docs/contributing/creating_role.html ):
role_name

Optional. Use to override the name of the role.

In the past, Galaxy would apply a regex expression to the GitHub repository name and automatically remove 'ansible-' and 'ansible-role-'. For example, if your repository name was 'ansible-role-apache', the role name would translate to 'apache'. Galaxy no longer does this automatically. Instead, use the role_name setting to tell Galaxy what the role name should be.

If no value is provided, then the role name will match the repository name, with a couple of exceptions, including: converting the name to all lowercase, and replacing any '-' or '.' characters with '_'.


text:
Q: Proper page aspect ratio? I have a question regarding the aspect ratio of my pages. I wonder if the given aspect ratio in my example is a good choice or if I should change any values to achieve a better print space. Experts, what do you think? :)
\documentclass[12pt,ngerman]{article}
\usepackage[a4paper,margin=2cm]{geometry}  \usepackage{setspace}
\usepackage[T1]{fontenc}   \usepackage{mathptmx}
\usepackage[scaled=.90]{helvet}   \usepackage{courier}
\onehalfspacing \lipsum

\begin{document} \setlength{\headheight}{15pt}
\setlength{\topmargin}{5pt} \setlength{\headsep}{15pt} \textheight =
635pt \setlength{\skip\footins}{10mm}

\lipsum

\end{document}

A: The traditional French canon des ateliers would give these  values for geometry on a4 paper (not taking into account marginpars, headers nor footers):
"ordinary" printing:
\geometry{textwidth=15.75cm, textheight=23.4cm, marginratio={4:6,5:7}}

"neat" printing:
 \geometry{textwidth=14cm, textheight=21.3cm, marginratio={4:6,5:7}}

"luxury" printing:
\geometry{textwidth=13.1cm, textheight=20.75cm, marginratio={4:6,5:7}}

You can see some explanations and details in my answer to this question.


text:
Q: Does Firefox 4 have keyboard shortcuts for the "Group your tabs" and "List all tabs" buttons? Firefox 4 has two features for visualizing tabs: the little button at the right end of the tab bar with the tooltip "List all tabs", and the "Group your tabs" button, which brings up the panorama thingy for putting tabs in groups. Does either of these have a keyboard shortcut?

A: There is an article about keyboard shortcuts in Firefox Help: http://support.mozilla.com/en-US/kb/Keyboard%20shortcuts#w_windows-tabs
It mentions that the shortcut for the Tab Groups View is Ctrl + Shift + E.


text:
Q: How to create new Document Template for pages library We have a pages library that has two content types: CustomLink and CustomPage. CustomLink is based on the Link to Document and CustomPage is based on the Page. Both add some metadata, but nothing particularly complex.
We don't like the current user experience for creating new items in our pages library and are looking to change how that happens. I see that creating a new link goes to _layouts/15/NewLink.aspx. A new page goes either to _layouts/15/CreatePublishingPageDialog.aspx or _layouts/15/CreatePage.aspx depending if the user selects Add a page from the gear menu or New > CustomPage from the library's listview control bar or Ribbon.
In Library Settings > CustomPage > Advanced Settings I can change the document template. I was able to change the CreatePage one to the CreatePublishingPageDialog and at least now there is only one user experience for creating a new page. One that we don't like is better than two that we don't like, but we would prefer to set up our own document template!
I've searched for instructions on how to do this, but everything I find is about document libraries and setting up a .dotx or other office template. Like this MS documentation.
I can't seem to find anything about how to make a document template for a pages library. I'm only a Site Collection owner with now access to _layouts so I can't even reverse engineer the existing ones.
Anybody know how to create custom document templates for a pages library?
Edit
Just to be clear. I'm looking to replace this page with a custom page. We don't like that there is no connection between the content-type page you chose and its related page layouts here. We don't like that it then just dumps you back into the page library. There are so many things about this user experience.

Or this one, which doesn't give you the opportunity to choose the contenttype or pagelayout.

A: I think you are looking for Page Layouts. This link have a lot of information regarding creation of page layouts in sharepoint https://docs.microsoft.com/en-us/sharepoint/dev/general-development/how-to-create-a-page-layout-in-sharepoint
But to get you started you need to enable publishing on the page you want to use the design manager.
All created page layouts end up in the masterpage directory. https://tenant.sharepoint.com/sites/[site]/_catalogs/masterpage/Forms/AllItems.aspx
Here you can access both the required html and aspx page.
Then add this page layout to the content type of your choice. The link above describes the procedure quite thoroughly.

A: If I understood correctly, you want two things:
a) your own, highly customized page/form that allows users create new page instances
b) hook up your new page with the library
for a), nothing stops you from setting up a brand new .aspx page somewhere, add a couple UI fields and javascript logic, to ask the user which content type and which page layout they want, and then programatically create the page/link. you don't need to rely on any existing pages or objects (and it's usually a good idea to not touch ootb files), you can just implement it however you want.
sure it will take some effort, to fetch the data, conditional logic, etc., but it's doable.
example on how to create a publishing page programatically (no UI):
https://www.c-sharpcorner.com/article/create-a-publishing-page-in-sharepoint-using-javascript-object-model/
now for b), I'm sure that there are many options, but as long as you have an URL you can use for your custom form, the hard part is done
other refs
https://www.sharepointpals.com/post/how-to-create-a-publishing-page-programmatically-in-sharepoint-2013/
https://stackoverflow.com/questions/29154160/trying-to-create-publishing-page-using-jsom-sharepoint-2013-and-changing-page-la
Create a link to "New Document" template link
hope that I'm not too far from what you seek and that this helps in some way


text:
Q: Send SSL certificate in javascript GET query Is it possible to send a SSL certificate got from a textbox/textarea to a https GET query?
I need to make a GET to a server to get a json file and it needs to use SSL certificates in this way.
Server is made in node.js, I don't know if it helps.

A: If the target address and the server at that address is setup to use https the javascript get will be encrypted automaticly. Theres is nothing done manually in javascript whatsoever


text:
Q: Is it possible to emulate a network between my device and my desktop? I'm developing an app and I need to use my network to access some webservices. I was connecting on WiFi and it was ok but I think that a system administrator should have blocked the incoming connections in my desktop.
I want to know if I can find an app to simulate a network between my desktop ( Windows 7 ) and my Android device.
Do you know if it's possible? How?

A: If somebody put a locket, than has a reason. Easier to talk with him. If he don't want... than  use an USB to Wi-fi adapter and the WI-FI connection is ready :)


text:
Q: Determine $x+y$ where $x$ and $y$ are real numbers such that $(2x+1)^2+y^2+(y-2x)^2=\frac{1}{3}$ Determine $x+y$ where $x$ and $y$ are real numbers such that $(2x+1)^2+y^2+(y-2x)^2=\frac{1}{3}$
I used the quadratic equation to get $$x=\frac{y-1\pm\sqrt{-2y-3y^2-\frac{5}{3}}}{4}$$
But I don't see how that helps, hints and solutions would be appreciated
Taken from the 2006 IWYMIC

A: Hint: Show that $\frac{1}{3}$ is the unique minimum of the function $f(x,y)=(2x+1)^2+y^2+(y-2x)^2$. Then find the $(x,y)$ where this minimum occurs.
Your expression under the radical is also incorrect. It should be $-3y^2-2y-\frac{1}{3}$, or $-\frac{1}{3}(9y^2+6y+1) = -\frac{1}{3}(3y+1)^2$. Thus there is exactly one value of $y$ for which the expression under the radical is nonnegative.

A: Multiply out and collect terms $$8x^2+4x-4xy+2y^2+\frac{2}{3}=0.$$
Multiply by $6$ and complete the square for $x$ terms $$3(4x+1-y)^2+9y^2+6y+1=0$$
$$3(4x+1-y)^2+(3y+1)^2=0$$
Therefore $x=y=-\frac{1}{3}.$


text:
Q: Why won't these form elements with width 50% display on one line? I have two form elements (a text input and a submit button), that I want to display on one line, both with a width of 50%. This doesn't work with the following HTML/CSS:
HTML
  <form name="newsletter" target="#" method="post" class="group">
    <input name="email" type="text" placeholder="email here..." />
    <input name="submit" type="submit" class="button" value="subscribe" />
  </form>

CSS
* {
    box-sizing:border-box;
}

input[type="text"] {
    margin: 0;
    width: 50%;
    font-size: 0.75rem; /* 16x0.75=12px */
    padding: 0.625em;
    border: 1px solid black;
    border-radius: 0.3125em 0.3125em 0.3125em 0.3125em;
}

input[type="submit"] {
    margin: 0;
    width: 50%;
    font-size: 0.75rem; /* 16x0.75=12px */
    padding: 0.625em;
    border: none;
    border-radius: 0.3125em 0.3125em 0.3125em 0.3125em;
    text-transform: uppercase;
}

Setting them to display:block or inline-block doesn't help either. But when I set them both to width:50%, and float:left and float:right they stay on one line without a problem.
Why is that?

A: You have whitespace (newlines, tabs, etc.) between your elements.  Remove it (or comment it out), and they fit as you would expect:
http://tinker.io/9a125
  <form name="newsletter" target="#" method="post" class="group">
    <input name="email" type="text" placeholder="email here..." /><!--
    --><input name="submit" type="submit" class="button" value="subscribe" />
  </form>

Inline* elements honor whitespace between them.  The reason floating works is because the elements are no longer inline.

A: Try this style:
input{float:left}

A: It could be that you have also set a border of 1px which will add to the 50%.


text:
Q: javascript FB.api call works inside getLoginStatus not outside Can someone explain why the api('/me'... call works inside the getLoginStatus block and fails out side the block?
(When I say fails, response.name in undefined as well as everything else)
I've tried doing this inside the fbAsyncInit code and in a callback that is suppose to trigger after the init is complete and in both cases, the api('/me'... call only works in the getLoginStatus block.
In both cases I can only get api('/me' to work inside the getLoginStatus() block.
Note: I've not had any trouble with the user not being connected.
FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {
    var uid = response.authResponse.userID;
    var accessToken = response.authResponse.accessToken;
    console.info("connected");
    FB.api('/me', function(response) {
      // this works
      console.info("Name: "+ response.name + "\nFirst name: "+response.first_name+"");
    });
 } else if (response.status === 'not_authorized') {
              console.info("bad");
 }
});

FB.api('/me', function(response) {
  // response.name == 'undefined'
  console.info("Name: "+ response.name + "\nFirst name: "+response.first_name+"");
});