text:
Q: How to add a jquery slider in an html4/css2 webpage at a particular place. Friends
I have created an website with HTML4/CSS2. And now i want to add an jquery image slider. But, i haven't work with jquery. And i have downloded some free jquery slider. But, the problem is i have not been able to set them in a particular place. I am in a fix. please help me out.

A: First read how to use the slider plugin.
For any plugin you need to download plugin package with supported JS, CSS, images files then
1. Include required site CSS file and plugin CSS file

2. Include jQuery file

3. Include dependency files for the plugin if needed
   (some plugin require jqueryui, mousewheel,etc)

4. Write the HTML content code as instructed in plugin document for your requirement.
   (something like

item1

 etc)

5. Configure the HTML content with jQuery plugin. This happens usually at document.ready event.Like

$(document).ready(function(){

 $('.my-slider').pluginfunction(); // .slider();
});


text:
Q: upper bound for the ratio of two solutions of a Diophantine equation Let $P(x)$ be a polynomial of degree $d$ with integer coefficients. Define
$$
A=\{(m,n)\in (\mathbb{Z}\setminus\{0\})^2: m-n=P(m)-P(n) \}
$$ and
$$
L=\max_{(m,n)\in A}\left|\frac{m}{n}\right|
$$
I can prove that $L$ is bounded by some constant depending on $P$. But I'm wondering if $L$ is bounded by some constant depending only on $d$, the degree of $P$.

A: The answer is no. For example, let $d=2$. Consider the quadratic polynomial $P(x)=(x-1)(x-n)$. Then $P(m)=0$ has two solutions, who ratio goes to infinity as $n$ goes to infinity.

redpajama_set_name: RedPajamaStackExchange


text:
Q: linux/solaris insert date & time at the beginning of each line in file I want to add date & time at the begging of each line in some file
I used sed in order to add the date & time before each line in file
please advice what I need to update in my sed in order to support this action ,
I can accept other solution with awk or perl one liner etc ...
# date="[`date +%d"/"%b"/"%G"-"%T`]"
# echo $date
[21/Feb/2013-14:07:58]
#  sed "s/^/$date /" file
sed: command garbled: s/^/[21/Feb/2013-14:07:58] /

example
file before edit
 param1=3478374
 param2=34128374
 param3=34783743

file after edit
 [21/Feb/2013-14:07:58] param1=3478374
 [21/Feb/2013-14:07:58] param2=34128374
 [21/Feb/2013-14:07:58] param3=34783743

A: or use another separator like "|", i tried it on mac.
$ date="[`date +%d"/"%b"/"%G"-"%T`]"
$ echo $date
[21/Feb/2013-21:17:22]

$ cat /tmp/a
param1=3478374
param2=34128374
param3=34783743

$ sed "s|^|$date  |g" /tmp/a
[21/Feb/2013-21:14:15]  param1=3478374
[21/Feb/2013-21:14:15]  param2=34128374
[21/Feb/2013-21:14:15]  param3=34783743

A: There are too many slashes in that sed command.  The ones in your $date variable need to be escaped.
This is what I get (which is a somewhat more useful error message):
> echo foo | sed "s/^/[21/Feb/2013-14:07:58] /"
sed: -e expression #1, char 9: unknown option to `s'
> echo foo | sed "s/^/[21\/Feb\/2013-14:07:58] /"
[21/Feb/2013-14:07:58] foo

Escaped:
date="[`date +%d"\/"%b"\/"%G"-"%T`]"

You may need to double-escape your variable if single-escaping is not enough because the escaping may be removed when the variable is dereferenced:
date="[`date +%d"\\/"%b"\\/"%G"-"%T`]"


text:
Q: CentOS 5.8 - Can't login to tty1 as root after updates? I've ran a yum update on my CentOS 5.8 box and now I am unable to log into the console as root.  Basically what happens is I receive the login prompt, enter the correct username and password, and am immediately spit back to the login prompt.  If I enter an incorrect password, I am told the password is incorrect, therefore I know that I am using the proper credentials.
The only log I can seem to find of what's going on is /var/log/secure which simply contains:
15:33:41 centosbox login: pam_unix(login:session): session opened for user root by (uid=0)
15:33:41 centosbox login: ROOT LOGIN ON tty1
15:33:42 centosbox login: pam_unix(login:session): session closed for user root

The shell is never spawned.
I've checked my inittab which looks like so:
1:2345:respawn:/sbin/mingetty tty1
2:2345:respawn:/sbin/mingetty tty2
3:2345:respawn:/sbin/mingetty tty3
4:2345:respawn:/sbin/mingetty tty4
5:2345:respawn:/sbin/mingetty tty5
6:2345:respawn:/sbin/mingetty tty6

And my /etc/passwd which properly has bash listed for my root user:
root:x:0:0:root:/root:/bin/bash

As well as permissions on /tmp (1777) & /root (750).
I've attempted re-installing bash, pam, and mingetty to no avail, and confirmed /bin/login exists.
Any thoughts would be greatly appreciated.
Thanks!!
-slashp

A: You're logging in just fine - whatever shell you're starting is exiting immediately.
Boot to single user mode or a rescue CD and chroot into your installed system.
First, check your startup scripts (profile, bashrc and the like). Make sure they're not doing anything that would exit immediately.
Can you even chroot? If you can't, that means it can't run your shell. Try chrooting and specify a static shell.
Change root's shell to a static shell and that should help. Then from there you can reboot into the installed system and start figuring things out.
Are you using selinux/apparmor? Have you tried setting enforcement to permissive? Does that help?

A: Perhaps you had a major glibc change or something that's affecting login. Did you reboot following your yum update or at least see what was updated in /var/log/yum.log? The latter will tell you which packages were modified/updated.
You can verify the installed /bin/login binary with:
# rpm -qf /bin/login
util-linux-2.13-0.59.el5
# rpm -vV util-linux | grep S.5

And report back if there's any output from the second command...
Edit:
So it appears to be a library problem. Let's assume that it's /bin/login that's causing the issue. Can you run a quick ldd on the binary? Does your output look like this?
# ldd /bin/login
    linux-vdso.so.1 =>  (0x00007fffb57ec000)
    libcrypt.so.1 => /lib64/libcrypt.so.1 (0x00000035f3c00000)
    libpam.so.0 => /lib64/libpam.so.0 (0x00000035f8800000)
    libpam_misc.so.0 => /lib64/libpam_misc.so.0 (0x00000035f3800000)
    libaudit.so.0 => /lib64/libaudit.so.0 (0x00000035f6c00000)
    libc.so.6 => /lib64/libc.so.6 (0x00000035f1800000)
    libdl.so.2 => /lib64/libdl.so.2 (0x00000035f2400000)
    /lib64/ld-linux-x86-64.so.2 (0x00000035f1400000)


text:
Q: Assigning to a Range ignores the type of data being assigned - workarounds? If I have a variant array (that is, the elements can be various types) and assign the array to the Range.Value (or constants to Range.Formula) property then Excel will automatically convert the values being passed into a 'best-guess' type based on the destination cell's NumberFormat.
For example, in the below all 'numbers stored as strings' (intentionally) will be converted to numeric types if they are assigned to a cell with the "General" number format.
Sub foo()

    Selection.Value = Array( _
        100, _
        "100", _
        "A Cat", _
        "2012-05-02", _
        "36.4")

End Sub

In other words, Range.Value = Range.Value does not round-trip as type-information in the data being assigned back is ignored on the assignment back to Range.Value, with only the Range.NumberFormat controlling its interpretation.
Are there any good workarounds to prevent or deal with this?
The only one I can think of is to iterate through the array, testing if it is a string and adding an apostrophe in front if it is. This has an undesireable side-effect of the apostrophe actually being present in the workbook (albeit ignored by Excel itself for the purposes of Range.Value etc). It is not possible (as far as I know) to assign number formats to cells en-masse based (otherwise one could prepare an array that has the number formats of the data to 'pre-load' the cells with the correct number format).
I use arrays and collections frequently to greatly increase the performance of data processing but I desire, when finally pumping the data out, to preserve the datatype.

A: You can get around this by putting an apostrophe in front of any text values:
Sub foo()

    Selection.Value = Array( _
        100, _
        "'100", _
        "A Cat", _
        "'2012-05-02", _
        "'36.4")

End Sub


text:
Q: Software to export Abs (Absolute database) to MySQL Can anyone suggest any software to export Abs (Absolute database) to MySQL? I have already tried: http://www.componentace.com/bde_replacement_database_delphi_absolute_database.htm; which returns corrupted data ( trying to decode data (exporting Abs to MySQL) ) and ABC Amber Absolute Converter 1.03 which was unable to handle data (900 MB). Can anyone suggest alternatives? The database contains only one table (entries) and has one column in it WIDEMEMO. I am trying to export data to MySQL as stated above.

A: Have you thought about writing your own?  If you've got one table with just one column, this isn't a big programming project.
Just open the table, loop through the records, writing them to temporary intermediate file. Then write another program to read them in to MySQL.
But, I agree with Radu: if you're in good standing with the Absolute people, they should be able to help you.  Maybe they, like me, can't figure why you just wouldn't write a quick and dirty program to do this.
Sorry if I've overlooked something that makes my suggestion unreasonable.

A: As I've answered in your other question, have you tried to contact the vendor(Absolute database producer) and ask some advice from it?


text:
Q: In Python, what is `sys.maxsize`? I assumed that this number ( 2^63 - 1 ) was the maximum value python could handle, or store as a variable. But these commands seem to be working fine:
>>> sys.maxsize
9223372036854775807
>>> a=sys.maxsize + 1
>>> a
9223372036854775808

So is there any significance at all? Can Python handle arbitrarily large numbers, if computation resoruces permitt?
Note, here's the print-out of my version is:
>>> sys.version
3.5.2 |Anaconda custom (64-bit)| (default, Jul  5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)]'

A: Documentation for sys.maxsize:

An integer giving the maximum value a variable of type Py_ssize_t can take. It's usually 2**31 - 1 on a 32-bit platform and 2**63 - 1 on a 64-bit platform. python3

The largest positive integer supported by the platform's Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have. python2

What is Py_ssize_t?
It is an index type (number type for indexing things, like lists). It is the signed version of size_t (from the C language).

*

*We don't use a normal number/ int, because this is unbounded in Python.

*In Python, we don't use size_t because we want to support negative indexing, in Python we can do my_list[-4:]. So Py_ssize_t provides negative and positive numbers between a range.

*The _t stands for type, to inform developers that size_t is a type name, not a variable. Just a convention.

So what is the effect of having a limit on Py_ssize_t? Why does this limit list, strings, dict size?

*

*There is no way to index a list with an element larger than this. The list cannot get bigger than this, because it won't accept a non Py_ssize_t.

*In the dictionary case, Py_ssize_t is used as the hash. Python doesn't use linked lists in its dictionary implementation, it uses Open Addressing/ probing, where if a collision is found, we a systematic way of getting another place to find the key and put the value. So you can't have more than Py_ssize_t in a dictionary in Python.

