CoffeeScript Existential Operator and this

Question: I noticed something a little odd with the CoffeeScript compilier and was wondering if this was correct behavior or not. If it is correct I'm curious why there is a difference..
Given the following CoffeeScript:
if @myVar?
  alert myVar

I was expecting it to compile to JavaScript like this:
if (typeof this.myVar !== "undefined" && this.myVar !== null) {
  alert(myVar);
}

But instead what the CoffeeScript compiler outputs is this:
if (this.myVar != null) {
  alert(myVar);
}

If I don't reference this (or any other parent object), the CoffeeScript compiles as I would expect.
Is this the correct behavior? If so, why does it work different when using this?
Edit:
To add a little more clarification. This doesn't happen with only this, but any other properties of objects. For instance, if I were replace the above CoffeeScript with what's below it still would compile with only "!= null"...
if myVar.myProp?
  alert myVar

Comment: possible duplicate of [Existential operator and object properties](http://stackoverflow.com/questions/9990117/existential-operator-and-object-properties)
Answer: In the case of:
myVar = 10
if myVar?
  alert myVar

Coffeescript compiler is able to see that myVar is really defined in the first line, so it can omit typeof myVar !== "undefined" check.
if (myVar !== null) {
  alert(myVar);
}

But in this case:
if myVar?
  alert myVar

compiler can't guarantee that myVar is actually defined, so extra check is required:
if (typeof myVar !== "undefined" && myVar !== null) {
  alert(myVar);
}

So, the answer is: Coffeescript compiler tries to be smart to produce efficient code.
EDIT
The way Coffeescript deals with properties is also correct: this.prop will return undefined if property is not defined. != will convert it to null. That is why we don't need additional check.
In few words:

accessing undefined variable throws exception -- need to check typeof
accessing undefined property returns undefined -- just != is enough
Comment: I understand that. My question had more to do with checking existence of properties on objects.. this.var, or that.var.property.. etc.. it omits the undefined check and only does a != null instead of !== null...
Comment: I understand now. I have to chalk this up to my lack of understanding of the CoffeeScript compiler :) I really didn't know it was smart enough to make these "decisions". That's really good to know, though. Thank you very much for the insight!


MariaDB Galera Clustering - Active Active - Operation not permitted error

Question: I am having issues with MariaDB and Galera running on RHEL 6.4 & 6.2 64bit servers and getting them to cluster. I installed the required RPM's for Galera clustering:

MariaDB-Galera-server
MariaDB-client
MariaDB-compat
MariaDB-common
MariaDB-shared
MariaDB-test
galera

Then after installing MariaDB and all of its components, I checked the directories where it normally keeps its files, /var/lib/mysql/ and /var/log/mysql/ and performed a
chown -R mysql:mysql /var/lib/mysql/
chown -R mysql:mysql /var/log/mysql/

I started both servers in standalone mode and configured a replication user:
grant all privileges on *.* to 'mariadb-user'@'localhost' identified by 'password' with grant option;
grant all privileges on *.* to 'mariadb-user'@'%' identified by 'password' with grant option;

That way, I would have a user for the databases to communicate with. Then I edited my configs on both the Master and Slave nodes:
#
# These groups are read by MariaDB server.
# Use it for options that only the server (but not clients) should see
#
# See the examples of server my.cnf files in /usr/share/mysql/
#

# this is read by the standalone daemon and embedded servers
[server]
general_log_file=/var/log/mysql/mysqld.log
general_log=1
log_warning=2
log-error=/var/log/mysql/error.log
#log-bin=/var/log/mysql-bin.log
log-slow-queries=/var/log/mysql-slow-queries.log
# this is only for the mysqld standalone daemon
[mysqld]

# this is only for embedded server
[embedded]

# This group is only read by MariaDB-5.5 servers.
# If you use the same .cnf file for MariaDB of different versions,
# use this group for options that older servers don't understand
[mysqld-5.5]

# These two groups are only read by MariaDB servers, not by MySQL.
# If you use the same .cnf file for MySQL and MariaDB,
# you can put MariaDB-only options here
[mariadb]
wsrep_cluster_address=gcomm://mariadb-master.net,mariadb-slave.net
wsrep_provider=/usr/lib64/galera/libgalera_smm.so
binlog_format=ROW
default_storage_engine=InnoDB
innodb_autoinc_lock_mode=2
innodb_locks_unsafe_for_binlog=1
wsrep_cluster_name=corp-zabbix-server
wsrep_debug=on
wsrep_sst_auth=mariadb-user:cerner
##wsrep_sst_auth=root:
wsrep_sst_method=mysqldump
##wsrep_sst_method=xtrabackup
[mariadb-5.5]

Once the configs were in place, I made sure that the firewalls allowed the traffic to go through, basically by just wiping them out iptables -F. Then I initialized the cluster on the master using:
/etc/init.d/mysql start --wsrep_cluster_address=gcomm://

The Process comes up on the Master node, and on the Slave node using:
service mysql start

The slave node then connects for a bit, exchanges states, and exits saying that the operation is not permitted.
MariaDB_Error_Log at Pastebin.com
This is the output from /var/log/mysql/mysql.log:
/usr/sbin/mysqld, Version: 5.5.32-MariaDB-log (MariaDB Server, wsrep_23.7.5.rXXXX). started with:
Tcp port: 0  Unix socket: (null)
Time                 Id Command    Argument
/usr/sbin/mysqld, Version: 5.5.32-MariaDB-log (MariaDB Server, wsrep_23.7.5.rXXXX). started with:
Tcp port: 0  Unix socket: (null)
Time                 Id Command    Argument
130910  8:18:48     3 Connect   firstname.lastname@example.com as anonymous on
                    3 Query     select @@version_comment limit 1
                    3 Query     SET wsrep_on=OFF
                    3 Query     SELECT @@GENERAL_LOG
                    3 Quit
                    4 Connect   email@example.com as anonymous on
                    4 Query     select @@version_comment limit 1
                    4 Query     SET wsrep_on=OFF
                    4 Query     SELECT @@SLOW_QUERY_LOG
                    4 Quit
                    5 Connect   firstname.lastname@example.com as anonymous on
                    5 Query     select @@version_comment limit 1
                    5 Query     SET wsrep_on=OFF
                    5 Query     SET GLOBAL GENERAL_LOG=OFF
/usr/sbin/mysqld, Version: 5.5.32-MariaDB-log (MariaDB Server, wsrep_23.7.5.rXXXX). started with:
Tcp port: 3306  Unix socket: /var/lib/mysql/mysql.sock
Time                 Id Command    Argument
130910  8:18:50     7 Query     SET GLOBAL SLOW_QUERY_LOG=1
                    7 Quit
130910  8:18:51     8 Connect   email@example.com as anonymous on
                    8 Query     select @@version_comment limit 1
                    8 Query     SET wsrep_on=OFF
                    8 Query     SELECT @@GENERAL_LOG
                    8 Quit
                    9 Connect   firstname.lastname@example.com as anonymous on
                    9 Query     select @@version_comment limit 1
                    9 Query     SET wsrep_on=OFF
                    9 Query     SELECT @@SLOW_QUERY_LOG
                    9 Quit
                   10 Connect   firstname.lastname@example.com as anonymous on
                   10 Query     select @@version_comment limit 1
                   10 Query     SET wsrep_on=OFF
                   10 Query     SET GLOBAL GENERAL_LOG=OFF
/usr/sbin/mysqld, Version: 5.5.32-MariaDB-log (MariaDB Server, wsrep_23.7.5.rXXXX). started with:
Tcp port: 3306  Unix socket: /var/lib/mysql/mysql.sock
Time                 Id Command    Argument
130910  8:18:52    12 Query     SET GLOBAL SLOW_QUERY_LOG=1
                   12 Quit
130910  8:18:53    13 Connect   email@example.com as anonymous on
                   13 Query     select @@version_comment limit 1
                   13 Query     SET wsrep_on=OFF
                   13 Query     SELECT @@GENERAL_LOG
                   13 Quit
                   14 Connect   email@example.com as anonymous on
                   14 Query     select @@version_comment limit 1
                   14 Query     SET wsrep_on=OFF
                   14 Query     SELECT @@SLOW_QUERY_LOG
                   14 Quit
                   15 Connect   email@example.com as anonymous on
                   15 Query     select @@version_comment limit 1
                   15 Query     SET wsrep_on=OFF
                   15 Query     SET GLOBAL GENERAL_LOG=OFF
/usr/sbin/mysqld, Version: 5.5.32-MariaDB-log (MariaDB Server, wsrep_23.7.5.rXXXX). started with:
Tcp port: 3306  Unix socket: /var/lib/mysql/mysql.sock
Time                 Id Command    Argument
130910  8:18:55    17 Query     SET GLOBAL SLOW_QUERY_LOG=1
                   17 Quit

I'm not sure what else I should do. I had this cluster working before, but I reverted to the snapshot right after I had the OS baseline completed. So, in my mind, it should have worked the same way, but it didn't. Should I create a local user on the boxes themselves named the same as the database user?
Answer: If you look at the error messages on the pastebin link, on line 18 and 19, there is a reference to this:
130906 12:47:32 [ERROR] mysqld: File '/var/log/mysql-slow-queries.log' not found (Errcode: 13)
130906 12:47:32 [ERROR] Could not use /var/log/mysql-slow-queries.log for logging (error 13). Turning logging off for the whole duration of the MySQL server process. To turn it on again: fix the cause, shutdown the MySQL server and restart it.

What I had done is when I made my config file, I finger fudged a line:
log-slow-queries=/var/log/mysql-slow-queries.log

Once I edited this line to reflect:
log-slow-queries=/var/log/mysql/mysql-slow-queries.log

The cluster magically worked. I am able to replicate between databases and have them function now. I'm not exactly sure why that one line would prevent everything from working, but it did.


jQuery not working in Chrome 18

Question: Nothing in jQuery appears to be working in Chrome for me. My version is 18.0.1025.151 m. The javascript is in the file test.js:
$('#paragraph').click(function() {
$('#paragraph').hide();
});

And the html is this:
<!doctype html>

    <meta charset="utf-8">
    <title>jQuery Example</title>

This is my paragragh 401!

I have triple-checked that the jQuery file is where it's supposed to be. Essentially, the code is supposed to make the paragraph disappear when clicked on. Seems simple enough and syntactically correct. I chose such a simple code because while regular javascript statements and code work fine (such as alert() and whatnot), absolutely nothing in jQuery has worked so far at all.
Here's the strange part though. When using the console in Chrome's developer tools, if I input the exact same jQuery stuff and hit enter, it actually works and functions how it's supposed to.
Does this have anything to do with Chrome's security structure or something?
Edit: Also, I should note that I have not yet uploaded these files on my server yet. This is on localhost (I'm using xammp for what it's worth), so perhaps that may help shed some light on the issue.
Comment: Downvoters, cool your trigger fingers.  Even though the question essentially asks about something pretty basic, this is actually a well-written question that shows actual [effort](http://tinyurl.com/so-hints) on the part of the asker.
Comment: do you have your javascript wrapped in a document.ready function?
Comment: So according to your question title, this problem is specific only to Chrome 18? It works in all other browsers?
Comment: Oddly enough, it works with Firefox and Internet Explorer 9.
Answer: Wrap the code in a document ready, or put test.js before the end body tag.
Comment: Regardless you should learn how to do the doc ready thing as per the other answer, as sometimes it isn't always feasible to put the script before the end body tag.
Comment: Wow, placing scripts at the end of the body works! Thanks a lot people! This site rocks. :)
Answer: It's executing before the DOM is ready. It should look like this:
$(function(){
    $('#paragraph').click(function() {
        $('#paragraph').hide();
    });
});

