Preciso modificar o css de um radio button md-radio-button via jQuery

Question: Colegas, estou tentando modificar o css de um md-radio-button via jQuery porém não estou conseguindo.
<md-radio-button id="radio_letter" style="margin: 2px!important" ng-click="changeCorrectAlternative(command.key, alternative.key)" ng-repeat="alternative in command.alternative_set" ng-value="alternative.key">
    <md-item style="margin:-21px;text-align:center;">
        {{ ORDER_TO_LETTER[alternative.order-1] }}
    </md-item>
</md-radio-button>

Jquery
jQuery(document).ready(function () {
    jQuery('#radio_letter').each(function(){
        $(this).css('width','21px');
        $(this).css('height','21px');
    });
});

Alguma sugestão?
Comment: Por que exatamente você precisa mudar através de `jQuery`? Não pode ser feito direto com uma classe `css` ?
Comment: Pode postar o Controller do angular ?
Answer: Voce pode tentar chamar o seu jquery pela diretiva ng-init. Se não funcionar, faça uma chamada a sua função JQuery de dentro do controller utilizando o serviço $window e $timeout
Cria uma funçã ode ajuste no escopo global (window)
function adjust() {
      jQuery('#radio_letter').css({ 'width':'21px', 'height':'21px'});
});

Tente:
<md-radio-button ng-init="window.adjust()" ...

Ou pelo Controller:
app.controller('MeuController', function($window, $timeout) {
     $timeout($window.adjust, 50);
});

Comment: Valeu Rogério Foi de prima. Funcionou que foi uma blz ! obrigado


problem metric involving sequences

Question:
UPDATED: In preparation for an exam I am struggling with the following problem. We have $A:=\{x=(x_{n})_{n}\in \ell^{2}| \phantom{x} \|x\|\leq 1\}$. Consider the metric $d:A\times A \rightarrow \mathbb{R}_{+}$ defined by
  $$d(x,y)=\sum_{n=1}^{\infty}(1/3)^{n}|x_{n}-y_{n}|.$$
  Prove that $(A,d)$ is sequentially compact.

What I have done so far:
I have updated what I have done so far using the hints below. But I still have some questions as I want to make sure I understand it thorougly.
Let $(x_{n})_{n}$ be an arbitrarily chosen sequence in $A$. Now first take a subsequence $(x_{n1})_{n}$ such that the first component converges. Now take a subsequence of this subsequence $(x_{n2})_{n}$ such that the second component converges.
Going on in the same way we get a sequence of nested subsequences $(x_{n(k+1)})_{n}\subset (x_{nk})_{n}$. Now take the sequence $(x_{kk})_{k}$, this construction guarantees that every component of this sequence converges, it is equivalent to the convergence in the metric. Also note that for each $k,n$ that $x_{nk}$ is a sequence of real numbers so we have in fact three layers of sequences. Since the elements are sequences and we take sequences of these elements and than a sequence of subsequences of the sequence of elements in $A$. Hence, $(A,d)$ is sequentially compact.
(Question: Have I now formally proved that indeed $(A,d)$ is sequentially compact)
I don't have much experience with these kind of proofs so any help is much appreciated.
Comment: Made updates using the hints below.
Comment: You need to use an indexed subscript to keep track of the various subsequences to get it totally right. Something like this: The first subsequence is given by indices $n_{j1}$ so that $x_{n_{j1}}1$ converges as $j\to\infty$. The next one will be given by $n_{j2}$ being a subsequence of $(n_{j1})$ so that $x_{n_{j2}2}$ converges, and so forth. You may prefer to write $y_{jk}=x_{n_{jk}k}$ instead, so that $(y_{j(k+1)})_j$ is a subsequence of $(y_{jk})_j$, then take the diagonal $y_{jj}$. This awful mess is the reason I wrote the note I refer to in my answer.
Answer: (Note: The question was substantially altered since I wrote this answer. If you wish to see what I really answered, use the history mechanism to see the original question.)
You got it wrong from the start. Let's drop the comma and just write $x_n=(x_{nj})_j$, shall we? Now you want convergence in the first component, so you'd like to have $x_{n1}$ convergent as $n\to\infty$. It won't be convergent necessarily, but you can pick a subsequence that converges. Note that this really means picking a subsequence of $(x_n)$ so that $(x_{n1})$ converges. Next, pick a subsequence of the subsequence so that $(x_{n2})$ converges, and so on. Finally, "take the diagonal" to finish the proof.
Incidentally, I think the conventional notation for subsequences is a horrible mess, and makes this kind of proof much harder than necessary, both to write and to read. So I have written up an alternative view of the diagonal method. The basic idea: All the difficulties stem from the insistence of relabeling indices when taking a subsequence, so that the sequence is always indexed on the set of natural numbers. By allowing subsets of the natural numbers as index sets, we simplify this tremendeously.
Comment: Thank you very much for your help. I have updated my question using your hints and I want to make sure that I understand it thoroughly so if you could give me feedback if I have now really finished the proof I would really appreciate it.
Comment: Much better. Unfortunately, I don't have time for a detailed reading right now. I think you have the right idea, but your notation at the end still seems somewhat deficient. (It is *notoriously* hard to get right, so don't feel bad about it.) I'll add a comment to the question with a bit more detail.
Comment: Thank you. I look forward to your comment.
Answer: You need to show something that's bounded with respect to the $d$ metric has a convergent subsequence, not that something that's bounded with respect to the normal $l^2$ norm has a convergent subsequence.

problem metric involving sequences


Script expression to get part of a string?

Question: I'm using the bash shell in CentOS, version ...
$ uname -a
Linux mydomain.com 3.2.29-48.63.amzn1.x86_64 #1 SMP Sat Sep 15 01:43:12 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux

In my shell script, I want to get part of a string, specifically, everything before the last dash ("-").  So if my string is "my-importer-1.0.ear," I want to extract "my-importer".  However, the expression below
prefix=${fname%-*}

is only returning "my", because its matching against the first dash.  How can I adjust the expression to match everything up until the last dash?
Comment: Use sed instead?  `echo my-importer-1.0.ear | sed -re 's/^(.*)-.*$/\1/'`
Answer: Are you sure you're not using %% which deletes the longest match from the end of the string and thus gives you my whereas a % deletes the shortest match and provides (for you example) what you want
fname=my-importer-1.0.ear
echo ${fname%%-*}
my

whereas
echo ${fname%-*}
my-importer


parse output of script/utils-linux into human-readable form

Question: How do I parse the output of script/utils-linux  into human-readable form
or into something I can process with regexps?
There are some binary escape sequences used to display colours etc.
Is there a unix tool to record the text console (e.g. gnu screen)
in a human-readable form with milliseconds timings ?
ttyrec/ttyplay uses a rather unreadable format I was not able to find
proper documentation for; the screen function logstamp creates a
somewhat more readable log but is unable to give precise timings, only
up to a second.
Answer: You want the script command.
Comment: Thanks!  One more question: it seems to use escape sequences/codes, how do I know what these mean? Is there some standard?
Comment: @John, those are probably coming from GNU Screen, not `script`  From the `script` man page, "Certain interactive commands, such as vi(1), create garbage in the typescript file. Script works best with commands that do not manipulate the screen"
Answer: you can easily parese ttyrec with something like that: https://github.com/antono/shelr/blob/master/lib/shelr/ttyrec.rb
If you want to just share your terminal there is http://shelr.tv/ with corresponding utility: https://github.com/antono/shelr
If you want strip escape sequences you can do it with following command:
sed -r "s/\x1B[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"


How do I create a php page that has access to the Drupal API?

Question: I would like to create a PHP page that executes Drupal API functions.
The page would be inside my Drupal 7 website, perhaps the theme directory, but I'm not sure where it should reside.
I would like this page to run a query to the database using the Drupal's database abstraction layer. Once the query is retrieved, I would like to run some other D7 API functions and finally print out a page.
The page should not be one of the default Drupal templates, but a new page, that simply has one single  within it.
How can I achieve this?
EDIT: The correct way to do this is to implement hook_menu() inside a module. I'm trying to do this, but my approach doesn't work. This is what I'm doing:

the profileBox.info file

name = PB
description = "Creates a callback to returnuid.tpl.php"
package = SDNN
core = 7.x
files[] = profileBox.module

the profileBox.module file is installed and has the following code:

function profileBox_menu() {
  $items['returnunid'] = array(
    'title'=>'Example'
    'description'=>'examples'
    'page callback' => 'profileBoxGetit',
    'access callback'=>TRUE,
  );

  return $items;
}

function profileBoxGetit() {
  $stringit = "the string output";

  return $stringit;
}

I created a returnuid.tpl.php file with some html code in it - just to test (not functional code)
I then pointed my browser to [root]/?q=returnuid
I expected to get the content of the $stringit variable, but I instead got an "access denied" error

This module actually messes up the Administration menu, which dissapears when the module is installed.
What am I doing wrong?
Comment: You should not update your question too add further issue while dealing with the early answer. Ask new questions instead. Otherwise, it makes the original questions and answer useless to others.
Comment: Also a few other hints: 1. You do not need to add the .module file to files[], only files which contain php classes. 2. Use a lower case name for your module, e.g. "profilebox". Otherwise, update_N hooks will not work.
Comment: I've deleted my answer because it answered only the original question, and it was a really bad idea :) Glad to see you've rephrased this.
Answer: The correct way to "create a PHP page that executes Drupal API functions" is to create a module.
In that module, you implement hook_menu() which allows you to tell Drupal that it should call a given php function for a specific path, for example 'yourmodule/somepath'. Inside that, you can then execute whatever PHP and Drupal API functions which you want.
See http://drupal.org/node/1074360 for more information.
Comment: Your hook menu implementation is incomplete. You need to either set a permission with `'access arguments' => array('permission name')` (which you can define with hook_permission() if you want your own) or set `'access callback' => TRUE` to allow access to everyone. Also, you need to define a title or set the type to MENU_CALLBACK if you don't want to have it visible in the menu.
Comment: When you say "Administration menu", do you mean the black bar provided by http://drupal.org/project/admin_menu? If not: what do you mean? If yes: check if your page has valid HTML code and if there are any javascript errors on the page.
Comment: you're right, the correct way should be hook_menu(). can you take a look at my edit above?
Comment: yes. this work, but it makes my administration menu dissapear. any idea why?
Comment: I'm back, I had to get some sleep :)  No, the admin menu provided by Drupal works fine. What I mean is the contrib module called administration menu (http://drupal.org/project/admin_menu). This menu dissapears when my module is on. I checked all the code and it seems ok. any ideas?
Answer: Another approach is to create standalone file, just like index.php, and perform drupal bootstrap there. For example:
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
/**
Write your code here
use PHP core, drupal core and contrib functions
**/