In all practical cases (64 bit machines aka. probably you), you will run out of memory before you max out Py_ssize_t. Trying dict.fromkeys(range(sys.maxsize + 5)) never got there, it just slowed my computer down.

A: Python can handle arbitrarily large integers in computation. Any integer too big to fit in 64 bits (or whatever the underlying hardware limit is) is handled in software. For that reason, Python 3 doesn't have a sys.maxint constant.
The value sys.maxsize, on the other hand, reports the platform's pointer size, and that limits the size of Python's data structures such as strings and lists.


text:
Q: The LightningMessageChannel named boatMessageChannel was not found in the workspace In LWC Super badge Challenge 2, we have to create a lightning message channel named BoatMessageChannel.
I tried creating it with the name boatMessageChannel coz the naming should be in the camel case.
But while verifying the channel I'm not able to complete the challenge though I have verified that the channel is properly deployed by including it into lwc.
After searching a while I found that I have to use BoatMessageChannel.messageChannel-meta.xml rather than boatMessageChannel.messageChannel-meta.xml. but while deploying this file I'm getting the following error:

A: The Lightning Message Channel should be in the camel case is the best practice.
But in challenge 2, they are applying the test case which checks the LMC with Pascal case, and hence it fails to complete.
Note: while deploying from the file editor context we are getting the mentioned error that

SourceElementDoesNotExist: The LightningMessageChannel named boatMessageChannel was not found in the workspace.

To deploy it, we have to right-click on the file from the file explorer which will not give the error mentioned above.


text:
Q: Embedding an application inside another application I'm sure some of you noticed that if you have Acrobat Reader ( or any other pdf viewer ) , and open a pdf in Firefox , you will see it embedded inside your tab . Is there any way to embed an application in a JFrame ?

A: This is a rather tricky. In general, native application such and Adobe Reader does not provide component which can be embedded into swing application. But in Windows there is COM/OLE approach which allows embedding of application together. This article can help you. It points on two project JCOM and JACOB which allows such embedding.

A: Yes, but that application will need to provide JComponent version which is embeddable.


text:
Q: get the array with html array path hey, i have this path name from an input element interesse[angebote][flurfuerderfahrzeuge] as a string in my php var. now i need convert it somehow (with regex or explode()) so it looks like this: $_POST['interesse']['angebote']['flurfuerderfahrzeuge'] and the use eval() to get the value. But I'm sure there must be a much easier way do this.
Any ideas? Thanks!

A: eval() is evil(). And there are some faster options to avoid it in this case.
If you just want to convert the syntax, then I have a regex:
  $name = '$' . preg_replace("/\[([^\]]+)\]/", '["$1"]', $path);

If your input string not only contains the path, but also an value (attach a dummy value if you must), then you can just use parse_str() to extract the array names into a real PHP array:
  $path = "whatever[subname][deepnesting]=1";
  parse_str($path, $as_var);
  print_r($as_var);

Tell something more about your input data.

Okay, just figured out what you mean. You want to submerge in the $_POST array. Then use step-wise references like so:
$path = "xxxx[yyyy][zzzz]";
$ref = & $_POST;

preg_match_all("/\w+/", $path, $uu);
foreach ($uu[0] as $subname) {
   $ref = & $ref[$subname];
}

print_r($ref);   // = $_POST[xxxx][yyyy][zzzz]

A: ok i know its simple but i looks so ugly,
thats what i use now:
    $path = 'interesse[angebote][flurfuerderfahrzeuge]';
    $post_var = '$_POST['.str_replace(']]', ']', str_replace('[', '][', $path));
    eval('$value = '.$post_var.';');
    echo $value;


text:
Q: Как соединить содержимое контейнера и фон в одно целое? Текст и бэкграунд "скролятся" отдельно друг от друга. Проблема решается при отключении свойства overflow-x в css, однако исчезает фон при этом.
Как сделать, чтобы содержимое контейнера не ездило при "скроллинге"?

.clear {
        float: none;
        clear: both;
    }

.background-loyality {
    background: url("/products/loyality/images/images/loyality-background.png") top center no-repeat;
    overflow-x: auto;
    margin-top: 94px;
}

.background-loyality .main-container {
    width: 1170px;
    min-height: 100%;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 330px;
    position: relative;
}
.background-loyality .main-container h1, h2, h3 {
    /* margin-top: 24px; */
    padding-top: 50px;
    color: #3c1a75;
    text-transform: uppercase;
    line-height: normal;
}

.background-loyality .main-container h1 {
    font-size: 48px;
}

.background-loyality .main-container .title-text {
    font-size: 22px;
    font-weight: bold;
    line-height: 30px;
    padding-top: 15px;
}

.background-loyality .main-container .loyality-picture {
    display: block;
    position: absolute;
    right: -100px;
    top: 160px;
}

.background-loyality .main-container .loyality-second-picture {
    display: block;
    position: absolute;
    top: 655px;
    left: -30px;
}
.background-loyality .main-container .loyality-opp {
    float: right;
    color: white;
    margin-top: 320px;
    padding-right: 73px;
    font-size: 22px;
    width: 710px;
}
.background-loyality .main-container .loyality-opp h3, h4 {
    text-transform: uppercase;
    color: white;
    font-size: 24px;
}

.background-loyality .main-container .loyality-opp ul li:before {
    content: '\25CF';
    color: white;
    padding-right: 20px;
    font-size: 16px;
}

.background-loyality .main-container .loyality-opp  ul {
    list-style-type: none;
    margin-left: 0px;
    line-height: 26px;
    margin-top: 20px;
    margin-bottom: 40px;
}

.background-loyality .main-container .loyality-opp ul li {
    font-size: 22px;
}

.background-loyality .main-container .loyality-goals {
    line-height: 26px;
}

.background-loyality .main-container .loyality-goals h2 {
    font-size: 24px;
    text-transform: uppercase;
    margin-top: 30px;
    color: #3c1a75;
    line-height: normal;
    font-weight: bold;
}

.background-loyality .main-container .loyality-goals ul li:before {
    content: '\25CF';
    padding-right: 10px;
    font-size: 16px;
}

.background-loyality .main-container .loyality-goals  ul {
    list-style-type: none;
    margin-left: 0px;
    padding-left: 0px;
    margin-top: 30px;
}

.background-loyality .main-container .loyality-goals ul li {
    font-size: 22px;
    color: #656a74;
}

.background-loyality .main-container .loyality-goals h2 {
    font-size: 24px;
}

.background-loyality .main-container .loyality-opp ul h4 {
    padding-top: 41px;
    /* margin-bottom: 11px; */
    padding-bottom: 9px;
}

Программа лояльности

Мотивационная программа для стимулирования сотрудников к повышению показателей с возможным
дальнейшим награждением

Цели:

Стимулирование сотрудников на продажу

Увеличение доли продаж

Удержание сотрудников и повышение их
лояльности к месту работы

Стимулирование сотрудников на приобретения
новых компетенций

Увеличение производительности труда

Возможности:

Создание простого и привлекательного сценария
 программы лояльности

Вовлечение сотрудников в коллективную работу

Сочетание различных типов мотиваций

Разработка как краткосрочной, так и долгосрочной
 программы мотивации

PUSH-уведомления (SMS/E-mail)

Система отчетности (Excel, CSV)

Возможность обратной связи

Контроль за поставленными и выполненными задачами

Необходимое оборудование:

ПК, планшет, смартфон


text:
Q: Clique enumeration in medium sized graph I have a medium sized graph (570 nodes, 69127 edges, density: 0.42 in gexf format) and I want to enumerate all cliques with a size larger than N (say 5). What is the most efficient method available? I am looking for a library in any popular language or software package.

A: You can use the SNAP network analysis library, which implements the Tomita et al. 2006 algorithm. All other theoretically-fast algorithms have been shown to be significantly slower than Tomita et al. in practice, for sparse graphs at least  (Eppstein et al. 2010).
If that algorithm requires too much memory for a large graph, you can try the linear-space algorithm of Eppstein et al. 2010/2011.

*

*Tomita, E.; Tanaka, A. & Takahashi, H. The worst-case time complexity for generating all maximal cliques and computational experiments. Theoretical Computer Science, 2006, 363, 28 - 42. DOI:10.1016/j.tcs.2006.06.015

*Eppstein, D.; Löffler, M. & Strash, D. Cheong, O. Listing all maximal cliques in sparse graphs in near-optimal time. ISAAC '10: Proc. 21st International Symposium on Algorithms and Computation, Springer Berlin / Heidelberg, 2010, 6506, 403-414. DOI:10.1007/978-3-642-17517-6_36

*Eppstein, D. & Strash, D. Listing all maximal cliques in large sparse real-world graphs. SEA '11: Proc. 10th International Symposium on Experimental Algorithms, Springer
Berlin / Heidelberg, 2011, 6630, 364-375. DOI:10.1007/978-3-642-20662-7_31


text:
Q: Cannot redeclare function() previously declared - Magento I have a script working where a comment is sent which includes a price. An observer.php monitoring checkout_cart_product_add_after, extracts the price and uses it to increase the original product price.
This all works great!
    <?php

class YBizz_PriceChange_Model_Observer  {

public function change_price(Varient_Event_Observer $obs) {

    $quote = $obs->getEvent()->getQuote();
    $custom = $obs->getQuoteItem();
    $product_id=$custom->getProductId();

//Get $str
$items = null;
$files = array();
$hlp = Mage::helper('orderattachment');
$obAll = Mage::getSingleton('core/session')->getObjProducts();
if(is_object($obAll)) $items = @$obAll->getItems();
if(!empty($items))
{
    foreach($items as $item)
    {
        $it = $item->getData();
        if($product_id == intval($it['set_product_id'])) $files[] = $it;
    }
}
foreach($files as $file){
$str = $file['set_comment'];

//Extract Price from $str
$from = "£";
$to = "]";

function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
return substr($sub,0,strpos($sub,$to));
}
$var =  getStringBetween($str,$from,$to);

//Calc Custom Price
    $_product=Mage::getModel('catalog/product')->load($product_id);
    $newprice=$_product->getPrice()+$var;

// Set the custom price
    $custom->setCustomPrice($newprice);
    $custom->setOriginalCustomPrice($newprice);

// Enable super mode on the product.
    $custom->getProduct()->setIsSuperMode(true);

}

}

}

