How do you set up shared ASIO in Window 10?

Question: I recently purchased a USB interface and, as almost every other home musician on the planet, I wanted to use it for all of my audio needs and of course concurrently shared between my Windows applications.
The steps taken for installation were the following:

I installed its ASIO drivers from the manufacturer.
I made it the default device in both Playback Devices and Recording Devices.
I unticked the options for allowing application to take exclusive control of the device both in Playback Devices and Recording Devices.
I disabled all other audio producing and recording devices incorporated within the motherboard via the Windows Sound configuration.

Still, unfortunately, every time my DAW started, I could no longer use the device to listen to anything else like Youtube, Media players, etc, resulting to both apps crashing.  Sounds familiar?
Long story short, a few nights down the road and following each advise provided in forums around the world, I installed several of the below tools:

Virtual drivers
Virtual bridges
Virtual mixers
Virtual wires
Every other "virtual everything" I found online.

No luck with most of those and the ones that did provide a result with concurrency, would really mess things up with latency.  Though described in a few words the whole process took long nights without any results.
So what is the correct way to set up shared ASIO in Window 10?
Answer: <code>To retain some structure, I continue here with the "answer" part
to my own question.
</code>

All in all I was both fed up and giving up until...

Following several utility installations I decided to clean up my system from all the Virtual This & That in order to start fresh the next day.  During this cleanup process I executed the typical uninstall routines of the utilities I had tried, but also went manually to delete any left over files, folders etc.
One of the utilities installed a virtual audio device to help route the signals in order to supply some sort of mixing tool.  To confirm this was fully and properly uninstalled, I went into the Device Manager and checked the remaining audio devices.  Everything was clean and the only devices found were the motherboards audio device and my usb interface.
Exactly at that point, it struck me!  The onboard audio devices were set as disabled within Windows Sound configuration, but were still "visible" by Windows as existant and operable devices.
I then disabled them withing Device Manager and rebooted...  Test... Voila!!!
The single available Audio Device within Windows Device Manager was now my USB Interface.
It behaves super fast using my DAW, while concurrently playing videos on YouTube.
Not clear if it matters but for all good reasons I have kept my settings to not allow exclusive use of my device by one application within Sound configuration for both Playback and Recording.
While I am still speechless by the result and the process to get there, I can only guess that this is somehow a bug within the Windows audio subsystem.
Working further to improve my system, I disabled the onboard audio from the BIOS.  Additionally, working to minimize latency, I have installed ASIO4ALL which handles the ASIO and then routes to my interface.
The final result gave me a latency of around 2.75 ms.
The USB interface is an Alientek D8 DAC/Headamp and the DAW is Ableton.
That's all folks!  I salute you hoping that this info will prove helpful to many of you struggling with this issue!
All the best,
Savvas


Java Concurrency - Adding a Shutdown hook before calling `ExecutorService#execute`

Question: I have a runnable thread MyDesiredRunnable which has the following run:
public void run() {
    try {
        this.process();
    } catch (InterruptedException e) {
        isAlive.set(false);
    }
}

isAlive is an AtomicBoolean.
The Scheduler:
// Class definition bla bla bla
   private final ExecutorService exth = Executors.newSingleThreadExecutor();

public void schedule() {
    Runnable r = new MyDesiredRunnable();
    Runnable sdt = ()->{MyDesiredRunnable.isAlive.set(false);};

    Runtime.getRuntime().addShutdownHook(new Thread(sdt));
    this.exth.execute(r);
}

This Scheduler will always be only one instance. My question is, "Does it matter if I add the shutdown hook before I call execute. All I can understand from javadocs is that the shutdown hook will not be resolved until JVM shutodown is commanded. Also, the execute command also doesn't seem to say anything against having a shutdown hook before/after. It's just that a few of ExecutorService examples on SO or even some books have the shutdownhook registration happening after we call execute. So I just wanted to know whether there is a "Catch" that I don't understand.
Thanks,
Comment: I suppose the only advantage to having the shutdown hook added first is that in the unlikely event that the JVM shuts down precisely between the two statements, you are guaranteed that the shutdown hook will be executed. That said, what is even the point of setting a boolean field when the JVM is about to terminate?
Comment: Instead of catching a specific Exception, why not set `false` in a `finally` block so only System.exit will prevent it being set.
Comment: the JVM can be stopped just before execute is called, so the shutdown hook will be called even if the desired runnable is not. But since the shutdown hook is *only* setting the AtomicBoolean (in thtat case), this is not a problem. (Could be a problem if freeing resources that are only created in the runnable - probably a wrong usage of a shutdown hook)
Comment: @PeterLawrey    Fair point! I wasn't in a good mood to craft the `try-catch-finally` setup, but yes you are right. Why not :)
Answer: To avoid trying to detect if the task is running indirectly you can use the Thread itself. If the thread isn't alive, your task isn't running.
class ThreadedRunnable implements Runnable {
    volatile boolean started = false;
    volatile Thread thread;
    Runnable runnable;

    ThreadedRunnable(Runnable runnable) { this.runnable = runnable; }

    public void run() {
        thread = Thread.currentThread();
        started = true;
        try {
            runnable.run();
        } catch (Throwable t) { // don't silently discard it
            logger.error(runnable + " died", t);
        } finally {
            thread = null;
        }
    }

    public String state() { // or return an Enum
        Thread t = thread;
        return !started ? "not started" :
               t == null || !t.isAlive() ? "finished" : "running";
    }
}


Changing tooltip for link buttons

Question: Does anyone know how to change the tooltip for the TinyMCE 4.x link buttons:

Thanks
Answer: Tooltips are defined when the button is created.  For the button in question look in the link plugin code which is in the plugins/link folder within TinyMCE.  You can find the addButton code there and change it as needed:
editor.addButton('unlink', {
    icon: 'unlink',
    tooltip: 'Remove link',
    cmd: 'unlink',
    stateSelector: 'a[href]'
});

....note that there are both minified and non-minified versions of the plugin code so change both to make sure your changes will work regardless of whether or not you load the minified or non-minified version of TinyMCE.

Changing tooltip for link buttons


Why some guitarists add a plastic gizmo in the guitar's sound hole?

Question: I've seen so many people add something made of plastic in the sound hole of a guitar, but I don't know what it's called. So what is this and why do they use it?
Comment: Shouldn't it be "a piece of plastic" or "a plastic thing" or something similar. "A plastic" doesn't sound right to me and leaves me hanging
Answer: I can think of two different things.
First, a "sound-hole pickup", a device that allows you to mount magnetic pickups onto/into a guitar so that it can be amplified without using a microphone.

Second, feedback suppressor -- a device that dampens the resonance of the guitar so that it does not feed back when being played at high volumes.  Sometimes these are just called "soundhole plug" or "soundhole damper" or "guitar damper" etc.
Comment: I think you covered all the possibilities.  Like the pictures.  Plus 1!


Prove that $A-(B-C)=(A-B) \cup (A\cap C)$

Question: I am trying to prove that
$A-(B-C)=(A-B) \cup (A\cap C)$
For the first statement, I do:
Let $x \in A-(B-C)$ means that $x \in A$ and $x \notin (B-C)$
$x \notin (B-C)$ means that $x \notin B$ or $x \in C$ $(*)$
Therefore $x \in A-(B-C)$ means that $x \in A$ AND ($x \notin B$ or $x \in C$)
For the second statement, I do: Let $x \in (A-B)$ means that $x \in A$ and $x \notin B$
$x \in (A \cap C)$ means that $x \in A$ and $x \in C$
Therefore, $x \in (A-B) \cup (A\cap C)$ means that $x \in A$ AND ($x \notin B$ or $x \in C$) $(*)$
Those two are the same so these sets are equal. I'm not sure if I did the $(*)$ parts correctly. Can someone give me some guidance?
Comment: The $(*)$ part is OK for me.
Comment: Note: You can find this question and countless variations of it on this site. I recommend to use https://approach0.xyz for search.
Answer: Everything you said makes sense. You do manage to prove the result, though your proof could be greatly clarified by the usage of some logical notation. We use $\land$ to denote "and" and $\lor$ to denote "or". Also we use $\iff$ to denote "if and only if", i.e. $P \iff Q$ means $P$ if and only if $Q$ is true, or in other words $P$ and $Q$ are both true or both false. Finally we use $\neg$ to denote negation. You can read anywhere about propositional logic to learn about the rigorous manipulation of these symbols.
Then we can realize that from the definitions, we have $x \in A \cup B \iff (x \in A \lor x \in B)$, $x \in A \cap B  \iff (x \in A \land x \in B)$, $x \in A - B \iff (x \in A \land x \not \in B)$. Then your proof is that:
$$ x\in A - (B - C) \iff x \in A \land \neg (x \in B - C) \iff x \in A \land \neg (x \in B \land x \not \in C)\\
\iff x \in A \land (x \not \in B \lor x \in C).$$
That was the first argument. Then second reads:
$$x \in (A - B) \cup (A \cap C) \iff x \in (A - B) \lor x \in A \cap C \iff (x \in A \land x \not \in B) \lor (x \in A \land x \in C)\\
\iff x \in A \land (x \not \in B \lor x \in C).$$
Putting it together gives $x \in A - (B -C) \iff x \in (A -B) \cup (A \cap C)$, which then gives that the sets are equal (by the Axiom of Extensionality).
Answer: I wouldn't ever try to restart a proof in the middle as you have.  Rather than where you write "For the second statement ...", I would continue...
By distributivity, $x \in A$ and ($x \not\in B$ or $x \in C$) is equivalent to ($x \in A$ and $x \not \in B$) or ($x \in A$ and $x \in C$).  Rewriting the parenthesized subexpressions in set notation, $x \in A \smallsetminus B$ or $x \in A \cap C$.  So $x \in (A \smallsetminus B) \cup (A \cap C)$.
Answer: You actually proved that
$$
A-(B-C)\subseteq A\cap(B^c\cup C)
$$
and you're a bit too fast in stating to have proved that
$$
(A-B)\cup(A\cap C)\subseteq A\cap(B^c\cup C)
$$
(where $B^c$ means the complement with respect to some set that contains $A$, $B$ and $C$).
So, no, you haven't really proved the statement, because you still need to prove the reverse inclusions.
Your "means" should be "implies".
Of course the reverse inequalities are easy. Why not using some algebra of sets?
If $U=A\cup B\cup C$ and we set $X^c=U-X$, where $X$ is any subset of $U$, you can see that $X-Y=X\cap Y^c$, for all subsets $X,Y\subseteq U$. Then
\begin{align}
A-(B-C)
&=A\cap(B\cap C^c)^c       &&\text{by $X-Y=X\cap Y^c$} \\
&=A\cap(B^c\cup C)         &&\text{De Morgan} \\
&=(A\cap B^c)\cup(A\cap C) &&\text{distributivity} \\
&=(A-B)\cup(A\cap C)       &&\text{by $X\cap Y^c=X-Y$}
\end{align}


