text:
Q: How to get replies of a comment? Is there a way to get replies of a comment by its ID? I have searched on google but could not find anything about it.
For example, I have a comment with ID 123
I want to display all the replies that comment ID 123 has.
I have tried something like the following but it did not work:
$args = array(
    'status' => 'approve',
    'ID' => 123,
    'number' => '5',
    'post_id' => 73871,
    'comment_parent' => 0

);
$comments = get_comments($args);

A: As comment_ID is a unique value, there is no need to include the post_id in the arguments.
This works fine for me:
$args = array(
    'status' => 'approve',
    'number' => '5',
    'parent' => 3194
);
$comments = get_comments($args);

This will return 5 approved comments whose parent is the comment with the comment_ID 3194.
Sample output could be done with something like this:
foreach($comments as $child_comment) {
    echo $child_comment->comment_ID;
}

A: I think I just found it, please corrent me if I am wrong:
$args = array(
    'status' => 'approve',
    'number' => '5',
    'post_id' => 73871,
    'parent' => 123

);
$comments = get_comments($args);

EDIT: not quite, it seems it returns the first reply only. The rest are missing.

A: You're correct so far but incomplete.
You need a foreach loop after your code. So it will be like:
$args = array(
    'status' => 'approve',
    'number' => '5',
    'post_id' => 73871,
    'parent' => 123
);

$comments = get_comments($args);

foreach ($comments as $comment) {
    echo $comment->comment_content; // echo all the other fields you need
}

A: In your foreach loop, you need to search for each comment if it has any replies submitted.
$replies = get_comments( array( 'parent' => $comment->comment_ID, 'status' => 'approve', 'order' => 'ASC' ) );
please have a look at this plugin https://github.com/mukto90/comment-search/blob/master/cb-comment-search.php
it'll help you search by a comment id and show all of its replies (and maybe their replies too).


text:
Q: Are Custom Settings included in a Database.rollback()? Apex has a Transaction Control system for rolling back changes to SObjects. Are Custom Settings included in a rollback? (To be more clear, are Custom Settings reverted to the state that they were in when setSavepoint() was called?)

A: Any DML in the transaction is rolled back, including custom settings.