However, what I need is if an additional comment is sent, this too will also add to the total product price.
Currently, everytime I attempt to send another comment, I get the fatal error message:
Cannot redeclare runMyFunction() (previously declared...

or
Cannot redeclare getStringBetween() (previously declared...

I look forward to any assistance you can offer.

A: Your getStringBetween function is defined in the change_price function. Every time change_price is called, it tries to redefine getStringBetween but it can't because it's already been defined. Move getStringBetween outside of change_price. I would assume runMyFunction is defined similarly.


text:
Q: Alternate UniqueId generation technique In the application, when special types of objects are created, I need to generate a unique-id for each of them. The objects are created thro' a factory and have a high possibility of being created in a 'bulk' operation. I realize that the "Random" from the framework is not so 'random' after all, so I tried appending the time-stamp as follows:
private string GenerateUniqueId()
{
    Random randomValue = new Random();
    return DateTime.Now.Ticks.ToString() + randomValue.Next().ToString();
}

Unfortunately, even this does not work. For objects that are created in rapid succession, I generate the same Unique Id :-(
Currently, I am implementing it in a crude way as follows:
private string GenerateUniqueId()
{
    Random randomValue = new Random();
    int value = randomValue.Next();
    Debug.WriteLine(value.ToString());
    Thread.Sleep(100);
    return DateTime.Now.Ticks.ToString() + value.ToString();
}

Since this is not a very large application, I think a simple and quick technique would suffice instead of implementing an elaborate algorithm.
Please suggest.

A: A GUID is probably what you're looking for:
private string GenerateUniqueId()
{
    return Guid.NewGuid().ToString("N");
}

If you want a smaller, more manageable ID then you could use something like this:
private string GenerateUniqueId()
{
    using (var rng = new RNGCryptoServiceProvider())
    {
        // change the size of the array depending on your requirements
        var rndBytes = new byte[8];
        rng.GetBytes(rndBytes);
        return BitConverter.ToString(rndBytes).Replace("-", "");
    }
}

Note: This will only give you a 64-bit number in comparison to the GUID's 128 bits, so there'll be more chance of a collision. Probably not an issue in the real world though. If it is an issue then you could increase the size of the byte array to generate a larger id.

A: Assuming you do not want a GUID, First option would be a static field, and interlocked:
private static long lastId = 0
private static long GetNextId() {
  return Interlocked.Increment(ref lastId);
}

If you want something based on time ticks, remember the last value and if the same manually increment and save; otherwise just save:
private static long lastTick = 0;
private static object idGenLock = new Object();
private static long GetNextId() {
  lock (idGenLock) {
    long tick = DateTime.UtcNow.Ticks;
    if (lastTick == tick) {
      tick = lastTick+1;
    }
    lastTick = tick;
    return tick;
  }
}

(Neither of these approaches will be good with multiple processes.)

A: In your comments Codex you say use the unique ID as a file name. There is a specific function for generating cryptographically secure file names, Path.GetRandomFileName()
As it's cryptographically secure these would be unique even in batch operations. The format is a little horrible though as they're optimised for filenames, but it may work for other references as well.

A: Why can't your factory (which is presumably single-threaded) generate sequential unique integers? If you expected Random() to work, why not Guid() (or whatever is equivalent)?

A: If you're going to resort to coding your own UUID-generator, make sure you salt the generator.
I suggest you check out the open source package ossp-uuid, which is an ISO-C API and CLI for generating Universally Unique Identifiers.


text:
Q: In C# 4.0, is there any way to make an otherwise private member of one class available only to a specific other class? We're creating an object hierarchy where each item has a collection of other items, and each item also has a Parent property pointing to its parent item. Pretty standard stuff.  We also have an ItemsCollection class that inherits from Collection<Item> which itself has an Owner property pointing to the item the collection belongs to.  Again, nothing interesting there.
When an item is added to the ItemsCollection class, we want it to automatically set the parent of Item (using the collection's Owner property) and when the item is removed, we want to clear the parent.
Here's the thing.  We only want the Parent setter to be available to ItemsCollection, nothing else.  That way not only can we know who the parent of an item is, but we can also ensure an item isn't added to multiple collections by checking for an existing value in Parent, or letting someone arbitrarily change it to something else.
The two ways we know how to do this are:

*

*Mark the setter as private, then enclose the collection definition within the scope of the item itself.  Pro: Full protection.  Con: Ugly code with nested classes.

*Use a private ISetParent interface on Item that only ItemsCollection knows about.  Pro: Much cleaner code and easy to follow.  Con: Technically anyone who knows of the interface can cast Item and get at the setter.
Now technically via reflection anyone can get at anything anyway, but still... trying to find the best way to do this.
Now I know there was a feature in C++ called Friend or something that let you designate an otherwise private member in one class as being available to another which would be the perfect scenario, but I don't know of any such thing in C#.
In pseudocode (e.g. all the property changed notifications and such have been removed for brevity and I'm just typing this here, not copying from code), we have this...
public class Item
{
    public string Name{ get; set; }
    public Item Parent{ get; private set; }
    public ItemsCollection ChildItems;

    public Item()
    {
        this.ChildItems = new ItemsCollection (this);
    }
}

public class ItemsCollection : ObservableCollection<Item>
{
    public ItemsCollection(Item owner)
    {
        this.Owner = owner;
    }

    public Item Owner{ get; private set; }

    private CheckParent(Item item)
    {
        if(item.Parent != null) throw new Exception("Item already belongs to another ItemsCollection");
        item.Parent = this.Owner; // <-- This is where we need to access the private Parent setter
    }

    protected override void InsertItem(int index, Item item)
    {
        CheckParent(item);
        base.InsertItem(index, item);
    }

    protected override void RemoveItem(int index)
    {
        this[index].Parent = null;
        base.RemoveItem(index);
    }

    protected override void SetItem(int index, Item item)
    {
        var existingItem = this[index];

        if(item == existingItem) return;

        CheckParent(item);
        existingItem.Parent = null;

        base.SetItem(index, item);
    }

    protected override void ClearItems()
    {
        foreach(var item in this) item.Parent = null; <-- ...as is this
        base.ClearItems();
    }

}

Any other way to do something similar?

A: C# Doesn't have a friend keyword, but it has something close called internal.  You could mark the methods you want to expose in a limited fashion as internal and then only other types in that assembly will be able to see them.  If all your code is in one assembly, this won't help you much, but if this class is packaged in a separate assembly it would work.
public class Item
{
    public string Name{ get; set; }
    public Item Parent{ get; internal set; } // changed to internal...
    public ItemsCollection ChildItems;

    public Item()
    {
        this.ChildItems = new ItemsCollection (this);
    }
}

A: Here's a way you can simulate friend in C#:
Mark your properties internal and then use this attribute to expose them to friend assemblies:
[assembly: InternalsVisibleTo("Friend1, PublicKey=002400000480000094" +
                              "0000000602000000240000525341310004000" +
                              "001000100bf8c25fcd44838d87e245ab35bf7" +
                              "3ba2615707feea295709559b3de903fb95a93" +
                              "3d2729967c3184a97d7b84c7547cd87e435b5" +
                              "6bdf8621bcb62b59c00c88bd83aa62c4fcdd4" +
                              "712da72eec2533dc00f8529c3a0bbb4103282" +
                              "f0d894d5f34e9f0103c473dce9f4b457a5dee" +
                              "fd8f920d8681ed6dfcb0a81e96bd9b176525a" +
                              "26e0b3")]

public class MyClass {
   // code...
}

A: The only two things I can think of:
One:
Use sort of option number 2 you mention above (which I do constantly myself)...but make the implementation of the interface (Item) be a nested private class inside of ItemsCollection... that way only ItemsCollection knows about the setter. The interface IItem only declares a getter for Parent...and no one can cast it to Item because Item is private to ItemsCollection. So, something like:
public class ItemsCollection : ObservableCollection<IItem>
{
    private class Item : IItem
    {
        public object Parent { get; set; }
    }

    private CheckParent(IItem item)
    {
        if(item.Parent != null) throw new Exception("Item already belongs to another ItemsCollection");
        ((Item)item).Parent = this.Owner; // <-- This is where we need to access the private Parent setter
    }

    public static IItem CreateItem() { return new Item(); }
}

public interface IItem
{
    object Parent {get; }
}

and when you want ItemsCollection to set the item Parent, case the IItem instance to Item (which does expose a setter). Only ItemsCollection can do this cast, since the Item implementation is private to ItemsCollection...so I think that accomplishes what you want.
Two:
Make it internal not private...you don't get exactly what you want, but you can use InternalsVisibleToAttribute to denote that the internal members are visible to another assembly.

A: I have to solve your problem every day, but I don't do it the way you're trying to do it.
Take a step back. What is the fundamental problem you're trying to solve?  Consistency. You are trying to ensure that the "x is a child of y" relationship and the "y is the parent of x" relationship are always consistent. That's a sensible goal.
Your supposition is that every item directly knows both its children and its parent because the children collection and the parent reference are stored locally in fields. This logically requires that when item x becomes a child of item y, you have to consistently change both x.Parent and y.Children.  That presents the problem that you've run into: who gets to be "in charge" of making sure that both changes are made consistently? And how do you ensure that only the "in charge" code gets to mutate the parent field?
Tricky.
Suppose we denied your supposition. It need not be the case that every item knows both its children and its parent.
Technique #1:
For example, you could say that there is one special item called "the universe", which is the ancestor of every item except itself. "The universe" could be a singleton stored in a well-known location. When you ask an item for its parent, the implementation could find the universe, and then do a search of every descendant of the universe looking for the item, keeping track of the path as you go. When you find the item, great, you're done. You look one step back on the "path" that got you there, and you have the parent. Even better, you can provide the entire chain of parents if you want; after all, you just computed it.
Technique #2:
That could be expensive if the universe is large and it takes a while to find each item.  Another solution would be to have the universe contain a hash table that maps items to their parents, and a second hash table that maps items to a list of their children. When you add child x to parent y, the "add" method actually calls the Universe and says "hey, item x is now parented by y", and the Universe takes care of updating the hash tables. Items do not contain any of their own "connectedness" information; that's the responsibility of the universe to enforce.
A down side of that is it is possible for the universe to then contain cycles; you could tell the universe that x is parented by y and y is parented by x. If you wish to avoid this then you'd have to write a cycle detector.
Technique #3:
You could say that there are two trees; the "real" tree and the "facade" tree. The real tree is immutable and persistent. In the real tree, every item knows its children but not its parent. Once you have built the immutable real tree, you make a facade node that is a proxy to the root of the real tree. When you ask that node for its children, it makes a new facade node wrapped around each child and sets the parent property of the facade node to the node that was queried for its children.
Now you can treat the facade tree as a parented tree, but the parent relationships are only computed as you traverse the tree.
When you want to edit the tree, you produce a new real tree, re-using as much of the old real tree as possible. You then make a new facade root.
The downside of this approach is that it only works if you typically traverse the tree from the top down after every edit.
We use this latter approach in the C# and VB compilers because that is precisely the situation we are in: when we rebuild a parse tree after a code edit we can re-use much of the existing immutable parse tree from the previous text. We always traverse the tree from the top down, and only want to compute the parent references when necessary.

A: The first thing that struck me with this scenario is that there is definite feature envy between ItemCollection and Item.  I understand your desire to make adding the child item to the collection and setting the parent to be an autonomous operation, but really I think the responsibility of maintaining that relationship is in the Item, not the ItemCollection.
I would recommend exposing the ChildItems on Item as a Read-Only collection (with IEnumerable<Item> perhaps), and putting the AddChild(Item child),RemoveChild(Item child), ClearChildren(), etc methods on the Item.  That puts the responsibility for maintaining the Parent with the Item where you don't have concerns leaking into other classes.

A: How about you make sure that only the item's current collection can orphan the item. That way no other collection can set the item's parent while it belongs to a collection. You could use a unique key of some sort so that a third party couldn't get involved:
public sealed class ItemsCollection : ObservableCollection<Item>
{
    private Dictionary<Item, Guid> guids = new Dictionary<Item, Guid>();

    public ItemsCollection(Item owner)
    {
        this.Owner = owner;
    }

    public Item Owner { get; private set; }

    private Guid CheckParent(Item item)
    {
        if (item.Parent != null)
            throw new Exception("Item already belongs to another ItemsCollection");
        //item.Parent = this.Owner; // <-- This is where we need to access the private Parent setter
        return item.BecomeMemberOf(this);

    }

    protected override void InsertItem(int index, Item item)
    {
        Guid g = CheckParent(item);
        base.InsertItem(index, item);
        guids.Add(item, g);
    }

    protected override void RemoveItem(int index)
    {
        Item item = this[index];
        DisownItem(item);
        base.RemoveItem(index);
    }

    protected override void DisownItem(Item item)
    {
        item.BecomeOrphan(guids[item]);
        guids.Remove(item);
    }

    protected override void SetItem(int index, Item item)
    {
        var existingItem = this[index];
        if (item == existingItem)
            return;
        Guid g = CheckParent(item);
        existingItem.BecomeOrphan(guids[existingItem]);
        base.SetItem(index, item);
        guids.Add(item, g);
    }

    protected override void ClearItems()
    {
        foreach (var item in this)
            DisownItem(item);
        base.ClearItems();
    }
}

public class Item
{
    public string Name { get; set; }
    public Item Parent { get; private set; }

    public ItemsCollection ChildItems;

    public Item()
    {
        this.ChildItems = new ItemsCollection(this);
    }

    private Guid guid;

    public Guid BecomeMemberOf(ItemsCollection collection)
    {
        if (Parent != null)
            throw new Exception("Item already belongs to another ItemsCollection");
        Parent = collection.Owner;
        guid = new Guid();
        return guid; // collection stores this privately
    }

    public void BecomeOrphan(Guid guid) // collection passes back stored guid
    {
        if (guid != this.guid)
            throw new InvalidOperationException("Item can only be orphaned by its current collection");
        Parent = null;
    }
}

Obviously there is redundancy there; the item collection is storing a second item collection (the dictionary). But there are numerous options for overcoming that which I assume you can think of. It's beside the point here.
However I do suggest you consider moving the task of child-item management to the item class, and keep the collection as 'dumb' as possible.
EDIT: in response to your quesion, how does this prevent and item from being in two ItemsCollections:
You ask what the point of the guids is. Why not just use the collection instance itself?
If you replace the guid argument with a collection reference, you could add an item to two different collections like this:
{
    collection1.InsertItem(item);  // item parent now == collection1
    collection2.InsertItem(item);  // fails, but I can get around it:
    item.BecomeOrphan(collection1); // item parent now == null
    collection2.InsertItem(item);  // collection2 hijacks item by changing its parent (and exists in both collections)
}

Now imagine doing this with the guid argument:
{
    collection1.InsertItem(item);  // item parent now == collection1
    collection2.InsertItem(item);  // fails, so...
    item.BecomeOrphan(????); // can't do it because I don't know the guid, only collection1 knows it.
}

So you can't add an item to more than one ItemsCollection. And ItemsCollection is sealed so you can't subclass it and override its Insert method (and even if you did that, you still couldn't change the item's parent).

A: You can do these sorts of things using Delegates:
public delegate void ItemParentChangerDelegate(Item item, Item newParent);

public class Item
{
    public string Name{ get; set; }
    public Item Parent{ get; private set; }
    public ItemsCollection ChildItems;

    static Item()
    {
        // I hereby empower ItemsCollection to be able to set the Parent property:
        ItemsCollection.ItemParentChanger = (item, parent) => { item.Parent = parent };
        // Now I just have to trust the ItemsCollection not to do evil things with it, such as passing it to someone else...
    }
    public static void Dummy() { }

    public Item()
    {
        this.ChildItems = new ItemsCollection (this);
    }
}

public class ItemsCollection : ObservableCollection<Item>
{
    static ItemsCollection()
    {
        /* Forces the static constructor of Item to run, so if anyone tries to set ItemParentChanger,
        it runs this static constructor, which in turn runs the static constructor of Item,
        which sets ItemParentChanger before the initial call can complete.*/
        Item.Dummy();
    }
    private static object itemParentChangerLock = new object();
    private static ItemParentChangerDelegate itemParentChanger;
    public static ItemParentChangerDelegate ItemParentChanger
    {
        private get
        {
            return itemParentChanger;
        }
        set
        {
            lock (itemParentChangerLock)
            {
                if (itemParentChanger != null)
                {
                    throw new InvalidStateException("ItemParentChanger has already been initialised!");
                }
                itemParentChanger = value;
            }
        }
    }

    public ItemsCollection(Item owner)
    {
        this.Owner = owner;
    }

    public Item Owner{ get; private set; }

    private CheckParent(Item item)
    {
        if(item.Parent != null) throw new Exception("Item already belongs to another ItemsCollection");
        //item.Parent = this.Owner;
        ItemParentChanger(item, this.Owner); // Perfectly legal! :)
    }

    protected override void InsertItem(int index, Item item)
    {
        CheckParent(item);
        base.InsertItem(index, item);
    }

    protected override void RemoveItem(int index)
    {
        ItemParentChanger(this[index], null);
        base.RemoveItem(index);
    }

    protected override void SetItem(int index, Item item)
    {
        var existingItem = this[index];

        if(item == existingItem) return;

        CheckParent(item);
        ItemParentChanger(existingItem, null);

        base.SetItem(index, item);
    }

    protected override void ClearItems()
    {
        foreach(var item in this) ItemParentChanger(item, null);
        base.ClearItems();
    }

A: My answer is built off of two parts

*

*Why is it so "Unsafe" to have the Interface ISetParent?

private/internal access modifiers are ment to prevent from mistakes,
not really "Secure Code".
Remember... you can call private methods using some Reflections/Invoke Etc...
.
2 .  i usually make everything public
and make sure both sides know how to handle each other,
ofcourse, there is a little ping-pong but it takes just few cycles
(in this case i have a NamedSet)
    private IPhysicalObject partOf;
    public IPhysicalObject PartOf
    {
        get { return partOf; }
        set
        {
            if (partOf != value)
            {
                if (partOf != null)
                    partOf.Children.Remove(this.Designation);

                partOf = value;

                if (partOf != null)
                    partOf.Children.Add(this.Designation);
            }
        }
    }

    public virtual void Add(String key, IPhysicalObject value)
    {
        IPhysicalObject o;
        if (!TryGetValue(key, out o))
        {
            innerDictionary.Add(key, value);
            value.PartOf = Parent;
        }
    }

    public virtual bool Remove(String key)
    {
        IPhysicalObject o;
        if(TryGetValue(key, out o))
        {
            innerDictionary.Remove(key);
            o.PartOf = null;
        }
    }

Hope this helps...
Good Day,
Tomer W.
P.S. I'll never get how this Editor is working... should i HTML it, or should i not?

A: One solution I've used to control visibility of class members is to define the class as partial, and then in a different namespace declare the class as partial, and define the special visibility members you want.
This controls member visibility depending on the namespace chosen.
The only thing you'll have to wrap your head around is referencing. It can get complex, but once you have it figured out, it works.


text:
Q: Nonlinear regression SSE Loss Notation
$y_i$ is observation $i$ of some response variable $Y$.
$\hat{y}_i$ is the value of $y_i$ predicted by the regression.
$\bar{y}$ is the average of all observations of the response variable.
$$ y_i-\bar{y} = (y_i - \hat{y_i} + \hat{y_i} - \bar{y}) = (y_i - \hat{y_i}) + (\hat{y_i} - \bar{y}) $$
$$( y_i-\bar{y})^2 = \Big[ (y_i - \hat{y_i}) + (\hat{y_i} - \bar{y}) \Big]^2  =
(y_i - \hat{y_i})^2 + (\hat{y_i} - \bar{y})^2 + 2(y_i - \hat{y_i})(\hat{y_i} - \bar{y})
$$
$$ \sum_i ( y_i-\bar{y})^2 = \sum_i(y_i - \hat{y_i})^2 + \sum_i(\hat{y_i} - \bar{y})^2 + 2\sum_i\Big[ (y_i - \hat{y_i})(\hat{y_i} - \bar{y}) \Big]$$
$$ = SSRes + SSReg + Other $$
When $Other = 0$, as we have in linear regression, then $SSRes$ is a perfectly reasonable measure of what strikes me as the real value of interest: $SSReg$. As one decreases, the other increases, so we can get a strong model fit (high $SSReg$) by minimizing $SSRes$.
However, $Other \ne 0$ in general, such as in nonlinear regressions. A popular nonlinear regression these days is a neural network. While neural nets may be most used for classification problems, they are perfectly reasonable to use in regression problems. In neural network regressions, I have seen $MSE$ as the loss function. For instance, sklearn's MLPRegressor uses SSRes as the loss function  (same $argmin$ as $MSE$).
Minimizing $SSRes$ misses the $Other$ term! The $SSRes$ could be very small, yet there could be a major contribution from the $Other$ term that shows the regression model not to be good.
I've tried it out in Python, using some code I found on Stack Overflow for MLPRegressor. That $Other$ term definitely doesn't drop to zero.
from sklearn.neural_network import MLPRegressor
import numpy as np
import random
random.seed(2019)

x = np.arange(0.0, 1, 0.001).reshape(-1, 1)
y = np.sin(2 * np.pi * x).ravel()
nn = MLPRegressor(hidden_layer_sizes=(100,), activation='relu')
n = nn.fit(x, y)
train_y_pred = n.predict(x)
Other = (train_y_pred - np.mean(y) ) * (y - train_y_pred)
sum(Other)

Questions

*

*What is the reason for using $SSRes$ or $MSE$ loss when there is that $Other$ term?

*This might be more philosophy or perhaps not so different from the first question, but am I off-base to claim that $SSReg$ is the real value of interest and that we use $SSRes$ as a proxy because we're used to minimizing loss rather than maximizing gain?
Code for linear regression:
import numpy as np
from sklearn.linear_model import LinearRegression
import random
random.seed(2019)
X = np.random.normal(10,1,100).reshape(-1, 1)
X = np.sin(X).reshape(-1, 1)
e = np.random.normal(0,0.25,100).reshape(-1, 1)
y = X + e
y.reshape(-1, 1)
reg = LinearRegression().fit(X, y)
y_pred = reg.predict(X)
resid = y - y_pred
Other = (y_pred - np.mean(y) )* (y - y_pred)
sum(Other)

A: Two years later, I can answer #1.
If we assume a Gaussian response variable (common), minimizing $SSRes$ is equivalent to maximum likelihood estimation of the regression parameters. Consequently, we get maximum likelihood estimates, which feel like a natural way of estimating the parameters.
I think that this leads to answering #2 in the negative. We minimize $SSRes$ instead of maximizing $SSReg$ because we aim to find the "most likely" regression parameters via maximum likelihood estimation, not maximize the variance we can explain. (That these two notions do not coincide, however, blows my mind.)

A: Humm, well being as you asked. The connection between MLE and ordinary least squares (OLS) has established for linear regression for normally distributed residuals. These are not equivalent in most (if not all) other circumstances. In general, OLS has omitted variable bias in the linear case, which is also problematic for nonlinear fitting. The magnitude of omitted variable bias is zero in special cases, e.g., when the $X_i$ are sequentially equidistant. This can be understood by noting that OLS minimizes error in the $y$ direction, and does not minimize error in both $x$ and $y$. To do the latter, one needs to perform some other type of regression, e.g., in the linear case Deming regression. This requires knowledge of both variance in $y$ and in $x$. In the linear fit equation case Deming regression has no omitted variable bias. For OLS, the minimum error is for prediction of least error in $y$, with omitted variable error, this makes the slope more shallow but optimizes the $r$-value. Deming regression will have a steeper slope, as it no longer "splits" the $y$-value error to be too much on one side and too little on the other just to minimize that error globally. In Deming regression, the correlation will be of lesser magnitude, but the regression line follows the "cloud" of data points more accurately and extrapolation beyond the range of the data is more accurate. There are nonparametric procedures that reduce omitted variable bias in the linear case, e.g., Passing-Bablok, and Theil-Sen, which unlike Deming regression do not require explicit knowledge of relative variances of $x$ and $y$.
The formula you wrote, after changing the order of subtraction of $ \hat{y_i}-\bar{y}$, is written as $$ \sum_i ( y_i-\bar{y})^2 = \sum_i(y_i - \hat{y_i})^2 + \sum_i(\hat{y_i} - \bar{y})^2 - 2\sum_i\Big[ (y_i - \hat{y_i})(\bar{y} - \hat{y_i}) \Big]\;\;,$$
and has the same structure as the law of cosines $$c^2=a^2+b^2-2\, a\, b\cos(\theta)\;\;,$$
for the exact same reasons. Moreover, this is (changing the sign back again) the variance of the sum of two correlated variables. In the answers to that question, note the equivalence of the law of cosines, i.e., the vector form, to the variance treatment, where $\cos(\theta)$ and the correlation coefficient $r$ are equivalent. Finally, error propagation, or at least the first approximation from Taylor series to it, takes the form $$\left(\frac{\sigma_f}{f}\right)^2 \approx \left(\frac{\sigma_a}{a} \right)^2 + \left(\frac{\sigma_b}{b}\right)^2 + 2\left(\frac{\sigma_a}{a}\right)\left(\frac{\sigma_b}{b}\right)\rho_{ab}\;,$$
where $\rho_{ab}$ is the correlation between $a$ and $b$. To make a long story short, it would seem that for OLS in $y$, we are assuming that the $x$ and $y$ errors are uncorrelated, "Homoscedasticity and independence of the error terms are key hypotheses in linear regression where it is assumed that the variances of the error terms are independent and identically distributed and normally distributed. When these assumptions are not possible to keep, ... the variance of the parameters corresponding to the beta coefficients of the linear model can be wrong and their confidence intervals as well."


text:
Q: Metodo SQL NATIVO JPA tengo una query en nativa, y me devuelve una lista, la cosa es como puedo hacer para lo que me devuelve parsearlo en un DTO. Tengo esto alguna ayuda...

@Query(value =
   + "SELECT BLABLA, BLABLA2, BLABLA3, BLABLA4
FROM BLABLATABLE ", nativeQuery = true)
 public List<BlablaDTO> getBlaBlaWithDades();

A: primero que nada dejemos un poco mas lindo ese método con su Query(entiendo que estas extendiendo para tu repository de jpaRepository) :
@Query(nativeQuery= true, value= "SELECT * FROM TABLA_DTO")
public List<ObjetoDto> getDTOsFromDB();

Ahora bien, primero que nada quisiera señalar el hecho de utilizar nativeQuery. Si estas utilizando el mapeo que nos brinda JPA deberías terminar de utilizarlo por completo. Esto conllevaría a que el método nos quede de la siguiente manera:
@Query("SELECT dto FROM ObjectoDto dto")
public List<ObjetoDto> getDTOsFromDB();

Lo que hicmos fué utilizar en la consulta, en este caso JPQL, la *entidad ObjetoDto (la cual esta mapeada con la tabla TABLA_DTO) para correspondernos con la utilizacion que JPA nos brinda.
Anteriormente asumimos que ObjectoDto era una entidad (por ende se corresponde con una tabla de nuestra base de datos). Ahora si vamos con el problema planteado. Si el DTO que usted quiere devolver de base de datos no se corresponde a ninguna tabla debería traer el objeto que si se encuentra mapeado y luego aplicarle un Adapter.
Entonces nuestro Repository nos quedaría igual :
@Query("SELECT dto FROM ObjectoDto dto")
public List<ObjetoDto> getDTOsFromDB();

Pero en nuestro Controller aplicaríamos, al momento de retornar nuestra ResponseEntity, un Adpater según que tipo de objeto nos gustaría devolver:
return ResponseEntity.status(HttpStatus.OK).body(ObjetoDtoAdapter.apply(ObjetoDto));

Nuestro Adapter sería algo como :
@Component
public class ObjetoDtoAdapter implements Function<ObjetoDto, ObjetoDtoResponse> {

    @Override
    public ObjetoDtoResponse apply(ObjetoDto objetoDto) {
        return ObjetoDtoResponse.builder()
            .id(objetoDto.getId())
            .name(objetoDto.getName())
            .surname(objetoDto.getSurname())
            .build();
    }
}

Va a ser al momento de crear nuestro adapter en donde tendremos que "jugar" en que tipo de objeto queramos construir.

*las entidades son clases que representa al modelo de datos, o mapea directamente contra una tabla de la base de datos


text:
Q: How to do ongoing synchronization with Salesforce? I'd like to develop an app on Salesforce that updates an Activity record with the amount of time a lead spent viewing something like an email message. I would keep updating this record until the lead stops viewing the message. (Let's assume that I have a reliable way of determining that.)
From what I understand, I can keep pushing the updated viewing time to Salesforce, but a Salesforce user wouldn't know that it's been updated until he refreshes the page.
It seems to me that Salesforce's interface isn't set up for this kind of ongoing data manipulation. How could I make sure that the "viewed duration" metric is always accurate to a Salesforce user?
Thanks!

A: You can try below approach , However its not very reliable.

*

*Use Inline Vissualforce page in Activity with hight 1px (So that would not be visible to user).

*Start Javascript timer when Page loads.

*In "onbeforeunload" event of page when user tries to navigate away from page, you can post AJAX request or REST request to update duration.


text:
Q: C++: how do I pass a variable for multiple arguments?
Possible Duplicate:
Passing Variable Number of Arguments with different type - C++

I have a function that takes n arguments.
And I want to call it like, function_name(number_args - 1, input, args_from_console[], output)
How do I do that?
*the function that takes n arguments already is written and works... I just don't want to hard code the variables being passed in.
Edit: (adding code)
struct fann *ann = fann_create_standard(num_layers,
                                            Config::NUMBER_OF_INPUT_NEURONS,
                                            Config::WIDTH_IN_BITS,
                                            Config::WIDTH_IN_BITS,
                                            Config::NUMBER_OF_OUTPUT_NEURONS);

the function above can have at least 3 arguments... the required arguments are num_layers, num_input, and num_output)
the optional arguments are the hidden layers of the neural network (what they are call isn't important.... but basically... it could look like this:
fann_create_standard(#layers, #input, #hidden1, #hidden2, #hidden3, #hidden4, ... #output);

what I want to be able to do, is pass in command line arguments to change how many layers, and what the values of each of the hidden layers are (the middle arguments in this function call), so that I don't have to re-compile the program every time I want to re-configure the network.

A: Hard-code the arguments. It is certainly the best alternative.
If there are really too many, package them into an appropriate data structure and rewrite the function to accept that instead.
Edit: I see that you are using an external library. Fortunately they already provide another function that accepts a data structure instead of a variable number of arguments.
FANN_EXTERNAL struct fann *FANN_API fann_create_standard_array(
    unsigned        int     num_layers,
    const unsigned  int     * layers
)

Simply use this instead.

A: I think what you're describing is that you want a variable number of arguments. It's called varargs, and this link should be helpful for you:
http://en.wikipedia.org/wiki/Stdarg.h#varargs.h
Unfortunately I see that your arguments are NOT all the same type. This is a problem. You'll need to use format strings (like printf) so that your code will be able to infer the correct type when it goes to fetch the data from the stack.

A: Rewrite the function so it doesn't need that.  Have it take a vector, instead of an array, then the number of arguments can be retrieved from the size() function.
If I understand you correctly, the function you want to call looks something like this(Ignore the argument types, I'm just using all ints for simplicity's sake)
int func(int n, int input, int args[], int & output);

And you don't want to have to figure out n.  Just wrap the function, thusly:
int func_wrap(int input, std::vector<int> & args, int & output)
{
    return func(args.size() - 1, input, &args[0], output);
}

A: SEE EDIT BELOW!! (I originally thought this had all the earmarks of pure homework)
Just reading your code for sense, could it be that your parameter "args_from_console[]" is really char **argv (or char *argv[]) that was passed to main( ), but presented to you here in disguise? In other words, does the caller of your function look something like this?
int
main ( int argc, char **argv ) {
   ...
   ...
  function_name(number_args - 1,
    input,
    argv,          // <-- from the command line, right?
    output);
    ..
  return 0;
}

If so, then main( ) is giving to your function the tokenized command-line argument string it received when it started. This argument is a pointer to an array of character pointers. The first member of that array points to the first command-line argument; the second member points to the second command-line argument; and so on for each command-line argument that the user typed to start the main( ) program.
Question for you: How can you know how many discrete arguments were passed in to main( ) when it started?
EDIT: I edited this after the OP made his example plainer.
IF you just want to give the command-line arguments to the called function, just pass in both int argc; and char **argv and let him figure it out. Or you modify the called function to figure it out for him.


text:
Q: "Validation error: PayPal currencies do not match" in WooCommerce Using WooCommerce and the standard PayPal gateway to accept payments.  When testing in Sandbox mode, everything works great.  When we test live with a real transaction, payment goes through no problem, but within WooCommerce there is a note as follows:
"Validation error: PayPal currencies do not match (code USD). Order status changed from Processing to On Hold."
We do not have multiple currencies in the shop.  Everything is set to USD.  PayPal is set to accept payments in different currencies and automatically convert them.  We do not have a currency conversion plugin installed.  We double checked the API settings (they are correct), we've generated new API keys and tried again, we tried it with and without IPN enabled.
The payment goes through via Paypal, but we still get this error inside the order notes, and the status changes to On-Hold instead of "Processing".
We also cannot process a refund via PayPal from within WooCommerce, we get a "Refund Failed" message.  Not sure if this is related, but we would like to figure that out as well.

A: i found temporary fix for this problem
go to "plugins/woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-ipn-handler.php" and comment two lines (line number : 176 and 177 ) like this
//$this->validate_currency( $order, $posted['mc_currency'] );
//$this->validate_amount( $order, $posted['mc_gross'] );

Source : https://www.kapadiya.net/wordpress/woocommerce-paypal-for-inr/


text:
Q: Aligning top of text with background image in list items I'm trying to set the text in my list items here in the left nav to be at the top of each image whehter single or double line, but can't get it to work correctly.
Here's the css and an example background image li:
.benefits li
{font-size: 16px;
padding-left: 25px;
line-height: 2.1;
}

li.social {
background:url("/images/users.png") 0% 50% no-repeat;
}

Any help much appreciated.

A: Update your li tag CSS to:
url("/images/megaphone.png") 0% 0% no-repeat;

That would be 50% to 0%.
Or, something like 0.4em so the icon lines up nicer with the text.
url("/images/megaphone.png") 0% .4em no-repeat;


text:
Q: configuring turbogears2 with importerrors ImportError: cannot import name 'MinimalApplicationConfigurator' from 'tg' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/tg/__init__.py)

Help, i have installed tg it cant import 'MinimalApplicationConfigurator'. How can i resolve it? Tried putting the path directory on my mac terminal but with no succes. Can someone help?


text:
Q: Tidy up .html.erb output My application layout has a login/logout link that displays depending on whether you are signed in or not:
<% if signed_in? %>
    <%= link_to "Sign out", signout_path, :method => :delete %>
<% else %>
    <%= link_to "Sign in", signin_path %>
<% end %>

This works fine, but seems really untidy and verbose. How can I output the appropriate link_to without so many <%...%> brackets?

A: I'd go with HAML, but if you don't want to use HAML, you could use a ternary operator:
<%= signed_in? ? link_to( 'Sign Out', signout_path, :method => :delete ) : link_to( 'Sign In', signin_path ) %>

A: Use HAML ;)
- if signed_in?
  = link_to "Sign out", signout_path, :method => :delete
- else
  = link_to "Sign in", signin_path

A: You could use the concat helper:  (ActionView::Helpers::TextHelper)
<%
if signed_in?
   concat link_to( "Sign out", signout_path, :method => :delete )
else
   concat link_to( "Sign in", signin_path )
end
%>

Though in the rails api they prefer the <% %> syntax....

A: Try adding a - (dash) to your closing tag, like so:
<% if signed_in? -%>
    <%= link_to "Sign out", signout_path, :method => :delete -%>
<% else -%>
    <%= link_to "Sign in", signin_path -%>
<% end -%>

From: http://www.plexusweb.com/staff/travis/blog/post/117/Rails-inline-ERb-effects-on-HTML-structure
Edit;
My bad, thought is was about formatting the HTML output (newlines etc.)

A: With 2 open-close brackets you could do it like this:
<%= link_to( "Sign out", signout_path, :method => :delete ) if signed_in? %>
<%= link_to( "Sign in", signin_path) if !signed_in? %>


text:
Q: Freezing and Unfreezing network layers in TF Estimator I am using the TF Estimator to train my model on a dataset. For the first few training iterations, I want to freeze certain layers in the network. For the remaining iterations I want to unfreeze these layers.
I found some solutions where we have two different optimizer train_ops in the estimator's model_fn.
def ModelFunction(features, labels, mode, params):
    if mode == tf.estimator.ModeKeys.TRAIN:
        layerTrainingVars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "LayerName")
        #Train Op for freezing layers
        freeze_train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step(), var_list=layerTrainingVars)
        #Train Op for training all layers
        train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
        #Based on whether we want to freeze or not, we send the corresponding train_op to the estimatorSpec. How do I do this?
        estimatorSpec = tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=freeze_train_op)

    return estimatorSpec

For the above solution, the corresponding EstimatorSpec could be returned based on the train_op. I tried using the freeze_train_op for a few training iterations, and then killing the process, and changing the train_op to have no layer freezing in the code. After doing this, there is a checkpoint error, which says that the graphs/variables saved in the checkpoints are different. I guess the first set of iterations did not save the frozen layers. How do I switch train_ops programmatically such that checkpointing works too?
Is there any better way to go about freezing/unfreezing layers for training in TF.Estmator?

A: You can return 2 train_op by grouping them together.
def ModelFunction(features, labels, mode, params):
    if mode == tf.estimator.ModeKeys.TRAIN:
        layerTrainingVars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "LayerName")
        #Train Op for freezing layers
        freeze_train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step(), var_list=layerTrainingVars)
        #Train Op for training all layers
        train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
        estimatorSpec = tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=tf.group(freeze_train_op, train_op))

    return estimatorSpec

