Fetch in Slim framework not doing what I expect

Question: I am trying to make an API using the slim framework. Based upon a tutorial from the web, I have index.php which calls dbHelper.php. I am simply trying to get a list of all unique languages in a specific table. The query returns 1 result (as I only have one language loaded at present), however fetch returns "true".
public function get_languages(){
    $response=array();

    $stmt = $this->conn->prepare('SELECT language, count(language)AS count FROM vocab GROUP BY language');
    $result=$stmt->execute();
    if($result){
        while($language_instance = $stmt->fetch()){
            array_push($response,$language_instance['language']);
        }
        array_push($response,$stmt);
    }
    $stmt->close();
    return $response;
}

The response array returns
[
        null,
        {
            "affected_rows": null,
            "insert_id": null,
            "num_rows": null,
            "param_count": null,
            "field_count": null,
            "errno": null,
            "error": null,
            "error_list": null,
            "sqlstate": null,
            "id": null
        }
    ]

When executing the query via phpMyAdmin, I get a single line with the correct values, so I assuming I am doing something fundamentally wrong within Slim however Mr. Google has so far been unhelpful.
Any pointers or link to appropriate documentation would be helpful.
Kind regards
Chris H
Answer: It appears that the fetch method is not what it appears, so I adjusted this to as follows and am now getting the results I want.
$result=$this->conn->query('SELECT language FROM vocab GROUP BY language');
while ($language_instance = $result->fetch_array(MYSQLI_ASSOC) ) {
    array_push($response,$language_instance['language']);
}

This does NOT answer my question regarding why fetch() does not return an array, however it solves my problem.


If $A$ is an invertible matrix of order 2, then $|A^*|$ is (where $A^*$ is inverse of matrix $A$)

Question: I am having some formula without proof (u can find it by ur self) $\def\adj{\operatorname{adj}}$
$A^* = 1/|A| \cdot \adj A $
and
$|\adj A| = |A|^{n-1}$ where $n$ is order of matrix
By using these formulae
$$\begin{align}
|A^*| &= 1/|A| \cdot |\adj A|\qquad \text  {as $|A|$ is constant}\\
&= 1/|A| \cdot |A|^{n-1}\\
&= |A|^{n-2}
\end{align}
$$
Now here $n$ is 2
So finally we gotta
$|A^*| = |A|^0 = 1$
But why it is not 1. Plz help me.
Answer: Note when $M$ has order $n$, we have $|kM| = k^n \cdot|M|$, not $k\cdot|M|.$  Therefore,
$$|A^*| = 1/|A|^n \cdot |\text{adj } A| = |A|^{-1}$$

For future reference: OP has used $A^*$ for the inverse of $A$ so I have used this notation.  This should not be confused with the common notation of the conjugate transpose.
Comment: @5Dots You have written  $$\text{|A*| = 1/|A| × |adj A| (as |A| is constant)}$$ My whole point is that this is wrong unless $n=1$.  Therefore, when you ask the only question: "But why it is not 1...... " it's because you misapplied the determinant.
Comment: @5Dots As best I can tell, you're mixing up two formulas.  The following both are true: $$\text{inv}(A) = 1/|A| \cdot \text{adj}(A) \\ |\text{inv}(A)| = 1/|A|^n \cdot |\text{adj}(A)|$$
Comment: Ok thanks i got this, sorry for the trouble man. Appreciates a lot


Understanding rare definition of the likelihood function and corresponding posterior from research paper

Question: Reading the paper https://storage.googleapis.com/pub-tools-public-publication-data/pdf/b20467a5c27b86c08cceed56fc72ceadb875184a.pdf i came across a rare definition of the likelihood function that in my eyes seems misspelled.
Have a look at function 8 and 9, ctrl-f "(8)" or ctr-lf "(9)" in the document.
"Let Φ denote the vector of parameters in the model in (7), X denote all the media variables,
Z denote all the control variables, and y denote the vector of response values. The frequentist
approach finds the most likely value of the parameters by maximizing the likelihood (MLE), as in $\phi_{hat} = \underset{\phi}{\operatorname{argmax}}L(y | X, Z, \phi)$
This goes against the definition known to me, it would make sence however if they substituted the L with an P indicating probability instead of likelihood. Or by substituting $\phi$ with $y$.
Similarly, the definition they use of the posterior seems really strange and has the same error as stated above.
$p(\phi|y, X) \propto L(y|X, Z, \phi)\pi(\phi)$
same case here...
Can someone shed some light onto this?
Comment: google connection removed in question.
Answer: Imho, there is nothing rare there with the likelihood definition or notation except for a minor mistake.
Here is the relevant excerpt from the paper:

Hence there is a clear mistake/typo in using $\mathcal L$ in both (8)$-$where it stands for a log-likelihood$-$and (9)$-$where it stands for a likelihood$-$. Assuming $\mathcal L$ stands for a likelihood  does not modify (8) and removes the double meaning.
Apart from that easily resolved ambiguity between likelihood and log-likelihood, I see no issue with this traditional and basic presentation of MLE and Bayesian approaches. The notation $\mathcal L$ or $L$ is standard for the likelihood function (with $\ell$ sometimes being used for log-likelihoods), even though the order in$$\mathcal L(y|X, Z, \phi)$$is often inverted to$$\mathcal L(\Phi|X, Z, y)$$to stress that the likelihood is a function of the parameter $\Phi$, indexed or parameterised by the observed realisation of $(X, Z, y)$.
There is no trace of a $\text{Pr}(\cdot)$ function in the paper, hence I assume you mean by this the density function of the distribution attached to the data $y$, but (i) this is not a standard notation as $\text{Pr}(\cdot)$ is usually denoting a probability function, which entries are events, not (continuous) random variates and (ii) the authors appear to use $\mathcal L(y|X, Z, \phi)$ as this density, which is mathematically correct.
Comment: excellent answer: accepted.


Why would crontab PHP script execution differ from CLI?

Question: I have a PHP script that begins as follows:
#!/usr/local/bin/php -q
<?php

require_once 'vendor/autoload.php';

//set up google api client

$client = new \Google_Client();

When I execute directly from the command line using:
php /Users/xxxx/app.php

It executes normally. However when I include in crontab in the form:
30 7 * * * php /Users/xxxx/app.php

I get the following error:
Fatal error: Uncaught Error: Class 'Google_Client' not found in
  /Users/xxxx/app.php:8
Stack trace:
#0 {main}
  thrown in /Users/xxxx/app.php on line 8

I haven't used cron much previously - any idea how I might rectify this?
Comment: That's weird, it passes the `require_once`, are you perhaps using `include_once` instead? It should stop there already as the relative path will not exist. You could try something like `cd /Users/xxxx && php app.php`
Comment: That did it! Thank you - I didn't know about '&&'.
Comment: Are these scripts run by the same user?
Comment: I suggest you don't write scripts than depend on working directory to load fixed assets. Why not `require_once __DIR__ . '/vendor/autoload.php';`? That's what they use in the [Basic usage](https://getcomposer.org/doc/01-basic-usage.md#autoloading) chapter of Composer documentation.
Answer: IMO the first thing to do is to use the complete path to the php executable and maybe also try setting the cronjob to run as the same user from when you execute from cli:
From cli run

which php

and insert the path in your cronjob (usually /usr/bin/php):

30 7 * * * YOUR_USER /PATH_TO_EXEC/php /Users/xxxx/app.php


how to solve this exercise with python numpy vectorization?

Question: how to solve this exercise 4.5 on page 2 with python Numpy vectorization?
Link to download:
https://dl.dropbox.com/u/92795325/Python%20Scripting%20for%20Computational%20Scien%20-%20H.P.%20%20Langtangen.pdf
I tried this with Python loop, but I need Vectorization version.
from numpy import *
import time

def fun1(x):
       return 2*x+1

def integ(a,b,n):
       t0 = time.time()
       h = (b-a)/n
       a1 = (h/2)*fun1(a)
       b1 = (h/2)*fun1(b)
       c1 = 0
       for i in range(1,n,1):
              c1 = fun1((a+i*h))+c1
       t1 = time.time()
       return a1+b1+h*c1, t1-t0

Comment: Hi Ardeshir, do you know what it means to "vectorize" the problem?
Comment: You may read the previous pages which helps you understand.
Comment: I understand, I was asking if you did :)  If you do understand, have you tried to implement it?
Comment: I have already understand the "vectorize" in recursions, but I can't find out what I have to do with this exercise. I am beginner in Python and I want to see some more examples of vectorizing. Here is the Recursion I have understood: https://dl.dropbox.com/u/92795325/Recursion%20%26%20Vectorization.py                                                                                The problem is that each argument of the new array must be the sum of the two arguments beside that! (very simple and clear)
Answer: To "vectorize" using numpy, all this means is that instead of doing an explicit loop like,
for i in range(1, n):
    c = c + f(i)

Then instead you should make i into a numpy array, and simply take its sum:
i = np.arange(1,n)
c = i.sum()

And numpy automatically does the vectorization for you.  The reason this is faster is because numpy loops are done in a better optimized way than a plain python loop, for a variety of reasons.  Generally speaking, the longer the loop/array, the better the advantage.  Here is your trapezoidal integration implemented:
import numpy as np

def f1(x):
    return 2*x + 1

# Here's your original function modified just a little bit:
def integ(f,a,b,n):
    h = (b-a)/n
    a1 = (h/2)*f(a)
    b1 = (h/2)*f(b)
    c1 = 0
    for i in range(1,n,1):
        c1 = f((a+i*h))+c1
    return a1 + b1 + h*c1

# Here's the 'vectorized' function:
def vinteg(f, a, b, n):
    h = (b-a) / n
    ab = 0.5 * h * (f(a)+f(b)) #only divide h/2 once

    # use numpy to make `i` a 1d array:
    i = np.arange(1, n)
    # then, passing a numpy array to `f()` means that `f` returns an array
    c = f(a + h*i) # now c is a numpy array

    return ab + c.sum() # ab + np.sum(c) is equivalent

Here I will import what I named tmp.py into an ipython session for easier timing than using time.time:
import trap
f = trap.f1
a = 0
b = 100
n = 1000

timeit trap.integ(f, a, b, n)
#1000 loops, best of 3: 378 us per loop

timeit trap.vinteg(f, a, b, n)
#10000 loops, best of 3: 51.6 us per loop

Wow, seven times faster.
See if it helps much for smaller n
n = 10

