text:
Q: Expected size of least prime factor of $(16^p-1)/15$ Let's define a function $g(x)$ as follows:
$g(x)=-x+\displaystyle\sum_{\substack{3\le p\le x/2}\\{p \text{ prime}}}{\log_2 \left( \text{LeastPrimeFactor} \left( \frac{16^p-1}{15} \right) \right) }$
This function comes from a specific rabbit-hole of investigation around the Freudenthal Problem.  I want to know if $\liminf g(x) > 0$.  This leads directly to the question in the title.
The sum ranges over odd primes less than $x/2$, so the crux of the problem is finding the factors of Mersenne numbers, which makes me immediately think this is out of reach.  However, I've seen some heuristics discussed that make it seem like there might be a way forward.
Naively, we know 4 factors of $16^p-1$:

*

*$2^p-1$

*$2^p+1$

*$2^p-2^\frac{1+p}{2}+1$

*$2^p+2^\frac{1+p}{2}+1$
These are all of order $2^p$, one is divisible by 5 and another by 3, but there are not guaranteed factors beyond this.  Plugging them in gives us the sum of all odd primes up to $x/2$, dominating the $-x$ and leading to $+\infty$.
On the other hand, for $p\ge 7$ we know the lower bound for the least prime factor of this expression is $2p+1$, a bound which is attained quite often.  Summing $\log_2 \left( 2p+1 \right)$ gives something $O(x)$, and if we replace it throughout, $g(x)$ tends to $-\infty$.
Using actual data, mostly scraped from Will Edgington's database and assembled in Mathematica, it looks like the big factors eventually start winning.  Of course, I'm hesitant to make claims using only data, particularly when discussing not-yet-found factors.  For example, when $p=2267$, it seems that we know one prime factor with 40 digits and haven't proven that it is the least prime factor.  But when $p=11423$, we don't know any prime factors!

Is there some reasonable way to predict in-bulk, the expected behavior of the least prime factors of these Mersenne-adjacent numbers?  If so, what does it predict about $g(x)$?
Edit:
I tried my hand at a probabilistic number theory approach.
The progression $2np+1$ includes all factors of $(16^p-1)/15$.
The size of the $k$th prime in that progression goes as $2pk \log(2pk) / \log(2p)$, but the log of that value can be approximated reasonably as $\log(2pk)$.
The upper limit of $k$ is $2^p$ due to the known factors.  You could also put $2^{p/2}$ here and the expressions below would not change at leading order.
Some integrals show that

*

*$\int^{2^p} \frac{1}{k} \,dk \rightarrow p \log 2$

*$\int^{2^p} \frac{1}{k \log k} \,dk \rightarrow \log p$

*$\int^{2^p} \frac{1}{k \log^2 k} \,dk \rightarrow 1/\log 2$.

If I follow the argument in Expected smallest prime factor with appropriate generality, I think the probability the $k$th prime in the progression is the smallest prime factor, goes as $\frac{1}{k \log^2 k}$.
This gives rise to an expectation value for $\log_2 \left( \text{LeastPrimeFactor} \left( 2^p-1 \right) \right)$ that is $(1 + 1/\log2)\log p + O(\log \log p)$, and a variance that is $O(p)$.
This might be a classic result?  Or it might be an erroneous result.  But converting the base it sounds like the expected number-of-bits in the smallest factor of the $p$th Mersenne number is $1 + \log 2 = 1.69315..$ times the number of bits in $p$ itelf.
The variance is large, and the distribution has a hard minimum of $\log(2p+1)$, so among many samples of this distribution there will be cases where the log of the factor is itself $O(\sqrt{p})$.
Now, the log-least-prime-factor of $(16^p - 1)/15$ would be the minimum of 4 reasonably-independent draws from this distribution, so it avoids the $O(\sqrt{p})$ draws with higher likelihood.  But by this point I feel like the approximations and assumptions are going to catch up with me before I get anywhere.
So, I'd like to have help with continuing/refining this argument until it can predict something reasonably useful about $g(x)$.

A: Ok, I have at least some progress worth sharing.
Put $f(p) = \log_2\left(\text{LeastPrimeFactor}\left(\left(16^p-1\right)/15\right)\right)$.  Let's treat $f(p)$ as a random variable, and compute its expectation value as a function of $p$:
To do so, consider "some value of order $2^p$ which is divisible only by numbers of the form $2pn+1$".  Namely, this definition encompasses Mersenne numbers of prime exponent $2^p-1$, as well as $(2^p+1)/3$, $2^p\pm 2^{(1+p)/2}+1$, and $(2^p\mp 2^{(1+p)/2}+1)/5$.
The product of these 4 expressions is our current target number, and because $2^p+1-(2^p-1)=2$, $4^p+1-(4^p-1)=2$, and $2^p + 2^{(1+p)/2}+1 - (2^p - 2^{(1+p)/2}+1) = 2^{(3+p)/2}$, there is no way for any pair of them to have factors in common.
Among the progression $2pn+1$, which numbers can be the smallest prime factor?  Only the primes, for one.  Additionally, they must be either less than $2^{p/2}$ (otherwise the cofactor would be smaller and thus have smaller prime factors), or be the expression itself.  With our goal here, we will be able to neglect the case where all 4 expressions are prime.  It will make $f(p)$ larger than we predict, if it does happen for some large $p$, but we are able to make progress whether or not it ever happens for $p>7$.
By the behavior of PNT in arithmetic progressions, we expect the $k$th prime $p_k$ in the progression $2pn+1$ to be approximately $p_k \approx pk\log(2pk)$.  This holds up well vs data.
The probability $\pi_k$ that $p_k$ is the smallest prime factor of $(16^p-1)/15$ is the product of:

*

*The probability that it divides one of the 4 known factors of order $2^p$. If we just used sieve theory, this would be $4/p_k$ for sufficiently large $p$.  However, we will add a factor $A$ in as well, for reasons understood later.

*The probability that for all $k' < k$, The $k'$th prime is not a divisor of any of the 4 known factors. From the above, this is a product $\prod_{k'<k}{\left(1-4A/p_{k'}\right)}$.

When $p$ and $k$ are sufficiently large,
$\frac{\pi_{k+1}}{\pi_{k}} = \frac{k\log(2pk)}{(k+1)\log(2pk+2p)}\left(1-\frac
{4A}{pk\log(2pk)}\right) \approx 1-\frac{4A+p+p\log(2pk))}{pk\log(2pk)} \rightarrow \partial_k(\log(\pi_k))=-\frac{4A+p+p\log(2pk))}{pk\log(2pk)}$
Which suggsts that
$\pi_k \propto \exp\left(-\int\frac{4A+p+p\log(2pk))}{pk\log(2pk)}\right) \approx k^{-1}\log(2pk)^{-(1+4A/p)}$
For any $A>0$ this is a convergent sum, but most of its support at large $p$ is over $k>2^p$, which is too large to be a factor.  We need an upper bound on $k$ at $k_{\text{max}}=p^{-2}\times2^{p/2}$, so that $p_{k_\text{max}} \approx 2^{p/2}$.  We cannot simply truncate the sum and then divide throughout by the partial sum, as this changes the "probability that $p_k$ divides the expression" without corresponding changes to "the probability that for all $k'<k$, $p_k'$ does not divide the expression".  This is why we have the factor $A$.  We pick $A$ such that the partial sum is self-consistent, as follows:
$\pi_k \approx \frac{4A}{pk \log(2pk)}\left(\frac{\log(2p)}{\log(2pk)}\right)^{4A/p}\hspace{15pt}\sum_{k=1}^{p^{-2}2^p}\pi_k \approx \frac{4A}{p}(\log(p)-\log\log(2p)-1)\hspace{15pt} A=\frac{p}{4(\log(p)-\log\log(2p)-1)}$
The renormalization is bizarre and I frankly don't trust it.  For one, it completely disregards the distinction between $2^p-1$, $(4^p-1)/3$, and $(16^p-1)/15$, since that boils down to the $4$ that gets swallowed by $A$.  For another, one gets $f(p) = O(p)$ which is much larger than observed data.
I think the conclusion of this, is that sieve methods are not applicable because the set of numbers we are considering do not constitute an appropriately dense portion of the integers.  It is not correct to give a sieve-like form $\approx 1/p_k$for the probability that $p_k$ divides our target number.  I'll keep thinking, but I'm posting my work here for people to at least learn a dead end.


text:
Q: Handle Dimensionality when Clustering How can I perform a cluster analysis (e.g. kmeans, complete link,etc) when objects are represented by vectors of different sizes? For example, Object 1 is represented by a 4-dim vector, Object 2 by 6-dim vector, Object 3 by 3-dim vector, etc...
Is there any way to normalize the representation of objects? What do you suggest?
Thank you!

A: In short, no, it is not possible. It may be possible to represent your objects' vectors as member of the same (higher dimensional space). This will only work if there is some overlap in the features of your objects. Consider the following vectors:
 object1: a, b, c, d
 object2: b, d, e
 object2: a, d

The set of all features is {a, b, c, d, e}, and the three objects can be represented as follows:
 object1: a, b, c, d, 0
 object2: 0, b, 0, d, e
 object2: a, 0, 0, d, 0

0 is a placeholder indicating this object does not have the particular features. Your objects now live in the same 5-dimensional space and can be clustered.
Note: any sane vector library will actually store vector in a sparse format such as the one in my first example. This gives you a very small memory footprint if only a few features are non-zero. The format of my second example is dense. Some libraries expect a dense input and some can to convert from one to the other automatically. In any case I think it is unlikely that you will have to manually do the conversion I did above.

Edit: feature vectors need to end up as list of integers. Each position in the list corresponds to a particular piece of information. You might start with the following features:
cat- weight 4 kg, is very cute
whale- weight 3000kg, not very cute, lives in ocean
rat- weight 0.3 kg, not cute at all, lives in sewers

So cat here is represented by 2 features, or a vector of dimensionality 2. This information translates to the following table:
        weight(kg)    cuteness(%)     lives_in_sewers?    lives_in_ocean?
 cat        4             8                  0                  0
 whale    3000            3                  0                  1
 rat       0.2            2                  1                  0

The feature vectors are:
cat = [4, 8, 0, 0]
whale = [3000m 3, 0, 1]
rat = [0.2, 2, 1, 0]

redpajama_set_name: RedPajamaStackExchange


text:
Q: from scipy.interpolate import interp1d hangs django Need to use interp1d from scipy, but if i try to import it, app can't finish loading page.
I have view which works fine:
def index(request):
     return render_to_response('price/index.html')

As far as i just try to import
from scipy.interpolate import interp1d