But this won't take into account different iterations. If you want to train different set of variables on different iterations and don't want to stop training and load weights from checkpoint, you need to use session. Estimator api doesn't allow session management.


text:
Q: Different environment files for production and development in vue+webpack app I'm building a vue app using webpack. Now that I have to deploy the app to a production server I feel the need to have different settings for development and production cases (for example the main url where the app must reach an api service changes for each type). After reading some guides I have not yet clear how to achieve this.
What I would like to do is that when I run:
npm run dev

environment variables in development.env should be used and when I run:
npm run build

environment variables in production.env should be used.
Is it possible to accomplish this with webpack?
Cheers.

A: you can use webpack-cli and --env allows you pass as manu environment variables as you want.
In your build script pass this:
--env.PLATFORM=production

For example anywhere in webpack config, you need to covert to module.exports to a function:
module.exports = env => {

 if (env.PLATFORM === 'production') {
  return {
    entry: './src/index.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist')
    }

   };
   }

But for production and development I would recommend to make different webpack config files:
webpack.prod.config.js
webpack.dev.config.js

Later you can pass --config webpack.prod.config.js in your build script. And usually for env in webpack when it comes to merging different parts of webpack config targeting different environments


text:
Q: Replace value in a column with 'blank' if it matches the value in another column I have a following data set as a data frame within R
article_number   1st_cutoff_date   2nd_cutoff_date

