Want to show image caotion or title above portfolio image

Question: For a recently developed wordpress website http://stc.co.in, I'm using Huge-IT portfolio to show the projects in each sectors. On clicking on projects a popup is showing with multiple images. Now I want to show image caption or title above the big image which was added while uploading image through WordPress. Please guide how to achieve this.
Thanks in advance.
Regards, Sanjay
Answer: If the plugin cant let you do it simply with text editor, in wordpress you need to search the specific section you want and work on php file.
When you have founded it you can put an html section with your title.
Comment: Thanks Andrew. I traced the php file section, but how to fetch the image title and add to it?
image_url != ';'){ ?>

Comment: @vrajesh answered you with a great big image...follow his advice. hope you resolve your problem
Answer: you need to made changes in plugin file..
follow path :

wordpress-sitename/wp-content/plugins/portfolio-gallery/Front_end/portfolio_front_end_view.php

modify line :
   <ul id="huge_it_portfolio_popup_list_<?php echo $portfolioID; ?>">
    <?php
    foreach($images as $key=>$row)
    {

        $imgurl=explode(";",$row->image_url);
        array_pop($imgurl);
        $link = $row->sl_url;
        $descnohtml=strip_tags($row->description);
        $result = substr($descnohtml, 0, 50);

        ?>
        <li class="pupup-element" id="huge_it_portfolio_pupup_element_<?php echo $row->id; ?>">

            <div class="heading-navigation_<?php echo $portfolioID; ?>">

            <div class="popup-wrapper_<?php echo $portfolioID; ?>">
                <div class="image-block_<?php echo $portfolioID; ?>">
                <?php   if($paramssld["ht_view2_show_popup_title"]=='on'){?>
<?php echo $row->name; ?>
<?php } ?>
                    <?php   if($row->image_url != ';'){ ?>
                    <img alt="<?php echo $row->name; ?>" id="wd-cl-img<?php echo $key; ?>" src="<?php echo $imgurl[0]; ?>" />
                    <?php
                                        global $wpdb;
                                    $cimg_url = $imgurl[0];
                                    $attachment = $wpdb->get_results("SELECT ID FROM wp_posts WHERE guid='".$cimg_url."'",'ARRAY_A');
                                    $attachment_title = get_the_title($attachment[0]['ID']);

                    ?>

<?php echo $attachment_title; ?>

                    <?php } else { ?>
                    <img alt="<?php echo $row->name; ?>" id="wd-cl-img<?php echo $key; ?>" src="images/noimage.jpg" />
                    <?php
                    } ?>

                    <?php if($paramssld["ht_view2_show_popup_title"]=='on'){?>
<?php echo $row->name; ?>
<?php } ?>

                    <?php if($paramssld["ht_view2_thumbs_position"]=='before' and $paramssld["ht_view2_show_thumbs"] == 'on'){?>

<ul class="thumbs-list_<?php echo $portfolioID; ?>">
                        <?php
                                global $wpdb;
                                foreach($imgurl as $key=>$img){
                                    $cimg_url = $img;
                                    $attachment = $wpdb->get_results("SELECT ID FROM wp_posts WHERE guid='".$cimg_url."'",'ARRAY_A');
                                    $attachment_title = get_the_title($attachment[0]['ID']);
                        ?>

<a href="<?php echo $row->sl_url; ?>" class="group1" data-ttl="<?php echo $attachment_title; ?>" >
                                    <img src="<?php echo $img; ?>">

                                <?php } ?>

                    <?php } ?>

                    <?php if($paramssld["ht_view2_show_description"]=='on'){?>
<?php echo $row->description; ?>
<?php } ?>

                    <?php if($paramssld["ht_view2_thumbs_position"]=='after' and $paramssld["ht_view2_show_thumbs"] == 'on'){?>

<ul class="thumbs-list_<?php echo $portfolioID; ?>">
                        <?php   $imgurl=explode(";",$row->image_url);array_pop($imgurl);
                                foreach($imgurl as $key=>$img){?>

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

                                <?php } ?>

                    <?php } ?>

                    <?php if($paramssld["ht_view2_show_popup_linkbutton"]=='on'){?>

                        <a href="<?php echo $link; ?>"  <?php if ($row->link_target=="on"){echo 'target="_blank"';}?>><?php echo $paramssld["ht_view2_popup_linkbutton_text"]; ?>

                    <?php } ?>

        <?php
    }?>

JS:
jQuery('#huge_it_portfolio_popup_list_<?php echo $portfolioID; ?> .popup-wrapper_<?php echo $portfolioID; ?> .right-block ul.thumbs-list_<?php echo $portfolioID; ?> li a').click(function(){
        var width=jQuery(window).width();
        if(width<=767){
            jQuery('body').scrollTop(0);
        }
        jQuery(this).parent().parent().find('li.active').removeClass('active');
        jQuery(this).parent().addClass('active');
        var main_img_ttl =  jQuery(this).attr('data-ttl');
        alert(main_img_ttl);
        jQuery(this).parents('.right-block').prev().find('.cls_img_ttl').html(main_img_ttl);
        jQuery(this).parents('.right-block').prev().find('img').attr('src',jQuery(this).find('img').attr('src'));
        return false;
    });

you can download file here : LINK
Comment: Thank you Vrajesh,
$row->name is the project title which is already showing in the right side of the popup. I want to show the caption or title of each image which was added while uploading images through media library.
Comment: Not the file name, but there are 4 textboxes given while uploading image through portfolio plugin. which is title, caption, Alt text & Description. I want to show that particular title for each image. Hope you understood.
Comment: Thanks a lot Vrajesh, I need it for the big image only, not for the thumbnails. appreciate your help.
Comment: you can get it easily
Comment: hope you get your solution..i have updated my answer ..this is my last try :)
Comment: Thanks a lot for the time taken to help me. But this didn't solved the purpose as it is now showing the sector name for all big images.
Comment: so you want to put for perticular image?
Comment: For example there are three thumbnails in the popup. On clicking on each thumbnail it will show the bigger image. I want to show the bigger image along with the particular image title above the bigger image....
Comment: if you get your answer ..please up vote and right..thx..hope you appreciate my effort..
Comment: Sure, Let me try this.
Comment: Sorry vrajesh, It didn't helped. Now also it is only showing the sector heading like "Water Supply" for all images in the particular sector. If you can help I'll create a temp. development copy on my server and share with you personally. Anyway, Thanks a lot for your time and effort.
Comment: Please provide your mail ID/Skype ID


Is there a way to make a square wave sound more like an instument in a simple circuit?

Question: Basically I've built a simple circuit that outputs a square wave of different frequencies (i.e. a DIY tone generator), but it obviously sounds very robotic. Are there any small, simple devices that could take an input of a certain frequency and output something that sounds more like an instrument?  Like a single note played on a piano or a bell corresponding to the frequency input.  This is just a simple DIY side project so I'm trying not to have anything too large or expensive.
I know very little about electronic sound generation so sorry if this has an obvious answer; I haven't been able to find anything through google.
Comment: This probably would be a better fit for https://dsp.stackexchange.com/ or https://electronics.stackexchange.com/
Comment: You're doing the wrong search. A Google search for "sound synthesis" turns up lots of articles
Comment: The question as asked does not make a lot of sense.  The "square" wave will have some harmonic content.  An "instrument" will have some other harmonic content.  You cannot make one sound like the other except to alter the first so that it is no longer a square, which defeats the point.
Comment: @ggcg as I read it, rather than defeating the point, that *is* the point? Perhaps hard to do with something small/simple though.
Answer: More electronics than music but try playing with some capacitors.  In parallel with the load, these could dampen the high harmonics of the square wave and round off its edges.  A variable capacitor would let you play with the effect.  You'd need to judge yourself whether your existing circuit would tolerate this addition.  Start with a small value capacitor and work up until either you get the sound you want or your circuit burns out.
Answer: My thought would be....what if you add many square waves together?
What sound would you get?
Try your circuit with many different parameters added together.
I believe, most instruments make sounds more like a sine wave but with many harmonics.
Comment: Needs, at minimum, an envelope generator. Still way off-topic for here.
Comment: @Tetsujin "describe the required function and setting in which the equipment will be used, and ask what you should look for to achieve that" is one of the equipment question formats allowed here - does this not fit that, in your opinion?
Answer: You may want to look into audio-to-MIDI conversion. If you can convert your square wave to a stream of MIDI events, you can then use that stream to drive a more sophisticated MIDI synthesizer (e.g. something sample based).
Another way to go would be to do a search for "convert voice to instrument", which will bring up a few apps that are designed to that - maybe some of them might work with your square wave?
Of course neither of these necessarily satisfy your 'in a simple circuit' criteria, but I think the answer to whether there is anything simple on the electronic that can transform a square wave into a natural instrument sound is probably 'no'.
One thing you could do though is add something on the acoustic side - so you could have a transducer being driven by your square wave in turn driving a reverberating plate inside a large tube, or something like that - something to add some extra resonances and reverberation. It wouldn't sound like a piano but it might sound a bit less robotic.


Drush cc gives only two options even when I am in root folder

Question: I am working with drupal 8, MAMP version 3.5, and drush version 8.1.3. I have installed drush globally and when I enter drush st it gives me complete information and shows that drush is installed but when I run drush cc, it gives me only two options

cancel
drush

whereas, it is suppose to give me many options. I am in a root folder of the site I am working on .i.e. /Applications/MAMP/htdocs/mysites/mysite. My OS is OSX on macbook pro, just in case if this is mac specific issue.
Done with this step as well:
sudo ln -s /Applications/MAMP/tmp/mysql /var/mysql
Not sure what else to look into, can you anyone please guide? I am new to drush, terminal and mac
Comment: Is the drupal site running?
Comment: Yupx ! drupal site is running fine :)
Comment: does the directory you are in include an index.php file? (`ls -l` to list files)
Comment: Yupx it does have index.php file in that directory which illustrates that I am in root directory :)
Comment: sorry, just wanted to be sure :)
Answer: Use drush cr (container rebuild) rather than drush cc (clear cache)
for drupal 8.
Comment: Got this error:  exception 'PDOException' with message 'SQLSTATE[HY000] [2002] No such[error]
file or directory' in
/Applications/MAMP/htdocs/mysites/mysite/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php:142
Comment: I have resolved the error mentioned in above comment, now drush cr works but drush cc still gives only two options
Answer: I found a solution which worked for me on this link : https://www.drupal.org/node/1016268#comment-10466949
And the proposed solution on comment # 31 was:

Add this to your .bash_profile export PATH=/Applications/MAMP/Library/bin/:$PATH
run this then in terminal source ~/.bash_profile

It ended my 3 days search to resolve my issue.


lean tools/methods to make a browser addon available in all major browsers?

Question: are there any simple tools/methods to make a browser extension available in all major browsers without bothering with each too much?
Else, will the code tend to be be easier/completely portable using a mighty language like java instead of javascript and therefore less browser sepecific code?
Yet for all browsers (Chrome, Firefox, [ie, Opera, Safari or more])
i saw http://www.besttoolbars.net/products/addon_framework/download/,
 http://en.wikipedia.org/wiki/Browser_toolbar#Cross-Browser_Toolbar_Development , etc.