timeit trap.integ(f, a, b, n)
#100000 loops, best of 3: 6 us per loop

timeit trap.vinteg(f, a, b, n)
#10000 loops, best of 3: 43.4 us per loop

Nope, much slower for small loops!  What about very large n?
n = 10000

timeit trap.integ(f, a, b, n)
#100 loops, best of 3: 3.69 ms per loop

timeit trap.vinteg(f, a, b, n)
#10000 loops, best of 3: 111 us per loop

Thirty times faster!
Comment: Thanks for your help. I see... But I have some more question if you don't mind. First, is "vectorized version" always more efficient than loops--i.e. should I avoid using loops whenever possible? Second, what is the difference between loops and vectors that makes such big difference? Why there is not such thing in (for example) FORTRAN and C programming?
Comment: @ArdeshirDVD First: Usually faster, but not always.  Also it's also more readable than loops, which can more important. Second: The difference isn't that they're loops, but the way the data is stored and iterated over.  Numpy builtin functions are mainly written and compiled in C which is faster.  They don't exist in Fortran or C because F. and C don't need them:  those are compiled languages, and it's the fact that python is an "interpreted" language that slows down its loops.
Comment: @ArdeshirDVD Since python is interpreted and not compiled, and because its variables are all dynamically typed, each iteration of the loop must check the types of the variable, which is wasteful for a loop over 10000 floats of identical type. See questions like http://stackoverflow.com/a/8097669/1730674 and http://stackoverflow.com/q/3033329/1730674 for a little discussion on why python is so slow running for some things


How can I quickly install FreeBSD ports?

Question: I am a Linux system administrator, so my knowledge of the specifics of FreeBSD are very literal, and not very thorough; I've been configuring packages and what not a for a few days now and every one of them has taken a very long time because I am being prompted for decisions (for various options I cannot select anyway).
Is there any way to bypass/automate this selection process so I can leave this unattended while the building, etc. occurs?
Comment: See Also: http://serverfault.com/questions/159271/use-default-options-when-compiling-ports
Answer: First, you can select any option the system presents you with.
Port maintainers take a great deal of time to make sure that the options presented work (or mark them as broken/experimental).  If you're compiling stuff from ports we generally assume you want these options so you can customize the installation to suit your environment.

To answer your question, you have a few options:
Option 1: Use packages instead of ports.
If you're new to FreeBSD and have no need to customize options this is probably the choice for you. It saves you both the configuration step and the compile time.
Refer to the FreeBSD Handbook for more information on using packages.
Option 2: Use -DBATCH when building ports
make -DBATCH will tell the ports system that you are "batch-builing" ports and won't be hanging around to answer config questions. It will use the default options for any ports that need configuring.
You can also add BATCH=1 to /etc/make.conf to set this permanently.
Option 3: Use make config recursive before you build
This allows you to configure all the ports that need configuring before your build starts.
Note there are a few ports where this doesn't work, so you might still get a few prompts, but it takes care of the majority of them.
For the sake of your sanity, run this only on the ports you intend to build. You could be there for a very long time if you run this at the top level of the tree and try to configure every possible port.

If you configure ports to suit your environment you should copy the contents of /var/db/ports someplace safe when you're done.  The /var/db/ports/*/options files contain the configuration settings you selected, and can be used in the future to avoid having to use the configuration menu system again.


How to make a series of non database methods mimic transactions.

Question: I have several method calls I need to perform that need to be "transactional" but I am unsure how to implement this aside from try/catch/finally.
Background

Application is console based.
Application will have multiple threads
A database is queried for connection information, connection is made to a webservice to login, a session ID is generated and a database is updated.
An operation invokes a logout, which needs to clean up the database, clear the session ID and log out of the webservice

What I'm trying to figure out
I want to make sure that when a logout is requested I want to ensure that the entire process is either all successful, or not at all. For instance I don't want the database to be cleaned up, the session ID cleaned and the logout operation fail (hence the login is still valid).
Ideally the solution would "rollback" on a failure, thereby ensuring the previous state is maintained.
Is there is a slick way to accomplish this, or am I stuck with a series of nested try/catch/finally blocks to do this?
Answer: If you want to implement some rollback method, you must store undo data for all the things you'll need to rollback in case of a failure.

for the DB you already have a rollback method.
for each file you are modifying/deleting in the operation that may need to be rolled-back, you have to keep a backup copy, to allow you to revert to the previous state.
any in-memory variables that may have to be rolled-back should have backup copies.

This will allow you at any point in your code to rollback to a previous state when an error occurs.
Comment: Good answer but I would also clarify the need to consider *deep* copy backups. The rollback feature will get itself into a terrible mess if shallow, mutable references are copied instead. I'd also add (further to comments above) that try/catch/finally is not *inherently* atomic. I've added an example of that amongst the answers.
Comment: that's what I was figuring, essentially the try/catch/finally. Transaction rollback in the database is only good for the database itself, I'll still have to manage all the other states via temp variables.
Comment: Even with DB transactions you need a try/catch/finally block, in order to rollback in the catch and close the connection the the finally. You can reduce the number of such blocks if you throw exceptions in all the places that fail, and catch them at the top level, where you'll call your rollback method. Your finally method can clear all the temp variables/files.
Comment: True. I guess pending any other information I'm going to have to go that route. Ahh well nothing ventured, nothing gained.
Answer: "neat" might mean something like this ?
(http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html)
but i would much prefer KISS constructs like you mentioned...at least until solidly working before implementing with complex language/resource constructs...make it work...then make it more pretty/fast/decoupled/...
Answer: For any casual glancers to this question, don't assume that try/catch blocks are inherritently atomic. They're not:
Code proof:
public class TransactionTest {

    private class Thing {
        public int number = 1;
        public String thingName = "Marge";

    }

    public static void main(String args[]) {
        new TransactionTest();
    }

    public TransactionTest() {
        transactionExperiment();
    }

    private void transactionExperiment() {

        Thing t = new Thing();
        try {
            System.out.println("Original name: " + t.thingName);
            t.thingName = "Homer";
            throw new IllegalArgumentException("Throw exception deliberately");
        }
        catch(IllegalArgumentException e) {
            System.out.println("Caught exception");
        }

        System.out.println("Thing is: " + t.thingName);
    }
}

Output:

Original name: Marge
Caught exception
Thing is: Homer


How to properly configure Play Framework 2.1+ and Nginx for Production?

Question: I am attempting to properly set up Play Framework with Nginx as the front-end HTTP server on Amazon AMI.
I am a bit confused by the official documentation set out by Play. Are they suggesting that you run
start -Dhttp.port=9000

and then configure Nginx to reroute to port 9000 in order to properly serve up my app? I feel like having a dedicated user just to run the start command is a waste, isn't there a better way to do this?
I would really appreciate some basic strategies for best practices for a production Play Framework web app.
Answer: The reason I use a dedicated user for this is so that I can put a number of different environments on a single machine, they are all kept from treading on each other by the separate user id. For example we have an app called "d1" which we have to put into several environments so we have a user for each environment:
d1test
d1development
d1nightly
For the nightly build the nginx.conf looks like:
upstream d1nightly {
  ip_hash;
  server 127.0.0.1:20101;
  server 127.0.0.1:20102;
 }

 server {
  listen 443 ssl;
  server_name nightly.d1.org;
  ssl_certificate      /etc/ssl/certs/cert.pem;
  ssl_certificate_key    /etc/ssl/private/key.pem;
  ssl_session_timeout 5m;
  ssl_protocols SSLv3 TLSv1;
  ssl_ciphers HIGH:!ADH:!MD5;
  ssl_prefer_server_ciphers on;
  location /500x.html {
    alias /usr/share/nginx/html/500x.html;
  }

  location / {
   proxy_set_header Host $http_host;
   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-Proto https;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_redirect http:// https://;
   add_header Pragma "no-cache";
   proxy_pass http://d1nightly;
   error_page 500 502 503 504 /500x.html;
  }
 }

Now when we go to nightly.d1.org we get the nightly release.
We pay a fixed rate per VM per hour rather than for CPU time so it we get more value for money with this combination by packing 3 or 4 environments onto a single machine during our testing.
For starting the play applications, I've got a really basic shell script function:
function startPlayAppd1 {
        #start a d1 play app with appropriate system properties
        nohup ${base_directory}/${app}-latest-${jvm}/${snapshot_name}/start \
                       -Dhttp.port=${listen_port}                                             \
                       -Denv.name=${env_name}                                                 \
                       -Dlogger.file=${logger_file}                                           \
                       -Dsession.secure=${session_secure}                                     \
                       -Dga.domain=${ga_domain}                                               \
                       -Djava.net.preferIPv4Stack=${preferIPv4Stack}                          \
                       -Dcom.sun.management.jmxremote                                         \
                       -Dcom.sun.management.jmxremote.port=${jmx_port}                        \
                       -Dcom.sun.management.jmxremote.authenticate=${jmx_remote_authenticate} \
                       -Dcom.sun.management.jmxremote.password.file=jmxremote.password        \
                       -Dcom.sun.management.jmxremote.access.file=jmxremote.access            \
                       -Dcom.sun.management.jmxremote.ssl=false                               \
                       -Djavax.net.debug=${javaxDebugLevel}                                   \
                > ${listen_port}.nohup 2>&1 &
        sleep 5
}

The other advantage of an environment per user is the flexibility it creates.
As you can see various system properties have been added, for example to enable JMX so our monitoring tools can observe the play applications.
This is one solution which has worked well for our use cases.


Admob doesn't work in phonegap application

Question: Hi I'm working on a phonegap application for android. I'm having trouble integrating the admob script since it doesn't show any ads. I think I have all the permissions in the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="eu.mauriziopz.disegna"
    android:versionCode="1"
    android:versionName="1.0" >
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:resizeable="true"
android:anyDensity="true"
/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-sdk android:minSdkVersion="7" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".DisegnaActivity"
            android:label="@string/app_name" android:configChanges="keyboardHidden|orientation|screenLayout">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

This is my test page, which doesn't work
<!DOCTYPE HTML>

<title>PhoneGap</title>

Test

I Tried both in manual mode and not, but never was able to get it working.
Any ideas?
Thanks
Comment: I'm having this problem too. Did you ever solve this?
Comment: no, I switched to http://www.smaato.com/
Answer: I'm not an expert on this, but i think you have to execute your var a.
function onDeviceReady() {
     var a = _admob.fetchAd(document.getElementById('admob_ad'));
    //trigger the var
     a;
}
and add body onLoad to execute