abc                12/01/2019       01/14/2020

def                02/10/2020       02/10/2020

What I want to do is in cases where 1st_cutoff_date == 2nd_cutoff_date, then replace 2nd_cutoff date with blank value " ".  So in the second case 'def' then 2nd_cutoff_date would be blank " "
the data frame is of factors and there are NA's - I have converted to character and tried the following:
AAR_FTW_Final_w_LL[AAR_FTW_Final_w_LL$`1st_Booking_Deadline` == AAR_FTW_Final_w_LL$`2nd_Booking_Deadline`, c("2nd_Booking_Deadline")] <- " "

&
ind<- AAR_FTW_Final_w_LL$`1st_Booking_Deadline` == AAR_FTW_Final_w_LL[`2nd_Booking_Deadlilne`]
AAR_FTW_Final_w_LL[ind, c("2nd_Booking_Deadline")] <- " "

Both return the error:
Error in AAR_FTW_Final_w_LL$`1st_Booking_Deadline` :
  $ operator is invalid for atomic vectors

I have tried replacing the $ with [] but then I get the error that one of the columns is missing.  Is there any easier way to do to this task?

A: Convert from factors to characters :
df[] <- lapply(df, as.character)

Then use replace
transform(df, `2nd_cutoff_date` = replace(`2nd_cutoff_date`,
                            `1st_cutoff_date` == `2nd_cutoff_date`, ''))