but dont know if any of these are completely free?
and if they allow something for http head/status code request to external domains?
(like wiki.greasespot.net/GM_xmlhttpRequest does, which won't workout with an injected javascript alone as of cross-site-scriting.)
Answer: All browsers use their own api's to create their extensions, but there are some services that claim (not from my experience) to make the extension process easier to make them available for multiple browsers. One i've heard is Crossrider. Check it out and see if it fits your needs.


Md-dialog call template

Question: I am trying to load  template in md-dialog  when on click of button and all i see /src/app/pages/signup/signup.html
Home.Controller
 var vm = this;
     vm.showCustomGreeting=function($event){
           var parentEl = angular.element(document.body);
           $mdDialog.show({
             parent: parentEl,
             targetEvent: $event,
             template:require('../signup/signup.html'),
             fullscreen:true,
             controller: function ControllerName($scope){
                        $scope.data = "Controller Loaded";
             },
          });
       }

Answer: Per docs - https://material.angularjs.org/latest/api/service/$mdDialog
should be templateUrl, not template.
Answer: It should be like this, there is no need of require function as per now also, just make sure given template path should be right. Try this :
var vm = this;
 vm.showCustomGreeting=function($event){
       var parentEl = angular.element(document.body);
       $mdDialog.show({
         parent: parentEl,
         targetEvent: $event,
         templateUrl:'../signup/signup.html',
         parent: angular.element(document.body),
         fullscreen:true,
         controller: function ControllerName($scope){
                    $scope.data = "Controller Loaded";
         },
      });
   }

Comment: i'm already use templateUrl  i get this error "Failed to load template"
Comment: Have you tried this code? i have also made one another change about required function.
Comment: yes i tried still get this error : "Failed to load template"

Md-dialog call template


vb.net - Can't generate the custom event

Question: I'm a little confused about the problem in this class. I want the Pay Button to generate a custom event. I am using Visual Basic Studio 2010 in .NET I think the main problem is within the RaiseEvent line.
    Public Class Payment
    Public Delegate Sub PaymentMadeEvent(ByVal sender As Object, ByVal e As PaymentMadeEventArgs)
    Public Event PaymentEvent As PaymentMadeEvent

    Private Property __paymentAmount As Decimal
    Public Property paymentAmount As Decimal
        Get
            Return __paymentAmount
        End Get
        Set(ByVal value As Decimal)
            __paymentAmount = value
            PaymentBox.Text = String.Format("{0:c}", __paymentAmount)
        End Set
    End Property

    Private Sub PayButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PayButton.Click
        RaiseEvent PaymentEvent(Me, New PaymentMadeEventArgs() {paymentSuccess = True})
    End Sub

    Public Class PaymentMadeEventArgs : Class EventArgs
            Private Property __paymentSuccess As Boolean
            Public Property paymentSuccess As Boolean
                Get
                    Return __paymentSuccess
                End Get
                Set(ByVal value As Boolean)
                    __paymentSuccess = value
                End Set
            End Property
        End Class
    End Class
End Class

Anyways, Advance thanks!
Comment: what is the error/unwanted behavior?
Comment: The system thinks the "paymentSuccess" variable is not declared
Comment: You used the wrong syntax for object initializing. Try `RaiseEvent PaymentEvent(Me, New PaymentMadeEventArgs() With {.paymentSuccess = True})`
Comment: now the error says that payment success is not a member of PaymentMadeEventArgs
Answer: There are several errors/bad coding styles in your code.

Private Property __paymentAmount As Decimal

You don´t need a private property, just use a variable. Also don´t use __ as prefix. Use single _ underscore or no prefix:
Private _paymentAmount As Decimal

Public Property paymentAmount As Decimal

Start public property names with a capital:
Public Property PaymentAmount As Decimal

Public Class PaymentMadeEventArgs : Class EventArgs

This is not the correct VB .NET syntax for inheritance.
Additionally use a Auto-Property for PaymentSuccess less code and better reading:
  Public Class PaymentMadeEventArgs
        Inherits EventArgs
        Public Property PaymentSuccess As Boolean

  End Class

After you fixed all of that raise your custom event in PayButton_Click:
RaiseEvent PaymentEvent(Me, New PaymentMadeEventArgs() With {.PaymentSuccess = True})

Comment: The inherits EventArgs line worked. I didn't knew this beforehand. My bad. Also will take note of these coding styles in the future. Thanks!


Is it possible to upgrade Ubuntu 10.04 32bit to 64bit with out reinstall OS?

Question: My VPS server is running Ubuntu 10.04 32bit now, but I have to upgrade my OS to 64bit because of the 32-bit limitation of mongoDB.
But if i reinstall the system, there are a lot of programs need to reinstall and reconfig, and I have to backup database and other files to another computer.
Is there a way to upgrade from 32-bit Ubuntu to 64-bit Ubunut with out reinstall system?
Comment: AFAIK there is no supported way to go from 32 to a 64 bit system.  You should use this as an opportunity to test your backups and system documentation.  If you have documented your system properly this really should be pretty easy.
Comment: Technically it is possible. However it is non-trivial and I would not do it unless I had physical/iLO or DRAC access to the machine and I could test it before in a VM. Wiping and reinstalling is likely to takes less time, cause less downtime and is less likely to leave strange configurations behind.
Comment: This is one of these things that are 100% theoretically possible, 99% technically possible, but practically are very long, error-prone and unreliable. Don't do it.
Comment: See also http://askubuntu.com/questions/153379/can-i-upgrade-ubuntu-12-04-from-32-bit-to-64-bit and http://askubuntu.com/questions/5018/is-it-possible-to-upgrade-from-a-32bit-to-a-64bit-installation
Comment: Automated? No, forget it. Just reinstall. Chances of getting tons of errors is very high.
Answer: I tried to switch from 32 bits to 64 bits on a ubuntu.
It's faster to reinstall everything, dpkg REALLY don't like playing with him.
If you try, try in a VM first, to be sure you understand how to do.
Good Luck.
Answer: As an automated upgrade? No.
I think it may be possible manually, but it would involve replacing every package and the kernel. It is hard and very prone to errors. I'm also not sure the result will work very well. I wouldn't do that on a server!
Anyways, if your disk crashes or if someone deletes everything on it, what will you do?
Take note of what applications you have installed, backup /etc to save your configurations. Other parts of the filesystem may also be useful depending on the software you're currently running on that machine.
For the databases, dump everything (and don't forget the authentication and authorization tables). Database dumps are quick and easy to restore.
Reinstalling the same applications is not long and configuration should not be a problem if you have the old /etc in hands.
If this is a web server, don't forget about places like /var/www
Comment: Heh, I agree. It has been done on FreeBSD (see http://wiki.freebsd.org/amd64/i386Migration), especially the part where it mentions **some ports may not work**. Which is fine for a personal play system, but unacceptable for a server.
Answer: Linode let you change the kernel to 64 bit, without upgrading everything else.  I just tried this on my system (also Ubuntu 10.04 32 bit like yours), and ... well it worked just fine.  There were no problems at all.  I'm also running a web server (Apache) and various other applications, and I haven't encountered problems.
See:  https://www.linode.com/docs/migrate-to-linode/disk-images/switching-to-a-64bit-kernel
It takes about 5 minutes in total.  I'm slightly staggered that it just worked, without problems but, touch wood, that's my experience, so it really was a quick and easy thing to do.
Of course, as the documentation points out, this only upgrades the kernel, the OS (and everything else) is still 32 bit.


Mathematical representation of 1D convolution

Question: How does one write the mathematical formula for conv1d used in PyTorch, including parameters like stride length and padding?
For instance, I can write
import torch

input1d = torch.tensor([[[1,2,3,4,5]]])
filter1d = torch.tensor([[[4,3]]])

torch.nn.functional.conv1d(input1d, filter1d)

Output:
tensor([[[10, 17, 24, 31]]])

This is equivalent to
torch.einsum("abcd,abd->abc", input1d.unfold(2,2,1), filter1d)

How does this translate to mathematical operations? I am particularly uncertain about input1d.unfold(2,2,1).
I have the following, but I am quite sure it is incorrect
$$
x = \mathrm{input1d} \in \mathbb{R}^{1 \times 1 \times 5} \\
w = \mathrm{filter1d} \in \mathbb{R}^{1 \times 1 \times 2} \\
\int_{-\infty}^{\infty} \sum_{d} x_{abcd}\,w_{abd}
$$
Answer: So a few things here:
Firstly, it is worth mentioning for the sake of transparency that torch.nn.functional.conv1d is more strictly cross-correlation rather than convolution, which involves flipping the filter, in a more broad usage. However, for CNN applications, the distinction is not important, and so the term convolution is overwhelmingly overloaded to mean cross-correlation (no flip).
The second thing that is worth mentioning is that ``mathematical operations'' can mean a few things as well. A relatively straightforward approach would be using
$$(\vec{a}\star\vec{b})[i] = \vec{a}\left[i:i+\text{len}(\vec{b})\right]\cdot \vec{b}$$
where $\vec{a}\star\vec{b}$ is the desired result of cross-correlating $\vec{a}$ and $\vec{b}$ (given as a vector-describing function $\vec{a}\star\vec{b}:\mathbb{Z}
\rightarrow\mathbb{R}$ that maps the vector indices in $\mathbb{Z}$ to results in $\mathbb{R}$). $:$ and $\cdot$ are range-indexing and dot product operations, which can be broken down into summation notation as desired.
Incorporating stride, this is
$$\text{corr}(\vec{a}, \vec{b}, \text{stride})[i] = \vec{a}\left[i\cdot\text{stride}:i\cdot\text{stride}+\text{len}(\vec{b})\right]\cdot \vec{b}$$
After breaking this down into summation notation, you should be able to extend the dot product operation to consider padded zeros (or more precisely, only sum/multiply existing elements). I will circle back to address this and your question involving matrix multiplication and reindexing when I'm free from work.
Comment: (+1) Thank you for mentioning that `torch.nn.functional.conv1d` is the cross-correlation. Too bad they have a misleading naming convention.
Comment: @DavidMcKnight Great explanation. I admit that writing convolution as a mathematical operation is a bit ambiguous. But the indexing operation on $\vec{a}$ is clear to me, it reminds me of slice notation in python. The convolution can be simulated by using a circulant matrix, which I thought was a bit more more intuitive because the numbers in $\vec{a}$ and $\vec{b}$ can be written out. However, I am confused on how to describe a function for generating the circulant matrix.
Comment: @DavidMcKnight I posted a question about this here: https://stats.stackexchange.com/questions/557703/discrete-convolution-with-circular-matrices
Comment: Definitely misleading, but I think there's decent reason for it. IIRC, the seminal paper(s) for CNNs (or possibly for vision, IDR) actually did use the more broad usage of convolution. In the context of CNNs, though, the two have the same utility, and so since you can swap out convolution and cross-correlation as long as you're consistent, people did.

Thus, in pretty much all the stuff out there about CNNs you actually /can/ use convolution, it's just easier to think with cross-correlation.

(Personally, however, going from ECE -> ML, I was very surprised by the convention at first)


How to integrate CAC card with Windows Login

Question: Does anyone know how to integrate the DoD CAC card with the Windows Server 2003/2008/2012 Login Process? I want my users to be able to insert the card into the reader and just enter their pin to login to the system. I know its possible to do in Linux but I can't find out how to do it in Windows.
Answer: This is the best public hint on how to do this is here: http://support.microsoft.com/kb/281245. However for others who need to set this up, that document was not enough for me to get it working.
On a side note there is an excellent step-by-step process available to walk someone through setting this up but it is available only through the US DoD INFOSEC department.


Problemas com Construtor de Queries (Query Builder) no Laravel 4.2

Question: Olá,
estou com problemas para gerar uma querie utilizando o Querie Builder do Laravel 4.2, a dificuldade surge da necessidade de que as sentenças resultantes para pesquisa na base de dados estejam dentro de parenteses, abaixo esta a querie desejada:
select * from `EV_RELATORIO`
    where `DTALTERACAO` between ? and ? and
         (`MUN_ID` is null or (`MUN_ID` in (?))) and
         (`REG_ID` is null or (`REG_ID` in (?)));

Porém esta retornando a seguinte querie:
select * from `EV_RELATORIO`
    where `DTALTERACAO` between ? and ? and
          `MUN_ID` in (?) or `MUN_ID` is null and
          `REG_ID` in (?) or `MUN_ID` is null';

A construção da querie dentro da model utilizando o Laravel segue abaixo:
(Arquivo VW_Relatorio.php)
<?php

class VW_Relatorio extends BaseModel
{
    protected $table = 'EV_RELATORIO';
    protected $primaryKey = 'ID';

    public function scopeMundos($query, $dados) {
        if(!empty($dados)){
            $query->whereIn('MUN_ID', $dados)->orWhereNull('MUN_ID');
        }
        return $query;
    }

     public function scopeRegionais($query, $dados) {
        if(!empty($dados)){
            $query->whereIn('REG_ID', $dados)->orWhereNull('MUN_ID');
        }
        return $query;
    }
}

Faço a chamada na minha classe com o seguinte código:
$rel = \VW_Relatorio::whereBetween('DTALTERACAO',array($dataInicial, $dataFinal))
    ->mundos($data[0]['mundos'])
    ->regionais($data[0]['regionais'])
    ->get();

Tentei utilizar "Where" avançados, porém não conseguir gerar a querie corretamente.
Agradeço desde já a atenção de todos.
Answer: Acho que é assim, eu fiz direto sem colocar como scope se der certo é só transferir pra lá, a sintaxe é essa:.
$param1 = $data[0]['mundos'];
$param2 = $data[0]['regionais'];
$rel = \VW_Relatorio::whereBetween('DTALTERACAO',array($dataInicial, $dataFinal))
    ->where(function($query) use ($param1){
           $query->whereIn('MUN_ID', $param1)
                 ->orWhere(\DB::raw('MUN_ID is NULL'));
    })
    ->where(function($query) use ($param2){
           $query->whereIn('REG_ID', $param2)
                 ->orWhere(\DB::raw('REG_ID is NULL'));
    })
    ->get();

Comment: Muito obrigado pela ajuda, alterei minha Model e funcionou, com o detalhe que utilizei **"use"** no lugar de **"uses"**.
Comment: @LeandroJ.S.Paiva foi erro de digitação desculpas ... !!! que bom que funcionou!


Multiple twitter Bootstrap Carousel control with class

Question: I'm trying to setup multiple twitter bootstrap carousels on one page, but I don't want to use different IDs, as later I will be creating these dynamically. My issue is that by pressing buttons in first carousel I control all of them. I can't figure out how to address the elements correctly. How can I set up this code so that I can control each carousel separately, by using class and not ID?
jsfidle:
http://jsfiddle.net/RobRalph/shk63x3g/1/
HTML:

1

Lorum ipsum

2

Lorum ipsum

3

Lorum ipsum

1

Lorum ipsum

2

Lorum ipsum

3

Lorum ipsum

Extra CSS:
.backview {
position:absolute;
top:0;
z-index:-99;
height:100%;
width:100%;

background: linear-gradient( rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3) ), url('https://scontent.xx.fbcdn.net/hphotos-xpa1/v/t1.0-9/p480x480/10408976_1175768429116191_8145612220139098697_n.jpg?oh=45022b3bbf32769af5bf339f40cb2cb1&oe=55F527C3') no-repeat center center;
background-size:cover;

}

.headeritem {
    height:80px;

}

.bodyitem {
    height:140px;

}

Answer: I think you are going to need to use different IDs, when you are create them dynamically you should also assign them distinct IDs.
Here is a working Bootply demo with two carousels: http://www.bootply.com/04KMcAK0w4
You will need to use the ID in two locations.
On the carousel indicators (bullets) as the value of data attribute called data-target:

And on the forward and back buttons as the value of the href:

Comment: si it's not possible with Class, unless I modify bootstrap.js?
I was afraid that it will come to the IDs, I guess I will have to look around how to add the specific IDs dynamically, shouldn't be too bad


sequential estimators for a proportion

Question: Does anyone have any reference for a sequential estimator for proportions?
I am planning an experiment to measure the probability of a certain event happening and would like to know how many observations to take to estimate it to within a certain accuracy. Clearly, this will depend of the size of the probability we end up observing about which our option will change sequentially as we obtain more information.
Classical Wald sequential ratio tests can be very efficient for two groups. Is there a parallel for the one sample case.
Comment: Does this help: http://stats.stackexchange.com/questions/165035/number-of-samples-needed-in-monte-carlo-simulation-how-good-is-this-approximati ?
Answer: Wald's SPRT (sequential probability ratio test) was not originally formulated as a two group comparison test:
https://en.wikipedia.org/wiki/Sequential_probability_ratio_test
The "bible" for sequential analysis is probably last year's book Sequential Analysis: Hypothesis Testing and Changepoint Detection by Alexander Tartakovsky. It is magisterial and seemingly exhaustive in its coverage of the topic.
http://www.amazon.com/Sequential-Analysis-Hypothesis-Changepoint-Probability-ebook/dp/B00MMOIWTS/ref=sr_1_1?ie=UTF8&qid=1445511005&sr=8-1&keywords=sequential+analysis+tartakovsky
That said, last June Columbia sponsored The Fifth International Workshop in Sequential Methodologies which brought together the latest and greatest practitioners in the field. Tartakovsky was on the organizing committee.
https://sites.google.com/site/iwsm2015/home
See the "Detailed Program" link on the conference website for abstracts and papers. There's probably something there targeted specifically to your question.
Comment: you're right. Its the hypothesis testing aspect that sets the SPRT apart from my estimation problem. Will follow up the links and then mark it as solved when I find a reference. Many thanks.

sequential estimators for a proportion


Pandas style.apply matches between 2 dataframes with .isin

Question: I have two dataframes and I want to check for their matches.
Dataframe1
some_stuff    big_number
a             111
b             112
c             117

Dataframe2
another_big_num
0111
0114
0117

If the number of df2 exists in df1, I want to highlight the entire row.
I understand that by using .isin I can check for the matches but I don't know how I can use .style.applymap provided by pandas in such a context.
So doing something like
df_test1["big_number"].isin(df_test2["another_big_num"]) gives me the matches I want but I don't know where to go from there.
Comment: @mozway that isn't the issue I am struggling with
Answer: You can do something like:
def big_number(s,x):
    if s.big_number in x:
        return ['background-color: yellow'] * len(s)
    else:
        return ['background-color: white'] * len(s)

df_test1.style.apply(big_number(df_test1,df_test2["another_big_num"].values), axis=1)

Comment: Also, how can I save the result as a new excel file? Adding `.to_excel(...)` doesn't seem to work for me giving me `pandas.core.base.SpecificationError: Function names must be unique if there is no new column names assigned` this error.


Probability problem ( shuffling cards )

Question: Suppose we shuffle a deck of 10 cards, each bearing a distinct number from 1 to 10, to mix the cards thoroughly. We then remove three cards, one at a time, from the deck. What is the probability that we select the three cards in sorted (increasing) order?
Answer: Let's first consider that we draw 3 cards without ordering them, then we order our 3 drawn cards. This is an equivalent problem and regardless of the cards we drew, there are 6 equiprobable orderings, only one of which yields an increasing order.
The probability is therefore 1/6.
Comment: It's right the first card we need to draw must be strictly less than 9, but then the other "allowed" cards depend on the first drawn card. Computing the probability in this way becomes a combinatorial nightmare, so I think it is better to consider we just pick three cards at random, then order them randomly, which is equivalent but easier to compute.
Comment: I don't understand your reasoning. First we need to draw a card that should be between 1 and 8 inclusive, then two others with probability 1/9 and the last one with probability 1/8: So the probability is ${8/10 * 1/9 * 1/8}$ NO ??
Answer: Let E = event that we draw 3-cards that are in increasing order
Then P(E) = |E|/|S|
Note we can use P(E)= |E|/|S| because each outcome is of equal probability.
First, we find the size of the sample space |S| as the total permutations of 3 cards out of 10 cards:
n!/(n-k)! = 10!/7! = 720. That's the easy part.
Second, what are the total # of 3-card orderings that are in increasing order? i.e. |E|
This is simply the total combinations of 3 cards out of 10 cards:
n!/[n!(n-k)!] = 10!/(3!7!) = 120
Why can we use the combinations formula?
Well, when counting combinations, order doesn't matter,
so {1,2,3} = {2,1,3} = {2,3,1} = {3,2,1} = {3,1,2}
In any set of the same numbers, there is only one ordering where the numbers are increasing.
Therefore, by counting the combinations, its the same as counting the only sorted order and disregard the non-sorted orders.
P(E) = |E|/|S| = 120/720 = 1/6
Please feel free to let me know if I made some logical shortcuts in the second part.
Comment: The second part seems a bit confusing to me. You can make it different  by merely saying that the set of strictly increasing sequences with length three over $\{1,\ldots,10\}$ is equipotent to the set of all subsets of $\{1,\ldots,10\}$ with cardinality $3$. The latter has $\binom{10}{3}$ elements.
Answer: I used the approach of counting. Since we are drawing one card at a time:
$S = 10 * 9 * 8$ (10 ways to pick first card, then 9, then 8) and
$$E = \sum_{i = 1}^8 \sum_{j = i+1}^9 \sum_{k = j+1}^ {10}i.j.k$$
As somebody already pointed out, a combinatorial nightmare. Wondering how this shall turn out to be $10C3$

Probability problem ( shuffling cards )


Bootstrap blog fixed sidebar issue

Question: I'm trying to build a blog site and I'm initially using the template on getbootstrap.com's examples.
Basically, I want the sidebar on the right, to be fixed, so that when you scroll through blog posts, the sidebar stays where it is, like the top navigation does.
I've tried using the affix plugin, but having issues keeping it in the same place.

Here's a JSFiddle - http://jsfiddle.net/Sambolina/L3a7q/
Answer: First, split out your sidebar from your column- in my earlier answer, I missed that:

When your sidebar gains the class affix, the css updates from position:relative to position:fixed, but you don't provide any CSS for the position of the sidebar once it is fixed. Now that your column isn't being affixed, you need to explicitly define the top positioning. To keep the width consistent, we'll also explicitly define it for both affixed and unaffixed states:
.blog-sidebar{
    width: 200px;
}

.blog-sidebar.affix{
    top: 40px;
    padding-top: 15px; /*or add it into the top value, I'm just weird*/
    width: 200px;
}

The only issue after that is handling how you'll deal with the column when it collapses- since it's affixed, the content will stay even after the column collapses. A good way to fix this is to add the class hidden-xs (and others if you change the column from sm) to hide this content, then create a new div as you want it to show up on small viewports and give it the class visible-xs. You can style this uniquely, which is probably a good idea since a navbar + nav + content on the smallest devices is probably too much.
For an example of all of this, see the Bootstrap docs which have a right affixed nav.
(edited per author's comments below)
Comment: I understand that I need to style the affix'ed item, but I'm unable to style the sidebar in the same way it was when the position was relative. If I just give it a right value, it won't adjust responsively and the sidebar width changes, which I'm struggling to adjust to what it was originally.
Comment: Can you drop a jsfiddle so I can try something specific? Width has to be defined too per above, and you might need a min-width depending on what you're seeing.

I don't know off the top of my head how to get it to affix differently if the column collapses for the smallest viewports, though I'm sure it is feasible; in the past I've always just set it to **hidden-xs** and made an alternate version for **visible-xs** positioned and styled differently.
Comment: Here's a fiddle - http://jsfiddle.net/Sambolina/fhbtxjg3/1/

If I widen the result box, with the added CSS it stays the right width and transitions nicely. I don't know if it will be the same result for you on your display. So I could just do this for every viewport with media queries, but I'd much prefer a more simple solution..
Comment: I edited my response above, so check it out. Basically (a) you need to pull that sidebar div outside of the column before you affix it, and (b) you need to set a width for that div both affixed and not-affixed. The values I gave up there look pretty nice when you scroll, so try them out and tweak things.

Bootstrap blog fixed sidebar issue


How do I select all child rows corresponding to a set of parent ids

Question: How do I select all child rows corresponding to a certain parent table using ActiveRecord queries.
create table foo (id, ...)
create table bar (id, foo_id, ...)

select * from foo where key = ?
# The above return a single row or multiple rows.

select * from bar where foo_id in <ids from the above output>

How do I achieve this?
Answer: Using only queries with ActiveRecord
foo = Foo.where(:key = ?)
Bar.where(:foo_id => foo)

Using associations and eager loading :
#foo model
class Foo < ActiveRecord::Base
  has_many :bars
end

#bar model
class Bar < ActiveRecord::Base
 belongs_to :foo
end

#query
Foo.includes(:bars).where(:key => ?).collect(&:bars)

Comment: Your query returns instances of foo, not bar. According to the last query stated in the question, it specifically says "select * from bar...".
Comment: I am assuming the query will return a collection of Bar(s) here
Comment: If you strictly just want `bars` you can collect them from the previous query I will update the answer.
Comment: You don't need eager loading - you can load Bar directly and join the foos
Answer: Humm... I don't know if your question is whether something like that can be done with ARel or not (which, it cannot). What you want is to provide matches using a sub-query, which you can do in SQL, and therefore using ActiveRecord::Base.find_by_sql.
ActiveRecord::Base.find_by_sql("select * from bar where foo_id in
(select id from foo where key = #{key})")

Comment: in rails 3.x (or at least 3.2) you can do subselects with arel.
Answer: Arel will do this:
Profile.where(user_id: User.select("id").where(exclude_from_analytics: true))
#=> Profile Load (395.1ms)  SELECT `profiles`.* FROM `profiles` WHERE `profiles`.`user_id` IN (SELECT id FROM `users` WHERE `users`.`exclude_from_analytics` = 1)

Whether you actually want to do a subselect is another thing - its worth trying to write the query as a join:
Bar.joins(:foo).where(:foos => {:key => key})

assuming that you have setup Bar with a belongs_to :foo association. The joins method will also accept a raw sql fragment
Answer: You should be able to do
Bar.find_all_by_foo_id([1,2,3,4])

In which case you will have to find all the foo ids previously.  But if you need it in one query sub-query which ChuckE mentioned is best.


Preencher matriz de char com palavras aleatórias

Question: Estou tentando desenvolver um algorítimo capaz de obter um vetor de strings, ordenar por tamanho de palavras de forma decrescente e colocá-las dentro de uma matriz de char encaixando se possível todas as palavras. A ideia de tudo seria como criar um grid e fazer com que as palavras de "conectem" através de letras em comum, para desenhar a ideia imaginem um caça-palavras.
Ex:
String[] palavras = new String[]{"vidro", "plastico", "amarelo", "madeira", "metal"};

palavras = OrdernarPorTamanho(palavras, DECRESCENTE);

char[][] grid = new char[15][15];

for(int linha = 0; linha < 15; linha++)
{
    for(int coluna = 0; coluna < 15; coluna++)
    {
       // Aqui viria as verificações para colocar todas as palavras do vetor dentro da matriz
    }
}

A minha saída desejada da matriz seria da seguinte forma:
Ex:
- P L A S T I C O - - - - - -
- - - M E T A L - - - - - - -
- - - A - - - - - - - - - - -
- - - R - - - - - - - - - - -
M A D E I R A - - - - - - - -
- - - L - - - - - - - - - - -
- - - O R D I V - - - - - - -
- - - - - - - - - - - - - - -
- - - - - - - - - - - - - - -
- - - - - - - - - - - - - - -
- - - - - - - - - - - - - - -
- - - - - - - - - - - - - - -
- - - - - - - - - - - - - - -
- - - - - - - - - - - - - - -
- - - - - - - - - - - - - - -

Alguém tem alguma sugestão de como fazer esse algoritmo?
Valeu :)
Comment: Qual linguagem?
Comment: @diegofm qualquer uma, mas a principio seria Java
Comment: Acho que este problema requer um algoritmo genético. Espalhar as palavras se torna complicado a medida que as palavras que já estão no quadro podem estar ocupando espaços sorteados para as próximas.
Comment: @CelsoMarigoJr Alguma sugestão de algoritimo?
Answer: Esse problema é NP-completo, você pode usar um algoritmo Força Bruta para resolvê-lo. Ele consiste em tentar todas as possibilidades, e parar quando uma possibilidade é um válida. Vai retornar falha quando testar todas as soluções possíveis e não encontrar nenhuma.
Uma solução usando força bruta é o Backtracking, veja esse pseudocódigo:
solve(words,grid):
   if words is empty:
       if grid.isValudSol():
          return grid
       else:
          return None
   for each word in words:
       possibleSol <- grid.fillFirst(word)
       ret <- solve(words\{word},possibleSol)
       if (ret != None):
          return ret
   return None

Nesse link, tem um algoritmo pronto em Python.
No stackoverflow em inglês tem essa pergunta, acho que pode ser útil, pois a linguagem utilizada é Java.


How to use plugins to add nodes and edges in cytoscape.js?

Question: I'm trying to migrate from the old Flash CytoscapeWeb to the HTML5 version, cytoscape.js.  I'm trying to build a tool that allows interactive creation of networks - meaning we need to add nodes and edges.  There were some wonderful demos for CytoscapeWeb (eg http://cytoscapeweb.cytoscape.org/demos/compound) that demonstrated this functionality.  I can't find anything similar for Cytoscape.js.  I've looked through the documentation and I'm not finding anything.
I've tried this (How do I use the jquery.cxtmenu.js plugin packaged with cytoscape.js?) and the context menu appears on right click, but the two commands both fail.  The Connect command simply does nothing (it's calling EdgeHandles but there's no documentation about what that's doing) and the Delete command fails with "doc.removeEntity(...) is not defined".
I get the strong sense that the functionality that I'm looking for already exists in the core or plugins, so I don't want to recreate all that stuff.  But I can't figure out how to use what's already there.
Answer: Documentation and organisation of the UI plugins in the jQuery plugins system is planned for 2.1:
https://github.com/cytoscape/cytoscape.js/issues?milestone=3
There is an example of those particular plugins being used on the cy.js debug page:
https://github.com/cytoscape/cytoscape.js/blob/master/debug/init.js


Nginx vhost on non-standard port not working

Question: I am attempting to use varnish as a front-end proxy to Nginx.
When I attempt to using the following as my vhost configuration:
server {
  listen 8080;
  server_name playwithbits.com  www.playwithbits.com;

  # limit_conn limit_per_ip 16;
  # ssi  on;

  access_log /home/nginx/domains/playwithbits/log/access.log combined buffer=32k;
  error_log /home/nginx/domains/playwithbits/log/error.log;

  root /home/nginx/domains/playwithbits/public;

  location / {

  # Enables directory listings when index file not found
  #autoindex  on;

  # Shows file listing times as local time
  #autoindex_localtime on;

  # Enable for vBulletin usage WITHOUT vbSEO installed
  #try_files             / /index.php;

  }

  include /usr/local/nginx/conf/staticfiles.conf;
  include /usr/local/nginx/conf/php.conf;
  include /usr/local/nginx/conf/drop.conf;
  #include /usr/local/nginx/conf/errorpage.conf;
}

However this stops working when I specify listen 8080 and redirects to the default nginx web root (as specified in virtual.conf), if I remove that line it works as expected and redirects to the correct directory.
Does anyone know why this is happening and how I can set a non-standard port for my vhost so varnish can listen on port 80.
Comment: Did you do `nginx -t` to check nginx config when `listen 8080;` was specified?
Comment: @hangover Cheers, didn't know about that. It returns `nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful`
Answer: The problem wasn't Nginx, it was Wordpress. Apparently WordPress redirects itself and you have to put the port extension onto the WordPress Address (URL) setting in the dashboard like so:
http://playwithbits.com:8080
And it works, otherwise WordPress redirects to port 80 causing my default Nginx configuration to kick in.


Soma de campos de tabela com PHP e Codeigniter

Question: Preciso somar alguns campos de uma tabela. Tenho o id da transação e preciso somar todos os campos amount com o id 224, todos com 222.
Comment: Você precisa somar todos os `amount` que tem o mesmo `customer_id`?
Comment: Sim, creio que seria mais ou menos como a resposta abaixo.
Answer: Você pode fazer isso usando a função SUM e agrupando os registros pelo campo que você quer com GROUP BY. Exemplo:
SELECT `customer_id`,  SUM(`amount`) AS `amount`
FROM `tb_customer_credit`
GROUP BY `customer_id`;

SQLFiddle
Assim terá a soma de todos os registros. Caso precise da soma de apenas um registro, pode fazer da forma que o @BernardoKowacic fez, utilizando o WHERE.
Comment: Seria apenas 1 mesmo, consegui fazer com o código do @BernardoKowacic, esse id eu pego do cookie do usuario.
Answer: Você pode fazer isso utilizando apenas um select no banco de dados, facilitando a sua vida. No seu caso o select ficará da seguinte maneira:
select sum(amount) as 'amount' from `tb_customer_credit` where customer_id = 224

Referente a linha de código acima, você só precisara substituir o valor 224 pelo nome da variável que será utilizada pela sua aplicação para enviar o ID.
Você também conseguiria pegar o maior valor, entre outras coisas utilizando apenas o select, diminuindo assim a quantidade de coisas no php e diminuindo o tempo de resposta do seu site.
Comment: Para fazer no Code Igniter, você deve criar uma nova função na sua classe Model (aonde faz os selects no BD) e colar lá esse código.
Comment: Perfeito, tive que apenas trocar o 224 pela id que estou puxando e funcionou perfeitamente.


Should I mention the reason why I stopped performing piano for 10 years?

Question: I had a good career as a young pianist around ten years ago, performing in several venues and winning some local competitions. This came to a halt when I had to stop due to severe back pain that made it impossible for me to practise at the piano. I managed to take the Music School Diploma in Piano Performance (with 10/10 cum laude) and then I had to stop playing, taking a different career path.
Long story short, in September this year, around ten years later, I managed to solve my back issues. I prepared a new repertoire and am going to perform in a music venue in my current town. It is a small venue, and I am going to share the evening with a clarinettist (we are both playing solo, I am the headliner). I am playing in the UK.
I was preparing a little leaflet with my biography. My biography is short because:
a) I lived in a different country then, in the past, and mentioning the places I played ten years ago would not mean anything to the people here
b) I won mostly local competition that are probably meaningless to people here.
c) I didn't play for the ten years after the diploma, important years for getting stuff done.
So in my short biography I briefly mention that I performed in several venues and won several competitions - without any detail, then I say that I graduated in 2008.
At this point, should I mention that I stopped playing the piano due to health issue connected with piano playing? And that this is my first concert in 10 years? How would this come across?
It goes without saying that I am really proud about my story and I would like to share it. But people may think that I am bragging or getting too personal. Maybe people don't want to hear "excuses" about why I stopped playing for 10 years.
So.. how would this come across? Should I just not mention anything and ignore the fact that last entry in my biography is from 2008?
Comment: I think your question is better suited for https://workplace.stackexchange.com/
Answer: I used to call this the Rock Star Motto:

Never apologize, never explain.

If you're an entertainer and you're not famous, nobody's interested in your problems. They have their own problems. The audience just wants to be entertained.  If you promo by giving an excuse (subtext: "Gee folks, I haven't played for 10 years, please be gentle."), the audience is going to think that maybe they won't have a good time.  Frame your promo positively.
History is in the past.  Impress your audience now and your audience will grow in the future.
PS: The quote is actually from a 19th century Oxford scholar, Benjamin Jovett:

Never retreat. Never explain. Get it done and let them howl.
Answer: From what I have been told, people don't really care how long you've been playing or about years/age. (I am an emerging composer and I wondered if I should explain why I don't have many compositions in my early 40s.) You could list the titles of the competitions you won, say that you've been playing piano since you were young, and maybe mention the venues and countries you've played in. The most important thing is now. Are you playing well? Great. The proof is in the pudding, as they say. I know people with bios that are amazing on paper but who really aren't great players.
Comment: @Vaaal, I'm just saying that they don't *need to know* there was a gap at all!  Why even bother mentioning dates. Just say what you have done, not when.
Comment: Starting late and having a big gap in your career is different. In my case I would leave people wondering what I have done during the past 10 years..a person starting late would not raise such question
Comment: There's a saying - 'you're only as good as your last gig...' Make this one the best!
Answer: Sadly, the only credit the general audience would be really interested in - the only one worth putting on the posters - is 'Finalist on Britain's got Talent'.
But this is a debut recital in your home town.  The audience will be largely your friends and neighbours (as long as you PESTER them to buy tickets!)
In this particular case - and ONLY for this concert, in this town -  pick the appropriate parts from something like this:
'@Vaaal's promising career in {country} was cut short by back pain.  10 years later he is proud to be making a second debut in his new home of ...    Special thanks to the doctors at ...  who  helped to make this possible.   Proceeds of the concert will go to {appropriate medical charity}.'
Answer: I look at what are the reasons we print and distribute this kind of literature and find the main reason is to sell others on your talents and abilities to entertain people. The accepted  tried and proven method to accomplish this goal is to keep things positive, play up accomplishments, use positive reviews, and speak in complimentary and glowing terms about what you do. Avoid negative statements at all costs. You're selling yourself and what you do, not trying to garner sympathy for your life's situations. Then do your best to live up to their expectations.


Rounded Corners in HTML

Question: I have this code and when it displays, there's a weird vertical line to the right side. I can't figure out what might be causing it. Any help would be appreciated.

Here's the full code that I'm using.

 We have spacious and modern training rooms.

Comment: http://css3generator.com/  > Border Radius
Comment: It's your td background color. You're using an image to create the rounded corner, but the width of the image is smaller than the width of your td.
Comment: So you are using images to give the rounded appearance?
Comment: Yes. If you know of a solution or a better method please let me know
Comment: images as background images is still the only way to do things if you want to guarantee compatibility in all browsers. I would set background images in css and not in the dom. That will ensure you have rounded corners in IE6+
Answer: You might want to look at incorporating CSS3 rounded corners without having to bang in a bunch of codes. Just try a google search on it!
Answer: It's due to your widths being off.
Change:

to

Working example at (minus the corner graphics): http://jsfiddle.net/GuuLs/
If you wanted the width to be 600px then you would need to modify the width of your middle td (currently 410) to 570.
Answer: The middle cell should be 570 width, that will solve the problem.
However I would not tackle this problem in this way.
Instead I would just use css to set background images to top right, bottom right, top left, bottom left.

Rounded Corners in HTML


Representing the uncertainty of the median in a clean way

Question: So suppose I want to estimate the fraction of the year a user of some demographics is active, and I have n users (effectively, n samples). So I get the fraction of the year each user is active.
It turns out that the distribution is lognormal for non-active user types, but the log-transformed variable is negatively skewed for very active user types (since there is an upper bound).
In this case, the median is better than the mean as a "typical" value, but how do I represent uncertainties of this estimate? If the distribution were symmetric, then $mean \pm  stdev$ will be a good way to do it, but in a skewed distribution, should I represent it as $median \pm something$ something (maybe IQR/2? std?)? What's the best way to represent it?
Comment: Your title asks about distribution of means but your body text asks about uncertainty of the median. Which is it?
Comment: Ah I got confused there. I also have one quantity (not the fraction of the year) that is the mean daily usage *per user*, so if I plot the histogram of this, then what I would be getting is the mean/median *of the means*. Anyway, updating the title.
Comment: Also edited to include info that the data is lognormal for non-active user types, but highly skewed (still using log-transformed variables) for very active user types.
Comment: I don't see any basis for asserting that it's lognormal there. It might be an adequate approximation, but with that large a sample size you can tell it won't be lognormal.
Comment: @Glen_b the figure I showed earlier is in log-transformed variables. If I use the original scale, it's long-tailed. Whether the red curves are lognormal may be debatable, but I think the blue curves are. Both pass the Pearson-d'Agostino and Anderson-Darling tests.
Comment: I realize from what you said those are log-transformed values, so if the blue curves were normal that would correspond to a lognormal variate. I don't buy the claim that the blue curves represent random samples from a normal. If you really have 20K observations the histogram is much too far from the smoothness you should see - specifically near the center, there's too much variation in counts for it to be normal. https://i.stack.imgur.com/5GvWK.png  ... this is exactly where the tests you mention will be weakest at detecting such a problem (I am surprised the AD didn't pick up the left tail)
Comment: However, even with a more powerful test for this kind of deviation from normality (like say a Chen-Shapiro) failure to reject normality doesn't mean you have normality.
Comment: The question has somewhat changed from what it said when I started answering it, but I believe my answer remains relevant.
Comment: I see what you mean. I think the question behind this question is much more complicated. I'll think about how else to say what I need, and then I'll post another question. Thanks a lot.
Answer:
In this case, the median is better than the mean as a "typical" value

This is a misleading oversimplification common to many introductory texts. It depends on what you want to find out (/what typical means for your particular needs). It can be perfectly reasonable to be interested in the behaviour of the mean with a skewed distribution, and where the mean isn't quite what you need, it may easily be that the median is less useful still!
As an example, consider how long I wait for the lights at a particular intersection while travelling to work. This waiting time is quite right skew.  I am interested in the average wait (for example, in working out my average travel time or how much time I waste at that intersection in a year); on the other hand if I am worried about being late to work, neither the mean nor the median are much direct use; I'm much more interested in the chance that the wait might exceed say 10 minutes (in heavy traffic it does sometimes happen)

how do I represent uncertainties of this estimate?

If you're interested in an interval for the population median for a continuous variate, one can be produced without even assuming a distributional form (a nonparametric/distribution-free estimate), based on sample quantiles (or more precisely, on order statistics).
This calculation is discussed in various places, including other questions on site. Also see Wikipedia or here for example. These small-sample intervals are "exact" in the sense that they have the relevant coverage (from the binomial), but those possible values for the coverage ('confidence level') are discrete (i.e. you can't form an exact 95% interval but for example at n=30, you can choose symmetric intervals that have coverages 99.5%, 98.4%,
95.7%  and 90.1%).
This sort of interval is related to sign tests and proportions tests.
As an explicit example, let's say we have n=15 values randomly drawn from a continuously distributed population; one of the available levels is 96.5%, corresponding to the interval from the 4th to the 12th sorted observations. That is to say, under repeated sampling, about 96.5% of intervals from the 4th largest to the 12th largest observation would include the population median.
If you're interested in a standard error of the sample median, there's an asymptotic approximation that relies on knowing the height of the density at the median (in large samples from a continuous distribution the sample median will be asymptotically normal, so this can potentially be used to give large-sample intervals).
$\text{s.e.}(\tilde{x})\approx\frac{1}{2\sqrt{n}\,f(\tilde{\mu})}$
If your sample is also large enough to form a reliable estimate of scale (so that you can in turn get that estimate of the density at the median if you know $f$ up to location and scale) this may be useful.

should I represent it as median±something something (maybe IQR/2? std?)? What's the best way to represent it?

What's "best" for your purposes? What, if anything is known about the distribution?
Comment: You might be best to make a new post relating to what you need to do; other thoughts than mine may be more help to you
Comment: Here's what the plot looks like: https://drive.google.com/open?id=1xZDzNXD2qdGN8Fdf1B_2SSUcgrmSdYEy What I want to point out is that the red curve is further to the right than the blue curve. For the other quantities I've examined, I've had no problem because all curves were symmetric (so I just used mean $\pm$ std), but here I'm at a loss what's the best way to represent what the graph tells.
Comment: It seems you have a different problem to the one you asked about (you asked about your attempted solution to the problem rather than the problem you started with). "*The red curve is further to the right than the blue curve*" looks like an excellent description to me. Symmetry or not, if you give a pair of means and standard deviations it doesn't really convey the extent of what is obvious in the diagram. ...ctd
Comment: ctd... You can quantify that movement of probability to the right in a number of ways, but conceiving of it as a location shift (whether of means or medians) may not be so useful when it's bounded. It may be that the proportion of red values higher than blue values (out of those higher and lower, considered pairwise) could be more useful for example. If it's only intended as a rough summary of a plot, you may be fine to talk about the change in the mean but ultimately you must tailor your choices to your audience of course.
Comment: I could *describe* it that way, but it has to be described in a table together with all the other quantities I've obtained. I have several of these curves, and the degree of difference differs from one plot to another, hence a table of values (instead of several graphs) is preferred. The idea is that the cyan curve is actually composed of two different types of users -- those in the red curve and those in the blue, each characterized by a different "typical value". I was actually debating whether to use median or mode in this case, but median seems better; but the uncertainty, I'm not sure.
Comment: Also, the sample size here is large (>20,000), and since this is the raw histogram, the proportion of red and blue users are comparable.
Comment: 1. (re previous comment) If you're trying to illustrate a difference, the standard errors on the individual means or medians doesn't convey the existence of a difference; it would be the standard error of the difference that would tell you more. 2. (re later comment) your comment about the relative proportions was not what I was getting at (not at all). But with very large $n$ you can just invoke asymptotic results for the standard error of the median.
Comment: I see. Seems there's a lot more to think about this case. Thanks for your inputs.


Display comma-separated list of taxonomy terms?

Question: In my node.tpl.php template, I want to print out a list of taxonomy terms (the taxonomy is called "channels.").  If I use:
<?php print render($content['field_channel']); ?>

It works, obviously, but the best I can do to get them inline is to use CSS to float them left. I would like them to be separated by commas.  Any ideas?
Answer: You could try theming the field using field.tpl.php or theme_field().
As an example (using field.tpl.php):

Copy field.tpl.php to your theme directory from "modules/field/theme"
Make a copy of that file and rename it to field--field-channel.tpl.php
Edit the file however you like.

As a quick/dirty example for this to work, field--field-channel.tpl.php could look like:
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php if (!$label_hidden) : ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item) : ?>
      <div style="display:inline;" class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>
        <?php
          print render($item);
          // Add comma if not last item
          if ($delta < (count($items) - 1)) {
            print ',';
          }
        ?>

    <?php endforeach; ?>

There are probably multiple ways to accomplish this using the .tpl file, but this is just one option.  I recommend adding a class to the DIV instead of a style and make the changes in your stylesheet instead of using inline styles.
Comment: Awesome, this worked perfectly.  I didn't know you could use templates on the fields like that.  Still have a lot to learn with this stuff.  Thanks again.
Comment: Using tpl files is a bit more resource intense and the preferred mode is to use the hook_field suggestion below.
Answer: The Text Formatter module is now available for Drupal 7, and lets you do this without custom theme work.

This module provides a field display formatter to render field values
as HTML or comma-separated lists. This can currently be used on all
core field types (text, long text, number, list, and taxonomy
reference etc..) and some contributed fields. (see below).
For multi-value fields, each field value becomes a list item. For long
text fields, each line becomes a list item.
Comment: Text Formatter module is probably the ideal solution to this now, as opposed to the chosen answer above which requires mucking around in the theme layer.
Answer: Here's one way to use the theme_field approach (add it to your template.php file):
/**
 * Implements theme_field()
 *
 * Make field items a comma separated unordered list
 */
function THEMENAME_field__NAME_OF_FIELD__NAME_OF_CONTENT_TYPE($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '
' . $variables['label'] . ':
';
  }

  // Render the items as a comma separated inline list
  $output .= '
';
  for ($i=0; $i < count($variables['items']); $i++) {
    $output .= '
'. drupal_render($variables['items'][$i]);
    $output .= ($i == count($variables['items'])-1) ? '
' : ',
';
  }
  $output .= '
';

  return $output;
}

