text:
Q: Only apply image upload url to specific input field I'm making a custom field in a custom meta box in WordPress. I have input text fields, textareas, and checkboxes that are all working fine. I also included a browse button for the image gallery that is working.
When you click on the "Browse" button, it pulls up the WordPress media upload screen, and when you select that image, it will replace the input value (as well as an image thumbnail).
Here is the relevant part of the WordPress meta box set up.
function show_custom_fields_meta_box() {
    global $post;
    $meta = get_post_meta( $post->ID, 'custom_fields', true ); ?>
    <input type="hidden" name="custom_meta_box_nonce" value="<?php echo wp_create_nonce( basename(__FILE__) ); ?>">

      Image Upload

      <input type="text" name="custom_fields[image]" id="custom_fields[image]" class="meta-image regular-text" value="<?php echo $meta['image']; ?>">
      <input type="button" class="button image-upload" value="Choose or Upload an Image">

<img src="<?php echo $meta['image']; ?>" style="max-width: 250px;">

 }

And here's the jQuery I'm using to open the WordPress media gallery and upload the image.

Now, this works perfectly fine as-is. The input button has a class of .image-upload, and the input text field has a class of meta-image.
However, if I add another field...(custom_fields[image2])

  Image Upload

  <input type="text" name="custom_fields[image2]" id="custom_fields[image2]" class="meta-image regular-text" value="<?php echo $meta['image2']; ?>">
  <input type="button" class="button image-upload" value="Choose or Upload an Image">

<img src="<?php echo $meta['image2']; ?>" style="max-width: 250px;">

The jQuery will apply to both browse buttons and text inputs, because it's a class. I know (think) I have to use some form of $(this) to get the correct button and text input, but all of my efforts have been in vain so far.
I've tried $(this).closest('.meta-image'), but that doesn't seem to work.
Thank you!

A: You could use the variable selected in the select event handler.
Try this:
var metaImage = $(selected).closest('p').find('.meta-image),
    imgurl = $(metaImage).val();

A: I was able to do it with this code:
var meta_image = $(this).parent().children('.meta-image');


text:
Q: The server tag is not well formed - hyperlink templatefield <asp:TemplateField HeaderText="" HeaderStyle-HorizontalAlign="Center" HeaderStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>

                                                                   <asp:HyperLink runat="server" NavigateUrl='<%# string.Format("~/Details.aspx?MstId={0}&SaleDate={1}",HttpUtility.UrlEncode(Eval("MstId").ToString()), HttpUtility.UrlEncode(Eval("SaleDate").ToString())) %>'Text="View Details" />
                                                                </ItemTemplate>
                                                            </asp:TemplateField>

I am using above code to Show detail and wanted to pass two parameters in query string. but it is giving error as server tag is not well formed

A: Based on your code the issue possible because there is not space between single quotes and attribute "Text". Try to add a space in front of attribute "Text".

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to disable "just in time" debugger from visual studio 2008? I have started to see this winlogon.exe crash when i installed visual studio 2008, could it be possible to disable "just in time debugger" because once i press "no" or shut off the dialog window, my computer shuts off. the same happens when i shut off winlogon.exe with process explorer...
I would like to disable that just-in-time-debugger because i never needed it and sometimes when a fullscreen program crashes i cant click the "no" button at all and i have to press reset button from my computer.

A: You can disable JIT, You can find it in Visual studio 2008 under Options.

A: It can be found under Tools... Options... Debugging... Just In Time. Uncheck "native code."


text:
Q: bad base64 error during decrypting on AES I'm trying to encrypt and decrypt some text using AES algorithm like :
private static final String ALGORITHM = "AES";
private static final String MODE = "AES/CBC/PKCS7Padding";

public String encrypt(String value, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
    Cipher cipher = Cipher.getInstance(MODE);
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(key.getBytes()));
    byte[] values = cipher.doFinal(value.getBytes());
    return Base64.encodeToString(values, Base64.URL_SAFE);
}

public String decrypt(String value, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

    byte[] values = Base64.decode(value, Base64.DEFAULT);
    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
    Cipher cipher = Cipher.getInstance(MODE);
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(key.getBytes()));
    return new String(cipher.doFinal(values));
}

The encrypting code works perfectly fine but when I'm trying to decrypt the encrypted text it returns a bad base64 error.
What I tried to do before:
I already tried to change Base64.DEFAULT to Base64.URL_SAFE but it gave me the same error.
Also, I tried to replace "/" and "+" with "_" and "-" and it doesn't work either.
Heres the value I'm encrypted and trying to decrypt:
Ssg2w+dv7es7/wWAeAcoAOSVnYKsoLlefbmS8tYr+jc=
Thanks for helping...


text:
Q: Get volume-name from mounted volume as shown in finder I'm mounting an iso-file. Finder shows the name as "This Product" but the folder-name is /Volumes/this_product_" or could be something else.
How can I retrieve the name as shown in the Finder?