Page loads forever. No errors.

A: Finally could make it work. Need to add directive
WSGIApplicationGroup %{GLOBAL}

to apache2 config.


text:
Q: How to add data to table that is existing if (file_exists(TEMP.'/'."$check_dir".'/'."$endofname$test".'.jpeg'))
        {
                echo "File : $endofname$test was made <br />";
                move($new_file_destination);

                $img_name = 'http:localhost/single4thenight/media/com_jomclassifieds/items/backpage/'."$check_dir".'/'."$endofname$test".'_1.jpeg, ';
                $img_title = "UPDATE iutca_jomcl_adverts SET images='$img_name' WHERE title='$title'";
                if ($conn->query($img_title) === TRUE)
                    {
                        echo "Record updated successfully";
                    } else {
                            echo "Error updating record: " . mysqli_error($conn);
                                }
        }

I need to add data to a table that is existing but I want to add data to the table not erase it with the updating data

A: Try to use the INSERT INTO SQL if you want to add a new row.
INSERT INTO table (column1, column2, ..., columnN) VALUES ('value_column1',...,'value_columnN')

If you want to add data to an existing row (not table), you should use UPDATE SQL setting only field you want to edit/add.

A: You are updating rows using the UPDATE syntax. That only tells MySQL that you want to update data in that database NOT create a new row.
You will have to use the INSERT INTO syntax outlined in the MySQL documentation.

A: If you're trying to append (concatenate) a new value to the end of an existing row's value you will still need to use UPDATE.
It would look something like this:
UPDATE iutca_jomcl_adverts SET images = CONCAT_WS('|', images, '$img_name') WHERE title='$title'
(CONCAT_WS is "concatenate with separator")
However, that won't handle the case where the row doesn't already exist. In that case, you would need to do an INSERT and use MySQL's ON DUPLICATE KEY UPDATE images = CONCAT(images,'|$img_name') (if title is a unique key).


text:
Q: I am getting a 400 Bad Request error when using Nginx and PHP-FPM, why? I am trying to run a website (that requires PHP - it technically doesn't require MySQL at this time, but it may sometime in the near future as I continue developing it, so I went ahead and installed that as well) using nginx 1.2.4 and PHP-FPM 5.3.3 on Ubuntu 12.04.1 LTS. As far as I know, I haven't done anything wrong, but clearly something is not quite right - I seem to be getting a 400 Bad Request error whenever I try to browse to my website. I've been mostly following one guide, and I've done more or less everything it recommends, except for not setting up PHP-FPM to use a Unix Socket and I used service as opposed to /etc/init.d/ when starting/stopping nginx, PHP, and MySQL.
Anyways, here are my relevant configuration files (I have only censored personal/sensitive details, like my domain name - which contains my real name):
/etc/nginx/nginx.conf
user www-data;
worker_processes 4;
pid /var/run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 15;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;
        gzip_disable "msie6";

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # nginx-naxsi config
        ##
        # Uncomment it if you installed nginx-naxsi
        ##

        #include /etc/nginx/naxsi_core.rules;

        ##
        # nginx-passenger config
        ##
        # Uncomment it if you installed nginx-passenger
        ##

        #passenger_root /usr;
        #passenger_ruby /usr/bin/ruby;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

/etc/nginx/sites-enabled/subdomain.mydomain.net
server {
        listen 80;      # listen for IPv4
        listen [::]:80; # listen for IPv6

        server_name www.subdomain.mydomain.net subdomain.mydomain.net;

        access_log /srv/www/subdomain.mydomain.net/logs/access.log;
        error_log /srv/www/subdomain.mydomain.net/logs/error.log;

        location / {
                root /srv/www/subdomain.mydomain.net/public;
                index index.php;
        }

        location ~ \.php$ {
                try_files $uri =400;
                include fastcgi_params;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME /srv/www/subdomain.mydomain.net/public$fastcgi_script_name;
        }
}

All the directories listed in the configuration files above are correct on my server (to the extent of my knowledge).
I have not included /etc/php5/fpm/pool.d/www.conf or /etc/php5/fpm/php.ini in this post as they're rather long, but I have posted them on Pastebin: http://pastebin.com/ensErJD8 and http://pastebin.com/T23dt7vM, respectively. Although, the only thing I've changed in either of the two files was in php.ini, where I set expose_php to off so as to hide the .php file extension from users.
What can I do to resolve my issue? Please let me know if I need to supply any additional details.

A: This is probably a typo:
            try_files $uri =400;

It should almost certainly be:
            try_files $uri =404;

A: I'm guessing TechZilla already stated this, but you could modify this line:
fastcgi_pass 127.0.0.1:9000;

to be this.
fastcgi_pass unix:/var/run/php5-fpm.sock;

I was assuming because you stated you installed PHP-FPM, that the using the .sock method should be better than passing on through TCP.
Connecting to PHP-FPM through the .sock method can be done if the package installing PHP-FPM also sets the necessary permissions and configured correctly. If not, you may have to resort to connecting to PHP-FPM through 127.0.0.1:9000. Thanks to Paul for informing me on that.

It is also possible that this line:
include fastcgi_params;

could be changed into this:
include fastcgi.conf;

However, don't count me on this. I have no clue why this works on my Ubuntu Server VM, but it does at the moment.

Source: https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-14-04


text:
Q: There's a discrepancy between the number of starred messages reported at different places In the C++ chat room, the number of all starred messages is currently reported in the right-hand panel as 3407.
That number is a link, and if I click on it, it takes me to [an info page with a tab saying 5.9k stars.

I'm sure there is an explanation for this discrepancy, but I'd like to think it is a bug no matter what the explanation is.

A: There are 3407 messages, which are cumulatively starred 5.9k times. It might make more sense if the stars tab was actually the starred tab so that the number would be consistent, since I imagine most people are interested in the number of messages starred (although the number of total stars could still be shown somewhere on that page).


text:
Q: After login navigation not working due to fetch async in reactjs After successful login using the fetch call, when I try to navigate to an explorer view using
    self.props.history.push('/explore');
it appears that it works only sometimes due to async nature of fetch.
Even when it works, it navigates back to login back after momentarily flashing the explorer view.
What is the right way to do this?
Thanks
If I put an alert after the fetch …. alert("Done")
in the code, it does flash or stay at explorer view, before routing back to login view.
class login extends Component {
    constructor() {
    super();

    this.state = {
      email: "",
      password: "",
      loggedIn: false
    };

    this.handleEmailChange = this.handleEmailChange.bind(this);
    this.onClick = this.onClick.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
  }

  handleEmailChange  = event => {
      this.setState({email: event.target.value});
  }

  handlePasswordChange  = event => {
    this.setState({password: event.target.value});
  }

    onClick = ({ event, props }) =>
    {
      alert('on login');
      // alert("EMail: " + this.state.email);

      const self = this;
      fetch('http://xx.xx.xx.xx/api/login/', {
          method: 'post',
          headers: {
              'Content-Type': 'application/json',
          },
          body: JSON.stringify({
              username: this.state.email,
              password: this.state.password
          })
      })
      .then(function(response){
        //console.log(response);
        //alert(response);
        return response.json();
      })
      .then(function(myJson) {
          console.log(JSON.stringify(myJson));
          var obj = myJson.success;
          console.log(obj);
          if(obj == true)
          {
            self.props.history.push('/explore');
          }
          self.setState({ loggedIn: myJson.success});
          //console.log(JSON.stringify(myJson.data));
        });
      alert('Done ');
    }

   render() {

    return (

        <form>

Email

        <input type="text" name="" placeholder="Enter Email" value={this.state.email} onChange={this.handleEmailChange}></input>

Password

        <input type="password" name="" placeholder="***********" value={this.state.password} onChange={this.handlePasswordChange}></input>
        <input type="submit" name="" value="Sign In" onClick={this.onClick}></input>
        </form>

    );
  }
}

A: I would suggest that you declare the function onclick outside the render method. The onclick function exists only in the context of the render, each time the inputs or states of the composite muten are recreated. Also that the actions as calls to api declare them in a container and that the function passes as property to the Login component.

A: First of all move fetch to componentDidMount and its better not to use history.push('/explore'); instead of it store a variable and depending on it redirect by returning <Redirect /> in render.
https://medium.com/@anneeb/redirecting-in-react-4de5e517354a


text:
Q: How to do userEvnt.click on a div in react testing library so i have a component that maps an array and returns a div with an onClick event
     {credits?.crew.slice(0, maxCreditsResults).map((crew, idx) => {
              return (

 navigate(`/${EPages.person}/${crew.id}`)}
                >

-{crew.name}

Department: {crew.department}

              );
            })}

i want to test this click event but i dont know how to get that specific div so i can click it with userEvent.click()
i looked at the methods of the sreen that comes from react testing library but i cant find one that would help me

A: You can add data-testid like <div data-testid = {idx + '-cast-card' }
Then call first element of div.
const element = screen.getByTestId('0-cast-cart')
fireEvent.click(element);


text:
Q: List containers a user has access to in Azure storage Given an accesstoken that allows me access to an Azure storage account, (so I can read/write blobs on behalf of a user), I would also like to be able to discover all the containers the user has read/write access to in the storage account.
Is there a way in C#, to get a list of these containers? I know that there is a general way to get a list of all containers (for example, https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-containers-list?tabs=dotnet), but the user would need read access on the storage account for this, and I just want to find the containers the user has access to.

A: Per my understanding, you are using Azure AD Auth to protect your blob containers, and you want to get a container list that a user has read access.
Basically, if a user with roles: Storage Blob Data Contributor, Storage Blob Data Owner,Storage Blob Data Reader of a container, will have read access. Details see here.
So we just need to check under a storage account scope, if this user is granted anyone of these 3 roles. We can do it via the Azure Management API, just refer to the console application code below:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace AzureRoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var subscriptionID = "<your subscription ID>";
            var userObJId = "<user Object ID>";
            var storageAccountName = "<storage Account name>";
            var resourceGroup = "<resource group name>";

            var adminAccessToken = "<access token to call Azure management API>";

            List<Role> destRoles = new List<Role>();
            destRoles.Add(new Role() { name = "Storage Blob Data Contributor", RoleId = "ba92f5b4-2d11-453d-a403-e96b0029c9fe" });
            destRoles.Add(new Role() { name = "Storage Blob Data Owner", RoleId = "2a2b9908-6ea1-4ae2-8e65-a410df84e7d1" });
            destRoles.Add(new Role() { name = "Storage Blob Data Reader", RoleId = "db58b8e5-c6ad-4a2a-8342-4190687cbf4a" });

            //get all role assigment records relatged to a user under a storage account
            var requestUrl = @"https://management.azure.com/subscriptions/"+ subscriptionID + "/resourceGroups/"+resourceGroup+"/providers/Microsoft.Storage/storageAccounts/" + storageAccountName + "/providers/Microsoft.Authorization/roleAssignments?$filter=principalId eq '" + userObJId + "'&api-version=2020-04-01-preview";
            WebRequest request = WebRequest.Create(requestUrl);
            request.Headers.Add("Authorization", "Bearer " + adminAccessToken);
            WebResponse response = request.GetResponse();
            using (Stream dataStream = response.GetResponseStream())
            {
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();

                var result = JsonConvert.DeserializeObject<RoleList>(responseFromServer);

                Console.WriteLine("User has permission to access containers:");
                //Filter roles that has permission to read container
                foreach (var roleItem in result.value){
                    var destRole = destRoles.Find(x => roleItem.properties.roleDefinitionId.Contains(x.RoleId) && roleItem.properties.scope.Contains("containers"));
                    if (destRole != null) {

                        Console.WriteLine("Container Name:" + roleItem.properties.scope.Substring(roleItem.properties.scope.LastIndexOf("/") + 1) + " Role:" + destRole.name );
                    }
                }

            }

            // Close the response.
            response.Close();

        }

        public class Role {
            public string name { get; set; }
            public string RoleId{ get; set; }
        }

        public class Properties
        {
            public string roleDefinitionId { get; set; }
            public string principalId { get; set; }
            public string principalType { get; set; }
            public string scope { get; set; }
            public object condition { get; set; }
            public object conditionVersion { get; set; }
            public DateTime createdOn { get; set; }
            public DateTime updatedOn { get; set; }
            public string createdBy { get; set; }
            public string updatedBy { get; set; }
            public object delegatedManagedIdentityResourceId { get; set; }
            public object description { get; set; }
        }

        public class RoleDetils
        {
            public Properties properties { get; set; }
            public string id { get; set; }
            public string type { get; set; }
            public string name { get; set; }
        }

        public class RoleList
        {
            public List<RoleDetils> value { get; set; }
        }
    }
}