It's working here, like this:

Answer: @MaurizioPz: You need to add an activity in the android manifest file for Admob as follows:
  <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.google.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />

</application>

Also make sure you are using the latest Admob SDK.


Search Bar Through Another Search Bar

Question: I am not familiar with scripts that utilize this, so searching through Google gave me no valuable results.
To explain what I want let's make an example:

I have a search bar on my example website
A user inputs something and clicks search
The search bar does a series of searches, not on the website, but on other website's search bars, like a macro or a script of some sort. Then on my example websites, the search results of each page are listed

I have no idea how to even search for this, don't even know if there is a tutorial about whatever I am looking for. Any sort of pointers, or even links are appreciated. Thank you
Answer: First, in each of these sites, you will need to preform a search by hand (just search whatever) then record the URL of the page once you hit submit.
The URL should contain the word you searched in some fashion.
What you can do on your site when someone performs a search is you inject their search into each of those URLs you collected.
Then, you can use a thing called cURL to fetch the contents of those web pages.
Once you have the contents of each of those pages, I suggest you use regular expressions to only grab a portion of the page that you want to display (or even just product page URLs).
Comment: of course, this is assuming you don't have direct access to the databases behind these sites.
Comment: Great, I'll give this a try see if I get stuck somewhere
Answer: Why would you search through other site's search bars, and not just through their web services or APIs, which is what their search bars are doing?  Why not just add Google to your site?  It's all the search engine most people need.  And it's free.  Even if this is not a full solution to your need, put this in place while you are researching, and I doubt anyone will know the difference.
http://www.google.com/cse/
Comment: The custom google search is not a global search, you can specify which sites you are searching.  Click on this link.  You would put your 4-6 sites in the definition of your search engine and that is your custom solution.  http://www.google.com/cse/manage/create
Comment: Thanks. I see. So I can use this to list the few websites I need and then somehow modify the website to refer to this search?
Comment: Hmm, I've tried what you suggested. While its good on its own, it doesn't really work the way I want. Its searching for everything with the keywords. This is why I said browsing the search bar, that is how the results page would list only products of the sort, not forum discussions, headlines, news etc...
Comment: Well, it was worth a shot, maybe someone else will come along with a solution.
Comment: Yeah, thanks. Even though it didn't solve my problem, it specified what I need :)
Comment: A global google search isn't what my website needs. I have 4-6 websites and their products. My website is an intermediary between clients and their products. Can you point me towards some tutorial or some reading material about using other website's APIs?

Search Bar Through Another Search Bar


To convert google sheet script into an array to run faster

Question: I have a script that when run adds cells together (i.e A1 + A2 and returning the result in A1), there are 2 tables that are each 2 x 17 so currently I have a chunk of code for each cell is there a way to do this via an array? Here is the script I am currently using.
function Transfer() {

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C5").getValue();
var num2 = ss.getRange("2ndTrailer!B3").getValue();
ss.getRange("Monday-Saturday!C5").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D5").getValue();
var num2 = ss.getRange("2ndTrailer!C3").getValue();
ss.getRange("Monday-Saturday!D5").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C6").getValue();
var num2 = ss.getRange("2ndTrailer!B4").getValue();
ss.getRange("Monday-Saturday!C6").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D6").getValue();
var num2 = ss.getRange("2ndTrailer!C4").getValue();
ss.getRange("Monday-Saturday!D6").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C7").getValue();
var num2 = ss.getRange("2ndTrailer!B5").getValue();
ss.getRange("Monday-Saturday!C7").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D7").getValue();
var num2 = ss.getRange("2ndTrailer!C5").getValue();
ss.getRange("Monday-Saturday!D7").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C8").getValue();
var num2 = ss.getRange("2ndTrailer!B6").getValue();
ss.getRange("Monday-Saturday!C8").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D8").getValue();
var num2 = ss.getRange("2ndTrailer!C6").getValue();
ss.getRange("Monday-Saturday!D8").setValue(num1+num2);

 var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C9").getValue();
var num2 = ss.getRange("2ndTrailer!B7").getValue();
ss.getRange("Monday-Saturday!C9").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D9").getValue();
var num2 = ss.getRange("2ndTrailer!C7").getValue();
ss.getRange("Monday-Saturday!D9").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C11").getValue();
var num2 = ss.getRange("2ndTrailer!B9").getValue();
ss.getRange("Monday-Saturday!C11").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D11").getValue();
var num2 = ss.getRange("2ndTrailer!C9").getValue();
ss.getRange("Monday-Saturday!D11").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C12").getValue();
var num2 = ss.getRange("2ndTrailer!B10").getValue();
ss.getRange("Monday-Saturday!C12").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D12").getValue();
var num2 = ss.getRange("2ndTrailer!C10").getValue();
ss.getRange("Monday-Saturday!D12").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C13").getValue();
var num2 = ss.getRange("2ndTrailer!B11").getValue();
ss.getRange("Monday-Saturday!C13").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D13").getValue();
var num2 = ss.getRange("2ndTrailer!C11").getValue();
ss.getRange("Monday-Saturday!D13").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C14").getValue();
var num2 = ss.getRange("2ndTrailer!B12").getValue();
ss.getRange("Monday-Saturday!C14").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D14").getValue();
var num2 = ss.getRange("2ndTrailer!C12").getValue();
ss.getRange("Monday-Saturday!D14").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C15").getValue();
var num2 = ss.getRange("2ndTrailer!B13").getValue();
ss.getRange("Monday-Saturday!C15").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D15").getValue();
var num2 = ss.getRange("2ndTrailer!C13").getValue();
ss.getRange("Monday-Saturday!D15").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C16").getValue();
var num2 = ss.getRange("2ndTrailer!B14").getValue();
ss.getRange("Monday-Saturday!C16").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D16").getValue();
var num2 = ss.getRange("2ndTrailer!C14").getValue();
ss.getRange("Monday-Saturday!D16").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C17").getValue();
var num2 = ss.getRange("2ndTrailer!B15").getValue();
ss.getRange("Monday-Saturday!C17").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D17").getValue();
var num2 = ss.getRange("2ndTrailer!C15").getValue();
ss.getRange("Monday-Saturday!D17").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C18").getValue();
var num2 = ss.getRange("2ndTrailer!B16").getValue();
ss.getRange("Monday-Saturday!C18").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D18").getValue();
var num2 = ss.getRange("2ndTrailer!C16").getValue();
ss.getRange("Monday-Saturday!D18").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C19").getValue();
var num2 = ss.getRange("2ndTrailer!B17").getValue();
ss.getRange("Monday-Saturday!C19").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D19").getValue();
var num2 = ss.getRange("2ndTrailer!C17").getValue();
ss.getRange("Monday-Saturday!D19").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C20").getValue();
var num2 = ss.getRange("2ndTrailer!B18").getValue();
ss.getRange("Monday-Saturday!C20").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D20").getValue();
var num2 = ss.getRange("2ndTrailer!C18").getValue();
ss.getRange("Monday-Saturday!D20").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C21").getValue();
var num2 = ss.getRange("2ndTrailer!B19").getValue();
ss.getRange("Monday-Saturday!C21").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D21").getValue();
var num2 = ss.getRange("2ndTrailer!C19").getValue();
ss.getRange("Monday-Saturday!D21").setValue(num1+num2);

var ss = SpreadsheetApp.getActiveSpreadsheet();
var num1 = ss.getRange("Monday-Saturday!C22").getValue();
var num2 = ss.getRange("2ndTrailer!B20").getValue();
ss.getRange("Monday-Saturday!C22").setValue(num1+num2);

var num1 = ss.getRange("Monday-Saturday!D22").getValue();
var num2 = ss.getRange("2ndTrailer!C20").getValue();
ss.getRange("Monday-Saturday!D22").setValue(num1+num2);

var sheet = SpreadsheetApp.getActive().getSheetByName('2ndTrailer');
sheet.getRange('A2').clearContent();

var sheet = SpreadsheetApp.getActive().getSheetByName('Monday-Saturday');
sheet.getRange('A23').setValue('YES');

}

Thanks
Comment: Can you give us access to a sample of you Spreadsheet, to better understand your problem ?
Comment: You can get the sheet as a 2D array with `getDataRange()` and `getValues()` and then loop through rows and columns, performing the calculation.
Answer: Here is your code with arrays and loop :
function Transfer() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s1 = ss.getSheetByName('Monday-Saturday');
  var s2 = ss.getSheetByName('2ndTrailer');

  var data1 = s1.getRange(5, 3, 18, 2).getValues();
  var data2 = s2.getRange(3, 2, 18, 2).getValues();
  var newData = [];

  for(var i = 0 ; i < data1.length; i++){

    var newValueC = data1[i][0] + data2[i][1];
    var newValueD = data1[i][1] + data2[i][1];

    newData.push([newValueC, newValueD]);

  }

  s1.getRange(5, 3, 18, 2).setValues(newData);

  s2.getRange('A2').clearContent();
  s1.getRange('A23').setValue('YES');

}