To address the comment below:
http://api.jquery.com/ready/

The .ready() method is typically used with an anonymous function:

$(document).ready(function() {
  // Handler for .ready() called.
});

Which is equivalent to calling:

$(function() {
 // Handler for .ready() called.
});

Comment: @iambriansreed I do believe you are incorrect good sir. :) See my edit.
Comment: @iambriansreed No worries. I like the coffeecript version even more though, it's simply: `$ -> `
Answer: You have to wrap it in document ready. That's probably your problem. Also you can use $(this) or cache the selector.
$(function () {
    $('#paragraph').click(function () {
        $(this).hide();
    });
});

jQuery not working in Chrome 18


query mysql database containing HTML special character with php

Question: ...i am not getting any further.
my database contains a column 'name' = 'John Richards'
i try to query it like:
<code>$act = "John Richards";
prepareEditing($act);

function prepareEditing($act) {
include ($_SERVER['DOCUMENT_ROOT']."/final_ritg/includes/dbconnect.php");
$act = str_replace(" ", " ", $act);
$sql = "select `name`,`genre`, `members`, `story`, `image`, `contact_fname`, `contact_lname`, `contact_phone`, `contact_email` from `festival`.`act` where `name` = :name ;";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $act);
$stmt->execute();

echo $stmt->rowCount();
}
</code>
when 'name' only contains a single word, like 'john', the function returns 1 ($act holds 'john' as well).
How do I have to prepare my query?
Edit: I am using utf8 across the board.
Edit: This is the prepare stmt I use to insert the data:
    $stmt->bindParam(':name', str_replace(' ',' ',$name));
I did so, because the query result would have been cut off at the whitespace when trying to retrieve it.
Comment: I was going to add that even though you have the variable being replaced in the query string, it should be enclosed in quotes. So rather than `"name" = :name`, you should do `"name" = ':name'`.
Comment: That's not how PDO works. Placeholders are given quotes if and when they are required. See the [prepared statements docs](http://php.net/manual/en/pdo.prepared-statements.php) for more details.
Comment: Are you sure the value is literally what you're selecting against? Trailing or doubled spaces can interfere with exact matches.
Answer: As it turns out, my mistake was not in the php, but inside the html.
I was creating a select list from a table. because the names were unique, i used those as primary keys and as value for each select-option...those dont like whitespace.
The solution here would be to either add a numbered index to the table or to do some string-conversion (but that would cause a lot of extra work preparing the string for the query) I dont yet know how I would be going over this.
Anyways, maybe another beginner runs into the same trap and finds this useful.


Capturar a URL através do código Admob

Question: Quero gravar a url do componente BannerAd após efetuar o Load, percebo que o componente passa a url ao navegador padrão do dispositivo. O código é o seguinte:
    unit Unit1;

    interface

    uses
    System.SysUtils, System.Types, System.UITypes, System.Classes,System.Variants,
    FMX.Types, FMX.Controls,
    FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
    FMX.Controls.Presentation, FMX.Edit, FMX.Advertising;

    type
    TForm1 = class(TForm)
    BannerAd1: TBannerAd;
    procedure FormCreate(Sender: TObject);
    private
    { Private declarations }

     public
    { Public declarations }
     end;

     var
     Form1: TForm1;

     implementation

     {$R *.fmx}

     procedure TForm1.FormCreate(Sender: TObject);
     begin
       BannerAd1.AdUnitID := 'Código fornecido pelo Admob';
       BannerAd1.LoadAd;
     end;

     end.

Alguém tem alguma ideia de como posso fazer?
Comment: Deve postar o código para facilitar o entendimento e a resposta.
Comment: ok, ja editei o post
Answer: BannerAd1.AdUnitID := 'Aqui vem o id que é dado, com esse id carrega a propaganda';
BannerAd1.LoadAd;
BannerAd1.visible:= true;

Capturar a URL através do código Admob


Zend php function error - Warning: array_merge(): Argument #1 is not an array in

Question: I've this function and am getting this error
Warning: array_merge(): Argument #1 is not an array in

$diff = array_merge($followers['ids'], $friends['ids']);

then
Invalid argument supplied for foreach() in