Comment: There are reasons to do this, but in most cases, this isn't a good idea. You should extend Drupal with modules, not standalone files. A possible exception for example is providing a faster callback for  ajax calls and avoiding the full drupal bootstrap.
Comment: I have some php files including the drupal_bootstrap. I wonder how to register these php files to Drupal using hook_menu. I want to add one of those files as a tab on the user page.


How to show a view with 2 columns on the front page?

Question: I need in the front page on my website to show a view with two columns : the left column will show the two latest content from a category, and the same for the right column.
How can I achieve this?
Answer: There are many ways to do this:

Create a block for each of your views, then add the blocks to the
content area and select to show on front only (all done via block
UI), and set it side by side via CSS.
Create a content type for the front page. Then create a new instance
of that content type. Run it through panels and choose two column
layout, then add views of your liking to the left and right panel.
Create a content type for the front page. Manage the display of this
content type via Display Suite and use two column layout. Add a
dynamic field for each of the left and right columns, and set the
dynamic field to display a view of your liking.
Implement hook_menu_alter for the front page in a custom module.
Return the output of 2 views_embed_view() calls wrapped in HTML for
the columns, or in a render array that will suit your layout.
Create a content type for the front page or use an existing type.
Then create a new instance of that content type. Note the path of
this content (node/ID). In configuration - site information, set it
as the front page. Edit this content type's body element, and using
the PHP filter embed the views with calls to views_embed_view().

Methods 2 and 3 are in my opinion preferable, with method 5 the least preferable method. Method 1 is perhaps the easiest.


Joining 2 tables is not working correctly