#  article_number X1st_cutoff_date X2nd_cutoff_date
#1            abc       12/01/2019       01/14/2020
#2            def       02/10/2020

It adds X to the column name since it is not a standard in R to have columns starting with a number.

Another approach after you convert the data to characters would be
df$`2nd_cutoff_date`[df$`1st_cutoff_date` == df$`2nd_cutoff_date`] <- ""

data
df <- structure(list(article_number = structure(1:2, .Label = c("abc",
"def"), class = "factor"), `1st_cutoff_date` = structure(2:1,
.Label = c("02/10/2020", "12/01/2019"), class = "factor"),
`2nd_cutoff_date` = structure(1:2, .Label = c("01/14/2020",
"02/10/2020"), class = "factor")), class = "data.frame", row.names = c(NA, -2L))


text:
Q: How to find out what view a touch event ended at? I wish to drag a UIImage on to one of several UIButtons and have it repositioned based on which button I drag it to.
The problem I've ran in to is that UITouch only records the view where my touch began, I'd like to access the view my touch ends at. How can I do this?
Code:
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self.view];

    dealerBtnOrigin = [touch locationInView:self.view];

    //NSLog(@"%u %u",touch.view.tag, ((UIView *)[dealerBtns objectAtIndex:[table getButtonSeat]]).tag);
    //CHECK TO SEE WHICH BUTTON WAS TOUCHED
    if (touch.view == ((UIView *)[dealerBtns objectAtIndex:[table getButtonSeat]]))
    {
        ((UIView *)[dealerBtns objectAtIndex:[table getButtonSeat]]).center = location;
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self.view];

    if (touch.view == ((UIView *)[dealerBtns objectAtIndex:[table getButtonSeat]]))
    {
        ((UIView *)[dealerBtns objectAtIndex:[table getButtonSeat]]).center = location;
    }
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self.view];
    UIView *endView = [self.view hitTest:location withEvent:nil];

    if (touch.view == ((UIView *)[dealerBtns objectAtIndex:[table getButtonSeat]]))
    {
        NSLog(@"%u %u",endView.tag, touch.view.tag);
        if([buttons containsObject:(UIButton *)endView])
        {
            [[dealerBtns objectAtIndex:[table getButtonSeat]] setHidden:YES];
            [table passButton:touch.view.tag];
            [[dealerBtns objectAtIndex: touch.view.tag] setHidden:NO];
        }
        ((UIView *)[dealerBtns objectAtIndex:[table getButtonSeat]]).center = dealerBtnOrigin;
    }

}

A: Use hit-testing. You know the location of this point as a CGPoint in terms of the ultimate superview, self.view. Then you can ask self.view which of its subviews that point is in:
CGPoint location = [touch locationInView:self.view];
UIView* v = [self.view hitTest:location withEvent:nil];

The UIView v is the view you're looking for.