Result:


text:
Q: Snowplow Enrich Setup Issue collector.conf
collector {

  interface = "0.0.0.0"
  interface = ${?COLLECTOR_INTERFACE}
  port = 8181
  port = ${?COLLECTOR_PORT}

  # optional SSL/TLS configuration
  ssl {
    enable = false
    enable = ${?COLLECTOR_SSL}
    # whether to redirect HTTP to HTTPS
    redirect = false
    redirect = ${?COLLECTOR_SSL_REDIRECT}
    port = 9543
    port = ${?COLLECTOR_SSL_PORT}
  }

  paths {
    # "/com.acme/track" = "/com.snowplowanalytics.snowplow/tp2"
    # "/com.acme/redirect" = "/r/tp2"
    # "/com.acme/iglu" = "/com.snowplowanalytics.iglu/v1"
  }

  # Configure the P3P policy header.
  p3p {
    policyRef = "/w3c/p3p.xml"
    CP = "NOI DSP COR NID PSA OUR IND COM NAV STA"
  }

  crossDomain {
    enabled = false
    # Domains that are granted access, *.acme.com will match http://acme.com and http://sub.acme.com
    enabled = ${?COLLECTOR_CROSS_DOMAIN_ENABLED}
    domains = [ "*" ]
    domains = [ ${?COLLECTOR_CROSS_DOMAIN_DOMAIN} ]
    # Whether to only grant access to HTTPS or both HTTPS and HTTP sources
    secure = true
    secure = ${?COLLECTOR_CROSS_DOMAIN_SECURE}
  }

  cookie {
    enabled = true
    enabled = ${?COLLECTOR_COOKIE_ENABLED}
    expiration = "365 days"
    expiration = ${?COLLECTOR_COOKIE_EXPIRATION}
    # Network cookie name
    name = zanui_collector_cookie
    name = ${?COLLECTOR_COOKIE_NAME}
    domains = [
        "{{cookieDomain1}}" # e.g. "domain.com" -> any origin domain ending with this will be matched and domain.com will be returned
        "{{cookieDomain2}}" # e.g. "secure.anotherdomain.com" -> any origin domain ending with this will be matched and secure.anotherdomain.com will be returned
        # ... more domains
    ]
    domains += ${?COLLECTOR_COOKIE_DOMAIN_1}
    domains += ${?COLLECTOR_COOKIE_DOMAIN_2}
    fallbackDomain = ""
    fallbackDomain = ${?FALLBACK_DOMAIN}
    secure = false
    secure = ${?COLLECTOR_COOKIE_SECURE}
    httpOnly = false
    httpOnly = ${?COLLECTOR_COOKIE_HTTP_ONLY}
    sameSite = "{{cookieSameSite}}"
    sameSite = ${?COLLECTOR_COOKIE_SAME_SITE}
  }

  doNotTrackCookie {
    enabled = false
    enabled = ${?COLLECTOR_DO_NOT_TRACK_COOKIE_ENABLED}
   # name = {{doNotTrackCookieName}}
    name = zanui-collector-do-not-track-cookie
   # value = {{doNotTrackCookieValue}}
    value = zanui-collector-do-not-track-cookie-value
  }

  cookieBounce {
    enabled = false
    enabled = ${?COLLECTOR_COOKIE_BOUNCE_ENABLED}
    name = "n3pc"
    name = ${?COLLECTOR_COOKIE_BOUNCE_NAME}
    fallbackNetworkUserId = "00000000-0000-4000-A000-000000000000"
    fallbackNetworkUserId = ${?COLLECTOR_COOKIE_BOUNCE_FALLBACK_NETWORK_USER_ID}
    forwardedProtocolHeader = "X-Forwarded-Proto"
    forwardedProtocolHeader = ${?COLLECTOR_COOKIE_BOUNCE_FORWARDED_PROTOCOL_HEADER}
  }
  enableDefaultRedirect = true
  enableDefaultRedirect = ${?COLLECTOR_ALLOW_REDIRECTS}
  redirectMacro {
    enabled = false
    enabled = ${?COLLECTOR_REDIRECT_MACRO_ENABLED}
    # Optional custom placeholder token (defaults to the literal `${SP_NUID}`)
    placeholder = "[TOKEN]"
    placeholder = ${?COLLECTOR_REDIRECT_REDIRECT_MACRO_PLACEHOLDER}
  }
  rootResponse {
    enabled = false
    enabled = ${?COLLECTOR_ROOT_RESPONSE_ENABLED}
    statusCode = 302
    statusCode = ${?COLLECTOR_ROOT_RESPONSE_STATUS_CODE}
    # Optional, defaults to empty map
    headers = {
      Location = "https://127.0.0.1/",
      Location = ${?COLLECTOR_ROOT_RESPONSE_HEADERS_LOCATION},
      X-Custom = "something"
    }
    # Optional, defaults to empty string
    body = "302, redirecting"
    body = ${?COLLECTOR_ROOT_RESPONSE_BODY}
  }
  cors {
    accessControlMaxAge = 5 seconds
    accessControlMaxAge = ${?COLLECTOR_CORS_ACCESS_CONTROL_MAX_AGE}
  }

  # Configuration of prometheus http metrics
  prometheusMetrics {
    enabled = false
  }

  streams {
    # Events which have successfully been collected will be stored in the good stream/topic
    good = snowplow-collected-good-events-stream
    good = ${?COLLECTOR_STREAMS_GOOD}

    # Events that are too big (w.r.t Kinesis 1MB limit) will be stored in the bad stream/topic
    bad = snowplow-collected-bad-events-stream
    bad = ${?COLLECTOR_STREAMS_BAD}

    useIpAddressAsPartitionKey = false
    useIpAddressAsPartitionKey = ${?COLLECTOR_STREAMS_USE_IP_ADDRESS_AS_PARTITION_KEY}

    sink {
      enabled = kinesis
      enabled = ${?COLLECTOR_STREAMS_SINK_ENABLED}

      # Region where the streams are located
      region = ap-southeast-2
      region = ${?COLLECTOR_STREAMS_SINK_REGION}

      threadPoolSize = 10
      threadPoolSize = ${?COLLECTOR_STREAMS_SINK_THREAD_POOL_SIZE}
      aws {
        accessKey = env
        accessKey = ${?COLLECTOR_STREAMS_SINK_AWS_ACCESS_KEY}
        secretKey = env
        secretKey = ${?COLLECTOR_STREAMS_SINK_AWS_SECRET_KEY}
      }

      # Minimum and maximum backoff periods, in milliseconds
      backoffPolicy {
        #minBackoff = {{minBackoffMillis}}
        minBackoff = 10
        #maxBackoff = {{maxBackoffMillis}}
        maxBackoff = 10
        }

 }

    buffer {
      byteLimit = 4500000
      byteLimit = ${?COLLECTOR_STREAMS_BUFFER_BYTE_LIMIT}
      recordLimit =500 # Not supported by Kafka; will be ignored
      recordLimit = ${?COLLECTOR_STREAMS_BUFFER_RECORD_LIMIT}
      timeLimit = 5000
      timeLimit = ${?COLLECTOR_STREAMS_BUFFER_TIME_LIMIT}
    }
  }

}

akka {
  loglevel = DEBUG # 'OFF' for no logging, 'DEBUG' for all logging.
  loglevel = ${?AKKA_LOGLEVEL}
  loggers = ["akka.event.slf4j.Slf4jLogger"]
  loggers = [${?AKKA_LOGGERS}]

  http.server {
    remote-address-header = on
    remote-address-header = ${?AKKA_HTTP_SERVER_REMOTE_ADDRESS_HEADER}

    raw-request-uri-header = on
    raw-request-uri-header = ${?AKKA_HTTP_SERVER_RAW_REQUEST_URI_HEADER}

    # Define the maximum request length (the default is 2048)
    parsing {
      max-uri-length = 32768
      max-uri-length = ${?AKKA_HTTP_SERVER_PARSING_MAX_URI_LENGTH}
      uri-parsing-mode = relaxed
      uri-parsing-mode = ${?AKKA_HTTP_SERVER_PARSING_URI_PARSING_MODE}
    }
  }

}

Run Command:
java -Dcom.amazonaws.sdk.disableCbor -jar snowplow-stream-collector-kinesis-1.0.0.jar --config collector.conf