A bit ugly, but should do the trick.
Edit: Made a few changes, since the range.setValue() method causing problems
Comment: Hi thanks for that but it seems to be functioning incorrectly, for example 'Monday-Saturday' C5 is not adding with 2ndTrailer B3 to give a result back in C5 the 'cages' column in 2ndTrailer seems to be adding to both columns in 'Monday-Saturday' and the final row 'Gift Food' seems to be missed from the script. Here is copy of sheet. https://docs.google.com/spreadsheets/d/11eclWiYXjC2hTaTJdzK5PeSsfTOm86laEwnmWViuErM/edit?usp=sharing
Comment: Hi, I've made a few changes on the code, it's should work now (I've tried on a copy of your spreadsheet and it work.


Author name in comment preview not rendering apostrophe properly: a bug or by-design?

Question: This happens on a Drupal 7.26 using the default theme when previewing a comment. The <code>&#039</code> part is equivalent to an apostrophe. What I don't know if this is something that is part of Drupal to prevent exploits or if this is a bug that should be fixed. I tried searching the Drupal.org forums if this is a bug, I wasn't able to find anything relevant.
Answer: Interesting problem to solve ... Here are the findings of above problem.. I do see this issue in latest Drupal..  I believe it's a bug since check_plain method is not used in any other comment rendering features where as we can see proper name while viewing comment...
Comment preview is rendered from comment_preview function defined in 2062 Line in comment module..
<code>/**
 * Generate a comment preview.
 */
function comment_preview($comment) {
  global $user;

  drupal_set_title(t('Preview comment'), PASS_THROUGH);

  $node = node_load($comment->nid);

  if (!form_get_errors()) {
    $comment_body = field_get_items('comment', $comment, 'comment_body');
    $comment->format = $comment_body[0]['format'];
    // Attach the user and time information.
    if (!empty($comment->name)) {
      $account = user_load_by_name($comment->name);
    }
    elseif ($user->uid && empty($comment->is_anonymous)) {
      $account = $user;
    }

    if (!empty($account->uid)) {
      $comment->uid = $account->uid;
      $comment->name = check_plain($account->name);
      $comment->signature = $account->signature;
      $comment->signature_format = $account->signature_format;
      $comment->picture = $account->picture;
    }
    elseif (empty($comment->name)) {
      $comment->name = variable_get('anonymous', t('Anonymous'));
    }

    $comment->created = !empty($comment->created) ? $comment->created : REQUEST_TIME;
    $comment->changed = REQUEST_TIME;
    $comment->in_preview = TRUE;
    $comment_build = comment_view($comment, $node);
    $comment_build['#weight'] = -100;

    $form['comment_preview'] = $comment_build;
  }

  if ($comment->pid) {
    $build = array();
    if ($comments = comment_load_multiple(array($comment->pid), array('status' => COMMENT_PUBLISHED))) {
      $parent_comment = $comments[$comment->pid];
      $build = comment_view($parent_comment, $node);
    }
  }
  else {
    $build = node_view($node);
  }

  $form['comment_output_below'] = $build;
  $form['comment_output_below']['#weight'] = 100;

  return $form;
}
</code>
As you can see
<code>$comment->name = check_plain($account->name);
</code>
Comment name is rendered using above statement which takes $account->name as input and wraps using check_plain function which "Encodes special characters in a plain-text string for display as HTML."
Coming to the solution..

Comment Preview is rendered using Comment_view Function which gives us hook "hook_comment_view"
By Implementing above hook in your custom module you can check for $account->name and use htmlspecialchars_decode to decode back to original value...


Problemas na ordenação por mais de um critério

Question: Em java temos a possibilidade de sobreescrever a função compareTo de uma classe e utilizar o sort() para ordenar um vetor de objetos. Gostaria de fazer o mesmo com JavaScript, já sei que poderia usar essa chamada de função sort(propriedade) mas não estou conseguindo adaptar a função abaixo no sort. Acredito que seja porque quero utilizar mais de um critério de ordenação.
Tenho um objeto do tipo relatório, com as propriedades abaixo:
Eu quero ordenar por qualis, e depois por ano.
Quando eu tento chamar a ordenação 2 vezes, ele re-ordena para o ano e ignora a ordenação por qualis.
var relatorio = {
        ano: '',
        sigla: '',
        veiculo: '',
        qualis: '',
        fator: '',
        titulo: '',
        autores: ''
    };

Chamada da função:
Relatorio.sort(ordenacaoDinamica());

Função que estou tentando:
function teste(){
        var propriedade = 'qualis';
        return function (a,b) {
            if (a[propriedade]  b[propriedade]){
                return 1;
            }
            else{
                propriedade = 'ano';
                if (a[propriedade] > b[propriedade]){
                    return -1;
                }
                if (a[propriedade] < b[propriedade]){
                    return 1;
                }
            }
            return 0;
        }
    }

Comment: Mas se é texto usar `<` e `>` não vai ordenar como deve ser. Podes dar uma array de exemplo(?) com 4 ou 5 elementos para montarmos uma demo
Comment: Essa propriedade `qualis` é numérica ou texto?
Comment: é texto, a ordenação está funcionando, porém ao tentar ordenar dentro de qualis iguais, dá errado... ele re-orderna todo o vetor e ignora a ordenação anterior
Comment: Sugiro que faça como o Sergio disse e monte um exemplo com a ordenação que diz não funcionar, para que nós possamos ver, testar e responder.
Answer: Parecido como a forma que você estava fazendo com os if, você pode verificar se o qualis é igual ao outro, caso ele seja você verifica o ano.
No javascript você pode aproveitar que o valor 0 é interpretado com false para fazer:
let ordenacao = comparacaoDoQualis || comparacaoDoAno;

Segue um exemplo da função para ordenar:

let relatorio = [
    {'ano': '2020', 'qualis': 'B2'},
    {'ano': '2017', 'qualis': 'A2'},
    {'ano': '2017', 'qualis': 'B2'},
    {'ano': '2018', 'qualis': 'A3'},
    {'ano': '2017', 'qualis': 'A3'},
    {'ano': '2018', 'qualis': 'B1'},
    {'ano': '2015', 'qualis': 'B2'},
];

relatorio.sort((a, b) => {
   let qualis = (a.qualis == b.qualis) ? 0 : ((a.qualis > b.qualis) ? 1 : -1);
   let ano = (a.ano == b.ano) ? 0 : ((a.ano > b.ano) ? 1 : -1);

   //se o qualis for 0 ele retorna o valor da comparação do ano
   return qualis || ano;
});

console.log(relatorio);
Answer: Tente assim:

const data = [
    { qualis: 'A1', ano: '2017' },
    { qualis: 'A1', ano: '2014' },
    { qualis: 'A2', ano: '2011' },
    { qualis: 'A3', ano: '2012' },
    { qualis: 'A6', ano: '2019' },
    { qualis: 'A9', ano: '2020' },
];

function sortData(data) {
  return data.slice().sort((o1, o2) => {
    const qualis = o1.qualis.localeCompare(o2.qualis);

    if (qualis !== 0) {
      return qualis;
    }

    const ano = o1.ano.localeCompare(o2.ano);

    return ano;
  });
}

const sortedData = sortData(data);

console.log(sortedData);


execute action on workflow transition

Question: I want to execute PHP script in my custom module, when transition occurs. Workflow is assigned to custom entity. I'm using Drupal's core modules Workflow and Content moderation. How can I do that programmatically?
Answer: You can use hook_ENTITY_TYPE_update to achieve this.
<code>/**
 * Implements hook_ENTITY_TYPE_update().
*/

function mymodule_node_update(Drupal\Core\Entity\EntityInterface $entity) {

    //Get the current Moderation state;
    if (isset($entity->moderation_state) && isset($entity->moderation_state->getValue()[0]['target_id'])) {
        $currentState = $entity->hasField('moderation_state') ? $entity->moderation_state->getValue()[0]['target_id'] : null;
    }
    //Get the original Moderation state;
    if ( isset($entity->original->moderation_state ) && isset($entity->original->moderation_state->getValue()[0]['target_id']) ) {
        $originalState = $entity->original !== NULL ? $entity->original->moderation_state->getValue()[0]['target_id'] : null;
    }

    #Get the Transition;
    $workflowTransition = rtrim($originalState.'-->'.$currentState);

    switch ($workflowTransition) {
       case 'published-->needs_review':
       case 'draft-->needs_review':
       //Do something.
      break;
       case 'draft-->needs_review':
      //Do something else;
      break;
    }
 }
</code>
Comment: Yes, you will need to compare states and provide your logic as needed. Look at the updated example.
Comment: I am shocked to learn there are no event emitters for this. But after some searching around I found the request for this: https://www.drupal.org/project/drupal/issues/2873287. Hopefully we can use those in the near future :)
Comment: `if ($workflowTransition) {` this will always be true no matter what, because it's set to a string on the line above.
Comment: It seems like workaround, but it works. :)
Comment: Where does this script live?  In the Content Moderation directory?
Comment: In your custom module.
Comment: I was pretty sure I could do this with entity_update hook but wanted to try to do it the right way with an EventSubscriber. Spent 2 hours trying to find what the event was that is generated by the Content Moderation module.. and eventually ended here.. Ughh!! Why are we ready to release D9 when 8 is barely ready for prime time? lol.
Comment: Thanks for the code. In a general sense it is indeed a disappointment you can't subscribe in a more "proper" way (without contrib).

execute action on workflow transition


Explicitly calculating Green's function in complex dynamics

Question: I was reading about Bottcher coordinates at infinity, and currently have a problem that would be most easily solved by calculating Green's function (more precisely, I would like to know whether several distinct points in the dynamic plane of a polynomial of degree $d$ are in the domain/range of Bottcher coordinates).
Is there a nice way to calculate Green's function, especially at critical points?
For reference, here is Green's function. Let $p(z)$ be a polynomial with degree $d$ and $\ln^+(x)=\max\{0,ln(x)\}.$ Then Green's function $G_p$ for polynomial $p$ is:
$G_p(z):=\lim_{n\to \infty} \frac{1}{d^n} \ln^+|p^{\circ n}|.$
Thanks in advance!
Comment: What I've been able to see so far is that the limit seems to converge rather quickly, and even the n=2 term seems to give a reasonable estimate.
Answer: Short answer: no, except in very special cases you won't be able to explicitly compute the Green function (except where it's equal to zero).
Like you said, it is however easy to compute numerically; you can also find rigorous bounds, that will enable you to for instance give a rigorous computer-assisted proof that some explicit points are in the basin of infinity.
Cases where you can explicitly compute Böttcher coordinates: power maps $z \mapsto z^d$ and Chebyshev polynomials.


Qual a melhor maneira de ler propriedades de entidades no "Include" com nomes similiares?

Question: Eu tenho a seguinte consulta:
            var recs = (from p in _db.Fichas
                    .Include(c => c.Tipo01)
                    .Include(c => c.Tipo02)
                    .Include(c => c.Tipo03)
                    .Include(c => c.Pessoa01)
                    .Include(c => c.Pessoa02)
                    .Include(c => c.Pessoa03)
                    .AsNoTracking()
                    where p.Id == 100
                    select p).FirstOrDefault();

Com base na consulta acima, estou obtendo e lendo (acredito que de maneira equivocada) os valores das seguintes propriedades:
        var nome1 = recs.Pessoa01 != null ? recs.Pessoa01.Nome : null;
        var nome2 = recs.Pessoa02 != null ? recs.Pessoa02.Nome : null;
        var nome3 = recs.Pessoa03 != null ? recs.Pessoa03.Nome : null;
        var tip1 = recs.Tipo01 != null ? recs.Tipo01.ModeloA : null;
        var tip2 = recs.Tipo02 != null ? recs.Tipo02.ModeloA : null;