A: Yes, they are. In fact changes you wouldn't think of as DML are also rolled back: calling @future method, sending email, and others. In essence outside of the current apex state rolling back undoes EVERYTHING you did.
Note that Big Objects are the exception to this, they commit immediatley and do not support rollbacks. Even in tests.
Platform events are also not able to be rolled back (but don't fire real event handers form tests like Big Objects do)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replace a comma "," with "||" in a list I have a list of equations:
dene = {x1== 0.2, x2== 0.4, x3==0.5};

I would like to convert this list into a rule:
iki = {ToRules[x1==0.2 || x2==0.4 || x3==0.5]} // Flatten

which works. Since my list of equations is a very long list, I'd like to use some Mathematica function.
I have tried two options to make "dene" a rule: either eeplace "==" with "->" or substitute "," with "||". I could not do any of these options work, although I've spent quite some time on the problem. I need your help.

A: Here is a simple function that does what I think you want.
makeRules[p : {_Equal ..}] := Rule @@@ p

Then
dene = {x1 == 0.2, x2 == 0.4, x3 == 0.5};
makeRules[dene]

{x1 -> 0.2, x2 -> 0.4, x3 -> 0.5}

A: This is a good use for Cases with a level specification, which allows you to use rules and pattern matching to create rules! The level spec helps if you have deeper nesting of Or expressions:
expr = x1 == 0.2 || x2 == 0.4 || x3 == 0.5;

Cases[expr, lhs_ == rhs_ :> {lhs -> rhs}, Infinity]
(* {{x1 -> 0.2}, {x2 -> 0.4}, {x3 -> 0.5}} *)

A: Much like @AccidentalFourierTransform's comment and @Pillsy's answer, you can also replace the heads but on all levels.
{x1 == 0.2, x2 == 0.4, x3 == 0.5} /. Equal -> Rule

{x1 -> 0.2, x2 -> 0.4, x3 -> 0.5}

A multi-level example
Array[x[##] == {##} &, {2, 2}]
% /. Equal -> Rule

{{x[1, 1] == {1, 1}, x[1, 2] == {1, 2}}, {x[2, 1] == {2, 1},
    x[2, 2] == {2, 2}}}
{{x[1, 1] -> {1, 1}, x[1, 2] -> {1, 2}}, {x[2, 1] -> {2, 1},
    x[2, 2] -> {2, 2}}}


text:
Q: Entity Framework "Enable-Migrations" command generates Configurations.cs file encoded in ANSI. Why? I am using EF Code First with migrations for a project and I have stumbled upon a strange behavior:
Executing the "Enable-Migrations"-command in the Package Manager Console generates a "Migrations" folder and "Configurations.cs" file. When I check the encoding of the "Configurations.cs" in Notepad++ it shows that it is ANSI encoded.
When I create an arbitrary file in Visual Studio 2010 it's always encoded in UTF-8. Why does NuGet generate the file in another encoding?
Thanks in advance,
Chris

A: I finally got around to properly investigating this...
The files (Configuration.cs and the individual migration files) are actually being saved as UTF-8 without a file signiture. This format is indistinguishable from ANSI unless non-ANSI characters appear somewhere in the file. Tools like Notepad++ will only show it as UTF-8 if there are non-ANSI characters in the file. This is because a UTF-8 file with only ANSI characters is 100% compatible with the ANSI format.
If you have non-ANSI characters in your context type name, table names, etc. things will work as you expect, and Notepad++ will report the file format as UTF-8.

A: The configuration file is actually stored as a template embedded in an assembly in the NuGet package and is then processed and copied into your project when Enable-Migrations is used. The stored template is an ANSI file and hence the file you get is an ANSI file. You should be able to re-save it as UTF-8--the runtime won't care.


text:
Q: Lodash remove duplicates from array This is my data:
[
    {
        url: 'www.example.com/hello',
        id: "22"
    },
    {
        url: 'www.example.com/hello',
        id: "22"
    },
    {
        url: 'www.example.com/hello-how-are-you',
        id: "23"
    },
    {
        url: 'www.example.com/i-like-cats',
        id: "24"
    },
    {
        url: 'www.example.com/i-like-pie',
        id: "25"
    }
]

With Lodash, how could I remove objects with duplicate id keys?
Something with filter, map and unique, but not quite sure.
My real data set is much larger and has more keys, but the concept should be the same.

A: Simply use _.uniqBy(). It creates duplicate-free version of an array.
This is a new way and available from 4.0.0 version.
_.uniqBy(data, 'id');

or
_.uniqBy(data, obj => obj.id);

A: You could use lodash method _.uniqWith, it is available in the current version of lodash 4.17.2.
Example:
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]

More info:
https://lodash.com/docs/#uniqWith

A: _.unique no longer works for the current version of Lodash as version 4.0.0 has this breaking change. The functionality of _.unique was splitted into _.uniq, _.sortedUniq, _.sortedUniqBy, and _.uniqBy.
You could use _.uniqBy like this:
_.uniqBy(data, function (e) {
  return e.id;
});

...or like this:
_.uniqBy(data, 'id');

Documentation: https://lodash.com/docs#uniqBy

For older versions of Lodash (< 4.0.0 ):
Assuming that the data should be uniqued by each object's id property and your data is stored in data variable, you can use the _.unique() function like this:
_.unique(data, function (e) {
  return e.id;
});

Or simply like this:
_.uniq(data, 'id');

A: In LODASH versions lower than 4 you will find most of this function are not implemented same way. And opposite from version 4 _.uniq was modified. I personally had a project that was in transition for a few months (from V3 -> to V4).
If you run in same situation and you have a lot of functions to be updated. You can do it in stages and when you are done with transition you can come and fix it later. This is the trick i used to avoid downtime of the platform:
/* LODASH Version 3 & 4 Compatibility Mode */
if ((_.VERSION).charAt(0) <= 3){ //Detect LODASH version 3 or 4.
    //V3 or lower
    _.uniq(data, true, 'id');
} else {
    //V4 or Higher
    _.uniqBy(data, 'id');
}

Also if you look at lodash documentation for most of this cases you
can find migration of _.uniq from version lower than 4 can be performed
with both functions:
_.uniqBy(data, 'id') or
_.unionBy(data, 'id')
Both of them will bring same result. I personally was guessing which
one to pick. In the end I picked this one:  _.uniqBy(data, 'id').

A: With lodash version 4+, you would remove duplicate objects either by specific property or by the entire object like so:
var users = [
  {id:1,name:'ted'},
  {id:1,name:'ted'},
  {id:1,name:'bob'},
  {id:3,name:'sara'}
];
var uniqueUsersByID = _.uniqBy(users,'id'); //removed if had duplicate id
var uniqueUsers = _.uniqWith(users, _.isEqual);//removed complete duplicates

Source:https://www.codegrepper.com/?search_term=Lodash+remove+duplicates+from+array

A: Or simply Use union, for simple array.
_.union([1,2,3,3], [3,5])

// [1,2,3,5]

A: You can also use unionBy for 4.0.0 and later, as follows:
let uniques = _.unionBy(data, 'id')

A: For a simple array, you have the union approach, but you can also use :
_.uniq([2, 1, 2]);


text:
Q: floating left side button for call me and contact me I'm trying to make a floating left side, out of the main container, for call me and contact me.
similar to this http://www.jqueryscript.net/demo/jQuery-Plugin-For-Floating-Social-Share-Contact-Sidebar/
the contact button opens your email client but I'd like it to pop open a form to fill out instead.
this is an example of what I've used before from contactme.com but they are shutting down. I know the html code to make the call me button work
Basically, I want to know how to be able to code something like that.

A: this is the code that I currently have
<script type="text/javascript">var _cmo = {form: '55cd1ee8adfbd40003002d54', text: 'Contact', align: 'left', valign: 'middle', lang: 'en', background_color: '#003E02'}; (function() {var cms = document.createElement('script'); cms.type = 'text/javascript'; cms.async = true; cms.src = ('https:' == document.location.protocol ? 'https://d1uwd25yvxu96k.cloudfront.net' : 'http://static.contactme.com') + '/widgets/tab/v1/tab.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(cms, s);})();</script>


text:
Q: How to get higher and lower values for a given data type? In Delphi I often use the Low and High functions which returns respectively the highest and the lowest value for a given ordinal data type.
Is there something similar in Firebird?

A: There is no feature in Firebird to get the minimum or maximum value of a type.


text:
Q: About a balloon in a balloon in a balloon in a balloon in a balloon Suppose we manage to put $x$ identical (blown up) balloons into one another. The balloons are identical and snap if the inside air pressure is $l$ times as big as the atmospheric pressure (if the outside of the balloon is the atmosphere).
The first balloon is in a state just below snapping, so we can say that the inside air pressure is almost $l$ times as big as the atmospheric pressure. The second balloon is in a state so that is will just snap if the first balloon snaps. The third balloon inside this (second) balloon is in such a state so that it will just snap if the first and second balloon are snapped. The fourth balloon inside the third balloon is again in such a state that it just snaps after the first, second and third one are snapped. And so on until the $x$-th balloon.
Now we saw that the pressure inside the first balloon is almost $l$ times as big as the atmospheric pressure. For the second balloon the inside pressure is $l^2$ as big as the atmospheric pressure, the inside pressure of the third balloon is $l^3$ as big as the atmospheric pressure, and so on until the $x$-th balloon, in which the air pressure is $l^x$ times as big as the atmospheric pressure (although these pressures are bigger than $l$ times the atmospheric pressure they won't snap, because this happens only for balloons without blown up balloons around them).
Is my reasoning right that if we let the first balloon snap by a needle, all the others will snap, one after another, or am I overlooking something? For example the fact that each balloon expands after the surrounding balloon snaps (which would imply that the enclosed balloons would have to be under greater pressure)? How would the ditribution of pressures in the balloons have to be to let them snap one aftyer another if you let the first one snap?


text:
Q: Getting Correct IPv6 Address from given prefix On my windows xp machine, i have this information:
IP Address: fcb1:cafe:1:9e33::2
Default Gateway: fcb1:cafe:1:9e33::1

It works fine, and i can ping the gateway. However now there is another prefix for host given as:
fcb1:abab:cdcd:efe1::/64

To access this, i added static route to this IP via gateway:
netsh interface ipv6 add route fcb1:abab:cdcd:efe1:1::/64 "Local Area Connection" fcb1:cafe:1:9e33::1

This command was accepted successfully, but now when i try to ping:
ping6 fcb1:abab:cdcd:efe1:1

I get message: Bad IPv6 address fcb1:abab:cdcd:efe1:1
It seems the IP i am using is incorrect, however the host entry was accepted. Could someone suggest with the prefix: fcb1:abab:cdcd:efe1::/64 what is a valid ip that i can ping???
I tried checking subnet calculator but they seem to detect this as incorrect, however this prefix is used on a valid system and is working fine, any idea??

A: You are missing the second colon » ping6 fcb1:abab:cdcd:efe1::1

Since I don't like one-liners here's something most people probably don't know:

Wrong: 2001:0 db8 :: 0001
Correct: 2001: db8 :: 1
Leading zeros should be suppressed!

Wrong: 2001: db8: 0:0:0:0:2:1
Correct: 2001: db8 :: 2:1
Wrong: 2001: db8 :: 0:1
Correct: 2001: db8 :: 1
The use of "::" must be carried out to the max!

Wrong: 2001: db8 :: 1:1:1:1:1
Correct: 2001: db8: 0:1:1:1:1:1
A single 16-bit field with zeros can not be combined!

Wrong: 2001 :: 1:0:0:0:1
Correct: 2001:0:0:1 :: 1
Have several options at the address with "::" to shorten
the longest occurrence of zeros will be reduced!

Wrong: 2001: db8: 0:0:1 :: 1
Also wrong: 2001: db8 :: 1 :: 1
Correct: 2001: db8 :: 1:0:0:1
If multiple sequences are the same length of zeros,
the first must be shortened!

Wrong: 2001: db8: 0:0: A :: B
Correct: 2001: db8: 0:0: a :: b
The characters "a" through "f" must be lowercase!

Source


text:
Q: How I can show error message for each field in form? In my validator I add some description for each field, and want to display error message in form(.jsp), but when I display message for each field, the error messages is the same, what's problem, my code:
Validator
public class StoreValidator implements Validator {

@Override
public boolean supports(Class<?> clazz) {
    return Store.class.equals(clazz);
}

@Override
public void validate(Object target, Errors errors) {
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.empty", "Name field is empty");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "address.empty", "Address field is empty");
}

}
Controller
    @Autowired
private StoreValidator storeValidator;

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(storeValidator);
}

//post method create store
@RequestMapping(value = "/regStoreSuccessful", method = RequestMethod.POST)
public ModelAndView addStorePost(@Valid @ModelAttribute("storeForm") Store storeForm, BindingResult bindingResult, Principal principal, RedirectAttributes redirectAttrs) throws SQLException {
    ModelAndView modelAndView = new ModelAndView("redirect:body");

    storeValidator.validate(storeForm,bindingResult);

    if(bindingResult.hasErrors()) {
        redirectAttrs.addFlashAttribute("error", bindingResult.getFieldError().getDefaultMessage());
        //modelAndView.addObject("storeForm", bindingResult.getFieldError().getDefaultMessage());
  //modelAndView.addObject("storeForm", storeForm);

  //redirectAttrs.addFlashAttribute("errors", bindingResult.getFieldError().getRejectedValue());
        //redirectAttrs.addFlashAttribute("storeForm", storeForm);

    //..
    }
    //..
    }

Form
<form:form method="POST" action="/regStoreSuccessful" commandName="storeForm">

    <form:label path="name">Name store</form:label>
    <form:input path="name" />
    <form:errors path="name" />

    <form:label path="address">Address store</form:label>
    <form:input path="address" />
    <form:errors path="address" />

  </form:form>

Also I tried used <form:errors path = "name" />, but isn't working...

A: You should add entire object in model attribute in hasErrors method
and  for each input separately  use form:errors for each input.
<form:errors path = "name" />
<form:errors path = "address" />

if(bindingResult.hasErrors()) {
    model.addAttribute("storeForm",storeForm);
//..
}


text:
Q: pandas map to next week's monday Is there a canonical/easy way to map a date/list of dates to their respective next Monday in pandas?
E.g. given a list of 7 days, return a list of 7 days where Monday stays the same and Tuesday-Sunday get mapped to the next Monday

A: You can use the Week offset:
In [11]: days = pd.date_range('2019-01-01', '2019-01-31')

In [12]: days + pd.offsets.Week(weekday=0)
Out[12]:
DatetimeIndex(['2019-01-07', '2019-01-07', '2019-01-07', '2019-01-07',
               '2019-01-07', '2019-01-07', '2019-01-14', '2019-01-14',
               '2019-01-14', '2019-01-14', '2019-01-14', '2019-01-14',
               '2019-01-14', '2019-01-21', '2019-01-21', '2019-01-21',
               '2019-01-21', '2019-01-21', '2019-01-21', '2019-01-21',
               '2019-01-28', '2019-01-28', '2019-01-28', '2019-01-28',
               '2019-01-28', '2019-01-28', '2019-01-28', '2019-02-04',
               '2019-02-04', '2019-02-04', '2019-02-04'],
              dtype='datetime64[ns]', freq=None)

To fix Mondays:
In [13]: days + pd.offsets.Week(weekday=0, n=0)
Out[13]:
DatetimeIndex(['2019-01-07', '2019-01-07', '2019-01-07', '2019-01-07',
               '2019-01-07', '2019-01-07', '2019-01-07', '2019-01-14',
               '2019-01-14', '2019-01-14', '2019-01-14', '2019-01-14',
               '2019-01-14', '2019-01-14', '2019-01-21', '2019-01-21',
               '2019-01-21', '2019-01-21', '2019-01-21', '2019-01-21',
               '2019-01-21', '2019-01-28', '2019-01-28', '2019-01-28',
               '2019-01-28', '2019-01-28', '2019-01-28', '2019-01-28',
               '2019-02-04', '2019-02-04', '2019-02-04'],
              dtype='datetime64[ns]', freq=None)

Note: You can use a different number for a different weekday (e.g. 2 for Tuesday), and you can also subtract to get the previous Monday.

A: Using np.where with weekday
s=pd.Series(pd.date_range(start='2019-02-11',periods=7))
s=pd.Series(np.where(s.dt.weekday!=0,s+pd.to_timedelta(7-s.dt.weekday,'D'),s))
s
0   2019-02-11
1   2019-02-18
2   2019-02-18
3   2019-02-18
4   2019-02-18
5   2019-02-18
6   2019-02-18
dtype: datetime64[ns]

A: There might be a better way to do this, but looking at documentation for Timestamps, it looks like you can do something like
my_timestamp += datetime.timedelta(days=(7 - my_timestamp.weekday())%7)


text:
Q: ifconfig: SIOCGIFFLAGS: No such device Running ifconfig wlan0 up returns
ifconfig: SIOCGIFFLAGS: No such device

I tried ifconfig wlan0 and got
ifconfig: wlan0: error fetching interface information: Device not found

Boot-up logs showing
Starting network: [    6.178148] ip (252) used greatest stack depth: 5756 bytes left
/bin/sh: wpa_supplicant: not found
FAIL

How can I debug this? Any suggestions?


text:
Q: So, you can't develop android app without being open-source? I just read these topics:
Is there a way to get the source code from an APK file?
How to avoid reverse engineering of an APK file?
...and realized that you can't develop an android program without being possible for  its .apk file to be reverse engineed.
You can use Proguard and tricks but still your code will not be completely hideable.
So if you want to make an app completely close-source what you have to do?
For example, what Facebook and Snapchat and Messenger (e.g) did so their source codes are not accessible?
Also, another question: if you upload your app on google play, then a user can get your .apk?
Thanks in advance!

A: From what I know, there are programs you can use to extract an apk from your phone. For example APK Extractor is listed in the Play Store.
You can use this kind of apps to get the apks you want.

A: Every app may be reverse engineered.
The difference is only time needed to do it.
Proguard is a minimal solution whish requires minimal efforts and provides a level of protection that is enough in most cases.
You may also use other obfuscation tools (for example, DexGuard).
Another way is making shared libraries with Android NDK and using it. Reverse engineering of native binaries is usually more difficult than Java classes.
Probably the only way to completely protect your algorithms is to remove them from user's device - move to a server. In that way application will do a requests, but computation will be performed on your server.
As for extracting APK - it is possible, as Giorgos Pippos wrote.


text:
Q: Any way to make a generic response handler in nodejs? I'm trying to write a couple of endpoints that will make GET and POST http requests to various backend services, the format of data is all going to be very similar so responseHandler function will be copied over and over to different route function, I wonder if there is a way to externalize responseHandler for reuse. I tried to just move it out, but then I would lose reference to res. Anyone has any tips on a more modular design?
routes['/endpoint'] = function(req, res){
    console.log("Serving endpoint: /endpoint")
    var params={"param": "param-value"}

    var options = {
      host: 'localhost',
      path: '/service?param='+params.param,
      method: 'GET'
    };

    var responseHandler = function(response) {
      var data = '';

      // keep track of the data you receive
      response.on('data', function(chunk) {
        data += chunk + "\n";
      });

      // finished? ok, send the data to the client in JSON format
      response.on('end', function() {
            res.header("Content-Type:","application/json");
            res.end(data);
      });
    };

    // make the request, and then end it, to close the connection
    http.request(options, responseHandler).end();
};

A: generally i would think you could create a folder in your lib called responseHandlers, add a file that contains something like
var responseHandler = function(response) {
  var data = '';

  // keep track of the data you receive
  response.on('data', function(chunk) {
    data += chunk + "\n";
  });

  // finished? ok, send the data to the client in JSON format
  response.on('end', function() {
        res.header("Content-Type:","application/json");
        res.end(data);
  });
};
exports.Handler = responseHandler;

save that as whateverHandler.js, then create an index.js file that requires whatever.js and exports it Handler.  this way if you need to add more handlers in the future you just have to add a file and update the index.js.  to use, do something in the route handler like
var handler = require('./lib/responseHandlers').whateverHandler;
routes['/endpoint'] = function(req, res){
    console.log("Serving endpoint: /endpoint")
    var params={"param": "param-value"}

    var options = {
      host: 'localhost',
      path: '/service?param='+params.param,
      method: 'GET'
    };
};

// make the request, and then end it, to close the connection
http.request(options, handler).end();
};

A: You could turn responseHandler into a function generator, and pass in your res object so you don't lose it:
var responseHandler = function(res) {
  return function(response) {
    var data = '';

    // keep track of the data you receive
    response.on('data', function(chunk) {
      data += chunk + "\n";
    });

    // finished? ok, send the data to the client in JSON format
    response.on('end', function() {
          res.header("Content-Type:","application/json");
          res.end(data);
    });
  };
}

And use it like this:
routes['/endpoint'] = function(req, res){
    console.log("Serving endpoint: /endpoint")
    var params={"param": "param-value"}

    var options = {
      host: 'localhost',
      path: '/service?param='+params.param,
      method: 'GET'
    };

    // make the request, and then end it, to close the connection
    http.request(options, responseHandler(res)).end();
};


text:
Q: "Connection to remote host was lost." error i am trying to make a little program with websocket, but after like 30min of running, i get this big error
websocket._exceptions.WebSocketConnectionClosedException: Connection to remote host was lost.
(full error : https://paste.pythondiscord.com/oduwigunim)
can someone help me to fix that ?
(the whole code :https://paste.pythondiscord.com/ifabolehit)


text:
Q: javascript issue undefined variable in array Can someone please tell me what's wrong with this code? Chrome and Firefox are saying that scrns[i] is undefined though Chrome still runs the code on mouseover.
function nextPrev() {
  if (!document.getElementsByClassName) return false;
  var scrns = document.getElementsByClassName('scrn');
  for (var i=0; i<=scrns.length; i++) {
    // console.log(i);
    scrns[i].onmouseover = function() {
      // console.log('foo');
    }
  }
}
window.onload = nextPrev();

I've tested that the for loop is working and tried to pin down where the problem is coming from in every way I know how. I'm even looking at an example I took from a book sometime ago and cannot understand why scrns[i] would be undefined.
Any help greatly appreciated!

A: You are looping too far. If i is equal to scrns.length then it is beyond the end of the array. Remove the = in your stop condition:
for (var i=0; i < scrns.length; i++) {

A: You're using <= when looping through. But remember that arrays are indexed starting at 0, not 1. So an array with 10 elements has a length of 10, but elements 0-9. Change the following:
for (var i=0; i<=scrns.length; i++) {

to:
for (var i=0; i < scrns.length; i++) {

A: You have an off by one error. Changing <= to < should fix your issue. You can use loop invariants in the future to make sure that you don't go over.
http://en.wikipedia.org/wiki/Loop_invariant
In general though, when looping through an array, begin with the iterating counter at 0 and then loop so long as the counter is less than the length of the array.


text:
Q: Magento Paypal Express Error I am looking for help in fixing a problem we have been having with our Magento for a while now
This is what has been happening:
A customer will come to the website and use a coupon code during checkout. When they are paying they can choose between Paypal or Credit card. Both options are going through Paypal anyways using "Website Payments Pro". Right before the customer confirms the payment they see an error like this "PayPal gateway has rejected request. A successful transaction has already been completed for this token (#10415: Transaction refused because of an invalid argument. See additional error messages for details)."
Then once that happens they are STILL getting charged through Paypal/Credit card. But an order is not being generated in Magento for our records and the customer is not receiving an order confirmation. If they keep clicking on Confirm Order then they will see this error each time while their card is getting billed each time.
Since there was no response to the question here http://www.magentocommerce.com/boards/c../viewthread/291770/ I copied it over to stackoverflow.


text:
Q: Css selector when one class is present and not both classes I want to do something like this .horizontal-nav:not(.horizontal-nav.responsive-nav-enabled)
i.e. I want to apply styles of .horizontal-nav only if the div does not have the .responsive-nav-enabled class. If it has both classes then the styles of .horizontal-nav must not apply. Is it possible?

A: You need to use .horizontal-nav:not(.responsive-nav-enabled) to get the desired result:

.horizontal-nav {
  height: 20px;
  border: thin solid;
}

.horizontal-nav:not(.responsive-nav-enabled) {
  background-color: red;
}

The problem with your original selector is that it is invalid and rejected by the browser. :not accepts a simple selector while .horizontal-nav.responsive-nav-enabled is a sequence of simple selectors.


text:
Q: Failed to connect to iphone XR in appium studio got error of  "Failed to connect to XCAutomation"

A: I was getting an error of Failed to connect to XCAutomation due to I have the latest software version iOS 14.3 in the mobile (iPhone XR) & I am using the old version of Appium Studio 20.6.7047. I have upgraded to the latest software and the problem resolved.
Reference Link: https://appium.experitest.com/t/failed-to-connect-xcautomation-after-upgrading-to-ios-14-1/2130/4
Download links for appium Studio:
For Mac: https://go.experitest.com/appium-studio-download-mac-thank-you-page
For Windows: https://go.experitest.com/appium-studio-for-windows


text:
Q: Which components of Linux IO subsystem are device-independent and device-dependent? From Tanenbaum's Modern OS,

every operating system has an I/O subsystem for managing its
  I/O  devices.  Some  of  the  I/O  software  is  device  independent,  that  is,  applies  to
  many or all I/O devices equally well. Other parts of it, such as device drivers, are
  specific to particular I/O devices.

There is also a diagram of the layers of the I/O software systems:

In the following two diagrams of Linux's IO subsystem, can you draw a boundary between device-independent and device-dependent components? In other wards, which components are device-dependent, and which components are device-independent? My thought is "drivers" are device-dependent, and "VFS" is device-independent. But I am not sure about the other components.
From the same book:

Bovet's Understanding the Linux Kernel 2005 also has one:

A: In the first Linux diagram, above the "device driver" part; same for Bovet's diagram.
When writing an operating system, you want to keep the device-dependent parts as isolated as possible, so you can add further devices cleanly. In Linux' case, "device driver for a disk" (or "network card", or "WiFi card", or whatever) is a class in the sense of object oriented programming, further refined into classes for individual device types(e .g. "Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller"), which in turn can be instatiated as several copies of the same (or similar enough) devices, as needed. e.g. whose objects are In some cases, device specific functionality is abstracted into higher-level subsystems, like the whole complex handling of WiFi administrative domains and restrictions (this was originally part of each driver). Sometimes there are devices layered on top of one another, like a USB thumbdrive, which uses USB and is handled in turn as a SCSI disk over USB, or SCSI over IP (which in turn runs over fiber optic network interfaces).
tl;dr: This clean separation (as much most what you see in "operating system" texts) is just a very crude first approximation, reality is a much more interesting mess.


text:
Q: How to remove Merged region using Apache POI? (Duplicate Data) So recently I had an issue which was related to the below question
How to remove Merged region using POI?
Although the above did partially solve my issue, I wanted to duplicate the data to other un-merged cells.
I couldn't find any guide or function in the library itself to resolve this and so I created a newer version based on the above
        HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
        HSSFSheet sheet = wb.getSheetAt(0);

        for(int i=0; i < sheet.getNumMergedRegions(); i++)
        {
            CellRangeAddress addresses = sheet.getMergedRegion(i);
            for(int x=addresses.getFirstRow()+1;x<addresses.getLastRow();x++)
            {
                HSSFCell cell = sheet.getRow(addresses.getFirstRow()).getCell(addresses.getFirstColumn());
                for(int y=addresses.getFirstColumn();y<=addresses.getLastColumn();y++)
                {
                    sheet.getRow(x).getCell(y).setCellStyle(cell.getCellStyle());
                    switch (cell.getCellType())
                    {
                        case _NONE:{}
                            break;
                        case BLANK:{}
                            break;
                        case STRING:{sheet.getRow(x).getCell(y).setCellValue(cell.getRichStringCellValue());}
                            break;
                        case BOOLEAN:{sheet.getRow(x).getCell(y).setCellValue(cell.getBooleanCellValue());}
                            break;
                        case NUMERIC:{sheet.getRow(x).getCell(y).setCellValue(cell.getNumericCellValue());}
                            break;
                        case FORMULA:{sheet.getRow(x).getCell(y).setCellValue(cell.getCellFormula());}
                    }
                }
            }
        }

The above resolved my issue, but as you can see I had to use a switch case. So I was hoping if there are any other better ways to this?


text:
Q: What's the difference between an interface and a design pattern? I have a hard time knowing when something is an interface or a design pattern. For example what are observer - observerable? And what is MVC?

A: I don't quite get your confusion. An Interface is simply a set of methods the class that implements it, 'promises' to implement. A pattern's definition may vary and this is the one I found online:

Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time.

As per this example you've given, it is my understanding that Observable would be an Interface, that every object that wants to have a trait of "observability" should implement. On the other side:

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.

The key point here is : usually by calling one of their methods. Every object that is in the list of "dependents" needs to implement the Observable interface as to be sure that it has the required method that the Observer will call, regardless of what type of object it is. By defining an interface which has the aforementioned method, you can guarantee that different classes will provide their own implementation of the method, which is unimportant at the place where the method is called. All it matters is that the method exists.
I hope I was in a way helpful and clear.


text:
Q: Scream of the day - Javascript serialising arrays in different ways This is royally annoying me at the moment:
Consider an array of 2 values:
var myArray = new Array();
myArray.push(21031);
myArray.push(21486);

When storing this in a cookie using jquery and toJSON, the value of the cookie looks like this:
["21031","21486"]

Now consider an array of a single value:
var myArray = new Array();
myArray.push(21239);

When storing this in a cookie using jquery and toJSON, the value of the cookie looks like this:
21239

This is almost completely useless to me as when I pull the items from the cookie, one comes back as a single value, the other comes back as an array that I can iterate over....ahhh!
Why?

A: I'd suggest using json2.js' JSON.stringify.  It gets both of those cases right:
// [] is the same as new Array();
var foo = [];

foo.push(1);
foo.push(2);

JSON.stringify(foo); // "[1, 2]"

var bar = [];

bar.push(1);

JSON.stringify(bar); // "[1]"

In addition, when you use the json2.js API, your code automatically takes advantage of browser-native functionality in newer browsers.

A: You're doing something wrong. Regardless of what JSON lib you're using (presuming it actually works), serializing this:
[21031, 21486]

should produce this:
"[21031,21486]"

Not ["21031","21486"] as you've posted. That looks like you're serializing the individual elements. Post more code.

A: Cookies are strings, so all you are doing is storing a string serialisation of the array. If I do:
document.cookie = [1, 2].toString()

then document.cookie has the value "1,2", which is not an array.
EDIT: as toJSON isn't a native jQuery method, it presumably comes from a plugin. Have you checked the plugin documentation? Alternatively, try a different plugin that works as you expect.


text:
Q: Xamarin - Reload Page after Navigation.PopModalAsync() I am using Xamarin to create an app for both iOS and Android, I have a use case that I press a button and it will open a Modal, then after selecting a button on the modal, it will update some information and then I need to pop the Modal off and reload the main page under it. How is that possible?
Main Page:
public partial class MainPage : ContentPage
{
    public MainPage(Object obj)
    {

        InitializeComponent();

        // do some things with obj...

        BindingContext = this;

    }

    public ButtonPressed(object sender, EventArgs args)
    {
        Navigation.PushModalAsync(new SecondaryPage(newObj));
    }

}

Secondary Page:
public partial class SecondaryPage : ContentPage
{
    public SecondaryPage(Object newObj)
    {

        InitializeComponent();

        BindingContext = this;

    }

    public ButtonPressed(object sender, EventArgs args)
    {
        // Do something to change newObj

        Navigation.PopModalAsync();
    }

}

So after the PopModalAsync(), I need to be able to call the MainPage() constructor but pass it the "newObj" that I changed in the SecondaryPage. Is this even possible?

A: The proper way to do this in .Net is to set up an event:
public partial class SecondaryPage : ContentPage
{
    public SecondaryPage(Object newObj)
    {

        InitializeComponent();

        BindingContext = this;

    }

    // Add an event to notify when things are updated
    public event EventHandler<EventArgs> OperationCompeleted;

    public ButtonPressed(object sender, EventArgs args)
    {
        // Do something to change newObj
        OperationCompleted?.Invoke(this, EventArgs.Empty);
        Navigation.PopModalAsync();
    }

}

public partial class MainPage : ContentPage
{
    public MainPage(Object obj)
    {

        InitializeComponent();

        // do some things with obj...

        BindingContext = this;

    }

    public ButtonPressed(object sender, EventArgs args)
    {
        var secondaryPage = new SecondaryPage(newObj);
        // Subscribe to the event when things are updated
        secondaryPage.OperationCompeleted += SecondaryPage_OperationCompleted;
        Navigation.PushModalAsync(secondaryPage);
    }

    private void SecondaryPage_OperationCompleted(object sender, EventArgs e)
    {
        // Unsubscribe to the event to prevent memory leak
        (sender as SecondaryPage).OperationCompeleted -= SecondaryPage_OperationCompleted;
        // Do something after change
    }
}


text:
Q: Как узнать в какие группы установлено приложение vk mini apps? Запрос на установку приложения в группу выполненен таким образом, но если пользователь уже установил приложение в группу, то как узнать список группу/группу в которое уже установлено приложение?
Еще не совсем понятно каждый раз токен надо получать для работы с группой? или токен надо сохранять куда либо и потом извлекать его?
const installApp = await bridge.send('VKWebAppAddToCommunity')
        .then((data) => {
          if (data.group_id) {
            console.log(data.group_id);
            return data.group_id;
          }
        })
        .catch((error) => {
          // Ошибка
          console.log(error);
        });

        const tokenGroup = await bridge.send("VKWebAppGetCommunityToken", {
            app_id: 51531083,
            group_id: Number(installApp),
            scope: 'messages'
            })
           .then((data) => {
             if (data.access_token) {
                console.log(data.access_token);
                return data.access_token;
             }
           })
           .catch((error) => {
             // Ошибка
             console.log(error);
           });


text:
Q: jQuery Data Tables with Lightning Component? I implemented jQuery Data Tables to display child records based on a filter in a another component. Whenever the filter is selected, the jQuery Data Table updates to only show the records related to that filtered value, however, when I start typing in the Search Field in the data table (with a filter on), the table "starts from scratch" and shows all my records - is there a way to make it work so the search "continues" based on the filter? Please see images attached below.
https://prnt.sc/j4qpm6
https://prnt.sc/j4qrav


text:
Q: Passing number as props in React becomes Object object I am trying to send a number as props in React. When I access it it is not a number, it is Object object. I know that an object in JS is {} but in this context I expect a number not an object.
Here is the value
<button onClick={this.showNumber} value={1}>

Here is the function recieving the value
showNumber(value) {
    const userInput = document.getElementById("userInput");
    console.log("value", value);
    userInput.value = value;
  }

I have tried "1" but it do not work and feels wrong anyway. I want to pass a number, not a string.

A: Set onClick to a function that calls your function with the value you want:
<button onClick={() => {this.showNumber(1)}}>one</button>
<button onClick={() => {this.showNumber(2)}}>two</button>
<button onClick={() => {this.showNumber(3)}}>three</button>

You may need to bind this.showNumber.


text:
Q: Pygame window does not close properly when clock.tick in the loop I'm working on a project and when I add the clock.tick to my main game loop, my pygame window doesnt close.

def game_loop():
    """The main game loop that runs as the game runs. Returns when the pygame window is closed."""
    global running
    global timer
    while running:
        while timer > screen.fixed_fps:
            fixed_update()
            timer -= screen.fixed_fps
        update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                return
        screen.clock.tick(screen.fps)
        timer += delta_time()
    pygame.quit()
    return

When I click the X, the screen freezes until I let go, but unless I click the X in a very specific time frame( I usually need to click it 20 times to close) it doesnt work.

A: This is likely because of the way you are handling the QUIT event in your event loop. The pygame.event.get() function returns all of the events that have occurred since the last time it was called, so if there is a delay in your loop, the QUIT event may not be handled until multiple events have accumulated. To fix this, you should move the QUIT event handling code to the top of your event loop so that it is handled as soon as the event occurs. Also you could try to add pygame.display.update() after the event handling to make sure it is updated.
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                pygame.quit()
                return
        while timer > screen.fixed_fps:
            fixed_update()
            timer -= screen.fixed_fps
        update()
        screen.clock.tick(screen.fps)
        timer += delta_time()


text:
Q: How to get error estimates for fit parameters in scipy.stats.gamma.fit? I have some which I am fitting to the gamma distribution using scipy.stats. I am able to extract the shape, loc, and scale params and they look reasonable with the data ranges I expect.
My question is: is there a way to also get the errors in the parameters? something like the output of curve_fit. NOTE: I don't use curve fit directly because it is not working properly and most of the time is not able to compute the parameters of the gamma distribution. On the other hand, scipy.stats.gamma.fit works ok.
This is an example (no my actual data) of what I am doing.
from scipy.stats import gamma
shape = 12; loc = 0.71; scale = 0.0166
data = gamma.rvs(shape, loc=loc, scale=scale, size=1000)
params = gamma.fit(data) # params close to but not the same as (shape, loc, scale)
# HOW TO ESTIMATE/GET ERRORS FOR EACH PARAM?

Thanks in advance

A: edit
Warning: The following illustrates the use of GenericLikelihoodModel following the example in the question.
However, in the case of the gamma distribution the location parameter shifts the support of the distribution which is ruled out by the general assumptions for maximum likelihood estimation. The more standard usage would fix the support, floc=0, so it is just a two-parameter distribution. In that case, standard MLE theory applies.
Statsmodels has a generic class for maximum likelihood estimation, GenericLikelihoodModel. It's not directly designed for this case, but can be used with some help (defining attributes and providing start_params).
import numpy as np
from statsmodels.base.model import GenericLikelihoodModel

from scipy.stats import gamma
shape = 12; loc = 0.71; scale = 0.0166
data = gamma.rvs(shape, loc=loc, scale=scale, size=1000)
params = gamma.fit(data) # params close to but not the same as (shape, loc, scale)
# HOW TO ESTIMATE/GET ERRORS FOR EACH PARAM?

print(params)
print('\n')

class Gamma(GenericLikelihoodModel):

    nparams = 3

    def loglike(self, params):
        return gamma.logpdf(self.endog, *params).sum()

res = Gamma(data).fit(start_params=params)
res.df_model = len(params)
res.df_resid = len(data) - len(params)
print(res.summary())

This prints the following
(10.31888758604304, 0.71645502437403186, 0.018447479022445423)

Optimization terminated successfully.
         Current function value: -1.439996
         Iterations: 69
         Function evaluations: 119
                                Gamma Results
==============================================================================
Dep. Variable:                      y   Log-Likelihood:                 1440.0
Model:                          Gamma   AIC:                            -2872.
Method:            Maximum Likelihood   BIC:                            -2852.
Date:                Sun, 12 Jul 2015
Time:                        04:00:05
No. Observations:                1000
Df Residuals:                     997
Df Model:                           3
==============================================================================
                 coef    std err          z      P>|z|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
par0          10.3187      2.242      4.603      0.000         5.925    14.712
par1           0.7165      0.019     37.957      0.000         0.679     0.753
par2           0.0184      0.002      8.183      0.000         0.014     0.023
==============================================================================

Other results based on the maximum likelihood estimates are then also available, for example a z-test that the first parameter is 10 can be performed like either by specifying a restriction matrix or by using a string expression with the equality:
>>> res.t_test(([1, 0, 0], [10]))
<class 'statsmodels.stats.contrast.ContrastResults'>
                             Test for Constraints
==============================================================================
                 coef    std err          z      P>|z|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
c0            10.3187      2.242      0.142      0.887         5.925    14.712
==============================================================================

>>> res.t_test('par0=10')
<class 'statsmodels.stats.contrast.ContrastResults'>
                             Test for Constraints
==============================================================================
                 coef    std err          z      P>|z|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
c0            10.3187      2.242      0.142      0.887         5.925    14.712
==============================================================================


text:
Q: is it possible to only load part of a pickle file or can I use streaming? I have a large pickle file which is a pandas dataframe. The data is minute data measuring certain weather metrics.
There are two operations that need to be run, on a daily basis which take longer than needed & I believe that is because of how I am loading the data.
# load the pickle file
with open('my_file.pickle', 'rb') as handle:
    df = pd.read_pickle(handle)

So currently I load whole file just to get the last record in the dataframe which gives me the last time stamp of the last observation. Is there a way of loading part of the file?
Also once I have last time stamp, I then want to append the new data. Do I need to open the whole file & append the data to the dataframe or is there a better alternative?


text:
Q: How to configure Eclipse with Tomcat and MySQL I am trying to get rows from a MySQL table with JSP in Eclipse. My Tomcat server is started, jConnector is in JRE Library and my code is:
import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {
    public Connection getDBConnection() throws Exception{
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","myuname","mypass");
        return conn;
    }
}

JSP is :
<jsp:useBean id="dbConn" scope="request" class="dbConn.DBConnection"/>
<%
  Connection conn=dbConn.getDBConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select * from user");
%>

...

<%while (rs.next()){ %>

<%=rs.getString(2) %>

<%} %>

<%
  if(conn!=null)
    conn.close();
%>

And final result is

error: root cause
javax.servlet.ServletException: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

A:
jConnector is in JRE Library

This is not correct. You should drop the JAR file in web project's /WEB-INF/lib folder. That should be basically all you need to do. Everything in this folder ends up in webapp's runtime classpath. If you have also fiddled around in project's Build Path properties, then I recommend to undo that all. It would otherwise possibly break or confuse something else now or in the future.
See also:

*

*Class not found loading JDBC org.postgresql.Driver

Unrelated to the concrete problem: writing Java code in a JSP file is strongly discouraged since a decade. I recommend to write Java code in normal Java classes and learn about servlets to control the HTTP requests.
See also:

*

*How to avoid Java code in JSP files?

*Our Servlets wiki page

*Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern


text:
Q: Hiding all but the selected rows of data I am unable to send any pictures,
The data contains 98 column headings, with the first column being unique identifiers, and 1000 rows of items.  I receive commentary on specific items throughout the day.  Updating those items is difficult because they are hard to locate.  I would like to be able to enter, in a specified input cell, a comma delimited list of the target items (on the order of 50 items), and have all of the data rows become hidden except for the rows of the specified items.
A VBA solution is acceptable.  I am currently trying to do this using filters but the quantity of items makes this unwieldy and I am looking for a better solution.
        col1      col2  .....col98
        UniqueID  header.....header

row1    ItemA1    Data2  ....Data98

row2    ItemA2    Data2  ....Data98

row3    ItemA3    Data2......Data98

row4    ItemA4    Data2......Data98

Input cell: A2,A3  hides all rows except the rows with A2,A3
        col1      col2  .....col98
        UniqueID  header.....header

row2    ItemA2    Data2  ....Data98

row3    ItemA3    Data2......Data98

A: EDIT: As Scott points out in his comment, the answer below does not provide the ability to navigate to and edit the source data, it only displays it.  His answer provides a solution to the question.  I'll leave the answer in place as general information in case someone needs a method to just display the selected data, and because Scott's answer references it.
There is a relatively simple way to do what you want by creating the output you want in another location rather than trying to hide rows (I believe that would require VBA).  There are two parts to the problem you described: entering your selections in a comma delimited list and using that, and displaying the selected rows.  You can simplify it by listing your selections individually in a column, so I'll cover the output first.
The output you want can be done using the VLOOKUP function.  You can create one generic formula and replicate it as needed.  In this step, I'll assume your selections are listed individually in a column.  If you enter them that way, all you need is this step.  If you want to use the comma delimited list, step two will decode that to create the individual selections in the column.
So let's assume your reference names are in column A, the associated data is in the 97 adjacent columns, and all of the data are in rows 2 through 1001.  I'll describe doing your output in another location on the same sheet.  If you want to do this on a separate sheet, just include the sheet reference as part of any cell reference that points to your data.
Let's assume that your output starts in column DA, row 2, and includes the next 97 columns.  The selections are entered in DA2 through DA50, or however many you need.  The entry in DB2 would be:
    =IFERROR(VLOOKUP($DA2,$A$2:$CW$1001,COL(DB2)-COL($DA2)+1,FALSE),"")

Quick explanation: The IFERROR at the beginning and double quotes at the end force blank output if the lookup produces an error.  This will happen if there is no entry in DA.  So if you start with no entries, the output will be blank.  If there are 10 entries, all the rows after that will be blank.
VLOOKUP looks for the selection entered in DA2, works with all of the data (I show it as A2:CW1001), compares DA2 to the entries in column A (the "false" specifies an exact match), and returns the contents in the associated column of data for the matching row.  Since the output columns are in the same relative positions as the data, the COL functions calculate the equivalent column in the data.  Copy this formula across all of the output columns and for as many rows as you need.
As the selections are entered in column DA, the data for each selection will appear.  If you want to enter the selections as a comma delimited list, keep in mind that there is a character limit for a cell.  If you are talking about 50 selections and the unique references are long, it could exceed the character limit.  That said, here is a way to decode it.  I will describe a method that isn't elegant, but it keeps it simple and easy to debug.
Let's assume you enter your list in DA1.  We will use the three columns to the left of DA to decode the list, so that would be CX, CY, and CZ.  In CX, we locate the commas.  The formula in CX2 is:
    =FIND(",",DA1)

After the first comma, we need to tell the FIND function where to start looking for the next one, so CX3 is:
    =FIND(",",$DA$1,CX2+1)

This formula can be copied down for as many rows as you need.  In each row, it will start looking in the character position after the last comma.  Next, we'll skip to column CZ and calculate the length of each selection.  In CZ2, the formula is:
    =IF(ISERROR(CX2),LEN($DA$1),CX2-1)

If no comma was found (an error was returned), there was either zero or one entries in the list, in which case the length is whatever is in the list.  Otherwise, it is one character fewer than the position of the comma.  For CZ3, the formula is:
    =IF(ISERROR(CX2),NA(),IF(ISERROR(CX3),LEN($DA$1)-CX2,CX3-CX2-1))

If no comma was found in the previous search, it means there is no selection to decode for this row and it returns an error code.  If no comma was found for the current row, it means that there is one more entry and its length is everything after the last comma.  If another comma was found, the length is the characters between the last two commas.  This formula can be copied down for as many rows as you need.
In column CY, we calculate the starting position of each entry in the list.  CY2 doesn't need a value because it is always the beginning.  The formula in CY3 is:
    =CZ2+2

That's the character after the length of the first item plus the comma.  The formula in CY4 is:
    =CY3+CZ3+1

That's the starting position of the previous item plus the length of the previous item plus the comma.  Copy that down for as many rows as you need.  Now you have identified where to find the entry in the list for each row.  The next step is to populate the selections.  The formula for DA2 is:
    =IF(ISBLANK(DA1),"",LEFT(DA1,CZ2))

If the list is empty, this returns a blank.  Otherwise it takes the leftmost characters for the length previously calculated.  The formula for DA3 is:
    =IF(OR(ISBLANK($DA$1),ISNA(CZ3)),"",MID($DA$1,CY3,CZ3))

If either the list is empty or the length calculation returned #NA, the result is blank.  Otherwise, it uses the calculated start position and length to return those characters from the list.  This formula can be copied down for as many rows as you need.  Now the output works the same as in the first part, only the selection entries are populated from the comma delimited list.

A: fixer1234's answer is a good start.
I'll assume that you have used the techniques in that answer to take the identifiers
that you are interested in and break them out into separate rows in column DA.
And let's assume that your identifiers are the states of the USA:

Enter some arbitrary heading in row 1 of some other unused column; e.g., CZ.
Enter
=(COUNTIF(DA$2:DA$51,A2)>0)

into CZ2 and drag down to cover all the rows where you have data (i.e., through row 1001).
Note that my use of DA$51 assumes that you have up to 50 targets that you're searching for
(as you said).
This will evaluate to TRUE on every row where the value in column A appears
(at least once) in column DA.
Now filter column CZ and display only the rows where it is TRUE:


text:
Q: Cisco 2821 call history SetupTime Сisco logs (show call history voice) have parameter SetupTime.
in what format this parameter? Example:
SetupTime=780535960 ms

Milliseconds since what time?

A: It is the number of milliseconds since the router booted. From the documentation:
http://www.cisco.com/en/US/docs/ios/12_3/vvf_r/vrg_sh1_ps1839_TSD_Products_Command_Reference_Chapter.html#wp1161535

SetupTime
Value of the system UpTime, in milliseconds, when the call associated with this entry was started.


text:
Q: Swashbuckle.OData doesn't add controller if I change the Entity Set name I have Swashbuckle.OData working with OData (4.0) in an Web Api project.
It's all working fine, but when I change the 'Entity Set' name in the OData config, the OData controller no longer shows up in the swagger JSON file, and consequently the Swagger UI.
This works: builder.EntitySet("AccountRecords");
This does not work: builder.EntitySet("Records");
Is there something I am doing wrong or missing? How do I 'tell' Swashbuckle.OData that the name is different?

A: The name of the controller and EntitySet should match. For your AccountRecords you should have a AccountRecordsController (which I guess you have) and if you rename the entity to Records the controller name should be RecordsController.
This is not a Swashbuckle/Swagger problem but WebAPI naming convention.
I wonder if your API actually works if the names don't match.


text:
Q: How do theoretical physicists do their calculations? I am doing a PhD in experimental particle physics. In this field, at least in my experience, almost the 100 % of the job is done using some software, for example Root and Python, because of the numerical nature of the calculations.
On the other hand, each time I had to do some theoretical developments I ended up working in a mixture of hand work (as in primary school but harder) and some tedious calculations with the help of wxMaxima. When I tried to switch 100 % to wxMaxima (as if it were Python for numerical analysis) I found that it was not possible, some (yet simple but tedious) calculations I still had to proceed by hand to get human-readable and useful results.
So this makes me wonder how do theoretical physicists deal with this? How are calculations done? By hand in a paper? With CAS software? Which software? A mixture of different ways as I did? In your minds?

A: Depends on what you are doing. The nature of work in theoretical physics is as varied as the theoretical physicist. Most likely, the work takes on different forms.
For the most simple calculations, good old pen(cil) and paper is still the best thing. I keep a little note book beside me where I can calculate something quickly if I need to.
For more complicated calculations, the use of analytic software (such as Maple or Mathematica) is essential. I use Maple. The reason is that such large calculation can easily cause you to make copy errors (forgetting a factor of 2 or something) when you do it on paper. That can waste a lot of time when you need to find such errors and redo the calculations. If you use the analytic software in a disciplined way, you can avoid such copy errors. Keep in mind that the results that the analytic software produces can be pages of messy expressions. Such software is not good at doing simplifications of expressions. However, it does provide some tools that you can use to try and simplify the expressions. Over the years, I have develop a skill at simplifying such expressions using these tools, but it is something of an art that takes time to learn.
For numerical simulations/calculations one can use software that is better geared for such calculations. There are many options. I use octave, which is open source. Julia is a more powerful version suitable for parallel computing.
Then last and not least, when I need to do a derivation instead of a calculation, I often do it directly in Latex. Analytic software is not always suitable for such derivations. Since I would then have to do it on paper anyway and because I often want to write it up in some document that I may submit for publication, I just do the derivations directly in Latex, which I can compile and keep as notes. The benefit is that I can include as many steps in the derivation as I like and then just comment out some of them when I compile the document.
Hope it give you a glimpse of the way theoretical physicists do their work. Sorry if this is a somewhat subjective view of it.


text:
Q: Extracting HTML information from a URL I'm trying to write a program in python that reads all the data from a web page and appends the contents of any of the heading tags <h1> through <h6> to a list. So far I'm just trying to get the website information in the first place, which has proven to be difficult.
Edit: This is for a class. Sadly, we aren't allowed to use libraries that don't come pre-installed with python.
Edit 2: Thank you for all your tips. The program now successfully reads the HTML of a given website. Does anybody have any suggestions to search for a specific string (being the <H> tags) within webPage?
import urllib
from urllib.request import urlopen

#example URL that includes an <h> tag: http://www.hobo-web.co.uk/headers/
userAddress = input("Enter a website URL: ")

webPage = urllib.request.urlopen(userAddress)

print (webPage.read())

webPage.close()

A: I would suggest using the requests library.
import requests

r = requests.get('http://www.hobo-web.co.uk/')
print(r.text)

check the docs out at http://docs.python-requests.org/en/latest/user/quickstart/

A: I suppose you are using python3 for fetching the web page.
It can be fetched by following code:
import urllib
from urllib.request import urlopen

address = "http://www.hobo-web.co.uk/headers/"
webPage = urllib.request.urlopen(address)

print (webPage.read())

For pulling out information from a webpage, you can use BeautifulSoup.
It is an incredible tool for pulling out information from a webpage. You can use it to extract tables, lists, paragraph and you can also put filters to extract information from web pages.
Install it from here: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-beautiful-soup

A: Check out the beautifulsoup library. Its an API for parsing the DOM tree.
You can do things like soup.find_all('h1') which will return a list of all h1 elements.

A: Its better to use with open so it automatically closes connections. Heres an example:
import urllib.request
address = "http://www.hobo-web.co.uk/headers/"
with urllib.request.urlopen(address) as response:
   html = response.read()
   print html

A: your webPage variable is a network object, to actually get the html content use
content = webPage.read()

for getting the contents of the heading tag you can use the BeautifulSoup library
from bs4 import BeautifulSoup

htmlContent = webPage.read()
soup = BeautifulSoup(htmlContent, from_encoding=htmlContent.info().getparam('charset'))
heads = soup.find_all('head').text

now heads is a list of the content of all occurrences of the head tag

to read more about the BeautifulSoup library go to: http://www.crummy.com/software/BeautifulSoup/bs4/doc/


text:
Q: How do I know if my Stata file needs unicode translate? I suspect I do not quite grasp the difference between extended ASCII and unicode and what they mean to Stata, therefore I am not able to determine if I need to use unicode translate on my Stata files or not. The files contain a lot of text with Nordic characters such as å, ä, ö that I need to analyse, so this is potentially important.
Using the browse mode, the text contained in the string variables in the original file looks fine to me (e.g. "myös"). But running unicode analyze suggests using unicode translate.
However, if I do unicode translate (using encoding that allows for Nordic characters which are important in my data), in browse mode the text looks all wrong, displaying weird characters in places of å, ä and ö (e.g. "myäs" instead of "myös").
How I even ran into this issue is that someone had translated the data, and the text was messed up. I eventually found out by unicode restore that the original looks fine. But I do not understand why that someone wanted to translate it in the first place, if it was fine already.
So my question is: if the data LOOKS fine to me, does that mean it is then fine for Stata as well? And if it LOOKS wrong to me, can it still be fine for Stata?
I have tried:
//browse mydata.dta: looks fine

unicode encoding set iso-8859_10-1998
unicode analyze mydata.dta

        1  file(s) specified
        1  file(s) to be examined ...

  File mydata.dta (Stata dataset)
        1 str# variable needs translation
          -------------------------------------------------------------------------------------------------------------------------------
          Some elements of the file appear to be UTF-8 already.  Sometimes elements that need translating can look like UTF-8.  Look at
          these example(s):
              variable name "xyzö"
              contents of str# variable ntrl
          Do they look okay to you?
          If not, the file needs translating or retranslating with the transutf8 option.  Type
              . unicode   translate "mydata.dta", transutf8
              . unicode retranslate "mydata.dta", transutf8
          -------------------------------------------------------------------------------------------------------------------------------
          File needs translation.  Use unicode translate on this file.

unicode translate mydata.dta

//browse mydata.dta: Nordic characters in text all messed up

I have tried different encodings as well, none seem to work. And based on help encodings I've understood that because of the use of Nordic letters it should be iso-8859_10-1998.


text:
Q: Returning values to functions in tikz \begin{tikzpicture}[declare function=
{matmul(\a,\b)=
\def\product{}
\foreach \i in \b
{
\def\temp{}
\foreach \j in \a
{
\edef\temp{\temp,{\i}[0]*{\j}[0]+{\i}[1]*{\j}[1]+{\i}[2]*{\j}[2]}
}
\edef\product{\product,{\temp}}
}
}
]
\end{tikzpicture}

Here is my function that takes two lists and operates on them. I don't know how to return the \product list back to the function. e.g.
output = matmul(list1,list2)

I would now want output to contain everything that \product contained

A: Your approach has the problem that \foreach does things in groups, and \edef only defines macros locally. So you could do \xdef instead. Because you may run out of name space and/or overwrite other macros, one usually does this with some temporary macros that have hilarious names and some @ in to minimize the chance of doing harm. So the following monster does some matrix multiplication with \foreach. There are other ways which might be more elegant but also harder to comprehend. You need to feed the function matmult with the names of the macros (no \) that contain the matrices. The monster does some minimal sanity checks.
\documentclass{article}
\usepackage{tikz}
\makeatletter
\pgfmathdeclarefunction{matmult}{2}{%
\begingroup%
\edef\pgfutil@tempA{\csname #1\endcsname}%
\edef\pgfutil@tempB{\csname #2\endcsname}%
\foreach \pgfutil@tempa [count=\pgfutil@tempc starting from 0] in \pgfutil@tempA
{\foreach \pgfutil@tempb [count=\pgfutil@tempd starting from 0] in \pgfutil@tempa
{\xdef\pgfutil@tempe{\pgfutil@tempd}%
}\xdef\pgfutil@tempf{\pgfutil@tempc}%
}%
\edef\tmp@cols@A{\pgfutil@tempe}%
\edef\tmp@rows@A{\pgfutil@tempf}%
\foreach\pgfutil@tempa[count=\pgfutil@tempc starting from 0]in\pgfutil@tempB
{\foreach\pgfutil@tempb[count=\pgfutil@tempd starting from 0]in\pgfutil@tempa
{\xdef\pgfutil@tempe{\pgfutil@tempd}%
}\xdef\pgfutil@tempf{\pgfutil@tempc}%
}%
\edef\tmp@cols@B{\pgfutil@tempe}%
\edef\tmp@rows@B{\pgfutil@tempf}%
 %\typeout{A:\the\numexpr\tmp@rows@A+1 x\the\numexpr\tmp@cols@A+1,B:\the\numexpr\tmp@rows@B+1\space x\the\numexpr\tmp@cols@B+1}%
\ifnum\tmp@rows@B=\tmp@cols@A
\foreach\pgfutil@tempa in{0,...,\tmp@rows@A}%
{\foreach\pgfutil@tempb in{0,...,\tmp@cols@B}%
{\foreach\pgfutil@tempc in{0,...,\tmp@cols@A}%
{\pgfmathparse{{\pgfutil@tempA}[\pgfutil@tempa][\pgfutil@tempc]*{\pgfutil@tempB}[\pgfutil@tempc][\pgfutil@tempb]}%
\ifnum\pgfutil@tempc=0\relax
 \xdef\pgfutil@tempd{\pgfmathresult}%
\else
 \pgfmathparse{\pgfmathresult+\pgfutil@tempd}%
 \xdef\pgfutil@tempd{\pgfmathresult}%
\fi
}%
\ifnum\pgfutil@tempb=0\relax
\xdef\pgfutil@tempe{\pgfutil@tempd}%
\else
\xdef\pgfutil@tempe{\pgfutil@tempe,\pgfutil@tempd}%
\fi
 %\typeout{curr row=\pgfutil@tempe}%
}%
\ifnum\pgfutil@tempa=0\relax
\xdef\pgfutil@tempf{{\pgfutil@tempe}}%
\else
\xdef\pgfutil@tempf{\pgfutil@tempf,{\pgfutil@tempe}}%
\fi
 %\typeout{a=\pgfutil@tempa:curr mat=\pgfutil@tempf}%
}%
\edef\pgfmathresult{\pgfutil@tempf}%
\else
\typeout{Dimensions do not match up.}%
\edef\pgfmathresult{}%
\fi
\pgfmathsmuggle\pgfmathresult\endgroup%
}%
\makeatother
\begin{document}
test:\edef\matA{{1,2,1},{-1,0,1},{1,2,3}}%
\edef\matB{{1,-2,0},{-1,2,0},{2,0,-3}}%
\pgfmathparse{matmult("matA","matB")}%
$A\cdot B=\pgfmathresult$\typeout{AxB=\pgfmathresult}
\end{document}

The typeout says
AxB={1.0,2.0,-3.0},{1.0,2.0,-3.0},{5.0,2.0,-9.0}

which is correct.
A slightly shorter variant is
\documentclass{article}
\usepackage{tikz}
\makeatletter
\pgfmathdeclarefunction{Dim}{1}{%
\begingroup%
\pgfutil@tempcnta0%
\@for\pgfutil@tempa:=#1\do{\advance\pgfutil@tempcnta1}%
\edef\pgfmathresult{\the\pgfutil@tempcnta}%
\pgfmathsmuggle\pgfmathresult\endgroup%
}
\pgfmathdeclarefunction{matmult}{2}{%
\begingroup%
\edef\pgfutil@tempA{\csname #1\endcsname}%
\edef\pgfutil@tempB{\csname #2\endcsname}%
\pgfmathtruncatemacro{\tmp@rows@A}{Dim("\pgfutil@tempA")-1}%
\pgfmathtruncatemacro{\tmp@cols@A}{Dim("\pgfutil@tempA[0]")-1}%
\pgfmathtruncatemacro{\tmp@rows@B}{Dim("\pgfutil@tempB")-1}%
\pgfmathtruncatemacro{\tmp@cols@B}{Dim("\pgfutil@tempB[0]")-1}%
 %\typeout{A:\the\numexpr\tmp@rows@A+1 x\the\numexpr\tmp@cols@A+1,B:\the\numexpr\tmp@rows@B+1\space x\the\numexpr\tmp@cols@B+1}%
\ifnum\tmp@rows@B=\tmp@cols@A
\foreach\pgfutil@tempa in{0,...,\tmp@rows@A}%
{\foreach\pgfutil@tempb in{0,...,\tmp@cols@B}%
{\foreach\pgfutil@tempc in{0,...,\tmp@cols@A}%
{\pgfmathparse{{\pgfutil@tempA}[\pgfutil@tempa][\pgfutil@tempc]*{\pgfutil@tempB}[\pgfutil@tempc][\pgfutil@tempb]}%
\ifnum\pgfutil@tempc=0\relax
 \xdef\pgfutil@tempd{\pgfmathresult}%
\else
 \pgfmathparse{\pgfmathresult+\pgfutil@tempd}%
 \xdef\pgfutil@tempd{\pgfmathresult}%
\fi
}%
\ifnum\pgfutil@tempb=0\relax
\xdef\pgfutil@tempe{\pgfutil@tempd}%
\else
\xdef\pgfutil@tempe{\pgfutil@tempe,\pgfutil@tempd}%
\fi
 %\typeout{curr row=\pgfutil@tempe}%
}%
\ifnum\pgfutil@tempa=0\relax
\xdef\pgfutil@tempf{{\pgfutil@tempe}}%
\else
\xdef\pgfutil@tempf{\pgfutil@tempf,{\pgfutil@tempe}}%
\fi
 %\typeout{a=\pgfutil@tempa:curr mat=\pgfutil@tempf}%
}%
\edef\pgfmathresult{\pgfutil@tempf}%
\else
\typeout{Dimensions do not match up.}%
\edef\pgfmathresult{}%
\fi
\pgfmathsmuggle\pgfmathresult\endgroup%
}%
\makeatother
\begin{document}
test:\edef\matA{{1,2,1},{-1,0,1},{1,2,3}}%
\edef\matB{{1,-2,0},{-1,2,0},{2,0,-3}}%
\pgfmathparse{matmult("matA","matB")}%
$A\cdot B=\pgfmathresult$\typeout{AxB=\pgfmathresult}

\pgfmathparse{Dim("\matA[0]")}%
\pgfmathresult
\end{document}

One can go on and use more \@fors to avoid the \xdefs, if needed. It might be just get harder and harder to understand.


text:
Q: Solr query a particular field ONLY using qf: parameter I'm trying to search for a particular set of keywords keyword1,keyword2 or keyword3 in a particular field. I'm doing it by using the query,

http://localhost:8983/solr/gettingstarted_shard2_replica2/browse?q=keyword1
  keyword 2 keyword 3&qf=field1

However, when I run this it finds keyword2 in another field field2 and returns that row as well! As far as I understand, the qf:field1 parameter limits the search for all the keywords in just field1 right?
Where am I incorrect? Is it because of the schema that I have defined?
My schema config is:
<field name="field1" type="text_general" indexed="true"/>
<field name="field2" type="strings" indexed="false"/>

A: Disclaimer: I'm the author of Solr Query Debugger Google Chrome plugin.
I suggest to use this debugger in order to see what's is execute and explain why your query have such strange behaviour.
Just execute the solr query in your browser and then start the Solr Query Debugger plugin.
In the plugin page you'll see Debug and Echo tabs where explain what's executed by Solr. In the Explain tab you'll see the score explanations  structured as a tree.

A: Are you using standard (default) Query parser or an eDisMax one? If standard (most likely), then you need to use df parameter.
qf parameter is used with eDisMax, but then you need to also have defType=edismax
Enabling debug flag will show you against which fields the search is actually issued.


text:
Q: Why AtomicReference CAS return false with value 128? I was using AtomicReference to implement AtomicInteger. However while in testing I notice even in single threaded environment the CAS operation got stuck once its value hit 128.. Am I doing something wrong or there is a caveat in AtomicReference (may be related to CPU)? Here is my code:
public class MyAtomInt {
  private final AtomicReference<Integer> ref;

  public MyAtomInt(int init) {
    ref = new AtomicReference<Integer>(init);
  }

  public MyAtomInt() {
    this(0);
  }

  public void inc() {
    while (true) {
      int oldVal = ref.get();
      int nextVal = oldVal + 1;
      boolean success = ref.compareAndSet(oldVal, nextVal); // false once oldVal = 128
      if (success) {
        return;
      }
    }
  }

  public int get() {
    return ref.get();
  }

  static class Task implements Runnable {

    private final MyAtomInt myAtomInt;
    private final int incCount;

    public Task(MyAtomInt myAtomInt, int cnt) {
      this.myAtomInt = myAtomInt;
      this.incCount = cnt;
    }

    @Override
    public void run() {
      for (int i = 0; i < incCount; ++i) {
        myAtomInt.inc();
      }
    }
  }

  public static void main(String[] args) throws Exception {
    MyAtomInt myAtomInt = new MyAtomInt();
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.submit(new Task(new MyAtomInt(), 150)).get();
    System.out.println(myAtomInt.get());
    exec.shutdown();
  }
}

A: The reason for this is that when you box an int into an Integer, you may or may not create a new Integer instance.  If you do, then the new instance may not have reference equality with other Integer instances, even if they share the same value.  AtomicReference.compareAndSet() uses reference equality (identity) for comparisons.
The key is in how the compiler handles automatic boxing of int values: it emits calls to Integer.valueOf().  As an optimization, Integer.valueOf() has a cache of boxed integers, and by default that cache includes values up to 128.  If you box an integer n twice, you will get the same Integer reference back each time if the value was small enough to be in the cache; otherwise, you will get two separate instances.
Currently, you unbox the old value, compute the new value, and when you call compareAndSet() you box the old value again.  Once you hit 128, you stop getting cached values, so the second boxed copy is no longer the same one that's in the AtomicReference.


text:
Q: Collapsible network plot in R I am trying to implement collapsible network in R based on the blog post more network layouts. However, I am always getting the error of Object not found.
devtools::install_github
devtools::install_github("timelyportfolio/networkD3@feature/d3.chart.layout")
library(htmltools)
library(networkD3)

hc = hclust(dist(mtcars))

treeNetwork(
   as.treeNetwork(hc, "mtcars")
)

tagList(
  lapply(
    c("tree.cartesian"
      ,"tree.radial"
      ,"cluster.cartesian"
      ,"cluster.radial"
     )
    ,function(chartType){
      hierNetwork(as.treeNetwork(hc), type=chartType, zoomable=T,    collapsible=T)
    }
  )
)
tree.cartesian

EDIT 1
How can we use these graphs for an edges file to build a network? Example:
From   To
 A      B
 A      C
 A      D
 D      L
 L      J
 J      T
 B      O

A: The current official dev version of networkD3 (v0.4.9000 as of 2017.09.02) has a new function treeNetwork that enables collapsible trees.
devtools::install_github("christophergandrud/networkD3")
library(networkD3)

hc <- hclust(dist(mtcars))
treeNetwork(hc)

edges <- read.table(header = T, text = "
From   To
NA     A
A      B
A      C
A      D
D      L
L      J
J      T
B      O
")

edges <- as_treenetdf(edges, cols = c(nodeId = "To", parentId = "From"))
treeNetwork(edges)

It's still in development, so we'd appreciate feedback.

A: Yes:
library(networkD3)
to <- c("a","a","a","d","l","j","b")
from <- c("b","c","d","l","j","t","o")
df <-data.frame(to,from)
simpleNetwork(df)

You should use the official networkD3 package:
install.packages("networkD3")

A: I'm not sure what the tree.cartesian object is supposed to be in your code, but you're getting the error "Object not found" because the tree.cartesian object is never being created in your code.
Having said that, your code will work if you remove your lapply command from the tagList function. Or more succinctly...
devtools::install_github("timelyportfolio/networkD3@feature/d3.chart.layout")
library(networkD3)

hc = hclust(dist(mtcars))

hierNetwork(as.treeNetwork(hc), type = 'tree.cartesian', zoomable = T, collapsible = T)
# or
hierNetwork(as.treeNetwork(hc), type = 'tree.radial', zoomable = T, collapsible = T)
# or
hierNetwork(as.treeNetwork(hc), type = 'cluster.cartesian', zoomable = T, collapsible = T)
# or
hierNetwork(as.treeNetwork(hc), type = 'cluster.radial', zoomable = T, collapsible = T)

Just to be clear, you are using a branch of networkD3, which (as far as I know) is no longer being developed. There is some current intention to add this feature to the official networkD3 branch, but at the moment (v0.3.1), this feature (collapsible branches) is not currently available.


text:
Q: Calculate the percentile rank of a set of scores based on a population I have a set of scores on 31 competencies for one individual
data <- data.frame(scores=sample(100,31,replace=T),row.names=paste0("X",1:31))

and I have a benchmark file for scores of 100 (or any number) individuals on the same 31 competencies
bmark <- data.frame(replicate(31,sample(0:100,100,rep=TRUE)))

I need to calculate the percentile rank of each competency score for the individual relative to the benchmark for that competency, the output should look something like this (random values, just to demonstrate the required format)
data <- data.frame(scores=sample(100,31,replace=T),percentile=sample(100,31,replace=T),row.names=paste0("X",1:31))

I can calculate each score's percentile rank using a basic percentile formula:
length(bmark$X31[bmark$X31<data$scores[rownames(data)=="X31"]])/length(bmark$X31)*100

But I don't know how to make this work across the whole data set at once, so that each row in data$percentile has the appropriate value for the corresponding competency in the benchmark file. I could do this with a loop, but still not great with R vectorisation.
EDIT:
Here is a dput of my data frames for subsequent comments/questions below. Note that this is a snippet of the bmark data (only a few columns/'competencies'). Data is in long format (thus has all compentencies) and has a column identifier for subject (data$Split).
bmark
    bmark <- structure(list(FinPerf = c(2.41333333333333, 2.94047619047619,
2.87538940809969, 2.16666666666667, 2.34146341463415, 2.425,
2.58148148148148, 2.97297297297297, 2.325, 2.52542372881356,
2.35593220338983, 1.69105691056911, 2.73493975903614, 2.01666666666667,
1.94010416666667, 1.94603174603175, 2.56666666666667, 2.48550724637681,
2.61846110878369, 2.15873015873016, 2.56565656565657, 2.23529411764706,
2.98974358974359, 3.09195402298851, 2.59289617486339, 2.44306418219462,
2.72345679012346, 2.85714285714286, 2.62962962962963, 2.90833333333333
), Opt = c(2.74, 2.83928571428571, 2.87383177570093, 2.56692506459948,
2.64634146341463, 2.6625, 2.53333333333333, 3.31081081081081,
2.4, 2.50847457627119, 2.55932203389831, 1.89024390243902, 2.60240963855422,
2.3, 2.3203125, 2.24761904761905, 2.85, 2.76086956521739, 2.78064516129032,
2.30952380952381, 2.65151515151515, 2.29411764705882, 3.06923076923077,
3.12931034482759, 2.64754098360656, 2.08695652173913, 2.41111111111111,
2.78571428571429, 2.88888888888889, 2.9625), SatExp = c(2.44,
2.58928571428571, 2.70093457943925, 2.11111111111111, 2.29268292682927,
2.525, 2.33888888888889, 3.10810810810811, 2.375, 2.73728813559322,
2.6864406779661, 1.91463414634146, 2.65060240963855, 2.225, 2.01171875,
1.94285714285714, 2.6, 2.51086956521739, 2.83225806451613, 2.28571428571429,
2.84848484848485, 2.02941176470588, 3.13076923076923, 3.22413793103448,
2.45491803278689, 2.5, 2.78518518518518, 2.85714285714286, 2.75925925925926,
2.975)), .Names = c("FinPerf", "Opt", "SatExp"), class = "data.frame", row.names = c(NA,
-30L))

And data
    data <- structure(list(Area.short = structure(c(13L, 25L, 28L, 6L, 3L,
16L, 12L, 9L, 7L, 20L, 21L, 14L, 5L, 4L, 26L, 8L, 11L, 18L, 2L,
27L, 31L, 30L, 24L, 19L, 1L, 23L, 22L, 10L, 15L, 29L, 17L, 13L,
25L, 28L, 6L, 3L, 16L, 12L, 9L, 7L, 20L, 21L, 14L, 5L, 4L, 26L,
8L, 11L, 18L, 2L, 27L, 31L, 30L, 24L, 19L, 1L, 23L, 22L, 10L,
15L, 29L, 17L, 13L, 25L, 28L, 6L, 3L, 16L, 12L, 9L, 7L, 20L,
21L, 14L, 5L, 4L, 26L, 8L, 11L, 18L, 2L, 27L, 31L, 30L, 24L,
19L, 1L, 23L, 22L, 10L, 15L, 29L, 17L, 13L, 25L, 28L, 6L, 3L,
16L, 12L, 9L, 7L, 20L, 21L, 14L, 5L, 4L, 26L, 8L, 11L, 18L, 2L,
27L, 31L, 30L, 24L, 19L, 1L, 23L, 22L, 10L, 15L, 29L, 17L, 13L,
25L, 28L, 6L, 3L, 16L, 12L, 9L, 7L, 20L, 21L, 14L, 5L, 4L, 26L,
8L, 11L, 18L, 2L, 27L, 31L, 30L, 24L, 19L, 1L, 23L, 22L, 10L,
15L, 29L, 17L, 13L, 25L, 28L, 6L, 3L, 16L, 12L, 9L, 7L, 20L,
21L, 14L, 5L, 4L, 26L, 8L, 11L, 18L, 2L, 27L, 31L, 30L, 24L,
19L, 1L, 23L, 22L, 10L, 15L, 29L, 17L, 13L, 25L, 28L, 6L, 3L,
16L, 12L, 9L, 7L, 20L, 21L, 14L, 5L, 4L, 26L, 8L, 11L, 18L, 2L,
27L, 31L, 30L, 24L, 19L, 1L, 23L, 22L, 10L, 15L, 29L, 17L, 13L,
25L, 28L, 6L, 3L, 16L, 12L, 9L, 7L, 20L, 21L, 14L, 5L, 4L, 26L,
8L, 11L, 18L, 2L, 27L, 31L, 30L, 24L, 19L, 1L, 23L, 22L, 10L,
15L, 29L, 17L), .Label = c("ACHIEVEMENT", "Apprec", "Bal", "Belong",
"BrandPass", "Burn", "Care", "Comms", "Comp", "CONNECTION", "Consul",
"Fam", "FinPerf", "Forw", "FRANCHISE PARTNERSHIP", "Ful", "GENSAT",
"Harm", "Innov", "Integ", "LeadCom", "LEADERSHIP", "LIFESTYLE",
"MarkSup", "Opt", "Part", "PracSup", "SatExp", "SUPPORT", "Syst",
"Train"), class = "factor"), MM = c(22.8758169934641, 29.4117647058824,
7.84313725490196, -29.4117647058824, 11.7647058823529, -3.26797385620914,
7.84313725490196, 11.1111111111111, 15.6862745098039, 9.80392156862744,
9.80392156862744, 5.88235294117648, 33.3333333333333, 17.6470588235294,
13.7254901960784, 19.6078431372549, 11.7647058823529, 1.96078431372548,
13.7254901960784, 21.5686274509804, 15.6862745098039, 11.1111111111111,
21.5686274509804, 1.96078431372548, 20.4481792717087, -3.26797385620914,
10.1307189542484, 20.0980392156863, 10.9803921568627, 14.7058823529412,
11.7647058823529, 22.2222222222222, 16.6666666666667, 8.33333333333333,
-25, 0, -11.1111111111111, 0, -5.55555555555557, 16.6666666666667,
58.3333333333333, 16.6666666666667, 0, 25, 11.1111111111111,
0, 33.3333333333333, 8.33333333333333, -11.1111111111111, 11.1111111111111,
50, 0, 11.1111111111111, 16.6666666666667, 25, 16.6666666666667,
-9.25925925925926, 13.8888888888889, 10.4166666666667, 8.33333333333333,
19.4444444444444, 10.3448275862069, 100, 66.6666666666667, 66.6666666666667,
-33.3333333333333, 100, 55.5555555555556, 100, 55.5555555555556,
100, 33.3333333333333, 66.6666666666667, -11.1111111111111, 100,
77.7777777777778, 33.3333333333333, 66.6666666666667, 66.6666666666667,
11.1111111111111, 77.7777777777778, 66.6666666666667, 33.3333333333333,
33.3333333333333, 100, 33.3333333333333, 80.952380952381, 55.5555555555556,
44.4444444444444, 66.6666666666667, 53.3333333333333, 55.5555555555556,
57.4712643678161, 7.40740740740741, 33.3333333333333, -5.55555555555557,
-5.55555555555557, -5.55555555555557, -14.8148148148148, -22.2222222222222,
-3.70370370370369, -22.2222222222222, -27.7777777777778, -16.6666666666667,
7.40740740740741, 22.2222222222222, 7.40740740740741, 3.70370370370369,
5.55555555555557, 5.55555555555557, 14.8148148148148, -3.70370370370369,
5.55555555555557, 11.1111111111111, 0, 18.5185185185185, -11.1111111111111,
11.1111111111111, -12.3456790123457, -10.1851851851852, 9.72222222222223,
5.55555555555557, 5.55555555555557, 0.766283524904221, 25.9259259259259,
27.7777777777778, 11.1111111111111, -55.5555555555556, 22.2222222222222,
3.70370370370369, 27.7777777777778, 29.6296296296296, 38.8888888888889,
11.1111111111111, 22.2222222222222, 11.1111111111111, 38.8888888888889,
22.2222222222222, 29.6296296296296, 16.6666666666667, 11.1111111111111,
-3.70370370370369, 22.2222222222222, 11.1111111111111, 27.7777777777778,
18.5185185185185, 14.8148148148148, -5.55555555555557, 22.2222222222222,
0, 22.2222222222222, 29.1666666666667, 11.1111111111111, 13.8888888888889,
16.0919540229885, -6.17283950617284, 11.1111111111111, -18.5185185185185,
14.8148148148148, -18.5185185185185, -28.3950617283951, -44.4444444444444,
-16.0493827160494, -29.6296296296296, -25.9259259259259, -33.3333333333333,
3.70370370370369, -3.70370370370369, -18.5185185185185, -18.5185185185185,
-7.40740740740741, -14.8148148148148, -6.17283950617284, -28.3950617283951,
3.70370370370369, -3.70370370370369, -16.0493827160494, -11.1111111111111,
-7.40740740740741, -4.76190476190478, -20.1646090534979, -17.9012345679012,
-14.8148148148148, -14.8148148148148, -8.02469135802468, -13.6653895274585,
42.2222222222222, 53.3333333333333, 33.3333333333333, -86.6666666666667,
26.6666666666667, 2.22222222222221, 46.6666666666667, 20, 60,
46.6666666666667, 53.3333333333333, 6.66666666666667, 66.6666666666667,
51.1111111111111, 42.2222222222222, 46.6666666666667, 33.3333333333333,
11.1111111111111, 55.5555555555556, 33.3333333333333, 33.3333333333333,
33.3333333333333, 55.5555555555556, 13.3333333333333, 42.8571428571429,
-2.22222222222221, 33.3333333333333, 51.6666666666667, 36, 35.5555555555555,
32.4137931034483, 77.7777777777778, 44.4444444444444, 44.4444444444444,
-66.6666666666667, 77.7777777777778, 62.962962962963, 100, 77.7777777777778,
77.7777777777778, 55.5555555555556, 66.6666666666667, 11.1111111111111,
88.8888888888889, 70.3703703703704, 62.962962962963, 55.5555555555556,
55.5555555555556, 11.1111111111111, 70.3703703703704, 55.5555555555556,
44.4444444444444, 55.5555555555556, 62.962962962963, 11.1111111111111,
58.7301587301587, 45.679012345679, 55.5555555555556, 72.2222222222222,
46.6666666666667, 48.1481481481482, 53.639846743295), Split = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L), .Label = c("Success4u", "NSW/ACT",
"QLD", "SA/WA", "VIC/TAS", "Type 1", "Type 2", "Type 3", "Franchise Sector Benchmark"
), class = "factor")), .Names = c("Area.short", "MM", "Split"
), row.names = c(NA, 248L), class = "data.frame")

A: Here's a way to get the percentile on each benchmark for one subject. We use the empirical cumulative distribution function to calculate percentiles:
# Fake data
set.seed(595)
dat <- data.frame(scores=sample(100,31,replace=T),row.names=paste0("X",1:31))
bmark <- data.frame(replicate(31,sample(100,100,rep=TRUE)))

# Get percentile on each benchmark for one subject
dat$percentile = mapply(function(ref, subj) {
  ecdf(ref)(subj)*100
}, ref=bmark, subj=dat$scores)

dat

    scores percentile
X1      28         25
X2      25         30
X3      91         92
...
X29     42         46
X30     76         71
X31      1          2

Here's a boxplot of the distribution of bmark for each competency, along with a red dot showing where the subject scored on each of them:
boxplot(bmark)
points(1:31, data$scores, pch=16, col="red")

If you have multiple subjects, you can get their percentiles all at once. We take the mapply code from above, which calculates percentiles for a single subject, and wrap it in sapply, which feeds the mapply code each subject in succession and returns all of the results in a single matrix:
# Scores on 31 benchmarks for 20 subjects. Each column is a subject.
set.seed(58)
subjects = as.data.frame(replicate(20, sample(100, 31, replace=TRUE)))

# Get percentile on each benchmark for each subject
percentile.score = sapply(subjects, function(s) {
  mapply(function(ref, subj) {
    ecdf(ref)(subj)*100
  }, ref=bmark, subj=s)
})

percentile.score

    V1 V2 V3  V4 V5  V6 V7  V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20
X1  28 95  2  24 95  18 61   6 44  11  82  50  28  37  59  41  91  51  35  76
X2  20 49 62   3 24  24 54  23 50  50  60  95  25  63  57  78  72  89  79  66
X3  69 37 40  49 59  30 91   5 92  43  56  22  34  33  28  54  35   1  59  29
...
X29 34 42 10  76 40  48 13  36 76  13  88  91  99  31  13  76  93  42  31  91
X30 16 66 86  56 21  67 86  45 81  16  70  66  24  11  23  18  32  53  31  32
X31 81 81 52   2  3  32 64  36 33  39  92 100  80   2  44  63  59   2  34  99


text:
Q: Grails - Loading image from the controller I am trying to retrieve zip file from FTP, unzip it, and get xml file and image file from them and parse the xml, display the contents of xml and image.
byte[] image = ftpClientService.getThumbnailInZip(customer.ftpUser,
    customer.ftpPassword, customer.ftpHost, customer.ftpToWrapDirectory,
    fileName)
FileOutputStream fos1 = new FileOutputStream("zip.img")
try {
    fos1.write(image);
} finally {
    fos1.close();
}
return [
    command: this,
    fileName: fileName,
    applicationName: applicationName,
    contentProvider: contentProvider,
    operatingSystem: operatingSystem,
    handSets: handSets,
    zipImg:"zip.img" ]

I could finish the xml part successfully and image also I am able to retrieve from the zip in a byte format( i could convert it to a file using file outputstream),
Now I am stuck in sending the image to gsp and to display that. Any inputs are much appreciated.
Thanks

A: If you want to use the image only once, meaning it should always be extract from the zip file, then embedding the img in base64 format into the webpage is a good option here because you don't need to worry about the image file after sending that base64 encoding value to gsp.
If you still need that image file to be used by other http requests then you should extract the images to a folder and send the list of img paths to gsp.

A: You can either

*

*point img src="${g.createLink(action: 'a', params: [p: p])}" to some other action (with createLink) that will cache the image on your server side,

*or embed it right into HTML, like in this question.

A: Browsers can render byte arrays if you specify the format.
Having a variable image in the model sent to the gsp of type byte[], this is the way to render it HTML:
<img src="data:image/png;base64,${image.encodeBase64()}"/>

You also need to specify if it's image/png or other format.


text:
Q: Извлечь значение из объекта Сделал запрос к БД, подучил ответ в виде:
Array ( [0] => stdClass Object ( [SUM(`number_room`)] => 42 ) )

Обычно значение удавалось получить с помощью:
$value[0]->index; //если Array ( [0] => stdClass Object ( [index] => 42 ) )

Но тут так не получается. Как извлечь число?


text:
Q: How to display category page for custom post type (made with ACF)? I just started to create a website working with ACF. On this website, I want to display Artworks by Category.
I want a Menu like that :
Home - Painting - Scultpure - etc...
      - Golf     - Old School
      - Social   - New era

But I can't figure out how to add in a Menu a category pages.
I already created a Taxonomie for the Category.
Thanks for your help!

A: Kindly share your code.
I assume you have created custom taxonomies with the CPT.
If so then make sure  you have the following in your snippet 'has_archive' => true,
You'll have the following then, sitename.com/{{taxonomy}}/{{slug}}
And then just go ahead and create archive-{{name}}.php for a custom archive landing page else archive.php would do.


text:
Q: develop custom extension in magento, which processes image of product and tags with prominent color codes I have been struggling in figuring out how can I tag a product with a color and when a user selects color from color picker, user should get all the products tagged with particular color or near by hex codes.

A: A very simple solution is to create two product attribute like main_color and related_colors, main_color should be a single selection input type and should be searchable while related_color should be Multi-selectbut not searchable. you can then assign one main color to the product and multiple related color shades. On frontend you have to custom code, get the related_color attribute value,extract all related color codes and fetch all products having main_color with that value.
Hope this makes some sense.


text:
Q: Variable and parameter in a method I am new to Python and I have an issue with it when I am creating a function:
I created a dictionary where the keys are parameters like n_estimators, C, max_depths for instance.
I have a loop where I would like to set the parameters for a given estimator (which is an input of my funtion) but I got an issue.
For instance let's say my estimator is a RandomForestClassifier,
The code will be:
key = 'n_estimators'
estimator = estimator.set_params(key=100)

I got the error:
ValueError: Invalid parameter key for estimator RandomForestClassifier.

I understand the problem which is that set_params consider key as a parameter (and not as 'n_estimators') but I don't know how to solve the problem yet.
I would really appreciate any advice here.

A: Use a dict with the ** operator:
key = 'n_estimators'
estimator = estimator.set_params(**{key: 100})

A: or you know, just
estimator.set_params(n_estimators=100)

A: You could consider using GridSearchCV to evaluate a model over multiple hyperparameter values, and for different hyperparameters.


text:
Q: Get cached thumbnail image url in Magento 2.2 I need to get the url of a product cached thumbnail image.
This is my code:
$appEmulation->startEnvironmentEmulation($_POST['store_id'], \Magento\Framework\App\Area::AREA_FRONTEND, true);

$image = $helperImage->create()->init($product, 'product_thumbnail_image')
                    ->constrainOnly(TRUE)
                    ->keepAspectRatio(TRUE)
                    ->keepTransparency(TRUE)
                    ->keepFrame(FALSE)
                    ->resize(245,300);

$temp[] = $image->getUrl();

$appEmulation->stopEnvironmentEmulation();

The path I get is http://domain.com/pub/static/version1522319407/frontend/Vendor/theme_child/it_IT/Magento_Catalog/images/product/placeholder/thumbnail.jpg
How can I get the cached thumbnail image url?
Thanks in advance.