Is it normal for Outlook to take 2 weeks or more to grab AD thumbnailPhoto?

Question: I've been updating user images in AD over the last few weeks. For most users, that thumbnailPhoto attribute is pulled and viewed in Outlook correctly anywhere from an hour or so to 3 days after uploading the photo. For a handful, however, Outlooks sees some photos and not others even though it's been 3 weeks or longer since the photo has been uploaded.
Is it normal for it to take that long? Is there something keeping these users from seeing the photos?
I've tried manually downloading the global address list from their machine with no change.
Comment: I've done an update of AD's thumbnailPhoto attribute recently, and it certainly doesn't take that long. Though, you have to consider replication or any replication latency within your environment. In the past, I've ran an export from various DCs to ensure it picked up the update ->
Export-RecipientDataProperty -Identity UserA -Picture | ForEach { $_.FileData | Add-Content "C:\UserAExport.jpg" -Encoding Byte}
Comment: On-premises or office 365?
Comment: @msemack - on-premise
Answer: No, it's not normal; this is probably caused by cache issues in Outlook (which version, BTW?).
Try disabling cached mode in Outlook on the clients which have this problem, or re-creating the Outlook profile altogether.
Comment: I know one of them is Outlook 2010. I haven't perfectly identified all of the users that are having issues because they're reporting the problem with HR, who took their photo, and they're relaying it to me but I know one of them is 2010.
Comment: It's very likely to be an Outlook cache issue; try disabling cache mode and/or re-creating the Outlook profile.
Comment: It doesn't look like it's a cache issue. I went to disable cached mode and it was already disabled.


Sites one page aparecem em buscadores?

Question: Sites One page, são listados normalmente em buscadores?
Existem diversos artigos e parece que sites One page não são muito amigáveis para buscadores, isto é uma realidade? Em quais casos? Somente em conteúdo entregue por Ajax?
Penso em montar um "cartão online" para o cliente, com conteúdo bem resumido, usando efeito parallax, listando apenas algumas formas de contato.
Usando como exemplo este site abaixo, o que eu devo fazer para melhorar o resultado de buscas?
http://ianlunn.co.uk/plugins/jquery-parallax/
Considerando que este site seria apenas um portfólio, e one page ou não teria o mesmo conteúdo;
Resumindo:
Um one page com 4 sections, ligados por anchor links tem menos eficiência de busca contra um site com 4 páginas com uma section dentro de cada?
Comment: Seu site usa ajax? A questão não é ser one-page ou utilizar o efeito x ou y. Se o conteúdo que precisa ser indexado está contido no HTML que seu server entrega, os buscadores enxergam. Se vem por ajax, eles geralmente não enxergam e você precisa usar técnicas específicas para "conversar" com eles.
Comment: Se estiver tudo sendo servido junto, será indexado sim. Agora, se vai indexar links de seções e levar para as seções corretas, depende da sua programação. Recomendo você testar.
Comment: Então o site irá indexar normalmente, aparecer em buscas normalmente?
Answer: TL;DR
Sim, sites de uma única página aparecem em buscadores, mas em geral é necessário um grande esforço adicional para isso.
Páginas tradicionais x dinâmicas
Os buscadores indexam vários tipos de conteúdo, principalmente HTML, que é a base da web tradicional.
Isso significa que se o conteúdo não estiver prontamente disponível no código HTML ele não ai adivinhar onde está, nem vai interpretar seus scripts e saber qual conteúdo você pode carregar dinamicamente.
Técnicas alternativas
Para resolver esse problema, existem algumas técnicas que podem ser usadas:

Incluir todo o conteúdo dinâmico oculto no HTML de forma que o usuário não veja, mas o robô indexador sim. Dessa forma a navegação no site consiste em alternar a visibilidade dos elementos.

Mostrar uma página alternativa para os buscadores. É possível identificar se um robô indexador está lendo seu site através dos cabeçalhos HTTP. Você pode configurar o Apache ou qualquer servidor web para exibir uma página em HTML puro para ele com todo o conteúdo do site.

Usar um site map e criar várias URLs alternativas que renderizam o respectivo conteúdo, entretanto se o usuário acessar uma delas ele então é redirecionado para a aplicação principal.

Nota: não pretendi ser exaustivo. Podem haver inúmeras outras técnicas.
Conclusão
É perfeitamente possível otimizar um Single Page Application para SEO, mas leve o esforço adicional em conta antes de adotar uma solução como essa.
Particularmente, para a web em geral eu prefero um modelo tradicional com páginas separadas.

Sites one page aparecem em buscadores?


How to compile Browser source code for Android 4.0.3

Question: I downloaded the Browser source code from https://github.com/android/platform_packages_apps_browser.
I am able to access the hidden and internal package with the help of http://devmaze.wordpress.com/2011/01/18/using-com-android-internal-part-1-introduction/ tutorial.
I am not able to build the source code for Android 4.0.3. But when compiled for Android 4.0.3 Eclipse shows "This class must implement the inherited abstract method AbsSpinner.layout(int, boolean), but cannot override it since it is not visible from FolderSpinner. Either make the type abstract or make the inherited method visible" error in FolderSpinner class.
Thanks in advance for help.
Regards,
Vibhor
Answer: You can only build AOSP apps as part of the whole firmware. They are not designed to be built individually.
Comment: I am able to build the Browser source code for Android 3.2 and the code is running fine on Android 3.2 device. But when I compile the using Android 4.0.3, I get the compile time error. Actually its is a Java compilation error and not able to find the correct reason for the same.
Comment: @vibhor, I tried the steps mentioned in the tutorial for 3.2. I created the classes.dex.dex2.jar file. But inside the jar file i browsed through com/android/internal folder which is empty. I tried many times but facing the same issue.. I am working on windows 7 OS ...Need your help on resolving the issue
Comment: @CommonsWare couldn't I just download the android source and link it?


How to add up price values when group by month?

Question: I have a Views table view that shows bank transactions. Each transaction has:

A price field (which consists of a single positive OR negative amount)
A date field

I would like to display the transactions grouped by month and then display a total of all the price fields for each month.
How can I do this?

Steps I have tried
1) Use Views built in tools
In the setting for a table view, you can chose to group entries by a field. So I group my fields by month.
I then go to other > Use Aggregation and set it to "on".
Finally I select "Sum" in the aggregation options of the price field.
Results:

Entries are grouped by month Months are not in order (It goes March,
January, February, December)
The total of the prices fields for each
month is not displayed.

2) Use Views Calculation module
This requires a patch to support Group fields. Unfortunately, the patch does not work with price fields (see comment #118). My own testing confirms this.
3) Use Views Aggregator Plus
Views Aggregator Plus module is designed to be an alternative to Views Calc.
In Views format, I select a "Table with aggregation options"
I apply the "column function" to my price field and select "sum"
I apply the "group function" to my date field and select "group and compress".
Results:

Only the first transaction for each month is show (The other
transactions are hidden)
The total is displayed, but it is incorrect
and doesn't seem to relate to anything.
Comment: About "**2)**": can you be more specific about "does not work" (e.g. via an edit of your comment #119 in that issue. Also, what is "special" about such price field, how does it differ from "classic number" (as in comment # 118 of that issue)?
Comment: @Pierre.Vriens  The price field has a field type of `float`. When used with View Calc, the total price is displayed as 0.00.
Comment: Shouldn't price field be of type Decimal rather? Decimal is mire precise than float.
Comment: @J. Reynolds I've been using float for over a year. Is it possible to change it without losing my data in the fields?
Comment: Apologies for not being able to offer a bounty. I spent a lot of time implementing all the suggestions, but couldn't get any of them to work sadly. I'm not sure why, but I will investigate. If I ever find a working solution, I will come back and mark the correct answer. (Or provide an answer if I find a new approach).
Answer: You can use views date format sql with simple in built views aggregation. No need to use views aggregator plus.
Comment: That doesn't seem to work with date fields: https://www.drupal.org/node/1830436
Comment: I disagree. It does work. Install the latest patch, then make sure to clear your cache. After that the 'Use SQL to format date' tick box becomes available. The only thing that does not work is getting the sort right. For that you can do a custom sort in hook_views_pre_render or something similar.
Comment: @J. Reynolds - Yes it works with the patch. Thanks!
Comment: @vgoradiya: I use "format > table" I then set the date as the group. I then turn on Views built in simple aggregation. I then set my price field to "sum" aggregation. However, all the fields in the View display disappear. What am I doing wrong?
Answer: When using "Views Aggregation Plus" as described in your question, you also need to change the date field to use a Custom PHP "Date Format" something like "F Y".
Then disable the "group function" for date column in the "Table with aggregation options".
Also make sure views has "Use aggregation",
This should give you totaled rows for each month.
Also make sure views_date_format_sql module is enabled.
Comment: @Z Z when you say "Custom PHP Date format" are you referring to the option marked "Choose how users view dates and times:" (This option is found for the date field in Views)? When I follow your instructions, the results are grouped by month, but the price fields are displayed as "1" instead of the original price value. Also, the dates are out of order (It goes March, Jan, Feb, Dec). Thanks for any help you can offer.
Comment: Also, when I use "views_date_format_sql" module, all my date fields display "Broken/missing handler".
Comment: To clarify, When you edit the view, and go to the date field, edit the date field. You will find the "Date format" field - choose "Custom", then it will provide a field "Custom date format" in which you enter the PHP format.  Further down, choose " Use SQL to format date". Then save the field. You can fix the sorting by adding Date to "Sort Criteria" section of the view, and choose type of sorting you want
Comment: Is this with "views_date_format_sql" enabled? With this module, all my date fields display "Broken/missing handler". Is there a way to get the date fields to display when the modules are enabled. I've searched around but can find nothing!
Comment: Yes, views_date_format_sql" is enabled. Make sure the Views "Other" Section you select "Use aggregation" to be Yes. Then for the Price field, edit it again and use SUM as its "aggregation type"
Comment: If by chance you are using drupal commerce, and you install commerce_reports, there is a sales report there which has monthly totals which can help you understand what to do.
Comment: I had to install this patch, to get it to work with the date field: https://www.drupal.org/node/1830436   However, I still cannot see a custom PGP Date format. I have made a screenshot of what I can see on the field: http://web.madhu.co/views.jpg Thanks!
Comment: I am using an older version - "views_date_format_sql"  7.x-3.1. But see image posted by Pierre.Vriens below as it looks just like what I am describing to you. You have to select "Custom" for it to appear.
Comment: Do you have to do something special to get that option to appear? Here is a screenshot of what I see: http://web.madhu.co/views.jpg
Comment: No I do not. Not sure why you are not seeing it, unless you have different versions modules e.g. date, views, etc.
Answer: I realise your question is not about creating a chart from these data. However there is an interesting Charts-issue you may want to look at (for which the challenge is similar to your question here). I.e. Graph node input over time (support date formatting on a continuous axis). In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'.
Part of the recommended solution there is to (also) use the Views Date Format SQL module. Here are some details (from its project page):

The Views Date Format SQL module allows to format date fields using SQL. This enables group aggregation for date fields using the choosen granularity.
The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE_FORMAT rather than PHP's format_date. This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views_handler_field_date.
The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

Some more suggestions from that very same comment:

If you're doing grouping by node post date or other built-in fields however, this problem can be solved by using the Views Date Format SQL module. It adds a nice little checkbox that allows you to group dates by a custom formatted string. In this screenshot, I set the custom date to be "M Y" (which translates to Oct 2012 for example), then checked the box for "Use SQL to format Date".
Answer: I made a site once that provided a service.  Clients would log in and request the service, then the company would process them through a workflow and generate a report.  The company wanted to know which clients were requesting how many of what type of report on a monthly and weekly basis.  I wrote a statistics report set of views and bundled it into a feature for them.  In order to get the sub totals by type and also the grand totals by client in each table, I had to use a combination of placeholders in a footer area and hook_views_pre_render to do the summations and replace the placeholders.
This hook has the ability to rewrite the rows[] section of the view before render, so you can even change what the view is going to show as the data, but there are better ways to do that.  This approach gives you access to all the data that the view has fetched and lets you change and/or add things before the theme gets to work on making it look pretty.  I would recommend making the view data as simple as possible to give your custom processing more room to work.  Empty global text fields in the table and in the header/footer give you somewhere to put the new information into the view when you are done processing it.
Having a look at the structure of the view object before you are manipulating it will make it easier to grab the data for your sums and also put it in place.  I use this recursive print tool in a watchdog statement because not every hook can print_r to the screen.  I think the hook_views_pre_render can though, so you probably don't need the watchdog log.
Answer: Have you tried with
Force using fields

checked ? (Under Format -> Settings)
Thsi is in german, but you'll find it under Format Format: Unformatierte Liste | Einstellungen (underlined)
Comment: Yup, that should 'unlock' the grouping options for the format settings.
Comment: @rémy @neograph734 I can't find `Force Using Fields` anywhere! Which method does this apply to (1) Views built in tools, (2) Views calc module or (3) Views Aggregation plus? Thanks!
Comment: that's a standard view setting. found under Format: Format, i guess you have Table (with aggregation), left, there's a settings link where you find that property
Comment: Is this for Drupal 7? I've checked under `"Format > Table"` and `"Format> Table with aggregation options"` but I can't find `Force Using Fields` anywhere! Thanks in advance and thanks for your patience.
Comment: yes - it's D7 .. if i choose format > table, it isn't there .. try to change to unformatted list, tick it, save and put the format back. tables uses only fields, and probably has this setting as default .. (or maybe not ...)
Comment: This is what I see when I select "format > table" and then click on "settings" http://web.madhu.co/views-2.jpg
Answer: Yo can do It using pre render hook in your theme template.php or in a custom module.
function your_theme_views_pre_render(&$view) {
  if ('your_view_name' == $view->name && 'your_display_name' == $view->current_display ) {
    foreach ($view->result as $key => $row){
      /* here you can acces each row data (view result) ,
      take all the values for the rows on each month
      (which you get from the date field) and sum them,
      you have the values you need */
      $date = $row->field_field_date[0]['raw']['value'];
      $month = /* get the month from the date */
      $month_price = $row->field_field_price[0]['raw']['value'];
      $_SESSION['month_sum'][$month] += $month_price
    }
  }
}

Once you have the values you can keep them and modify the output with a preprocess hook. Another (and easier way) if you won't use the price field for anything else, you can iterate again through the $view->result and change every price with the sum of all the prices on his month so, on the final output you will have it already, resulting in something like:
function your_theme_views_pre_render(&$view) {
  if ('your_view_name' == $view->name && 'your_display_name' == $view->current_display ) {
    foreach ($view->result as $key => $row){
      /* here you can acces each row data (view result) ,
      take all the values for the rows on each month
      (which you get from the date field) and sum them,
      you have the values you need */
      $date = $row->field_field_date[0]['raw']['value'];
      $month = /* get the month from the date */
      $month_price = $row->field_field_price[0]['raw']['value'];
      $_SESSION['month_sum'][$month] += $month_price;
    }
    foreach ($view->result as $key => $row){
      $date = $row->field_field_date[0]['raw']['value'];
      $month = /* get the month from the date */
      $row->field_field_price[0]['raw']['value'] = $_SESSION['month_sum'][$month];
    }
  }
}


Checked remote service exception translated to StatusCodeException in tomcat

Question: I've got a GWT app that does regular RPC calls to a RemoteService whose methods may throw a ServiceException:
public class ServiceException extends Exception implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    public ServiceException() {}
    public ServiceException(final Throwable cause) {
        super(cause);
    }
    public ServiceException(final String errorMsg) {
        super(errorMsg);
    }
}

This works perfectly fine in development mode where I get the expected exception messages in my onFailure async callback but when I compile the app and deploy it to tomcat my exception gets translated to
com.google.gwt.user.client.rpc.StatusCodeException: 500 The call failed on the server; see server log for details