Algum colega poderia me ajudar e me mostrar uma maneira mais decente de executar essa tarefa?
Forte abraço
Hugo
Answer: Pela sua pergunta não dá pra ter certeza do que você pretende...
Mas se o objetivo é remover essas condições ternárias e considerando que o seu código está preparado para trabalhar com esses valores nulos. Você pode escrever essas declarações de formas mais simples e legível.
    var nome1 = recs?.Pessoa01?.Nome;
    var nome2 = recs?.Pessoa02?.Nome;
    var nome3 = recs?.Pessoa03?.Nome;
    var tip1 = recs?.Tipo01?.ModeloA;
    var tip2 = recs?.Tipo02?.ModeloA;

Também recomendo que você reavalie o nome das suas propriedades, variáveis e objetos... Pessoa01, nome1, Tipo01 e tip1 não fazem nenhum sentido semântico. E se o seu domínio está estruturado dessa forma, é melhor você rever o seu projeto desde a base.
Comment: Bom dia, Leandro.  Muito obrigado pelo seu feedback.  Estou dando manutenção em sistema de terceiros.  Na realidade, para economizar linhas de desenvolvimento, eu pensei em algo como um loop para ler as propriedades e entidades. Por exemplo, ao invés de ter que obter o "Nome" das entidades "Pessoa01, Pessoa02 e etc"; talvez eu pudesse fazer um loop concatenando um contador e assim fazer a leitura.
Comment: Algo assim:  rec.Pessoa(i+1).Nome Entendeu?


jQuery change "PLUS MINUS image"

Question: I try to make a small code for changing the plus minus on click.

$(".plus").click(function(){
    $(this).next(".navigation").slideToggle(100);
})
.toggle( function() {
    $(this).children("class").img("plus.png");
}, function() {
    $(this).children("class").img("minus.png");
});

Maybe i do something wrong...
Thank for any ideas
Comment: There is no `$.img()`, and the `.children('class')` selector would like to pick all `` tags [which is unlikely to happen]. Moreover, this should be done in pure CSS, by giving different background-images to 2 different classes of same element [or better by spriting].
Answer: Maybe something like this:
$('.plus').click(function(){
    $(this).children('img').toggle(0);
});

http://jsfiddle.net/XPBpm/3/

jQuery change "PLUS MINUS image"


On click inside form gets submitted in angular even if required fields are blank

Question: There is drop down in form when its value changes, I check if its drop down or not. If its drop down then the user have to enter the value of the drop down. On the change of drop down I call "ChangeSortOrder" function, but along with it, the form gets submitted. So instead of NgSubmit I used to click on submit button. But now the problem is it's not checking required fields and submit even if values are empty.
<form role="form" class="form form-horizontal" #Editform="ngForm" ngNativeValidate>

        <button class="btn btn-outline-allow" id="dropdownBasic1" ngbDropdownToggle>{{selectedQuestionType}}</button>

            <button class="dropdown-item" (click)="ChangeSortOrder('Text')">Text</button>

            <button class="dropdown-item" (click)="ChangeSortOrder('DropDown')">DropDown</button>

                You have selected a Drop Down question. This means diner will select from 5 options in response to this question. This score can contribute to your overall score and section.

                You have selected a text question. This means the diner will enter a text in response to this question. This score can contribute to your overall score and section.

                <textarea class="form-control" name="question" value={{editQuestion.question}} [(ngModel)]="question" required> </textarea>

            <input type="text" class="form-control" name="DropDown1" [(ngModel)]="DropDown1" placeholder="Give Label for drop down" required/>

            <input type="text" class="form-control" name="DropDown2" [(ngModel)]="DropDown2" placeholder="Give Label for drop down" required/>

                <input ngbButton type="radio" [value]="2"> Staff

                <input ngbButton type="radio" [value]="3"> Marketing

                You have selected a Staff question. We will provide you with insights on where are you performing well and where there is
                room for improvement.

                You have selected a Marketing question. We will provide you with insights on where are you performing well and where there is room for improvement.

    <button type="submit" (click)="onSubmit()" class="btn btn-raised btn-danger pull-right mt-2">Save</button>
</form>

Comment: Please consider creating a StackBlitz if possible.
Answer: There are a couple ways to prevent the form from being submitted:

Set the type of the button to type="button"
On the button call $event.preventDefault();

<button class="dropdown-item" (click)="ChangeSortOrder('DropDown'); $event.preventDefault()">DropDown</button>
Answer: Have you tried to change the button type from "submit" to "button"?
<button type="button"
    (click)="onSubmit()"
    class="btn btn-raised btn-danger pull-right mt-2">
       Save
</button>


sp_xml_preparedocument fails to return in openquery statement? (The metadata could not be determined)

Question: Need to call Sp in open query.
Sample Sp
CREATE PROCEDURE testsp
AS
DECLARE @idoc int,@doc varchar(1000)=
    '<OutLookContact>
         <Contact FirstName="Asif" LastName="Ghafoor" EmailAddress1="firstname.lastname@example.com" />
         <Contact FirstName="Rameez" LastName="Ali" EmailAddress1="firstname.lastname@example.com" />
     </OutLookContact>'

EXEC sp_xml_preparedocument @idoc OUTPUT, @doc

SELECT *
FROM OPENXML (@idoc, '/OutLookContact/Contact',1)
WITH
(
    FirstName varchar(50),
    LastName varchar(50),
    EmailAddress1 varchar(50)
)

Now when executing
SELECT * FROM OPENQUERY ( linkserver,'Exec testsp' )

But it returns error

Error Message: Msg 11529, Level 16, State 1, Procedure
  sp_describe_first_result_set, Line 1 The metadata could not be
  determined because every code path results in an error; see previous
  errors for some of these. Msg 2812, Level 16, State 62, Procedure
  sp_describe_first_result_set, Line 1 Could not find stored procedure
  'testsp'.
Answer:
You must specify Database name and schema name in exec
SELECT * FROM OPENQUERY ( linkserver,'Exec [Database].dbo.testsp' )

But you'll get an error:

Msg 11520, Level 16, State 1, Procedure sp_describe_first_result_set,
  Line 1 The metadata could not be determined because statement 'EXEC
  sp_xml_preparedocument @idoc OUTPUT, @doc' in procedure 'testsp'
  invokes an extended stored procedure.

You need a workaround - wrap you SP to new SP with result set:
ALTER PROCEDURE testsp2
AS

EXEC testsp
WITH RESULT SETS
(
    (
        FirstName nvarchar(max),
        LastName nvarchar(max),
        EmailAddress1  nvarchar(max)
    )
);