A: It is very easy to detect your finally touched view, try this code
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint location = [[touches anyObject] locationInView:self.view];
    CGRect fingerRect = CGRectMake(location.x-5, location.y-5, 10, 10);

    for(UIView *view in self.view.subviews){
        CGRect subviewFrame = view.frame;

        if(CGRectIntersectsRect(fingerRect, subviewFrame)){
            //we found the finally touched view
            NSLog(@"Yeah !, i found it %@",view);
        }

    }

}

A: In general, you need to take the point where the touch ended, and determine whether it lies within the view you're interested in.  I do this using code similar to the following:
CGPoint newCenter = dragView.center;
for (UIView *v in dropTargets)
{
    CGRect convertedTargetFrame = [v.superview convertRect:v.frame toView:nil];
    if (CGRectContainsPoint(convertedTargetFrame, newCenter))
    {
        activeTargetIndex = idx;
    }
}

(this code was edited on the fly to take out a lot of irrelevant stuff, but I keep a list of potential drop targets in dropTargets, and this is just looking at that list to see which of the potential UIViews might contain the point).
The essential thing is that if you know the view or views you're potentially dragging the item to, then you can determine whether that view's frame contains the point using CGRectContainsPoint.  The important thing is to keep in mind they may lie in different coordinate systems and it may be necessary to convert from one to the other before your comparison.

A: Assuming there is a @property of the target view in your container, and the target view is added to the container:
@property (nonatomic, strong) UIView* targetView;

// ...

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSSet* touchesForTargetView = [event touchesForView:self.targetView];
    if (touchesForTargetView.allObjects.count != 0) {
        // touch was at target view
    }
    else {
        // touch  was somewhere else
    }
}

A: swift 4:
override func touchesEnded(_ touches: Set, with event: UIEvent?) {
    if let touch = touches.first{
        let location = touch.location(in: self.view)
        let v = touch.view

// go on..
        }
}


text:
Q: Small unwanted delay loading icons with Glide I've a list of installed applications that I display in a RecyclerView.
The application icon is stored in a byte array and I use Glide to bind it to an ImageView using:
    Glide.with(itemView.getContext())
            .load(application.getIcon())
            .into(icon);

The problem is that it tooks about 500-700 ms for the icon to be displayed, then it appears in a nice and smooth way. But I don't want that delay nor want to fallback to a placeholder.
If I change Glide code for direct loading (in main application thread) then the icons appear instantly:
    byte[] image = application.getIcon();
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap bitmap = BitmapFactory.decodeByteArray(image,0,image.length,options);
    icon.setImageBitmap(bitmap);

But the problem is that If I scroll fast the list sometimes there are some little glitches.
Is there something that I can do to load the icons faster with Glide?
I've tried with .dontAnimate() and .dontTransform() but I haven't seen any differences. What can I do to load the images instantly and get similar results than loading directly in main thread?


text:
Q: mySQL correlated Subquery trying to write a mysql query and having a lot of difficult with this one.
I have two tables( Item: info about items, and itemReview: reviews for the items )
What I would like to do is select all the items that belong to a particular location (which is what my outer query does) and then for each item in the outer query, get the average of all the rating fields in the itemReview table
Here is my attempt:
SELECT
    Item.idDish,
    Item.dateAdded,
    Item.dateModified,
    Item.fidLocation,
    Item.category,
    Item.description,
    Item.price,
    Item.name,
    Item.fullImageName,
    Item.thumbnailImageName,
    sub.rating
FROM Item
JOIN (
        SELECT
            AVG(ItemReview.rating) AS rating
        FROM ItemReview
        WHERE ItemReview.fidItem = Item.idItem
    ) AS sub
WHERE Item.fidLocation = '63';

but mySQL says: Unknown column 'Item.idItem' in 'where clause'
Any help would be very appreciated!! thanks!!

A: You are trying to access the Item.idItem inside of the subquery but it is not available there. You should use something like this:
SELECT
    Item.idDish,
    Item.dateAdded,
    Item.dateModified,
    Item.fidLocation,
    Item.category,
    Item.description,
    Item.price,
    Item.name,
    Item.fullImageName,
    Item.thumbnailImageName,
    sub.rating
FROM Item
JOIN
(
    SELECT fidItem, AVG(ItemReview.rating) AS rating
    FROM ItemReview
    GROUP BY ItemReview.fidItem
) AS sub
   ON sub.fidItem = Item.idItem
WHERE Item.fidLocation = '63';

A: Query:
SELECT
    Item.idDish,
    Item.dateAdded,
    Item.dateModified,
    Item.fidLocation,
    Item.category,
    Item.description,
    Item.price,
    Item.name,
    Item.fullImageName,
    Item.thumbnailImageName,
    (   SELECT
            AVG(ItemReview.rating) AS rating
        FROM ItemReview
        WHERE ItemReview.fidItem = Item.idItem
    ) AS rating
FROM Item
WHERE Item.fidLocation = '63'

A: Try this:
SELECT i.idDish, i.dateAdded, i.dateModified, i.fidLocation, i.category,
       i.description, i.price, i.name, i.fullImageName,
       i.thumbnailImageName, ir.rating
FROM Item i
LEFT JOIN (SELECT fiditem, AVG(ItemReview.rating) AS rating
           FROM ItemReview
           GROUP BY fiditem) ir ON ir.fidItem = i.idItem
WHERE i.fidLocation = '63';

A: Try this
SELECT
    Item.idDish,
    Item.dateAdded,
    Item.dateModified,
    Item.fidLocation,
    Item.category,
    Item.description,
    Item.price,
    Item.name,
    Item.fullImageName,
    Item.thumbnailImageName,
    sub.rating,
    Item.idItem
FROM Item
JOIN (
        SELECT
            AVG(ItemReview.rating) AS rating ,
            fidItem
        FROM ItemReview
        GROUP BY fidItem
    ) AS sub on sub.fidItem = Item.idItem
WHERE Item.fidLocation = '63';

A: You cannot refer to "outer" tables in such way. One solution is already proposed by bluefeet, another which will also work in your case :
SELECT
Item.idDish,
Item.dateAdded,
Item.dateModified,
Item.fidLocation,
Item.category,
Item.description,
Item.price,
Item.name,
Item.fullImageName,
Item.thumbnailImageName,
(SELECT AVG(ItemReview.rating) AS rating
    FROM ItemReview
    WHERE ItemReview.fidItem = Item.idItem
) as rating
FROM Item
WHERE Item.fidLocation = '63';

A: What about this:
SELECT
    Item.idDish,
    Item.dateAdded,
    Item.dateModified,
    Item.fidLocation,
    Item.category,
    Item.description,
    Item.price,
    Item.name,
    Item.fullImageName,
    Item.thumbnailImageName,
    sub.rating
FROM Item myTable
JOIN (
        SELECT
            AVG(ItemReview.rating) AS rating
        FROM ItemReview
        WHERE ItemReview.fidItem = myTable.idItem
    ) AS sub
WHERE Item.fidLocation = '63';

Here you are giving a name to main query and referencing the new table name in the subquery. Using the original table names causes MySQL don't know about what table take.


text:
Q: Mac OS X 10.10 php 5.5.14 free type support It appears the GD library is installed, but free type is not. How can I add this to my php installation in mac os x 10.10 system php install?

A: I would install homebrew and then use:
brew install freetype

A: To get this configured with php
brew remove --ignore-dependencies --force php71
brew install php71 --with-freetype

Then make sure to load this brew installed php into your apache httpd.config, and restart your apache server.
LoadModule php7_module /usr/local/opt/php@7.1/lib/httpd/modules/libphp7.so


text:
Q: Prove that a function that is equal almost everywere to a measurable function is measurable
If $f: [a,b] \rightarrow \mathbb{R} $ is Lebesgue measurable and for $g:[a,b] \rightarrow \mathbb{R}$ we have $ f = g $ almost everywhere, then $g$ is Lebesgue measurable.

Here is my proof:
Let $E$ be the set such that $f(x) = g(x)\ $ for $x\in[a,b]\backslash E$.
Since $f$ is measurable, the set $$\{x\in[a,b]: f(x) > \alpha \}$$ is measurable, and $$\{x\in[a,b]: f(x) > \alpha \} \cap E^c$$ is also measurable because it is the intersection of measurable sets. Finally $$\{x\in[a,b]: f(x) > \alpha \} \cap E^c = \{x\in[a,b]\backslash E: f(x) > \alpha \} = \{x\in[a,b]\backslash E: g(x) > \alpha \} $$ as required.
Is that correct? I mean I did not use the fact that $m(E) = 0$.

A: I think your idea is good. Note that $\{x\in[a,b]: g(x) > \alpha \} = (\{x\in[a,b]: g(x) > \alpha \} \cap E^c) \cup (\{x\in[a,b]: f(x) > \alpha \} \cap E)$. The second set in the union in the RHS is measurable by your argument, and the first set is measurable because is a subset of $E^c$, which has zero measure.


text:
Q: Multi-Dimensional Arrays of Different Types in Swift I can easily write a multi-dimensional array in Swift when all the dimensions are of the same type, for example:
var totalTime : [[Int]]

How would I get the first dimension to be String and the second dimension Int?

A: I would recommend using an array of tuples instead. What you want could be accomplished using an array of type Any, but it is not a good idea.
Instead, your array should be [[(String, Int)]]. This would also be more compact than what you want to do.
var myArray: [[(String, Int)]] = []


text:
Q: How to parse a DateTime string with like 03-22-2022 03:28 p.m. in C# As my question says i would like to parse a datetime with format like 03-22-2022 03:28 p.m. (month-day-year hour:minute a.m. or p.m.) into t DateTime object in C#, not sure how to do this.
I tried the following but it doesn't work:
var ss = "03-22-2022 03:28 p.m.";
format = "MM-dd-yyyy hh:mm t.t.";

success = DateTime.TryParseExact(ss, format, System.Globalization.CultureInfo.InvariantCulture,
                    System.Globalization.DateTimeStyles.None, out DateTime result);

A: First of all, I recommend you not use a var, but a string instead for ss. It's also hard to tell where the "success" variable came from. You don't normally assign a value on the left-hand side if you are using an out variable in the right-hand side, unless you are trying to capture the boolean to determine if it worked. There is a way to do that without the success variable.
If I were to do it your way, where I use the var instead of string, and I use TryParse with an out variable, here's what I would do.
var ss = "03-22-2022 03:28 p.m.";
DateTime.TryParse(ss, out DateTime result);

return (result != DateTime.MinValue);

By using the DateTime in the out parameter, you are defining the variable inline. That allows you to use result later. Also, a DateTime variable is never null, so you can check to see if it is equal to DateTime.MinValue instead of creating another variable you are going to use in a conditional statement. Checking DateTime.MinValue will produce the same result. In my example, I am returning the result as if it were a function with a return value. You could use that any way you wanted.
If you are not returning a boolean value, but are using it later, you might do:
string ss = "03-22-2022 03:28 p.m.";
DateTime.TryParse(ss, out DateTime result)

if (result != DateTime.MinValue)
{
     //ToDo: continue process here
}