Just as in dev mode, my server logs show the expected exception reason which I logged myself just before throwing the ServiceException.
I've looked this up in google but could not find anything relevant.
(I'm working on Mac OS X Lion with GWT 2.4, java 1.6 and Tomcat 7.0.16)
Comment: Post the client side code where you check the type of the exception
Comment: for debugging purposes, the client-side code is:    `public void onFailure(Throwable arg0) { setErrorMessage(arg0.toString()); }` this displays the string into a label field in my app.
Comment: I found that exception is properly received in the client side. Refer this [tutorial](https://developers.google.com/web-toolkit/doc/latest/tutorial/RPC#exceptions) to check if your implementation is right
Comment: I followed exactly the steps in the tutorial; you can see the declaration of my exception and the service interface methods throws the ServiceException. As I said, the exception is properly received in dev mode, it's only when compiled and running in tomcat that it is translated
Comment: Just for the debugging purpose, you can check the type of the exception by using `caught instaceof ServiceException` in the client code.
Answer: It seems that your gwt-rpc servlet does not handle the exception properly. Then your tomcat container handles the exception by sending the http-500 error page. Usually an exception should result in a http-200 response and "EX" in the end of the gwt encoded answer. The development mode runs with some kind of jetty container. Maybe there is some difference between the development mode's jetty and tomcat that causes the different behaviour.
Please look at your gwt-rpc servlet code to find the reason.
btw: It is a bad idea to put the error cause into a field of your exception. You'll never know if the cause is serializable or not.
Answer: Stupid mistake. I finally figured out that the problem came from an accidental typo in the configuration of the java obfuscator I am using. Because of that my class name was renamed when building the war that I was deploying in tomcat.


Drupal commerce based recommendations engine

Question: I want a shop where experts join the shop and each expert recommends his favorite products.

Expert's user profile will show his recommended products.
Users can vote recommendations up and down, much like happens in amazon.
The product's page will show the recommendations for that product.
The expert will also be an affiliate.

Possible architecture:

Commnets may be themed to be recommendations, together with voting stars.
Affiliates may be added with the Post Affiliate Pro integration.

Questions:

From your experience, what are the best modules / drupal commerce extensions to support this scenario?
Is there another, internal affiliate solution?

Thanks
Amnon
Answer: I would not use comments to be recommendations but I would use nodes. This will give more flexibillity.
Here is a possible architecture:
I would use the flag module to let user flag (recommend) a product.
On flagging, I would use hook_flag to create a new node (content type: recommendation). This node would reference to the product. The new node would contain a body field that will contain the actual recommendation. Finally, I would attach the rate module to this node so that users will be able to vote on it.
As far as I know the flag 3.x module is now an entity, which means that you can attach fields to the flag. So, another possible architecture would be to use the flag itself for storing the recommendation. Have not tried this though but seems interesting.


Physical/portable Hard drive tester/diagnostics tool

Question: Are there any tools that I can plug into a hard drive and perform diagnostics such as displaying if there are SMART errors? I work with a lot of commodity hardware and need to check if some of the disks laying around are good. It's a pain to put them in a computer. boot up Unix or some proprietary recovery software, and check each drive individually. It would be awesome if there was a device that I could plug in, and after a reasonably short time, give a status code or something. Ideally this would work with both IDE and SATA interfaces.
Answer: All the major manufaturers (Seagte, Fujitsu, WD) offer testing apps. I would invest in a cheap ($15) drive caddy. They attach via USB and drives are inserted like bread into a toaster. No opening the case, cables to deal with, etc. They do only come SATA or IDE though, so you would need two.
You can use the vendor tools I mentioned or smartctl and you'll have more information about the drives than you ever wanted!
Comment: Yeah, I got these on a thumbdrive. I was just hoping there was a more portable solution. Something to throw in the tool bag.
Answer: For this sort of work (and more) I've invested in a "universal" drive adapter, which is a set up plugs and a power supply that allows me to connect both SATA and PATA 2.5" and 3.5" drives via a USB cable. Mine's an older version of this one.
Comment: Yeah, theres actually something similar sitting next to me. I guess I'll just setup a box for testing. The only downside to this is that its just not portable unless I hook it to a laptop or something and even then I still need the power. =/


(not asympotic) relation between hypergeometric and binomial distribution

Question: Let $H$ be a random variable with hypergeometric distribution of parameters $n,h,r$ (that is $n$ is the total number of elements, $h$ elements are white and I choose $r$ elements).
Let $B$ be a random variable with binomial distribution of parameters $r$, $h/n$
(that is $r$ independent trials with success probability $h/n$)
Is it true that for any $k$ $$Pr(H\ge k)\ge Pr(B\ge k)?$$
Thanks!
Answer: Since $H$ and $B$ have the same expected value,
$$ \sum_{k} Pr(H\ge k) - Pr(B \ge k) = E[H] - E[B] = 0 $$
In any case where the distributions are not the same, your inequality can't be true for all $k$.
Comment: Is the statement valid for $k$ beyond the mean? Since the Chernoff tail bounds for binomial apply to hypergeometric (negative correlation), it seems like binomial should have a heavier tail than hypergeometric.


Use decltype to declare the return type

Question: I've got the following code snippet:
int odd[] = { 1,3,5,7,9 };
int even[] = { 0,2,4,6,8 };

// returns a pointer to an array of five int elements
decltype(odd) *arrPtr(int i) {
    return (i % 2) ? &odd : &even; // returns a pointer to the array
}

int main()
{
    int *res1 = arrPtr(3);
    decltype(odd) *res2 = arrPtr(3);
    auto res3 = arrPtr(3);
}

For the first line I get the following error message:

int (*arrPtr(int i))[5]
returns a pointer to an array of five int elements
Error: a value of type "int (*)[5]" cannot be used to initialize an entity of type "int *"

Why can't int* be used to initialize my return value from arrayPtr()? I would have assumed that the compiler is doing an explicit conversion.
Furthermore, what would one use as return type (best practice)?
Comment: Please do never post code on screenshots. And also better prepare a [MCVE].
Answer: It seems odd is declared as an array of int:
int odd[5];

The type of odd is int[5] and taking the address (or adding a * to decltype(odd)) of this array yields an int(*)[5]. It seems, you actually want to use the decayed type of odd:
decltype(+odd) arrPtr(int i) {
    return i % 2? odd: even;
}

int main() {
   int*           res1 = arrPtr(3);
   decltype(+odd) res2 = arrPtr(3);
   auto           res3 = arrPtr(3)
}

Note this use of unary + which forces decay of the array to become a pointer to the first element of the array.
If you really mean to return a pointer to the array, you'd need to use a suitable type when capturing the result (assuming the original implementation):
int (*res1)[5]      = arrPtr(3);
decltype(odd)* res2 = arrPtr(3);
auto res3           = arrPtr(3);

Note, that this is a pointer to an array of 5 int, i.e., you'd access an element of it using
(*res1)[3];

or
res1[0][3];

Comment: Now this is something new, at least for me.
Answer: int (&)[5] can decay to int *, it is not the case for int (*)[5].
You may change your code to
decltype(odd)& arrPtr(int i) {
    return (i % 2) ? odd : even; // returns the reference to the array
}

and then
int main()
{
    int *res1 = arrPtr(3);
    decltype(odd)& res2 = arrPtr(3); // int (&)[5]
    auto res3 = arrPtr(3); // int*
    const auto& res4 = arrPtr(3); // const int (&)[5]
}

Use decltype to declare the return type


What kind of Fender Strat is this

Question: I was offered a Fender Strat Custom Shop Guitar and I am interested in buying it but I have no info about it, only some pictures and would like to know if it's worth it. Any help is greatly appreciated. Thanks.
Comment: Looks a bit suspect to me, the logo on the front of the headstock doesn't look right.
Comment: @MichaelCurtis All you would need to do to change that is look at the photos of current fender custom shop models on the fender or reputable reseller web site. They don't seem to be putting them in the middle of the back of the headstock right now, just found a picture showing it inside the scroll bit at the tip of the headstock, but its position has varied over the years.
Comment: Perhaps you can locate the serial number and use Fender's website to see more information about the instrument?
Comment: The seller also has no info about it? Custom Shop Strats are not cheap. It would be strange for the current owner not to know anything about it, unless they did not acquire it legitimately. I haven't been able to find a Strat that has that art on it, so the art might be after market.
Comment: I would ask the seller for a photo of the neck plate (the square metal plate on the back of the guitar where the neck joins the body).
Comment: it doesn't have the serial number anymore. Thanks
Comment: I've not see that chevron mark on the back on a Fender before.
Answer: Normally, the Fender logo aligns with the bottom straight edge of the headstock. The logo is usually either golden and smaller or large and black. Smaller and black is not one I've seen.
I think the one thing I can say is that this guitar has never been in the Fender Custom Shop.
Comment: Thank you for your comments, I am not buying it.
Answer: A genuine Fender Custom Shop guitar comes with a Certificate Of Authenticity, which contains the serial number and describes the instrument and when it was made and sometimes also by whom. Without this document, the guitar isn't worth half as much. I'd be wary of a seller who claims to have mislaid this document.
If you can try the guitar, and it feels and sounds great, then go ahead and buy it for the price of a regular second-hand Fender. But don't pay a premium if the seller can't prove it's a genuine Custom Shop instrument and you have no way of verifying that claim.
Maybe only the neck is from a custom shop guitar. Maybe the seller just printed the custom shop logo on it himself, or the previous owner did and duped the current owner. Maybe it's a partscaster made with Mexican and Squier parts. There's no way of knowing, unless you can take someone with you who has experience in authenticating Vintage or Custom Shop guitars. Maybe you can ask in a local guitar shop if they want to accompany you when you go check out the guitar, in exchange for a fee?
Comment: Thanks for answering, I'm not buying it. It's probably fake.
Answer: A single detail -- the machine heads (first photo) aligned very, very poorly -- is enough to tell you this is no custom shop but a cheap copy.

What kind of Fender Strat is this


Cannot move csv file from one directory to other

Question: I am trying to archive a csv file after reading its content and storing it in the database. I am doing it as
String filename = file.getName();
File destiantion = new File(getAttribute(ST_ARCHIVE_FOLDER) + "/"+ filename);
boolean fileArchived = file.renameTo(destiantion);

where file = "D:\Users\400220260.INDCORP\Desktop\ParameterMargin20141009.csv"
and destination = "D:\Users\400220260.INDCORP\Desktop\Archive\ParameterMargin20141009.csv"
Please help
Thanks in advance
Comment: Let us see some code
Comment: I forgot to close the FileReader in my File Object. Its working fine now.
Answer: You have your File objects, but now you have to copy the old file to your new location. Just a rename on the file won't do what you want. This can be done like this:
public static void copyFile(File sourceFile, File destFile) throws IOException {
   destFile.createNewFile();
   FileChannel source = null;
   FileChannel destination = null;

   try {
      source = new FileInputStream(sourceFile).getChannel();
      destination = new FileOutputStream(destFile).getChannel();
      destination.transferFrom(source, 0, source.size());
   }
   finally {
      if(source != null) {
         source.close();
      }
      if(destination != null) {
         destination.close();
      }
   }
}

What would be even easier is using the copyFile method of FileUtils from Apache Commons IO, but therefore you have to add that library in your project:
FileUtils.copyFile(File srcFile, File destFile)

Comment: I have to move the file it is working fine but it is copying the file from one location to another
Comment: You can delete the first file using file.delete()
Answer: As it stated in Javadoc:
The rename operation might not be able to move a file from one filesystem to another.

You could use Files.copy(InputStream in, Path target, CopyOption... options) from java.nio.file to achieve this.


Is it an anti-pattern to use async/await inside of a new Promise() constructor?

Question: I'm using the async.eachLimit function to control the maximum number of operations at a time.
const { eachLimit } = require("async");

function myFunction() {
 return new Promise(async (resolve, reject) => {
   eachLimit((await getAsyncArray), 500, (item, callback) => {
     // do other things that use native promises.
   }, (error) => {
     if (error) return reject(error);
     // resolve here passing the next value.
   });
 });
}

As you can see, I can't declare the myFunction function as async because I don't have access to the value inside the second callback of the eachLimit function.
Comment: Oh, ok... sorry. I need the constructor because i need the async.eachLimit to avoid more than 500 asynchronous operations at a time. I'm downloading and extracting data from text files and i want avoid to much asynchronous operations, after i extract the data, i must return a Promise with the data, and i wont be able to return it from the callback of the async.eachLimit.
Comment: "As you can see, i can't declare the myFunction as async" --- can you elaborate more?
Comment: 1. Why do you need the await? Async is already a control-flow mechanism. 2. If you want to use async.js with promises inside node.js take a look at async-q
Comment: To avoid callback hell, and if something throws, the outer promise would catch.
Answer: You're effectively using promises inside the promise constructor executor function, so this is the Promise constructor anti-pattern.
Your code is a good example of the main risk: not propagating all errors safely. Read why there.
In addition, the use of async/await can make the same traps even more surprising. Compare:

let p = new Promise(resolve => {
  ""(); // TypeError
  resolve();
});

(async () => {
  await p;
})().catch(e => console.log("Caught: " + e)); // Catches it.

with a naive (wrong) async equivalent:

let p = new Promise(async resolve => {
  ""(); // TypeError
  resolve();
});

(async () => {
  await p;
})().catch(e => console.log("Caught: " + e)); // Doesn't catch it!

Look in your browser's web console for the last one.
The first one works because any immediate exception in a Promise constructor executor function conveniently rejects the newly constructed promise (but inside any .then you're on your own).
The second one doesn't work because any immediate exception in an async function rejects the implicit promise returned by the async function itself.
Since the return value of a promise constructor executor function is unused, that's bad news!
Your code
There's no reason you can't define myFunction as async:
async function myFunction() {
  let array = await getAsyncArray();
  return new Promise((resolve, reject) => {
    eachLimit(array, 500, (item, callback) => {
      // do other things that use native promises.
    }, error => {
      if (error) return reject(error);
      // resolve here passing the next value.
    });
  });
}

Though why use outdated concurrency control libraries when you have await?
Comment: You don't need `return await`: `return new Promise` is sufficient.
Comment: I officially approve this answer, I'd have said exactly the same :-)
Comment: @celoxxx Have a look [here](http://stackoverflow.com/a/39197252/1048572). You indeed should never use async.js with promises
Comment: @celoxxx Just drop the types and it becomes plain js. You should not use async.js because the different interfaces - node-style callbacks vs promises - cause too much friction and lead to unnecessary complicated and error-prone code.
Comment: I agree with you... But this code is old, and i'm refactoring to use events + async.js (to control the limit of async, yet. If you know a better way, please say).
Comment: Because i need control the maximum number of async operations at a time. Do you know any other way to do it without the eachLimit? @jib
Comment: I need this because i'm spawning child process, and if i don't control the number, this will cause OS exceptions. Sometimes i need open 10.000 child process's.
Comment: I don't understand TypeScript @Bergi.
Comment: I'm a bit curious... why not use async + promises? Promise.all won't resolve the problem of limiting the number of async operations.
Comment: That's not the first time i see you saying it's wrong use the Promise + Async module. I really would like to understand what problems would case this.
Comment: I agree with user5487299 - if you have100,000 tasks that need to be run, then you don't necessarily want synchronous execution. But you can't execute them all at once either. A library like [p-limit](https://www.npmjs.com/package/p-limit) allows you to specify the appropriate amount of concurrency to your desired resource usage and speed.
Answer: Based on the feedback given by @Bergi, I want to highlight that I agree with the answers given above and would rather choose a different approach.
However, if you need to have async inside your promise, I would consider using something like this:
const operation1 = Promise.resolve(5)
const operation2 = Promise.resolve(15)
const publishResult = () => Promise.reject(`Can't publish`)

let p = new Promise((resolve, reject) => {
  (async () => {
    try {
      const op1 = await operation1;
      const op2 = await operation2;

      if (op2 == null) {
         throw new Error('Validation error');
      }

      const res = op1 + op2;
      const result = await publishResult(res);
      resolve(result)
    } catch (err) {
      reject(err)
    }
  })()
});

(async () => {
  await p;
})().catch(e => console.log("Caught: " + e));

The function passed to Promise constructor is not async, so linters don't show errors.
All of the async functions can be called in sequential order using await.
Custom errors can be added to validate the results of async operations
The error is caught nicely eventually.

A drawback though is that you have to remember putting try/catch and attaching it to reject.
Comment: While this works, you might as well get rid of the wrapping promise, try/catch etc, and do the same with the remaining of your IEFE function: https://i.stack.imgur.com/S3pU2.png
Comment: @noseratio can't agree more. the op though asked if it's okay to use `async` inside of a `Promise` body.
Comment: it gives linting error: `Promises must be handled appropriately or explicitly marked as ignored with the void operator`
https://github.com/typescript-eslint/typescript-eslint/blob/v4.28.0/packages/eslint-plugin/docs/rules/no-floating-promises.md
Comment: This answer is a perfect complement of jib's answer and exactly what that I need to understand.
Comment: @VladyslavZavalykhatko If you agree with noseratio, it should be clear that it's not okay to use `async` inside of a `new Promise`. It's not even "*neater*".
Comment: @Bergi I agree with noseratio in the sense that _my particular example_ does not require the wrapping promise; it is provided only to illustrate the idea
Comment: @VladyslavZavalykhatko Then please [edit] your answer to show a better example. (Hint: you shouldn't be able to find any where the wrapping promise is required)
Comment: @Bergi I agree that the wrapping promise won't be _required_. a necessity to use callbacks and passing `resolve` or `reject` could be a case when it's "_neater_"
Comment: @VladyslavZavalykhatko There is no necessity to use callbacks though?
Comment: @Bergi in own code probably not. what would you do for 3rd party providers exposing functions expecting callbacks?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/253416/discussion-between-vladyslav-zavalykhatko-and-bergi).
Answer: BELIEVING IN ANTI-PATTERNS IS AN ANTI-PATTERN
Throws within an async promise callback can easily be caught.
(async () => {
    try {
        await new Promise (async (FULFILL, BREAK) => {
            try {
                throw null;
            }
            catch (BALL) {
                BREAK (BALL);
            }
        });
    }
    catch (BALL) {
        console.log ("(A) BALL CAUGHT", BALL);
        throw BALL;
    }
}) ().
catch (BALL => {
    console.log ("(B) BALL CAUGHT", BALL);
});

or even more simply,
(async () => {
    await new Promise (async (FULFILL, BREAK) => {
        try {
            throw null;
        }
        catch (BALL) {
            BREAK (BALL);
        }
    });
}) ().
catch (BALL => {
    console.log ("(B) BALL CAUGHT", BALL);
});

Comment: It really is a pattern that should never be used. Just remove the line `await new Promise (async (FULFILL, BREAK) => {` and replace `BREAK` with `throw`.
Comment: Actually no, this is anti-pattern and demonstrates you do not fully understand Promises and the supporting async..await syntax. Moreover it's very ugly, especially the eye-crossing line of `}) ().`
Comment: "BELIEVING IN ANTI-PATTERNS IS AN ANTI-PATTERN" sounds like an attempt to be contrarian for the sake of it. Adding pointless wrappers on top of promises like this makes code objectively more confusing and is very much an antipattern. Even if this was good practice, JS isn't COBOL, so naming variables in all caps and calling `(resolve, reject)` `(FULFILL, BREAK)` would never fly in any PR or linter I know of.
Comment: @ggorlen--onLLMstrike has the right of it.
Answer: I didn't realized it directly by reading the other answers, but what is important is to evaluate your async function to turn it into a Promise.
So if you define your async function using something like:
let f = async () => {
    // ... You can use await, try/catch, throw syntax here (see answer of Vladyslav Zavalykhatko) ..
};

your turn it into a promise using:
let myPromise = f()

You can then manipulate is as a Promise, using for instance Promise.all([myPromise])...
Of course, you can turn it into a one liner using:
(async () => { code with await })()

Comment: This should be the top answer, it is actually what u want to do with the new Promise(async) thing, u jsut want to store the async and just call it, it's the same
Thank u for opening my eyes lol
Answer: static getPosts(){
    return new Promise( (resolve, reject) =>{
        try {
            const res =  axios.get(url);
            const data = res.data;
            resolve(
                data.map(post => ({
                    ...post,
                    createdAt: new Date(post.createdAt)
                }))
            )
        } catch (err) {
            reject(err);
        }
    })
}

remove await and async will solve this issue. because you have applied Promise object, that's enough.
Comment: No it won't, `res` will contain a promise and rest of the code will fail since `res.data` will be undefined.
Comment: So in your example, will `axios.get(url)` function as though it was called as `await axios.get(url)`?
Comment: This code is broken and misleading. Suggest deletion. Even if you _could_ magically avoid `async`/`await` with a `new Promise()`, it's still uglier than just using `async`/`await`.


Duvida Normalizer + Regex

Question: Alguem poderia me explicar o código abaixo?
returnStr = Normalizer.normalize(returnStr, Normalizer.Form.NFD)
    .replaceAll("[^\\p{ASCII}]", "");

returnStr tem como valor inicial uma url.
Comment: O `\p` possui um ancora negada `\P`, desta forma a regex poderia ser simplesmente `"\\P{ASCII}"`, não necessitando do `[^ ]`
Comment: mas porque "\\p" e não só "\p"? não entendi essa parte do regex
Comment: Pois se trata de um string, em string o caractere de `\ ` é um atalho para literal, desta forma p resultado final da conversão da string para REGEX é `[^\p{ASCII}]`, que a torna correta, se tive-se so um `\ ` ficaria `[^p{ASCII}]` e geraria um erro.
Answer: Analisando a sentença [^\\p{ASCII}]

Ela esta em um String que sera convertida em REGEX, e o \ em String é um caractere de escape, que torna próximo literal, assim apos a conversão o resultado sera [^\p{ASCII}].
[] significa uma cadeia que sera capturada, [^ ] é uma cadeia negada, ou seja em vez de capturar apenas o que se enquadra na cadeia, ele vai capturar tudo que não se enquadra.
\p*, assim como \w, \d, \x é uma ancora, serve para se escrever menos, em vez de fazer [A-Za-z0-9_] basta um \w
{ASCII} é uma condição para o \p, isso vai depender a biblioteca REGEX da linguagem/compilador que esta usando.

Nota
Usando o REGEX101, em Quick reference>Meta sequences temos o \p.

Corresponde a um caractere unicode que foi passado como parametro.

Nesta pagina temos alguns controladores suportados, contudo comparando com a tabela ASCII, nem todas as sentenças batem, isso porque a tabela ASCII só é padrão do 0-127, apos isso ela não segue um padrão absoluto então vai depender a linguagem que esta usando, por exemplo a pcre pelo que vi, não tem suporte ao {ASCII} do \p.
Adendo
O \p possui uma ancora negada \P, desta forma você poderia converte a String simplesmente para \\P{ASCII}, não necessitando da cadeia negada [^ ].
Answer: Analisando a expressão regular, trata-se de uma lista negada. Ele substituirá
qualquer ocorrência de caractere não ASCII por vazio (removerá).

Pegue a URL
Remova qualquer caractere não ASCII.

ASCII é uma tabela de caracteres, contendo letras números e símbolos e código computacional correspodente a ele.
Comment: A resposta esta certa, mas creio que ficaria melhor se explica-se o porque dele considerar caracteres ASCII, explicando que o `\p` se trata de uma "ancora/atalho" assim como `\x`, na qual creio que seja a real duvida do AP.
Answer: As outras respostas focaram em explicar a regex, mas faltou explicar a parte do Normalizer, e como ambos funcionam juntos.

Regex
Apenas para complementar/reafirmar, pois já foi coberto em detalhes pelas outras respostas, o atalho \\p{ASCII} está definido na documentação desta forma:
\p{ASCII}   All ASCII:[\x00-\x7F]

Ou seja, ele é equivalente a todos os caracteres da tabela ASCII (code points entre zero e 127, que acima estão escritos em hexadecimal: \x00 e \x7F). Para entender o que é um code point, leia aqui

Lembrando que a barra invertida é escrita como \\ por causa das regras de escape da linguagem.

Já o [^ ] é uma classe de caracteres negada (qualquer coisa que não seja o que está dentro dos colchetes). Por isso a expressão está pegando qualquer caractere que não seja ASCII (e como já dito em outra resposta, a expressão [^\\p{ASCII}] poderia ser trocada por \\P{ASCII} - com "P" maiúsculo).

Normalizer
Já o Normalizer serve para aplicar as normalizações Unicode em uma string. Para entender em detalhes, sugiro ler aqui, aqui e aqui (e para se aprofundar no assunto, pode ler todas as perguntas relacionadas).
Mas de maneira bem resumida, o Unicode define que alguns caracteres possuem mais de uma forma de serem representados. Por exemplo, o á (letra "a" com acento agudo) pode ser representado de duas formas:

composta - como o code point U+00E1 (LATIN SMALL LETTER A WITH ACUTE) (á)
decomposta - como uma combinação de dois code points (nesta ordem):

a letra "a" (sem acento): U+0061 (LATIN SMALL LETTER A)
o acento agudo: U+0301 (COMBINING ACUTE ACCENT)

A primeira forma é chamada NFC (Canonical Composition), e a segunda, NFD (Canonical Decomposition). As duas formas acima são consideradas "canonicamente equivalentes", quando se trata de representar a letra a com acento agudo. Ou seja, são duas formas de se representar a mesma coisa.
Portanto, Normalizer.normalize(returnStr, Normalizer.Form.NFD) está convertendo a string para a forma NFD. Se ela tiver caracteres acentuados, eles serão decompostos de acordo com a descrição acima: o á é decomposto em a e o acento agudo, õ é decomposto em o e o til, ç é decomposto em c e a cedilha, etc.
E como os caracteres que representam os acentos/cedilha não estão na faixa de valores do ASCII, o replaceAll acaba removendo-os, sobrando apenas as letras sem acentos/cedilha.
Portanto, o que esse código faz é remover os acentos e a cedilha (á, â, ã e á se tornam a, ç se torna c, etc). Ex:
String str = "opção";

// imprime "opcao"
System.out.println(Normalizer.normalize(str, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", ""));

Vale lembrar que a regex remove qualquer caractere que não seja ASCII, o que quer dizer que letras de outros idiomas, entre outros caracteres, como emojis, também serão removidos:
String str = "時opção";

// além dos acentos, também remove o caractere japonês e o emoji, e imprime "opcao"
System.out.println(Normalizer.normalize(str, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", ""));

Sem contar os milhares de caracteres "especiais" que o Unicode define, como os vários tipos diferentes de espaços, hífens, aspas, etc, muitos deles - a maioria, na verdade - fora da tabela ASCII, e portanto seriam removidos também.

Mas aí é claro que depende das strings que você tem. Se só tiver textos em português, por exemplo, não seria tão problemático assim. Mas se tiver outros caracteres não-ASCII que não deveriam ser removidos, aí teria que mudar a regex de acordo com cada caso. Um exemplo seria remover apenas os acentos, usando a categoria Unicode a qual eles pertencem, por exemplo:
Normalizer.normalize(str, Normalizer.Form.NFD).replaceAll("\\p{M}", "")

No caso, \\p{M} pega apenas as categorias Mark, Spacing Combining, Mark, Enclosing e Mark, Nonspacing, que possuem os caracteres de acentuação e a cedilha (não só os usados no português, clique nos links para ver a lista completa). Assim, emojis e letras de outros alfabetos são preservadas. Mas enfim, aí já foge um pouco do escopo da pergunta, é só para mostrar que regex não é algo mágico e depende muito de ajustes que variam conforme o contexto (ainda mais quando envolve essas propriedades Unicode).

Duvida Normalizer + Regex


r data.frame create a conditional column

Question: I have data as below. I want a new column called accuracy_level. How can I get it done? I tried if but it didn't work well.
If the

accuracy_percentage is within +/-10% then accuracy_level will be "Good"
accuracy_percentage is within +/-30% and outside +/- 10% then accuracy_level will be "Bad"
accuracy_percentage is outside +/-30% then accuracy_level will be "Worst"

Here is my code:
actuals=seq(0,10,0.1)
forecast=seq(10,0,-0.1)
data1=data.frame(actuals,forecast)
data1$diff=data1$actuals-data1$forecast
data1$accuracy_percentage=(data1$diff/data1$actuals)*100
if((data1$accuracy_percentage < 10)&(data1$accuracy_percentage > -10),data1$accuracy_level="good",)

Comment: You can use `ifelse` instead of `if/else` or better may be to use `cut` and specify the `labels`
Comment: the first row of your df has an `inf` value. `0.0
10.0
-10.0
-Inf`
Comment: Best practices are to use white space so you and others can read your code and you don't accidentally do `x<-1` when trying to test `x < -1`
Answer: data1$accuracy_level <- cut(abs(data1$accuracy_percentage), c(0, 10, 30, Inf), c("Good", "Bad", "Worst"), include.lowest=T)
#    actuals forecast diff accuracy_percentage accuracy_level
# 19     1.8      8.2 -6.4          -355.55556          Worst
# 71     7.0      3.0  4.0            57.14286          Worst
# 57     5.6      4.4  1.2            21.42857            Bad
# 17     1.6      8.4 -6.8          -425.00000          Worst
# 92     9.1      0.9  8.2            90.10989          Worst
# 91     9.0      1.0  8.0            88.88889          Worst
# 13     1.2      8.8 -7.6          -633.33333          Worst
# 79     7.8      2.2  5.6            71.79487          Worst
# 44     4.3      5.7 -1.4           -32.55814          Worst
# 51     5.0      5.0  0.0             0.00000           Good

Using cut will give you a boost in speed and scalability. We find the intervals of the absolute values, abs, of the accuracy percentages based on the cut points c(0, 10, 30, Inf). And supply labels for the groups. We also add the argument include.lowest=TRUE for 0.000 cases which fall on the lower limit of our cut points.
Nested ifelse statements are used because they are easy to understand when read out. But if you had to nest 10 different conditions, it could easily get out of control.
As a note, if we did not require new label names, we could have used the related function findInterval which would essentially do the same thing with the difference of assigning integer values as output (i.e. 1 2 3 4..).
Answer: I used a compound ifelse
data1$accuracy_category <- ifelse(abs(data1$accuracy_percentage)<10, "Good",
                                  ifelse(abs(data1$accuracy_percentage)<30, "Bad", "Worst"))

yields
> head(data1)
  actuals forecast  diff accuracy_percentage accuracy_category
1     0.0     10.0 -10.0                -Inf             Worst
2     0.1      9.9  -9.8           -9800.000             Worst
3     0.2      9.8  -9.6           -4800.000             Worst
4     0.3      9.7  -9.4           -3133.333             Worst
5     0.4      9.6  -9.2           -2300.000             Worst
6     0.5      9.5  -9.0           -1800.000             Worst

and as pointed out by @pierre-lafortune, it is easier to read but less performant. In the spirit of Knuth I ran some tests. With your initial set:
> system.time(data1$accuracy_category <- ifelse(abs(data1$accuracy_percentage)<10, "Good",
+ ifelse(abs(data1$accuracy_percentage)<30, "Bad", "Worst")))
   user  system elapsed
      0       0       0
> system.time(data1$accuracy_level <- cut(abs(data1$accuracy_percentage), c(0, 10, 30, Inf), c("Good", "Bad", "Worst"), include.lowest=T))
   user  system elapsed
  0.000   0.000   0.001

but that isn't really telling. So let's crank it up :) With
actuals=seq(0,100000,0.1)
forecast=seq(100000,0,-0.1)

I got
> system.time(data1$accuracy_category <- ifelse(abs(data1$accuracy_percentage)<10, "Good",
+ ifelse(abs(data1$accuracy_percentage)<30, "Bad", "Worst")))
   user  system elapsed
  0.776   0.060   0.840
> system.time(data1$accuracy_level <- cut(abs(data1$accuracy_percentage), c(0, 10, 30, Inf), c("Good", "Bad", "Worst"), include.lowest=T))
   user  system elapsed
  0.152   0.003   0.155

which does show that the cut will be much more performant as you scale up. All of that said, the cut is more elegant if not less readable, and I upvoted his answer :) ymmv.


AutoMenu and Tokens

Question: I am working in Drupal 6.22 and want to know if anybody knows of a way to get tokens working with the AutoMenu module?  Its become a bit of an issue from a usability perspective and want to have this working with my breadcrumbs (using menu_breadcrumb).
For instance I have the ability to create multiple galleries, which fall under /media/galleries/[gallery-title-raw], and the breadcrumb reads accordingly as Home > Media > Galleries > [gallery-title-raw]. It would make sense then for individual photos (photo node) to fall under its parent gallery. So when a user navigates to the full node for the photo, the breadcrumb should read: Home > Media > Galleries > [gallery-title-raw] > [photo-title-raw] and a hidden menu item for the photo is automatically created.
Here's hoping that someone out there found a way to make this work :)
Cheers!
Answer: The Custom Breadcrumbs module integrates nicely with tokens and allows for per content type breadcrumb trails.  If your photos are linked to your gallery via a nodereference or something else that already has a token, using Custom Breadcrumbs would work without any coding.  If you are using a gallery solution where the photo content type doesn't have a token for the gallery it is associated with, you will have to implement the Token module's hooks to add that data as an available token for use in Custom Breadcrumbs.
Comment: Hi Chris, thanks! I'll take a look at Custom breadcrumbs and see if it can do what menu_breadcrumb does, plus the little extra bit I require. Trying to looking through the code to see if I can perhaps submit a patch.

AutoMenu and Tokens


How to copy/paste shape using Shell Application?

Question: I'm trying to export a single image to a folder.
I inserted the image manually in the workbook, and renamed the shape 'logo'.
I've used something similar earlier, but perhaps it only works with OLEObjects?
ThisWorkbook.Sheets("Start Here").Shapes("logo").Copy
CreateObject("Shell.Application").Namespace(ThisWorkbook.Path & "\").Self.InvokeVerb "Paste"

The code runs, but the object isn't 'pasted' to the destination directory.
Answer: Sub test()
Dim chtObj As ChartObject

    With ThisWorkbook.Worksheets("Start Here")

        .Activate

        Set chtObj = .ChartObjects.Add(100, 30, 400, 250)
        chtObj.Name = "TemporaryPictureChart"

        'resize chart to picture size
        chtObj.Width = .Shapes("logo").Width
        chtObj.Height = .Shapes("logo").Height

        ActiveSheet.Shapes.Range(Array("logo")).Select
        Selection.Copy

        ActiveSheet.ChartObjects("TemporaryPictureChart").Activate
        ActiveChart.Paste

        ActiveChart.Export Filename:=ThisWorkbook.Path & "\image.jpg", FilterName:="jpg"

        chtObj.Delete

    End With

End Sub

Updated code from Export Pictures Excel VBA


How can I redirect node page for a content type to custom URL?

Question: I need to redirect all the pages for a content type to a custom URL in Drupal 8.
I used to do this in Drupal 7 by implementing hook_init() with the function drupal_goto() or by using the Rules module. Unfortunately both hook_init() and drupal_goto() are removed in Drupal 8, and the Rules module is not stable yet, and I can't figure out how to do it in Drupal 8.
How can I achieve what I am trying to do?
Comment: You should look at the [Change Records](https://www.drupal.org/list-changes/drupal) to learn about alternatives to removed functions/hooks. Specifically https://www.drupal.org/node/2013014 has an example extremely similar to what you are trying to do.
Comment: Thanks @mradcliffe, actually I already tried to add Event Subscriber like in   https://www.drupal.org/node/2013014 but the problem was in detecting the content type of the node in the node page. anyway, I managed to solve this issue and I added an answer :)
Answer: Here is how I managed to solve this issue, based on the example in drupal.org/node/2013014:
I registered Event Subscriber in my_redirect_module.services.yml file:
   services:
     my_redirect_module_event_subscriber:
     class: Drupal\hbmsu_redirect\EventSubscriber\MyRedirectModuleSubscriber
     tags:
       - {name: event_subscriber}

and then in the file my_redirect_module/src/EventSubscriber/MyRedirectModuleSubscriber.php
I added this code:
  namespace Drupal\my_redirect_module\EventSubscriber;

  use Symfony\Component\HttpFoundation\RedirectResponse;
  use Symfony\Component\HttpKernel\KernelEvents;
  use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  use Symfony\Component\EventDispatcher\EventSubscriberInterface;

  class MyRedirectModuleSubscriber implements EventSubscriberInterface {

      public function checkForRedirection(GetResponseEvent $event) {

          $baseUrl = $event->getRequest()->getBaseUrl();
          $attr = $event->getRequest()->attributes;
          if(null !== $attr &&
             null !== $attr->get('node') &&
             $attr->get('node')->get('type')->getString() == 'my_content_type') {
              $event->setResponse(new RedirectResponse($baseUrl.'/some_internal_url_path'));
          }
      }

      /**
       * {@inheritdoc}
       */
      static function getSubscribedEvents() {
          $events[KernelEvents::REQUEST][] = array('checkForRedirection');
          return $events;
      }

  }

in checkForRedirection function, I'm checking if the page is for a node with the content type my_content_type, then redirect to the page mywebsite.com/some_internal_url_path
Comment: For me this broke node editing. To fix, assert `$attr->get('_entity_form') !== 'node.edit'` before redirecting.
Comment: As per @LincolnBergeson, there should be a test for node "sub-tabs", Josh Fremer has a nice clean walkthrough here: https://www.thirdandgrove.com/redirecting-node-pages-drupal-8
Comment: Works fine, though GetResponseEvent is deprecated since Symfony 4.3, use RequestEvent instead
Answer: If you need to redirect from a custom form or an existing form (login, logout,...)=> (I assume this is what you want as you ask redirecting from a content type, I think you mean "after editing a content type");
then you can use
$form_state->setRedirect('user.page');

you can add this code in your form_alter, form_submit functions of your content type that you need to redirect
You can find some doc: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Form!FormSubmitterInterface.php/function/FormSubmitterInterface%3A%3AredirectForm/8.2.x
Like this example:
$form_state->setRedirect('entity.node.canonical',
 array('node' => 123),
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),

));
Comment: Thanks @Baud, actually in my case I don't have form submission. I wanted to redirect all the node pages for certain content type to another page created with Views has a list of all these contents. anyway, I found the solution for this issue and I added an answer here :)
Answer: You can use Rabbit hole and Token modules. With Rabbit hole you will be able to set a Page Redirect for the content type, and with Token you can choose a field where users will be redirected when they try to access to a node.
Comment: If the nodes need to be secure, rabbit hole is the better option. It will block the node on more levels than what you could do with only using a Subscriber.
Comment: Yes, Rabbit hole module. Superb.. also one more module available https://www.drupal.org/project/node_view_redirect
Answer: You can install Entity Redirect module
That module provides a UI configurable redirect after saving a node or other entity and works for both Drupal 8, 9, 10.
Provides four different types of redirection:
Default: This will not impact the entity but will just go to the default.
Add Form: Redirect to a new add form for the content type/entity.
Local Url: provide a local url in the form of /about to go to any page on the site.
External Url: Same as local url but to an external location. Note: this is only available to users with the permission set external entity redirects.

. For example for the Node type Article that would be at /admin/structure/types/manage/article, click on Publishing options, you will see a REDIRECT AFTER ENITY OPERATIONS


Infinite intersection of sets of multiples of naturals

Question: There is a example in my Set Theory Book that is giving me trouble:
$$\cap_{i=10}^{\infty}D_i=\emptyset, D_i=multiples\;of\;i\;in\;\mathbb{N}.$$
For me, every time I do and intersection, there will be aways a set of numbers that will be there, since I can just multiply tem for the intersected number (i).
I have shown something like these:
$$D_{10}\cap D_{11}\dots D_x=\cap_{i=10}^x=\{z:z=10.11.12(\dots).x.m\;|\;m\in\mathbb{N}\},$$
and then tryed to limit this to $\infty$. But I don't know how to finish it without bias.
Comment: Isn't it enough to note that that $i \notin D_{i+1}$. (And also that none of the numbers less than 10 are in $D_{11}$.)
Comment: BTW, I added my comment, which uses a completely different approach than yours, because I don't think your approach of characterizing the finite intersections can be completed to answer the infinite intersection question. Happy to be proved wrong, but that's my guess.
Answer: Take an $x\in\bigcap_{i=10}^\infty D_i$, then for every $i\geq 10$ we have $x\in D_i$, so $i$ has to divide $x$. If we use $0\notin\mathbb{N}$ then we can conclude $i\leq x$ for every $i\geq 10$. Since $x\in\mathbb{N}$ and $\infty\notin\mathbb{N}$, there is no such $x$. Therefore $\bigcap_{i=10}^\infty D_i=\emptyset$.
There is a different proof using the limits you mentioned:
\begin{equation}
\limsup_{i\rightarrow\infty}D_i
=\bigcap_{i\geq 1}\bigcup_{j\geq i}D_j
=\bigcap_{i\geq 1}\{n\in\mathbb{N}|n\geq i\}=\emptyset
\end{equation}
\begin{equation}
\bigcap_{j\geq 10}D_j
\subseteq\bigcup_{i\geq 1}\bigcap_{j\geq i}D_j
=\liminf_{i\rightarrow\infty}D_i
\subseteq\limsup_{i\rightarrow\infty}D_i=\emptyset.
\end{equation}


Como obter o tipo específico de erro retornado pelo EntityFramework?

Question: Seguindo a pergunta: Como interceptar exceções quando se trabalha com o Entity Framework?
É possível obter algum identificador de tipo de erro? Como por exemplo, Violação de Chave Primária, Inconsistência de Chave Estrangeira e, no meu caso específico, quando é uma violação de chave única.
Enfim, trabalhando com EntityFramework estou interceptando as exceções lançadas da seguinte forma:
try {
    ...
}
catch (DbUpdateException e) {
    TempData["Mensagens"] = "Ocorreu um erro enquanto ...";
}

Como identificar o tipo de erro específico do EF e então poder tratar a mensagem?
Answer:
Assim:
try {
    ...
}
catch (DbUpdateException e) {
    switch (((SqlException)e.InnerException.InnerException).Number)
    {
             case 547:
                 {
                     //FK exception
                     TempData["Mensagens"] = "Chave Estrangeira";
                 }
             case 2627:
             case 2601:
                 {
                     //primary key exception
                     TempData["Mensagens"] = "Chave Primária";
                 }
             default:
                 {
                     TempData["Mensagens"] = "Erros";
                 }
    }
}

Ai você coloca a mensagem de sua preferência.
Todos os erros contidos no MSDN Microsoft Developers - System Error Messages
Referência:

Handle exceptions in entity framework 4
System Error Messages
Comment: Sim, pelo que eu entendi sim os erros seguem um padrão, isso é bom, porque ai não depende do banco
Comment: @TremDoido, vou fazer uma pesquisa mais profunda e conversar com uma galera sobre o entity e seus exceptions se descobri coisa nova te aviso no (@)
Comment: http://msdn.microsoft.com/en-us/library/cc645603(v=sql.105).aspx olha isso ...
Comment: Entendi vou editar


laravel 5.2 project is not working on production server

Question: Working on laravel project, facing issue on production server, my project is working on my local, but when i uploaded it on server its not responding anything , it shows blank screen, not event any error.
When i did debugging i echo things in public/index.php file and found that its not printing anything after a particular code.
<code>$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);
print('Hello');
</code>
Afdter this code in index.php its not executing print function above this code it executes print function, it means my project is able to getting request.
I am accessing my project using
<code>domain.com/public
</code>
I am new to laravel so don't have much understanding about this framework.
Answer: Change permissions in your server after su or after root login
chown -R:www-data path_to/storage
chmod 775 path_to/storage
And I reccomend not put your app under domain.com/public, instead point your server configuration webroot to /var/www/laravel/public


Strange behavior of fsck

Question: I am using Debian 7 with two HDDs: 500Gb PATA and 750Gb SATA.
blkid shows me the following:
root@intel:/etc# blkid
/dev/sda1: UUID="b6350c6b-5fbd-4e07-9a4b-10b600fbb64c" TYPE="swap"
/dev/sda2: UUID="2f852e13-38ee-4b56-a474-d675c22d5f28" TYPE="ext4"
/dev/sda3: UUID="78e34fe3-365c-4c4d-86b8-51615641f9ec" TYPE="ext4"
/dev/sdb1: LABEL="data" UUID="03c3f01f-d390-49de-a570-3de4b73a9fea" TYPE="ext4"

content of fstab:
root@intel:/etc# cat /etc/fstab
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda2 during installation
UUID=2f852e13-38ee-4b56-a474-d675c22d5f28    /               ext4    errors=remount-ro  0       1
# /home was on /dev/sda3 during installation
UUID=78e34fe3-365c-4c4d-86b8-51615641f9ec    /home           ext4    defaults       0       2
# /data was on /dev/sdb1
UUID=b6350c6b-5fbd-4e07-9a4b-10b600fbb64c    /data       ext4    defaults       0   2
# swap was on /dev/sda1 during installation
UUID=03c3f01f-d390-49de-a570-3de4b73a9fea    none            swap    sw         0       0
/dev/sr0        /media/cdrom0   udf,iso9660 user,noauto     0       0

System can't boot until I comment out /dev/sdb1. The fsck fails to check filesystem:
root@intel:/etc# fsck /dev/sdb1
fsck from util-linux 2.20.1
fsck: fsck.swap: not found
fsck: error 2 while executing fsck.swap for /dev/sdb1

but after boot with commented
# /data was on /dev/sdb1
UUID=b6350c6b-5fbd-4e07-9a4b-10b600fbb64c    /data       ext4    defaults       0   2

line of fstab I can mount /dev/sdb1.
The only one question is "What's happening?". Is my 750Gb HDD dying? How can I check /dev/sdb1?
Best regards.
Comment: When you say that after boot you can mount `/dev/sdb1`, could you tell us **exactly** what command you're using to mount it?
Comment: `mount /dev/sdb1 /mnt` works fine.
Answer: Your blkid shows that /dev/sdb1 is an ext4 filesystem (and by you trying to mount it, suggests it is) however, your fstab disagrees:
# swap was on /dev/sda1 during installation
UUID=03c3f01f-d390-49de-a570-3de4b73a9fea    none            swap    sw         0       0

And your UUID matches /dev/sdb1 as you showed with blkid:
/dev/sdb1: LABEL="data" UUID="03c3f01f-d390-49de-a570-3de4b73a9fea" TYPE="ext4"

During boot, it is trying to use /dev/sdb1 as it's swap partition and does an fsck.swap /dev/sdb1 which fails since it's not a swap partition.
You should be able to fsck it with fsck.ext4 /dev/sdb1 and you'll need to edit your fstab to reflect the REAL swap parition's uuid.
It appears you just have your two UUIDs switched around:
UUID=b6350c6b-5fbd-4e07-9a4b-10b600fbb64c    /data       ext4    defaults       0   2
UUID=03c3f01f-d390-49de-a570-3de4b73a9fea    none            swap    sw         0       0

vs
/dev/sda1: UUID="b6350c6b-5fbd-4e07-9a4b-10b600fbb64c" TYPE="swap"
/dev/sdb1: UUID="03c3f01f-d390-49de-a570-3de4b73a9fea" TYPE="ext4"

Comment: Yep. I found it too just after writing a question. But I don't know why it's happened. Thank you for your answer.
Answer: Check your partition table with cfdisk or similar tool. Chances are the partition type of /dev/sdb1 is set to "Linux swap" instead of "Linux".
In order to check the partition directly, call e4fsck /dev/sdb1.

Strange behavior of fsck


How can I change the label for the vote button?

Question: I am using poll module in my site. Everything is working fine. But the submit button(label) is "vote", I want to change it to "Submit". How can i change this? And this is a block.
Answer: You need to implement hook_form_alter() for altering the poll_view_voting form and change #value from Vote to Submit.
function mymodule_form_poll_view_voting_alter(&$form, &$form_state, $form_id) {
  $form['vote']['#value'] = t('Submit');
}


Cross Browser issues with Center Align

Question: I'm new to coding, and I am having problems making the page appear correctly on all browsers. Right now it works perfectly with IE, but I lose formatting when I open in in Firefox or Chrome.
This is an excerpt of the code I'm using:

 <form action="https://test.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">

<input type=hidden name="oid" value="00DK0000005Iu4O">
<input type=hidden name="retURL" value="http://www.vela-ins.com">

First Name
<input  id="first_name" maxlength="40" name="first_name" size="20" type="text" />

Last Name
<input  id="last_name" maxlength="80" name="last_name" size="20" type="text" />

Email
<input  id="email" maxlength="80" name="email" size="20" type="text" />

Phone
<input  id="phone" maxlength="15" name="phone" size="20" type="text" />

Company
<input  id="company" maxlength="40" name="company" size="20" type="text" />

City
<input  id="city" maxlength="40" name="city" size="20" type="text" />

State/Province	<input  id="state" maxlength="20" name="state" size="20" type="text" />

</select>
</form>

Comment: Yes. Please tell us which error you are asking about. Which code piece exactly does not work as expected? Please put only the relevant code in the question, and use the whole code for a demo (on your domain, jsfiddle, jsbin or wherever) only.
Comment: I've been coding for about a week, so I'm sure there are plenty of errors in here. Sorry!
Answer: To center the table, remove those centerspacer cells from the markup, and use only
table {
    margin-left: auto;
    margin-right: auto;
}

Besides, you have a syntax error in your css declaration for label, which will crash any following styles. Check your browser's error console!
Answer: For relatively positioned elements:
margin:0 auto;

For everything else:
http://jqueryui.com/position/

Cross Browser issues with Center Align


How to display iPhone contacts like path

Question: How to display iPhone contacts with email like path application.
I tried following code, its show the contacts name, when I click the contact it navigate to contact details page. But, I need to display contacts in table view then user click customer row the dialog box is open it contain contacts email like path application.
<code>var values = {cancel:function(){}};
values.fields = ['firstName', 'lastName', 'phone', 'email'];

values.selectedProperty = function(e) {
    if(e.property == 'email')
    {
        alert(e.person.email);
    }
 };
$.contactWin.addEventListener('open', function(e){
   Titanium.Contacts.showContacts(values);
});
</code>
Answer: Take a look at this link. It will show you how you can get contacts from contacts then you can create a table with custom row as you want.
http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.Contacts


Inferential statistics for multiple classes / groups

Question: I have data regarding calls to a company. Only a small proportion of calls are classified into about a hundred different categories by a group of humans. The volume of calls is in the range of hundreds of thousands and only a few thousand calls are classified. I would like to estimate the proportions of each class in the population of calls using inferential statistics.
I have read a lot about inferential statistics but it seems like all the tutorials out there are about estimating the mean from sampling distributions, but there are only 2 classes - success or fail.
I cannot find anything to help estimate the proportions with more than 2 classes. Perhaps I am using the wrong keywords? Any help would be greatly appreciated. Thank you.
Answer: I think in your case you would need to fit a multinomial distribution (generalisation of binomial distribution for more than 2 classes), whose parameter is a vector of probabilities $\pi= (\pi_1, ..., \pi_k)$ where $k$ is the number of different classes. An easy way to estimate these probabilities is to comupte the different proportions of calls in the different categories among all the calls which are already classified(these proportions actually give the maximum likelihood estimator of $\pi$). You can then give confidence interavals, make tests, etc.
If you have explanatory variables you would like to use to estimate proportions, then you can go for a mulitnomial (or polytomous) logistic regression.


Add a class to a field based on the page regions

Question: I have my field tpl file which sets in a div classes 'field-item', 'odd/even' etc. I need to dynamically assign a class to it based on the regions that exist on the page. I am using bootstrap theme and the class I need to add reflects the column span count, so f I have a sidebar on the left I will have less space for that field and need a narrower column class.
Bootstrap already comes with a function doing it for page preprocess:
<code>function mytheme_preprocess_page(&$variables) {
  // Add information about the number of sidebars.
  if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
    $variables['columns'] = 3;
  }
  elseif (!empty($variables['page']['sidebar_first'])) {
    $variables['columns'] = 2;
  }
  elseif (!empty($variables['page']['sidebar_second'])) {
    $variables['columns'] = 2;
  }
  else {
    $variables['columns'] = 1;
  }
</code>
So basically what I need is to make my field aware of that page variable. How can I use this variable on my field tpl file?
Answer: A quick look shows that the content region is wrapped in a class derived from that $columns variable, getting it from this function...
<code>/**
 * Returns the correct span class for a region
 */
function _bootstrap_content_span($columns = 1) {
  $class = FALSE;

  switch($columns) {
    case 1:
      $class = 'span12';
      break;
    case 2:
      $class = 'span9';
      break;
    case 3:
      $class = 'span6';
      break;
  }

  return $class;
}
</code>
...so you should be able to use the cascading features of CSS to theme your field, eg...
<code>.span12 .your-field-stuff {
  /* widescreen */
}

.span9 .your-field-stuff {
  /* one sidebar */
}

.span6 .your-field-stuff {
  /* two sidebars */
}
</code>


Time series grouping for detecting market cannibalism

Question: I'm dealing with daily sales of products in a supermarket.
Together with the historical data I have promotions for each product and weather data. What I lack is data about stock in and stock out of products.
In particular the stock out I miss for a product $i$ at time $t$  (say Pepsi)
 $Y_{i_t}$ could correspond to a spike in sales for a similar product $j$ at the same time $t$ (say Coke) $Y_{j_t}$ , where $t$ denotes a day.
Basically I want to find clusters of the same kind of products so that I know how to redistribute the items over similar products, avoiding other stock outs of the similar products, what is called Market Cannibalism
I don't have data on the amount of time the supermarket need to restock the items stocked out, but I hope they don't restock the items daily, since at that point I could not use the information for forecasting.
Thank you :)
Comment: what do you mean clusters ? Are you trying to use models/coefficients to determine commonality ? An outlier in one series could coincide with an outlier in another series reflecting the cannibalism effect..To identify this you would need very informative models .
Comment: Hi @IrishStat, I would say that I have a latent hierarchical structure of my products. For now I have been using as a distance the weighted Euclidean distance between the simple autocorrelation ( dist.ACF) or partial autocorrelation ( dist.PACF ) coefficients, and the Pearson correlation distance, through the TSclust package.
Comment: acf/pacf are correlations . correlations can be severe;y afftected by anomalies see http://stats.stackexchange.com/questions/245931/is-there-a-version-of-the-correlation-coefficient-that-is-less-sensitive-to-outl/245935#245935 . This post has set a personal record for me ( 4 down votes) . All without cause AFAIAC . You may have a similar need to obtain robust estimates of the acf/pacf unaffected by exceptional activity for your grouping. If you like my response to that question by all means give it an uptick as I am currently demoralized Just kidding I think I will make it through the day ..
Comment: @IrishStat Thank you again! I'll read that and wait for other answers here before ticking this question
Comment: I didn't mean this question I was referring to the one I pointed to requesting advice on a robust correlation coefficient. You certainly should leave your question open as it invites help from a large audience
Answer: I'm mostly answering how and why the available data can be sufficient. This is what I understand your question to be about.
Don't worry too much, you have the most important data available. I'm not sure if you have a background in statistics and time series and have now been assigned this task or if you have a background in supply chain management. Please don't feel insulted if I explain familiar concepts to you.
You do not have data about how much stock came in at what moment. There are a couple of ways to manage stocks, one or a combination of which will probably have been used in the past:

It could have been an economic order quantity (EOC) per SKU (which determines the restocking frequency at a given level of demand) combined with a safety stock per SKU.
It could have been a kanban system with two containers where you order a new container as soon as you open the last one in stock. (If deliveries are in fixed intervals, not every SKU can be on its EOC. Some will typically be on a kanban system.)
Some inventory could be managed by your suppliers. (This happens when sales for a particular product are very difficult to predict and the supplier has better demand forecasts)

Even if you do not have the past data about stock intake, you should be able to find out with which policies this supermarket operates. This tells you enough about stock intake to construct your model and get actionable recommendations from it.
Regarding stockouts, you do not crucially need data about past stockouts per SKU per day I think. You can find your clusters using data about sales per day per SKU. This data you should have, right? (I couldn't imagine a supermarket who doesn't log this data.) I don't understand why you would want to find clusters based on stockouts in the first place. Stockouts are a delayed consequence of exceptional demand, at best a proxy for measuring demand. You have the direct data of this demand (daily sales), base your clusters on that data.
Comment: well said ..good advice ..
Comment: Thank you!

To further explain: I'm not trying to find clusters based on stockouts. I'm trying to find groups of products which are similar in the sense that being one not available the consumer usually buys the other and viceversa. How do I detect this? If I know one product was stocked out and I see rises in other similar product sales I may infer that those similar product have answered the demand for the first one. Another causal factor could be a promotion which causes up-spikes in the demand of the product promoted and down-ones in the similar products.
Comment: In your first example you describe substitutes. While they can be found in the way you suggest, they could also manifest through joint periods of high sales. You have the data to look in the second way, not in the first way. Your second example describes complementary products. When you buy more of both when one is on promotion, it means you use them together (not that one replaces the other). This is not the same concept. You could find complementary products through frequent item set mining.
Comment: @user7019377 what do you mean with "they could manifest through joint periods of high sales" in reference to substitutes? If I have joint periods of high sales I would have low residuals for any of the products (if I don't expect the spike in the demand).
I didn't consider whether a promotion could positively affect other products not in promotion (frequent set mining), but intuitively I would expect a negative correlation when a promotion occurs.
What I'm doing right now is checking the residuals of my univariate fitted models and see whether a big residual corresponds to a compensation
Comment: effect in other *similar* products residuals..
by the way, thank you for your answers, I was able to know that there is the possibility of a daily restock for my items
Comment: You should refresh the notions of substitutes and complementaries. What you state as your intuition is how substitutes manifest, complementary products manifest in the opposite way to price changes. As for substitutes, you can detect them by linking sales of product X to low inventory or stockout of Y. You can also link high sales of X to high sales of Y. If you only consider substitution of X by Y after X is gone, you assume Y is an inferior substitute. Clients may also be more or less indifferent between X and Y, or their individual preferences could average out.