enricher.conf
enrich {

  streams {

    in {
      # Stream/topic where the raw events to be enriched are located
      raw = snowplow-collected-good-events-stream
      raw = ${?ENRICH_STREAMS_IN_RAW}
    }

    out {
      # Stream/topic where the events that were successfully enriched will end up
      enriched = snowplow-collected-good-events-stream

      # Stream/topic where the event that failed enrichment will be stored
      bad = snowplow-collected-bad-events-stream
      bad = ${?ENRICH_STREAMS_OUT_BAD}
      # Stream/topic where the pii tranformation events will end up
     # pii = {{outPii}}
     # pii = ${?ENRICH_STREAMS_OUT_PII}

      partitionKey = event_id
      partitionKey = ${?ENRICH_STREAMS_OUT_PARTITION_KEY}
    }

    sourceSink {

      enabled =  kinesis
      enabled =  ${?ENRICH_STREAMS_SOURCE_SINK_ENABLED}

      region = ap-southeast-2

       aws {
         accessKey = env
         accessKey = ${?ENRICH_STREAMS_SOURCE_SINK_AWS_ACCESS_KEY}
         secretKey = env
         secretKey = ${?ENRICH_STREAMS_SOURCE_SINK_AWS_SECRET_KEY}
       }

       maxRecords = 10000

      initialPosition = TRIM_HORIZON
      initialTimestamp = "2020-09-10T10:00:00Z"

      backoffPolicy {
        minBackoff = 1000
        minBackoff = ${?ENRICH_STREAMS_SOURCE_SINK_BACKOFF_POLICY_MIN_BACKOFF}
        maxBackoff = 5000
        maxBackoff = ${?ENRICH_STREAMS_SOURCE_SINK_BACKOFF_POLICY_MAX_BACKOFF}
      }

    }

    buffer {
      byteLimit = 1000000000
      byteLimit = ${?ENRICH_STREAMS_BUFFER_BYTE_LIMIT}
      recordLimit = 10 # Not supported by Kafka; will be ignored
      recordLimit = ${?ENRICH_STREAMS_BUFFER_RECORD_LIMIT}
      timeLimit = 5000
      timeLimit = ${?ENRICH_STREAMS_BUFFER_TIME_LIMIT}
    }

    appName = "zanui-enricher-app"
    appName = ${?ENRICH_STREAMS_APP_NAME}
  }

}

Run Command:
java -jar snowplow-stream-enrich-kinesis-1.0.0.jar --config enricher.conf --resolver file:resolver.json

S3 Loader Config
source = "kinesis"

sink = "kinesis"

aws {
  accessKey = "env"
  secretKey = "env"
}

# Config for NSQ
 nsq {
  channelName = "nsqSourceChannelName"

  # Host name for NSQ tools
  host = "127.0.0.1"

  # HTTP port for nsqd
   port = 4150

  # HTTP port for nsqlookupd
   lookupPort = 4161
}

kinesis {

  initialPosition = "TRIM_HORIZON"
  initialTimestamp = "2017-05-17T10:00:00Z"
  maxRecords = 10000
  region = "ap-southeast-2"
  appName = "zanui-enricher-app"
}

streams {
  inStreamName = "snowplow-collected-good-events-stream"
  outStreamName = "snowplow-collected-bad-events-stream"

  buffer {
    byteLimit = 1000000000 # Not supported by NSQ; will be ignored
    recordLimit = 10
    timeLimit = 5000 # Not supported by NSQ; will be ignored
  }
}

s3 {
  region = "ap-southeast-2"
  bucket = "snowplow-enriched-good-events"
  partitionedBucket = "snowplow-enriched-good-events/partitioned"
  dateFormat = "{YYYY}/{MM}/{dd}/{HH}"
  outputDirectory = "zanui-enriched/good"
  filenamePrefix = "zanui-output"
  format = "gzip"
  # Maximum Timeout that the application is allowed to fail for (in milliseconds)
  maxTimeout = 300000 # 5 minutes
}

Run Command:
java -jar snowplow-s3-loader-0.6.0.jar --config my.conf

But this Snowplow S3 Loader not doing anything so i used Data Fireshose to transfer stream to S3 bucket.
When i try to use Aws Lambda in Data Fireshose, it give error
{"attemptsMade":4,"arrivalTimestamp":1600154159619,"errorCode":"Lambda.FunctionError","errorMessage":"The Lambda function was successfully invoked but it returned an error result.","attemptEndingTimestamp":1600154235846,"rawData":"****","lambdaArn":"arn:aws:lambda:ap-southeast-2:573188294151:function:snowplow-json-transformer-lambda:$LATEST"}
    {"attemptsMade":4,"arrivalTimestamp":1600154161523,"errorCode":"Lambda.FunctionError","errorMessage":"The Lambda function was successfully invoked but it returned an error result.","attemptEndingTimestamp":1600154235846,"rawData":"*****=","lambdaArn":"arn:aws:lambda:ap-southeast-2:573188294151:function:snowplow-json-transformer-lambda:$LATEST"}

If i dont use lambda, log is created in S3 Good Enriched Bucket for page view event, but at the same time, log is created in S3 bad Enriched Bucket for the same page view event saying
{"schema":"iglu:com.snowplowanalytics.snowplow.badrows/collector_payload_format_violation/jsonschema/1-0-0","data":{"processor":{"artifact":"snowplow-stream-enrich","version":"1.0.0"},"failure":{"timestamp":"2020-09-15T07:16:02.488Z","loader":"thrift","message":{"error":"error deserializing raw event: Cannot read. Remote side has closed. Tried to read 2 bytes, but only got 1 bytes. (This is often indicative of an internal error on the server side. Please check your server logs.)"}},"payload":"****="}}