Comment: Super great thanks this helped a lot actually! Also the preferred method then a tpl file!
Answer: You can do this easily just in CSS:

.field-type-taxonomy-term-reference .field-items .field-item {
  display: inline-block;
  *display: inline;
  *zoom: 1;
}
.field-type-taxonomy-term-reference .field-items .field-item:after {
  content: ", ";
}
.field-type-taxonomy-term-reference .field-items .field-item:last-child:after {
  content: "";
}
Comment: Thanks, although I had to use escaped Unicode for the space, like this `content: ", \00a0"`: http://stackoverflow.com/a/5467676/724176
Answer: Use a preprocess function:  http://planken.org/2009/08/03/create-comma-separated-taxonomy-term-list-drupal
Comment: Sorry this is for Drupal 6, just realized this is a D7 post
Answer: <?php
if ($node->taxonomy) {
    foreach($node->taxonomy as $term) {
        if ($term->vid == 3) { // the id of the vocabulary
            $my_terms[] = l(
                t($term->name),
                'taxonomy/term/' . $term->tid
            );
        }
    }
}

if ($my_terms) { ?>

            <?php print implode(", ", $my_terms); ?>

<?php } ?>

Comment: This is sidestepping the theme system, putting hard coded display logic into the tpl file and creating a maintenance headache.
Comment: Is it better to use side modules which are doing almost the same? Could you please provide a more maintenance-friendly code?
Answer: Even easier for delimiter and the wrapper, you use the Taxonomy Formatter module:
http://drupal.org/project/taxonomy_formatter
More details from project page:

This is a small module written to provide a custom formatter for taxonomy items. The default formatters both output the terms wrapped in divs. This module adds a new formatter that allows you to specify the element type, the wrapper type, classes for both, the separator used, and if they link to the term pages or not. This gives much more customizable layout options.


Ler arquivo txt e salvar em array PHP

Question: Tenho um arquivo txt, em que os dados são separados por |.
Gostaria de ler e separar o conteúdo de dentro de cada par de | em uma posição de um vetor. Porém não imprime quando coloco o print_r fora do while.
<?php
    $arquivo = fopen ('arq.txt', 'r');
    $result = array();
    while(!feof($arquivo)){
        $result = explode("|",fgets($arquivo));
    }
    fclose($arquivo);
    print_r($result);
?>

Answer: Então, uma pequena explicação de cada linha para que você possa se situar no próprio código:
    <?php
    // Aqui você abre e lê o arquivo
    $arquivo = fopen ('arq.txt', 'r');
    // Aqui você está definindo que a variável é um 'array()'
    $result = array();
    // Você agora irá verificar se existe o arquivo e se o código acim o leu (true|false)
    while(!feof($arquivo)){
        // Aqui foi onde você errou, pois seria '$result[]' e não '$result'
        $result[] = explode("|",fgets($arquivo));
    }
    // Fechando a leitura do arquivo
    fclose($arquivo);
    // Postando resultados
    print_r($result);