Others may have better advice, but this works for me.


text:
Q: Given elements $x,y$ of a group $G$, where both $x,y$ have finite order, what is the order of $x*y$? I've read somewhere that if $x,y$ commute, and $gcd(|x|,|y|) = 1$, then $|x*y|$ is the product of their individual order, but I don't even know why the criterion of commutativity is needed there. Also, is there a formula to find the order of $x*y$ in general? Do you need to have any restriction on the size of $G$, by any chance (as in, does it matter whether its finite or not, in regards to this question)?

A: Consider the dihedral group of order $2n$.  It contains 2 reflections (which have order 2) whose product is a rotation of order $n$, which is half the order of the group.  Half the order of the group is the highest possible order of an element in a noncyclic group, so no better bounds are possible in general.


text: Q: Magento 2 Configurable product images showing with child products I added images in magento 2 configurable product and then I added 3 child products with images but on product detail page after selected child product it is showing both images (parent and child product), I want to show only child product images if selected otherwise parent's product images. Is there any patch to do this?


text:
Q: Replace days with 1 - 7 R Hope your doing well, I am working on an assignment related to data pre processing and I need some help in R
I have a column for days in which they are 711 unique values. In total I have 2 million observations. The data has been collected over 2 years and each day represents one day in a week.
For example day 1 is Monday and day 8 is Monday aswell and day 15 Is Monday and so on.
Could someone help me to replace this with 1 to 7 so if day 1 is Monday I want the cell which contains the value 8 to be replaced by 1 and 15 with 1 and so on.
I hope this makes sense.
thank you for your help.
Regards
A

A: Rather than issue 7 separate commands (one for each day) you can use dplyr:
require(dplyr)

d <- data.frame(day = seq(1:711))

mutate(d, day = day %% 7 +1)

What we're doing here is taking the day number and finding its remainder when divided by 7. We have to add 1 back to this so we dont get 0 when there is no remainder.

A: Following the comments (since I can't comment), try this:
# An example data.frame
mydata <- data.frame(DAY= 1:21, ABC= letters[1:21])
mydata

# Do "mod 7" with variable DAY, so DAY have now values from 0 to 6,
# Then assign back to variable DAY
mydata$DAY <- mydata$DAY %% 7
mydata

# Replace 0 for 7 in DAY variable
mydata$DAY <- ifelse(mydata$DAY == 0, 7, mydata$DAY)
mydata

# Save final data.frame
write.csv(mydata, file='mydata.csv')


text:
Q: Unauthorized access. 'Send' claim(s) are required to perform this operation - Azure Queue Send Message We have been trying to send a test message to Azure Service Bus Queue from SPFx webpart, however, every time we are seeing --> Unauthorized access. 'Send' claim(s) are required to perform this operation. Resource: 'sb://.servicebus.windows.net/'.
Steps we have followed -

*

*Created a sample SPFx webpart.

*Used
{
"resource": "Microsoft.ServiceBus",
"scope": "user_impersonation"
}
inside webApiPermissionRequests of package-solution.json.

*Deployed the webpart and approved scopes from Admin center so that an Azure AD App service principal gets created with API Permissions.

*Now migrated the Redirect Uris to SPA for PKCE flow (MSAL 2.0).

*Set Allow Public Client Flows to "Yes".

*Then got the client id and tenant id from AD App and used in our SPFx solution to connect Service Bus Queue through javascript SDK.

*Used InteractiveBrowserCredential from @azure/identity and ServiceBusClient from @azure/service-bus to send a message to the Queue. Snippet below -

try{
      const credential = new InteractiveBrowserCredential({
          tenantId: "<tenant-id>",
          clientId: "<SharePoint Online Client Extensibility Web Application Principal client-id>"
      });
      const fullyQualifiedNamespace = "<servicebus-namespace>.servicebus.windows.net";
      const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
      const sender = serviceBusClient.createSender("queue-name");
      await sender.sendMessages({body: "test"});
      console.log("message sent");
}
catch(error){
      console.log(error);
}

*Provided Owner and Azure Service Bus Data Owner access from IAM to the Service Principal. Both queue and service bus level.

However, every time code block is throwing exception and the message is - Unauthorized access. 'Send' claim(s) are required to perform this operation. Resource: 'sb://.servicebus.windows.net/'.
Any help would be appreciated. Thanks !!


text:
Q: create new column with values with np.where function in python Hi I'm collecting data from 3 different input files and combining in to one and I like to check the compliant of 3 different columns(all these column values should contains same value to be compliant). based on the check I will create a new column which indicates the status of the compliance check (see below desired output)
df_serial_compliance = pd.DataFrame({"Serial Number Compliance":[]})
df_data = {"Serial Number 1":["", "F5349H2", "FX626H2", "H1JFZF2", "5TBBMH2", "4DN7PH2"] , "Serial Number 2":["DVMYNH2", "F5349H2", "", "5TBBMH2","5TBBMH2", "4DN7PH2"], "Serial Number 3":["5TBBMH2", "F5349H2", "FX626H2", "5TBBMH2","", "4DN7PH2"]}
df_serial = pd.DataFrame(df_data, columns=["Serial Number 1", "Serial Number 2","Serial Number 3"])

print(df_serial)

df_serial["Serial Number Compliance"] = np.where((df_serial["Serial Number 1"] == df_serial["Serial Number 2"]) & (df_serial["Serial Number 1"] == df_serial["Serial Number 3"]) ,"YES","NO")
print(df_serial)

the out put is :
  Serial Number 1 Serial Number 2 Serial Number 3
0                         DVMYNH2         5TBBMH2
1         F5349H2         F5349H2         F5349H2
2         FX626H2                         FX626H2
3         H1JFZF2         5TBBMH2         5TBBMH2
4         5TBBMH2         5TBBMH2
5         4DN7PH2         4DN7PH2         4DN7PH2
  Serial Number 1 Serial Number 2 Serial Number 3 Serial Number Compliance
0                         DVMYNH2         5TBBMH2                       NO
1         F5349H2         F5349H2         F5349H2                      YES
2         FX626H2                         FX626H2                       NO
3         H1JFZF2         5TBBMH2         5TBBMH2                       NO
4         5TBBMH2         5TBBMH2                                       NO
5         4DN7PH2         4DN7PH2         4DN7PH2                      YES

The desired output is:
  Serial Number 1 Serial Number 2 Serial Number 3
0                         DVMYNH2         5TBBMH2
1         F5349H2         F5349H2         F5349H2
2         FX626H2                         FX626H2
3         H1JFZF2         5TBBMH2         5TBBMH2
4         5TBBMH2         5TBBMH2
5         4DN7PH2
  Serial Number 1 Serial Number 2 Serial Number 3 Serial Number Compliance
0                         DVMYNH2         5TBBMH2                       S1 is null
1         F5349H2         F5349H2         F5349H2                      YES
2         FX626H2                         FX626H2                       S2 is null
3         H1JFZF2         5TBBMH2         5TBBMH2                       NO
4         5TBBMH2         5TBBMH2                                       S3 is null
5         4DN7PH2                                                       NO

Edited: if more than one column have null value the result should be "NO
can you help/advice how can I achieve this, please ?
many thanks in advance


text:
Q: .NET Wizards Frameworks I'm aware that there is an ASP.NET Wizards Control however this is fairly basic and doesn't offer a whole lot of flexibility.
I was wondering if there was a .Net based wizards framework that allowed you to build complex wizards with some of the following features:

*

*Re-use steps between wizards

*Dynamically control the wizard flow

*Per page and wizard wide validation

I know there are workflow / BPM style systems like Skelta and BPM, but I'm looking to build things like Line of Credit application or a Mortgage application which needs multiple steps and could have complex validation rules.

A: You can do all three of your bullet points with the ASP.Net Wizard Control

*

*Use Web Controls for the content of your steps.

*On a click of the NextButton, capture what the ActiveStepIndex is and continue processing based on the result.

*See #2.  You could, for example, call a validation function based on the step the user is currently on and control flow from step -to-step based on the result.


text:
Q: does linux kill() return after the process excute signal handler? I want use kill() to kill a program.
does linux kernel ensure that the program is killed before kill() returned?
If not, I have to check whether the program is killed already.

A:
does linux kernel ensure that the program is killed before kill() returned?

No, kill merely sends a signal to a process or group of processes.  Its successful return only tells you that the signal was sent.
The Linux man pages are straightforward about this, clarifying that a successful return means "at least one signal was sent".
So, this does not tell you whether the signal is blocked/held pending by the target process, was ignored (SIG_IGN), has taken its default action, has been handled, or accepted.


text:
Q: Not able to map Nginx Port 80 with docker container port 80 I'm running a NodeJS app that is running on port 4242 and here's the dockefile, docker-compose and nginx conf looks like this
Dockerfile
FROM node:12-alpine
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
EXPOSE 4242
CMD node index.js.

Docker Compose
services:
   web:
      build: .
   ports:
      - "80:4242"
   environment:
   DATABASE_URL: <DB_URL>
   depends_on:
      - db
command: >
    npm run start"

NGINX
server {
listen 80;
server_name server_name;

location / {
        try_files $uri $uri/ =404;
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
        proxy_pass http://localhost:80;
}
}

I wanted to make this app accessible via port 80 through Nginx along with with basic auth on port 80 but I'm not able to map the port correctly.
EDIT: I always get port already in use error because Nginx by default is listening on port 80 whereas and in docker-compose I'm mapping 80 with the 4242 which Dockerfile is exposing
Thanks in advance

A: You can't have both nginx and docker container on port 80.
They must listen to different ports to avoid "port already in use error".
You could map the container port 4242 to host port 4242 : replace - "80:4242" by - "4242:4242" in docker-compose file.
Restart your container with docker-compose restart web, you can check that your container is running with docker-compose ps (you'll see mapped ports at the same time)
Then, you have to change nginx conf accordingly :
server {
  listen         80;
  server_name    your_server_name;

  location / {
    auth_basic "Restricted Content";
    auth_basic_user_file /etc/nginx/.htpasswd;
    proxy_pass http://localhost:4242;
  }
}

Notes :

*

*I removed try_files as it was bypassing the proxy_pass instruction. Please provide context if you try to achieve something else with try_files.

*Replace your_server_name with your real server name.

*reload nginx

In the end you have :

*

*nginx (directly on host) listening on port 80,

*location block with basic auth,

*forwarding traffic to host port 4242,

*which is mapped to docker container port 4242 with proxy_pass,

*Finally hitting your NodeJS app.


text:
Q: How to customize context menu of Slack windows client? Im trying to build custom context menu for slack. But, the Slack API page doesn't contain any information about customizing user interface.
Currently Slack displays only 2 options:

Is it a known restriction? If not can anyone please let me know where to start to build the custom context menu for Slack windows client?

A: No, that is not something you can do to my knowledge. Slack is made to run on many different platform incl. mobiles, so I would not expect them to ever provide this feature.