And call it:
SELECT * FROM OPENQUERY ( linkserver,'Exec [Database].dbo.testsp2'

Or modify your first SP in such way.
Comment: Thanks.. This is what i need.
Comment: Need your help again [Help](http://stackoverflow.com/questions/32651662/length-error-when-using-dynamic-sql-statement-in-openquery)
Comment: @Ragul you can ask new question :)
Comment: I already did check this link  http://stackoverflow.com/questions/32651662/length-error-when-using-dynamic-sql-statement-in-openquery
Comment: @Ragul oh, I see. I'll check it later, and try to help


Kuberentes kubelet-client-current.pem expired

Question: I'm new in K8s and I'm facing a problem with certificate.
1.13 version is used.
One of the worker nodes is in NotReady status.
I check logs and it turned out that:
Part of the existing bootstrap client certificate is expired
Using bootstrap kubeconfig to generate TLS client cert, key and kubeconfig file
Loading cert/key pair from "/var/lib/kubelet/pki/kubelet-client-current.pem"
Failed to connect to apiserver: the server has asked for the client to provide credentials
I checked and indeed kubelet-client-current.pem is pointing to expired certificate. My question is how to renew this kubelet-client-<current_date>.pem file.
EDIT:
I read that for this current cert:
The initial validity period is one year. When the certificate is about to expire, it is automatically renewed and the validity period is extended by one year.
Is there any way to create it manually? Or how to force kubeadm to do it?
I also deleted /var/lib/kubelet/pki and after kubelet restart it was recreated but only with kubelet-client.key.tmp,  kubelet.crt,  kubelet.key.
Answer: Finally I was able to renew this certificate.
Solution is described under https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/troubleshooting-kubeadm/#kubelet-client-cert


HeapSort code works on smaller arrays but not bigger ones

Question: def heapSort(arr, end):
    '''Heap Sort Algorithm'''
    '''Average Case: O(n*log(n))'''
    '''Worst Case: Θ(n*log(n))'''
    '''Best Case: Ω(n*log(n))'''
    if end <= 0 or len(arr) <= 1: #algorithm ends when there's one element or less
        return arr
    buildHeap(arr, end)
    arr[0], arr[end] = arr[end], arr[0]
    end -= 1
    return heapSort(arr,end)

def buildHeap(arr, end):
    '''Builds the Max Heap'''
    if end <=0: #recursively max heap half of arr to the start
        return arr

    i = (end-1)//2 #parent
    while i >= 0: #index backwards, swapping the parent with the bigger of each child
        leftChild = 2*i+1
        rightChild = 2*i+2

        if arr[leftChild] > arr[rightChild] and arr[leftChild] > arr[i] and rightChild <= end: #make sure right child is within our end bounds
            arr[i], arr[leftChild] = arr[leftChild], arr[i]

        elif arr[rightChild] > arr[leftChild] and arr[rightChild] > arr[i] and rightChild <= end:
            arr[i], arr[rightChild] = arr[rightChild], arr[i]
        i-=1
    end-=1
    return buildHeap(arr, end)
from random import randint
A = [randint(1,100) for i in range(20)]
print(A)
print(heapSort(A, len(A)-1))

Above is my following heap sort code, the error occurs in my buildHeap function (the if line(s)). On all initial runs the right child ends up being equals to the length of the array (not the length of the array-1), so the code goes out of index bounds. Weirdly enough, my Python implementation of the algorithm works for smaller lists. Any help on how to fix and/or improve my code?
Comment: If the last entry in the array is a left child, then `i = (end-1)//2` gives the index of that child's parent, and `2*i+2` is equal to the length of the array. So your observation that smaller lists work was misleading. Your smaller lists apparently all ended with a right child.
Comment: This doesn't work reliably on a smaller list, either. I think too many things are wrong to say anything beyond the obvious: you know where the end is, so check it.
Answer: You are making the within-bounds check too late in the below statements, because by the time that check is made you already have referenced arr[rightChild]. You should first check -- as a guard -- and only then access arr[rightChild]. So replace:
if arr[leftChild] > arr[rightChild] and arr[leftChild] > arr[i] and rightChild <= end: #make sure right child is within our end bounds
    arr[i], arr[leftChild] = arr[leftChild], arr[i]

elif arr[rightChild] > arr[leftChild] and arr[rightChild] > arr[i] and rightChild <= end:
    arr[i], arr[rightChild] = arr[rightChild], arr[i]

With:
if arr[leftChild] > arr[i] and (rightChild > end or arr[leftChild] > arr[rightChild]):
    arr[i], arr[leftChild] = arr[leftChild], arr[i]

elif rightChild <= end and arr[rightChild] > arr[i]:
    arr[i], arr[rightChild] = arr[rightChild], arr[i]

BTW, your heap building function is not very efficient. It has a time complexity of O(n²), using O(n) extra (stack) space, while this can be done in linear time and constant extra space, with Floyd's method.


Android receiver cannot always get broadcast correctly

Question: I have a package added receiver in my Android application, and has been distributed for a couple months.
Recently I found that not all the PACKAGE_ADDED broadcasts can be received by my receiver.
looked up a while, someone said that if your app had been killed by users or system, then you will no longer get broadcasts.
My questions are:

Is that true?
   confirmed, if you terminate your app from Settings->Applications --> force stop
   then your application wont receive any broadcast.
How can I prevent this happening, or is there a work around?
Answer: 1.Yes that is true.
2.Take a look at WakefulBroadcastReceiver that will wake up when it receives an Intent. Then make sure you spawn eg. an IntentService so it will process your work in the background.
Take a look at CommonsWare's WakefulIntentService for implementation example.
Comment: also it seems like it might not work; http://stackoverflow.com/questions/1593022/cant-receive-broadcasts-for-package-intents/1596466#1596466. If this is true then I would take advantage of the alarm manager and register the receiver at certain intervals.
Comment: I tried WakefulBroadcastReceiver, but it dosen`t work when I terminate my application manually, I cannot receive any PACKAGE_ADDED broadcast anymore
Comment: and I assume you've registered your receiver in the Manifest and not in your code? If not make sure to register your receiver in the Manifest.
Comment: I have registered it in Manifest. still  dosen`t work.
Comment: do you have the ``in the intent filter? http://stackoverflow.com/questions/10888768/package-added-broadcastreceiver-doesnt-work
Comment: Thx for ur suggestions. I would take those in consideration.


Do I have to replace all violin strings when E string broke?

Question: I just received my violin 2 days ago.
My E string broke when I tuning it.
I enquired nearby musical instrument store and they only sell the whole set of strings.
So, do I have to replace all strings or I keep G, D, A strings and only replace E string?
Comment: Find another music store - or buy online. You can certainly buy strings separately. On the other hand, if you don't have any spare strings, it might be worth buying full set plus another E string. Note, it's possible you broke the string by trying to tune the violin incorrectly - an E string shouldn't "just break" after only two days, or even two months. You were using the tuning adjuster on the tail piece, not trying to tune the E string with the tuning peg, I hope!
Comment: You can absolutely buy individual violin strings. Many players use an E string that doesn't match the brand of their other strings.  A generic music shop probably doesn't do enough volume to sell anything other than sets,  but a shop that caters to string players will have the individual strings. There may be one locally,  or you can order online.
Comment: I asked 3 different music store. Unfortunately, all of them do not sell individual string. Ya, I use tuning peg to tune because need more 100Hz to reach E5.
Comment: Yes to all of the above.  I'll just add that new violins are nowadays often furnished with really bad strings, and it's not uncommon for them to break pretty much immediately.
Answer: There is no point in changing all the strings, especially since the remaining ones are so new. When comes the time for total replacement in 6 months, a year, depending how much it gets played, then yes, change them all.
I'm pretty sure singles are available, but if not, a whole set isn't going to break the bank, and having spares is a sensible situation to be in. Bit like that insurance policy - useless until it's needed!
As a new violinist, be very careful you tune to the correct notes, and not an octave higher. Seen it happen, not a pretty sight.
Comment: "a whole set isn't going to break the bank" - that depends. It's quite easy to spend £50 on a decent set of violin strings, and possible to spend £100 without trying really hard to find the most expensive ones available!
Answer: Hint: Get into the habit of slackening off your fine tuner when you are changing a string. This will give you more adjustment after you have roughly tuned it with the tuning peg and for subsequent tuning adjustments. Your violin is unlikely to get bumped 'sharp', so you will rarely need to fine tune it down far.
For the first time, maybe it's best to ask the music store to fit the new string. Watch the way they do it. For example, it's good to make sure that the string windings stay near the outside of the peg box, rather than the centre. That will stop the peg from slipping outwards and loosening its grip in the peg hole.
Comment: Ok, but is changing string is easy? Because I planning to let the music store's staff change for me.
Comment: @Coolwei- if you're still here: let the music store change it for you, but watch carefully and you can do it next time.
Answer: You can absolutely buy individual violin strings. Many players use an E string that doesn't match the brand of their other strings.  A generic music shop probably doesn't do enough volume to sell anything other than sets,  but a shop that caters to string players will have the individual strings. There may be one locally,  or you can order online.
The three stores I've bought from online are Shar music,  Johnson Violin, and Southwest Strings. There are certainly other reputable shops as well.
You mention having the music store put in your string. Ask them to show you how to change the string,  because it is very simple and something every student should know. They may charge a small fee,  especially if you don't buy the string from them.
Comment: You are right. I purchased 2 set of strings and I learnt how to replace it from Youtube, it's very easy. Thank you.
Answer: From experience, violinists don't actually like the timbre of new strings. While guitarists typically chase the timbre produced by a fresh set of strings, violinists prefer the timbre of strings that have at least bedded in, and will only replace strings if they break, start to unwind or develop an undesirable tonal artifact.
With this in mind, I think it would be more typical for a violinist to replace a single string than to replace all four when one breaks. The other thing to note here is the cost of violin strings. Beyond purchasing a spare set for emergencies, it could get fairly costly fairly quickly were you to replace all four strings whenever one broke.
Comment: I saw other people said have to replace all strings to ensure the strings ageing is the same. Since I only used my violin for 2 days so I decided to replace E string only.
Answer: The thing to keep in mind when replacing single strings is to find the gauge of the broken string and get an individual string of the same gauge. This way, the original setup of your violin stays intact.
Usually, a music store should have a device to measure the gauge. So I advice you to find another store to get it replaced.
Comment: I bought 2 set of strings eventually, each set is about 3USD (converted from MYR).
Answer: I suggest you replace the strings that came with your violin within 6 months. It probably is not of the greatest quality unless you bought a 4000 dollar violin. Keep at least 2 sets of spares safely. They may get damaged on exposure to extreme atmospheric conditions. After a while adjust your set up mixing and matching different strings of different brands and gauges to your preference.


Deselecting an element in jQuery

Question: I have a collection of span elements. In the code I have a global variable that represents the "selected" object. Using the click event when a span is clicked I reset the object's class, reset the global variable, then set the object to the variable and change its class (to make it "highlighted"). This effectively toggles selection when clicking an object.
var currentItem = null;
$( ".item" ).click( function() {
    if( $( this ).hasClass( "selected" ) ) {
        $( this ).removeClass( "selected" )
        currentItem = null;
    } else {
        if( $( ".item" ).hasClass( "selected" ) ){
            $( ".item" ).removeClass( "selected" )
        }

            $( this ).addClass( "selected" );
            currentItem = $( this );
        }
} );

What I'd like to be able to do is unselect when clicking on an empty area of the page. I tried creating a click event on the body object, but that overrode the span click event so nothing was selected. I'm a complete jQuery noob and not sure where to go with this.
Comment: Quick note on selecting a Best Answer: Nick Craver responded first and his answer was accurate. Gaby posted shortly thereafter and the response was clear, concise, and equally accurate. I'd give either one of these individuals the credit. :)
Comment: Yeah, the only part of SO that I don't like so much: picking the winners when its close like that.
Comment: Quick note on selecting a Best Answer: I have every confidence in your own capacity for judgement and discernment that you can figure out such a simple task for yourself.
Answer: Use event.stopPropagation() in your current handler so that click doesn't bubble up to the , triggering it's handler as well, then your approach works, like this:
var currentItem = null;
$(".item").click(function(e) {
  if($(this).hasClass("selected")) {
    $(this).removeClass("selected")
    currentItem = null;
  } else {
    $(".item.selected").removeClass("selected");
    currentItem = $(this).addClass("selected");
  }
  e.stopPropagation();
});
$(document).click(function() {
  $(".item.selected").removeClass("selected");
});

You can view a demo here, one suggestion though, if only one element can be selected do you need to keep track of it?  If lookup cost isn't a factor, you could aways find the currentItem by doing $(".item.selected"), simplifying this code quite a bit. I'm not sure how you're using currentItem, just an option you have :)
Comment: Nick... do you ever sleep? :D
Comment: @Gert G - Every third sunday on odd months, yes :)
Comment: LOL - That's what I thought. Btw... Good answer. :)
Answer: You did well setting a click event on the body. BUt you must also tell the span click event to stop the propagation of the event..
$( ".item" ).click( function(event) {

    event.stopPropagation();
    //your code
});