?>

O código limpo ficaria:
    <?php
    $arquivo = fopen ('arq.txt', 'r');
    $result = array();
    while(!feof($arquivo)){
        $result[] = explode("|",fgets($arquivo));
    }
    fclose($arquivo);
    print_r($result);
?>

No caso, você esqueceu de definir que a variável dentro do while continua sendo um array(), sendo assim ele não irá puxar nenhum resultado.
Comment: Oi Rapha! Obrigado por me ajudar, porém quando tento esse código, que vc gentilmente me passou, exibe o erro 500... Poderia me ajudar??
Comment: Dentro do seu log apresenta algum erro em específico?
Comment: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Comment: Sim, que ele exibe o **500 Internal Server Error** sabemos, mas você viu algum erro dentro do arquivo de log?
Comment: Como estou começando na programação ainda não sei do que se trata esse arquivo de log...
Comment: Editei o código, tente agora, por favor!
Comment: Obrigado por tentar de novo Rapha, porém ainda com erro 500.

Ler arquivo txt e salvar em array PHP


Performance. How do I get grid devices to sleep when not in use?

Question: I would like my grid items to sleep when there is neither audio nor note-events entering them.  I have a drum machine with a bunch of FX grids.  Here is a photo of the cpu usage when my grid devices are enabled vs disabled.  None of them are creating any audio, or receiving any audio.  None of them are receiving note events.  This is a fully silent, nothing running project.
Is there a way to make grid devices stop hogging cpu they don't need?  I would like for them to stop sending audio down the line once their envelopes are closed.
Answer: The grid uses a voice system to determine whether grid modules are in use. Using one of the mono voice modes will mean that the modules are always activate even when no note input is being received.
The best way to prevent this is to use a voice mode with multiple voices. When using polyphony (non-mono voices) the grid will not consume any CPU power if there is no note input. You can change polyphony modes from the inspector panel when you have one of the grids selected - the parameter is called 'voices', and there are three states true mono, digi mono and polyphony (where a number is shown). If voices show as 'mono' you can click and drag on it to set voices to a number.
The other piece of the puzzle with the polyphony grid mode is how bitwig knows to keep the voice active. There are a few different modules that determine if the voice is kept active:

ADSR or AR envelopes can be used to keep the voice alive after release for time period equal to the release parameter
The Audio Out I/O module can be used to keep the voice alive if there is audio output happening above a threshold
Gate In also keeps voices alive but just for the length of the incoming gate

For each of these you'll need to enable the 'keep voice alive' setting in the inspector panel for the module.
Comment: Thank you Pike!  I had been digging around after putting in this question and ended up trying all of the above.  Even with all the changes, the no-input grids are still consuming a lot of resources.  Marginally less at least.  I think I might have to actually automate turning them on and off to get them to where they should be.  Do you happen to know if the BItwig team does zero input optimization?  It seems strange that device chains don't inherently skip by each node if it's known zero in will equal zero out.
Comment: There is a new update available which has some grid performance updates - [5.0.5 Release notes](https://downloads.bitwig.com/5.0.5/Release-Notes-5.0.5.html).

If you have an example where performance is poor in a basic case you can share the preset with Bitwig support at email@example.com. In my experience they are very quick to respond to newly introduced issues.


Bayesian vs. Frequentist results question

Question: A researcher computes both a frequentist confidence interval, and a Bayesian credible interval. After the computation, the researcher realizes that the credible interval is much more narrow than the confidence interval. What could be a reason why this happened?
An analyst conducts both a Bayesian hypothesis test (using Bayes Factors) and classic NHST (using p-values). The Bayesian results indicate weak support for the null hypothesis, but the p-value is small, indicating that the null should be rejected. Consider a reason why this could happen.
We have discussed four ways of statistical inference in class (NHST, Confidence Intervals, Bayes Factors, Credible Intervals). For each of these four methods, describe BRIEFLY (one or two sentences) two advantages and two disadvantages. You can list reasons that we have covered in class, or you can be creative and anticipate certain problems or benefits of the methods.
Comment: @BruceET thank you that makes great sense. So if the credible interval is in the same area but only narrower than the confidence interval, then there must be some information we have included in the prior that gives us a more specific range of values that we are sure are the true values?
Comment: The Bayesian credible can be shorter than the frequentist CI if the Bayesian analysis uses an informative prior--especially an informative prior that is somewhat in agreement with the population.
Comment: That's the idea. See examples in my Answer.
Answer: Example: Consider $n = 100$ observations from a population with success probability $\theta = 1/4.$ Suppose the results are as sampled in R below,
with $X = 29$ Successes.
Frequentist confidence interval.
Then a frequentist Agresti-Coull 95% CI for $\theta$ is $(0.210, 0.386).$
set.seed(1015)
x = rbinom(1, 100, 1/4);  x
[1] 29
th.est = (x+2)/(100+4);  pm = c(-1,1)
th.est + pm*1.96*sqrt(th.est*(1-th.est)/104)
[1] 0.2101649 0.3859890

Bayestian credible interval from informative prior. Suppose the Bayesian prior distribution is $\theta \sim \mathsf{Beta}(10, 30),$ which puts 95% of its probability in $(0.130,0.393).$
qbeta(c(.025,.975),10,30)
[1] 0.1303768 0.3932615

Then with the given prior distribution and a binomial likelihood function
based on $x = 29$ successes in $n = 100,$ the Bayesian posterior distribution is $\mathsf{Beta}(10+x, 30+n-x) = \mathsf{Beta}(49, 101)$
and the Bayesian 95% posterior interval estimate is $(0.254, 0.404),$
which is somewhat shorter than the frequentist Agresti-Coull interval above.
qbeta(c(.025,.975), 49, 101)
[1] 0.2541815 0.4035301

Bayes credible interval from Jeffreys prior. By contrast, if the Bayesian analysis had begun with the non-informative
Jeffreys prior distribution $\mathsf{Beta}(0.5,0.5),$ then the Bayesian
credible interval would have been $(0.208, 0.384),$ much the same as the frequentist Agresti
interval.
qbeta(c(.025, .975), 29.5, 71.5)
[1] 0.2079839 0.3839729

Comment: thank you so much. This example is illuminating.
Comment: What do you suppose happens if I'm doing a Bayesian analysis and pretend to have prior knowledge which I don't really have, giving an "informative" prior that is pretty much _wrong:_ say $\mathsf{Beta}(30, 10).?$
Comment: Then we fail to reject the null? Or we draw an opposite conclusion?
Comment: While your question deals with both interval estimation and hypothesis testing, please notice that my answer deals explicitly only with interval estimation. So the question in my last comment has to do with credible intervals. Can you say what Bayesian interval estimate results from the data of my example and the prior $\mathsf{Beta}(30,10).?$ How long in that interval?
Comment: Just to make it clear, you are probably making the homework for OP
Comment: @Firebug. Your concern is valid. Been doing this for a while. Carefully giving examples and discussing issues, not working exact hwk problem. [Esp not if posted as (a), (b), (c), $\dots.]$ Sometimes simulate aprx results without showing analytic derivation (if deriv seems main point of exercise). // After some discussion (edited Q or in Comments) showing serious engagement by OP,  I may be willing to get into particulars.


Problem with home page misaligned on website

Question: The site in question is http://johannabolhoven.co.uk/.
As you can no doubt see, the home page seems to be misaligned from the other pages.
I've got the disable breadcrumbs module installed and I'm wondering if the problem is that the space is still being left for the disabled breadcrumbs, but it could also be something else.
I've tried (to the best of my ability) to disable the breadcrumb div in the template files, but that didn't seem to help either.
Comment: Link to website doesn't work.
Comment: noticed you are using Artisteer to create the Theme.  How do you like it?
Comment: The home page doesn't seem misaligned to me. I must say, my screen has a resolution of 1600x900; maybe that could explain why I don't see any issue.
Comment: There is less space between the main nav and the Johanna img on the home page than in the non-home pages.  See my answer below for the cause/fix.
Answer: Found it.  You have a custom content pane when you have an image that is inside of a p tag.  That p tag has a margin of 12px on the top and bottom and the image has 10px border on all sides.  Remove that and you should be good to go.

I got this from http://johannabolhoven.co.uk/personal_shopping.
Let me know if there were other issues that you had, but the home page being higher than the other pages was the only thing I could find.
Comment: Hi,
Thanks for the responses. I find Artisteer good for quick and dirty themes and if you are quite creative with it you can get some good results. Where it falls down is trying to make sense of what's going on behind the scenes when you do want to modify the code. I can't figure out how to fix the problem, even through it's now identified, as far as I can see all the pages are created the same way. In fact most of the other pages were cloned from the home page, which lead me to believe it is something to do with space for the breadcrumb.
Comment: In fact, I decided to try something. I modified the Personal Shopping page to the Home Page and vice versa and it became the Personal Shopping page that was out of line with the others. So my guess it is a result of the space for the breadcrumb.
Comment: Have you tried changing the css files manually?
Comment: Hi Nmillin,Apologies for the delay in responding to this but the client went on holiday so the project got shelved while they were away. I haven't tried changing the css files manually. I wouldn't know where to start. However I have noticed that it isn't just an artisteer themes problem. I changed the default to Bartik and the problem still exists. I think it's definitely a breadcrumb type of thing.#


Define new Imagefeatures with yocto

Question: in yocto imagebuildscripts there is a config variable named "IMAGE_FEATURES" i want to create a custom Imagefeature.
I searched my yocto installation which runs poky for existing imagefeatures but i wasn't able to find it.
Answer: IMAGE_FEATURES is a bit special, as its basically being hardcoded into image.bbclass.
Generally you are way better off creating custom DISTRO_FEATURES, and triggering on them whereever needed. See packagegroup-core-boot as an example of a recipe changing behaviour based on DISTRO_FEATURE in various places.
Usage wise there is little difference, the only thing you can't do is set DISTRO_FEATURES in the image recipe. If that is your actual need, then you probably should pour the new functionality in a custom image class the includes and extends image.bbclassm and call it myimage.bbclass (or similar).
EDIT:
Initially, I referred to the dropbear recipe as an example that triggers behaviour based on systemd being set as DISTRO_FEATURE. This is technically correct (and it was the first recipe that came to my mind), but probably confusing as there is a dropbear spedific IMAGE_FEATURE too.
Comment: isn't ssh-server-dropbear a imagefeature?

Define new Imagefeatures with yocto


Angularjs: convert string CSV format to Array

Question: I don't know how can I convert my string data in $scope.fileContent ( I got it from my CSV file) in array. I printed my $scope.fileContent:
console.log($scope.fileContent) =
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2

But I would like a function to convert it to a array like this:
[
  { heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1" }
  { heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" }
]

Any ideia of how to implement it in Angularjs?
I saw some examples but I didn't get with that, I guess the most releant is this.
Comment: [ng-csv](https://github.com/asafdav/ng-csv) could help you..
Answer: Using a CSV parsing library would probably be best.  I've used Papa Parse before and it worked great.  However, if you want to do it yourself...
function csvToArray(csvString) {
    var lines = csvString.split('\n');
    var headerValues = lines[0].split(',');
    var dataValues = lines.splice(1).map(function (dataLine) { return dataLine.split(','); });
    return dataValues.map(function (rowValues) {
        var row = {};
        headerValues.forEach(function (headerValue, index) {
            row[headerValue] = (index < rowValues.length) ? rowValues[index] : null;
        });
        return row;
    });
}

var x = "heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2";
console.log(csvToArray(x));

// OUTPUT
// [ { heading1: 'value1_1',
//    heading2: 'value2_1',
//    heading3: 'value3_1',
//    heading4: 'value4_1',
//    heading5: 'value5_1' },
//  { heading1: 'value1_2',
//    heading2: 'value2_2',
//    heading3: 'value3_2',
//    heading4: 'value4_2',
//    heading5: 'value5_2' } ]

Comment: Perfect! Thank you @Pace!! Now I need to do it but from Excel file (XLSX,XLS...) to a Array [object], if possible see this another question [link](http://stackoverflow.com/questions/41638768/angularjs-any-directive-to-convert-a-file-xlsx-xls-to-array-object-ou-other).


Sandbox module doesn't show any download link

Question: I've recently developed a module, Drupal to SugarCRM Lea', and decided to contribute to community. I've followed every steps on drupal.org to do so. I have managed to upload all my code to the sandbox, but my project page is not showing any download links for my module.

Repository
Module page

What did I forget to do?
Answer: Sandbox projects may not have releases.
There is a "Has project releases" checkbox, in the "Releases" vertical tab when you edit your sandbox, but it will be automatically cleared.
Thus it is not possible, but if you wish, you can apply for full project access.


how to add the audio name in database and audio file in folder?

Question: I tried to add the audio file into the folder and its name to database but file doesnot upload into the folder but it is added into the database.Following is my Controller:
public function add_audio(){

            $config['upload_path'] = './songs/';
            $config['allowed_types'] = 'mp3|3gp|mpeg|mp4';

            $this->load->library('upload',$config);
            $this->upload->do_upload('output');

            $data['audio'] = $_FILES['output']['name'];

            $this->load->model('main');
            $query = $this->main->insert('audio',$data);

            if($query = TRUE){

            $this->load->view('admin/success');

        }else{

        redirect($_SERVER['HTTP_REFERER']);
    }//end else
    }//end function

my folder name is songs.and database name is audio.Database is uploading the audio name but not the folder..so please help
Comment: is your `songs` folder at root directory??
Comment: yes...it is in root
Comment: Did you set the folder permission to 777??
Comment: I dont know what is that...and where to set the permission..i am new to the programming so would you help?
Answer: You need to set permission 777 to your upload directory. go to your root directory first and then use below command:
chmod 0777 songs/

check this to know more to change folder permission.
Comment: i didn't set the permission level for the image it works fine but do i have to set permission level to audio files?
Comment: you provide me the code but where to paste it.....please help...i am running windows and xampp as my server
Comment: @sudeepacharya it was actually a command to run on terminal....if it worked for image then it should work for songs folder too! try debugging...
If you want code then try putting `chmod('songs/', 0777);` this line before your `$this->upload->do_upload()`


How to determine the number of nilpotent $3\times 3$ matrices over $\mathbb F_2$?

Question: I've read that it equals, upto conjugation, the number of partitions of 3. Is that irrespective of the base field? In that case, shouldn't there be 4 nilpotent matrices over $\mathbb F_2$, upto conjugation?
Answer: An $n \times n$ matrix (over any field) is nilpotent iff it is similar to a matrix in Jordan canonical fo rm where all diagonal elements are $0$.  We may assume wlog that the sizes of the Jordan blocks are, say, nondecreasing.  The
sizes of the Jordan blocks give you the correspondence to partitions.  In the $3 \times 3$ case, there are $3$ partitions of $3$: $3$, $2+1$, $1+1+1$, corresponding to the following matrices:
$$ \pmatrix{0 & 1 & 0\cr 0 & 0 & 1\cr 0 & 0 & 0\cr},\
\pmatrix{0 & 1 & 0\cr 0 & 0 & 0\cr 0 & 0 & 0\cr},\
\pmatrix{0 & 0 & 0\cr 0 & 0 & 0\cr 0 & 0 & 0\cr}$$


Determining whether a user specified point is inside a 2d polygon

Question: I've done some research and there are many methods to doing this if the vertices and points are predetermined as seen here. However in my case, everything is specified by the user. The code I have put together (with the help of others), allows the user to create the polygon, and place points. I wrote functions to try and create vectors from the point to the vertices and then compute the angle. If it comes to 360 it should be inside and it should be colored green. Else it should be outside and red.
This is what I've been working on, but I cant seem to figure it out:
(Edit: Included my entire code)
GLint vert[100][2];
int width = 400, height = 600, n = 0, m = 0, type = GL_LINE_STRIP, v;
bool rubberbanding = false;
bool closed = false;

double testx, testy;
bool isitin;

double dotp(double x1, double y1, double x2, double y2) {
    double a;
    a = (x1 * x2) + (y1 * y2);
    return a;
}

double mag(double x1, double y1, double x2, double y2) {
    double a;
    double x = (x2 - x1);
    double y = (y2 - y1);
    a = sqrt((x*x) + (y*y));
    return a;
}

bool inpoly(int numv, GLint vx[][2], GLint vy[][2], double tx, double ty) {
    double angle = 0.0;
    int n = 0;
    while (n != numv) {
        //vector from point to vertex
        double newv1x = vx[n][0] - tx;
        double newv1y = vy[n][1] - ty;
        double magv1 = mag(tx, ty, vx[n][0], vy[n][1]); //magnitude of vector

        //vector from point to next vertex
        double newv2x = vx[n + 1][0] - tx;
        double newv2y = vy[n + 1][1] - ty;
        double magv2 = mag(tx, ty, vx[n+1][0], vy[n+1][1]);//magnitude of vector

        //dot product between the two vectors
        double dp = dotp(newv1x, newv1y, newv2x, newv2y);

        //angle between two vectors
        double vang = acos(dp / (magv1*magv2));

        angle += vang;

        n++;
    }

    //vector from point to last vertex
    double newv1x = vx[numv][0] - tx;
    double newv1y = vy[numv][1] - ty;
    double magv1 = mag(tx, ty, vx[numv][0], vy[numv][1]); //magnitude of vector

    //vector from point to first vertex
    double newv2x = vx[0][0] - tx;
    double newv2y = vy[0][1] - ty;
    double magv2 = mag(tx, ty, vx[0][0], vy[0][1]);//magnitude of vector

    //dot product between the two vectors
    double dp = dotp(newv1x, newv1y, newv2x, newv2y);

    //angle between two vectors
    double vang = acos(dp / (magv1*magv2));

    angle += vang;

    if (angle == 360.0) return true;

    return false;

}

void display(){
     glClear(GL_COLOR_BUFFER_BIT);
     glColor3f(1, 1, 0);
     glBegin(closed ? GL_LINE_LOOP : GL_LINE_STRIP);
     for(int i = 0; i < m; i++){
             glVertex2iv(vert[i]);
     }
     glEnd();
     /*
     glColor3f(0, 0, 1);
     glBegin(GL_POINTS);
     for (int i = m; i < n; i++) {
         glVertex2iv(vert[i]);
     }
     */

     isitin = inpoly(m, vert, vert, testx, testy);

     if (isitin == true) {
         glColor3f(0, 1, 0);
         glBegin(GL_POINTS);
         for (int i = m; i < n; i++) {
             glVertex2iv(vert[i]);
         }
     }
     else {
         glColor3f(1, 0, 0);
         glBegin(GL_POINTS);
         for (int i = m; i < n; i++) {
             glVertex2iv(vert[i]);
         }
     }

     glEnd();
     glutSwapBuffers();
     glutPostRedisplay();
}

void keyboard(unsigned char key, int x, int y){
     switch(key){
                 case 'r': n = 0; m = 0; closed = false; break;

                 case 'c': closed = true; break;
     }
     glutPostRedisplay();
}

int findVertex(int x, int y){
    int dx, dy;
    for(int i = 0; i < n; i++){
            dx = vert[i][0] - x;
            dy = vert[i][1] - y;
            if(dx*dx + dy*dy < 16) return i;
    }
    return - 1;
}

void mousemove(int x, int y)
{
    testx = x;
    testy = height - 1 - y;
}

void mouse(int button, int state, int x, int y){
     switch(button){
     case GLUT_LEFT_BUTTON:
                         if(state == GLUT_DOWN){
                             if (n < 100) {
                                v = n++;
                                vert[v][0] = x;
                                 vert[v][1] = height - 1 - y;

                                // n++;
                                 rubberbanding = true;
                                 glutPostRedisplay();

                                 if (!closed) m = n;
                             }
                         }
                         else{
                                  rubberbanding = false;
                         }
                         break;
     }
}
void motion(int x, int y){
     if(rubberbanding){
                       vert[v][0] = x;
                       vert[v][1] = height - 1 - y;
                       glutPostRedisplay();
     }
}

void main(int argc, char** argv){
     glutInit(&argc, argv);
     glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE);
     glutInitWindowSize(width,height);
     glutInitWindowPosition(50,100);
     glutCreateWindow("Project 3");
     glClearColor(0.0,0.0,0.0,0.0);
     glColor3f( 1, 1, 0);
     glMatrixMode(GL_PROJECTION);
     glLoadIdentity();
     gluOrtho2D(0, width, 0, height);
     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
     glutDisplayFunc(display);
     glutKeyboardFunc(keyboard);
     glutMouseFunc(mouse);
     glutPassiveMotionFunc(mousemove);
     glutMotionFunc(motion);
     glutMainLoop();
}

When I run the program in Visual Studio, I can draw the polygon, and I can specify

points, but for some reason all the points appear red. If anyone has any ideas on how to fix this, it would be greatly appreciated.
Comment: did you check if your `inpoly` function work? can be simply done by `cout` or debugger.
Comment: That is where my problem is, its not working right. And im not sure how to fix it.
Comment: so the rendering part is all right?
Comment: Im not sure what you mean by the 'rendering part'.

Im pretty sure its the inpoly function that isnt working properly. When i use cout in the inpoly function to output the final angle, I get a continuous stream of random decimals.
Comment: I actually think I was able to figure it out. Only thing is that all the colors change when I create a new point. Do you know of anyway that I can stop all the colors from changing when I create a new point?
Answer: Probably your error is that acos returns in radians, and you're testing if the sum equals 360 degrees.
Also, you shouldn't compare doubles that way, since that calculation is probably adding rounding error in each sum. See here for more information.
Comment: I completely forgot that acos returns in radians, good catch. Unfortunately, my program still isnt working the way I want it too. I think my `inpoly` function is still messed up but im not sure how to fix it.
Comment: I actually think I was able to figure it out. Only thing is that all the colors change when I create a new point. Do you know of anyway that I can stop all the colors from changing when I create a new point?


implode(): Invalid arguments passed

Question: Estou trabalhando num sistema para upload de conteúdos e diversas fotos no qual preciso mudar os nomes dos arquivos usando a hash md5 e criando uma string com os novos nomes porém estou encontrando dificuldades em usar o MD5 com o implode;
//segue parte do meu código
$string = implode( ";", md5($fotos['name']) );
                   echo $string;
}

//segue o erro
implode(): Invalid arguments passed

//Queria que a string final fosse algo como:
46e3cca98604344b0dcc1dfbf4d96c68.jpg;abfb69de2141ef5002ce364ccf7af37d.jpg;

//código completo
//faz a conexão
include( "../../../include/funcoes/conexao.php" );
//calcula o tamanho do arquivo
include( "../../../include/funcoes/tamanho-arquivo.php" );

//resgata as variáveis
$titulo = $_POST["titulo"];
$categoria = $_POST["categoria"];
$conteudo = addslashes( $_POST["texto"] );
$status = $_POST["status"];
$tag = $_POST["tag"];

//inicia a função
if ( isset( $_FILES['arquivos'] ) && !empty( $_FILES['arquivos']['name'] ) ) {
    //pega o nome
    $fotos = $_FILES['arquivos'];
    //quantidade de fotos
    $total = count( $fotos['name'] );
    //executa o laço
    for ( $i = 0; $i < $total; $i++ ) {
   //pega o caminho
        $caminho = "../fotos/";
        //pega o nome
        $nome = pathinfo( $fotos['name'][$i], PATHINFO_FILENAME );
        //pega a extensão
        $entensao = pathinfo( $fotos['name'][$i], PATHINFO_EXTENSION );
        //pega o endereço do arquivo, nome e a extensão
        $nome_final = $caminho.md5($nome).".".$entensao;
        //pega o tamanho do arquivo
        $tamanho = tamanho_arquivo( $caminho.md5($nome).".".$entensao );
        //verifica a extensão do arquivo
        if ( $entensao != "jpg" and $entensao != "jpeg" and $entensao != "png" and $entensao != "webp" and $entensao != "gif" ) {
            //exibe a mensagem
            echo "O arquivo precisa ser uma imagem";
        } else {
            //verifica o tamanho
            if ( $tamanho >= "1024" ) {
                //exibe a mensagem
                "O arquivo é muito grande. É preciso carregar fotos com menos de 1MB";
            } else {
                //executa o upload
                if ( move_uploaded_file( $fotos['tmp_name'][$i], $nome_final ) ) {

                    //exibe a mensagem
                    echo "Upload realizado com sucesso";

                } else {
                    //exibe a mensagem
                    echo "Houve um erro com upload do arquivo, por favor verifique o tamanho das imagens e tente novamente!";
                }
            }
        }
    }
}

$string = implode( ";", md5($fotos['name']) );
echo $string;

Answer: Há 2 problemas acontecendo no código. O primeiro é que a função md5() espera ter uma string como parâmetro e no código você está passando um array à ela ($fotos['name']):
$string = implode( ";", md5($fotos['name']) );

O outro problema é que o segundo parâmetro da função implode() deve ser um array e, como a função md5() retorna uma string, o erro implode(): Invalid arguments passed aparece.
Uma forma de resolver o problema é criar um novo array com os nomes das fotos já formatados e depois passar este array na função implode():
$fotos_renomeadas = [];
foreach ($fotos['name'] as $key=>$foto){
        $fotos_renomeadas[$key] = md5($foto).".jpg";
}
$string = implode( ";", $fotos_renomeadas);
echo $string;

O output será:
# Considerando fotos['name'] = ['img1','img2']

a8a63b4d63a08aed720d0f5f249e07d9.jpg;fe5067706fde605fcc635835a1e52fc8.jpg

Comment: Obrigado! Resolveu. Santa sabedoria, hein Batman?

implode(): Invalid arguments passed