Question: Idk what i am doing wrong.I am still new to php and mysqli and wanted to know what I am doing wrong.What I have on my 1st list are name of the food,description and what kind of food they are.On my 2nd list I have the ratings of the foods.
TableImg
So lets say for example I click on korean food all the foods with the cuisine_type = korean will be displayed on my page. When mysqli_fetch_array($query_type) it displays kimchi and ribs but when i replace $query_fetch it only displays the first one which is kimchi.My goal is to get all the food from cuisine_type display correctly and their ratings attached to them.
    <?php
    if(isset($_GET['type'])){

      $type = (string)$_GET['type'];
       }

 (Displays only 1 of them)->  $query_fetch = mysqli_query($connect,"SELECT
         cuisine.*,AVG(ratings.cuisine_rating) AS rt FROM cuisine
        LEFT JOIN ratings ON cuisine.dish_name = ratings.cuisine_name WHERE
        cuisine_type = '$type'");

 (Displays everything)->  $query_type = mysqli_query($connect,"SELECT * FROM cuisine WHERE
       cuisine_fetch ='$type'");

       while($show = mysqli_fetch_array($query_type)){
        echo "

".$show['dish_name']."

".$show['text']."

";

      }
?>

Answer: Assuming the TableImg is correct, you're not using the same names in the query as in the db.
SELECT
  cuisine.*,
  AVG(ratings.cuisine_rating) AS rt
FROM cuisine
LEFT JOIN ratings ON
  cuisine.dish_name = ratings.cuisine_name
WHERE
  cuisine_type = '$type'

Use this instead:
SELECT
  cuisine.*,
  AVG(ratings.Rating) AS rt
FROM cuisine
LEFT JOIN ratings ON
  cuisine.dish_name = ratings.dish_name
WHERE
  cuisine_type = '$type'

Comment: its still the same result
Comment: It's not a naming issue here Jorge
Answer: What you want is to do your average using GROUPing.
SELECT c.*, avg(r.rating) AS rt FROM cuisine c
LEFT JOIN ratings r
ON c.dish_name = r.dish_name
WHERE c.cuisine_type = 'korean'
GROUP BY dish_name

The code can be tested via SQLFiddle.
You will need to replace where i hard coded korean with your php variable to make it work in your system.

The issue you had was you didn't specify how to group your rows, this caused the server to put them into all one group. Most DBMS would have errored when you tried to select columns not in the grouping (which was no columns) without an aggregate (like avg), though it appears yours does not, it allows you to group this way and simply return the first row for every non aggregate.
NOTE you still may need some kind of null handling for avg(r.rating), since Korean Ribs has no ratings, it will return an average rating of NULL. You can handle this by using IFNULL like this: IFNULL(avg(r.rating),2.5) AS rt. I would suggest using maybe 2.5 if rating is out of 5, so your no rating is the middle number, though you can use 0 or 5 or anything.


what is Valgrind error overlap in strcpy?

Question: I am facing this error I never have faced using valgrind do you guys have any input. I am new to C and still learning. Thank you!
This is below the error I got using valgrind.
==8410== Source and destination overlap in strcpy(0xfff000560, 0xfff000560)
==8410==    at 0x4C2E272: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8410==    by 0x40126B: trim (in /********/********/********/private/********/********/********/calls)
==8410==    by 0x40154B: main (in /********/********/********/private/********/********/********/calls)
==8410==
==8410== Source and destination overlap in strcpy(0xfff000560, 0xfff000560)
==8410==    at 0x4C2E272: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8410==    by 0x40126B: trim (in /********/********/********/private/********/********/********/calls)
==8410==    by 0x4016C6: main (in /********/********/********/private/********/********/********/calls)
==8410==
==8410==
==8410== HEAP SUMMARY:
==8410==     in use at exit: 0 bytes in 0 blocks
==8410==   total heap usage: 30 allocs, 30 frees, 1,288 bytes allocated
==8410==
==8410== All heap blocks were freed -- no leaks are possible
==8410== For counts of detected and suppressed errors, rerun with: -v
==8410== ERROR SUMMARY: 19 errors from 2 contexts (suppressed: 0 from 0)

my method
static char *trim(char *s)
{
    int i;
    for (i = 0; isspace(s[i]); i++)    // skip leading
        ;
    int from = i;    // start here

    for (; s[i]; i++)    // move until end
        ;

    // move backwards, skip trailing
    for (i--; i>from && isspace(s[i]); i--)
        ;
    s[i+1] = '\0';    // stop here

    strcpy(s, &s[from]);    // copy this part to beginning

    return s;
}

Comment: Well, `s` and `s[from]` are obviously overlapping. This is not allowed. This is explicitly stated in `strcpy` documentation.
Comment: You have a comment `// (it is ok as we copy from higher to upper addresses always)` — that is incorrect.  If the source and destination strings overlap, the behaviour is undefined and that's what Valgrind is telling you.  Using `memmove()`, you have to say how many characters to copy — that's the third argument you're missing.
Comment: @Leo Use memmove instead of strcpy.
Comment: @VladfromMoscow will it do the same job as copying?
Comment: @VladfromMoscow I am getting too few arguments changing to memmove
Comment: @JonathanLeffler I see thank you
Comment: @Leo: You should revert the edit, since it's covering up the error that was the source of your question to begin with. Edits are not to revise your code once you fix it, but to revise the question if the original was unclear.
Answer: Changed this line
strcpy(s, &s[from]);

To
                    //# of characters
memmove(s, &s[from], i - from + 1);

Comment: Wikiquotes on [Donald Knuth](https://en.wikiquote.org/wiki/Donald_Knuth) says: _Beware of bugs in the above code; I have only proved it correct, not tried it._ It's even the first item in the list of quotes, @ZanLynx.
Comment: I think I'd expect to see `memmove(s, &s[from], strlen(&s[from]) + 1);` so that the length is calculated correctly and the terminal null byte is copied too (`strlen()` doesn't count the terminal null byte).
Comment: Yes, I agree — the value needed is already available (and I didn't notice that when scanning).  Two brilliant people both coming up with `i - from + 1` suggests that might be correct :D
Comment: @JonathanLeffler As Knuth wrote somewhere, paraphrased, I wrote this code but I didn't test it. Heh.
Comment: In this context, we think (but haven't formally verified) that using `i - from + 1` in place of `strlen(&s[from]) + 1` would be correct and (marginally) quicker than calling `strlen()`.  Double-check by experimenting.  If you're dealing with a 20 kilobyte string with a couple of kilobytes of trailing white space, the results might be different from what you get from dealing with a 20 byte string.
Comment: So far I have tested 4 test cases with 4 different file inputs all worked with `i - from + 1` with no errors or any other issues
Comment: This answer would be a lot better if it explained *why* the suggested change is necessary.
Comment: @JonathanLeffler oh thank you I wasn't sure about that
Comment: @JonathanLeffler that would be more dynamic than what I have put as well right?
Comment: Yes: it would work correctly for different lengths of strings, neither overrunning short strings nor omitting key portions of long strings.  Note that `memcpy()` has a 'no overlap' restriction; only `memmove()` works correctly for overlapping data.
Comment: You don't need `strlen`. You already calculated that using `i`.
Comment: @ZanLynx — you read the rest of the code; I just looked at what it would take to get `memmove()` to work correctly.  I see that `i = strlren(&s[from]);` is written out in a loop in the function (`for (;s[i];i++);`).  But `i` is then decremented as trailing white space is removed too.  I think you'd need to use `i - from + 1` as the length; there could still be an off-by-one error here.
Comment: @JonathanLeffler It just bugs me to call a function to get a value the code is already holding... It would be something like `(i - from + 1)` I think.
Comment: so its best to use `i - from + 1` ?


solve the equation $(x-1)\frac{d^2y}{dx^2}-x\frac{dy}{dx}+y=(x-1)^2$.

Question: solve the equation $(x-1)\frac{d^2y}{dx^2}-x\frac{dy}{dx}+y=(x-1)^2$ given that $x$ and $e^x$ are the particular integrals of the equation without the right hand member.
What is the right hand member here?
$(x-1)\frac{d^2y}{dx^2}-x\frac{dy}{dx}+y=(x-1)^2$
Comment: I think the problem is saying those are the solutions of the homogeneous equation $(x-1)y''-xy'+y=0$
Answer: It means that $x$ and $e^x$ are solutions of the homogeneous associated equation:
$$(x-1)\frac{d^2y}{dx^2}-x\frac{dy}{dx}+y=0 $$
The right hand side is $(x-1)^2$
Answer: Divide both sides of this equation by $x-1$:
$$y''-\frac{x}{x-1} y' + \frac{1}{x-1} y = x-1$$
The right-hand side is $x-1$.
Multiply through by $e^{-x}/(x-1)$.  This is an integrating factor which puts the equation in a Sturm-Liouville form:
$$\frac{d}{dx} \left [\frac{e^{-x}}{x-1} y'\right] + \frac{e^{-x}}{(x-1)^2} y = e^{-x}$$
Comment: is there a step wise process to solve this.
Comment: Actually, not really in this form.  I thought it more useful to see the solutions of the homogeneous equation more clearly.  In general, SL form is more useful for solving when the equation is homogeoneous and is used to find eigenvalues of the differential operator defined by the left hand side.  See http://en.wikipedia.org/wiki/Sturm%E2%80%93Liouville_theory if you are interested.
Comment: @ rlgordonma: thanks !!
Answer: Just solve it by variation of parameters.
$y_1=x$ , $y_2=e^x$
The Wronskian of these two functions is $\begin{vmatrix}x&e^x\\1&e^x\end{vmatrix}=(x-1)e^x$
$\therefore y=C_1x+C_2e^x-x\int\dfrac{1}{(x-1)e^x}e^x(x-1)~dx+e^x\int\dfrac{1}{(x-1)e^x}x(x-1)~dx=C_1x+C_2e^x-x\int~dx+e^x\int xe^{-x}~dx=C_1x+C_2e^x-x^2-e^x\int x~d(e^{-x})=C_1x+C_2e^x-x^2-x+e^x\int e^{-x}~dx=C_1x+C_2e^x-x^2-1$


ZFS permission error 'cannot set property' when receiving snapshot from remote machine despite delegated permission

Question: Context
I'm setting up ZFS autobackup on my home server for offsite backups. All commands printed below are run as non-root.
Problem
A 'permission denied' error arises originating from the target machine when the following command is issued:
(zfs send --large-block --embed --raw --verbose --parsable --props \
 -i @previous_snap localpool/mydataset@newest_snap) | \
(ssh ostsite 'zfs recv -u -o canmount=noauto -v -s \
remotepool/myserver/localpool/mydataset')

Full command output:
incremental localpool/mydataset@previous_snap   localpool/mydataset@newest_snap 624
size    624
receiving incremental stream of localpool/mydataset@newest_snap into     remotepool/myserver/localpool/mydataset@newest_snap
received 1.31K stream in 1 seconds (1.31K/sec)
cannot set property for 'remotepool/myserver/localpool/mydataset': permission denied

Findings so far
ZFS doesn't explicitly say which property cannot be set, but the only one I'm requesting to be set is canmount=noauto. On the target machine, I've delegated some zfs permissions to the receiving user:
sudo zfs allow myuser snapshot,receive,create,mountpoint,mount,userprop remotepool/myserver

And when I manually execute zfs set canmount=noauto remotepool/myserver/localpool/mydataset, this succeeds.
Questions

How can I see which property cannot be set?
How can I allow this property to be set (at recv-time)?

EDIT
It was unrelated to the canmount property -- that was being set fine (as long as you've zfs-allowed it). Instead, I was missing the keylocation delegation. This is required because sending with --raw doesn't de/re-encrypt and therefore wants to change the keylocation to prompt upon arrival.
In addition, but this is purely a zfs-autobackup thing, I was missing the hold and release delegations.
Comment: *And when I manually execute `zfs set canmount=noauto remotepool/myserver/localpool/mydataset`, this succeeds.*  Are you running that as `root`, or as a normal user?  What user are you using to send/receive the snapshots?
Comment: @AndrewHenle I've updated the question. the `zfs set` command succeeds as a regular user. The send and receive commands are also issued by regular users.
Comment: I'm pretty sure that low level filesystem operations require root or at least specific elevated rights.
Comment: @paladin hmm. But then I'm confused as to why it works when I manually execute `zfs set canmount ...` (as a regular user with appropriate zfs delegation).
Answer: It was unrelated to the canmount property -- that was being set fine (as long as you've zfs-allowed it). Instead, I was missing the keylocation delegation. This is required because sending with --raw doesn't de/re-encrypt and therefore wants to change the keylocation to "prompt" upon arrival.
In addition, but this is purely a zfs-autobackup thing, I was missing the hold and release delegations.


How to get automatically sized columns when using tablesorter theme

Question: I have a simple web application that uses jQuery (v1.12.4) and the tablesorter plugin (v2.28.15).
On one page of the application I am displaying an HTML table that contains two columns where the content is not particularly wide.
If I do NOT specify a tablesorter theme, the table displays as I expect (and desire) with the two columns sized to fit the data that they contain.
However, if I do specify a tablesorter theme, the table width is fixed at the width of the browser window and each column gets half of that space.  The result is usually unnaturally wide columns that are hard to read because the text is too far apart.
I have sniffed through the tablesorter github documentation and not found anything on point.
I have experimented with different tablesorter themes and see the same behavior with each.
Is there a way to get sized-to-fit columns while using a tablesorter theme?
Sample code:
<!DOCTYPE html>

    <link rel="stylesheet" href="jQuery/tablesorter-master/css/theme.blue.css">

                Column1
                Column2

                r1c1
                r1c2

                r2c1
                r2c2

                r3c1
                r3c2

Answer: Each theme sets the table width to 100%. This expands the table to fit its parent container and the browser automatically adjusts the column widths.
To override this, do one of the following:

Remove the width: 100% definition from the selected theme.
Add a table.tablesorter { width: auto; } definition to override the behavior (demo)
Define the column widths in the HTML (demo)
Numeric
Animals

Define the column widths for each column using header class names or use the css :nth-child() selector (demo)
Numeric

/* Numeric column */
.numbers { width: 50px; }
/* Animals column */
table th:nth-child(3) { width: 50px; }

Comment: I went with option two.  I added table.tablesorter {
    width: auto;
} to my application's global css file.  Worked great.Thanks @Mottie!


Deixar itens ao lado no mobile com bootstrap 4

Question: Preciso deixar os seguintes itens um ao lado do outro como é o no desktop.
Como é no desktop

Como esta no mobile

Preciso que ele tenha o mesmo comportamento no mobile e no desktop para estes itens.

xxx

xxx

xxx

Answer: Nesse caso basta vc não declarar o bracking point do grid na classe, por exemplo, não coloque na div col-md-4, coloque apenas col-4, assim ele sempre ocupara 1/3 da largura, mesmo em telas pequenas como de celulares. Link da documentação oficial do Grid do BS4 que fala sobre esse tipo de uso

  <link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
  <link rel="stylesheet" type="text/css" media="screen" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" />

xxx

xxx

xxx

Comment: Isso mesmo valeu.


ftplib MLSD command gives 500 Unknown command

Question: I have been using ls = f.mlsd() to get list of files and timestamp from ftp but it gives me
ftplib.error_perm: 500 Unknown command

Is there any problem with ftp server? do i need to install anything on the server to get this command working
Answer: In the fact, MLSD is nothing but a protocol extension introduced in RFC 3659 that may be not supported by some FTP servers. If you care about portability, it's better to use f.nlst() instead.
If changing something on server is acceptable for you, then I suggest you switching to proftpd which has MLSD support as a part of it's mod_facts extension.
Comment: Thanks i have switched to proftpd with mod_facts extension and MLSD command works fine now
Answer: MLSD command was not a part of an original FTP standard. It was added only later in RFC 3659, in 2007. While that's still quite some time ago, even now some major FTP servers do not support it. Particularly IIS and vsftpd.
If you need timestamps and yet you need to talk to a server that does not support MLSD command, you have two options:

Use FTP.dir (LIST command). And parse proprietary format of file listing to retrieve the timestamps.

Use FTP.nlst to retrieve a list of files (and folders). Then, use FTP.voidcmd to send MDTM command for each of the listed files. MDTM returns a file timestamp in a standardized format.
Obviously this is a way less effective than the previous approach, but you won't have to deal with a proprietary formats of directory listings.
Note that MDTM is not supported by all FTP servers either, but it is more widely supported than MLSD, although both commands come from the same RFC (3659). Particularly one of common Linux FTP servers, vsftpd, supports MDTM, but not MLSD.

For a code to implement both approaches see my answer to:
How to get FTP file's modify time using Python ftplib
Comment: I have switched to proftpd and enabled mod_facts and MLSD command works fine now


Importação .txt para MySQL - valores entre strings

Question: Tenho um arquivo TXT que contém diversos registros diferentes, em alguns casos preciso pegar as informações que estão entre 2 strings, ex: Cliente: FULANO DE TAL CPF: preciso do que esta entre Cliente: e CPF:.
Em outras partes do mesmo documento preciso pegar os primeiros 12 caracteres de uma linha após a string Tipo_OS: caso exista alguma informação após o Tipo_OS: e antes de outra string também fixa no documento, pois pode ou não existir dados entre essas strings.
Obs. não tenho um caracter separador padrão para gerar minhas arrays, poderia utilizar o :, porém alguns dados não estão após o : e sim na linha abaixo ou ainda após outros dados da linha abaixo.
Sei que parece meio confuso, porém o que já consegui foi o seguinte:
encontrei uma função na internet que me permite pegar valores entre 2 strings.
function GetBetween($var1="",$var2="",$pool){

    $temp1 = strpos($pool,$var1)+strlen($var1);
    $result = substr($pool,$temp1,strlen($pool));
    $dd=strpos($result,$var2);
    if($dd == 0){
        $dd = strlen($result);
    }
    return substr($result,0,$dd);
}

Até é funcional, porém no echo continua aparecendo os outros dados do documento excluindo a exibição somente a string que defini como inicial e final.
Inicialmente o que preciso seria o seguinte, encontrar um valor entre 2 strings e exibir somente ele, porém quero definir varios valores entre 2 strings até capturar todas informações dessa Ordem de serviço, após eu capturar tudo eu necessite rodar um while para verificar se existem mais coisas nas próximas páginas, montando assim meu banco de dados com as ordens de serviços contidas nesse documento. Toda vez que o documento ler Cliente: ele identificar que é o começo de um novo registro.
Comment: Pode colocar um exemplo do ficheiro `.txt`?
Comment: Nesse modelo abaixo, são 3 Ordem de Serviço.
Comment: Excedeu o tamanho, vou colocar somente 2 registros
Comment: vou upar o arquivo... não posso colar o arquivo todo.. excede o tamanho
Comment: Segue link do arquivo .txt no mediafire
Comment: https://www.mediafire.com/?1pvi6p2ag92sx7o
Comment: Conseguiu Visualizar Sergio?
Comment: Sabe porque criaram o xml e o json ?
Comment: Então Edilson, essa pergunta ficou meio sem nexo... Se tem alguma coisa a acrescentar para poder ajudar um brother com problemas fico agradecido!!!
Esse tipo de comentário não ajuda em nada...
Tem alguma coisa que posso fazer com Json ou XML que vai me ajudar na minha conversão do TXT para MYSQL???
Obrigado pela ajuda !!!
Answer: Isto vai dar-lhe algum trabalho e idealmente devia estar já numa base de dados.
Aqui fica uma ajuda usando RegEx. Expressões regulares podem ser muito úteis neste tipo de situação. Dê uma olhada a esta regex que fiz para o seu caso.
Um exemplo online aqui (clique em 'execute code')
No fundo vai procurar todas as ocorrências e gerar um array com o que encontrar. Você só tem de defenir os campos.
Alguns parametros relevantes da regex:
() - imdica uma captura, qua vai ser colhida pelo php
.* - qualquer coisa menos quebra de linhas
\s - quebra de linha
\s{1,} - uma ou mais quebras de linha
Assim esta regex,
$regex = '/Cliente:(.*)CPF\/C\.N\.P\.J\.:(.*)\sEndereço:(.*)CEP:(.*)\s{1,}Tel EBT:\s{1,}Tel Res:(.*)Tel Outros:(.*)Tel Comercial:(.*)/';
preg_match_all($regex, $txt, $dados);
var_dump($dados);

com a função preg_match_all do php deu-me isto:
{
[0] => array(
    3
)
    {
    [0] => string(210) "Cliente: FULANO DE TAL CPF/C.N.P.J.: 123456789123 Endereço: R RITA ALVES PEREIRA , 01 -CARAPICUIBA -CARAPICUIBA-SP CEP: 6365000 Tel EBT: Tel Res: 01141874187 Tel Outros: Tel Comercial: 011999999999 "[1] => string(205) "Cliente: OUTRO FULANO DE TAL CPF/C.N.P.J.: 00000000011 Endereço: R ANTONIO FL, 01 -VILA DIRCE -CARAPICUIBA-SP CEP: 6343000 Tel EBT: Tel Res: 01141464146 Tel Outros: Tel Comercial: 011999999999 "[2] => string(192) "Cliente: MAIS UM FULANO DE TAL CPF/C.N.P.J.: 00000000011 Endereço: R TIBIRICA, 00 -VILA DIRCE -CARAPICUIBA-SP CEP: 6335000 Tel EBT: Tel Res: 01141674167 Tel Outros: Tel Comercial: "
    }

[1] => array(
    3
)
    {
    [0] => string(15) " FULANO DE TAL "[1] => string(21) " OUTRO FULANO DE TAL "[2] => string(23) " MAIS UM FULANO DE TAL "
    }

[2] => array(
    3
)
    {
    [0] => string(15) " 123456789123 "[1] => string(14) " 00000000011 "[2] => string(14) " 00000000011 "
    }

[3] => array(
    3
)
    {
    [0] => string(56) " R RITA ALVES PEREIRA , 01 -CARAPICUIBA -CARAPICUIBA-SP "[1] => string(46) " R ANTONIO FL, 01 -VILA DIRCE -CARAPICUIBA-SP "[2] => string(44) " R TIBIRICA, 00 -VILA DIRCE -CARAPICUIBA-SP "
    }

[4] => array(
    3
)
    {
    [0] => string(10) " 6365000 "[1] => string(10) " 6343000 "[2] => string(10) " 6335000 "
    }

[5] => array(
    3
)
    {
    [0] => string(13) " 01141874187 "[1] => string(13) " 01141464146 "[2] => string(13) " 01141674167 "
    }

[6] => array(
    3
)
    {
    [0] => string(1) " "[1] => string(1) " "[2] => string(1) " "
    }

[7] => array(
    3
)
    {
    [0] => string(15) " 011999999999 "[1] => string(15) " 011999999999 "[2] => string(2) " "
    }
}

Comment: Obrigado pela resposta, vou fazer alguns testes, em relação a ja devia estar em uma base de dados, na verdade está, porem a unica forma de extrair e importar tais dados do atual banco de dados é por meio de um arquvo pdf, pdf esse que extrai o .txt em questão.
Comment: @Ðracø que base de dados usa?
Comment: Não tenho nem idéia, é um sistema da Claro, só temos acesso a exportação de um PDF.
Comment: Meu código ficou assim, retorna null no browser.. pode me ajudar...
Comment: $txtfile = file_get_contents('rotaclaro.txt');
$regex = 'Cliente:(.*)CPF\/C\.N\.P\.J\.:(.*)\sEndereço:(.*)CEP:(.*)\s{1,}Tel EBT:\s{1,}Tel Res:(.*)Tel Outros:(.*)Tel Comercial:(.*)\sTel Celular:(.*)Tel Fax:(.*)\sReferência(.*)\sSolicitação:(.*)Emissão:(.*)Node:(.*)\s{2,}Agendado para: (.{10}) (.*)OS Número:(.*)\sEQUIPE:(.*)PARCEIRO:(.*)\s{1,}Prepostos:(.*)Portabilidade:(.*)\s{1,}Contrato:(.*)Data de Habilitação:(.*)\s{1,}(.*)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)';
preg_match_all($regex, $txtfile, $dados);
var_dump($dados);
Comment: @Ðracø o seu problema agora está relacionado com encoding acho. Dê uma olhada aqui (http://pt.stackoverflow.com/q/19150/129) e teste `echo mb_detect_encoding($txtfile);`
Comment: Retornou o seguinte: UTF-8
Answer: Você poderia utilizar um arquivo XLS e utilizar uma função para obter os valores entre as tabelas, então ao colocar o valor no XLS, automaticamente ele seria adicionado ao MYSQL.
Comment: O intuito de importar o TXT é exatamente criar um XLS do mesmo.
Comment: Mais ele não descreveu Isso.
Comment: Desculpe, alterei meu nome depois do post, eu preciso que as informações sejam exibidas corretamente para que eu possa importar isto para o mysql, e poder gerar um xls depois...


Show that $2 < (1+\frac{1}{n})^{n}< 3$ without using log or binommial coefficient

Question: $2 <(1+\frac{1}{n})^{n}< 3$
Is it possible to show the inequality without using binommial coefficients thus only by induction? The leftinequality can be shown using bernoulli inequality.
Comment: You can find a proof by creative telescoping at page 106 [here](https://drive.google.com/file/d/0BxKdOVsjsuEwdjBEM1dpRkhMa2s/view)
Comment: I suspect the fact that $(1-\frac16)^{-6}$ is (barely) less than $3$ will be relevant.
Comment: If this must be true for all $n$ then it is false unless you change the first inequality to $\le$.
Comment: yes n>1 and I am looking for a proof that would only use  tje ordering axioms and or induction. It is one of the first exc. of my book we have not introduced binommial coefficients yet or sequences or log so it wouldnt make sense using these methods in a proof.
Answer: Let $a_n=\left(1+\frac{1}{n}\right)^n$. For any $n>1$ the inequality $a_n>2$ is trivial. We have $a_{n+1}>a_n$ by AM-GM:
$$\sqrt[n+1]{1\cdot a_n} = \text{GM}\left(1,1+\tfrac{1}{n},\ldots,1+\tfrac{1}{n}\right) \stackrel{\text{AM-GM}}{<} \tfrac{1}{n+1}\left[1+n\cdot\left(1+\tfrac{1}{n}\right)\right] = 1+\tfrac{1}{n+1}.$$
Additionally:
$$ \frac{a_{2n}}{a_n} = \left(1+\frac{1}{4n(n+1)}\right)^n \leq \frac{1}{1-\frac{1}{4(n+1)}} = 1+\frac{1}{4n+3}$$
hence for any $N\geq 1$ we have:
$$ a_N \leq a_1 \prod_{k\geq 0}\left(1+\frac{1}{4\cdot 2^k+3}\right)=\frac{16}{7}\prod_{k\geq 1}\left(1+\frac{1}{4\cdot 2^k+3}\right)\leq \frac{16}{7}\prod_{k\geq 1}\frac{1+\frac{1}{2^{k+1}}}{1+\frac{1}{2^{k+2}}}=\frac{20}{7}.$$
Comment: We have not introduced roots yet but I searched for the definition of telescoping in the link you provided. And I noticed that there were some similarities with a formula that was in the scnd. exc. of my book (this question deals with the third exc.) the formula which had to be proved is $ a^{n+1} - b^{n+1} = (a-b)(\sum_{i=0}^{n} a^{n-i}b^{i})$ do you think I can use this somehow to prove this inequality?
Comment: What is AM  and GM?
Comment: @RM777: Arithmetic mean and geometric mean.
Answer: You have the left inequality already (Bernoulli).
The right inequality can be expressed as
$$
{n} \log (1+\frac{1}{n}) < \log 3
$$
Now $\log(1+x) < x$  by concavity, which gives $1 < \log 3$ which is true.
Comment: Most courses that still wonder about the size of $(1+\frac1n)^n$ do not yet have the log function at hand, I am afraid
Answer: I have found the answer to my problem in a different forum:
We show that $b_n > b_{n+1}$ with $b_n:= (1+\frac{1}{n})^{n+1}$
Proof:
To show: $\frac{b_n}{b_{n+1}}\geq 1$
$\frac{b_n}{b_{n+1}} = \frac{\left(1+\frac{1}{n}\right)^{n+1}}{\left(1+\frac{1}{n+1}\right)^{n+2}} = \frac{1}{1+\frac{1}{n}} \cdot \left(\frac{1+\frac{1}{n}}{1+\frac{1}{n+1}}\right)^{n+2} = \frac{1}{1+\frac{1}{n}} \cdot \left(1+\frac{1}{n(n+2)}\right)^{n+2}$
Exploiting the bernoulli inequality
$\frac{1}{1+\frac{1}{n}} \cdot \left(1+\frac{1}{n(n+2)}\right)^{n+2} \geq 1$
$b_5 < 3$ and $(1+\frac{1}{n})^n < b_n $
Thus $\forall n\geq 5: (1+\frac{1}{n})^n < 3$


can anyone tell me if a class extends view than how can i can i call xml in it to show buttons at bottom of image

Question: THis is My MainActivity which Activity
public class MainActvity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new BitmapView(this));
}

I have To show an Xml File having some buttons at bottom of this image
class BitmapView extends View {
    public BitmapView(Context context) {
        super(context);``
    }

    @Override
    public void onDraw(Canvas canvas) {
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
        canvas.drawColor(Color.BLACK);
        canvas.drawBitmap(bmp, 10, 10, null);
    }
}

}
Comment: I may be missing the context/limitations, but why not create an XML layout that has the bitmap as an image/background and buttons on the bottom of the screen? Then just inflate/create that layout instead of trying pull everything together in the code behind?
Comment: Actually This Image Comes from Gridview and at the bottom of this image i have to use 5  buttons from which diff diff activity are called....  also i have to move another image over this image .....called by one of the buttons....
Answer: It is not recommended to do so since the buttons won't be responsible (I mean, they won't be clickable nor change their state when they are pressed; in fact, it is up to you to detect when the buttons are pressed).
Whatever, if that's what you want, you can do so by doing something like this:
private void drawButton(Canvas canvas, float left, float right, Button button) {
    canvas.translate(left, right);
    button.draw(canvas);
    canvas.translate(-left, -right);
}

You can call this from within your onDraw method. Usually, you will have to instantiate the button manually. Also, you can draw entire Views... so, in that case you would have to either instantiate them or inflate them; then you just call its draw method passing the canvas you get on onDraw.
Comment: Actually This Image Comes from Gridview and at the bottom of this image i have to use 5  buttons from which diff diff activity are called....  also i have to move another image over this image .....called by one of the buttons....


ImageCache or different CCK image fields?

Question: I'm setting up a website with lots of different image presets (probably up to five or six), so basically depending what page and what view my story teasers end up in they will have different dimensions, however, the web publishers need to have as much control as possible over the way the photos are cropped and resized. Is it better to use ImageCache or have different CCK image fields and have the publishers crop the images to their liking in an external image editor such as photoshop and then upload all of the presets to Drupal so the story can automatically display the right preset depending on what page and view displays it?
Also, is it possible to set up different presets for ImageCache depending on which view displays the image? Finally, it doesn't seem to me that imagecache offers cropping functionality per se. Am I correct?
Answer: Imagecache can crop. Exact or relative dimensions.
And yes, you can choose the preset for an image field in views. It is very easy. And you can manipulate it with code, but that would be much more complex. I don't think you need this.
If you really need the publishers to manipulate the image on the node edit form, just use IMCE. It integrates with Imagecache, so they could use that.
But the more you can automatize the process, the better.
So try to allow your publishers to send images the way they like (only being bigger than the minimum size you will ever use), and then you use imagecache dynamically to crop and resize the images the way you want over all the places on your site.
Comment: OK thanks! After playing around with imagecache a little bit, I was under the impression it gave you limited options in terms of what area of the image you could use when cropping and resizing, guess I need to familiarize myself with it a little more. Anyway, thanks so much for all of the info!


Infinite Variance of Harmonic Mean Estimator of Marginal Likelihood of Data

Question: If y denotes the data and t denotes set of parameters, then the marginal likelihood is

Here,  is a proper prior, f(y|t) denotes the (conditional) likelihood and m(y) is used to denote the marginal likelihood of data y. The harmonic mean estimator of marginal likelihood is expressed as

, where  is set of MCMC draws from posterior distribution .
This estimator is unstable due to possible occurrence of t with a small likelihood which influences the result because  is often not square integrable. Hence the estimator may have infinite variance. [Source : Newton and Raftery (1994), P -21; DiCiccio et al. (1997), P - 905]
Question: I am not being able to understand or visualize the situations where  may not be square integrable and the estimator may end up in having infinite variance. Can you help me to understand this (may be with an example) ?
Answer: The issue is well-detailed in Radford Neal's highly popular blog post "The Harmonic Mean of the Likelihood: Worst Monte Carlo Method Ever". It contains this Normal-Normal example:
harmonic.mean.marg.lik <- function (x, s0, s1, n)
   { post.prec <- 1/s0^2 + 1/s1^2
     t <- rnorm(n,(x/s1^2)/post.prec,sqrt(1/post.prec))
     lik <- dnorm(x,t,s1)
     1/mean(1/lik)
   }

This corresponds to a Normal N$(\theta,\sigma_1^2)$ dnorm(x,t,s1) likelihood and to a Normal N$((\sigma_1^{-2}+\sigma_2^{-2})^{-1}\sigma_2^{-1},(\sigma_1^{-2}+\sigma_2^{-2})^{-1})$ rnorm(n,(x/s1^2)/post.prec,sqrt(1/post.prec)) posterior, induced by a Normal N$(0,\sigma_2^2)$ prior. As shown in this entry, non-sensical approximations occur:
   > set.seed(1)
   > harmonic.mean.marg.lik(2,1000,1,10^7)
   [1] 0.0791889
   > true.marg.lik(2,1000,1)
   [1] 0.0003989413


Guest OS provide internet access to another Guest through Host-Only adapter

Question: I have a set-up like this:
           Ubuntu (Host OS)

OpenWRT(Guest OS) | Damn Small Linux(Guest OS)

OpenWRT is connected to Ubuntu through two interfaces, eth0 via NAT (for internet) and eth1 via Host-only adapter.
Damn Small Linux has one network adapter, the Host-only adapter which OpenWRT uses.
I would like Damn Small Linux to be able to access the internet through OpenWRT through the Host-only adapter.
Here is a crude drawing I did to try an illustrate the situation:

Is what I am trying to do possible? Can anybody run through a high level description of what is needed to make this work? I.e OpenWRT acts as a dhcp server for the Host-Only Adapter interface etc..
The idea is this, I am trying to emulate OpenWRT being a physical router connected to the internet on one interface (eth0) and providing internet on another (eth1 / the host-only adapter)
I would appreciate any thoughts or comments on this!
Answer: Yes, that should work fine.
Some thoughts:

eth0 on Damn Small Linux VM must be a attached to the same Host-only network as eth1 on OpenWRT. Use the IP from eth1 on OpenWRT as your default Gateway.
I would use a bridged config for eth0 on OpenWRT rather than NAT. Assign it a unique IP on your host's network. This will prevent some complications and will also help emulate a physical router better.
Be sure to set up any necessary firewall rules or policies in OpenWRT. Also make sure your default outbound route is set correctly.  If you're using bridged config your next hop is the Gateway for your host network - so all outbound traffic should be routed there.

Specifics:
OpenWRT:

eth0 (emulated WAN)

IP: unique IP from host network
Subnet Mask: same as SM from host network
Gateway: Same as GW from host network

eth1 (emulated LAN [host-only])

IP: unique IP from host-only network
Subnet Mask: depends on the host-only network, usually /24
Gateway: none (it's a router!)

Damn Small Linux:

eth0 (emulated LAN [host-only])

IP: unique IP from host-only network
Subnet Mask: depends on the host-only network, usually /24
Gateway: LAN IP of OpenWRT
Answer: Theoretically it should be possible if you enable promiscuous mode on your host only network.
Where does Ubuntu fit into this whole picture ? It looks like, as far as the Ubuntu VM is concerned it's connected to just another port on the Host Only virtual switch.
Are you using VMware ? VBox? I believe you should be able to enable promiscuous mode on the Host only virtual switch.


What is the probability that a random function from $\mathbb{N} \to \mathbb{N}$ is surjective?

Question: Here $[n]$ denotes the first $n$ positive integers $\{1,2,...,n\}$ and $\mathbb{N}$ is the set of natural numbers.
Let $f:[n] \to [n]$ be a random function chosen uniformly from all possible functions from $[n] \to [n]$.  The probability that $f$ is surjective is $\frac{n!}{n^n}$ which tends to zero as $n \to \infty$.  This makes me want to believe that a function from $\mathbb{N} \to \mathbb{N}$ has probability zero of being surjective.
On the other hand, let $g:\mathbb{N} \to [n]$ be a random function chosen uniformly from all possible functions from $\mathbb{N} \to [n]$  . For each $m \in [n]$, the probability that $g^{-1}(m) = \emptyset$ is equal to the limit as $k \to \infty$ of $(\frac{n-1}{n})^k$ which equals zero.  This makes me think that the desired probability is 1.
Comment: What kind of probability measure do you want to put on the uncountable set of functions from $\mathbb{N}$ to itself?
Comment: What is the probability space under discussion here? What measure are you defining on this [rather large] space?
Comment: I'm pretty sure that it is not possible to choose a function uniformly at random from all possible functions from $\mathbb{N}$ to $[n]$. Your first approach seems like a reasonable way to define this kind of thing: it's essentially analogous to natural density.
Comment: @user3482749: The natural "uniform" measure seems to be the one where the values of $f(k)$ are iid uniform on $[n]$.
Comment: @NateEldredge Sure, but there doesn't seem to be a nice way to pass that to a distribution on the functions $\mathbb{N}\to\mathbb{N}$. Sure, you could instead take the same approach as for natural density, but it seems a bit odd to do that in one argument, and do something entirely different in the other.
Comment: @user3482749: Yes, extending to $\mathbb{N} \to \mathbb{N}$ is certainly still a problem.
Answer: It is possible to define a uniform distribution on the functions from $\mathbb{N}$ to $[n]$ - we just choose each value $f(k)$ independently from the discrete uniform distribution.
Now, the probability we're looking for, of the function being surjective? That's $1$. Why the difference from the $[n]\to[n]$ case? Because it's really a limit of functions from $[m]$ to $[n]$ as $m\to\infty$. The likelihood of those being surjective? See the coupon collector problem. While the specific probability at any $m$ is very complicated, the time needed to get all of them has expected value $n(1+\frac12+\frac13+\cdots+\frac1n)$. The very fact that there's an expected value for the time tells us that the probability of infinite time is zero, and the probability our random function includes all values is $1$.
The title question, about functions from $\mathbb{N}$ to $\mathbb{N}$? That's something there's no canonical probability distribution for. Still, we can do something. Choose some distribution $u$ such that every natural number has positive probability under $u$, and choose each value of the function $f$ independently from $u$. The probability that a given value $k$ is absent from the image of $f$ is zero for each $k$. By countable additivity of measure, the probability that at least one $k$ is absent from the image is thus $\le \sum_{k=1}^{\infty} 0 = 0$, and $f$ is surjective with probability $1$.
Comment: With probability 1, yes. Countable additivity can be nonintuitive sometimes.
Comment: If I choose $u$ to be a Poisson distribution (perhaps with a very small value of the parameter $\lambda$) then are you saying that a random function created as you describe above is surjective with probability 1.  Moreover, the preimage of any element in the codomain is infinite?
Answer: Consider the problem of looking for the value of $0^0$.  If you were to argue that $0^0$ should be $\lim\limits_{y\to 0} 0^y$ then you might think that $0^0$ should be zero since $0$ to any other power is again $0$.  On the other hand if you were to argue that $0^0$ should be $\lim\limits_{x\to 0} x^0$ you might say that $0^0$ should be $1$ since any other number raised to the zeroth power is $1$.  In the end, we say that $\lim\limits_{(x,y)\to (0,0)} x^y$ does not exist since we arrive at different answers depending on choices made.  (In the context of combinatorics and set theory we do commonly make the arbitrary decision to define $0^0$ to be equal to $1$ for a number of reasons.  See elsewhere on this site for a discussion of that topic in greater detail)
In effect, it matters "how quickly" the base and the exponent each travel to zero in relation to one another.  In related problems with limits you might want to talk about a limit which appears to be in the form of $\frac{\infty}{\infty}$ such as $\lim\limits_{n\to\infty}\frac{n!}{n^2}$ or $\lim\limits_{n\to\infty}\frac{\sqrt{n}}{\log(n)}$.  In this problem too, the relative speed at which each of the top or bottom approaches infinity will influence the final result.
In your specific problem, since you have not adequately specified a probability distribution (uniform distributions are tricky and do not make sense in a number of exotic scenarios and cannot work in countably infinite scenarios), we are forced to try to make sense of it using limits as the probability of a function being a surjection when taken from a function from $[m]\to[n]$ and letting both $m$ and $n$ approach infinity.  As in the earlier mentioned problems with limits however, it depends on the speed at which each of the terms moving toward infinity travel.  Indeed, as you showed, under one choice of relative speeds you would have expected a probability of $1$.  Under a difference choice of relative speeds you would have expected a probability of $0$.
That is not to say that the final answer is necessarily that there is no answer, just that given the way you have so far presented the problem it is impossible to answer.


Dynamics AX 2009 SSRS 2008 report mail subscrition

Question: I have some issues on creating mail subscriptions for AX SSRS reports.
I put integrated credentials in the report, but subscription still return exception:

An error has occurred during report processing.

Report works in browser with values for report parameters.
From the log file i extracted the error:
<code>e ERROR: An exception has occurred in data source 'AutoGen___Query'. Details: Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: Failed to close connection for data source 'AutoGen___Query'. ---> System.TypeInitializationException: The type initializer for 'Container' threw an exception. ---> System.Security.SecurityException: Request failed.
processing!WindowsService_0!f48!11/15/2012-03:35:04:: i INFO: Some other thread has already aborted processing.
processing!WindowsService_0!f48!11/15/2012-03:35:04:: e ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.ProcessingAbortedException: , Microsoft.ReportingServices.ReportProcessing.ProcessingAbortedException: An error has occurred during report processing. ---> Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: Query execution failed for dataset 'BankAccountParam'. ---> System.TypeInitializationException: The type initializer for 'Container' threw an exception. ---> System.Security.SecurityException: Request failed.
--- End of inner exception stack trace ---;
</code>

Can someone to help me with this issue?
Answer: Unfortunately in 2009 you will either have to re-write the report to avoid using the  data source 'AutoGen___Query' - business logic, AX queries, etc
Or Create a batch job to email the report out.


Exibir data format pt-br dd/mm/aaaa

Question: Boa tarde!
Estou utilizando o plugin air-datepicker para datas.
Quando eu clico no campo, eu vejo o formato pt-br dd/mm/aaaa.
Agora, portanto, eu quero que ao abrir a janela modal, esta data seja exibida no mesmo formato dd/mm/aaaa, já que esta sendo exibida no formato yyyy-mm-dd.
Lembrando que estou utilizando ajax.
Abaixo Ajax

function editar_lancamento(id)
{
metodo_salvar = 'update';
$('#form')[0].reset(); // Redefinir o formulário em modals
$('.form-group').removeClass('has-error'); // Apagar class de erro
$('.help-block').empty(); // clear error string

//Ajax - Carregar dados do ajax
$.ajax({
    url : "lancamento/lancamento_obter_por_id/" + id,
    type: "GET",
    dataType: "JSON",
    success: function( tbl_lancamento )
    {
        $('[name="id"]').val(tbl_lancamento.id);
  $('[name="txt_tipo"]').val(tbl_lancamento.tipo);
        $('[name="txt_descricao"]').val(tbl_lancamento.descricao);
  $('[name="txt_valor"]').val(tbl_lancamento.valor);
  $('[name="txt_dt_vencimento"]').val(tbl_lancamento.dt_vencimento);
  $('[name="sel_categoria"]').val(tbl_lancamento.id_categoria);
  $('[name="sel_conta"]').val(tbl_lancamento.id_conta);
  $('[name="txt_recebido"]').val(tbl_lancamento.recebido);
  $('[name="txt_dt_pagamento"]').val(tbl_lancamento.dt_pagamento);
  $('[name="sel_forma_pagamento"]').val(tbl_lancamento.forma_pagamento);

  var tipo = $('#tipo').val();
  if(tipo == '1'){
   console.log(tipo);
   $('#modal_lancamento').modal('show'); // Abrir bootstrap modal quando completo carregado
      $('.modal-title').html(' Editar Receita'); //Definir título e icone para o título modal Bootstrap
   $(".modal-header").css('background-color', '#00A65A');
   $('#lbl_recebido').text('Recebido ?');
  } else {
   console.log(tipo);
   $('#modal_lancamento').modal('show'); // Abrir bootstrap modal quando completo carregado
      $('.modal-title').html(' Editar Despesa'); //Definir título e icone para o título modal Bootstrap
   $(".modal-header").css('background-color', '#E9573F');
   $("#lbl_recebido").text('Pago ?');
  }
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        alert('Erro para obter dados ajax');
  console.log('Erro para obter dados ajax') ;

    }
});
}
Comment: Cara, ja oviu falar na bilbioteca moment.js? (https://momentjs.com/), ela pode ser uma solução paleativa para seu problema, alem de facilitar a manipulação de datas voce pode exibir ela em diversos formatos um deles sendo o padrao que voce deseja.
moment().format('L');    // 07/06/2017
Comment: Certo, mas e sem o moment.js, tem alguma sugestão?
Comment: `var dateStr = '2017/06/07';`
`var dateSplit = dateStr.split("/");`
`var dateFormated = dateSplit[2] + "/" + dateSplit[1] + "/" + dateSplit[0];`
`console.log(dateFormated);`
Comment: @MeAjudaSilvio, funcionou!!!
Coloque como resposta que avalio!

Obrigado
Answer:

//exemplo: tbl_lancamento.dt_vencimento.split('-').reverse().join("/");
var brDate = '2017-06-08'.split('-').reverse().join("/");
console.log(brDate);
Answer: Uma possibilidade mais braçal seria esta:
var dateStr = '2017/06/07';
var dateSplit = dateStr.split("/");
var dateFormated = dateSplit[2] + "/" + dateSplit[1] + "/" + dateSplit[0];
console.log(dateFormated);

Answer: Você precisa alterar o formato da data, existem diversas maneiras de fazer, segue abaixo um exemplo simples.
Mude isso :
 $('[name="txt_dt_vencimento"]').val(tbl_lancamento.dt_vencimento);

para :
 var spDate = tbl_lancamento.dt_vencimento.split('-');
 $('[name="txt_dt_vencimento"]').val(spDate[2]+'/'spDate[1]+'/'+spDate[0]);

Comment: veja erro `Uncaught ReferenceError: editar_lancamento is not defined
    at HTMLAnchorElement.onclick (lancamento:1)`
Answer: Resolvido com a resposta do MeAjudaSilvio

var dateStr = tbl_lancamento.dt_vencimento;
var dateSplit = dateStr.split("-");
var dateFormated = dateSplit[2] + "/" + dateSplit[1] + "/" + dateSplit[0];
console.log(dateFormated);
$('[name="txt_dt_vencimento"]').val(dateFormated);

Exibir data format pt-br dd/mm/aaaa


Schedule node modifications?

Question: I use Scheduler when i need to public/unpublish nodes and it works pretty well, but i would like to  schedule the modification of an specific node? is there any module or something?
Comment: What do you mean by "schedule the modification of a node"? Is it like "publish a new revision of the node"? If so, where would such revision come from (be stored before it is published)? Or is it something completely different? Please EDIT your question to clarify this.
Comment: Would you mind clarifying this question a bit further please? I've a possible answer in mind, but will only post it if I'm sure it makes sense (and applies). I don't want to post answers that are like "guesses", ok?
Answer: Take a look at Workbench Scheduler. you could make changes as a draft(or any other workbench moderation state) and let Scheduler publish it.

Schedule node modifications?


Can I use SEM to purely compute latent correlations? Do fit indices make sense in this instance?

Question: I have 3 variables X, Y and Z, with each variable being assessed by 3 items. The variables are not part of the same factor. Does it make sense to use a SEM model to purely compute the latent correlations without specifying any regression paths or dependent variables? Example using the lavaan syntax in R:
model <- 'X =~ X1 + X2 + X3, Y =~ Y1 + Y2 + Y3, Z =~ Z1 + Z2 + Z3'

fit <- sem (model, df)

I have not come across any articles that use this method to purely compute and report latent correlations. Does it make sense to do so? If it does, do fit indices make sense here as well?
Answer: Reporting (estimates/tests of) the latent correlations rests on the assumptions that (a) those latent variables exist and (b) are measured by the indicators.  Poor model fit is evidence against at least assumption (b), maybe hinting that even (a) is dubious.  So it is still recommended to report how well your model fits your data:

most often the following estimation results are of primary interest:
estimates of the fit of the model, estimates of model parameters, and estimates of the (asymptotic) standard errors of parameter estimates. The presentation of these results can be organized around four main questions... (p. 472)

Boomsma, A. (2000). Reporting analyses of covariance structures. Structural Equation Modeling, 7(3), 461-483. https://doi.org/10.1207/S15328007SEM0703_6
See also:
McDonald, R. P., & Ho, M.-H. R. (2002). Principles and practice in reporting structural equation analyses. Psychological Methods, 7(1), 64–82. https://doi.org/10.1037/1082-989X.7.1.64
FYI, your lavaan model syntax will only work if you replace commas with semicolons, or place each formula on a separate line.
model <- 'X =~ X1 + X2 + X3; Y =~ Y1 + Y2 + Y3; Z =~ Z1 + Z2 + Z3'
## or
model <- ' X =~ X1 + X2 + X3
           Y =~ Y1 + Y2 + Y3
           Z =~ Z1 + Z2 + Z3
'


Como modificar a URL de www.meusite.com/index.php?secao=quemsomos para www.meusite.com/quemsomos?

Question: Meu arquivo .htaccess está dessa maneira:
RewriteEngine ON

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?secao=$1

Quero traduzir a url www.meusite.com/index.php?secao=quemsomos
para www.meusite.com/quemsomos
Está correto da maneira que coloquei? Pq não está dando certo.
Comment: qual o erro? veja esse link http://blog.thiagobelem.net/aprendendo-urls-amigaveis.
Answer: A regra funciona corretamente, mas estas duas condições:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

significam que o arquivo (-f) não existe e que a pasta (-d) não existe, e deve ser cumprido para executar a reescrita.
Provavelmente, você tem uma pasta chamada /quemsomos, então a reescrita não se aplica.
Remova ou renomeie essa pasta ou remova essa condição.


Slick Slider slidesToScroll modification

Question: I use the slick slider on my site. And no matter how much I was pulling the slider to the left or to the right, it just runs only on the number of slides that is specified in the property slidesToScroll. Is it possible to do something with slick slider that it worked like this slider http://www.owlcarousel.owlgraphic.com/demos/mousewheel.html. How much do you pulling - it scroll the same distance. Sorry for my english. Thanks you.
There is my code for init slick slide:
 $('.slider-wrapper-2').slick({
        slidesToShow: 4,
        slidesToScroll: 4,
        rows: 1
    });

Comment: Hello, welcome to StackExchange. Please edit your question and update with your own code, so someone can tell you how to fix it. We can't do anything for you if we don't know the code you wrote.
Comment: I use Slick @Денис Яломист and I must admit that I've never come across this option. The touch panning is a 'swipe', specifically - rather than a proper pan. Have you gone over the docs to make sure there isn't an option for what you need?
Comment: I didnt find that option in slick slider docs. So i asked here about this option, maybe somebody faced with this problem. Maybe something can be corrected in slick.js file. Thanks.
Answer: Just add the swipeToSlide setting, which enables swiping to any slide irrespectively to slidesToScroll
Your initializing script should look like this:
$('.slider-wrapper-2').slick({
    slidesToShow: 4,
    slidesToScroll: 4,
    rows: 1,
    swipeToSlide: true
});

In case it doesn't work, remove the slidesToScroll option. Please comment how it worked so I can edit my answer.
Answer: swipeToSlide: true
Adding swipeToSlide option does the job, even with slidesToScroll enabled. No need to disable slidesToScroll.


Maven não faz download das bibliotecas

Question: Estou utilizando o IntelliJ e o plugin para Maven (primeira vez), estou tentando fazer funcionar para que faça o download das bibliotecas que utilizo no meu projeto, porém ele não está fazendo o download.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>src.main.java</groupId>
    <artifactId>IR-IndexadorRepositorio</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.tika</groupId>
                <artifactId>tika-core</artifactId>
                <version>1.5</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <dependency>
                <groupId>org.apache.lucene</groupId>
                <artifactId>lucene-core</artifactId>
                <version>4.7.0</version>
            </dependency>
            <dependency>
                <groupId>org.apache.lucene</groupId>
                <artifactId>lucene-analyzers-common</artifactId>
                <version>4.7.0</version>
            </dependency>
            <dependency>
                <groupId>org.apache.lucene</groupId>
                <artifactId>lucene-queryparser</artifactId>
                <version>4.7.0</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

Log:
[INFO] Scanning for projects...
[INFO]
[INFO] Using the builder org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder with a thread count of 1
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building IR-IndexadorRepositorio 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ IR-IndexadorRepositorio ---
[WARNING] Using platform encoding (windows-1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ IR-IndexadorRepositorio ---
[WARNING] File encoding has not been set, using platform encoding windows-1252, i.e. build is platform dependent!
[INFO] Compiling 8 source files to D:\Workspace\Desk\IR-IndexadorRepositorio\target\classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[3,23] error: package org.apache.log4j does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[4,33] error: package org.apache.lucene.analysis does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[5,42] error: package org.apache.lucene.analysis.standard does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[6,33] error: package org.apache.lucene.document does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[7,30] error: package org.apache.lucene.index does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[8,30] error: package org.apache.lucene.index does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[9,44] error: package org.apache.lucene.queryparser.classic does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[10,31] error: package org.apache.lucene.search does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[11,31] error: package org.apache.lucene.search does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[12,31] error: package org.apache.lucene.search does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[13,31] error: package org.apache.lucene.search does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[14,30] error: package org.apache.lucene.store does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[15,30] error: package org.apache.lucene.store does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[16,29] error: package org.apache.lucene.util does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[22,25] error: cannot find symbol
[ERROR]   symbol:   class Logger
  location: class Buscador
D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[1,23] error: package org.apache.log4j does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[2,33] error: package org.apache.lucene.analysis does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[3,42] error: package org.apache.lucene.analysis.standard does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[4,33] error: package org.apache.lucene.document does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[5,33] error: package org.apache.lucene.document does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[6,33] error: package org.apache.lucene.document does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[7,30] error: package org.apache.lucene.index does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[8,30] error: package org.apache.lucene.index does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[9,30] error: package org.apache.lucene.store does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[10,30] error: package org.apache.lucene.store does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[11,29] error: package org.apache.lucene.util does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[12,22] error: package org.apache.tika does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[21,25] error: cannot find symbol
[ERROR]   symbol:   class Logger
  location: class Indexador
D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[23,12] error: cannot find symbol
[ERROR]   symbol:   class IndexWriter
  location: class Indexador
D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[25,12] error: cannot find symbol
[ERROR]   symbol:   class Tika
  location: class Indexador
D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[139,4] error: cannot find symbol
[ERROR]   symbol:   class Tika
  location: class Indexador
D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[146,4] error: cannot find symbol
[ERROR]   symbol:   class IndexWriter
  location: class Indexador
D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[21,0] error: duplicate class: br.com.ir.Buscador
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Princ.java:[317,20] error: cannot access Buscador
[INFO] 34 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.133 s
[INFO] Finished at: 2014-04-10T16:12:30-03:00
[INFO] Final Memory: 8M/22M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.5.1:compile (default-compile) on project IR-IndexadorRepositorio: Compilation failure: Compilation failure:
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[3,23] error: package org.apache.log4j does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[4,33] error: package org.apache.lucene.analysis does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[5,42] error: package org.apache.lucene.analysis.standard does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[6,33] error: package org.apache.lucene.document does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[7,30] error: package org.apache.lucene.index does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[8,30] error: package org.apache.lucene.index does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[9,44] error: package org.apache.lucene.queryparser.classic does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[10,31] error: package org.apache.lucene.search does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[11,31] error: package org.apache.lucene.search does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[12,31] error: package org.apache.lucene.search does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[13,31] error: package org.apache.lucene.search does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[14,30] error: package org.apache.lucene.store does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[15,30] error: package org.apache.lucene.store does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[16,29] error: package org.apache.lucene.util does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[22,25] error: cannot find symbol
[ERROR] symbol:   class Logger
[ERROR] location: class Buscador
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[1,23] error: package org.apache.log4j does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[2,33] error: package org.apache.lucene.analysis does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[3,42] error: package org.apache.lucene.analysis.standard does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[4,33] error: package org.apache.lucene.document does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[5,33] error: package org.apache.lucene.document does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[6,33] error: package org.apache.lucene.document does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[7,30] error: package org.apache.lucene.index does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[8,30] error: package org.apache.lucene.index does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[9,30] error: package org.apache.lucene.store does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[10,30] error: package org.apache.lucene.store does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[11,29] error: package org.apache.lucene.util does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[12,22] error: package org.apache.tika does not exist
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[21,25] error: cannot find symbol
[ERROR] symbol:   class Logger
[ERROR] location: class Indexador
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[23,12] error: cannot find symbol
[ERROR] symbol:   class IndexWriter
[ERROR] location: class Indexador
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[25,12] error: cannot find symbol
[ERROR] symbol:   class Tika
[ERROR] location: class Indexador
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[139,4] error: cannot find symbol
[ERROR] symbol:   class Tika
[ERROR] location: class Indexador
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Indexador.java:[146,4] error: cannot find symbol
[ERROR] symbol:   class IndexWriter
[ERROR] location: class Indexador
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Buscador.java:[21,0] error: duplicate class: br.com.ir.Buscador
[ERROR] D:\Workspace\Desk\IR-IndexadorRepositorio\src\main\java\Princ.java:[317,20] error: cannot access Buscador
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Process finished with exit code 1

Comment: Você progrediu desde que postou sua pergunta? Poderia nos dizer em que pé que está? Talvez esse tutorial pode te ajudar: http://www.javacreed.com/how-to-use-maven-with-an-application/
Answer: O problema não está no Maven ou no IntelliJ e sim no código do pom.xml, eu estava incluindo as <dependencies> dentro do <dependencyManagement>. Bastou retirar o <dependencyManagement> que tudo funcionou perfeitamente.
Segue o código como ficou:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>IRMaven</artifactId>
    <version>1.0-SNAPSHOT</version>
        <dependencies>
            <dependency>
                <groupId>org.apache.tika</groupId>
                <artifactId>tika-core</artifactId>
                <version>1.5</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <dependency>
                <groupId>org.apache.lucene</groupId>
                <artifactId>lucene-core</artifactId>
                <version>4.7.0</version>
            </dependency>
            <dependency>
                <groupId>org.apache.lucene</groupId>
                <artifactId>lucene-analyzers-common</artifactId>
                <version>4.7.0</version>
            </dependency>
            <dependency>
                <groupId>org.apache.lucene</groupId>
                <artifactId>lucene-queryparser</artifactId>
                <version>4.7.0</version>
            </dependency>
        </dependencies>
</project>

Maven não faz download das bibliotecas


ODE of two-variable function $u_x=2u(x,y)$

Question: Let $u(x,y)$ : $\mathbb{R}^2\to\mathbb{R}$, solve the ODE $u_x = 2u$, or in another form, $\frac{\partial u}{\partial x}=2u$.
I know how to solve $\frac{du}{dx}=2u$ when $u$ is $\mathbb{R} \to \mathbb{R}$, but the case when $u$ is two variable function makes me confused.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: The solution to the PDE $u_x=2u$ is given by $u(x,y)=f(y)e^{2x}$, where $f(y)$ is some arbitrary function independent of $x$. You can show this by using the method of separation of variables, that is let $u(x,y)=A(x)B(y)$ and substitute into the PDE.
Comment: Hi could you be more specific of why we can let $u(x,y)=A(x)B(y)$?
Comment: It is a method to reduce linear PDEs to systems of ordinary differential equations. See [separation of variables](https://en.wikipedia.org/wiki/Partial_differential_equation#Analytical_solutions).


Retrieve Cubes that Share a Vertex

Question: Suppose that we have a world with an infinite number of cubes, each of which are 1x1x1 in size and have integral coordinates, e.g. (1, 2, 3)
Given that C is a cube at (XC, YC, ZC) and that P is a vertex of that cube with coordinates (XP, YP, ZP), what are the coordinates of the other 7 cubes that have the vertex P?
XC - XP = 0 or -1 and YC - YP = 0 or -1 and ZC - ZP = 0 or -1
Comment: How do you model the coordinates of a cube? Seemingly, you don't use the coordinates of the $8$ vertices whose convex hull the given cube is. So what do you do? Do you take the center as its coordinate?
Comment: @Stefan, I take the "Lowest" vertex for its location, so that CP - XP is either 0 or -1 (and the same applies to the Y and Z)
Answer: Let's look at the cube with vertices $\{(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0), (1,0,1), (1,1,0), (1,1,1) \}$. If I understand your comment, you would index this cube at $(0,0,0)$.
The $7$ other cubes that share this vertex are indexed at $(-1,0,0)$, $(0,-1,0)$, $(0,-1,-1)$, $(0,0,-1)$, $(-1,0,-1)$, $(0,-1,-1)$, and $(-1,-1,-1)$.
Now given any vertex $P = (x,y,z)$, there are $8$ cubes sharing this vertex and these are indexed at $(x,y,z)$, $(x-1,y,z)$, $(x,y-1,z)$, $(x,y-1,z-1)$, $(x,y,z-1)$, $(x-1,y,z-1)$, $(x,y-1,z-1)$, and $(x-1,y-1,z-1)$ respectively. If we remove the index of the cube we started with ( namely $(X_C, Y_C, Z_C)$ in your notation ), the remaining indices yield the desired answer.
Comment: Are you sure that this is right? Those would be the cubes around C but I asked for the cubes around P (which can be any vertex of C)
Comment: @Lolums I misread your question, let me fix that.

Retrieve Cubes that Share a Vertex


Installing ASP.NET MVC 4 killed all sites in IIS 7 with 503 error

Question: Installing ASP.NET MVC 4 killed all sites in IIS 7 with 503 error. I have no idea what happened. I already .NET 4 installed and MVC 3. Anyone have any ideas?
Comment: Did you try resetting IIS?  Have you looked at your system's event logs?  (You might look at the event logs first since resetting is just a shot in the dark.)
Answer: Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...

Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]
Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.

In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective. http://blogs.msdn.com/b/rahulso/archive/2006/03/02/what-is-a-crash-technically-in-asp-net-and-what-to-do-if-it-happens.aspx


How to archive old orders in Drupal Commerce

Question: I have a site with more than 15000 commerce orders. This is slowing down the site drastically. I have upgraded all the modules and applied the patches regarding the table locking and so on. They haven't been of much help.
I am ok with removing the order history from the site. I just want to keep an archive of that so that I can use them once I have enough resources to handle everything.
I am not able to get the site up. Hence I will have to do all the work from the command line. So is there any safe and suggested way to archive the orders?
Answer: Couldn't you just backup your database using phpmyadmin, doing a .mysql export of the whole database which would keep record of all orders in the commerce_order and commerce_customer_profile tables?
Then using phpmyadmin, just remove all rows from the commerce_order table, to wipe the slate clean.
In the future, if you wanted to add all orders back into the site, you could import the data from your backup.
Comment: Chris I need the last 100 orders to be kept. So I need to delete the tables in such a way last few orders are not screwed up and they are in sync. I mean they have proper relationship to their customer profile and other related data.
Comment: I see. I'm not 100% sure, but I believe that the table rows commerce_order and commerce_customer_profile both have a customer order number column to reference by. As long as you make sure you are not deleting the last 100 order numbers, its shouldn't be affected.


Prevent File Upload during an ajax call

Question: I have a form that includes a managed_file field as well as a data popup and select field.  When the user selects a date, an ajax call is made to populate the select field.  However, I noticed that each time the ajax call is made, the file is uploaded, causing multiple copies of the file to to exist (each subsequent file having a number appended to the .  If the user selects another date, the file is uploaded again. How do I prevent the file from being uploaded multiple times during the ajax call?
Here is my form code
function _timesdb_import_form($form,&$form_state) {

  $form['file_fid'] = array(
    '#type' => 'managed_file',
    '#title' => 'Import File',
    '#size' => 100,
    '#description' => 'Select an import file.',
      '#upload_location' => 'private://filelocation/',
      '#required' => true,
      '#default_value' => variable_get('file_fid',''),
    );
    $form['date'] = array(
      '#type' => 'date_popup',
      '#date_format' => 'm/d/Y',
      '#title' => 'Start Date',
      '#description' => 'Enter the start date of the meet. After changing the date, select the meet below',
      '#ajax' => array(
      'event' => 'change',
      'callback' => '_timesdb_import_meets_ajax',
      'wrapper' => 'timesdb-import-meets',
    ),
  );

  $meet_options = isset($form_state['values']['date']) ? _timesdb_import_get_meets($form_state['values']['date']) : array();
  $form['meet'] = array(
    '#type' => 'select',
    '#title' => 'Select meet',
    '#options' => $meet_options,
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#default_value' => 'Submit'
  );
  return $form;
}

The ajax callback looks like this
function _timesdb_import_meets_ajax($form,&$form_state) {
  return $form['meet'];
}

Answer: Drupal submits the entire form at every ajax call, I think you'd have to use hooks before submit, before send or similar to prevent it. Heres something to get you started. Or simply put the file field last or at least after the ajax form elements.
Disable all form elements when doing AJAX
Ideally drupal should allow you to specify what you want to submit. please share your solution if you figure it out.
Comment: Thanks for the input.  I posted my solution, which basically isn't a solution so conceding the solution to Drupal's way of doing things.
Answer: I ended up returning the entire form.  I moved the prefix and suffix to the form element, so the entire form is replaced after the ajax call.  I figured, if I can't beat it, join it :).
$form = array(
    '#prefix' => '
',
    '#suffix' => '
',
);
$form['file_fid'] = array(
    //'#name' => 'files[importfile]',
    '#type' => 'managed_file',
    '#title' => 'Import File',
    '#size' => 100,
    '#description' => 'Select an import file.  Supported types are CSV from SWIMS or Commlink',
    '#upload_location' => 'private://timesdatabase/',
    '#required' => true,
    '#default_value' => variable_get('file_fid',''),
);

$form['date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'm/d/Y',
    '#title' => 'Start Date',
    '#description' => 'Enter the start date of the meet. After changing the date, select the meet below',
    '#ajax' => array(
            'event' => 'change',
            'callback' => '_timesdb_import_meets_ajax',
            'wrapper' => 'timesdb-import-meets',
        ),

);
$meet_options = isset($form_state['values']['date']) ? _timesdb_import_get_meets($form_state['values']['date']) : array();
$form['meet'] = array(
    '#type' => 'select',
    '#title' => 'Select meet',
    '#options' => $meet_options,

);

$form['submit'] = array(
    '#type' => 'submit',
    '#default_value' => 'Submit'
);
return $form;

Prevent File Upload during an ajax call


How to add custom field to the user profile according to its role in Drupal 7?

Question: i need to add some custom fields to the user. These fields are not the same for every user, but they vary according to their roles. How can i do that?
I saw that you can add some custom fields in the configuration menu but those cannot be differentiated according to the role.
Answer: User role field module allows you to specify role-specific fields.
When creating a new field, you specify what roles this field is enabled for.
Fields are only visible and editable if a user has a specific role.
This role does not determine access controls for visible fields.
You could use the Field Permissions module for setting access controls.
More then 120 sites currently use this module.