Answer: Your idea to place the click event on the body is fine.
You just need to be aware that clicking on any descendants of body will cause the click event to bubble up to body, and fire that handler.
You need to stop that propagation in your span event handler.
$( ".item" ).click( function(event) {
    event.stopPropagation();
    ...

jQuery Docs
event.stopPropagation() http://api.jquery.com/event.stopPropagation/

EDIT:
Another valid alternative would be to simply return false at the end of the handler.
$( ".item" ).click( function() {
    // Your code...
    return false;
});

Answer: You don't necessarily need a global variable since your DOM holds that state info, too.
// de-select old selection and select new item
$(".item").click( function(evt) {
  $(".item.selected").removeClass("selected");
  $(this).addClass("selected");
  evt.stopPropagation();
});

// de-select everything
$("body").click( function() {
  $(".item.selected").removeClass("selected");
});

// your currently selected element can be retrieved by this anytime:
$(".item.selected")[0]

Not tracking state twice (in the DOM and in a global variable) spares you two headaches:

carefully updating the global variable all the time
bugs that arise of "global" state getting out of sync with "DOM" state
Answer: Create a click on the html element $("html") and return it as false whenever you do what you need to do. The body could not extend the whole page if you're doing some sizing with CSS with it. Here's an example:
$("html").click( function(e) {

    e.stopPropagation()

});

Edit
Yeah. forgot about stopPropagation(). Changed code to read that. Should still use the html element as the listener, however.
Answer: In addition to the answers stated (unless I missed this), you needn't attach the click() event to the body when the page loads -- you can simply do it after the item is selected. Not that it hurts since you're stopping propagation, but in my view its more "correct" to only activate/set an event handler for the duration in which it is relevant.
Answer: Too much code, we can do it easier:

"use strict";
/*global $*/
$(function () {
  $('html').live('click', function (e) {
    $('.item.selected').removeClass('selected');

    var $t = $(e.target);
    if ($t.hasClass('item')) {
      $t.addClass('selected');
    }
  });
});

Using 'html' to bind event is better due body can be not 100% height, for example. And clicking on empty area return not expected result.
We do not need global object, as this script guarantees that we have only one selected span and we can refer to it with:

$('.item.selected');

Deselecting an element in jQuery


Can a Webdriver interface be static(refer description for questions)?

Question: While writing selenium code I had seen a statement:-
public static WebDriver driver = new Firefox Driver();
Now I have multiple questions:-

WebDriver is an interface. Can an interface be static? If yes as per my understanding all the methods part of this interface will also be static methods.
As per my understanding for static class/method/variable no object should be defined as static cannot be instantiated. But from the above program statement it appears we are creating a new object of the WebDriver class although it is static. Please clarify how is this possible or is there a deviation in my understanding?
Answer:
For #2:
public static WebDriver driver = new Firefox Driver();

Above statement is not creating an object of Webdriver interface but it creates an object of class FirefoxDriver. FirefoxDriver is a class that inherits or implements interface WebDriver.
Answer: First of all your understanding of what is static is incorrect. In public static WebDriver driver = new FirefoxDriver();, WebDriver is type of the object, while driver is an instance of the object. When you declare a member as static, it refers to its instance, not its type. So you are not "making" WebDriver static, you are making driver static.
So the question "Can an interface be static?" does not apply to your situation at all. But if you care about it anyways, the answer is yes, you can define interface like this and it will be static for the parent class:
 public class WithStaticInterface
 {
     public static interface MyInterface
     {
         void hello();
     }
 }

However the members of the interface can never be static
I suggest reading more on what static members mean. For example here:

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
Comment: Thanks for the reply Kiril. Things are pretty much clear now. Thanks for clearing out the confusion.


QML Screen Coordinates of Component

Question: If I have a simple, self-contained QML application, I can get the absolute screen coordinates of a component by saying
Component.onCompeted: {
    var l = myThing.mapToItem(null, 0, 0)
    console.log("X: " + l.x + " y: " + l.y)
}

where myThing is the id of any other component in the file. However, if this file gets incorporated into another QML file and the component it defines is reused, I don't get the screen coordinates anymore; I get the local coordinates relative to the component where the statements above are executed.
How can I get the absolute screen coordinates of items?
Answer: Component.onCompleted: {
    var globalCoordinares = myThing.mapToItem(myThing.parent, 0, 0)
    console.log("X: " + globalCoordinares.x + " y: " + globalCoordinares.y)
}

where myThing.parent is your main compontent.
Comment: Unfortunately, I don't have access to the main component where this widget will be used.
Comment: `Item`s should have a `mapToGlobal` method. Further you can always access the toplevel `Item` with `ApplicationWindow.contentItem` if you use `ApplicationWindow` to create your window. I think `Window` is also an attached property to get the Window in which your Item is instantiated. (That is, nowadays. Might be different for 2014 Qt)
Comment: You're right. I tested it with `myThing.parent` which works in case the parent QML element fills the whole window. You can also use `myThing.parent.parent` if that is your root element. Not very nice and maintainable but it works.
Comment: @PaulCarlisle, There is exist way to access different QMLs using `import`.
`import "../Path/To/Parent/" as ParentOfMyThing`
Then, should be available following thing: `ParentOfMyThing.someId`
Comment: The main component can be made global using dynamic scoping, just have a `property Window vroot : id_root`, then `vroot` will be available for the entire application.
Answer: Since Qt 5.7, there is Item.mapToGlobal:
Component.onCompleted: {
    var globalCoordinates = mapToGlobal(0, 0)
    console.log("X: " + globalCoordinates.x + " y: " + globalCoordinates.y)
}

Comment: Unfortunately, this apparently doesn't work on delegates...
Answer: Here is a quick and very dirty solution. Note: This has only been lightly tested but so far seems to work. I would not recommend using this in production applications as it's a complete hack and likely to break at some point.
ApplicationWindow {
    id: mainWindow
    visible: true
    width: 640
    height: 480
    x: 150.0
    y: 150.0
    title: qsTr("Hello World")

    Rectangle {
        id: lolRect
        height: 50
        width: 50
        anchors.centerIn: parent;

        Component.onCompleted: {

            function getGlobalCordinatesOfItem(item) {

                // Find the root QML Window.
                function getRootWindowForItem(item) {
                    var cItem = item.parent;
                    if (cItem) {
                        return getRootWindowForItem(cItem);
                    } else {

                        // Path to the root items ApplicationWindow
                        var rootWindow = item.data[0].target;
                        if (rootWindow && rootWindow.toString().indexOf("ApplicationWindow") !== -1) {
                            return rootWindow;
                        } else {
                            console.exception("Unable to find root window!");
                            return null;
                        }
                    }
                }

                // Calculate the items position.
                var rootWindow = getRootWindowForItem(item);
                if (rootWindow) {
                    return Qt.point(rootWindow.x + lolRect.x,
                                    rootWindow.y + lolRect.y);
                } else {
                    return null;
                }
            }

            // Print the result.
            console.log(getGlobalCordinatesOfItem(this));
        }
    }
}

QML Screen Coordinates of Component


Get amount of screen home in Android except the offsetChange function

Question: I know about offsetChange function, but it doesn't work on such devices as Galaxy S4. I think it happens because of TouchWiz wrapper. So I need to find out another way to determine count of home screens.

Any help will be appreciated!
Comment: Please explain what "count of home screens" means.
Comment: Android has main screen like desktop. There are several home screens, you can switch between them. So I need to get amount of them.
Answer:
Android has main screen like desktop.

Android has a home screen. Whether it is "like desktop" or not depends upon the device and user.

There are several home screens, you can switch between them

It is unclear what you mean by this.
You might mean "an Android device can have multiple applications installed that each offer to be a home screen, and the user can choose which of those applications to use". In that case, creating an Intent for ACTION_MAIN and CATEGORY_HOME, then passing that to queryIntentActivities() on PackageManager, should give you the list of possible home screen implementations.
You might mean "all Android home screens offer some sort of swiping option to move to different portions of space". Some home screens offer this, and there is no standard way to find out. There is no requirement that a home screen offer the capability of swiping this way, let alone a requirement to supply an API for third-party apps to find out details about them.
Comment: @Ares: That is covered in the last paragraph of my answer.
Comment: In your opinion there is no simple way to determine this. Right?
Comment: @Ares: There is no simple way to determine this. In general, there is no way **at all** to determine this, though certain home screens may offer up solutions.


In apache, subdomain http://subdomain.domain working but www.subdomain.domain not working

Question: I have configured a subdomain in my Apache2 httpd server, but having a problem. I can reach the subdomain by using http://subdomain.domain.com but do not access it by using www.subdomain.domain.com
My top-level domain say, domain.com can be reached with both http://domain.com and www.domain.com
Here is source from my subdomain config file in sites-available
<VirtualHost *:80>
    ServerName subdomain.domain.com
    ServerAlias www.submdomain.domain.com
    ServerAlias http://www.subdomain.domain.com

    ServerAdmin admin@domain

    DocumentRoot /var/www/domain/subdomain
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/domain/subdomain>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

Where is the problem? Here in this configuration or in A records of my domain name?
EDIT : I get this message from my ISP when I try to reach by www.subdomain.domain.com = "Sorry, the website you were looking for is unavailable."
And when I used a proxy to reach it, it shows this error message = "The requested resource could not be loaded. libcurl returned the error: Couldn't resolve host 'www.subdomain.domain.com"
Comment: What happens or error message do you get when you try to access www.subdomain.domain.com ?
Comment: @Iain: I cannot reach there, my ISP shows this message "Sorry, the website you were looking for is unavailable."
Answer: You'd need to provide more details, ie. what error is returned when you try to reach your www.subdomain.domain.com.
My guess is you don't have www.subdomain.domain.com in your DNS server.
Comment: I have edited my question to include error message, have a look now
Comment: Can you paste the apache2 error report.
Answer:
Couldn't resolve host 'www.subdomain.domain.com"

You need to configure your DNS to resolve www.subdomain.domain.com to your server's IP address.
Comment: I am not using DNS, I am using A records and I have added subdomain to it.
Comment: @Abhi: You are using DNS what do you think an [A record](http://en.wikipedia.org/wiki/List_of_DNS_record_types) is ?
Comment: I figured it out, I had to configure cname for it to work with www as well.
Comment: So, like I said you had to configure your DNS ...


Problemas com Thread no Android

Question: Tenho uma listview a ser povoada/alimentada por um webservice, mas so faz o load das minhas images com um Handler.
Eu quero usar uma Thread, mas só corre com um Handler e eu não percebo porquê...
Alguém me pode ajudar?
Aqui está o código (excerto):
new Thread(new Runnable() {
            public void run() {
                do{
                    if(isOnline()){
                        initializeArrays();
                        populateList();
                        populateListView();
                    }
                }while(!isOnline());
                        progresso.dismiss();
            }
        })start();

private void populateListView() {
        ArrayAdapter<Clube> adapter = new MyArrayAdapter();
        list = (ListView) findViewById(R.id.classificacaoGeral);
        list.setAdapter(adapter);
        list.setOnItemClickListener(this);
    }

private class MyArrayAdapter extends ArrayAdapter<Clube> {
    public MyArrayAdapter() {
        super(Main.this, R.layout.list_item, clubes);
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = getLayoutInflater().inflate(R.layout.list_item,
                    parent, false);
        }
        // Counter de position no Ranking
        if(position == 0){
            convertView.setBackgroundColor(Color.rgb(235, 235, 235));
        }else if(position == 1){
            convertView.setBackgroundColor(Color.rgb(240, 240, 240));
        }else if(position == 2){
            convertView.setBackgroundColor(Color.rgb(249, 249, 249));
        }else{
            convertView.setBackgroundColor(Color.rgb(255, 255, 255));
        }
        Clube actual = clubes.get(position);
        TextView tv = (TextView) convertView.findViewById(R.id.item_name);
        tv.setText(actual.getName());
        // Logo do clube
        ImageView imgView = (ImageView) convertView
                .findViewById(R.id.item_img);
        imgView.setImageBitmap(this.getClubeLogo(actual.getImgURL()));
        // ID de Clube de acordo com a BD
        TextView pontos = (TextView) convertView
                .findViewById(R.id.item_pontos);
        pontos.setText(actual.getPontos() +" pontos");

        return convertView;
    }

    /**
     * Metodo para fazer o load de uma imagem por um URL
     *
     * @param src
     *            String de URL de image
     * @return Bitmap
     */
    private Bitmap getClubeLogo(String src) {
        try {
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap logo = BitmapFactory.decodeStream(input);
            return logo;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

Comment: Qual é exatamente o problema? Este código funciona ou apresenta algum erro?
Answer: Cara você só pode manipular uma View na UI Thread. Baixa os dados e trate eles como quiser na sua Thread, mas quando for popular esses dados na sua ListView volte a Thread Principal, para isso você pode usar uma Handler criada anteriormente na UI Thread ou pode chamar o metodo runOnUiThread.

Problemas com Thread no Android


How can I allow the current user to only see their own page?

Question: I created a page in a custom module. I want only the current user to access this page on their behalf.
For example, I am using it with ID 51. If I go to :
/user/51/tasks

I can see this page.
If I go on :
/user/78/tasks

I must have an error 403 access denied.
How to do this ?
task_notify.user_page.tasks:
  path: '/user/{user}/tasks'
  defaults:
    _controller: '\Drupal\task_notify\Controller\TaskNotifyUserController::Tasks'
    _title: 'Liste des tâches'
  requirements:
    _permission: 'access content'

UPDATE :
My custom module is here :
https://git.drupalcode.org/sandbox/zenimagine-3076032
I applied kiamlaluno's answer but I have the following error :

/task_notify/src/Controller/TaskNotifyUserController.php
<?php

namespace Drupal\task_notify\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\UserInterface;

class TaskNotifyUserController extends ControllerBase {

  public function Tasks() {
    return [
      '#theme' => 'task_notify_user_template',
    ];
  }

  public function taskAccess(UserInterface $user, AccountInterface $account) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user->id() == $account->id())
      ->orIf(AccessResult::allowedIfHasPermission($account, 'administer users'))
      ->cachePerUser();
  }

}

Comment: Does this answer your question? [How do I inject UserInterface into Access Control?](https://drupal.stackexchange.com/questions/280698/how-do-i-inject-userinterface-into-access-control)
Comment: You can achieve that by following the answer here https://drupal.stackexchange.com/a/280699/
Comment: I have updated my question
Answer: _permission only allows to give access to the route to the users who have that permission; it doesn't allow to give access basing on more complex conditions, as in the case of this question. As described in Custom route access checking, the route definition should be similar to the following one.
task_notify.user_page.tasks:
  path: '/user/{user}/tasks'
  defaults:
    _controller: '\Drupal\task_notify\Controller\TaskNotifyUserController::tasks'
    _title: 'Tasks list'
  requirements:
    _custom_access:  '\Drupal\task_notify\Controller\TaskNotifyUserController::taskAccess'
    user: \d+

The TaskNotifyUserController class would need to contain at least the following code (and other methods you need from that controller, including tasks()).
class TaskNotifyUserController extends ControllerBase {

  /**
   * Checks access for the users task page.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user being viewed.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The account viewing the page.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function taskAccess(UserInterface $user, AccountInterface $account) {
  public function taskAccess(UserInterface $user) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user()->id() == $account->id())
      ->cachePerUser();
  }

}

If then the access to the route should be allowed also to users with a specific permission (for example, the permission to administer users), the taskAccess() code would be similar to the following one.
  /**
   * Checks access for the users task page.
   *
  /**
   * Checks access for the tasks tab.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user being viewed.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The account viewing the page.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function taskAccess(UserInterface $user, AccountInterface $account) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user->id() == $account->id())
      ->orIf(AccessResult::allowedIfHasPermission($account, 'administer users'))
      ->cachePerUser();
  }

Don't forget to import the class used from the controller, adding the following lines at the top of the controller file.
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\UserInterface;

If the controller class uses other classes from different namespaces, similar lines must be added for each class.
I took the code used from Drupal core for the Tracker module as example. The Tracker module shows its tracker page on /activity/{user} using a controller to render it. See TrackerController.php.
  /**
   * Checks access for the users recent content tracker page.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user being viewed.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The account viewing the page.
   *
   * @return \Drupal\Core\Access\AccessResult
   *   The access result.
   */
  public function checkAccess(UserInterface $user, AccountInterface $account) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user
      ->id() == $account->id())->cachePerUser();
  }

The custom access callback is defined in tracker.routing.yml.
tracker.users_recent_content:
  path: '/activity/{user}'
  defaults:
    _controller: '\Drupal\tracker\Controller\TrackerController::buildContent'
    _title: 'My recent content'
  requirements:
    _permission: 'access content'
    _custom_access: '\Drupal\tracker\Controller\TrackerController::checkAccess'
    user: \d+

Comment: Each time you use a class from a different namespace, you need to add a line similar to `use Drupal\Core\Session\AccountInterface;` on the top of that file.
Comment: You need to add them in the files where those classes/interfaces are used. Adding them to the *task_notify.module* file, while those classes/interfaces are used in the *TaskNotifyUserController.php* would cause the error message you saw.
Comment: https://git.drupalcode.org/sandbox/zenimagine-3076032/-/blob/master/src/Controller/TaskNotifyUserController.php What's wrong with my code ?
Comment: I just saw that you have updated your answer, thank you but there is an error `RuntimeException: Callable "Drupal\task_notify\Controller\TaskNotifyUserController::taskAccess" requires a value for the "$user" argument. in Drupal\Component\Utility\ArgumentsResolver->handleUnresolvedArgument() (line 142 of core/lib/Drupal/Component/Utility/ArgumentsResolver.php).`
Comment: I rewrote the code basing on the code Drupal core is using on one of its modules.
Comment: It does not work because I have a blank page with the error of the previous comment
Comment: I have updated my question
Comment: I applied the answer but I have an error. I have updated my question `RuntimeException: Callable "Drupal\task_notify\Controller\TaskNotifyUserController::taskAccess" requires a value for the "$user" argument. in Drupal\Component\Utility\ArgumentsResolver->handleUnresolvedArgument() (line 142 of core/lib/Drupal/Component/Utility/ArgumentsResolver.php).`
Answer: In TaskNotifyUserController::Task you can access the current user with Drupal::currentUser(). Then compare that id with the id from the current Request, or if you're dealing with a node, the node's author's id (uid). If they don't match, issue a RedirectResponse or regular Response('', Response::HTTP_FORBIDDEN).
Comment: The [answer from @kiamlaluno](https://drupal.stackexchange.com/questions/294991/how-can-i-allow-the-current-user-to-only-see-their-own-page/294999#294999) is the better solution, because access checks in routes can do other things like control the visibility of menu items which your code in a controller can't. However, if you need to deny access from the inside of a controller then throw AccessDeniedHttpException, see https://drupal.stackexchange.com/questions/215627/programmatically-redirect-users-to-the-default-access-restricted/215633#215633
Comment: Thanks! Good to know
Comment: I have updated my question


what area of math for studying mathematical laws as a logical system?

Question: As a relative beginner trying to understand math more deeply, I'm trying to learn more about the mathematical laws (the laws of the operations $+, -, \times, \div$)
For example, I know the basic laws (the ones that are just taken to be true) -- the commutative, associative, and distributive laws. What area of math (what books to read) would I find things like how subtraction is defined from addition (and how division is defined from multiplication), and the presentation of the various laws of subtraction and division as they relate to the basic laws and how to prove them. Some examples:
$n-(m+k) = (n-m)-k$
$\frac{k}{m}+\frac{n}{m}=\frac{k+n}{m}$
$\frac{\frac{n}{m}}{\frac{k}{l}}=\frac{n\times l}{m\times k}$
How to derive and prove such laws (and many others like them)?
Thank you
Comment: Subtraction is defined from addition only when the field $\mathbb{F}$ has an additive inverse. That's math-speak for, subtraction only exists when "0" (the additive identity for the integers) is in the set.
Comment: The laws you described in example 1) Associative law, distributive law 2) closure law 3) not part of the axioms, but it can be proven
Answer: The rules you speak about are the subject of elementary algebra.
It can be a bit difficult to find places where they are derived in rigorous detail, because elementary algebra is usually taught to children who don't particularly care for mathematical rigor, and so many textbooks will focus on indoctrinating students with the correct rules, and at best try to present informal arguments that they work rather than something that satisfies mathematical standards of proof.
There must surely be textbooks out there that do present proper derivations, but rather than searching for them, I would suggest you look for an introduction to abstract algebra instead. Abstract algebra studies rules of operation that act on things that are not ordinary numbers, but where the rules of operation satisfy laws that are like those of arithmetic to a greater or smaller extent. Among other things it provides a vocabulary for describing how "arithmetic-like" a particular set of operations are, and since it's working in a context where not all of the usual laws may be available, introductory texts will usually place some emphasis on how some laws can be derived from others, rigorously.
Answer: Generally, one would need a good experience with number systems to understand the properties of numbers thoroughly well. In order to begin understanding what makes up those laws, just read about them and see if you can make something of it.
http://www.purplemath.com/modules/numbprop.htm
http://en.wikipedia.org/wiki/Peano_axioms
I suggest you read "How to write proofs: A strategic approach" to get you started on proof-writing.
Comment: According to Google there is no book or any other web page other than this containing phrase "How to write proofs: A strategic approach".