I have followed the documentation repeatedly but i am confused in the setup for stream enrich. What i did not understand is that , do we need to setup database for stream enrich if we are not using custom schema ? Because since i am trying to test with Page View event from Javascript Tracker, I have not setup any database. But i have provided access for DynamoDb create, edit for IAM role.
Please help me to setup snowplow if anyone has done before. Please :(

A: I had written a blog on how to setup Snowplow Analytics in AWS.
Here is the link, hope this helps you.


text:
Q: Convert float to int implicit vs explicit (cast) discrepancy int i1 = 0, i2 = 0;
float f = 2.8f;
i1 += f;
i2 += (int)f;
f += 0.1;
i1 += f;
i2 += (int)f;
f += 0.1;
i1 += f;
i2 += (int)f;
printf("%d %d\n", i1, i2);

Output:
7 6

*

*Why would implicit and explicit conversion results be different?

*I would like results to be like the ones for implicit conversion, but without compilation warning. Is it possible?

Platform is Windows7, VS2010 or 2013.

A: Here is the more detailed break down of the situation, in the form of compiler generated code and values of variables (i1, i2 an f) after line-by-line execution.
1.  int i1 = 0, i2 = 0;
2.  float f = 2.8f;
3.  i1 += f;            //i1 = (int)((float) i1 + f);  | i1 => 2,   i2 => 0,   f => 2.8
4.  i2 += (int) f;      //i2 = i2 + (int) f;           | i1 => 2,   i2 => 2,   f => 2.8
5.  f += 0.1;           //                             | i1 => 2,   i2 => 2,   f => 2.9
6.  i1 += f;            //i1 = (int)((float) i1 + f);  | i1 => 4,   i2 => 2,   f => 2.9
7.  i2 += (int) f;      //i2 = i2 + (int) f;           | i1 => 4,   i2 => 4,   f => 2.9
8.  f += 0.1;           //                             | i1 => 4,   i2 => 4,   f => 3.0
9.  i1 += f;            //i1 = (int)((float) i1 + f);  | i1 => 7,   i2 => 4,   f => 3.0
10. i2 += (int) f;      //i2 = i2 + (int) f;           | i1 => 7,   i2 => 6,   f => 3.0
11. printf("%d %d", i1, i2);

Notice lines 3, 6 and 9, here i1 is converted to float due to type promotion (I would recommend you to read this wiki), and then the result is converted back to integer to assign to integer L-value.
Line 5 and 8 would prompt this warning, which could be easily fixed by converting 'f += 0.1;' to 'f += 0.1f;'

warning C4305: '+=' : truncation from 'double' to 'float'

A: Because your explicit conversions are done before the addition (float f to int).
The implicit conversions are:

*

*Conversion of i1 to float.

*Conversion of result to int after addition.

A: To analyse this, the first job is to rewrite a += b as a = a + b.
i + (int)f will be computed in integer arithmetic due to the explicit cast.
But i + f will be computed in floating point arithmetic due to type promotion.
So the expressions have different types. Due to the way floating point works, the result, when converted back to an int could differ.
The moral of the story is to not use += for mixed types, and to not ignore helpful compiler warnings.


text:
Q: Have Error while try to Update Ember 2.14.2 to Ember 2.18.2 Anyone please help me with Ember update.My current code base was 2.14.2 and I try to update 2.18.2.And I got the below error.
Could not start watchman
Visit https://ember-cli.com/user-guide/#watchman for more info.
Cannot find module
'/sampleApp/bower_components/ember/ember-template-compiler.js'

Anyone, please guide me with this. If you have another method to upgrade the version of ember please let me know or please help to solve the issue.
Update
Full stack track:
Log File Source
`ENV Summary:
ERROR Summary:
- broccoliBuilderErrorStack: [undefined]
- code: MODULE_NOT_FOUND
- codeFrame: [undefined]
- errorMessage: Cannot find module
'/Users/mariselvan/Documents/sampleApp/bower_components/ember/ember-
template-compiler.js'
- errorType: [undefined]
- location:
- column: [undefined]
- file: [undefined]
 - line: [undefined]
- message: Cannot find module
'/Users/mariselvan/Documents/sampleApp/bower_components/ember/ember-
 template-compiler.js'
 - name: Error
 - nodeAnnotation: [undefined]
 - nodeName: [undefined]
 - originalErrorMessage: [undefined]
 - stack: Error: Cannot find module
'/Users/mariselvan/Documents/sampleApp/bower_components/ember/ember-
template-compiler.js'
  at Function.Module._resolveFilename
 (internal/modules/cjs/loader.js:580:15)
at Function.Module._load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Class.htmlbarsOptions (/Users/mariselvan/Documents/sampleApp/node_modules/ember-inplace-edit/node_modules/ember-cli-htmlbars/ember-addon-main.js:78:25)
at Object.toTree (/Users/mariselvan/Documents/sampleApp/node_modules/ember-inplace-edit/node_modules/ember-cli-htmlbars/ember-addon-main.js:31:36)
at /Users/mariselvan/Documents/sampleApp/node_modules/ember-cli-preprocess-registry/preprocessors.js:180:26
at Array.forEach (<anonymous>)
at processPlugins (/Users/mariselvan/Documents/sampleApp/node_modules/ember-cli-preprocess-registry/preprocessors.js:178:11)
at module.exports.preprocessTemplates (/Users/mariselvan/Documents/sampleApp/node_modules/ember-cli-preprocess-registry/preprocessors.js:161:10)

=================================================================================

Ember-Cli version of the project :
ember-cli: 2.14.2
node: 10.13.0
os: darwin x64

Thanks in advance.

A: I remember experiencing something like this around the late 2.x of ember. Basically, ember switched from bower to npm around 2.11 or so.
Are you using the ember-source npm version of ember? Your template compiler lookup is searching within bower which is most likely wrong if you've properly made the switch to npm, which you should have!
There's this issue that was fixed which may be the cause for you. Often times, updating the ember
version alone isn't enough. For me, it was always easiest to update to the ember-cli version whose blueprint installed the version of ember that you are wanting (which will help you know what other core dependencies need updating). Looking through old release notes helps here.
If you are using an old ember-cli-htmlbars-inline-precompiler, you need to upgrade to:
 "ember-cli-htmlbars-inline-precompile": "^0.3.6"

If it's not either of those, please update your question with the full stack trace and the ember-cli version
EDIT: I'd like to help enable you to solve this issue yourself in the future so here's the detailed breakdown of how I reach my conclusion. In your stack trace, we see:
/Users/mariselvan/Documents/sampleApp/bower_components/ember/ember-
template-compiler.js

This is looking for ember in bower which is no longer the case since you have ember-source in your package.json. This error results from
at Class.htmlbarsOptions (/Users/mariselvan/Documents/sampleApp/node_modules/ember-inplace-edit/node_modules/ember-cli-htmlbars/ember-addon-main.js:78:25)

So the conclusion here is that the version of ember-inplace-edit is old and you need to upgrade or fix yourself. Look at this addon's package.json and it's got this fixed dependency:
"dependencies": {
    "ember-cli-babel": "^5.1.3",
    "ember-cli-htmlbars": "0.7.9" // this was released Jun 12, 2015
}

For the record, my ember 2.18 app bundled "ember-cli-htmlbars": "^2.0.1" by default. So lets go to the release of 0.7.9, download the source code, and look at the offending line in :
templateCompilerPath: function() {
    var config = this.projectConfig();
    var templateCompilerPath = config['ember-cli-htmlbars'] && config['ember-cli-htmlbars'].templateCompilerPath;

    if (!templateCompilerPath) {
      // THIS ONLY WORKS FOR BOWER VERSIONS OF EMBER
      templateCompilerPath = this.project.bowerDirectory + '/ember/ember-template-compiler';
    }

    return path.resolve(this.project.root, templateCompilerPath);
  }

So you have a couple of reasonable options

*

*Fix the addon and make it support later Ember versions and open a PR to get merged upstream (by updating this ember cli htmlbars dependency)

*Fork the addon and fix it without merging upstream and point to your fork

*Remove the addon and rework this part of your application

*use the templateCompilerPath option to point to your ember-source version (but this is honestly the worst option)


text:
Q: Why should we wrap our templates inside script blocks? Background
All the JS template engines recommend putting your template text inside script blocks like so:

but many developers (understandably) dislike this because they lose HTML syntax highlighting in their code editor inside the script block. I've seen the workarounds like this: Keep correct HTML syntax highlighting in


text:
Q: Google Maps View Inflate Exception I am trying to implement a simple Map with a Marker which is giving me this error
android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class fragment
I have crosschecked Gradle,Java & XML.
Heres by code:
Logcat:
 E/AndroidRuntime: FATAL EXCEPTION: main
                                               Process:  com.propelit.actionapps.propelit_rev1, PID: 22070
                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.propelit.actionapps.propelit_rev1/com.propelit.actionapps.propelit_rev1.HomeActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class fragment
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2449)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)
                                                   at android.app.ActivityThread.access$1000(ActivityThread.java:153)
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                   at android.os.Looper.loop(Looper.java:154)
                                                   at android.app.ActivityThread.main(ActivityThread.java:5524)
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:740)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:630)
                                                Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class fragment
                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:543)
                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                   at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                   at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                   at com.propelit.actionapps.propelit_rev1.HomeActivity.onCreate(HomeActivity.java:19)
                                                   at android.app.Activity.performCreate(Activity.java:6303)
                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2402)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)
                                                   at android.app.ActivityThread.access$1000(ActivityThread.java:153)
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                   at android.os.Looper.loop(Looper.java:154)
                                                   at android.app.ActivityThread.main(ActivityThread.java:5524)
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:740)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:630)
                                                Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class fragment
                                                   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:786)
                                                   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:708)
                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:496)
                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                   at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                   at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                   at com.propelit.actionapps.propelit_rev1.HomeActivity.onCreate(HomeActivity.java:19)
                                                   at android.app.Activity.performCreate(Activity.java:6303)
                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2402)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)
                                                   at android.app.ActivityThread.access$1000(ActivityThread.java:153)
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                   at android.os.Looper.loop(Looper.java:154)
                                                   at android.app.ActivityThread.main(ActivityThread.java:5524)
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:740)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:630)
                                                Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class com.propelit.actionapps.propelit_rev1.HomeActivity that is not a Fragment
                                                   at android.app.Fragment.instantiate(Fragment.java:608)
                                                   at android.app.Fragment.instantiate(Fragment.java:584)

Java :
public class HomeActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        // Get the SupportMapFragment and request notification
        // when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        // Add a marker in Sydney, Australia,
        // and move the map's camera to the same location.
        LatLng sydney = new LatLng(-33.852, 151.211);
        googleMap.addMarker(new MarkerOptions().position(sydney)
                .title("Marker in Sydney"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

Gradle :
android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.propelit.actionapps.propelit_rev1"
        minSdkVersion 20
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.4.0'
    compile 'com.android.support:design:25.4.0'
    compile 'com.google.android.gms:play-services:9.8.0'
    compile 'com.google.maps.android:android-maps-utils:0.5+'
    compile 'com.github.florent37:materialtextfield:1.0.7'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

XML:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.propelit.actionapps.propelit_rev1.HomeActivity" />

A: Try this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.propelit.actionapps.propelit_rev1.HomeActivity">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       />
</LinearLayout>


text:
Q: Mocking datetime: isinstance() fails Mocking datetime does not work this way:
import mock
import datetime

with mock.patch('datetime.datetime', mock.Mock(wraps=datetime.datetime)) as datetime_mock:
    datetime_mock.now.return_value = datetime.datetime(1968, 8, 17)
    assert isinstance(datetime.datetime(2010, 1, 1), datetime.datetime)

Exception:
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

Has someone a solution to make the isinstance() call work for the mocked object?
Update
The isinstance() call does not happen in my code space. It happens in an external library. Answers like "don't use isinstance()" won't help.
Update 2
Python 2.7 and mock==1.0.1


text:
Q: cordova geolocation (3.0.0) does not ask for GPS permission I build an app using Cordova and Geolocation plugin, version 3.0.0. The plugin seems to be installed without error.
I build the .apk and install it in a device. The message I get is:
Do you want to install this application? It does not require any special access.

When I run the application for the first time, this pop-up appears:
Allow app to access this device's location?

It's been a while since I had my last build using a previous Geolocation plugin (I think, version 2.4.3), but I remember that it said during installation that it required GPS access, without asking for permission when running the app. During installation, it was asking for GPS permission with a message like:
Do you want to install this application? It will get access to:

access to precise location (GPS and network-based)

Now, plugin seems more like a web-API (HTML5) geolocation instead of a native GPS plugin. In addition, cordova won't let me use a previous version because of cordova-plugin compatibility issues.
My question is:
Is there a problem with the plugin installation? Or is it really the new geolocation version like this, asking for permission during runtime like HTML5 geolocation does?


text:
Q: How to tell which application prevent computer from sleeping My XPS 13 9360 is set to sleep after 3 minutes of inactivity. However, sometimes it does not follow the 3 minutes and stays awake all the time.
How do I catch the offending app/s that prevent it from going to sleep?
On the flipside, how do I also make sure that it does NOT go to sleep when told by the application (such as QBitTorrent or Adobe Media Encoder)? It doesn't always obey the app instructions too, so this is quite frustrating for me.
Thanks in advance for your help!

A: If you run the cmd with admin privileges, and run the command powercfg -requests, it will show you anything that is keeping your computer awake.


text:
Q: Stopping a threadpool on satisfied condition I'm using the ExecutorService to process thousands of small independent tasks. Each task, on completion, stores the result (which is either true of false).
So, instead of processing all of the tasks, I want to shutdown the threadpool prematurely, if a task has found the answer!
It feels like I'm missing something very obvious here...

A: Consider using the invokeAny method.  It returns when just one is done.
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#invokeAny(java.util.Collection)

A: The desire you express reminds me of a Klein bottle, where there's little distinction maintained between what's "inside" and what's "outside." Here, the tasks submitted to the ExecutorService need to know that they must notify a latching gate outside the thread pool and shut it down when first transitioning from having seen no true task outcomes to having seen at least one.
I won't write the code for you, but I'll sketch the solution. It may help to define an interface on which the tasks must call when they complete:
interface TaskObserver
{
  void completed(boolean result);
}

Each task instance can be constructed with a reference to such a TaskObserver, on which the task body will call just before it completes and yields control back to the invoking ExecutorService. You could even write a base class to assist in participating in this protocol:
public abstract class ObservableTask implements Callable<Boolean>
{
  protected ObservableTask(TaskObserver observer)
  {
    if (null == observer)
      throw NullPointerException();
    observer_ = observer;
  }

  public final Boolean call()
  {
    final boolean result = evaluate();
    observer_.completed(result);
    return result;
  }

  protected abstract boolean evaluate();

  private final TaskObserver observer_;
}

Alternately, instead of using extension to define tasks, you could write a concrete class like this that accepts a reference to a Callable<Boolean> in its constructor in addition to the TaskObserver reference, and works through delegation instead.
Moving on, the implementation of TaskObserver will store an AtomicBoolean, which must be set to false initially. The body of the completed(boolean) method must attempt to set the AtomicBoolean from false to true if the result passed to completed(boolean) is true. If the transition from false to true is successful, shut down the ExecutorService and stop submitting any more tasks; any subsequent calls calls to the TaskObserver will come from tasks that had already been submitted and were too far along to comply with a cancellation request.
public void complete(boolean result)
{
  if (result &&
      latch_.compareAndSet(false, true))
  {
    // Set a flag to cease submitting new tasks.
    service_.shutdownNow();
    if (!service_.awaitTermination(timeoutMagnitude, timeoutUnit))
    {
      // Report a problem in shutting down the pool in a timely manner.
    }
  }
}

If that's not enough of a push to get you started, please follow up with additional questions.


text:
Q: Error in LDA(cdes, k = K, method = "Gibbs", control = list(verbose = 25L, : Each row of the input matrix needs to contain at least one non-zero entry I have a big dataset of almost 90 columns and about 200k observations. One of the column contains descriptions, so it's only text. However, i have like 100 descriptions that are NAs.
I tried the code of Pablo Barbera from GitHub concerning Topic Models because i need it.
OUTPUT
library(topicmodels)
library(quanteda)

des <- subset(finalMSI, !is.na(description), select=c(description))
corpus_des <- corpus(des$description)
df_des <- dfm(corpus_des, remove=stopwords("spanish"), verbose=TRUE,
              remove_punct=TRUE, remove_numbers=TRUE)
cdes <- dfm_trim(df_des, min_docfreq = 2)

# estimate LDA with K topics
K <- 20
lda <- LDA(cdes, k = K, method = "Gibbs",
           control = list(verbose=25L, seed = 123, burnin = 100, iter = 500))

Error in LDA(cdes, k = K, method = "Gibbs", control = list(verbose = 25L,  : Each row of the input matrix needs to contain at least one non-zero entry

As i don't have any NA in my subset, i don't understand this error message (it's my first time using this package)

A: It looks like some of your documents are empty, in the sense that they contain no counts of any feature.
You can remove them with:
cdes <- dfm_trim(df_des, min_docfreq = 2) %>%
   dfm_subset(ntoken(cdes) > 0)


text:
Q: How to speed up PHP powered websites? Many people are talking about somethings like accelerator, opcode, etc to speed up a website's performance. To be honest I do not know how to make any PHP website perform well and when do I need to use such things and what if I use them will that cost me a lot? I generally like websites to perform well with excellent and quick load time for the user (I know the load time has other factors such as the internet speed but what I care about here is the performance of the PHP code itself how to make it perform better).
So, could you tell me about all the ways to speed up any PHP website and whether they are possible and easy to implement or not?

A: You need to know what is slowing down the site most before you can effectively 'speed-up' a website.
Do some profiling and determine exactly where your biggest bottle necks are first and pick of the most effective low-lying fruit until you get your desired performance. Remember, you will experience the effects of diminishing returns, so you will have to find the point of maximum value for the particular case in hand.
Typical areas you will have are as indicated by @guiman in his answer.
I would also add in:

*

*Hardware limitations

*

*Are you being memory bound

*CPU bound?

*Waiting on the disk?

*If any of the above, is the DB being run on a separate machine?

*Network limitations

*

*What is the utilization on the connect to the web server?

*What is the latency like?

*Potential to utilize a CDN to move traffic elsewhere?

A: If you think about performance, first thing come to mind is Cache, also i have read that its possible to compile php code, so that could be another way to go.
But if you think PHP as a web application that involves Sql queries and lots of javascripts executing, you should start worring about how much time does any browser uses to load and execute each javascript and how much optimized your Sql queries are.
So my priorities to build faster PHP web applications would be:

*

*Sql queries

*Javascripts execution (ajax could be a real pain in the processor :P )

*Caching
3.1 Object Cache if you are implementing some kind of OOP
3.2 Page Cache

*Code optimization (algorithms, data structures and related stuff)

A: you can try using Zend Server and/or Squid.
Zend Server provides many other features like your php configuration setting, page caching and also optimizing your PHP codes. while Squid provide provide caching which will reduce bandwidth and deliver pages quickly (taken from the cache instead of requesting the server to run the page again)

A: I mainly find perfomance issues in this two no so reviewed things :

*

*Page speed, to check for this use YSlow (firefox addon) or the online google page speed check :

*lack of PHP accelerator (Here I would suggest APC PHP acceletator)

Well then check the other things that guiman said! (sql queries,etc...)


text:
Q: onchange insert value into hidden input jquery When i select some data from my option i need the value to be showed when "onchange" the select... can someone help me ?
<select name="search_school" id="search_school" onchange="$('#search_school').val() = $('#school_name').val()">

I want the selected option value to be showed in the hidden input
<input type="hidden" name="school_name" id="school_name" value="" />

A: I think you want this as your onchange event:
<select name="search_school" id="search_school" onchange="$('#school_name').val($('#search_school').val())">

When you call val() without a parameter, it fetches the value of the element.  If you call it with a parameter like val('some value');, it sets the value of the element.

A: If you can, avoid inline event definition on html:
<select name="search_school" id="search_school">
...
</select>
<input type="hidden" name="school_name" id="school_name" />

$(document).ready(function () {
    $('#search_school').change(function () {
        $('#school_name').val($(this).val());
    });
});

A: You want something like this, I think:
$("#search_school").change(function(){
  $(this).val($("#search_school option:selected").text());
});

A: To set the selected value to your hidden control you should :
<select name="search_school" id="search_school"  onchange="$('#school_name').val($('#search_school').val())">

A: <script type="text/javascript">
    $(document).ready(function() {
        $("#search_school").change(
            function () {
                $('#school_name').attr('value', $("#search_school").val());
            }
        );
    });
</script>


text:
Q: Efficient way of avoiding adding duplicate entries to Django model I've read quite a few posts on how to make a Database/Model unique in Django and it all seems to work. However, I do not see any posts discussing an efficient way of avoiding adding duplicate entries to a database.
My model looks like this:
# from app.models
class TestModel(models.Model):
    text = models.TextField(unique=True, null=True)
    fixed_field = models.TextField()

The way I currently avoid adding duplicate entries without getting an error is as follows.
# from app.views
posts = ["one", "two", "three"]
fixed_field = "test"

for post in posts:
    try:
        TestModel(text=post, fixed_field = fixed_field).save()
    except IntegrityError:
        pass

If I would not do this I would get an IntegrityError. Is there any way I could make this more efficient?

A: If you are adding items in bulk, you can try to prevent adding these items in the first place, by fetching the texts that need to be unique, and then thus make a list of TestModels that introduce no duplicates:
used_text = set(TestModel.objects.values_list('text', flat=True))

posts = ['one', 'two', 'three']
fixed_field = "test"

test_models = []
for post in posts:
    if post not in used_text:
        used_text.add(post)
        test_models.add(TestModel(text=post, fixed_field = fixed_field))

test_models.objects.bulk_create(test_models)
The .bulk_create(..) [Django-doc] then creates all records in bulk, normally in one query. If the number of elements is huge in multiple queries, but each query will insert a large number of records.
Due to race conditions however, the above can still fail, since between fetching the texts in the database, and adding new ones, other queries can update the state of the database, so although not that likely, you probably should work with a retry-mechanism that filters out TestModels from the list again, and tries to re-insert these.


text:
Q: If $ g \circ f$ is real analytic and $g$ is a real analytic immersion, then $f$ is real analytic Let $M$ $N$ $P$ be complex manifolds, and let $$f: M\rightarrow N, g: N\rightarrow P$$
be $C^\infty$ maps with $g$ and $g\circ f$ holomorphic, and with $dg$ never degenerate. It's easy, then, to see that $f$ is holomorphic:
$f$ is holomorphic iff $df$ commutes with "multiplication-by-$i$", which I'll call $m$. We have
$$dg \circ df \circ m= m \circ dg \circ df = dg \circ m \circ df $$   Where the first inequality is due to $g\circ f$ holomorphic, and the second inequality to $g$ holomorphic. Since $dg$ is injective, we can cancel it in the equality to get that $df$ commutes with $m$.
This argument is given in Knapp's Lie Groups: Beyond an Introduction as a step toward proving the exponential map of a complex Lie group is holomorphic (using Ado's theorem to reduce to the case where the group is inside $GL(n, \mathbb{C})$). Toward proving that any $C^\infty$ Lie group admits a real analytic structure, Knapp cites the analogous result for real analytic manifolds, i.e. the result gotten from the statement above by replacing "complex manifold" with "real analytic manifold" and "holomorphic" with "real analytic".  However all he says is that "the analogous result is valid." I'm unable to fill in the proof.
I should mention that Knapp's definition of a real analytic function $f: \mathbb{R}^m \rightarrow \mathbb{R}^n$ $ (U \subset \mathbb{R}^m )$ is that f extends  to a holomorphic function on some open set of $\mathbb{C}^m$ around any point in U.

A: There is no difference between Knapp's definition and usual definition. Real analytic functions are all obtained in this way. In local sense, we can just consider real analytic maps between regions on $\mathbb{R}^n$.
Suppose $f : U \to V$ and $g: V \to W$ are real analytic. Naturally we just have to extend $g \circ f$ and $g$ to $H$ and $G$ as holomorphic functions from some domains in $\mathbb{C}^n$. Set $F = G^{-1} \circ H$ to be a holomorphic function. Here $dG$ to be non-degenerate since $dg$ is non-degenerate and $G$ is holomorhic.
Finally, $F$ restricts back to a real analytic function on $U$. This function is $f$.


text:
Q: Go math operations with different results (I hope) this is not a question about the accuracy of floating point math in Go. Below I have a test function with 2 expressions that I think should produce equal results, but given the inputs, produce different output.
Edit This ended up being just about floating point precision.
Playground Source
package main

import "fmt"

func main() {
    fmt.Println(test(10.0, 0.1, 1.0)) // 0.2
    fmt.Println(test(10.0, 0.2, 1.0)) // 0.3
    fmt.Println(test(10.0, 0.3, 1.0)) // 0.4
    fmt.Println(test(10.0, 0.4, 1.0)) // 0.5
    fmt.Println(test(10.0, 0.5, 1.0)) // 0.6
}

func test(plays float64, rate float64, value float64) float64 {
    // return (value/plays) + rate
    return (plays*rate + value) / plays
}

The first expression (value/plays) + rate prints:
0.2
0.30000000000000004
0.4
0.5
0.6

while the second expression (plays*rate + value) / plays prints the expected output:
0.2
0.3
0.4
0.5
0.6

Why is this?

A: Since floating point arithmetic is involved, the results for the two expressions will not be the same, even when the input is the same. They may appear to be the same once rounded off to a smaller number of precision positions.
The reason one of the outputs shows 17 digits after the decimal, while the remaining show only 1, is probably because you are hitting a boundary condition with the 3.0000.... result for the way Println rounds off the floating point values while formating output. To demonstrate the boundary condition, consider the following code:
package main

import "fmt"

func main() {
    fmt.Println(0.30000000000000000)
    fmt.Println(0.30000000000000001)
    fmt.Println(0.30000000000000002)
    fmt.Println(0.30000000000000003)
    fmt.Println(0.30000000000000004)
    fmt.Println(0.30000000000000005)
    fmt.Println(0.30000000000000006)
    fmt.Println(0.30000000000000007)
    fmt.Println(0.30000000000000008)
}

The output is:
0.3
0.3
0.30000000000000004
0.30000000000000004
0.30000000000000004
0.30000000000000004
0.30000000000000004
0.30000000000000004
0.3000000000000001

The results of the first two values are truncated and hence the output shows precision of 1 while the other values are rounded off but the precision is much greater. I did not look into the source code of fmt package but this seems to be a result of the way Println truncates floating point values.
Changing the playground code in the question above to use Printf with a large value for precision gives an idea about what the results actually look like. Here's the modified code in the Go Playground


text:
Q: Proving that $[0,1] \times X \cong [0,1] \times Y$, where $X$ is Möbius strip, $Y$ is curved surface of cylinder, and $\cong$ denotes homeomorphic I want to prove that $[0,1] \times X \cong [0,1] \times Y$ where $[0,1] \subset \mathbb R$ has the usual Euclidean topology, $X$ is a Möbius strip and $Y$ is the curved surface of a cylinder. Here, $\cong$ denotes that there exists a homeomorphism between the two spaces.
I know how to express $X$ and $Y$ as quotient spaces of $[0,1] \times [0,1]$ but I'm stuck on what to do next.

A: From the comments above.

Orientability is preserved under homeomorphisms and it is a general fact that if $X$ is non-orientable and $Y$ and $Z$ are orientable, then $Z \times X$ is non-orientable and $Z \times Y$ is orientable. In your case, we have $Z = [0,1]$, $X = $ Möbius strip and $Y = $ curved surface of cylinder. So,
$$
[0,1] \times X \not\cong [0,1] \times Y.
$$


text:
Q: Schur's theorem in DoCarmo's "Riemannian Geometry" The exercise 8 of chapter 4 of Do Carmo's "Riemannian Geometry" ask to prove the Schur's Theorem. I don't understand a step in the hint (the "hint" is essentially the proof of the theorem).
Schur's Theorem: Let $M^n$ be a connected Riemannian manifold with $n\ge3$. Suppose $M$ is isotropic, i.e. for each point $p \in M$ the sectional curvature $K(p, \sigma)$ does not depend on $\sigma \subset T_pM$. Prove that $M$ has constant sectional curvature, i.e. $K(p, \sigma)$ also doesn't depend on $p$.
Here is the beginning of the hint provided by the book.
Define a tensor $R'$ of order $4$ by
$$
R'(W,Z,X,Y) = \langle W, X \rangle \langle Z, Y \rangle - \langle Z, X \rangle \langle W, Y \rangle.
$$
If $K(p, \sigma) = K$ does not depend on $\sigma$, we know (thanks to a previous lemma) that $R = KR'$, where $R$ is the curvature tensor of $M$. Then the book says: Therefore, for every smooth vector field $U$, $\nabla_UR = (UK)R' $. I can't understand this passage. Shouldn't be $\nabla_UR = (UK)R' + K(U(R'))$?

A: That's because the metric itself is nabla-flat, so by Leibniz rule you get what you want.

A: I don't quite understand why the fact that the metric is nabla flat gives the answer.
What I saw is that, starting off from the definition of the covariant differential, if we expand the 2nd term we obtain
$$R(\nabla_U W,Z,X,Y)
= K(p)R'(\nabla_U W,Z,X,Y)
= K(p)\big(\langle \nabla_U W, X \rangle \langle Z,Y \rangle - \langle Z,X \rangle \langle \nabla_U W, Y \rangle\big),$$
and if we expand the first term of $K(p)U\big(R'(W,Z,X,Y)\big)$ we obtain
$$K(p)U\big(\langle W,X \rangle\big) \langle Z,Y \rangle
= K(p)\big(\langle \nabla_U W, X \rangle + \langle W, \nabla_U X \rangle\big) \langle Z,Y \rangle,$$
and thus we will get that all of those terms cancel each other, i.e.
$$\nabla_U R(W,Z,X,Y) = \nabla R(W,Z,X,Y,U) = U(K)R'(W,Z,X,Y).$$


text:
Q: Function is not defined for 'cell' inputs. - MATLAB error I have a problem with MATLAB that i cant quite fix. It is throwing me an error, stating
??? Error using ==> fprintf
Function is not defined for 'cell' inputs.

Error in ==> writedata at 93
           fprintf(fout, 'INSERT INTO postgres VALUES( %s, %s, %s.\n )', domain, start, stop);

@Florian Brucker wrote me this code and i changed the code to run 2 regular expressions instead of one, since the one regular expression seems to copy over both of the strings in the document into one cell array when its supposed to be in two separate cell arrays.
domain = '';
start = '';
stop = '';
fin = fopen('CathDomainDescriptionFile.txt', 'r');
fout = fopen('output_cath.txt', 'w');
% TODO: Add error check!
while true
    line = fgetl(fin); % Get the next line from the file
    if ~ischar(line)
        % End of file
        break;
    end
    [key, value] = strtok(line); % Split line at the first space
    switch key
        case 'DOMAIN'
           % Store domain
           domain = value;

        case 'SRANGE'

% two regular expressions since the doing it all in one throws an error
% Index exceeds matrix dimensions.

           m = regexp(value, 'START=(\d+)', 'tokens');
           m2 = regexp(value, 'STOP=(\d+)', 'tokens');

           start = m;
           stop = m2;

           % Print result
           fprintf(fout, 'INSERT INTO postgres VALUES( %s, %s, %s.\n )', domain, start, stop);
    end
end
fclose(fin);
fclose(fout);

It seems to print out the results for the DOMAIN, but not for the START and STOP values, due to the error. It should just simply, print out the Domain number, START and STOP values inside of the fprintf statement.
I am a beginner to MATLAB.

A: You should have a look at the return type of regexp.
In your call to fprintf you state that the input is an integer. This contradicts with the output of the regexp function called above.


text:
Q: What is replacement of fields.Method in flask-marshmallow? I am writing a REST API using python-flask.
I want to do some process on fetched fields before serializing them. So I guess the best solution is fields.Method but it seems fields.Method is removed from marshmallow since 3.0 version. What is the replacement of it in marshmallow schema?

A: Use pre/post processing, docs here:
https://marshmallow.readthedocs.io/en/stable/extending.html#pre-processing-and-post-processing-methods


text:
Q: Encryption with PBEWithHmacSHA256AndAES_128 in java I use PBEWithHmacSHA256AndAES_128 in java for encryption and my question is about the algorithm internals.
I understand the roles of PBE, Hmac, and aes in encryption process.
My question is: does the Hmac digest the plaintext and then gets appended to the plaintext and get encrypted by aes (as in SSL)? because the result is always a multiple of aes 16 bytes (if i encrypt only 1 character i get 16 bytes as the final result) but Hmac is 32 bytes.
When i read about Hmac i found that the most used way is to digest the ciphertext and append the result to the ciphertext and save it, but it seems not the case in PBEWithHmacSHA256AndAES_128.
I am asking this because i don't want to save the password and rely on Hmac's result to check for password's validity, and also to understand better the algorithm.
(I sometimes calculate Hmac separately again by using PBKDF2WithHmacSHA1 with different salt and count for secret key generation and append the result to the final ciphertext for more security.)


text:
Q: compiler doesn't know my include file I'm compiling my project using g++ and a jamroot file (jamroot.jam). I don't know why it doesn't know my files even it include the right directory.
Here is the output:
"g++"  -ftemplate-depth-128 -O0 -fno-inline -Wall -g -fPIC  -DLINUX  \
  -I"/home/oumaya/docs/UT_Cpp_Test/main/inc" \
  -I"/home/oumaya/docs/UT_Cpp_Test/main/inc/include/cppunit" \
  -I"/home/oumaya/docs/UT_Cpp_Test/main/inc/include/cppunit/ui/qt" \
  -I"/usr/share/boost" -c -o "bin/build/gcc-4.6/debug/src/main.o" "src/main.cpp"

In file included from src/main.cpp:6:0:
/home/oumaya/docs/UT_Cpp_Test/main/inc/UT_Instrument_Test.hpp:7:45: fatal error:
  cppunit/extensions/HelperMacros.h :  No such file or directory

A: You are missing one :
-I/home/oumaya/docs/UT_Cpp_Test/main/inc/include/

The reason is that you include like this :
#include "cppunit/extensions/HelperMacros.h"

and the full path is
/home/oumaya/docs/UT_Cpp_Test/main/inc/include/cppunit/extensions/HelperMacros.h

therefore you should tell the compiled the relative path to cppunit/extensions/HelperMacros.h

A: You are specifying the [...]inc/include/cppunit path for your input files, but refer to the header as cunit/extensions/HelperMacros.h  This means the compiler is expecting path relative to [...]inc/include/cppunit and ends up with [...]inc/include/cppunit/cunit/extensions/HelperMacros.h.  You only need to specify [...]inc/include for the include directories (or change the header path to extensions/HelperMacros.h)

A: Compare:
Your command -
-I"/home/oumaya/docs/UT_Cpp_Test/main/inc/include/cppunit"

The error message:
fatal error: cppunit/extensions/HelperMacros.h : No such file or directory

I.e., the "include root" is expected to be at /home/oumaya/docs/UT_Cpp_Test/main/inc/include, not the "cppunit" subdirectory (which is apparently stated in the #include directive).
Alternatively, your #include statement is wrong, and shouldn't have cppunit/ in front of extensions/HelperMacros.h.

A: It simply can't find the file. You're trying to include cppunit/extensions/HelperMacros.h so go through all the -I include paths in your build output and see if they concatenate together to a valid path to that file. They won't as you're missing a directory.
Next step is to go through the cppunit installation and find your file:
find <cppunit root> -name HelperMacros.h

When you find one which ends with your cppunit/extensions/HelperMacros.h include, strip that bit off the end and use the first part of the path as an extra -I include path on your compile command.

A: When running Ubuntu I found you can simply install the correct stuff with
For cppunit/extensions/HelperMacros.h or cppunit/BriefTestProgressListener.h:
sudo apt-get install libcppunit-dev


text:
Q: How can I visualize features found in an image? I am using Mathematica to explore the face detection feature of Core Image on Mac OS X Lion. To do this I have an Objective-C program which captures images from the iSight camera, runs face detection and logs the coordinates of any detected features, and then saves the image to the clipboard. I then switch to Mathematica and paste the captured image into one variable, and copy-and-paste the logged feature coordinates into another.
I've written a simple Mathematica function that can subsequently produce a "normalized" face image, but it would be helpful to be able to draw graphics on top of an image in order to visualize where features are and how they're oriented. When I naively try this I get the error: "Image is not a graphics primitive or directive."
Is there a simple way to draw (or composite) graphics on top of an image?

A: You can also achieve the same effects with ImageCompose
a = ExampleData[{"AerialImage", "Oakland2"}];
b = Graphics[{Opacity[0.5], Red, Thick, Circle[{200, 200}, 300],
    Circle[{1500, 200}, 200], Circle[{0, 0}, 200]}];

ImageCompose[a, b]

And also with Overlay:
Overlay[{a, b}, Alignment -> {Center}]

Though the co-ordinate system is not consistent between the two.

A: Show can combine Image and Graphics:
a = ExampleData[{"AerialImage", "Oakland2"}];
b = Graphics[{Red, Thick, Circle[{400, 400}, 300]}];
Show[a, b]

In this way you can do it in a programmatic way. But you can also do this manually and interactively via right-click menu access to Drawing Tools:


text:
Q: Intellij 14.1 Distraction free mode has a huge gap on the left side of the screen? I'm really liking intellij's Distraction Free Mode. However when I try it on my machine, there is this big space on the left side of the screen. For some reason, even if I try to scroll to the left, the space is still there. It's like this huge margin on the left and it's eating a significant amount of space. How do I get rid of that? Here's a screen shot of what I have.

If you look at this blog, the space on the left side of the screen is very little. I want it to look like that. How do I do that?

Edit: Ok, somehow I discovered that if I hit ctrl + mouse scroll up, the big margin on the left sort of hides itself, but in the process, the text also becomes larger, which isn't really what I was looking for at the moment. The text is just too large by that point.

A: UPDATE: currently, aka 27 Dec 2015, there's an issue opened on their tracker regarding this feature/bug

The same blog you're indicating, states the following

In addition, the text is center-aligned!

This got me thinking, so I played a bit with the right margin features and, as you can see in the pictures below, the 2 seem related:
1. Right margin at 80 I have it at 120 and I can't recall the default value, but this looks like yours.

2. Right margin at 160

In conclusion, the larger the number, the smaller the right margin, and in addition so to speak, the smaller the left margin.

A: The issue has been updated and a better solution is suggested by Tom Gregory. The solution updates the margin used for the distraction free mode.

For anyone coming to this bug looking for a solution, IntelliJ IDEA now offers a setting under Settings > Advanced Settings > Left margin in distraction free mode. Set it to 0 to achieve the desired result.

A: To get rid of the left gap in WebStorm increase the hard wrap value:
Settings > Editor > Code Style > your language > Wrapping and Braces > Hard Wrap at ...

A: Thank you! Works with IntelliJ 2019.1.1 as well.
CTRL+ALT+S -> code style -> increase hard wraps to > 200


text:
Q: How can I get all children from a parent row in the same table? Let's say I have a table called my_table that looks like this:
id      |  name                    | parent_id
1       |  Row 1                   | NULL
2       |  Row 2                   | NULL
3       |  Row 3                   | 1
4       |  Row 4                   | 1
5       |  Row 5                   | NULL
6       |  Row 6                   | NULL
7       |  Row 7                   | 8
8       |  Row 8                   | NULL
9       |  Row 9                   | 4
10      |  Row 10                  | 4

Basically I want my final array in PHP to look like this:
Array
(
    [0] => Array
        (
            [name] => Row 1
            [children] => Array
                (
                    [0] => Array
                        (
                            [name] => Row 3
                            [children] =>
                        )

                    [1] => Array
                        (
                            [name] => Row 4
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [name] => Row 9
                                            [children] =>
                                        )

                                    [1] => Array
                                        (
                                            [name] => Row 10
                                            [children] =>
                                        )

                                )

                        )

                )

        )

    [1] => Array
        (
            [name] => Row 2
            [children] =>
        )

    [2] => Array
        (
            [name] => Row 5
            [children] =>
        )

    [3] => Array
        (
            [name] => Row 6
            [children] =>
        )

    [4] => Array
        (
            [name] => Row 8
            [children] => Array
                (
                    [0] => Array
                        (
                            [name] => Row 7
                            [children] =>
                        )

                )

        )

)

So, I want it to get all of the rows where parent_id is null, then find all nested children recursively.
Now here's the part that I'm having trouble with:
How can this be done with 1 call to the database?
I'm sure I could do it with a simple select statement and then have PHP make the array look like this but I'm hoping this can be done with some kind of fancy db joining or something like that.

A: I'm not aware of any way to get such an array from a single database call. A mysql SQL query returns a table-like dataset which is always column based. Therefore, the answer is you can't.
However, it is possible to make quite smart tree based queries. A very interesting read about this can be found here.
On other systems than mysql, Common table expressions could achieve what you want.
But still no such array out of the box.

A: No Recursive queries in MySQL, but there's the nested set way of thinking. And the complete reference on it is there: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

A: AFAIK it is not possible. Unless you write some stored procedure to do the job.

A: I don't know MySQL, but in SQL Server (and I believe this is ANSI-SQL) this is done with a CTE (Common Table Expression), which takes this form:
WITH MyCTE
(
  -- Non-recursive anchor query
  UNION ALL
  -- Recursive portion that typically JOINs MyCTE to some other table
)
SELECT * FROM MyCTE;

A: In MySQL you can create stored procedure which will return you what you need. You can look at the simple example for MSSQL http://vyaskn.tripod.com/hierarchies_in_sql_server_databases.htm. But it's easy to make for MySQL too

A: Problem here is that Id's are not stored according to order in which you would traverse your tree. If you fix this problem by building your tree once an then copying all nodes back to the another table assigning Id in accordance to the order in which nodes of the are traversed - next time you will be able to populate your tree by simply scanning forward  results of select statement like
SELECT * FROM my_table ORDER BY Id.
This solution won't work if tree changes often because table will have to be regenerated. That can be solved by incrementing Id's initially by large number (say 1000) so that re-numbering will not be necessary every time because you can assign new node Id from the gap. Using fractions for keys also will work nicely if hight of the tree is small.

A: Simplest way is just to do it in PHP.  I had to do something similar in Symfony, but it should be easy to read and adapt.  Start off with an array from the table rows.
  public function executeGetTree(sfWebRequest $request)
  {
    $rows = Doctrine_Core::getTable('TreeNode')->findAll();
    $treeNodes = $rows->toArray();

    //set up new array to store children for each parent node
    $nodesContainer = array();
    foreach ($treeNodes as $node){
        $parentId = $node['parent_id'];
        //if node has no parent, it is a root node
        $nodesContainer[isset($parentId)? $parentId : 'root'][] = $node;
    }

    $tree = array();
    //recursively get descendents for each root node
    foreach($nodesContainer['root'] as $rootNode)
    {
      $tree[] = $this->getChildren($nodesContainer, array($rootNode));
    }

    print_r($tree);

    return sfView::NONE;
  }

  private function getChildren(&$container, $parentNode){
      $children = array();
      foreach ($parentNode as $node){
          if(isset($container[$node['id']])){
            $node['children'] = $this->getChildren($container, $container[$node['id']]);
          }
          $children[] = $node;
      }
      return $children;
  }

A:
I'm hoping this can be done with some kind of fancy db joining or something like that.

You should consider how impossible that sounds.
Consider just one branch in the tree, from 1 -> 4 -> 9 & 10
How would you visualize the relationship in a single row in the MySql result, or any DBMS.
The only sensible option I can think of for hierarchical result is XML, but you don't want to go there given it can be done much better in PHP on the base record.parent structure rather than parsing XML.

A: Maybe something like this, add levels as appropriate:
SELECT
    d1.*,
    d2.`name` AS '2nd Level',
    d3.`name` AS 'Top Level'
    FROM `my_table` AS d1
    LEFT JOIN `my_table` AS d2 ON d1.parent_id=d2.id
    LEFT JOIN `my_table` AS d3 ON d2.parent_id=d3.id


text:
Q: Compojure/Ring: can't get session working I'm clearly missing something obvious, but:
(ns session-demo.core
  (:gen-class)
  (:use compojure.core
        ring.middleware.session
        [hiccup core page form])
  (:require [compojure.route :as route]
            [compojure.handler :as handler]))

(defn index-page []
    (html5
     [:body
      (form-to [:get "/status"]
               (submit-button "Proceed"))]))

(defn status-page [params]
  (html5
   [:body
    [:p "Session: " (:session params)]
    [:p "Params: " params]]))

(defroutes the-routes
  (GET "/" [] (index-page))
  (GET "/status" {session :session :as params} (status-page params)))

(def app
  (-> (handler/site the-routes)
      wrap-session))

After clicking "Proceed" button shows:
Session: {}

Params: {:ssl-client-cert nil, :remote-addr "127.0.0.1", :scheme :http, :query-params {}, :session {}, :form-params {}, :multipart-params {}, :request-method :get, :query-string nil, :route-params {}, :content-type nil, :cookies {"org.cups.sid" {:value "72d6fc6a299669e6332da6eb72964f97"}}, :uri "/status", :server-name "localhost", :params {}, :headers {"accept-encoding" "gzip, deflate", "user-agent" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0", "referer" "http://localhost:3000/", "connection" "keep-alive", "accept-language" "en-US,en;q=0.5", "accept" "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "host" "localhost:3000", "cookie" "org.cups.sid=72d6fc6a299669e6332da6eb72964f97"}, :content-length nil, :server-port 3000, :character-encoding nil, :body #, :flash nil}

I'd expect something meaningful to be set in (:session params)...

A: The session starts empty. To put something in the session you need to return a map from your handler, and under the key :session you should provide the updated session data.
Something like this maybe:
(defn index-page []
  {:body (html5
          [:body
           (form-to [:get "/status"]
                    (submit-button "Proceed"))])
   :session {:test [1 2 3]}})


text:
Q: MySql trigger fires two times I have trigger:
CREATE TRIGGER catalog_product_entity_decimal_update AFTER UPDATE ON catalog_product_entity_decimal
  FOR EACH ROW
    BEGIN
    -- blah blah blah
    END

Trigger make lot of operations but it doesn't matter :) the real problem is that when I make update from hand by code:
UPDATE `grene2`.`catalog_product_entity_decimal` SET `value`='82.0000' WHERE `entity_id`='276259';

It fires 2 times (I see it by profiling), BUT if I change same field by MySql Workbench it fires only one time. MySql Workbench creates such query:
`UPDATE `grene2`.`catalog_product_entity_decimal` SET `value`='81.0000' WHERE `value_id`='132371'`;

value_id is PRIMARY index, entity_id not probably there is a problem but WHY? And how to fix it?