Function:
 public function addtosystemAction(){
        $this->_tweeps = new Application_Model_Tweeps();
        $http = new Zend_Http_Client();
        $http->setUri('http://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=testuser');
        $followers = Zend_Json::decode($http->request()->getBody(), true);
        $http->setUri('http://api.twitter.com/1.1/friends/ids.json?cursor=-1&screen_name=testuser');
        $friends = Zend_Json::decode($http->request()->getBody(), true);
        $diff = array_merge($followers['ids'], $friends['ids']);
        $resultArray = array();
        foreach ($diff as $id){
            if(FALSE == $this->_tweeps->checkExisting($id)){
                $resultArray[] = $id;
                if(count($resultArray) == 50){
                    break;
                }
            }
    }

Any tips why I'm getting this error ?
Comment: Have you tried debugging ? Check using `var_dump($followers['ids']);` if is it array or not.
Answer: you should check if array is empty before passing to the function
Try this
public function addtosystemAction(){
    $this->_tweeps = new Application_Model_Tweeps();
    $http = new Zend_Http_Client();
    $http->setUri('http://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=testuser');
    $followers = Zend_Json::decode($http->request()->getBody(), true);
    $http->setUri('http://api.twitter.com/1.1/friends/ids.json?cursor=-1&screen_name=testuser');
    $friends = Zend_Json::decode($http->request()->getBody(), true);

    if( (!empty($followers['ids'])) && (!empty($friends['ids'])) ){
      $diff = array_merge($followers['ids'], $friends['ids']);
      $resultArray = array();
      if(!empty($diff)){
      foreach ($diff as $id){
        if(FALSE == $this->_tweeps->checkExisting($id)){
            $resultArray[] = $id;
            if(count($resultArray) == 50){
                break;
            }
        }
      }
     }
    }
}

Answer: It looks like you're not authenticating when connecting to the Twitter API. Both of your links result in {"errors":[{"message":"Bad Authentication data","code":215}]} when not authenticated, and in that case, $followers['ids'] won't be an array because it doesn't exist.
Twitter's API documentation contains information on authentication.
If that's not the issue, I apologise, but it looks like it judging by your code.


how to upload image folder to colab?

Question: I was trying to upload a big image folder into google drive and github but github not allowed and google drive taking too long. How can I upload the local folder to colab.
Comment: Google Drive sync is likely the best option. How large is the folder, and what's the transfer rate?
Comment: about 345MB, taking too long.
Comment: you are saying it takes too long because of slow internet?
Comment: internet speed is fine
Answer: Sorry, I don't think there's a solution to your issue. If your fundamental problem is limited upload capacity from the machine with the images, you'll just need to wait.
A nice property to uploading to Drive is that you can use programs like Backup and Sync to retry the transfer until it's successful. And, once the images have been uploaded to Drive once, you'll be able to access them quickly in Colab thereafter without uploading again. (See this example notebook showing how to connect your Google Drive files to Colab as a filesystem.)
Answer: convert the folder to zip file and then upload it on colab.
further you can unzip your folder by following command.
! unzip "your path"
Answer: The unzip method only works for csv files.
If you use a kaggle dataset, use
os.environ['KAGGLE_USERNAME'] = 'enter_username_here' # username
os.environ['KAGGLE_KEY'] = 'enter_key_here' # key

!kaggle datasets download -d dataset_api_command_here

If you have the image in google drive, use
from google.colab import drive
drive.mount('/content/drive')

how to upload image folder to colab?


INNER JOIN Statement

Question: I know this is a simple INNER JOIN statement, I just can't get the syntax correct.
The scenario is this, Table 1 (AllUserData) contains the INT7 and INT6 fields.  INT7 is basically "Requested by" and INT6 is "Requested for".  These 2 fields contain an ID. Table 2 (UserInfo) has the field tp_ID which hold their ID and tp_Title is their name.
What I currently have is:
    SELECT alluserdata.int7, alluserdata.int6, UserInfo.tp_ID,
           userinfo.tp_Title
    FROM alluserdata
    INNER JOIN UserInfo on AllUserData.int7 = UserInfo.tp_ID or
                           AllUserData.int6 = UserInfo.tp_ID

The problem with that is, the output will be on two lines.  One line will show the "Requested by" name (int7) and one line will show the "Requested for" name (int6).  I want these entries to be on the same line.
Comment: Could you provide some sample data and expect result?
Comment: Do a double LEFT JOIN.
Answer: You need to JOIN twice:
SELECT a.int7, a.int6,
       u1.tp_ID, u1.tp_Title,
       u2.tp_ID, u2.tp_Title
FROM alluserdata a
LEFT JOIN UserInfo u1 on a.int7 = u1.tp_ID
LEFT JOIN UserInfo u2 ON a.int6 = u2.tp_ID
WHERE u1.tp_ID is not null or u2.tp_ID is not null;

Comment: where u1.tp_ID is not null or u2.tp_ID is not null
Comment: That was it. Thank you very much!

INNER JOIN Statement


Subgroup analysis

Question: I have a total of 3 studies in a meta-analysis. Using a group of 1 and then a group of 2 for subgroup analysis gives me the results for group 2 but for group 1 it says heterogeneity can't be calculated. However, between the groups, it does give me the result. Does this mean I can use the overall subgroup results?
Comment: "it says heterogeneity can't be calculated", "it does give me the result" - what's "it"?
Answer: I assume you are using the measure $I^2$ to assess heterogeneity. The point of measuring heterogeneity in meta-analysis is to assess if the proportion of difference in the estimates between the studies is due actual differences in the associations rather than sampling error.  This measure is really not useful if you have too few studies, such as 3. Maybe it would be more insightful to just make a descriptive comparison between the studies! For instance, you could compare the sample characteristics and the difference in the model specifications (if there are any).
To answer your specific question: if in one group you only have one study there is no heterogeneity to calculate. To make an analogy, it's like a dataset where you only have one observation, you can't calculate the variance! And in the case you have two observations, it's like computing the variance among them; you can still do it, but it might be more useful to try a different strategy.
Comment: Thank you for your reply! The two groups are focal and generalised epilepsy. The focal group has 1 paper and generalised has 2. So would I be able to use the results from the generalised subgrouping? it has significant heterogeneity with I2 = 95% and p=0.0003 and since there is no heterogeneity to calculate in the focal group the heterogeneity is caused by something else e.g. if I subgrouped by gender?

Subgroup analysis


Deb 6: Can't install Mongodb 64; uname -m and arch both return x86_64

Question: As the title suggests, in bash the commands uname -m and arch both return x86_64, suggesting to me that I'm on a 64bit OS and processor. But, when I use aptitude or apt-get to install the package mongodb-10gen, the 32-bit version is installed.
So, I tried downloading the 64bit tarball:
curl http://downloads.mongodb.org/linux/mongodb-linux-x86_64-2.4.4.tgz > mongodb.tgz
tar -zxvf mongodb.tgz

But then, when I try to run one of the executables therein (from within the untarred directory) ./bin/mongo, the response is "No such file or directory." The case is the same for all of the executables in the bin directory, though they very clearly DO exist.
What's going on here? Is uname -m misreporting the OS?
Update I know permissions aren't the problem. I ran chown -R myusername mongodb/ and chmod -R 777 mongodb/ with mongodb/ being where I moved the untarred directory to.
Comment: What does `uname -a` say?
Comment: `uname -a` returns:
`Linux mormonmoves 3.9.3-x86_64-linode33 #1 SMP Mon May 20 10:22:57 EDT 2013 x86_64 GNU/Linux`
Answer: You are missing shared libraries. Run ldd ./bin/mongo to see which ones.
However, you should use the 10gen repo. Do you see any configs in /etc/apt/conf.d setting APT::Architecture? If not, try forcing the architecture with apt-get install mongodb-10gen:amd64.
Edit: Are you using the 10gen repo? If not run apt-add-repository http://downloads-distro.mongodb.org/repo/debian-sysvinit dist 10gen
Edit2: WFM:
~/tmp$ curl http://downloads.mongodb.org/linux/mongodb-linux-x86_64-2.4.4.tgz > mongodb.tgz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 90.2M  100 90.2M    0     0  4088k      0  0:00:22  0:00:22 --:--:-- 4393k
~/tmp$ tar -zxf mongodb.tgz
~/tmp$ cd mongodb-linux-x86_64-2.4.4/
~/tmp/mongodb-linux-x86_64-2.4.4$ bin/mongo
MongoDB shell version: 2.4.4
connecting to: test
Fri Jun 14 13:44:59.379 JavaScript execution failed: Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112
exception: connect failed

Comment: `ldd ./bin/mongo` returned the same error, `ldd: ./bin/mongo: No such file or directory`

Running `apt-get install mongodb-10gen:amd64` returned `E: Unable to locate package mongodb-10gen:amd64`
Comment: Hmm...what does `echo bin/*` return?
Comment: It returns just `bin/*`
Comment: Since `apt-add-repository` gave an error that the command was not found, I tried adding that repo to my `/etc/apt/sources.list` instead. Using apt-get or aptitude after that still led to the 32-bit package being installed


classpath echo returns blank in linux

Question: I just open file :.bash_profile
export JAVA_HOME=/usr/java/jdk1.8.0_91/bin
Now in command prompt when I fire command : echo $JAVA_HOME , It returns me blank.
Am I missing anything? I am trying to set permanent class path in linux.
I have read and follow many similar questions but still no success.
Comment: You can try this solution to set JAVA_HOME: http://askubuntu.com/questions/175514/how-to-set-java-home-for-java
Comment: @xYan - That returns me : ** (gedit:48569): WARNING **: Could not open X display

(gedit:48569): Gtk-WARNING **: cannot open display:
Comment: So you are remotely connected to the machine? Try using vi instead of gedit or try some of the solutions here: http://superuser.com/questions/310197/how-do-i-fix-a-cannot-open-display-error-when-opening-an-x-program-after-sshi
Answer: The contents of .bash_profile are only executed when you start a Login Shell. This is what happens if you, say, log in, or if you run bash --login.
The file you're probably looking for is ~/.bashrc, which is sourced by bash (i.e. executed) every time you start bash. You should put your export there.
Alternatively, on Linux you could put the line JAVA_HOME=/usr/java/jdk1.8.0_91/bin in the file /etc/environment, which should do exactly what you're trying to do (but you need to log out and log in first). This will be system-wide, though.
(for the record, the system-wide .bashrc file is /etc/bash.bashrc)
EDIT: Protip: You can check your environment variables in BASH by typing export with no arguments.
Answer: If your .bash_profile doesn't read also .bashrc, you need to add the above export also to .bashrc.
Or, you could add:
if [ -f ~/.bashrc ]; then
    source ~/.bashrc
fi

And add everything in .bashrc from now on.
Comment: you mean I should add in both files?

classpath echo returns blank in linux


If two fields have default values

Question: I'm trying to make it to where when a user clicks a button and if two input fields both have their default values, to remove classes from those input fields.
Currently however I can only get it to work with one field, not multiple fields.
Any ideas? http://jsfiddle.net/3xaBs
Thanks!
Comment: Remove classes completely or remove a particular class?
Comment: To further AlienWebguy's point, what happens if an input has more than one class?
Answer: Try this
$('#button').click(function() {
    if ($("#fone").val() == 'Hello World' && $("#ftwo").val() == 'Lorem Ipsum'){
        $('#fone').removeClass('myclass');
        $('#ftwo').removeClass('myclass');
    }
});

Answer: Here's a scalable solution. You can as many fields as you wantand it will only clear the classes if all fields in the group have their default value on submit:
HTML - take advantage of custom data attributes so you can group the fields without assigning a class which JQuery will remove:
<input type="text" id="fone" name="fone" class="myclass" data-group="my_fields" data-default="Hello World" value="Hello World" />
<input type="text" id="ftwo" name="ftwo" class="anotherclass" data-group="my_fields" data-default="Lorem Ipsum" value="Lorem Ipsum" />

Link

JQuery - Grab the fields in the group, compare their current value to their default value, and increment the counter, compare against the number of fields total:
$('#button').click(function(event) {
    event.preventDefault();
    var default_count = 0;
    $('input[data-group=my_fields]').each(function(){
       if($(this).val() == $(this).data('default'))
       {
           default_count++;
       }
    });

    // If all fields have default value still...
    if(default_count == $('input[data-group=my_fields]').length)
    {
       $('input[data-group=my_fields]').removeClass(); // remove all classes
    }
});

Working demo: http://jsfiddle.net/AlienWebguy/3xaBs/5/
Answer: It looks like it works for me:
$('#button').click(function() {
   var one = $("#fone");
   var two = $("#ftwo");

   if (  one.val() == one[0].defaultValue
      && two.val() == two[0].defaultValue ){
       one.removeClass('myclass');
       two.removeClass('anotherclass');
   }
});

If two fields have default values


Como se implementa uma annotation "preprocessor"?

Question: Eu aprendi que as Annotations em Java são só uma forma de injetar metainformação no código. Entretanto, eu tenho visto que frameworks e algumas bibliotecas tem annotations que "magicamente" geram código ou definem regras de compilação. Um exemplo qualquer é o projectlombok:
POJO com getters e setters tradicional:
public class DataExample {
    private int data;

    public DataExample(int data) {
        this.data = data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public int getData() {
        return data;
    }
}

POJO usando Lombok:
public class DataExample {
    @Getter @Setter private int data;

    public DataExample(int data) {
        this.data = data;
    }
}

A diferença é que as annotations @Getter e @Setter fazem o Lombok gerar os métodos getters e setters pra você, então se você os invocá-los em outras classes, eles não dão erro de compilação.
Mas é estranho: Os tutoriais e lições de annotations que eu vi só ensinavam a usar annotations para inserir informação.
Como eu crio annotations que gerem código, criem regras de compilação e coisa do tipo?
Comment: Se quer fazer algo como o `Lombok faz`, veja como é feito [no original](https://github.com/rzwitserloot/lombok/blob/master/src/core/lombok/Getter.java)
Comment: Mas é aí que tá: O arquivo da annotation é só uma annotation. Qual a mágica que acontece pra essa annotation gerar código?
Comment: o que quer com essa pergunta? Entender como funciona ou criar uma anotação própria?
Answer: O que acontece é que o Lombok utiliza um mecanismo conhecido como APT (Annotation Processing Tool). Com isso é possível que os getters e setter sejam gerados ainda em tempo de compilação. Um link interessante sobre isso:
http://blog.caelum.com.br/metaprogramacao-em-java-o-papel-do-apt/


How to attach an existing buffer to a realgud debugger?

Question: I'm starting to use realgud in GNU Emacs 24.3.1 as an alternative to GUD.  (Mainly because when I set break points with vanilla pdb it does not honor it.)
I'm starting the OpenERP web server with pdb bin/start_openerp and it opens the main script.  But I need to be able to place breakpoints in the buffers I'm working on.
I need to how can I attach my buffers to the debugger.
More details about my environment
For OpenERP developing I'm using buildout and the anybox recipe.  This creates the bin/start_openerp script that rewrites the sys.path to match my buildout environment.
I'm developing several OpenERP's custom addons.  So I'm editing some when I need to enter the debugger session to tackle a problem.  I do the following:

Edit my buffers and save them.
Run pdb bin/start_openerp.  This opens the script with ShortKeys minor mode active.

If I execute the break file:lineno command on the realgud buffer it works and breaks are respected.  But I need to go to one of the buffers and with the point in some line, set the breakpoint there.
Answer: There is a conceptual problem that has to be overcome here.
But first, I need to define a couple of terms. A "command buffer" is where you see (Pdb) and it has the Python process and debugger associated with it. A "source-code buffer" is an Emacs buffer with Python source code in it.
When you are debugging several Python sessions, there are several command buffers. It is possible that several command buffers refer to the same Python source code at some point in the course of where they had stopped in running the Python program. So from inside a buffer of Python source code, how does one distinguish in which of several Python sessions you want the breakpoint to occur in?
When you are stopped in one of the sessions, the command buffer knows where you are. It arranges to pull up the source-code buffer and associate itself with that source-code buffer. The source-code buffer stores which Python command buffer is associated with it. In an ideal world it would store all of the associated command buffers and associate fringe marks with the right debugger process, but right now it can only store one pointer to a command buffer.
The source-code buffer may also go into "shortkey mode". Here, And typing "b" on any line will set a breakpoint at that line in the Python process associated with that source-code buffer.
But suppose there are several sessions and you are in a source-code buffer and don't know which command buffer is associated with that? The Emacs command and function realgud:srcbuf-info-describe when run from inside the source buffer will display information about the source-code buffer including which command buffer is associated with it.
So one simple way to set up a source-code buffer associated with the right Python process is to set a breakpoint from the right command buffer, and then clear the breakpoint. The source-code buffer will be in short-key mode, and then you can type "b" on any line and that will go to the right Python session.
The Emacs realgud function realgud-srcbuf-init-or-update can be used to initialize any Python buffer with a command buffer, but note that this is not an interactive command. You need to have the command buffer object and a source-code buffer
Finally let me put in a plug for a pdb-like and more gdb-like debugger trepan2 for Python2 and trepan3k for Python3.
See emacs-dbgr/common/buffer/source.el for more information about source buffers.
Comment: OK, got it working! It's as explained in the wiki here: https://github.com/realgud/realgud/wiki/How-to-Use#multiple-files. Launch trepan(2) as usual, then open the source file you'd like to break in, and do 'C-x C-a C-q'. I then asked me to associate to the trepan2 shell process, I pressed enter. After that the ShortKeys mode became active in the file and I could place a breakpoint with 'b'. Hurray!
Comment: I see... But I could overcome that by doing some elisp myself: A simple function that asks for a cmdbuf with (using dash.el): `(-select #'realgud-cmdbuf? (buffer-list))`; if there's a single cmdbuf (for me this is 99.99% of the time) then attach the current *source buffer* to that cmdbuf with `realgud-scrbuf-init-or-update`.
Comment: See gist: https://gist.github.com/mvaled/8871765  It works some times. I haven't been able to detect exactly when... It never sets the shortkey minor mode on the srcbuf, but *sometime* executing `realgud-cmd-break` do places the breakpoint...
Comment: Wow! I didn't know about either dash or grizzl, both cool. Will pick up discussion on that code in the gist soon. When this works, maybe we can get something like this back into realgud.
Comment: I've recently added `realgud:cmdbuf-associate` which takes the current buffer which is assumed to be a source-code buffer and will prompt for a command buffer to associate with that source code. It then turns on short-key mode.


Timber Pagination: page.php / not showing up

Question: In the Timber for Wordpress DOCs (link) they say

This will only work in a php file with an active query (like
  archive.php or home.php) (...)

By my understanding, what I have done, is an active query (?).
I need the pagination on one of my page.php sites however.
I can not get the pagination to display.
page.php
$context['blogposts'] = new Timber\PostQuery(array(
    'numberposts'   => -1,
    'posts_per_page'=> 2,
    'post_type'     => 'post',
    'order'         => 'DESC',
    'paged'         => (get_query_var('paged')) ? get_query_var('paged') : 1,
));

page.twig

    {% for post in blogposts %}
      {% include ['tease-'~post.post_type~'.twig', 'tease.twig'] %}
    {% endfor %}

  {% include 'partial/pagination.twig' with { pagination: blogposts.pagination({show_all: false, mid_size: 3, end_size: 2}) } %}

This pretty much exact logic works for the index + article pages (yes I tested it).
How can I get it to work for a page/custom page?
Dumping blogposts.pagination gives me the correct list of items.
Answer: Turns out i should have shown the pagination.twig too.
In my case I had to:
{% set posts = blogposts %}

for this partial to work.
Due to the partial using posts as the base object for displaying content.


Removing special characters from a string with RegEx

Question: Am reading a text file that contains words, numbers and special characters, I want to remove certain special characters like: [](),'
I have this code but it is not working !
using (var reader = new StreamReader ("C://Users//HP//Documents//result2.txt")) {
            string line = reader.ReadToEnd ();

            Regex rgx = new Regex ("[^[]()',]");
            string res = rgx.Replace (line, "");
            Message1.text = res;

        }

what am I missing, thanks
Comment: Almost all of these characters are special characters in Regex. They must be properly escaped.
Comment: What should I do ?
Comment: just use `.Replace()`
Comment: .Replace() is not working
Answer: Some of the characters in your Regex, specifically [ ] ( ) ^, hold special meaning in Regex and in order to use them literally they must be escaped.
Use the following properly escaped Regex:
Regex rgx = new Regex (@"[\^\[\]\(\)',]");

Note that it is necessary to use the @ verbatim string, because we don't want to escape these characters from the string, only from the Regex.
Alternatively, double escape the backslashes:
Regex rgx = new Regex ("[\\^\\[\\]\\(\\)',]");

But that's less readable in this case.
Comment: There is no need escaping these chars. [`"[][()'^,]"` will work](http://regexstorm.net/tester?p=%5b%5d%5b%28%29%27%5e%2c%5d&i=%5b%5d%5b%28%29%27%5e%2c%5d&r=x).
Answer: You could skip Regex and just maintain a list of characters you want to remove and then replace the old fashioned way:
string[] specialCharsToRemove = new [] { "[", "]", "(", ")", "'", "," };

using (var reader = new StreamReader ("C://Users//HP//Documents//result2.txt"))
{
    string line = reader.ReadToEnd();
    foreach(string s in specialCharsToRemove)
    {
        line = line.Replace(s, string.Empty);
    }
    Message1.text = res;
}

Ideally this would be in its own method, something like this:
private static string RemoveCharacters(string input, string[] specialCharactersToRemove)
{
    foreach(string s in specialCharactersToRemove)
    {
        input = input.Replace(s, string.Empty);
    }
    return input;
}

I made a fiddle here
Answer: Replace them one at a time with String.Replace:
using (var reader = new StreamReader ("C://Users//HP//Documents//result2.txt"))
{
        string line = reader.ReadToEnd ();

        string res = line.Replace(line, "[", "");
        res  = res.Replace(line, "]", "");
        res  = res.Replace(line, "(", "");
        res  = res.Replace(line, ")", "");
        res  = res.Replace(line, "'", "");
        res  = res.Replace(line, ",", "");
        Message1.text = res;

    }

Comment: A `foreach` would be nicer and easier to modify.
Comment: just fixed a typo
Comment: i considered that
Answer: I agree with avoiding regex for this, but I would not use string.Replace multiple times, either.
Consider implementing a Replace or Remove method that accepts an array of characters to replace, and scan the input string only once. For example:
var builder = new StringBuilder();

foreach (char ch in input)
{
    if (!chars.Contains(ch))
    {
        builder.Append(ch):
    }
}

return builder.ToString();


Fix detached entity passed to persist in one to one relationship in JPA

Question: I have following entity mapping (unidirectional):
@Entity
public class Parent {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;

   @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
   @JoinColumn(name = "ch_id", referencedColumnName = "ch_id", nullable = false, updatable = false)
   private Child child;
}

Child entity is just the regular entity.
I want to create parent entity with child, but I have two use cases:

When child entity already exists in database
When child entity is not created in database yet

when I go through the second use case, I successfully create child entity with parent entity (with help of cascade type PERSIST)
But when I go through the first use case I get
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.example.data.entity.Child; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.example.data.entity.Child
org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:319)
org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)
org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
jdk.proxy2/jdk.proxy2.$Proxy240.saveAll(Unknown Source)

How can I omit this error when I just need to link parent with child without removing PERSIST cascade type
In response of @Daniel Wosch comment:
Here I have ParentBO entity
public class ParentBO {

private Long childId;

// other fields

}

and this childId field is optional
so I get list of this parent BOs
    public void createParents(Collection<ParentBO> creationBOs) {

        List<Parent> parentsToPersistWithoutChild = creationBOs.stream()
                .map(parent -> prepareParentToPersist(parent))
                .collect(toList());

        repository.saveAll(parentsToPersist);
    }

    private Parent prepareParentToPersist(ParentBO parentBO) {
        Parent parent = new Parent();
        if (parentBO.getChildId != null) {
//            here I want just link child entity which already exists in DB with parent entity
//            (child existence I've validated before)
            parent.setChild(new Child(parentBO.getChildId()));
        } else {
            Child child = new Child();
//            here I set all required fields for child entity which
//            depends on parent fields (by business rules)
            parent.setChild(child);
        }
        return parent;
    }

Comment: How does your code look like to create both use cases? Especially the first one which is not working. Do you fetch the child from database first and then assign it to the parent?
Comment: I have a list of Parent entities which I need to create with child entities for every parent. And child entity may or may not be already persisted in DB
Comment: I try to not firstly fetch then but link on parent save to improve code readability
Comment: Could you post that code please? How do you link the child <-> parent? `new Child()` without saving is basically a detached entity.
Comment: I have provided pseudocode example above in question
Answer: You need to fetch the child first in your first case from database to get it into the Hibernate session storage and to be managed by hibernate.
new Child() => transient entity. Then you are setting excplicitly the ID of the new child. Hibernate assumes that its an managed entity (because if it has an ID it has to be in my state). But that is not the case in your code. Therefore persisting the entity results in the posted exception.Detached means that it is an entity which was persisted in the past and is not longer maintained / managed by hibernate. This happens because you are manually set the ID of that entity after creating a new instance. Instead of creating a new instance, fetch the child from the database and set it to the parent.

Fetch the child entity first (now its managed by hibernate)
Set the child to the parent entity
Save the parent
Be happy :D
Comment: Thanks for your response!
But is there any chance to do it using new Child(), because I have two different services to work with child and parent and  when I fetch child entities I get BO objects instead of entity object so I cannot set the child entity explicitly ?
Comment: As I have no experience with this but what you could try is to call EntityManager.merge(child). This will add the detached entity to the persistent context and is now managed by Hibernate. **Important** You need to set the ID before calling merge. Further you need to use the returned Entity from merge for further processing (set to parent). **Don't** work with the entity you have provided to the merge function.  You need to inject the entityManager instance into your service to work with it.
Comment: Give it a try and let me know if it worked.


How to use NSE in dplyr to refer to one variable?

Question: I want to write a function for use in a dplyr chain to arrange grouped data by a given variable and then to check that that variable is strictly increasing integers (eg, 1,2,3,...). To clarify, I mean every integer in order, not just increasing integers. So 1,2,4,... should fail.
The idea would be to have something like this in the end, that would look like this, and provide an error if x was not 1,2,3,... for every group.
d %>% group_by(group) %>% check(x)

I've written a SE version of this that seems to work, as follows, but am stuck on the NSE version.
check_ <- function(.data, var) {
  checkint <- function(x) { stopifnot(x == seq_along(x)) }
  do(.data, {
    . <- dplyr::arrange_(., var)
    checkint(lazyeval::lazy_eval(var, data=.))
    .
  })
}

In the documentation, it looks like I should be using lazy to process a single variable, but this doesn't work right when the variable I'm passing in also exists in the global environment.
checkX <- function(.data, var) {
  check_(.data, lazyeval::lazy(var))
}

d <- expand.grid(group=1:2, x=3:1)
x <- 5 ## put an "x" in the global environment
d %>% group_by(group) %>% checkX(x)

## Error: incorrect size (1), expecting : 3

I do have a version of the NSE that seems to work, but calling lazy_dots feels wrong because I only ever want one variable.
check <- function(.data, ...) {
  check_(.data, lazyeval::lazy_dots(...)[[1]])
}

Comment: I want it to fail if it's c(1,2,4), I'll clarify in the question. It also felt cleaner to me to not have the byproduct of the summary, as what I really want to do is to pipe the output of this to another function.
Answer: Looks like lazyeval has been changing.  The latest vignette doesn't even reference the lazy() function. It does seem to have problems with variables in scope (more on that at the bottom). There are now we functions being encouraged though they still haven't made their way into all of the "tidyverse" yet.
It looks like the function you want is expr_find. If we define checkX as
checkX <- function(.data, var) {
  check_(.data, lazyeval::expr_find(var))
}

Then this will work
x <- 5
d %>% group_by(group) %>% checkX(x)

(or at least it does with lazyeval_0.2.0 and dplyr_0.5.0)
But going back to the first example from the old vignette
library(lazyeval)
# `x` does not exist here
f <- function(x = a - b) {
  lazy(x)
}
f()
# <lazy>
#   expr: a - b
#   env:  <environment: 0x000000000663d618>
exists("x")
# [1] FALSE
f(x)
# <lazy>
#   expr: x
#   env:  <environment: R_GlobalEnv>
x <- 101
f(x)
# <lazy>
#   expr: 101
#   env:  <environment: R_GlobalEnv>

Or another even more simple example
# rm(x)
lazy(x)
# <lazy>
#   expr: x
#   env:  <environment: R_GlobalEnv>
x <- 100
lazy(x)
#  <lazy>
#   expr: 100
#   env:  <environment: R_GlobalEnv>

Somewhere its evaluating the parameter x so it's never being preserved in the lazy object if it exists in the environment it's coming from.
Comment: Thanks for investigating! Maybe I'll wait to do more complex things with dplyr until things have settled down. I also see that Hadley now is souring somewhat on NSE, so maybe I'll just stick to the SE methods.


Brownian Motion is almost surely unbounded, and a proof for the discrete Random Walk

Question:
If $B_t$ is a Brownian Motion, why we have
  $$
 P(\liminf_{t\to\infty} B_t = -\infty) = 1
$$
  and $P(\limsup_{t\to\infty} B_t = +\infty) = 1$?

I guess for the following "discrete version" of the "Brownian motion" (which isn't called Brownian Motion but Random Walk I guess) I have an argument. Let $B_n$ with $B_n \sim \mathcal N(0, n)$. Set
$$
 A_k := \{ B_n > k \mbox{ for infinitely many }n \}
            = \limsup_n ~ \{ B_n > k \}
$$
and $A := \bigcap_k A_k$, then $\omega \in A$ iff the path of $\omega$ is unbounded, i.e. $A = \{\limsup_n B_n = +\infty\}$. Each set $A_k$ is in the tail-$\sigma$-algebra as the limsup of sets, and so $A$ as a countable intersection is a tail-event, therefore by Kolmogoroff's 0-1-law we have $P(A) \in \{0,1\}$. As for each $n$ we have
$$
 P(B_n > \sqrt n) = 1 - \Phi\left(\frac{\sqrt n}{\sqrt n}\right) > 0.1
$$
where $\Phi$ denotes the cumulative distribution function of the normal distribution, and as
$$
 \bigcup_n \{ B_n > \sqrt n \} \subseteq A
$$
and by the above $0.1 < P( \bigcup_n \{ B_n > \sqrt n \} )$
we could not have $P(A) = 0$, therefore $P(A) = 1$. Similarly the case $P(\liminf_n B_n = -\infty) = 1$ might be establised.
In my approach I used that the process is discrete, but I do not know how to show it in the general case for continuous time. So any help would be greatly appreciated! Also if my solution for the discrete case is way to complicated I would also be thankful for feedback and alternative approaches.
Comment: Since the events $\{B_n>k\}$ are not independent, Kolmogorov's zero-one law doesn't apply.
Comment: It sounds like you're familiar with a similar result pertaining to the central limit theorem. It sufficies to show that the infimum is attained on a countable subsequence, so you're basically done. Just use the fact that differences of brownian motion are independent. Pick your favorite sequence $t_k$, say $t_k=k$ and look at $B_{t_k}=(B_{t_1}-B_{0}) + (B_{t_2}-B_{t_1})+\cdots + (B_{t_k}-B_{t_{k-1}})$. Divide $\sqrt{n}$ and carry over the proof.
Comment: "Divide $\sqrt n$ and carry over the proof" - is this division really necessary as $B_{t_k} \sim \mathcal N(0, n)$ holds already because of $B_{t_{i+1}} - B_{t_i} \sim \mathcal N(0,1)$?
Comment: You're right, I was thinking of a stronger result.
Answer: The continuous case follows from the discrete case! It's too bad you used "$B$" for both Brownian motion and the gaussians you're adding in the discrete case...
Say $B_t$ is brownian motion. For $n=1,2,\dots$ let $$X_n=B_n-B_{n-1}.$$The definition of brownian motion shows that the $X_n$ are iid gauussians. So if we let $$S_n=X_1+\dots+X_n$$then you've shown (I haven't looked at your proof) that $S_n$ is almost surely unbounded. But $S_n=B_n$.
EDIT: Looked at the OP's proof of the discrete case, at the his request.
I was misled by his use of the term "random walk". What the OP calls a random walk is not a random walk at all, as I understand the term. And I don't see how what he says about his "random walk" can be right, since there's no independence assumed. (Come to think of it, perhaps the $B_n$ at that point is still supposed to represent brownian motion; if so ignore this paragraph. I assummed we were redefining $B_n$ at that point because of the words "Let $B_n$...". Except no, $B_n$ can't be brownian motion at that point because that would make literally trivial to get the continuous case from the discrete case...)
For the record, it's very easy to show that the $S_n$ I define above is almost surely unbounded. Hint: If $|S_n|\le k$ and $|S_{n+1}|\le k$ then $|X_{n+1}|\le 2k$. The probability of this is $p<1$, so the probability that $|S_n|\le k$ for all $n$ is $0$.
Comment: Yes, thank you, so it is a small step from the discrete case :) But would be kind if you could say if my proof is okay, and maybe give an easier one if you know one if my arguments are to involved (using Kolmogoroff's 0-1 law and so)...
Comment: @Stefan  See edited answer
Comment: Okay, thank you for your comments!
Comment: @ByronSchmuland Yes, if $B_n$ is brownian motion there then that's a random walk - hence the words "if so ignore this paragraph". But the reason it's not, or at least wasn't, so "clear" to me has to do with more than the word "Let". Think about this: If $B_n$ is brownian motion then here is an _accurate_ paraphrase of the OP's question: "I've shown that $B_n$ is unbounded for integers $n>0$. How can I show that $B_t$ is unbounded for reals $t>0$?". Surely the _blatant_ triviality of that question makes it all not so clear...
Comment: @ByronSchmuland Of course students do that. And of course we see such questions here all the time. Now. Context. The OP's trying to prove things about brownian motion - he's aware of 0-1 laws and such. In that context, the fact that he doesn't seem to realize that a set with an unbounded subset must be unbounded doesn't surprise you one bit? Not a teensy bit? In spite of that it's absolutely clear that that's what he meant?
Comment: @DavidC.Ullrich: This is a few years old, but maybe you can answer my question regarding your answer: The thread wanted to prove that, almost surely, $lim_{t\rightarrow \infty} sup \; B(t) = \infty$. How does this follow from Brownian Motion being almost surely unbounded? It might go to $-\infty$ for some paths?
Comment: @MF14 Oh - good poiint. Say $A$ and $B$ are the events $\sup B_t=\infty$ and $\inf B_t=-\infty$. We know that $P(A\cup B)=1$. Since each of $A$ and $B$ has probability $0$ or $1$ this implies $P(A)=1$ or $P(B)=1$. But it's easy to see $P(A)=P(B)$.
Comment: @DavidC.Ullrich can you expand a bit on as to why $P(A)=P(B)$? I believe otherwise the expected value would not  be 0, but I cannot find a rigorous argument for that.
Comment: @MathR $P(A)=P(B)$ because $B_t$ and $-B_t$ have the same distribution


NginX installation-source best practice

Question: I'd like to install NginX as a reverse proxy on CentOS. I know three different ways to install NginX:

Compile itself
Install over EPEL
Install over official NginX package repository

Which way would you recommend for production use? Are there any cons for installing NginX over the official source?
Comment: What do you mean "compile itself" versus "install over official NGINX source"?
Comment: @gWaldo meant the official packages
Comment: Ah I see.  I've updated my answer regarding the nginx yum repository.
Answer: Installing from your distro's package manager is usually more convenient, but you're at their whim as to what version that you are going to run.  (Hint: It's an older version.)
Installing from source is more effort, but you get newer code (and the ability to make a decision on what version you are running).  Additionally, you can compile in additional options and features that may not be included in the package version.  Finally, compiling on your target machine allows the compiler to optimize for the processor features available on that system, where distro packages are compiled to a lowest-common denominator, so they may not perform as well.
If you use the nginx yum repo (details), you will get the convenience of using the package manager, but the version is much more likely to be kept up-to-date.  You still will not get the processor-optimizations that compiling it yourself would yield, however.
Answer: Don't install from source (as in make install). It is best practice to install software using packages. Packages make the process consistent and reproducible. For example if you need to deploy a second machine, or replace a failed machine. Package maintainers also update packages to fix security problems. Using packages will make automated deployment (using configuration management) easier.
If the EPEL version is too old you can get the official packages from nginx.org. But be aware that unlike EPEL they do not maintain version stability, meaning version updates may be incompatible with existing configurations. For that reason it is a good idea to maintain your own yum or apt repository with the version you use.
You can also compile and package from source yourself, which might be needed if you have special modules you need included.
Comment: Absolutely agree. If you need to include special modules, you can take src.rpm and enable them there too. beware: after upgrade, your package will be replaced with original EPEL one if you won't take a look at that.

NginX installation-source best practice


Change the width of the off-canvas dialog

Question: Layout Builder uses the off-canvas dialog. It comes out from the right side of the screen at a max width of 300px. We'd like to make it wider. I can do this with a powerful CSS rule, but is there a better Drupal way? Is there a setting I can't find?
Comment: There is no config setting for this. You could alternatively probably change it via [hook_link_alter](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/function/hook_link_alter/8.6.x) but to me it makes less sense to set the width via PHP rather than CSS.
Comment: If the width doesn't depend from a value you get using the Drupal API, for example the state API or the configuration API, it's better to do that via CSS.
Comment: There's also a modal available for better UX: https://www.drupal.org/project/layout_builder_modal
Answer: You Can modify the initial width of the offCanvasDialog by setting the 'data-dialog-options'.  We're doing that in the same_page_preview module with this implementation:
<code>$form['toggle_preview_link'] = [
  '#type' => 'link',
  '#title' => t('Launch preview'),
  '#weight' => -1,
  '#url' => Url::fromRoute('same_page_preview.preview_pane', $route_parameters),
  '#attributes' => [
    'class' => ['use-ajax', 'button','button--primary', 'visually-hidden'],
    'data-dialog-type' => 'dialog',
    'data-dialog-renderer' => 'off_canvas',
    'data-dialog-options' => Json::encode([
      'width' => '50%',
      'classes' => [
        // @todo figure out how to override more than just this one.
        'ui-dialog' => 'same-page-preview-dialog',
      ],
    ]),
  ],
  '#attached' => [
    'library' => [
      'core/drupal.dialog.ajax',
    ],
  ],
];
</code>
This sets the initial width of the dialog to be 50% of the page.
Modifying the width of the dialog after it renders can be done manually by dragging with edge of the dialog.  I'm also looking into modifying the width programmatically but don't have that figured out right now. I'll come back here if I do figure it out.


Django: Import data from uploaded excel file

Question: I'm trying to create an app to import thanks to an uploaded .csv file data to my database. This is where I've managed to arrive by myself: my file is uploaded without problems and I can pass the information from the file to the variable first_row and second row. My problem now is how I can save the information in the database. My views code:
VIEWS
@login_required
def file_upload(request):
    data = None

    if request.method == 'POST':
        file_form = FileForm(request.POST, request.FILES)
        data_form = DatasetForm(request.POST, request.FILES)
        raw_file= request.FILES
        if file_form.is_valid() or data_form.is_valid():
            data = request.FILES['file_upload']
            data = pd.read_csv(data, header=0, encoding="UTF-8")
            first_row = data.iloc[[0]]
            second_row = data.iloc[[1]]

            file_form.instance.user = request.user.profile
            file_form.instance.filename = raw_file['file_upload'].name
            file_form.save()
            return redirect('upload_file')
        else:
            return redirect('home')
    else:
        form = FileForm()

    context = {
               'data': data,
               'second_row': second_row,
               'file_form': file_form,
               'message': message,
               }
    return render(request, 'upload_file.html', context)

These are how my data and models looks:
DATA
        code  tot sd
name_1  aa    3    1
name_2  bb    7    2

MODEL
class File(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE)
    filename = models.CharField(max_length=250)
    file_upload = models.FileField(upload_to=path)
    upload_date  = models.DateField(default=datetime.now)

    def __str__(self):
        return self.user.name + 'file'

class Dataset(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE)
    file_uploaded = models.OneToOneField(File, on_delete=models.CASCADE)

    name_user_A = models.CharField(max_length=250)
    code_user_A = models.PositiveIntegerField(null=True)
    total_user_A = models.PositiveIntegerField(null=True)
    sd_user_A = models.PositiveIntegerField(null=True)

    name_user_B = models.CharField(max_length=250)
    code_user_B = models.PositiveIntegerField(null=True)
    total_user_B = models.PositiveIntegerField(null=True)
    sd_user_B = models.PositiveIntegerField(null=True)

FORMS
class FileForm(forms.ModelForm):
    class Meta:
        model = File
        fields = '__all__'

class DatasetForm(forms.ModelForm):
    class Meta:
        model = Dataset
        fields = '__all__'

Basicaly I need to save the first row in the field for user_A and the second row for the user_B. Only the model File is compiled by the user, while Dataset should be filled automatically from the information in the file.  How can I do this? Thank you all!
PS(I had to do some change to make it shorter and more understandable, there could be some typo but it's acutally works)
Comment: You can just retrieve data and create an object based on that.
Answer: If you import your Dataset model you can create a new object based on the data you've already got from the file.
for example:
#import your model
from . models import Dataset

@login_required
def file_upload(request):
    data = None

    if request.method == 'POST':
        file_form = FileForm(request.POST, request.FILES)
        data_form = DatasetForm(request.POST, request.FILES)
        raw_file= request.FILES
        if file_form.is_valid() or data_form.is_valid():
            data = request.FILES['file_upload']
            data = pd.read_csv(data, header=0, encoding="UTF-8")
            first_row = data.iloc[[0]]
            second_row = data.iloc[[1]]

            # create new dataset object
            Dataset.objects.create(
                name_user_A=first_row,
                name_user_B=second_row,
                ...,
                ...)

Comment: Thank you! I'm trying your advice and I'm getting this `error = NOT NULL constraint failed: app_data.file_uploaded_id`. I think I should automatically link the data form to the file form? I've tried this `data_form.file_uploaded = request.file_uploaded.file` and I'm getting this error `'WSGIRequest' object has no attribute 'file_uploaded'`. Thank you again for the helps
Comment: How do you show user the values that didn't get imported due to DB Integrity errors?


While calling bank api :The remote server returned an error: (401) Unauthorized

Question: i'm trying to get the access bank api using Below code to call bank API
    with parameter and also authenticate url with username password
    When call bank API showing Unauthorized API but here i added certificate
    and also set cros-option but still error is coming..
<code>Anyone can help me....

:
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.UseDefaultCredentials = true;
            request.PreAuthenticate = true;
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Method = "POST";
            request.PreAuthenticate = true;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Credentials = new NetworkCredential("testclient", "test@123");
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(jsonContent);
            request.ContentLength = byteArray.Length;    //  request.ContentType = "application/json";    //request.ContentType = "";
            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }
            long length = 0;
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    length = response.ContentLength;
                    if (response.StatusCode != HttpStatusCode.OK) throw new Exception(String.Format(
                        "Server error (HTTP {0}: {1}).", response.StatusCode,
                    response.StatusDescription));
                    Stream stream1 = response.GetResponseStream();
                    StreamReader sr = new StreamReader(stream1);
                    string strsb = sr.ReadToEnd();
                    object objResponse = JsonConvert.DeserializeObject(strsb);
                    //return objResponse;
                }

            }
            catch (WebException ex)
            {
                // Log exception
            }

The remote server returned an error: (401) Unauthorized.
</code>
Comment: certificate with pass, client id and secret in header

X509Certificate cert = new X509Certificate2("D:\\demo\\temp.crt", "temp", X509KeyStorageFlags.MachineKeySet);
            request.ClientCertificates.Add(cert);
            request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            request.Credentials = new NetworkCredential("temp", "temp");
            request.Headers.Add("authorization", "Basic dGVzdGNsaWVudDp0ZXN0QDEyMw==");
            request.Headers.Add("X-IBM-Client-Id", "id");
            request.Headers.Add("X-IBM-Client-Secret", "secret");
Answer:
Add certificate with pass, client id and secret in header

X509Certificate cert = new X509Certificate2("D:\demo\temp.crt", "temp", X509KeyStorageFlags.MachineKeySet); request.ClientCertificates.Add(cert); request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; request.Credentials = new NetworkCredential("temp", "temp"); request.Headers.Add("authorization", "authorization"); request.Headers.Add("X-IBM-Client-Id", "id"); request.Headers.Add("X-IBM-Client-Secret", "secret");


include a website in php file

Question: Hi i am trying to include a webpage link from another website into my website.
how can i do this?
i tried
<?php web_include ('http://website.com/website.html') ; ?>
but all the commands are not loading after this statement. I want to include another webpage into my homepage directly. my homepage is completely designed in php, but the other one is html or php.
i also tried <?php include("http://www.othersite.com/filename.html"); ?> but this html is not at all loading.
Possible Solution:
ok this is what i am using

I am just including a dropdown menu for my index page. The CMS of the my site is restricting me from viewing the dorpdown in IE. When i view the dropdown.html page, i can see the dropdown, so I am trying to use iframe. Now using the iframe i can see the dropdown in IE as well, but the dropdown is not showing on the top. It is showing behind the other images on the site. How do i get it on top of the other images. z-index is not working for this.
Comment: Why are you trying to do this? If you want to display contents of other page, use ``.
Comment: Based on the info you provided in your 'answer', it sounds like you're trying to include a menu from another site, or something? I'm skeptical about the whole plan. Maybe it'd be better to fetch the page, parse the data, and render it in your page in a way you can control.
Comment: An alternate solution, just to make you aware, is to use jQuery and it's load() function to display any arbitrary section of a remote page in the midst of your own html.  Though there are XSS risks to watch out for with that method as well.
Answer: This code requires allow_url_include=On in your php.ini, which is disabled by default because it's REMOTE CODE EXECUTION, one of the worst you can have in PHP.  This is called the Remote File Include (RFI) vulnerability. If there is PHP code on this site it will be executed on your server.
Extremely insecure:
<?php include("http://www.othersite.com/filename.html"); ?>

What you probably want is:
<?php print file_get_contents("http://www.othersite.com/filename.html"); ?>

However, this is technically an XSS vulnerability. So, if you trust the website there isn't a problem. But you probably want to run Html Purifer before printing it out.
Comment: Sure it isn't `allow_url_include`? I couldn't find any `remote_includes`.
Answer: Just a basic recommendation, but it sounds like you're trying to debug complex functionality within a complex environment, which will only make it harder.
Debugging is easier if you break it down into component steps. In this case, I recommend:
Display the iframe on a blank html page.
Make sure everything works in that simple case.
Display on the more complex page.
If it's still not working, comment out the javascript on the complex page to determine if that is causing the adverse interaction with the iframe page's javascript.
Going through the debuggging stepwise like that should simplify the process.

include a website in php file


Accessing returned scope method variables in another method in AngularJS

Question: I have an Angular app with a service and a controller:
service.js
.factory('MyService', function ($http, $q) {
    var api_url = 'http://localhost/api/';

    var MyService = {

        list: function (items_url) {
            var defer = $q.defer();
            $http({method: 'GET',
                url: api_url + items_url}).
                success(function (data, status, headers, config) {
                    defer.resolve(data);
                }).error(function (data, status, headers, config) {
                    defer.reject(status);
                });
            return defer.promise;
        },
        ...
   }
});

controller.js
.controller("ItemsCtrl", function ($scope, MyService) {

    $scope.getItems = function () {
        MyService.list('items/').then(function(data) {
            $scope.items = data;
        });
    };

    $scope.addItems = function () {
        $scope.getItems();

        // why is this undefined ??!!!
        console.log($scope.items);
    };

The issue is that I want to call the $scope.getItems method inside the $scope.addItems method. Do I perhaps need to use $scope.apply(), as the returned value is a promise?
I think what I am displaying here is a general lack of understanding.
Answer: Change your controller like this:
.controller("ItemsCtrl", function ($scope, MyService) {

    $scope.getItems = function () {
        return MyService.list('items/').then(function(data) {
            $scope.items = data;
        });
    };

    $scope.addItems = function () {
        $scope.getItems().then(function() {

          // should be what you want this time
          console.log($scope.items);

        });
    };

Your problem is when you call $scope.getItems(), http response is not returned yet, so $scope.items is not populated. You have to wait for all the promises are resolve to access items.
Answer: $scope.items is undefined because $http is an asynchronous communication. That is, when you call $scope.addItems(), it creates and sends the request to retrieve your list of items, then immediately moves on to the next line of code, which is to log $scope.items to the console. Since there's nothing in $scope.items yet, you get an undefined value.
If you want to operate on the data returned by the http call, you must guarantee that the data will be populated. In other words, any operations you want to perform on $scope.items should be called within your .then() block.
$scope.$apply() is used when you are not executing within an AngularJS context, to force the AngularJS framework to evaluate the expression. It will not help you here - you'll get an "$digest already in progress" error, or something along those lines.
Try this:
.controller("ItemsCtrl", function ($scope, MyService) {

  $scope.getItems = function () {
    MyService.list('items/').then(function(data) {
      $scope.items = data;
      console.log($scope.items);
    });
  };

  $scope.addItems = function () {
    $scope.getItems();
  };
});

Answer: That is because $scope.getItems is asynchronous. Your callback (that added via then) is called after $scope.addItems executed.


JavaScript adding variable to href

Question: I have a json that is taking from a db information and showing as link, im trying to show the link from db but im gettig some issues, this is what i have:
 $("#content_div").html('
Knowledge Info
');

When doing this im getting :
Uncaught SyntaxError: Unexpected string

Not sure why, the variable is there, when doing console.log(knowledge_info); i can see the info coming from the variable
Comment: String concatenation in JS is done using `+`, not `.`.
Comment: Possible duplicate of [How do I concatenate a string with a variable?](https://stackoverflow.com/questions/4234533/how-do-i-concatenate-a-string-with-a-variable)
Answer: JavaScript string concatenation is with the + sign:
$("#content_div").html('
Knowledge Info
');
If your IDE doesn't show you this is syntactically wrong you should probably find another editor and check out some JS basics courses.
Comment: Don't forget to set my answer to accepted please :)
Answer: Can you concatenate the string instead of using dots?
 $("#content_div").html('
Knowledge Info
');

Comment: Great, its fixed!
Answer: if you use ES6 you can type like this

  run snippet

and in js must be camelCase variables "knowledge_info"=>"knowledgeInfo"
Answer: . operator is invalid in javascript.
It is used in php to combine string.
So you would replace . operator to +.
$("#content_div").html('
Knowledge Info
');

Answer: You could try using template strings like so:
 $("#content_div").html(`<a href="${knowledge_info}"><h4 class="knowledge_base">Knowledge Info</h4></a>`);

:)

JavaScript adding variable to href


How to create variable from different time frames in R?

Question: I am wondering how I can create a variable within a pipe that comprises different time frames. For example, I have 4 groups of items, each occurring different frequencies throughout a year. Now, I would like to divide that month's amount by the total amount per group of the entire year. How would I write that?
What I got:
abc <- dataset %>%
  group_by(group, month) %>%
  summarize(month, TotItemsMonth = ?, TotItemsYear = ?,
            ratio = TotItemsMonth/TotItemsYear)

How would I write this? I don't know how to have TotItemsMonth sum months and TotItemsYear sum years within the same segment.
Hope this makes sense!
Thank you for reading.
Comment: It will be easier to help if you can provide a bit of example data as code we can load.
Comment: I'm guessing `dataset %>% count(group, month) %>% group_by(group) %>% summarize(TotItemsMonth = n, TotItemsYear = sum(n), ratio = n / sum(n))`
Answer: I created this data frame as an example.
df1<-tribble(
  ~year, ~month, ~group, ~n,
  #--|--|----|----
  2020, 1, "A", 3,
  2020, 2, "A", 4,
  2020, 3, "A", 3,
  2020, 4, "A", 4,
  2020, 5, "A", 3,
  2020, 6, "A", 4,
  2020, 7, "A", 3,
  2020, 8, "A", 4,
  2020, 9, "A", 3,
  2020, 10, "A", 4,
  2020, 11, "A", 3,
  2020, 12, "A", 4,
  2020, 1, "B", 5,
  2020, 2, "B", 4,
  2020, 3, "B", 3,
  2020, 4, "B", 3,
  2020, 5, "B", 3,
  2020, 6, "B", 4,
  2020, 7, "B", 7,
  2020, 8, "B", 4,
  2020, 9, "B", 10,
  2020, 10, "B", 4,
  2020, 11, "B", 3,
  2020, 12, "B", 4,
  2020, 1, "C", 3,
  2020, 2, "C", 4,
  2020, 3, "C", 3,
  2020, 4, "C", 4,
  2020, 5, "C", 46,
  2020, 6, "C", 4,
  2020, 7, "C", 3,
  2020, 8, "C", 47,
  2020, 9, "C", 3,
  2020, 10, "C", 4,
  2020, 11, "C", 34,
  2020, 12, "C", 4,
  2021, 1, "A", 3,
  2021, 2, "A", 4,
  2021, 3, "A", 33,
  2021, 4, "A", 4,
  2021, 5, "A", 32,
  2021, 6, "A", 4,
  2021, 7, "A", 3,
  2021, 8, "A", 41,
  2021, 9, "A", 3,
  2021, 10, "A", 4,
  2021, 11, "A", 3,
  2021, 12, "A", 4,
  2021, 1, "B", 52,
  2021, 2, "B", 4,
  2021, 3, "B", 3,
  2021, 4, "B", 3,
  2021, 5, "B", 3,
  2021, 6, "B", 43,
  2021, 7, "B", 7,
  2021, 8, "B", 4,
  2021, 9, "B", 10,
  2021, 10, "B", 4,
  2021, 11, "B", 3,
  2021, 12, "B", 4,
  2021, 1, "C", 3,
  2021, 2, "C", 4,
  2021, 3, "C", 34,
  2021, 4, "C", 4,
  2021, 5, "C", 6,
  2021, 6, "C", 4,
  2021, 7, "C", 3,
  2021, 8, "C", 47,
  2021, 9, "C", 3,
  2021, 10, "C", 4,
  2021, 11, "C", 34,
  2021, 12, "C", 4,
)

And then I calculated total amount per group of the entire year
df2<-df1 %>%
  group_by(group,year)%>%
  summarise(total_year=sum(n))

df2
# A tibble: 6 × 3
# Groups:   group [3]
  group  year total_year
  <chr> <dbl>      <dbl>
1 A      2020         42
2 A      2021        138
3 B      2020         54
4 B      2021        140
5 C      2020        159
6 C      2021        150

Next, I join df1 and df2 and then calculate the ratio
df3<-df1%>%
  left_join(df2, by=c('year'='year', 'group'='group'))%>%
  mutate(ratio = n/total_year)

> df3
# A tibble: 72 × 6
    year month group     n total_year  ratio
   <dbl> <dbl> <chr> <dbl>      <dbl>  <dbl>
 1  2020     1 A         3         42 0.0714
 2  2020     2 A         4         42 0.0952
 3  2020     3 A         3         42 0.0714
 4  2020     4 A         4         42 0.0952
 5  2020     5 A         3         42 0.0714
 6  2020     6 A         4         42 0.0952
 7  2020     7 A         3         42 0.0714
 8  2020     8 A         4         42 0.0952
 9  2020     9 A         3         42 0.0714
10  2020    10 A         4         42 0.0952
# … with 62 more rows

I hope this helps!


Preventing webform save

Question: Goal: Using webform (and it's hooks) in drupal 7 I need to, under certain conditions, avoid saving the form submission (i.e. under those conditions I need to discard the submission instead of saving it to submissions models or, if that's not possible, correctly reference the submission and delete it).
Question: How is that done? Either of the solutions would be fine for me. I didn't try anything yet, since I have no clue at all about how to do any of them. I can just barely imagine it should be done on _alter or _presave hooks, but I'm not sure, and can't find about.
Current state: Totally n00b and clueless about.
Notes: Assume hooks as:
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    //validations occur here to test whether the current form is a webform node.
}

EDIT - Additional IMPORTANT notes I forgot: Depending on the value of some fields, I have two possible scenarios:

Avoid saving, then redirect (to external URLs, i.e., urls not belonging to my Drupal install. The redirection url must be the result of an evaluated expression, and not just a single url which I could specify in the webform settings).
Save, then redirect (to internal URLs, i.e., urls belonging to my Drupal install. The redirection url must be the result of an evaluated expression, and not just a single url which I could specify in the webform settings).
Comment: when you say under certain conditions only, do you mean form validation?
Comment: No. Scenario: I need the form passes validation. After validation, I check a value. If the value is "X" (say), I must save the form. If it is "Y" or "Z" I want to redirect, based on other form's values, and NOT save the form.
Answer: yes hook_form_alter is the right hook you are looking for.
Something like below. Please check the values of form field inside $form_state and fix the code accordingly.
Basically hook_form_alter will allow you wo conditionally add submit handler to your webform which means if form field value is Y then only your custom submit handler will call, also the way we adding the custom submit handler is by replacing the other handlers so no conflict with your sudmit handler and any other comes by default.
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
   if($form_id == "your_webform_id") {
     if($form_state['your_form_field']['#value'] == 'Y') {
       $form['#submit'] = 'custom_submit_handler_external';
     }
     if($form_state['your_form_field']['#value'] == 'X') {
       $form['#submit'][] = 'custom_submit_handler_internal';
     }
   }
}

function custom_submit_handler_external(&$form, &$form_state) {
  drupal_goto("redirect to a page");
}

function custom_submit_handler_internal(&$form, &$form_state) {
  $redirect_to = $form_state['redirect_field']['#value'];
  $form_state['redirect'] = $redirect_to;
}

The above code is just an idea of how you can approach, please debug it at every step and make it workable for you.
Comment: Redirecting avoids saving? I need Two scenarios: 1. redirect (and no save), 2. save, then redirect (to an internal Drupal page, e.g. another node)
Comment: Sorry, did not explain it before, and the difference seems critical. will update question now.
Comment: question updated with "additional important notes".
Comment: @LuisMasuelli check the updated answer
Comment: Ty :D. [redirect_field][#value] expects drupal-only q= urls?
Answer: I had the certain scenario where I had to prevent webform save for a particular component namely 'pay' component. I could achieve this with the following code
function hook__webform_submission_presave($node, &$submission) {
  $components_list = $node->webform['components'];
  foreach ($components_list as $comp)
  {
   if($comp['type']=='pay')
   {
    $comp_id = $comp['cid'];
   }
  }
 unset($submission->data[$comp_id]);
}

Preventing webform save


Reference anonymous inner class from other class file

Question: Hi guys is there anyway that I can reference or use this anonymous inner class in other classes?
private DgtebdllLib.CallbackFunctionCharPtr getScan = new DgtebdllLib.CallbackFunctionCharPtr()

The full code is below and I found this Java code here. This is an example for interfacing with DGT chessboard DLL using Java.
What I just like to do is just to get the data str String variable from getScan anonymous inner class. Any help/suggestions is deeply appreciated. Thanks
public class DemoDll
{
    private static boolean running = true;
    private static DgtebdllLib dll = null;

    /**
     * Callback implementation function for the received status
     */
    private DgtebdllLib.CallbackFunctionCharPtr getStatus = new DgtebdllLib.CallbackFunctionCharPtr()
    {
        @Override
        public void callback(Pointer data)
        {
            String str = data.getString(0);
            System.out.println("Received status: " + str);
        }
    };

    /**
     * Callback implementation function for the evaluation of the received scan
     */
    private DgtebdllLib.CallbackFunctionCharPtr getScan = new DgtebdllLib.CallbackFunctionCharPtr()
    {
        @Override
        public void callback(Pointer data)
        {
            String str = data.getString(0);
            System.out.println("Received a scan: " + str);
        }
    };

Comment: If it is declared public static, yes.
Comment: You could provide a getter for the member variable `getScan`...
Comment: Hi Holger thanks for answering. If its a member class why can't create a new instance of it from another class ?
Comment: Hi Arnaud, its declared as private and the way its declared is even not familiar to me. I have used inner classes before in Swing but not in this manner.
Comment: Actually what I just want to do is to get the value of str inside that member class. You see the way I understood the program is that the whole class is  placed in an infinite loop and if there are any changes in the board such as moving a pawn that member class will also be called and str will contain the position of the chess piece in the board.
Answer: It seems you are asking the wrong question. The call back encapsulates an action and all you have to do is to implement the desired action. So If you want to store the received data, just store it, e.g. in the outer instance:
public class DemoDll {
    private static boolean running = true;
    private static DgtebdllLib dll = null;

    String status;
    String scan;

    /**
     * Callback implementation function for the received status
     */
    private DgtebdllLib.CallbackFunctionCharPtr getStatus
     = new DgtebdllLib.CallbackFunctionCharPtr() {
        @Override
        public void callback(Pointer data) {
            status = data.getString(0);
            System.out.println("Received status: " + status);
        }
    };

    /**
     * Callback implementation function for the evaluation of the received scan
     */
    private DgtebdllLib.CallbackFunctionCharPtr getScan
     = new DgtebdllLib.CallbackFunctionCharPtr() {
        @Override
        public void callback(Pointer data) {
            scan = data.getString(0);
            System.out.println("Received a scan: " + scan);
        }
    };

    …

Now you can access the most recent status and scan values received by the call-backs without any special "access anonymous inner classes" feature.
Alternatively you can make the values accessible through a member class which is not anonymous:
public class DemoDll {
    private static boolean running = true;
    private static DgtebdllLib dll = null;

    static class StringRef implements DgtebdllLib.CallbackFunctionCharPtr() {
        String value;

        @Override
        public void callback(Pointer data) {
            value = data.getString(0);
            System.out.println("Received: " + value);
        }
    }
    StringRef status;
    StringRef scan;

    …

so then you can use status and scan as call-backs and read status.value and scan.value afterwards.
Comment: hmmmm... why didn't i think of this before. I am going to try this out. I was just confused with how this member class is implemented. I've dealt with Swing inner classes before but this one is very new to me. Thanks Holger
Comment: Thanks very much Holger for your suggestion now am able to proceed with other things
Answer: The essence of a class being anonymous is that you cannot refer to it by name. Usually, though, it is enough to refer to its instances using the static type of its supertype.
There is a thoeretical, roundabout way to reflectively refer to the anonymous class by its binary name, but that would not be recommended.
Comment: Hi Marko, thanks for answering, am not that good with reflections but can I  make a getter or setter for this? as Oli suggested in the comments?


Grails databinding with decimal delimiter

Question: I have a problem when I use grail automatic databinding "ex: Test t = new Test(params)" with decimal delimiter on Double form field. After few search, I've found that it is relative to the browser Locale.
Example :
If I enter number with decimals separated by a dot '3.45' it does not work (The decimal part of the number is ignored). It store 3.0 in my database
If I do the same test but using a comma '3,45' for decimal separator, everything works fine. Grails store 3.45 in the database.
The problem is that nobody enter number with comma delimiter. (even the numpad enter a dot '.' when set to fr_CA)
I've already found some solutions like register custom number editor (bit painful when you have many apps) or set the global localeResolver to en_US (that last one doesn't do the job because I loose all the internationalization functionality of my app).
So, does someone have an easy solution to fix that problem?
using:
Grails : 2.2.0
Browser : Google Chrome (locale fr_CA)
Thanks a lot!
Answer: I've been searching and trying for 2 days. I've finally chosen to define a custom PropertyEditorRegistar. This way, I can fix the Locale only for the Double field format. However, I don't think that it's the best solution because it will be applied to all my Double fields. But in the mean time it does the job pretty well. So if someone have a better solution, I will be glad to test it and update my code.
So this is how I set this up :
1 - Create a new  groovy class that implements PropertyEditorRegistrar (if you already have one, just add the part of code contained by the method in the existing one)
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomNumberEditor;

public class CustomDoubleRegistrar implements PropertyEditorRegistrar {

    @Override
    public void registerCustomEditors(PropertyEditorRegistry registry) {
            //define new Double format with hardcoded Locale.ENGLISH
        registry.registerCustomEditor(Double.class,
                 new CustomNumberEditor(Double.class,
                           DecimalFormat.getInstance(Locale.ENGLISH),true))
    }

}

2- Define the custom registrar into the conf/spring/resources.goovy (if it's not already there of course)
beans = {
    customPropertyEditorRegistrar(CustomDoubleRegistrar)
}

3- That's it, the Grails auto data binding will work fine
Test t = new Test(params);
//params contains many Double fields with dot '.' as decimal delimiter

Don't hesitate to post better solutions...
Thanks
EDIT 1
Since Grails 2.3 this solution is no longer working. If you still want to use this solution, you have to add this configuration to the Config.groovy file
grails.databinding.useSpringBinder = true
Or implement one of the new DataBinding. I've tried few of them but nothing seems to solve the decimal delimiter issue. Thank you to post answer if you know how...
EDIT 2
Since Grails 2.4+ you can define your own ValueConverter to bypass the basic Locale validation. Note that you must remove the changes made in the initial post and in the EDIT 1. Here's how to implement the custom ValueConverter:
conf/spring/resources.groovy
// Place your Spring DSL code here
beans = {
    "defaultGrailsjava.lang.DoubleConverter"(DoubleValueConverter)
}

class DoubleValueConverter implements ValueConverter {

    public LongValueConverter() {
    }

    boolean canConvert(value) {
        value instanceof Double
    }

    def convert(value) {
        //In my case returning the same value did the trick but you can define
        //custom code that takes care about comma and point delimiter...
        return value
    }

    Class<?> getTargetType() {
        return Double.class
    }
}

Comment: i am working with grails 3.3.1 and this solution doesnt work for my command objects. also @BingUsing doesnt work. I don't know why they changes the old behavior. the new one ist disgusting :/
Answer: For Grails 2.3+ you can properly override the default binder/converter, although it is not trivial or intuitive.
See my answer here: Binding real number values to Grails domain attributes (values sent by Dojo widgets)
Answer: I have the same problem here. For example a user in Germany will usually enter a , (comma) as a decimal separator but obviously you cannot prevent him from entering a dot instead ;) Also if you fill the value from Javascript it's quite difficult to get a localized number. So I wrote this small helper method for the controller. It might not cover all possible scenarios, but I need it for entering GPS coordinates. Feel free to suggest improvements.
    /**
     * Replaces , in the param with . an converts it to a Double.
     * @param paramName an array of paramater names
     */
    private convertDicimalParamsToDouble(paramName) {
        paramName.each { it
            def val = params[it]
            if(val) {
                val = val.replace(",", ".")
                try {
                    params[it] = Double.parseDouble(val)
                } catch (NumberFormatException) {
                    //ignore
                }
                log.debug("Converted decimal param ${it} with value '${params[it]}' to new value '${val}'")
            }
        }
    }

Then call it like this for example:
def save() {
    convertDicimalParamsToDouble(["lat", "lng"])
    ...


Parse json react in native flatlist

Question: I'm try to render data in an Flatlist but it's not working any solution?
My Code:

import React from 'react'
import { ActivityIndicator,  FlatList, Text, View  } from 'react-native'
import styles from '../components/style.js'

export default class Nachrichten extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      nachrichtenapidata: [],
      loading: true
    };
  }

  async componentDidMount() {
    try {
        const nachrichtenApiCall = await fetch(URL);
        const nachrichten = await nachrichtenApiCall.json();
        this.setState({nachrichtenapidata: nachrichten.data, loading: false});
        console.log(this.state.nachrichtenapidata);
    } catch(err) {
        console.log("Error fetching data-----------", err);
    }
  }
  render() {
    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, padding: 20 }}>
          <ActivityIndicator />
        </View>
      );
    }
    return (
      <View style={{ flex: 1, paddingTop: 20 }}>
        <FlatList
          data={this.state.nachrichtenapidata}
          renderItem={({ item }) => (
            <Text>
              -> {item}
            </Text>
          )}
          keyExtractor={(index) => index}
        />
      </View>
    );
  }
}

My Output is:
enter image description here
Any solution - i think i'm doing something stupid but can#t see it....?
Tnx all for help!
Answer: You can use JSON.parse() :
async componentDidMount() {
    try {
        const nachrichtenApiCall = await fetch(URL);
        const nachrichten = await nachrichtenApiCall.json();
        const json = JSON.parse(nachrichten);
        this.setState({
          nachrichtenapidata: json.data,
          loading: false
        });
        console.log(this.state.nachrichtenapidata);
    } catch(err) {
        console.log("Error fetching data-----------", err);
    }
  }

Are you sure the server is returning a valid json response ?

Parse json react in native flatlist


How to set elements html content from a string using JS?

Question: Before:

After:

best site eva

How to accomplish this with pure JS (no jQuery)?
Answer: There are a number of ways, probably the simplest is
document.getElementById("foo").innerHTML = 'best site eva';


handle scrapy exception CloseSpider

Question: import scrapy
from urllib.parse import urlparse
from tkinter import filedialog
import tkinter as tk
import csv
from scrapy.exceptions import CloseSpider

class GoogleSpider(scrapy.Spider):
    name = 'google'
    allowed_domains = ['google.com']

    start_urls = ['http://www.google.com/search?q=summer&hl=en&num=40']

    def __init__(self,stats):
        self.stats = stats
        SignalManager(dispatcher.Any).connect(receiver=self._close, signal=signals.spider_closed)
        SignalManager(dispatcher.Any).connect(receiver=self._open,signal=signals.spider_opened)

    def _open(self):
        #os.system('cls' if os.name == 'nt' else 'clear')
        root = tk.Tk()
        root.withdraw()
        self.input_file = filedialog.askopenfilename(title='Please Select Keywords File', filetypes=[('CSV files', ('.csv'))])
        if not self.input_file:
            raise CloseSpider(reason='no_file')

    def _close(self):
        print("done")

I get this error if no file is given, what I want is to simply close the spider with no error showing. How can I handle this exception Exceptions, I read from doc this is how you close spider it doesn't mention how to deal with it
2019-08-10 14:55:56 [scrapy.utils.signal] ERROR: Error caught on signal handler: <bound method GoogleSpider._open of <GoogleSpider 'google' at 0x7fd56b6eda58>>
Traceback (most recent call last):
  File "/home/timmy/.local/lib/python3.6/site-packages/twisted/internet/defer.py", line 151, in maybeDeferred
    result = f(*args, **kw)
  File "/home/timmy/.local/lib/python3.6/site-packages/pydispatch/robustapply.py", line 55, in robustApply
    return receiver(*arguments, **named)
  File "/home/timmy/spiders/google.py", line 61, in _open
    raise CloseSpider(reason='no_file')
scrapy.exceptions.CloseSpider

Comment: What is your Scrapy version?
Answer: I don't think that is supported at the moment.
Alternatively, you could set self.start_urls = [] instead, with a similar result.

handle scrapy exception CloseSpider