A: It depends on what you are using it for (just for manual lookup or for parsing).
In Applications -> Utilities -> Disk Utiltity you can just mark the partition (not the whole volume) and at the bottom of the window it will show the mount point.
If you need output that can be parsed somehow here are two ideas:
1) diskinfo list gives you a list of all disks in the system. And with the partition names on the disk your're looking for you can do an diskutil info disk1s1 (replace disk1s1 with the actual partition name) which will list the mount point.
2) Alternately, if you know the name and location one file on the mounted volume, you could do an ls /Volumes/*/thatfile and you'll get output of the volumes folder where it is found.


text:
Q: Why is there openSSL version difference? So I was trying to install nginx on my virtual machine. I firstly used epel repository, but it couldn't resolve some dependencies. So I configured nginx repository and tried installing nginx again. However one dependency still remains:

Error: Package: 1:nginx-1.14.0-1.el7_4.ngx.x86_64 (nginx)
             Requires: libcrypto.so.10(OPENSSL_1.0.2)(64bit)

So I searched how can I update openssl version, and I found a procedure here. I followed the steps, and when I ran openssl version, the output was:

OpenSSL 1.0.2o  27 Mar 2018

So I thought the dependency has been resolved. I tried installing nginx again, but same problem showed up again. When I ran yum info openssl, I received this output:

Name        : openssl Arch        : x86_64 Epoch       : 1 Version
  : 1.0.1e Release     : 42.el7 Size        : 1.5 M Repo        :
  installed From repo   : anaconda Summary     : Utilities from the
  general purpose cryptography library with TLS
              : implementation URL         : http://www.openssl.org/ License     : OpenSSL Description : The OpenSSL toolkit provides
  support for secure communications
              : between machines. OpenSSL includes a certificate management tool
              : and shared libraries which provide various cryptographic
              : algorithms and protocols.

Now I am highly confused. Why openssl version is showing OpenSSL 1.0.2o while yum info openssl is showing the version to be 1.0.1e. Am I missing something out here?
How can this be resolved? And even after useing nginx repository, I am unable to install nginx due to dependencies. What can be done to resolve this issue?
Any help is appreciated. Many thanks.


text:
Q: Maximizing two variables If I wanted to maximize two variables can I just rank the two variables from the sample as a point system and then sum the points? I know this probably isn't the most mathematically correct way. For example, if I have an average and a variance for 150 different samples from one population and I rank each average and variance and then add the points from both rankings could I maximize the sum?

A: Based on our conversation in the comments of your post (=trying to find the data point with the highest combo of 2 components), yes, it would be correct to calculate the combination for each data point, order these, and select the highest value.
For example, if $\alpha \in [0,1]$ were the weight of the $x$ components, you could

*

*Calculate the score for each data point as $z_i, \forall i\in 1..150$:

$\alpha*x_1+(1-\alpha)*y_1 = z_1$
$\alpha*x_2+(1-\alpha)*y_2 = z_2$
and so on until $z_{150}$

*

*Order all the values of $z_i$ from highest to lowest.

*Select the highest value of $z_i$ and find the associated $x_i$ and $y_i$


text:
Q: Remove duplicate row based on select statement I have two select statements which is returning duplicated data. What I'm trying to accomplish is to remove a duplicated leg. But I'm having hard times to get to the second row programmatically.
select i.InvID, i.UID, i.StartDate, i.EndDate, i.Minutes,i.ABID from inv_v i, InvoiceLines_v i2 where
i.Period = '2014/08'
and i.EndDate = i2.EndDate
and i.Minutes = i2.Minutes
and i.Uid <> i2.Uid
and i.abid = i2.abid
order by i.EndDate

This select statement returns the following data.

As you can see it returns duplicate rows where minutes are the same ABID is the same but InvID are different. What I need to do is to remove one of the InvID where the criteria matches. Doesn't matter which one.
The second select statement is returning different data.
select i.InvID,  i.UID, i.StartDate, i.EndDate, i.Minutes from InvoiceLines_v i, InvoiceLines_v i2 where
i.Period = '2014/08'
and i.EndDate = i2.EndDate
and i.Uid = i2.Uid
and i.Abid <> i2.Abid
and i.Language <> i2.Language
order by i.startdate desc

In this select statement I want to remove an InvID where UID is the same then select the lowest Mintues. In This case, I would remove the following InvIDs: 2537676 , 2537210
My goal is to remove those rows...
I could accomplish this using cursor grab the InvID and remove it by simple delete statement, but I'm trying to stay away from cursors.
Any suggestions on how I can accomplish this?

A: I have faced similar problems regarding duplicate data and some one told me to use partition by and other methods but those were causing performance issues
However , I had a primary key in my table through which I was able to select one row from the duplicate data and then delete it.
For example in the first select statement "minutes" and "ABID" are the criteria to consider duplicacy in data.But "Invid" can be used to distinguish between the duplicate rows.
So you can use below query to remove duplicacy.
  delete from inv_i where inv_id in (select max(inv_id) from inv_i group by minutes,abid having count(*) > 1 );

This simple concept was helpful to me. It can be helpful in your case if "Inv_id" is unique.

A: You can use exists to delete all duplicates except the one with the highest InvID by deleting those rows where another row exists with the same values but with a higher InvID
delete from inv_v
where exists (
    select 1 from inv_v i2
    where i2.InvID > inv_v.InvID
    and i2.minutes = inv_v.minutes
    and i2.EndDate = inv_v.EndDate
    and i2.abid = inv_v.abid
    and i2.uid <> inv_v.uid -- not sure why <> is used here, copied from question
)

A: ;WITH CTE AS
 (
 SELECT InvID
      ,[UID]
      ,StartDate
      ,EndDate
      ,[Minutes]
      ,ROW_NUMBER() OVER (PARTITION BY InvID, [UID] ORDER BY [Minutes] ASC) rn
 FROM InvoiceLines_v
 )
SELECT *
FROM CTE
WHERE rn = 1

A: Replace the ORIGINAL_TABLE with your table name.
QUERY 1:
  WITH DUP_TABLE AS
             (
              SELECT ROW_NUMBER()
              OVER (PARTITION BY minutes, ABID ORDER BY minutes, ABID) As ROW_NO
              FROM <ORIGINAL_TABLE>
             )
 DELETE FROM DUP_TABLE WHERE ROW_NO > 1;

QUERY 2:
  WITH DUP_TABLE AS
             (
              SELECT ROW_NUMBER()
              OVER (PARTITION BY UID ORDER BY minutes) As ROW_NO
              FROM <ORIGINAL_TABLE>
             )
 DELETE FROM DUP_TABLE WHERE ROW_NO > 1;


text:
Q: How to calibrate memoir's \sloppybottom and \flushbottom behavior? Memoir provides the command \sloppybottom which "lets TeX put an extra line at the bottom of a page to avoid a widow on the following page." [1] However it also seems to set \raggedbottom which is not something I want. If I add a \flushbottom after the \sloppybottom command I get the somewhat strange behavior of TeX adding an extra line at the top of a page to avoid a widow. Is there a way to get TeX to fill the page like with \flushbottom when using \sloppybottom but still having the top of all pages aligning?
(That is, the bottoms would align to except when one extra line is need to avoid widows)

A: \sloppybottom does its work by setting \topskip to a non standard value:
\topskip=1\topskip plus 0.625\topskip minus .95\topskip

This glue is inserted before the first box on the page, but the natural length is shortened by the height of the first box (or set to zero if that value would be negative).
Let's make an example. Suppose that \topskip=10pt (the usual value for ten point document size); if the first line on a page contains as the highest character an `A', which is 6.83331pt high, the glue inserted is 3.16669pt.
When \sloppybottom is in force, the glue inserted would be
3.16669pt plus 6.25pt minus 9.5pt

and so the page gets a stretchability of 6.25pt and a shrinkability of 9.5pt, which allows for possibly squeezing into it an additional line.
However, when the page is being shipped out, memoir puts other glue at the top and bottom of the page:
\vskip 0pt plus -0.625\topskip minus -0.95\topskip

is put at the top and
\vskip 0pt plus.0001fil minus .95\topskip

is put at the bottom. The effect of the glue in front of the page is to cancel out the stretch and shrink components of \topskip, so that the first line will go into its normal place. The glue at the bottom is necessary to compensate the line possibly added, because the output routine always wants to say something similar to
\vbox to \vsize{<what's to be output}

in order to put the footer in the same position on all pages. If you say \flushbottom you make TeX not to insert the two glues on the top and the bottom, but the non standard \toskip glue is already there and so there's nothing for compensating it: the result is that the first line is moved away from its usual position.
\enlargethispage does its work in a very different way, but it needs to be specified explicitly on the page we wish to enlarge.


text:
Q: Array of objects not rendering in order as set in CMS, using Kentico Kontent I'm having trouble rendering an array of widgets in the correct order. I am using graphql to query page data from kentico's kontent.ai. A page in the cms has a rich text field that can include a number of widgets. When I console log the array of widget items from the graphql data object, however, the array is not in order. For example, if the order in the cms is:
text item, video item, image item
then in the array of objects, the order is something like:
[image item, text item, video item]
important: this only seems to happen when i am using more that 10 widgets in the rich text field. If I use up to ten widgets, the order is correct. but if I use more than 10, the order is incorrect.
This is strange, because it's not in order on my local or on the live site, but it is rendering in order on my colleagues local (even on the pages that render more than 10 items). We are using the same branch and there is no difference in the code. Do you know why this may be happening?
and is there some way I can make sure the order remains the same in array, as it is in the cms?
here is a simplified version of my query (it's the linked_items array that is not ordered correctly):
query workDetailQuery($slug: String!) {
kenticoCloudItemWorkDetailPage(fields: { slug: { eq: $slug } }) {
    body_text {
        linked_items {
            ... on KenticoCloudItemStatsBreaker {
                internal {
                    type
                }
            }
            ... on KenticoCloudItemSectionBlock {
                internal {
                    type
                }
            }
            ... on KenticoCloudItemQuoteWithImages {
                internal {
                    type
                }
            }
        }
    }
}

}
This is a gatsby project (version 2.0.19), and i am using the gatsby-source-kentico-cloud package.
UPDATE
so we managed to figure it out! It was just that the default node version on my machine and the node version netlify was using, was 10.19.0. We updated both versions (on my machine and on netlify) to 12.13.0 and now the order is correct.

A: I could reproduce this behavior on gatsby-source-kontent v4.3.0 and it seems to me like a bug in the source plugin.
According to the source code, it really should preserve the order from the CMS - it's in the correct order in the Delivery API response as well. Could you please file a bug in this repository so I can investigate it further?
EDIT: This behavior was casued by outdated node version. Works fine on v12.


text:
Q: Laravel 5 - using dynamic properties in view I have a dynamic property user in my model:
class Training extends Model
{
    ...

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

And I can easy get username in controller like this:
Training::find(1)->user->name

But I don't know how to perform the same in view. I tried this:
Controller:
return view('training/single', Training::find(1));

View:
{{ $user->name }};

but without success, I'm getting error Undefined variable: user. So it's look like I can't access dynamic property in view.
Any idea how can I use dynamic property in views?

A: I fear that's not really possible. There's no way to set the $this context in your view to the model. You could convert the model into an array with toArray() but that would include the related model and you would have to access it with $user['name'].
I personally would just declare the user variable explicitly:
$training = Training::find(1);
return view('training/single', ['training' => $training, 'user' => $training->user]);

A: Use eager loading
return view('training/single', Training::with('user')->find(1));


text:
Q: How to prevent form Submission on ClickFunnels I am working on ClickFunnels. I am working with AJAX by http Request method. I want to prevent form Submission on specific response value.
How can I achieve it ?
I had written below code yet to prevent form from submission
if(http.response == 'error')
{
    e.preventDefault();
}
else
{
    $('#abc').val("Thanks.");
}

If i wrote return false; instead of e.preventDefault(); .... It is also not working.
Also on submission the function execute using below line
$("#submit-btn").click(function(e)

A: You have to remove the previously "onSubmit" event handlers. see full example at codepen.
function check (e) {
  $.get('https://api.github.com/', function(res) {
    console.log(res);
    if (res.hasOwnProperty('user_url')) {
      console.log('disabling the form.');
      $('#myform').removeAttr('onsubmit').submit( function(event) {
        event.preventDefault();
        alert("can't submit");
      });
    }
  })
}

btw, make sure your code runs at the right time. use "Event Listener" tab in chrome and lookup "submit" event. all submit handlers would be available there to stop, debug and investigate.


text:
Q: Move left barbutton item more to the right I have a leftbar button item. But I want it to move it more to the right. At the moment it sticks to the left hand side. Any body has an idea how I can achieve this?
Here is my code for the button itself.
 UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"task_status.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(changeStatus:) forControlEvents:UIControlEventTouchUpInside];
    [button setFrame:CGRectMake(80, 0,100, 18)];
    self.tabBarController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

Hope anyone kan help me with this.
Kind regards

A: Why not Adding Directly rightbar Button?
self.tabBarController.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(changeStatus:)] autorelease];

A: this is what I have done it worked for me
UIImage *image = [UIImage imageNamed:@"btn_bar_back.png"] ;
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(10.0, -15.0, image.size.width, image.size.height);//set your button frame
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setTitle:@"BACK" forState:UIControlStateNormal];
button.contentEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 0);// if want to move text more towards right
[button addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width+10, 50)];
button.center = CGPointMake(view.center.x, view.center.y);
[view addSubview:button];

self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:view] autorelease];

[view release];


text:
Q: To Plot data points in Basemap and skip values which are zero Presently I am plotting my data values in Basemap using scatter , but some of the data values are zero, hence when I set the color bar they give me some colored dots even for zero (blue in my case). I would like to have only the data values which are not zero in my plot. I find imshow little complex , I just would just like to provide x , y values and plot the data with colorbar. I want something like vmin to show only values greater than zero.. Could you please suggest your view...
Below is the code
    xs, ys = m(lon,lat)
    m.scatter(xs, ys, c=mean)
    c = m.colorbar(location='bottom',pad='7%')

A: You can replace the 0 values with np.nan (after importing numpy), which will have them not display.
Alternatively, you can used a numpy masked array.


text:
Q: Is every upper bound of a subset of a partially ordered set also a maximal element of the set? Here's Definition 4.1-1 on page 210 in Introductory Functional Analysis With Applications by Erwine Kreyszig.

A partially ordered set is a set $M$ on which there is defined a partial ordering, that is, a binary relation which is written $\leqq$ and satisfies the conditions
(PO1) $a \leqq a$ for every $a \in M$. (Reflexivity)
(PO2) If $a \leqq b$ and $b \leqq a$, then $a = b$. (Antisymmetry)
(PO3) If $a \leqq b$ and $b \leqq c$, then $a \leqq c$. (Transitivity)
"Partially" emphasizes the fact that $M$ may contain elements for which neither $a \leqq b$ nor $b \leqq a$ holds. Then $a$ and $b$ are called incomparable elements. In contrast, two elements $a$ and $b$ are called comparable elements if they satisfy $a \leqq b$ or $b \leqq a$ (or both).
A totally ordered set or chain is a partially ordered set such that every two elements of the set are comparable. In other words, a chain is a partially ordered set that has no incomparable elements.
An upper bound of a subset $W$ of a partially ordered set $M$ is an element $u \in M$ such that $$x \leqq u \ \ \ \mbox{ for every } \ x \in W.$$
(Depending on $M$ and $W$, such a $u$ may or may not exist.) A maximal element of $M$ is an element $m \in M$ such that $$m \leqq x \ \mbox{ implies} \ m = x.$$
{Again, $M$ may or may not have maximal elements. Note further that a maximal element need not be an upper bound. }

I have copied verbatim what Kreyszig has stated.
Now my question is, if $S$ is a non-empty subset of a partially ordered set $M$, then (according to this set of definitions) is every upper bound of $S$ (in $M$) also a maximal element of $S$?

A: I don't think so: why do you think it should?
An easy counterexample is $M:=\mathbb{Z}$ with partial ordering induced by the absolute value, the subset $S$ being $\{-1,1\}$. Every point of $S$ is an upper bound, but none is maximal.


text:
Q: Restore database in mongodb replication My requirement is to restore mongodb databases from dev box to test server having three nodes. I have setup the replication between three nodes for high availability.
I have created backup on dev using mongodump to a different directory.
Now my requirement is to restore all databases in test server using copied folder path.
I have looked number of articles over internet but did not find the exact solution to restore databases. I know mongorestore command will work but how to restore from different path.
I tried following steps to achieve this >
   1. Restore with replication /without replication.
   2. stop mongodb service and copy backup folder to data directory then
      start service.
Mongo Config Information >
storage:
  dbPath: "E:/AO_DATA/mongodb/data"
systemLog:
  destination: file
  path: "E:/AO_DATA/mongodb/log/mongod.log"
net:
  port: 30198
replication:
  replSetName: "repl_01"
Please help me to implement it.

A: Try using Studio3T. When you setup your replicaset in this software, you will see your nodes and your collections. Right click on the collection, export & import in your desired format and location.


text:
Q: ASP.NET MVC Model alternatives I'm creating an MVC project but reluctant to use ADO.NET Entity Framework for the reason that it does not provide me a layered approach for my application (DAL, BLL). Is this correct? If so, are there alternatives?

A: Not really correct on the BLL/DAL issue (I've done it), although they don't make it easy on you. Next version in .Net 4.0 solves this for the most part.
This space is exploding, tons of choices out there.
Here is what I would consider the cream of the crop

*

*Entity Framework (MS choice du jeur)

*NHibernate (Huge following, but a bit of ramp up)

*Subsonic (compact and simple yet powerful)

*Linq2Sql (hey stack overflow uses it)

In general, going with MSFT is never a bad choice as the support for the product is always there, and if they stick with EF it will eventually be the best choice (they usually get it right at version 3).  Nhibernate has been around for a while and there is a lot of fanatical support for them as well. Take a look at each community, easy to do by keywords here on SO.
Please don't pay for one, too many good free/open solutions out there
Interesting performance comparison here


text:
Q: `npm cache add ` does not work I pack an NPM library with:
tarball=$(npm pack)

then I run
npm cache add "$PWD/$tarball"

but when I inspect the npm cache in .npm, there's nothing new there.
Does anyone know why the NPM cache would not get updated by the add command?

A: I came across the very same problem on Windows2012 machine when using npm version 5.3.0. Moving on to 5.6.0 it is no longer a problem.


text:
Q: differentiable equiavlence If a function is differentiable that implies that the partial derivatives exists (from every direction) and that the derivative is linear. But a function having these two properties need not to be differentiable (any example?). My prof claimed that there is no equivalence to (total) differentiable rather than the definition, really? can one prove that?

A: It is a well known fact (see T. Apostol's book on Analysis) that if a function $f$  has a partial derivative, say $\partial_1f$  at a point $c$, and the remaining partial derivatives exist and are continuous at  every element in a neighborhood of $c$, then $f$ is differentiable at $c$.

*

*If this does not occur, $f$ may not be differentiable. For example
$$f(x,y)=(x+y)\mathbb{1}_{\{xy=0\}}(x,y) +\mathbb{1}_{\{xy\neq0\}}(x,y)$$ has partial derivatives $\partial_1f$  and $\partial_2f$ at $(0,0)$, but it is  not differentiable

*Another classical example (counter example rather) is
$$g(x,y)=\frac{xy^2}{x^2+y^4}\mathbb{1}_{\{x\neq0\}}(x,y)$$
For this function, all directional derivatives exists at $(0,0)$ and in spite of this, $g$ fails to be continuous at $(0,0)$ which it turn, implies that $g$ is not differentiable at $(0,0)$

*Consider the function $F:\mathbb{R}^3\rightarrow\mathbb{R}$ defined by
\begin{equation*}
F(x,y)=\left\{\begin{array}{lcr}
x+y-\frac{x^3y}{x^4+y^2} &\quad &\text{if}\quad (x,y)\neq(0,0)\\
0 &\quad& \text{otherwise}
\end{array}\right.
\end{equation*}
For any $\mathbf{v}=(h,k)$, the directional derivative $D_vF(\mathbf{0})=h+k$, however, $F$ is not differentiable at $\mathbf{0}$ since
$$
\frac{F(h,k)-h-k}{\sqrt{h^2+k^2}}=\frac{1}{\sqrt{h^2+k^2}}\frac{h^3k}{h^4+k^2}
$$
fails to converge to $0$ as  $(h,k)\rightarrow(0,0)$.

The common definition of (Fréchet) differentiability says that $f:U\rightarrow\mathbb{R}^m$, $U\subset \mathbb{R}^n$ open,  is differentiable at $c\in U$ if there exists a linear map $A:\mathbb{R}^n\rightarrow\mathbb{R}^m$ such that for all $h$ small enough
$$f(x+h)=f(x)+Ah_r(h)$$
where $\lim_{h\rightarrow0}\frac{\|r(h)\|}{\|h\|}=0$.
There is another notion of differentiability (Gâteaux) that deals with directional derivatives. It says that $f$ is (Gâteaux) differentiable at $c$ if there is a map $L:\mathbb{R}^n\rightarrow\mathbb{R}^m$ such that for any $u\in\mathbb{R}^n$,
$$\lim_{\lambda\rightarrow0}\frac{f(x+\lambda u)-f(x)}{\lambda}=Lu$$
(it is implicit that the limit exists)

*

*Fréchet implies Gâteaux and in such case $A=L$.

*Gâteaux implies Fréchet under special conditions (such as the ones I mentioned above), and in such case $L$ is linear and $A=L$. There are other set of alternative conditions but that is beyond the point here.

A: A standard example goes something like this: define a function $f:\mathbb{R}^2 \to \mathbb{R}$ with the following properties:

*

*$f(x,y)=0$ whenever $y \geq 1.5x^2$ or $y \leq 0.5x^2$. In other words, we only allow $f$ to take nonzero values in the open region between the parabolas $y=0.5x^2$ and $y=1.5x^2$.

*$f(x,y)=1$ whenever $x \neq 0$ and $y=x^2$. In other words $f$ takes the value $1$ everywhere on the parabola $y=x^2$, except for the origin, where we already have required $f(0,0)=0$.

It is not too hard to convince yourself such a function exists. It is even possible to find such functions which are smooth (i.e. $C^\infty$) at every point other than $(0,0)$.
On the other hand, it is clear that such a function of is not even continuous at $(0,0)$, since the value there is $0$, even though we can approach along the parabola $y=x^2$ where the value is $1$.
Finally, in spite of the discontinuity, we can check that the derivative of this function at $(0,0)$ is $0$ from every direction (in particular the derivative is "linear", which seems to be a property you want). The reason for this is that, if $L$ is any line through the $(0,0)$, then $f$ only takes the value $0$ on a sufficiently small interval of the line centered at $(0,0)$. The intuition here is that parabolas vanish faster than lines so, for instance, the parabola $y=1.5x^2$ must, for sufficiently small $x > 0$, scoot underneath of any line $y=mx$ with $m > 0$.


text:
Q: How to resolve issue? I given description in body // Hi, i got response from url but getting error as below in title, please fix the issue.
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0
    let Url = String(format: "http://www.fgndbdsn.in/index.php?route=api/mywebservices/addition")
    guard let serviceUrl = URL(string: Url) else { return }

    let parameterDictionary = ["first" : "25", "second" : "25"]
    var request = URLRequest(url: serviceUrl)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
        return
    }
    request.httpBody = httpBody

    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {

            print(data)
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [[String:Any]]
                print(json)
            }catch {
                print(error)
            }
        }
        }.resume()

A: The response from the server must be valid JSON with a top level container which is an array or dictionary.


text:
Q: Align bottom if near bottom of screen othweise align top I've added a kebab menu to a project using alpine.js (not really relevant I don't think), and it works nicely, but I'm looking for a way to align it differently when it's near the bottom of the container.
Basically, the bottom 2 rows in the container will force the menu off the bottom of the screen, making the user scroll down. Not a massive deal, but I'm sure there should be some way to fix that. At the moment, I simply have position relative (this is in a Django template, though don't really think that's too relevant either). Oh, and I'm using tailwindcss (hence the use of relative  and the other classes there, but a non-tailwind solution would be great ... I can work out later if I can do it with tw stuff or not :slightly_smiling_face: )
<div
    class="relative w-2 mx-1"
    x-data="{ open: false, color: false }"
    @keydown.escape="open = false"
    @click.away="open = false"

Image 1: Kebab menu

Image 2: Clicked on kebab menu near the top of the container

Image 3: Clicked on kebab menu at the end of the container

Image 4: Same as image 3, but after I've then scrolled down to see the rest.


text:
Q: angular-translate-loader-partial not loading {parts} outside of .config() on initial load I am using angular-translate in my app and using angular-translate-loader-partial to load the resource modules as I need them.  If I try to use $translatePartialLoader.addPart(resource) on the initial load in a resource service, the "part" being loaded won't translate on the page although it shows it as being available using $translatePartialLoader.isPartAvailable(resource).
In the code below, the 'menus' resource gets translated fine.  The 'people' resource is "loaded" but the translation doesn't happen.
Here is the chunk of code in angular.config -
$translatePartialLoaderProvider.addPart('menus');
$translateProvider.useLoader('$translatePartialLoader', {
    urlTemplate: '/resources/files/{part}/{lang}.json'
});
$translateProvider.preferredLanguage('en-US');

This call is being made by my resource service on the initial load -
$translatePartialLoader.addPart('people');

I have the refresh being made in angular.run -
run(function ($rootScope, $translate) {
    $rootScope.$on('$translatePartialLoaderStructureChanged', function () {
        $translate.refresh();
    });
}).

Once the site is loaded, the call to $translatePartialLoader.addPart({part}); will work as designed.


text:
Q: Spring-Boot AMQP 1.3.1.RELEASE - Durable Queue For some reason my queue is not created as durable even though I specify that setting within the Spring AMQP Queue configuration:
@Bean
Queue queue() {
    //durable queue - true
    return new Queue(queueName, true);
}

I am the using Spring AMQP to connect to RabbitMQ and listen to that Queue on a Direct Exchange.
@Bean
DirectExchange exchange() {
    return new DirectExchange(exchangeName);
}

@Bean
Binding binding(Queue queue, DirectExchange exchange) {
    return BindingBuilder.bind(queue).to(exchange).with(queueName);
}

@Bean
public ConnectionFactory connectionFactory() {

    CloudFactory cloudFactory = new CloudFactory();
    Cloud cloud = cloudFactory.getCloud();

    AmqpServiceInfo serviceInfo = (AmqpServiceInfo)
            cloud.getServiceInfo(serviceName);

    CachingConnectionFactory connectionFactory =
        new CachingConnectionFactory(serviceInfo.getHost());
    connectionFactory.setUsername(serviceInfo.getUserName());
    connectionFactory.setPassword(serviceInfo.getPassword());
    connectionFactory.setVirtualHost(serviceInfo.getVirtualHost());
    return connectionFactory;
}

@Bean
MessageListenerAdapter underwritingMessageListener() throws Exception {
    return new MessageListenerAdapter(new UnderwritingMessageListener()) {{
        setDefaultListenerMethod("onMessage");
    }};
}

@Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
        MessageListenerAdapter underwritingMessageListener) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setQueueNames(queueName);
    container.setMessageListener(underwritingMessageListener);
    return container;
}

Am I missing a configuration step?

A: The setting did not take effect because the Queue already existed, as non-durable, prior to deploying the code above. Deleting the Queue, via the management console or CLI, allowed the application to declare the Queue as durable (after reboot).
It would be helpful if Spring-AMQP (RabbitMQ) threw an exception when a Queue was already declared in a different state rather than proceeding with an invalid deployment.

A: You need a RabbitAdmin @Bean to do the declarations.
It registers itself with the connection factory and performs the declarations when the connection is established.


text:
Q: Is it possible to use .after() and time.sleep() together in tkinter? I want to keep updating the program after some time(using time.sleep(0.1)) and call a certain function after a delay of every 1 second(using .after()). Is it possible to do that? Below is a part of the code, I just have to add .after() and I don't know where it should go since writing that in the while loop doesn't give the intended result.
while True:
    draw()
    time.sleep(0.1)
    win.update()

A: You can use after and sleep together, but they will each do what they are documented to do. sleep will cause the program to sleep, and after will run the job sometime after the given time period. If the program is sleeping, it can't process event queues so the jobs scheduled by after can't run until the program stops sleeping.
For example, if you do root.after(1000, something) followed by time.sleep(5), Then the program will sleep for five seconds, and then when it wakes up it will run something.
As a general rule of thumb, you should never call time.sleep in the main thread of a GUI program.


text:
Q: Spliting string into a list of substrings I have a string id <- "Hello these are words N12345678 hooray how fun".
I would like to extract just N12345678 from this string.
So far I have used strsplit(id, " "). Now I have
>id
>[[1]]
>[1] "Hello" "these" "are" "words" "N12345678" "hooray" "how"
>[8] "fun"

Which is of type list and of length 1 (despite apparently having 8 elements?)
If I then use id <- id[grep("^[N][0-9]",id)],
id is an empty list.
I think what I need to do is split the string into a list of length 8 with each element as a substring and then grep should be able to pick out the pattern, but I'm not sure how to go about that.

A: Use regmatches
> regmatches(id, regexpr("N[0-9]+", id))
[1] "N12345678"

A: Do you know about strtok? It will parse your input line on certain characters. For the purpose of my example, I am breaking off a piece of my string every time I hit a space.
tempVar = strtok(string, " ");
// tempVar has "id" or everything up to the first space
while (tempVar != NULL)
{
     tempVar = strtok(NULL, " ");
     //now tempVar picked up the next word, and will loop picking up the next word until the end of string
}

Using this, your "Hello these are words N123456789 Hooray" would do this:
tempVar would be Hello, then "these" etc etc.
Each time through the loop tempVar would get a new value. So i would suggest evaluating tempVar in the loop (before grabbing the next one) so that you can stop when you have N123456789

A: Try:
gsub('\\b[a-zA-Z]+\\b','',id)

A: If you insist on using strsplit. I think this can solve the problem:
id <- "Hello these are words N12345678 hooray how fun"
id = strsplit(id, " ")
id[[1]][grep("^N[1-9]", id[[1]])]

Notice that I haven't changed your regex. It could be more precise expression such as ^N\\d+$.


text:
Q: How are classes not objects in C++? I was reading "Design Patterns: Elements of Reusable Object-Oriented Software", (specifically the chapter about the prototype design pattern) and it stated that...

"Prototype is particularly useful with static languages like C++ where classes are not objects, and little or no type information is available at run-time." (pg 121)

(emphasis mine)
I had always thought that classes were synonymous to objects, and I'm confused as to what this statement means.  How are classes not objects, and why does it matter if a language is static?

A: A class in C++ is not an object: a class is a description of how to build an object, and a reference to a type of an object.
Compare with a language like Python: in python, like in C++, you instantiate an object from a class.  Unlike C++, the class you used is also an object: it usually has type type, and you can create new ones at runtime, manipulate them like any other object, or even create objects which are classes which themselves have different types.
You may be wondering why you'd want this, and usually you don't need it -- it's like C++ template meta-programming, you only need it when you need it because you can't achieve your goal in any other way.  It's probably also the case that problems you'd solve in Python with meta-classes you'd solve in C++ using template meta-programming.

A: In C++, this declares a class:
class A {
public:
  int a;
};

whereas this declares an object:
A a;

One cannot interrogate a class a run-time, as one can interrogate an object. It makes sense to say, "object 'a', what is your address? Please invoke operator+. etc." In C++, with its static typing, it makes no sense to say, "Class A, what is your list of members? Please add a new member, "b"."
In other languages (Python comes to mind), one can manipulate classes in this way, because each class is also an object. In addition to serving as a template for objects, the class itself is an object -- it can be printed, modified, etc.

A: For example, a class could describe what a book is: Name, Author, Date of Publishing, Description.
An object of the "Book" class would be a specific book: C++ Primer Plus, Stephen Prata, 2005, A book that teaches C++.
So, classes are not the same as objects.

A: To expand on what Andrew Aylett said.

A class in C++ is not an object: a class is a description of how to build an object, and a reference to a type of an object.

Furthermore, in languages like Python or smalltalk.  Everything is an object.  A function is a object, a class is a object.  As such these languages are Dynamically Typed, meaning that types are checked during runtime and variables can take on any type.
C++ is statically typed. Variables can only take on one type, and type checking is performed at compile time.
So in python for instance, you can modify a class on the fly. Add functions and fields, because it is an object, and can be modified.

A: What that sentence refers is to is the fact that classes are not first-order entities in a language like C++. In other languages, you can pass a class as a parameter to a function, e.g., the same way as you can pass an object or a function as a parameter.
There are many more implications of being classes first-order entities or not, e.g., the possibility of modifying a class at runtime, or inspecting the full internals of a class, etc.
Usually classes are found to be first-order entities in dynamic languages like ruby, or in the meta object protocol for lisp, etc.
Hope this clarifies it a bit.

A: When a class is said to be an object, it means that there's an object that represents that class at runtime. In C++, classes are dissolved at compile time. Their instances (i.e. objects) are merely sequences of bytes holding the object's fields, without any reference to the class itself. Now, C++ does provide some type information at runtime via RTTI, but that's only for polymorphic types, and is not considered a class object.
The lack of having objects that represent classes at runtime is the reason there's no reflection in C++ - there's just no way to get information about a certain class, as there's no object that represent it.
BTW, C++ is considered a 2-level language: objects are instances of classes, but classes are not instances of anything, because they only exist at compile type. On 3-level languages such as C# and Java, classes are also objects at runtime, and as such, are themselves instances of yet another class (Class in Java, Type in C#). The last class is an instance of itself, hence the language only has 3 levels. There are languages with more levels, but that's beyond the scope of this question...

A: Classes are not the same as Objects. A class is (more or less) the type, and an Object is the instance, simmiliar to the following:
int i;
YourClass object;

Here you wouldn't say i and int are the same -- neither are YourClass and object.
What the statement wants to say: Many object orientated languages are very object orientated, so that they start making everything (or nearly everything) an object (of one or another class). So in many languages a class would be an instance (hence an object) of some class class (which can be confusing).
This sometimes has advantages, as you can treat classes (that's types) in such languages like you could treat any other object. You can than do very dynamic stuff with them, like store them in variables or even manipulate the classes during runtime (e.g. to create new classes your program finds the need to have).
Take a look at this c++-similiar pseudo code:
YourClass myObject = new YourClass();                // creates an object (an instance)
Class baseClass = myObject.get_class();              // store the class of myObject in baseClass. That's storing a type in a variable (more or less)
Class subClass = myObject.inherit();                 // dynamically create a new class, that only exists in variable subClass (a Class-object), inheriting from baseClass
subClass.add_method(some_function);                  // extend the new class by adding a new method
subClass.get_class() subClass.create_instance();     // declare a new variable (object) of your newly created type
BaseClass another_onne = subClass.create_instance(); // also valid, since you inherited

This obviously doesn't translate well to c++, because of c++'s strict typing. Other languages are more dynamic in typing, and there this flexibility can come in handy (and make thinks more complicated; sometimes both at the same time). Still I think it explains the principle, if you understand c++.

A:
I had always thought that classes were synonymous to objects

The language in OOP literature is sometimes not specific. It doesn't help either that programming languages have somewhat different notions of what an object is.
A class is a template or definition from where objects (instances of that class) are created. That is, a class provides the structure, type signatures and behaviors that objects of that class (or type... more on that later.)
An object is just a location in memory of an instance of that class.
Wikipedia provides good documentation on this. I suggest you read it:
http://en.wikipedia.org/wiki/Class_(computer_programming)
http://en.wikipedia.org/wiki/Object_(object-oriented_programming)
Also, there is the concept of a type. A type (or interface as sometimes called in some literature or programming languages) is typically the collection of type/method signatures (and possibly behavior). Things like Java interfaces and C++ pure virtual classes tend to represent types (but aren't exactly the same).
Then a class that conforms to that type (be it interface or pure virtual class) is an implementation of that type.
That class, that type implementation is just a recipe of how to construct objects of that class/type in memory.
When you instantiate a class/type, you reify, construct an instance (object) of that class in memory.
In C++, a class is not an object since a class itself is not instantiated. A C++ class is not an instance of some other class (see the definitions I put above.)
OTH, in languages like Java, a class itself is represented by instances of a primordial class (java.lang.Class). So a class X has an object in memory (an java.lang.Class instance) associated with it. And with it, with that "class" object, you can (in theory) instantiate or manufacture another instance (or object) of class/type X.
It can get confusing. I strongly suggest you search and read the literature on classes, types, prototypes and objects/instances.

and I'm confused as to what this statement means. How are classes not
  objects,

As explained above. A class is not an object. An object is an instance, a piece of memory constructed and initialized by the "recipe" of a class or type.

and why does it matter if a language is static?

That part of the book is a bit misleading because Java, for example, is statically typed and yet, classes can be object themselves. Perhaps the text is refering to dynamically typed languages (like JavaScript) where classes can also be objects or instances.
My suggestion is to never use the word object, and to simply limit the vocabulary to "classes" and "instances". But that's my personal predilection. Other people might disagree, and so be it.

A: The simpler I can put it for you to understand it:
An object is a "physical" instance of a class. It consumes memory while the program is running.
A class describes an object: Hierarchy, properties, methods. A class it's like a "template" for creating objects.


text:
Q: Android Network Location While 'location' us disabled on Android none of GPS or Network locations are available.
Unfortunately location is an important feature for a product we are working on, but the sub km accuracy not. So we developed few scripts that are working with Google CID and WiFi based location system that is either quite precise (30mt urban area).
While testing the UX we discover that actually more than 90% of users are allways worried to keep location on (allmost none of them for privacy reasons).
- They link the meaning of location to GPS and they are worried of power consumption, either if we are not turning on the GPS.
- As far as they keep location on and forgot about it (as there is not satellite symbol blinking over there) they will remember to turn it off as soon as they open another of those applications that start heavily using GPS while available.
We were thinking for last few days about all possible solutions to improve UX becouse of that network and GPS location are set together by a single toggle that people still turning off.
I'm asking have you ever face this problem that user will offer you all the locations you need, because you are using it rationally, but you still losing this information because the negative feedback other APPs are giving to the user while loc is on? Have you ever figured out with a solution?


text: Q: Navigation Bar overlay its child view In iOS 7 I have a navigation controller and add a root view controller to it; but the navigation bar will overlay upper part of this root view controller's view. I know there's a solution that sets self.edgesForExtendedLayout = UIRectEdgeNone; but my root view controller contains two sub views: one is scroll view and the other is pagecontrol, and this solution doesn't work out for me. So can anyone help me?


text:
Q: Add ads on cordova apps with Admob I'm searching a way to add ad with admob on my cordova app. I tried to use cordova plugin admob free ( https://github.com/ratson/cordova-plugin-admob-free ). Test ads works, but I have no results un dev mode.
Can you help me pls!

A: Try admod-plus, it have more user-base and updates,
Link - https://admob-plus.github.io/


text:
Q: C#: How to Populate a DropDownList with an Object? I am having some problems.
I just created a class named Student which has an other class object which is Batch as
public class Student{
      public Batch batch {get;set;}
      public string Name{get;set;}
      public string CNIC {get;set;}
}

and here is Batch Class
public class Batch {
      public string BatchName {get;set;}
      public int BatchYear {get;set;}
}

and i created a strongly typed view for Student class now how i am supposed to display get Batch Object with User with DropdownListFor method helper.
thanks in advance.

A: The DropDownListFor takes a List<SelectListItem> and turns it into a list. So you need to build the List<SelectListItem> and pass that to your view in your View Model. You won't be able to use a DropDownListFor directly with your batch class.
In order to display a dropdown list of the Batch Class, try something like the following
public class Student{

      public Student()
      {
          BatchSelectList = new List<SelectListItem>();
          BatchSelectList.Add(new SelectListItem { Text = "Some Label", Value = "Some Val" };
      }

      public Batch batch {get;set;}
      public string Name{get;set;}
      public string CNIC {get;set;}

      //Drop down properties used in view
      public String BatchSelectedItem { get; set; }
      public List<SelectListItem> BatchSelectList { get; set; }
}

With the above, you are building a place holder for the item that will be selected in the list, BatchSelectedItem, and you are also building your select list that will be used in the view.
In your view, you will need to the following.
@Html.DropDownListFor(x => x.BatchSelectedItem, Model.BatchSelectList)

Where the first option is what property the select list is bound to, and the second property is the list of objects that populate the DropDownListFor

A: You can create a list of Batch in your Student model
public class Student{
      public Batch batch {get;set;}
      public string Name{get;set;}
      public string CNIC {get;set;}
      public List<Batch> batchList {get;set;}
}

Then on your model you can set your DropDownList as:
@Html.DropDownListFor(model => model.batch, new SelectList(Model.batchList,"BatchYear","BatchName"))

In the code above you're setting that you have a DDL for batch witch is filled by batchList, shows you BatchName and sets value as BatchYear.


text:
Q: Fieldset not properly displaying I'm trying to use a fieldset but it is not working as exactly i wanted...
The legend is displayed outside fieldset...But I want it covered like normal fieldsets.
My code is,

<fieldset style="border:1px solid #999; border-radius:8px; box-shadow:0 0 8px #999;padding:6px;">
<legend style="text-align: left;margin-top:-15px;">References</legend>
//Some Text...
</fieldset>

A:

<fieldset>
  <legend>References</legend>
  //text
 </fieldset>

A: I think this issue is in the margin-top:-15px;, specifically in the -15px which is making the margin -15px larger (in other words 15pxsmaller!).
Example(Without margin-top:-15px;):

<fieldset style="border:1px solid #999; border-radius:8px; box-shadow:0 0 8px #999;padding:6px;">
<legend style="text-align: left;">References</legend>
//Some Text...
</fieldset>


text:
Q: Why 32bit CentOS 6 can run 64bit software? Screenshot of "uname -a", "/etc/redhat-release" and "file":
screenshot
It show that the "brook" executable is 64-bit and my CentOS 6 is 32-bit,  But the executable work correctly!
Here is the software download link: https://github.com/txthinking/brook/releases/download/v20181212/brook
Note that this machine is a VPS(Virtual Private Server) using OpenVZ tech.


text:
Q: Spark and SparkSQL: How to imitate window function? Description
Given a dataframe df
id |       date
---------------
 1 | 2015-09-01
 2 | 2015-09-01
 1 | 2015-09-03
 1 | 2015-09-04
 2 | 2015-09-04

I want to create a running counter or index,

*

*grouped by the same id and

*sorted by date in that group,

thus
id |       date |  counter
--------------------------
 1 | 2015-09-01 |        1
 1 | 2015-09-03 |        2
 1 | 2015-09-04 |        3
 2 | 2015-09-01 |        1
 2 | 2015-09-04 |        2

This is something I can achieve with window function, e.g.
val w = Window.partitionBy("id").orderBy("date")
val resultDF = df.select( df("id"), rowNumber().over(w) )

Unfortunately, Spark 1.4.1 does not support window functions for regular dataframes:
org.apache.spark.sql.AnalysisException: Could not resolve window function 'row_number'. Note that, using window functions currently requires a HiveContext;

Questions

*

*How can I achieve the above computation on current Spark 1.4.1 without using window functions?

*When will window functions for regular dataframes be supported in Spark?

Thanks!

A: You can use HiveContext for local DataFrames as well and, unless you have a very good reason not to, it is probably a good idea anyway. It is a default SQLContext available in spark-shell and pyspark shell (as for now sparkR seems to use plain SQLContext) and its parser is recommended by Spark SQL and DataFrame Guide.
import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.sql.hive.HiveContext
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions.rowNumber

object HiveContextTest {
  def main(args: Array[String]) {
    val conf = new SparkConf().setAppName("Hive Context")
    val sc = new SparkContext(conf)
    val sqlContext = new HiveContext(sc)
    import sqlContext.implicits._

    val df = sc.parallelize(
        ("foo", 1) :: ("foo", 2) :: ("bar", 1) :: ("bar", 2) :: Nil
    ).toDF("k", "v")

    val w = Window.partitionBy($"k").orderBy($"v")
    df.select($"k", $"v", rowNumber.over(w).alias("rn")).show
  }
}

A: You can do this with RDDs. Personally I find the API for RDDs makes a lot more sense - I don't always want my data to be 'flat' like a dataframe.
val df = sqlContext.sql("select 1, '2015-09-01'"
    ).unionAll(sqlContext.sql("select 2, '2015-09-01'")
    ).unionAll(sqlContext.sql("select 1, '2015-09-03'")
    ).unionAll(sqlContext.sql("select 1, '2015-09-04'")
    ).unionAll(sqlContext.sql("select 2, '2015-09-04'"))

// dataframe as an RDD (of Row objects)
df.rdd
  // grouping by the first column of the row
  .groupBy(r => r(0))
  // map each group - an Iterable[Row] - to a list and sort by the second column
  .map(g => g._2.toList.sortBy(row => row(1).toString))
  .collect()

The above gives a result like the following:
Array[List[org.apache.spark.sql.Row]] =
Array(
  List([1,2015-09-01], [1,2015-09-03], [1,2015-09-04]),
  List([2,2015-09-01], [2,2015-09-04]))

If you want the position within the 'group' as well, you can use zipWithIndex.
df.rdd.groupBy(r => r(0)).map(g =>
    g._2.toList.sortBy(row => row(1).toString).zipWithIndex).collect()

Array[List[(org.apache.spark.sql.Row, Int)]] = Array(
  List(([1,2015-09-01],0), ([1,2015-09-03],1), ([1,2015-09-04],2)),
  List(([2,2015-09-01],0), ([2,2015-09-04],1)))

You could flatten this back to a simple List/Array of Row objects using FlatMap, but if you need to perform anything on the 'group' that won't be a great idea.
The downside to using RDD like this is that it's tedious to convert from DataFrame to RDD and back again.

A: I totally agree that Window functions for DataFrames are the way to go if you have Spark version (>=)1.5. But if you are really stuck with an older version(e.g 1.4.1), here is a hacky way to solve this
val df = sc.parallelize((1, "2015-09-01") :: (2, "2015-09-01") :: (1, "2015-09-03") :: (1, "2015-09-04") :: (1, "2015-09-04") :: Nil)
           .toDF("id", "date")

val dfDuplicate = df.selecExpr("id as idDup", "date as dateDup")
val dfWithCounter = df.join(dfDuplicate,$"id"===$"idDup")
                      .where($"date"<=$"dateDup")
                      .groupBy($"id", $"date")
                      .agg($"id", $"date", count($"idDup").as("counter"))
                      .select($"id",$"date",$"counter")

Now if you do dfWithCounter.show
You will get:
+---+----------+-------+
| id|      date|counter|
+---+----------+-------+
|  1|2015-09-01|      1|
|  1|2015-09-04|      3|
|  1|2015-09-03|      2|
|  2|2015-09-01|      1|
|  2|2015-09-04|      2|
+---+----------+-------+

Note that date is not sorted, but the counter is correct. Also you can change the ordering of the counter by changing the <= to >= in the where statement.


text:
Q: feeding data present in series seperated by , into a columns of data frame I am a beginner in python. I am working on a project where I have data in following pattern:
Data in json file looks like this :
"price_time":[1398823200,1403154000,1403247600,1403301600,1403380800],"price_value":[901,909,918,927,936],],"salesRank_value":[2176,2318,2192,1801,1829]
df.head() command looks like this:
>>> df.head()
                                            1974-12-11 20:55:21
price_time    [1398823200, 1403154000, 1403247600, 140330160...
price_value   [901, 909, 918, 927, 936, 945, 954, 963, 972, ...
rating_time                                        [1475972640]
rating_value                                               [43]
review_count  [6558, 6560, 6561, 6562, 6564, 6566, 6568, 656...

df = pd.read_json('results.json')
In [] : print(df.head())
output :
price_time       [1398823200, 1403154000, 1403247600, 140330160...
price_value      [901, 909, 918, 927, 936, 945, 954, 963, 972, ...
salesRank_value  [2176, 2318, 2192, 1801, 1829, 2207, 1757, 177...

I want to transform this data into following pattern:
price_time   price_value  salesRank_value
1398823200   901          2176
1403154000   909          2318
1403247600   918          2192

and so on...
The code which i wrote is here but i am unable to get the desired result:
import pandas as pd

df1={}
df1['price_time'] = df.loc['price_time']
df1['price_value'] = df.loc['price_value']
print(df1)

output:
{'price_value': 1974-12-11 20:55:21    [901, 909, 918, 927, 936, 945, 954, 963, 972, ...
Name: price_value, dtype: object, 'price_time': 1974-12-11 20:55:21    [1398823200, 1403154000, 1403247600, 140330160...
Name: price_time, dtype: object}

A: price_time = [1398823200, 1403154000, 1403247600, 140330160]
price_value  =  [901, 909, 918, 927]
salesRank_value = [2176, 2318, 2192, 1801]

listdata = zip(price_time,price_value,salesRank_value)
print listdata

A: I am guessing you are having the data in single string(lines are differentiated by newline character) or in a file then you can use the following one liners.
Assuming data in single string variable data=df.head() looks something like this:
'price_time       [1398823200, 1403154000, 1403247600]\nprice_value      [901, 909, 918]\nsalesRank_value  [2176, 2318, 2192]'

you can use following to get the required array:
array=[a.split() for a in data.replace("[","").replace(",","").replace("]","").split('\n')]

Output(2D array with each inside array containing each row with 1st element as name of row and remaining as data):
[['price_time', '1398823200', '1403154000', '1403247600'], ['price_value', '901', '909', '918'], ['salesRank_value', '2176', '2318', '2192']]

If you have the data in file data.txt like this:
price_time       [1398823200, 1403154000, 1403247600]
price_value      [901, 909, 918]
salesRank_value  [2176, 2318, 2192]

Then use the following:
array=[line.replace("[","").replace(",","").replace("]","").split() for line in open('data.txt')]

And the output again in 2D array like before:
[['price_time', '1398823200', '1403154000', '1403247600'], ['price_value', '901', '909', '918'], ['salesRank_value', '2176', '2318', '2192']]

For the json file's data as given by you:
"price_time":[1398823200,1403154000,1403247600,1403301600,1403380800],"price_value":[901,909,918,927,936],"salesRank_value":[2176,2318,2192,1801,1829]

Use this without needing pandas:
array=[b.split() for b in  open('data.json').read().replace('"',"").replace(":["," ").replace("],","\n").replace(","," ").replace("]","").split('\n')]
print array

(There is a neater way to remove non-alphanumeric characters, but since i needed to format string as i wanted i used this)
The output like earlier in a 2D array:
[['price_time', '1398823200', '1403154000', '1403247600', '1403301600', '1403380800'], ['price_value', '901', '909', '918', '927', '936'], ['salesRank_value', '2176', '2318', '2192', '1801', '1829']]

See the result in tabular form:
for z in range(len(array[0])):
 temp=''
 for y in range(len(array)):
  temp+=array[y][z]+'\t'
 temp+='\n'
 print temp

Output:
price_time      price_value     salesRank_value

1398823200      901     2176

1403154000      909     2318

1403247600      918     2192

1403301600      927     1801

1403380800      936     1829

For prettier output, use this:
s = [[str(e) for e in row] for row in array]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = ' '.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print '\n'.join(table)

Output:
price_time      1398823200 1403154000 1403247600 1403301600 1403380800
price_value     901        909        918        927        936
salesRank_value 2176       2318       2192       1801       1829


text:
Q: SQL - Is there a way know if a record exit in a source when joining 2 sources SQL - Is there a way know if a record exist in a source when joining 2 sources.
I am joining 2 sources S1 and S2 on a common field A. Lets S1 is a master list and contains all the records, whereas S2 is subset of S1 for A values.
SELECT S1.A, S1.B, S2.C
FROM S1 (NOLOCK) LEFT JOIN
     S2 (NOLOCK)
     ON S1.A = S2.A;

Is there a way to add a custom field in the SELECT to determine if that A record is present in S2 or not?

A: this should work:
SELECT S1.A, S1.B, S2.C,
       test=(case when s2.a is null then 'present' else 'not present' end)
FROM S1 (NOLOCK) LEFT JOIN
     S2 (NOLOCK)
     ON S1.A = S2.A;


text:
Q: Hindman's theorem on coloring a set with $n$ colours Hindman's theorem states that if we colour $\mathbb{N}$ (positive integers) with a finite number of colours $c_1,\ldots,c_n$, then there exists a color $c_i$ and an infinite subset $A \subset \mathbb{N}$ such that every finite sum of elements in $A$ has the same colour.
But wouldn't this imply that each element of $A$ has the same colour? If $a,b \in A$ and the colour of $a$ and $b$ are different, then ... that's a contradiction, right?
Clearly I'm misunderstanding something. If someone could shed some light on this that would be great.

A: A sum of one term is still a sum.  So yes, your reasoning is correct--the set $A$ must be all the same color.
That the set itself also has the same color is also made clear by Wikipedia, emphasis mine:

We can reformulate a special case of Hindman's Theorem in more familiar terms: Suppose the natural numbers are "colored" with $n$ different colors; each natural number gets one and only one of the $n$ colors.  Then there exists a color $c$ and an infinite set $D$ of natural numbers, all colored with $\boldsymbol{c}$, such that every finite sum over $D$ also has color $c$.

I previously erroneously claimed that it is equivalent that there exists an infinite subset of $\mathbb{N}$, all of the same color, and closed under addition--the set of all finite sums of elements of $A$.
This is incorrect.  The difference is that "finite sum" refers here only to sums of a finite number of distinct elements.
I apologize for the error.


text:
Q: How to solve fourth degree equation How do I solve?
$\frac{4}{x^2}=5-x^2$
My textbook just solve it like
$(x^2 −4)(x^2 −1)=0$
but do not explain how to to do it

A: multplying by $x^2$ we obtain:
$$x^4-5x^2+4=0$$ Setting $t=x^2$
we get;
$$t^2-5t+4=0$$ this is a quadratic equation to solve

A: As the hint given by @Moo says
$$4=5x^2-x^4 \Rightarrow x^4-5x^2+4=0,$$
then let $u=x^2$ so
$$u^2-5u+4=0.$$
Can you finish from here?

A: \begin{align}
\dfrac{4}{x^2} &= 5-x^2 \\
\dfrac{4}{x^2} - 5+x^2 &=0\\
\dfrac{4}{x^2} - \dfrac{5}{1} + \dfrac{x^2}{1} &=0\\
\dfrac{4-5x^2+x^4}{x^2}  &=0\\
\dfrac{4-4x^2-x^2+x^4}{x^2}  &=0\\
\dfrac{4(1-x^2)-x^2(1-x^2)}{x^2}  &=0\\
\dfrac{(4-x^2)(1-x^2)}{x^2}  &=0
\end{align}
for $x^2\neq0$ we have $(4-x^2)(1-x^2)=0$ or $(x^2-4)(x^2-1)=0$.

A: Well, we get $$4=5x^2-x^4$$ that is, we get $$x^4-5x^2+4=0$$ then  we get (by using factoring, it is quadratic in form) $$(x^2-4)(x^2-1)=0.$$


text:
Q: Trying to get property 'name' of non-object when trying to click next page using pagination I get an error saying "Trying to get property 'name' of non-object" when I tried to click on next page using pagination.
Here is my Controller:
$websites = Website::all();
    $menu = Menu::with('categories')->whereHas('categories', function ($query) {
        $query->where('slug', request()->category);
    })->paginate(8);

    $categories = Category::all();
    $categoryName = $categories->where('slug', request()->category)->first()->name;

    return view('shopmenu')->with([
        'menu' => $menu,
        'categories' => $categories,
        'categoryName' => $categoryName,
        'websites' => $websites,
    ]);

The error is in this code:
 $categoryName = $categories->where('slug', request()->category)->first()->name;

How do I solve this?

A: You need to put check if you are getting any record then try to access name.
 $categoryName = $categories->where('slug', request()->category)->first();

 if ($categoryName) {
 $categoryName = $categoryName->name;
 }

Basically due to chaining when you get null in this query $categories->where('slug', request()->category)->first() and you try to access name property on null you get this error.


text:
Q: Create a registration form with a PayPal checkout fee? My client is looking to start taking online registration for their many conventions and events. Previously they handled this all offline with PDF documents and in person payment. I'm looking for either a plugin or a detailed FAQ that will help me integrate an online registration plus payment system into their Wordpress site.
I'm open to both free and paid services. Any and all help will be greatly appreciated.
On a related note (just for some background on the scope of the project), ideally the user would have their own account on the Wordpress site. And they would register for one or multiple events at any given time throughout the year. This may or may not be difficult to implement. It's something they'd like to have, but if it's too hard I think we might just go without it.
Thank you!

A: Wordpress + Gravity Forms is all you'll need for this project. Gravity Forms even has paypal integration. Set up a registration form, add on payment and you're ready to roll. They have detailed instructions and tutorials on how to set everything up and a very active forum if you run into any issues.


text:
Q: How to exit apache config in Centos I'm sure this is a really dumb question but I was installing LAMP and added index.php to my file and now I want to save and exit and I have no idea how to save and get off this screen. I'm sure it cant be that hard I cant work it out, this is my first time using centos-
http://puu.sh/5SK3E.png


text:
Q: Pass image path from database to HTML image source using PHP I have a pics table that has the path of an uploaded photo. I want to display that image if a user uploaded a photo. I have a users table that has a pic_id that references the pic_id in a pics table.
Table schema:

After a user uploads a photo I reference the pic_id in the user's table with the pic_id in the pics table, which also has the pictures name and path.
I want to display that uploaded photo inside a div if the user has uploaded a photo. If not I attribute a default photo to the user.
HTML Sample code:

Inside by getimage.php:
<?php
session_start();
include 'db_connect.php';
    if(isset($_SESSION['pic_id']))
    {
        $pic_id = $_SESSION['pic_id'];
          $sql_select = "SELECT filepath FROM pics WHERE pic_id = '$pic_id'";
          $result = $conn->query("$sql_select");
          $filepath = $result->fetch_assoc();
          $path = $filepath['filepath'];
            $finfo = finfo_open(FILEINFO_MIME_TYPE);  // return mime type ala mimetype extension
            $mime_type = finfo_file($finfo, $path);
            finfo_close($finfo);
            switch($mimetype)
            {
                case "image/jpeg":
                header ('content-type: image/jpeg');
                echo '';
                break;

                case "image/png":
                header ('content-type: image/png');
                echo '';
                break;
            }
    }
    else
    {
        echo "uploaded_images/default_photo.jpg";
    }
?>

I'm not sure if this is the correct way to do this as I am trying to self teach myself PHP. If there is an easier way to do this with AJAX or any other way I would be happy to give it a shot.

A: I would recommend using a Framework if you are working on a project. If you are only testing stuff this is fine. For testing purpose I would put the code before the HTML and just assign the path of the image to a variable then echo this path in the src of the image.
<?php
...
if(isset($_SESSION['pic_id']))
    ...
    $imageSrc = '/path/to/image.jpg';
} else {
    $imageSrc = '/path/to/default.jpg';
}
?>
<!doctype html>

    <img src="<?php echo $imageSrc ?>">

A: if you only want to return a string with the new image url or html do not set the content-type to any image format.
otherwise if you really want to send the image back that is uploaded see this post

A: In your case, I see two solutions:

*

*on logging, create a session var with pic path and echo it in your src attribute simply

*

*if you want to preserve your getimage script, don't return an html tag but load image in var and echo this var and content type of image, nothing else (search for image proxy pattern if you want to study it)

Good luck

A: In a better way:
<?php
...
if(isset($_SESSION['pic_id']))
    ...
    $imageSrc = $_SESSION['pic_path'];
} else {
    $imageSrc = '/path/to/default.jpg';
}
?>
<!doctype html>

    <img src="<?php echo $imageSrc ?>">

But if you are learning PHP don't start with a framework now, you must know POO before and know basic procedural aspects


text:
Q: Find the different content using shell Does somebody know how to use shell to compare two files? and find the different content between them, for example, 1.txt contain 1023 name ,  2.txt contain 800, I want to know the different 223 name between 1.txt and 2.txt

A: comm
You'd have to sort the files for it though.
sort 1.txt > 1.sorted.txt
sort 2.txt > 2.sorted.txt

comm -3 1.sorted.txt 2.sorted.txt

Note that will also tell you if there are lines in 2 that are not present in 1. That it holds less lines does not necessarily mean they all exist in 1.
# only show lines that are in 1 or 2, but not both
comm -3 1.sorted.txt 2.sorted.txt

# only show lines that are unique to 1
comm -23 1.sorted.txt 2.sorted.txt

# only show lines that are unique to 2
comm -13 1.sorted.txt 2.sorted.txt


text:
Q: Get date difference in days, hours, mins and secs (AM/PM date) Trying to get date difference in day - hours - mins - sec from a string entry of date. Also the time entry is having AM, PM.
I am trying to use substring and converting it date time, but AM - PM is making it difficult.
I have: 06-OCT-15 09.30.20.000000 AM and 06-OCT-15 09.45.20.000000 PM
I am trying to get: 0 day(s) 12 hour(s) 15 min(s) 0 sec(s).

A: See below SQL Server query. I know this will work as I have some experience in this.
WITH CTE AS (
    SELECT CAST(
      DATEDIFF(
              DAY,
              '2015-10-06 08:00:00.00 AM',
              '2015-10-06 09:00:00.00 PM'
          ) AS
          VARCHAR(1000)
      ) + ' day(s)' AS      Days,
      CAST(
          DATEDIFF(
              hh,
              '2015-10-06 08:00:00.00 AM',
              '2015-10-06 09:00:00.00 PM'
          ) AS VARCHAR(1000)
      ) + ' hour(s)' AS     Hours,
      CAST(
          DATEDIFF(
              mi,
              '2015-10-06 08:00:00.00 AM',
              '2015-10-06 09:00:00.00 PM'
          ) AS VARCHAR(1000)
      ) + ' min(s)' AS      Minutes,
      CAST(
          DATEDIFF(
              ss,
              '2015-10-06 08:00:00.00 AM',
              '2015-10-06 09:00:00.00 PM'
          ) AS VARCHAR(1000)
      ) + ' sec(s)' AS Seconds
)
SELECT Days + ' ' + Hours + ' ' + Minutes + ' ' + Seconds AS FullDifference
FROM   CTE

A: it may help
http://www.w3schools.com/sql/func_datediff.asp
Example to get hours
you have to change you date string
like
select datediff(hour,CONVERT(datetime, '06-OCT-15 09:00:00.000 AM'),'06-OCT-15 08:00:00.000 PM') AS DiffDate
result:
11

A: The biggest problem seems to be a proper conversion of your datetime format to something that mySQL can work with.
Here you will find format options provided by mySQL to do this:
www.w3schools.com/sql/func_date_format.asp


text:
Q: Prove $\sum_{i=1}^{i=n}\frac{a_i}{S-a_i}\geqslant \frac{n}{n-1}$ and $\sum_{i=1}^{i=n}\frac{S-a_i}{a_i}\geqslant n(n-1)$. Let $a_1,a_2,\ldots ,a_n$, be positive real numbers and  S = $a_1+a_2+a_3+\cdots+a_n$. Use the Cauchy-Schwarz inequality to prove that
$$\sum_{i=1}^{i=n}\frac{a_i}{S-a_i}\geqslant \frac{n}{n-1}$$ and $$\sum_{i=1}^{i=n}\frac{S-a_i}{a_i}\geqslant n(n-1)$$
Hint: Apply the inequality to:

*

*$\sum \frac{S}{a_i}$ and $\sum \frac{a_i}{S}$ for one case,

*and $\sum a_i(S-a_i)$ and $\sum \frac{a_i}{S-a_i}$ for the other case.

A: Cauchy Schwarz Inequality:
$$
\begin{align*}
\left( \frac{1}{a_1}+\frac{1}{a_2}+\dots +\frac{1}{a_n}\right)\left( a_1+a_2+\dots+a_n \right) &\geq \left(\frac{1}{\sqrt{a_1}}\sqrt{a_1}+\frac{1}{\sqrt{a_2}}\sqrt{a_2}+\dots +\frac{1}{\sqrt{a_n}}\sqrt{a_n} \right)^2 \\\
&\geq \left( 1+1+\dots+1\right)^2 = n^2
\end{align*}
$$
which when applied here
$$
\begin{align*}
\displaystyle\sum_{i=1}^n \frac{S}{a_i} &= \left( \frac{1}{a_1}+\frac{1}{a_2}+\dots +\frac{1}{a_n}\right)S \geq n^2\\
\end{align*}
$$
Therefore
$$
\begin{align*}
\displaystyle\sum_{i=1}^n \frac{S-a_i}{a_i} &= \displaystyle\sum_{i=1}^n \frac{S}{a_i} -n\\
&\geq n^2 - n = n(n-1) \tag{1}
\end{align*}
$$
Similarly, re-writing the other summation
$$
\begin{align*}
\displaystyle\sum_{i=1}^n \frac{a_i}{S-a_i} &=
\frac{S-\displaystyle\sum_{j \neq 1}a_j}{\displaystyle\sum_{j \neq 1}a_j} + \frac{S-\displaystyle\sum_{j \neq 2}a_j}{\displaystyle\sum_{j \neq 2}a_j}+\dots +\frac{S-\displaystyle\sum_{j \neq n}a_j}{\displaystyle\sum_{j \neq n}a_j}\\
&= \displaystyle\sum_{i=1}^n \left(\frac{S}{\displaystyle\sum_{j \neq i}a_j}\right)-n \tag{2}
\end{align*}
$$
Also since
$$
\displaystyle\sum_{j \neq 1}a_j+\displaystyle\sum_{j \neq 2}a_j+\dots+\displaystyle\sum_{j \neq n}a_j = (n-1)S
$$
By Cauchy-Schwarz Inequality
$$
\begin{align*}
\displaystyle\sum_{i=1}^n \left(\frac{1}{\displaystyle\sum_{j \neq i}a_j}\right)(n-1)S \geq n^2\\
\Longrightarrow \displaystyle\sum_{i=1}^n \left(\frac{1}{\displaystyle\sum_{j \neq i}a_j}\right) \geq \frac{n^2}{(n-1)S}
\end{align*}
$$
From $(2)$
$$
\begin{align*}
\displaystyle\sum_{i=1}^n \frac{a_i}{S-a_i} &\geq \left(\frac{n^2}{n-1}\right) - n\\
&\geq \frac{n}{n-1}
\end{align*}
$$

A: The left sides are the values of $\sum f(p_i)$ and $\sum g(p_i)$ with $\sum p_i = 1$ being constant, where
$f(x) = \dfrac{x} {1-x}$
$g(x) = \dfrac 1 x - 1$, and
$p_i = \dfrac {a_i} S $.
Both functions are convex for $x>0$, so that each sum of values is minimized when all arguments $p_i$ (and therefore all $a_i$) are equal.
Another line of argument that makes this obvious is the Rearrangement Inequality: the average of the sequence $x_i y_i$ is larger or equal to the product of the averages of $x_i$ and $y_i$ if the two sequences are in the same order.  In the first inequality the sequences $a_i$ and $(S-a_i)^{-1}$ are in the same order, and in the second inequality, $(S-a_i)$ and $1/a_i$ are in the same order.  The averages of $a_i$ and $(S-a_i)$ are $S/n$ and $(n-1)S/n$, which depend only on $S$.  The other averages lead to the standard problem of minimizing a sum of reciprocals given the sum of the variables, which happens when the summands are equal.


text:
Q: Creating new arrays in a Table I have a 3x6 matrix a:
a = {{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17,
   18}}

What I want is to end up with 6 1x3 arrays,
{miniOut, minimaOut, curvaturesMiniOut, maxiOut, maximaOut, curvaturesMaxiOut}

such that miniOut = {1,7,13}, minimaOut = {2,8,14} etc.
My attempt is:
stuff = Table[{miniOut[[n]], minimaOut[[n]], curvaturesMiniOut[[n]],
    maxiOut[[n]], maximaOut[[n]], curvaturesMaxiOut[[n]]} =
   a[[n]], {n, 1, Length[a]}]

But it says

Symbol miniOut in part assignment does not have an immediate value.

and the same for the other variables.
Do I need to pre-define the arrays in advance and set all the elements to 0?

A: It seems you are looking to store each column of a into separate variables. There is no need to do this element-wise. The easiest way is to use Transpose on a so that the columns become rows: in other words, the columns become the elements at level 1 in Transpose[a]. Then you can assign them all simultaneously:
{miniOut, minimaOut, curvaturesMiniOut, maxiOut, maximaOut, curvaturesMaxiOut} = Transpose[a]


text:
Q: Exporting boxfuse image I have created a working image which I can start by simply calling boxfuse run <image name>. Can I export the image to a file and hand it over to my colleagues so they can run it from virtualbox?

A: Simply share you Boxfuse user and secret. You can then push your image to the Boxfuse Vault from one machine and pull it down on the other.


text:
Q: Can I use "Online Backup" to backup my DVS instead of pushing to an external repo? I'm currently signed up with a third party service that hosts my mercurial repositories as a central hub to push my changes to as a sort of backup.
Now, I'm looking at a system to backup my laptop and am concidering Mozy. I'm a loan developer, and work on a laptop and am usualy connected to my internet via wifi with my laptop only really being on when I'm working, so feel something like Mozy is my best option.
My question is, if I'm the only developer, could I get away with just using local mercurial repos and using Mozy to backup everything up? Rather than pushing to an external repo?
Many thanks
Matt

A: Disclaimer: My experience is with git rather than hg, but as I understand it the concepts apply equally to both systems.
An advantage of backing up to a remote repo is that if your local repo becomes corrupted (perhaps due to a problem with the underlying filesystem), that corruption does not get transferred over to the backup, unless the files in your working tree themselves are corrupted.
For example, it's possible for some of the objects in the repository, perhaps those which are rarely accessed because you don't change them, to become corrupted.  It could be months before you use one of those files again, and so months before you notice (though I think doing a garbage collect run, eg git gc, will detect corruption).
So if you are backing up by pushing commits, you're creating an independent version of those objects, and using checksums (ie the commit hash) to verify the transfer of any new files.  Whereas if you are backing up to a backup provider, you're duplicating the actual objects in the repo, in whatever state they are in, and duplicating any changes to those files, including corruption of them.
Usually backup providers will give you rollback (spideroak seems to be particularly good for this) but you'll still have to sift through a lot of versions to figure out when the corruption happened; also with some providers, the rollback period is limited (especially for free accounts).


text:
Q: How to send a variable from yml as an attribute for custom annotation in Spring Boot projects? I want to create a custom annotation to use it in Spring Boot projects at methods from RestController. I'll use a Before Advice to create it and I want send information to the advice. I want to use a variable url and this variable can have 2 different values for 2 different environments, so I want to configure it inside cloud config on the application.yml of the service and send it as an attribute to the external library. The business logic for the annotation will be implemented in an outside library and I'll import the dependency in all the services.
@PostMapping("/test")
@Traceable(url = "${url.external}")
public Data test(@RequestBody Data data, HttpServletRequest servletRequest) {

    System.out.println("Inside controller, data = " + data);

    return data;
}

I know how to send a constant or how to send the variable data as attributes. But I don't know how to send a value from application.yml as an attribute. I want to send this variable from the application.yml of the microservice because the external library isn't a Spring Boot project and it doesn't have an application.yml. How can I do that? Thank you!

A: If your question is about evaluating a Spel variable reference programmatically in your aspect, here's what you can do:
Aspect
@Aspect
@Component
public class TraceableAspect {
    private final EmbeddedValueResolver embeddedValueResolver;

    public TraceableAspect(ConfigurableBeanFactory beanFactory) {
        this.embeddedValueResolver = new EmbeddedValueResolver(beanFactory);
    }

    // use your actual Traceable package name here
    @Before(value = "@annotation(your.package.Traceable)")
    public void handleTraceable(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Traceable traceable = method.getAnnotation(Traceable.class);
        String urlExpression = traceable.url();
        String url = embeddedValueResolver.resolveStringValue(urlExpression);

        // your code that uses the resolved `url` ...
    }
}

Also, you can just make your aspect implement a EmbeddedValueResolverAware interface and get the resolver injected by Spring for you instead of creating it manually.
Just for completeness:
Traceable annotation
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Traceable {
    String url();
}

application.yaml
url.external: http://stackoverflow.com

Make sure to have the org.springframework.boot:spring-boot-starter-aop dependency in your project if you don't have it already.


text:
Q: In the Dune universe, how do the sandworms enlarge the desert? In Chapterhouse Dune and in Hunters of Dune, it is clear that the Sandworms are causing the desert area to grow and take more and more of the surface of the planet. However, the sandworms need desert-sand to be able to move (as implied by their name). Do they actually turn other types of ground into sand? Is this something caused by the melange or does it happen in some other way?

A: The factors involved in the ongoing desertification:

*

*Sandtrout wall off moist areas in the sand

*

*if the water is in a dry enough environment, the convert it to the pre-spice mass

*if the water is is not in a dry enough environment, or is a large enough body, it merely builds up a layer of dead sandtrout, creating a barrier to that water migrating nearby and thus preventing it's use by plants. (Read the descriptions of Jacrutu.)

*Sandtrout isolate and encapsulate root systems on the plants on the sand's edge.

*

*this process would be similar to the process Leto II experiences.

*encapsulated roots can draw nutrient only from the sandtrout; this will kill most trees and plants by starvation.

*as plants starve off and die, the edge of the desert expands, as their decomposition allows the sandtrout to push further back in the root mass.

*as the edge dries, sandtrout are also able to form the pre-spice mass, and when that mass generates a spice blow, it liberates the soil, and blows sand over the desert edge, also hastening the edge migration.

*Desert erosion of plant free surfaces increases sand.

*

*the more sand, the more water migrates under the sand.

*due to the sandtrout, moist sections that are deep enough in the sand will be capped off.

*likewise, water that hasn't migrated deep will be converted to spice.

*Sandoworms

*

*the sandworm friction results in heating

*

*this increases the vapor release from the sand to the atmosphere

*this converts a portion of the biological energy into heat, which is radiated from the ground.

*

*increased ground heat results in harsher climate at basin edge, with more severe wind, and nutrient stripping into the desert low-pressure system, as wel as moisture dump at the edges of the desert, where sand trout can encapsulate and isolate pools.

*Sandworm movement results in friction-erosion of basin bottoms and solid objects in the sand.

*

*this creates more and deeper sand

*this reduces dry biological particle sizes

*this reduces rocks and spires in the sand basins to smaller/thinner ones.

*sandworms eat biological material mixed in sand; this includes sand-top photosynthetic plantonids, as well as plant debris blown from desert edge.

*

*This reduces the amount of nutrient available in the sand for plants to absorb, preventing dune fixation by fast but shallow cover plants.

*this also limits moisture release by decaying biologicals.

A: It's part of the life-cycle of the sandworms.  In their initial stage, they are small sandtrout.  These sandtrout work together to isolate any water in the environment, which they then mix with.  This results in a subsurface pre-spice mass.  Eventually, this pre-spice mass builds enough pressure to erupt out of the ground as a spice blow.  Any sandtrout that survive the eruption then combine to form small, young sandworms.
Due to this, any environment with sandtrout present will eventually become desert as the moisture is removed from the ground and thus the environment at large.  Precipitation will enter the ground, then be converted to the pre-spice mass, interrupting the water cycle and preventing water from evaporating and re-entering the atmosphere to precipitate again.  This suppresses the amount of precipitation, leading to desert conditions.  As the number of sandworms and sandtrout increase, the desert will spread.
More information can be found at the Dune wikia.

A: When climate becomes very dry, most of the vegetation dies out.  As a result, the soil will dry up and get blown away by wind as grains of sand, without plants to fix it with their roots.  Forest-covered hills or mountains will be stripped to the bare rock.  Then more sand will be created by wind erosion: particles carried by wind would grind against rock, making more particles.
In short, if you remove moisture from an ecosystem, you will get a lot of sand.  That's what happened to the Sahara and to Australia.

A: The sandtrout, which is the larval stage of the worms, encase any source of water or moisture they can find as part of the conversion to pre-spice mass.  The process of walling off moisture removes it from the ecosystem, resulting in desert conditions.
The more sandworms there are, the more sandtrout.  The more sandtrout, the less moisture is in the ecosystem, which results in more arid (desert) regions.
In addition to the climactic impact, it seems likely that the abrasion of worms moving through ground would contribute to grinding rock and dirt into finer particles, resulting in faster development of sandy desert conditions.


text:
Q: Using future simple instead of future perfect Is it correct to say:

I will finish my work before you come back.

Or should I use future perfect:

I will have finished my work by the time you come back.

and are the two sentences same in meaning?

A: Both constructions are valid but they look at the completion of your work from different time perspectives.
The first example looks forward to the completion of your work.
In the second example, you are writing from the perspective of someone who has completed the task. You are looking back on a future event.
We often use this latter construction when we are impatient for the arrival of a future event, especially when we are going through a tough period in the meanwhile.
This time next week, I will have finished my studies.
In just a few months' time I will have qualified as a doctor.
Just two more days and I will have been discharged from hospital.
Another week and I will have completed my military service.


text:
Q: Setting a navigation bar selected menu item id from page title with jQuery http://jsfiddle.net/EAN5K/
<!DOCTYPE html>

<title>Education</title>

Education

Fast Cash

I am looking for a way to set the id of the parent .menuitem if .menutext value is equal to the title of the page. At the top there is a link to jsFiddle.
Thanks in advance...

A: Something like this will do it:
$("div.menuText").filter(function(i,el){
   return $.trim($(this).text()) === title;
}).parent()
.prop("id","someIdValue");

That is, filter all the .menuText divs to find the one with the matching text, then get its parent, then set the id.
Demo: http://jsbin.com/eqapih/1/edit
(I'm curious why you want to "set the id" though. If you want to highlight the menu that applies to the current page it would make more sense to add a "current" class to it.)


text:
Q: Typescript compiler as a service: how to test if one type is assignable to another? I'm making a command line nodejs tool that automates renaming symbols in Typescript files, using the Typescript language services.
You tell the tool: rename all symbols of this type to this symbol. Just like resharper, it will also rename local variables, properties, etc. Since it allows renaming multiple symbols at once, you can also swap two symbol names, without needing an intermediate temporary unique name (e.g. rename Foo to Bar and vice vesa).
I had to make the private function getSymbolInfoAtPosition in the language service public to make this work, so that I can get PullSymbol information
Currently it only detects exact name+type matches, by calling getNameAndTypeName on the PullSymbol, but I would like to perform structurally compatible matches.
In C#, this is easy, since a Type has an IsAssignableFrom method.
Does anyone know how the Typescript compiler-as-a-service can be used to detect if one PullSymbol is structurally compatible with another PullSymbol?
Thanks a lot,
Peter Verswyvelen

A: Basically, it doesn't look like you comprehensively check if one type if assignable another via reflection alone. The functionality to check if one type is assignable to another is already implemented in typescript, its just not exposed publicly and there is no real way to get at it without altering the typescript library manually.
One immediate workaround would be to effectively compile ad-hoc code to assign one to the other and see if there are compile errors.
The response to my request to expose isTypeAssignableTo has been favorable, so hopefully the answer will change in the near term.
[Update] it looks like it did eventually get exposed in a merge... I've not tried it though: https://github.com/microsoft/TypeScript/pull/33263/files#diff-c3ed224e4daa84352f7f1abcd23e8ccaR525-R527

A: I'm not sure what a direct comparison to the C# isAssignableFrom method would be, but perhaps you could write your own logic to create that function -
isAssignableFrom(pullSymbol): boolean {
    ....
    if (typeof pullSymbol === 'string') {
        // Is compatible with any type that allows strings
    }
    ....
}

You can read on some of the language specifications here to find things like:
The Any type is a supertype of all types, and is assignable to and from all types.
Using that information with some hard-coded logic may be a solution for you.


text:
Q: cutree не делит на кластеры Используя команду cutree, данные не делятся на кластеры, хотя на дендрограмме видно что делить есть что.

A: Функция cutree возвращает вектор с номером группы. Эти группы соответствуют веткам, выделенным красными прямоугольниками на дендрограмме.
Для примера используем данные USArrests.
# Загрузка пакетов
library(tibble)
library(dplyr)
library(tidyr)
library(ggdendro)
library(ggplot2)

# Подготовка данных
x <- USArrests %>%
    as_tibble() %>%
    rownames_to_column("State")

# Иерархический кластерный анализ
hc <- x %>%
    select_if(is.numeric) %>%
    scale() %>%
    dist() %>%
    hclust()

# Добавление меток
hc$labels <- x$State[hc$order]

# Дендрограмма
plot(hc)
rect.hclust(hc, k = 4)

Теперь продемонстрируем, что выделенные с помощью cutree группы соответствуют графику выше.
# Добавление выделенных групп в исходные данным
groups <- hc %>%
    cutree(k = 4) %>%
    as.data.frame() %>%
    rownames_to_column("State") %>%
    setNames(c("State", "Group")) %>%
    mutate(Group = as.factor(Group))
x <- inner_join(x, groups)

# Подготовка данных
dendr_data <- dendro_data(hc, type = "rectangle")
labs <- label(dendr_data)
labs <- inner_join(labs, groups, by = c("label" = "State"))

# Дендрограмма с подсветкой выделенных групп
ggplot() +
    geom_segment(data = segment(dendr_data),
                 mapping = aes(x = x, y = y, xend = xend, yend = yend)) +
    geom_text(data = labs,
              mapping = aes(label = label, x = x, y = 0, colour = Group),
              angle = 90, vjust = 0, hjust = 0)


text:
Q: Intermediate Value Property Justification I am working on showing the Intermediate Value Property holds for a certain function. I noticed the one page on here talks about this idea, but I can not follow with what they are trying to say. [The problem is posted below - Ed.] . Any guidance would be appreciated. I just am very unsure what the property says.

A: You should prove it for any interval $[a,b]$.
For any interval not containing $0$, $f(x)$ is continous on that interval and thus satisfies IVP. So you only have to consider the case where $a\leq 0 \leq b$.
Hint: $f(x)$ oscillates $\textbf{a lot}$ as you approach zero from either side.

A: So if you believe the intermediate value theorem, then you know that if $x_1, x_2 > 0$ or $x_1, x_2 < 0$, the property follows. So suppose $x_1 \leq 0 < x_2$. It's enough to show that there exists $c \in (0, x_1)$. To do this, consider the sequence $$(t_n)_{n \in \mathbb{n}} = \left( \frac{1}{ 2 \pi n + \arcsin (k) } \right)_{n \in \mathbb{N}} ,$$ along which $f(t_n) = k$. Let $n = \lceil 2 \pi n / x_2 \rceil + 1$. Then $t_n = \frac{1}{ 2 \pi n + \arcsin (k) } \leq \frac{1}{ 2 \pi (n - 1) } \leq x_2$.