Non-existence of bijective, continuous function from $(0,1)$ to $[0,1]$

Question: The problem : Give example of a continuous, onto function from $(0,1)$ to $[0,1]$. Is it possible for such a function to be one-one?
My partial solution : For the $1^{st}$ part of the question, I came up with this example -
$f : (0,1) \to [0,1]$ given by $f(x)=\sin\big({2\pi x}\big)$
This is continuous and onto, but not one-one.
What I'm asking : For the $2^{nd}$ part of the question, I feel that it should be provable that there cannot exist a continuous, onto, one-one function from $(0,1)$ to $[0,1]$ (If not, we need a counter-example). Any help regarding this proof (or what would really surprise me, a counter example)?
Thanks in advance.
Comment: **Hint:** think about $f^{-1}\left(0\right)$.
Comment: $[0,1]$ is compact and $(0,1)$ not. In addition which property must $f$ have?
Comment: Wouldn't such a function have to be strictly monotone, so map open intervals to open intervals?
Comment: May be we the assumption for $f$ is wrong, Can we really asssume such $f$?
Answer: Bijective continuous map implies the function is monotone, now $f(x)=0$ for some $x\in (0,1)$.
We know there exists a real number $y\in (0,x)$ and a real number  $z\in (x,1)$.
Now since $f(x)=0$ and the function is bijective then both $f(y)$ and $f(z)$ are greater than $0$ so the function was decreasing somewhere in $(y,x)$ and increasing somewhere in $(x,z)$, contradicting the monotonicity of $f$.
Comment: Thanks. To make it more tight (possibly), we may take $w$ such that $0 < w < \min\{f(y),f(z)\}$. By the Intermediate value theorem, there exists $t_1 \in (y,x)$ and $t_2 \in (x,z)$ such that $f(t_1)=f(t_2)=w$, contradicting the fact that $f$ is a bijection.
Answer: Suppose $f$ is bijective, then $f$ must be strictly increasing or decreasing function. W.l.g. take $f$ to be increasing. Then $\exists x\in (0,1)$ such that $f(x)=1$. Now take $x<y<1$, since $f$ is increasing, $f(y)>1$, which leads to contradiction.
Comment: https://math.stackexchange.com/questions/752073/continuous-injective-map-is-strictly-monotonic

We can append the answer by @Hagen von Eitzen up there.
Answer: Assume there exists $x \in (0,1)$ such that $f(x) = 0$. Then, by openness of $(0,1)$, for some $\epsilon > 0$, the interval $(x-\epsilon, x+\epsilon)$ is in the interval $(0,1)$.
If now $f$ is one-to-one and onto, either $f(x-\epsilon) < f(x)$ or $f(x+\epsilon) < f(x)$. This contradicts the fact that we want $f$ to map to the closed interval $[0,1]$.
Answer: If $f: A\rightarrow B$ is a continuous map, then $f$ pulls closed sets in $B$ to closed sets in $A$. Given, $f$ is onto and $[0, 1]$ is closed. So its pre-image should be closed. But its pre-image $(0,1)$ is not cloed in $\mathbb{R}$. A contradiction. So we can't have such $f$
Comment: not correct (0,1) is closed in (0,1)


azure data factory dependencies

Question: I have two activities in my azure data factory.
Activity A1 = a stored proc on a sql db. Input=none, output = DB (output1). The stored proc targets the output dataset.
Activity A2 = an azure copy activity ("type": "Copy") which copies from blob to same sql db. Input = blob, Output = DB (output2)
i need to run activity A1 before A2 and i cant for the world figure out what dependencies to put between them.
i tried to mark A2 as having two inputs - the blob + the DB (output1). if i do this, the copy activity doesn't throw error, but it does NOT copy the blob to db (i think it silently uses the DB as the source of copy, instead of blob as source of copy and somehow does nothing).
if i remove the DB input (output1) on A2 it can successfully copy blob to DB but i no longer have the dependency chain that A1 needs to run before A2
thanks!
Answer: I figured this out - I was able to keep two dependencies on A2, but just needed to make sure of the ordering of the 2 inputs. Weird. Looks like the Copy activity just acts on the FIRST input - so when i moved the blob as the first input it worked! :) (earlier i had the DB output1 as first input and it silently did nothing)
<code> "activities": [
        {
            "type": "Copy",
            "typeProperties": {
                "source": {
                    "type": "BlobSource"
                },
                "sink": {
                    "type": "SqlSink",
                    "writeBatchSize": 0,
                    "writeBatchTimeout": "00:00:00"
                }
            },
            "inputs": [
                {
                    "name": "MyBlobInput"
                },
                {
                    "name": "MyDBOutput1"
                }
            ],
            "outputs": [
                {
                    "name": "MyDBOutput2"
                }
            ],
            "policy": {
                "timeout": "01:00:00",
                "concurrency": 3,
                "retry": 3
            },
            "scheduler": {
                "frequency": "Day",
                "interval": 1
            },
            "name": "AzureBlobtoSQL",
            "description": "Copy Activity"
        }
    ],
</code>
Comment: Yes, in ADFv1 that is the way MSoft told us to do this.  Good find!

azure data factory dependencies


A simple explanation of PACF plot

Question: I am presenting some ACF and PACF plots to colleagues. I can explain how to interpret the plots and how to determine p and q based on what the plots look like, but I cannot find a simple intuitive explanation of what a PACF plot actually means.
I have read the explanation here, but am finding it a tad long winded: https://people.duke.edu/~rnau/411arim3.htm
Answer: An intuitive description of PACF can be "the amount of correlation with each lag that is not accounted for by more recent lags".
Autocorrelation satisfies a property that we could call dampened transitivity. If $x_t$ is correlated with $x_{t-1}$ by some amount $\rho<0$, then $x_{t-1}$ is correlated with $x_{t-2}$ by $\rho$. This implies that $x_t$ is correlated with $x_{t-2}$, although by some amount smaller than $\rho$.
Partial autocorrelation computes the "pure" correlation between $x_t$ and $x_{t-2}$ by removing the "transitive" correlation, that is, the amount of correlation explained by the first lag, and recomputing. For the partial autocorrelation between $x_t$ and $x_{t-3}$, we will remove the correlation with both $x_{t-1}$ and $x_{t-2}$ and recompute, and so on.
You can add some geometric flavour to the explanation. You can picture your time series at each lag as a vector in space. A highly autocorrelated series would look something like this.

The time series with lag 0 could be the vector at the bottom, for instance, the one above the series at lag 1, and the other one is lag 2. The autocorrelation translates to this setting as a large projection of each vector onto each other.
However, what happens if we remove from the original series the projection onto lag 1?

The projection of the remaining length of series 0 onto series 2 is very small. This corresponds to the PACF at lag 2.
Comment: Thanks so much, this was an excellent explanation! :-)
Comment: (+1) Could you explain a bit more how to interpret those figures? I'm unused to thinking in those terms and it seems useful, but for one thing, I don't know what the axes are supposed to represent.
Comment: If you think of the time series as a random variable, you can think of an observation of the time series as a vector in high-dimensional space, and each lagged series will be a different vector, say $v_0, \dots, v_k$ up to lag $k$. The correlation between a pair of these is then equivalent to the length of the projection of one onto the other, normalized by their respective lengths, simply because of how it is computed. The PAC at lag $k$ is the equivalent to 1) removing from $v_0$ the projection onto the span of $v_1, \dots, v_{k-1}$ 2) measuring the projection of the residual onto $v_k$.

A simple explanation of PACF plot


Count duplicate columns and update the counter column

Question:
Report table Columns:
ID | ipaddress | count | category

I have duplicate ipaddress entries, I want to count the number of each IP and
update the count column for each IP.
I'm able to count the duplicates like so
SELECT ipaddress, COUNT(*) FROM report GROUP BY ipaddress HAVING COUNT(*) > 1 ORDER BY COUNT(*) DESC

 Output

 ipaddress       COUNT(*)
192.168.2.187        16
192.168.6.14         14
192.168.2.17         11
3192.168.3.6         9
192.168.2.77         8

I just need to update each ip with its correct count number.
Answer: You can JOIN in an UPDATE, like so:
UPDATE report r
  JOIN (SELECT ipaddress, COUNT(*) cnt FROM report GROUP BY ipaddress) up
    ON up.ipaddress = r.ipaddress
   SET r.`count` = up.cnt


How to use uploaded images from an image gallery in an article?

Question: Maybe I am not searching for the correct terms, but I am trying to use an image gallery and be able to reference the images in that gallery from an article.  I want to be able to upload the images one time, but then have specific images to be shown in the article, either as a "sub-gallery" or just inline with the text, depending on the context of the article.
Is it just as simple as creating an image tag and setting the source to the relative address inside the drupal site?  Or is there a better way to accomplish what I am trying to do?
Answer: The module Entity reference can do the job.

Entity reference provides a field type that can reference arbitrary
  entities

...ie your gallery files!
With this module you can add an "Entity Reference Field" related to your gallery files to the Article Content Type.
Then, for each Article, you can add 1 or more images among those already loaded.
Comment: Thanks for the information.  I have had to delay the development of my site due to a project, but I will look into this to get it to work.  This sounds like it will do what I am asking for based on the information you provided.  I will hopefully be able to get back to this during this weekend and report my findings.
Answer: Creating galleries is a common request, which can be solved in various ways. Talking Drupal #083 is a great podcast about creating a Gallery, and includes a lot of recommended modules for it. Just to mention a few of them (mentioned on the linked page):

Gallery formatter - https://www.drupal.org/project/galleryformatter
Views Slideshow - https://www.drupal.org/project/views_slideshow
Flexslider - https://www.drupal.org/project/flexslider
Node Gallery - https://www.drupal.org/project/node_gallery
Multiupload  Filefield Widget - https://www.drupal.org/project/multiupload_filefield_widget
Multiupload Imagefield Widget - https://www.drupal.org/project/multiupload_imagefield_widget
Field Focus - www.drupal.org/project/imagefield_focus
pl upload - https://www.drupal.org/project/plupload

So if you're looking for a better way, consider the above list of modules as a possible shortlist to further explore. Which one is going to be "best" (cfr. the "better way to accomplish this" in your question) is a matter of preferences, actual requirements, etc.
Comment: Sounds like I have a bit of work to get to my final solution!  Thanks for the information and I will check out the podcast for further information as well.


Create a content type node programmatically

Question: I have a content type called ip_range and i was trying to create a node programmatically . I tried the follows :
use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
    $data = array(
      'type' => 'ip_range',
      'title' => '192.168.7.100/24',
      'field_ip_range_gw' => '192.168.7.100',
      'field_ip_range_hidden' => '',
      'field_ip_range_blocked' => '192.168.7.200',
      'field_ip_range_access_type' => 'Blocked',
      'field_ip_threshold' => '20',
      'field_ip_range_sec_zone' => 'C2',
      'field_ip_range_vlan_name' => 'Network58',
      'field_ip_range_vlan_tag' => '4054',
      'field_ip_range_comment' => 'Ip ranges from 192.168.7.100 to 192.168.7.255',
    );
    $node = Drupal::entityManager()
      ->getStorage('node')
      ->create($data);

    $node->save();

But its not creating any . Any idea ?
UPDATE

Its creating the node . But its creating as anonymous user . So i cant see it in front end . That was the problem . How to create it as a admin user ?
Comment: Where did you put this code? In a .module, a .theme?
Comment: this code in drupal root folder and executing this script using drush
Comment: use \Drupal\node\Entity\Node;                                                                   $node = Node::create([
 'type' => 'ip_range',
.
 .   'field_ip_range_comment' => 'Ip ranges from 192.168.7.100 to 192.168.7.255',
]);
  $node->save();
Comment: Have you tried creating a node afterwards to see if the id has been incremented?
Answer: Try this Code in MigrateContentController:
<?php

namespace Drupal\migrate_contents\Controller;
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;

class MigrateContentController extends ControllerBase {

 function migrateContent() {
 $updated = 0;
 $data = array(
   'type' => 'ip_range',
   'title' => '192.168.7.100/24',
   'field_ip_range_gw' => '192.168.7.100',
   'field_ip_range_hidden' => '',
   'field_ip_range_blocked' => '192.168.7.200',
   'field_ip_range_access_type' => 'Blocked',
   'field_ip_threshold' => '20',
   'field_ip_range_sec_zone' => 'C2',
   'field_ip_range_vlan_name' => 'Network58',
   'field_ip_range_vlan_tag' => '4054',
   'field_ip_range_comment' => 'Ip ranges from 192.168.7.100 to 192.168.7.255',
 );
 $node = Node::create($data);
 $node->save();
 $updated++;

 return array(
   '#markup' => $updated,
 );
 }
}

Inside your_module.routing.yml

migrate_contents.migrate_node:
  path: '/migrate-contents'
    defaults:
    _controller: 'Drupal\migrate_contents\Controller\MigrateContentController::migrateContent'
    _title: 'Migrate Contents'
  options:
    _admin_route: TRUE

Note: Clear the cache before proceeding.
Comment: can you update the question as what you have tried?
Comment: Not working though ! , and the script has no errors :(
Comment: Thanks ,man , actually its creating. But its not listing because am creating the node as anonymous user . DO you know how create it as a admin user ?
Comment: okay , i got it working , don't know why its worked because used **Node::create($data);** instead of  **Drupal::entityManager()
      ->getStorage('node')
      ->create($data);** , although am accepting your answer :)


C# WCF service - Access FoxPro DLL in multiuser scenario

Question: I plan to run a WCF-Console-Application as a Windows service.
The WCF-Console-Application calls a FoxPro-DLL to access data in FoxPro-DBF (read and write).
Different clients (WPF-Application) should consume the WCF-Service of the Console-Application to display and edit the data from the FoxPro-DBF.
If only one Client at a time calls the WCF-Console-Application, everything works fine. But the WCF-Console-Application does not handle parallel calls from multiple clients correctly.
The WCF-Console-Application consists of these classes:

main Class: derived from ServiceBase, can be either called from console or started as service
public class Service : ServiceBase
 {
        public ServiceHost serviceHost = null;
    const string CONSOLE = "console";

    public Service()
    {
        this.ServiceName = "ServiceTest";
    }

    public static void Main(string[] args)
    {
         if (args.Length == 1 && args[0].Equals(CONSOLE))
        {
            new Service().startConsole();
        }
        else
        {
            ServiceBase.Run(new Service());
        }
    }

    private void startConsole()
    {
        Console.WriteLine(string.Format("{0}::start Service...", GetType().FullName));
        OnStart(null);

        Console.WriteLine(string.Format("{0}::ready (ENTER to stop)", GetType().FullName));
        Console.ReadLine();

        OnStop();

        Console.WriteLine(string.Format("{0}::stop Service", GetType().FullName));

    }

    protected override void OnStop()
    {
        if (this.serviceHost != null)
        {
            this.serviceHost.Close();
            this.serviceHost = null;
        }
    }

    protected override void OnStart(string[] args)
    {
        if (this.serviceHost != null)
        {
            this.serviceHost.Close();
        }

       this.serviceHost = new ServiceHost(typeof(Server.TestServer));
       this.serviceHost.Open();

}

ServiceInstaller: installs the Service, derived from Installer

[RunInstaller(true)]
public class InstallService : Installer
{
    public InstallService()
    {
        process = new ServiceProcessInstaller();
        process.Account = ServiceAccount.LocalSystem;
        service= new ServiceInstaller();
        service.ServiceName = "ServiceTest";
        service.Description = "ServiceTest";
        service.DisplayName = "ServiceTest";
        service.StartType = ServiceStartMode.Automatic;

        Installers.Add(process);
        Installers.Add(service);
    }
}

static class for accessing the FoxPro-DLL

public static class DataAccess
{
    public static foxprotest.foxprotest accessData = new foxprotest.foxprotest();
}

ITestServer, Interface with the ServiceContract

[ServiceContract(Namespace = "http:/localhost.TestServer", SessionMode = SessionMode.Allowed)]
public interface ITestServer
{
    [OperationContract]
    String loadData(int id);
}

TestServer, implementation of ITestServer

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class TestServer : ITestServer
{
    public String loadData(int id)
    {
                    //set table
        DataAccess.accessData.CTABLE = "patient";
                    //set ID
          DataAccess.accessData.NPATIENT = id;
        //fetch the data
        DataAccess.accessData.FetchData();
                    //return data as XML
         return  DataAccess.accessData.CRESULT;
    }
}

This is how the App.Config looks like: the binding is set to netTcpBinding
  <system.serviceModel>
    <services>
      <service name="Server.TestServer" behaviorConfiguration="MyFileServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8888/"/>
            <add baseAddress="net.tcp://localhost:52/"/>
          </baseAddresses>
        </host>
        <endpoint address="TestServer" binding="basicHttpBinding"
          name="b" contract="Server.ITestServer" />
        <endpoint address="TestServer" binding="netTcpBinding"
          name="c" contract="Server.ITestServer" />
      </service>
    </services>
<behaviors>
  <serviceBehaviors>
    <behavior name="MyFileServiceBehavior">
      <serviceMetadata httpGetEnabled="true" />
      <serviceThrottling maxConcurrentCalls="80" maxConcurrentSessions="80"
          maxConcurrentInstances="80" />
    </behavior>
  </serviceBehaviors>
</behaviors>
</system.serviceModel>

I used svcutil.exe to generate the output.config and TestServer.cs for the WPF-Application.
The FoxPro-DLL is built as multi-threaded COM server, it is registered correctly and VFP9T.DLL is used. There is a little delay in the function loadData(), to test the parallel calls. When I call the DLL from multiple FoxPro-Instances, everything works as expected. If I include the dll into the WPF-Application and call it from there, it also works. Only with multiple calls through the WCF-Console-Application, it does not work correctly.
When I run the WCF-Console-Application through console and make a Console.WriteLine before every line in TestServer.LoadData(), the second call keeps hangig in front of
DataAccess.accessData.CTABLE = "patient";

until the first call is finished. The worst thing is: the returned XML-string is the same when I make parallel calls. Immediately after the first call with an ID, i start a second call with a different ID. For both calls I get the XML-String with the second ID.
What can I change, to get the parallel call to the FoxPro-DLL inside the WCF-Console-Application working? I tried every combination of InstanceContextMode and ConcurrencyMode, without success. Do I need thread safety? If so, what do I have to change?
The use of ODBC or a SQL-Server are no option for this project.
Thanks for any suggestion and advice!
EDIT: If I restart the WCF-Console-Application, only the first parallel test delivers wrong XML-strings. If I do a second parallel call, the returned XML-strings are correct. But the problem with the parallel call still exists.
Answer: BasicHttpBinding does not support sessions. You need to use InstanceContextMode.PerCall to make sure that every call is run in its own thread.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class TestServer : ITestServer
{
   ...
}

Update:
Is DataAccess.accessData static? If yes - that needs to be changed. Static data is shared across multiple threads. Therefore service can return data updated by another call if InstanceContextMode.PerCall is used.  ConcurrencyMode.Single still can be used with mutable static data but you will get all scalability issues of single thread.
Comment: The BasicHttpBinding is only used to get the informations about the WCF-service with svcutil.exe. If I remove the endpoint for the BasicHttpBinding and change the InstanceContextMode to PerCall nothing changes. The behaviour is still the same.

Edit: How can I check on server-side, which binding is used?
Comment: Indeed, DataAccas.accessData is static. If I change this, everything works perfectly! Thanks!
Comment: It's quite embarassing, but the parallel data access is not working again. I extended the WCF-Service with two ServiceContracts (file transfer, start of an external exe). I made two new CS-Files for the interfaces and two additional CS-Files with partial classes. Both worked like expected, but somehow the parallel data access broke down. I'm not sure, if it has to do with the extension, because if I make a blank project with the code above, it is not working as well. There are no static variables, it's still PerCall. Could it depend on how I include the dll into my project?


How should you express a negative binomial distribution (\w gamma function) in an exponential family form?

Question: How should you express a negative binomial distribution (\w gamma function), i.e.
$$f(y_i, \mu, \phi) = \frac{\Gamma (y+ \phi)}{\Gamma(\phi) \Gamma(y+1)}(\frac{\mu}{\mu + \phi})^y (\frac{\phi}{\mu + \phi})^{\phi}$$
where $\phi$ is assumed to be known,
in an exponential family form?
Answer: I'm not sure you can. Unless $\phi \in \mathbb{N}$ is known. You can see the problem in the last line.
\begin{align*}
&f(y_i, \mu, \phi) \\
&= \frac{\Gamma (y+ \phi)}{\Gamma(\phi) \Gamma(y+1)}(\frac{\mu}{\mu + \phi})^y (\frac{\phi}{\mu + \phi})^{\phi}\\
&= \exp\left[\log\left(\frac{\Gamma (y+ \phi)}{\Gamma(\phi) \Gamma(y+1)}(\frac{\mu}{\mu + \phi})^y (\frac{\phi}{\mu + \phi})^{\phi} \right) \right] \\
&= \exp\left[\log\left(\frac{\Gamma (y+ \phi)}{\Gamma(\phi) \Gamma(y+1)}\right) + y \log\left(\frac{\mu}{\mu + \phi}\right) + \phi \log\left(\frac{\phi}{\mu + \phi}\right)  \right] \\
&= \exp\left[\log\Gamma (y+ \phi) - \log\Gamma(\phi) - \log \Gamma(y+1) + y \log\left(\frac{\mu}{\mu + \phi}\right) + \phi \log\left(\frac{\phi}{\mu + \phi}\right)  \right] \\
&= \exp\left[\log\left[y\cdots (y+\phi-1)\Gamma(y) \right] - \log\Gamma(\phi) - \log \Gamma(y+1) + y \log\left(\frac{\mu}{\mu + \phi}\right) + \phi \log\left(\frac{\phi}{\mu + \phi}\right)  \right]
\end{align*}
Comment: Yes I forgot, $\phi$ is assumed to be known.
Comment: ok, well then second to last line is the answer :)


TextArea which adapts Line with Linebreak after x characters

Question: In our ExtJs5.1.2 project we want to have a textarea which breaks the line with a linefeed after x characters entered.
e.g. line should max be 5 characters long when entering 12345 the stay on one line and when entering 6 a new line with 6 is in the textarea.
12345
6

So when the user continuously enters text, the text is autoamtically adapted to a line length of 5.
12345
67890
12345
6...

I tried it with the following extend of the textarea, but it does not work as expected.
The function adaptLines formats the value accordingly to a line length of 5, but it is not populated to the textarea itself.
Ext.define('LineAdaptTextField', {
    extend: 'Ext.form.field.TextArea',

    _removeNewLineRegEx: /\n/g,
    _lineAdaptRegEx: /(.{1,5})/g,

    // called when text is entered, but no effect of value in the textfield
    processRawValue: function(value) {
        value = this.callParent([value]);
        var processed = this.adaptLines(value);

        console.info('processRawValue("%s") to "%s"', value, processed);

        return processed;
    },

    // never be called when entering text
    transformRawValue: function(value) {
        value = this.callParent([value]);
        var transformed = this.adaptLines(value);

        console.info('transformRawValue("%s") to "%s"', value, transformed);

        return transformed;
    },

    // is called but no effect on the textfield
    valueToRaw: function (value) {
        value = this.callParent([value]);
        var rawValue = this.adaptLines(value);

        console.info('valueToRaw("%s") to "%s"', value, rawValue);

        return rawValue;
    },

    // never be called when entering text
    rawToValue: function (rawValue) {
        rawValue = this.callParent([rawValue]);
        var value = this.adaptLines(rawValue);

        console.info('valueToRaw("%s") to "%s"', rawValue, value);

        return value;
    },

    // add linefeed after 5 characters
    adaptLines: function(value){
        var noNewLines = value.replace(this._removeNewLineRegEx, '');
        return noNewLines.replace(this._lineAdaptRegEx, '$1\n').replace(/\n$/, '');
    }
});

For trying out the problem see this Fiddle.
Answer: One of the solution to this issue will be to explicitly setting the formatted value. For example(fiddle), one can make use of change event:
listeners:{
    change: function ( field, newValue, oldValue, eOpts ){
        field.setValue(newValue);
    }
}

The value which is returned by rawToValue method, is available in newValue parameter of change event. Calling the setValue method by passing the newValueas argument will update the texteditor view.
Comment: I tried it and it works as you expressed, but the change event is only fired when the text entering is finished. So the user see when he holds a key that it is formated afterwards. Is there an other posibility to execute the formatting before the text is visible in the textarea?
Comment: Sorry, I don't think that is possible(not in my little knowledge). Because if user holds a key then during that time even the  "rawToValue" function is not call. According to my understanding we can process input only after user has entered it, not during the key holding time.


Como trazer o total de cada coluna no FooterRow de um jqGrid?

Question: Estou usando a propriedade grouping do jqGrid (4.6.0) com jQuery(1.11.0), mas só consegui gerar o total por coluna e não é isso que eu quero, gostaria do total geral.
O jqGrid contém a propriedade grouping que contém o footerrow que seria a fileira de rodapé do Grid (tabela). Alguém sabe como trazer os totais no footerrow?
As propriedades que estou usando no Grid:
$("#respostaRelatorio").jqGrid({
    url: urlRelatorio + "?" + dadosRelatorio,
    colModel: modeloColunas,
    mtype: "POST",
    altRows: true,
    datatype: "json",
    loadonce: true,
    height: "auto",
    width: 1130,
    rowNum: 10,
    rowList: [ 10, 20, 30, 40, 50 ],
    viewrecords: true,
    pager: "#paginacao",
    sortorder: "asc",
    shrinkToFit: false,
    headertitles: true,
    loadui: "disable",
    rownumbers: true,
    autoencode: true,
    caption: "Resultados encontrados",
    deselectAfterSort: true,
    gridview: true,
    idPrefix: "id",
    rowTotal: 4000,
    sortable: true,
    toppager: true,
    resizable: true,
    grouping: true,
    groupingView: {
        groupField: [ 'loginMedico' ],
        groupCollapse: false,
        groupOrder: [ 'asc' ],
        groupSummary: [ true ],
        groupDataSorted: true
    },
    footerrow: true,
    userDataOnFooter: true
});

var modeloColunas = [
    { name: "loginMedico", index: "loginMedico", jsonmap: "loginMedico", label: "Login Médico", sortable: true, sorttype: "text", summaryType: "count", summaryTpl: "total" },
    { name: "nomeMedico", index: "nomeMedico", jsonmap: "nomeMedico", label: "Nome do Médico", sortable: true, sorttype: "text" },
    { name: "perfilMedico", index: "perfilMedico", jsonmap: "perfilMedico", label: "Perfil Médico", sortable: true, sorttype: "text"},
    { name: "tipoSolicitacao", index: "tipoSolicitacao", jsonmap: "tipoSolicitacao", label: "Tipo da Solicitação", sortable: true, sorttype: "text" },
    { name: "cancelada", index: "cancelada", jsonmap: "cancelada", label: "Cancelada", sortable: true, sorttype: "int" },
    { name: "liberada", index: "liberada", jsonmap: "liberada", label: "Liberada", sortable: true, sorttype: "int", summaryType: "sum" },
    { name: "negada", index: "negada", jsonmap: "negada", label: "Negada", sortable: true, sorttype: "int", summaryType: "sum" },
    { name: "pendente", index: "pendente", jsonmap: "pendente", label: "Pendente", sortable: true, sorttype: "int", summaryType: "sum" },
    { name: "total", index: "total", jsonmap: "total", label: "Total", sortable: true, sorttype: "int", summaryTpl: "total"} ];

A imagem do meu Grid, observem que o footerrow aparece vazio:
Comment: Coloca um exemplo no jsfiddle que fica mais fácil de te ajudar.
Comment: Guilherme, como tanto aqui quanto no [SOE](http://stackoverflow.com/questions/22332506/how-to-put-data-on-the-total-footerrow) te pediram um exemplo completo e funcional, te apresento o [jsfiddle.net](http://jsfiddle.net/), busque sempre postar um exemplo autocontido e completo, incluindo dados de exemplo para receber respostas melhores mais rapidamente.
Comment: @AnthonyAccioly utilizo frenquentemente a ferramenta jsfidlle.net, mas acontece que nessa ocasião nao há pagina em html, fazendo com que nao seja necessario utilizar o jsfidle sendo que o que eu fizer la seria basicamente o que passei pra voces aqui.
Comment: Você poderia criar um exemplo funcional somente com a `div` do jqGrid no campo HTML e todo o código JavaScript (incluindo dados de exemplo, que  foi o que faltou aqui), assim fica mais fácil brincar com seu exemplo e te dar uma resposta funcional. A ideia não é empurrar o jsfiddle, apenas te ajudar a obter mais respostas (não sei se a minha resposta resolveu o seu problema).
Answer: De uma olhada nesse exemplo.
Basicamente você deve adicionar uma função loadComplete ao jqGrid para alimentar a linha de resumo:
loadComplete: function () {
    var $self = $(this);
    var somaCanceladas = $self.jqGrid("getCol", "cancelada", false, "sum");
    var somaLiberadas = $self.jqGrid("getCol", "liberada", false, "sum");
    var somaNegadas = $self.jqGrid("getCol", "negada", false, "sum");
    var somaPendentes = $self.jqGrid("getCol", "pendente", false, "sum");

    $self.jqGrid("footerData", "set", {
        loginMedico: "Total:",
        cancelada: somaCanceladas,
        liberada: somaLiberadas,
        negada: somaNegadas,
        pendente: somaPendentes
    });
}

Fonte: SOE - getting the sum using footerdata on jqgrid
Comment: Desculpe pela demora em gratifica-lo com os pontos @AnthonyAccioly, houve uma mudança de projeto e fiquei um tempo sem mexer nesse código, fiz um teste rápido e o teu exemplo funcionou perfeitamente, desde já agradeço a sua atenção e ajuda.


Why do the two sides of theilslopes() not meet neatly at the median value?

Question: I originally posted this question to StackExchange and was requested to move it here, as it relates to domain knowledge rather than code writing.
I've been playing with the theilslopes() function in Python to determine if the trends in two datasets are significantly different. While exploring this question I thought it would be useful to plot the probability distributions of the two datasets. I did this by running 50 different alpha levels through the function and plotting the upper and lower bounds. After doing this I was struck by the gap in the middle of the plot where the trend suddenly jumps from one side to the other through the median value.
Why are the upper and lower confidence levels not equal to the median value for alpha = 0.50?

<code>n_pts = 50
rng = np.random.default_rng()
x1 = rng.random(n_pts)
y1 = (np.random.rand()-0.5)*x1 + rng.random(n_pts)
alphas = [x / 100 for x in range(1, 51)]
temp = alphas.copy()
temp.reverse()
alphas_all = np.array(alphas + temp[1:])
slopes = np.full([len(alphas) * 2 - 1], np.nan)

for ii, alpha in enumerate(alphas):
    a1 = fun_c_theilslopes(y1, x1, alpha=alpha)
    slopes[ii] = a1[2]
    slopes[-1 - ii] = a1[3]
a1 = fun_c_theilslopes(y1, x1, alpha=0.05)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(4.5, 2.0), sharex=False, sharey=False)
axes[0].plot(x1, y1, "ok", ms=1, label="original data")
axes[0].plot(x1, a1[1] + (a1[0] * x1), "r")
intercept = a1[1] + (np.median(x1) * (a1[0] - a1[3]))
axes[0].plot([min(x1), max(x1)], intercept + (a1[3] * np.array([min(x1), max(x1)])),
             c='r', linestyle='--', dashes=(4, 2), label='upper')
intercept = a1[1] + (np.median(x1) * (a1[0] - a1[2]))
axes[0].plot([min(x1), max(x1)], intercept + (a1[2] * np.array([min(x1), max(x1)])),
             c='r', linestyle='--', dashes=(4, 2), label='lower')
axes[0].set_ylabel("y-value")
axes[0].set_xlabel("x-value")
axes[0].set_title("Original data points and slope with \n alpha = 0.05 confidence limits")

axes[1].plot(slopes, alphas_all, "ob", ms=1, label="original data")
axes[1].plot(slopes[[4, -5]], alphas_all[[4, -5]], "or", ms=3, label="original data")
axes[1].plot([a1[0], a1[0]], [0, 0.5],
             c="r", linestyle="-", label="median")
axes[1].set_ylabel("alpha")
axes[1].set_xlabel("slope")
axes[1].set_title("Upper and lower confidence \n limits for each alpha level")
plt.pause(5)
plt.show(block=True)
plt.close()
</code>
Following @Glen_b's answer (the gap is the 50% CI) I have plotted slopes corresponding to confidence intervals down to 1%. The theilslopes() function treats alpha = 0.05 and alpha = 0.95 the same - both are used to calculate the 95% confidence interval.
Answer: A symmetric 95% interval would have (1-0.95)/2 = 2.5% in each tail (outside the interval) and 95% within the interval. A symmetric 50% interval would have 25% in each tail and 50% within the interval (discreteness issues aside, which might change things slightly).
So, naturally, you should tend to expect them to have a gap.
Comment: Thanks for your suggestion - that makes sense considering values from both tails are returned. In the theilslopes() code alpha is symmetrical about 0.5, so alpha values of 0.05 and 0.95 both return the 95% confidence interval.

([link](https://github.com/scipy/scipy/blob/v1.9.0/scipy/stats/_stats_mstats_common.py#L212-L368))

I'll edit the original post to include what I think would be a more accurate figure considering your comment (I note of course the function wasn't designed to look at tighter confidence bounds than 50%).


Common Time Question

Question: I am composing a second species counterpoint in 4/4. The cantus firmus is on the bottom and consists of all quarter notes. The melody I have to compose will consist of all eighth notes.
My question is in regard to downbeats and upbeats. I know the first beat is the downbeat. But when I have an eighth note in between those quarter notes that are not on the quarter note. Is that the upbeat?
I know I know the answer and I am overthinking it.
Comment: I would call the quavers in between the beats the offbeats. With the last beat in 4/4 the upbeat. But I don't know if this is definitive, so this is just a comment.
Comment: please provide an excerpt
Comment: @NeilMeyer https://ibb.co/5sSFQb4 here is the excerpt. I am working on the top line
Comment: Just for the record: looking at the posted image, I think @BobBroadley's comment above is the only answer that was not to some degree confused by the question. Yes, the best term for eighth notes that fall "between" quarter note beats is off-beat.
Answer: A professor of mine in graduate school liked to use the phrase elevator operator to demonstrate that there is a subtle metrical hierarchy.  Imagine that phrase set in eighth notes in a 4/4 bar.  "Op-" comes on beat three.  It carries the principal accent of the word "operator," but it (normally) receives less emphasis than the first syllable of the first word.  Both words also have a secondary accent on their third syllable, which corresponds to beats two and four, and the unstressed syllables correspond to the even-numbered eighth notes.
I say "normally" above because the choice of primary stress actually depends on the context.  For example it would be different depending on whether you're answering the question "is that the superintendent?" or "is that the elevator technician?"  In the second case, you would emphasize "operator" over "elevator."
As a blatant oversimplification, but a good starting point nonetheless, consider this: the second instance of anything is less important than the first.   Beat 3 is less important than beat 1.  Beats 2 and 4 are less important than beats 1 and 3.  And the off-beat eighth notes (the "ands") are less important than the on-beat eighth notes.
Now that we've got that out of the way, on to the terminology.  It is unfortunately not very strict.  In the strictest sense, a measure can have only one downbeat, the first beat after the bar line.  But people don't always use the term in this strict sense.  Suppose there are 16th notes in the measure: in a very real sense the 13th one is the "downbeat" of beat 4.
Furthermore, the meaning of "upbeat" is even looser and more flexible.  In your example, it would not be unusual to hear someone refer to beat 4 as "the upbeat" to the next measure, but it would also be perfectly unexceptional if someone called the last eighth note "the upbeat."  Indeed, I probably wouldn't think twice if someone referred to any of the off-beat eighth notes as the upbeat to the following beat.  It depends on your "zoom level," if you will: what's the tempo?  How long is the phrase?  Are you talking about large-scale structure or more detailed articulation?
And now to your question:

When I have an eighth note in between those quarter notes that are not on the quarter note, is that the upbeat?

I would say that it is an upbeat, but it isn't necessarily the most important upbeat to you at any given moment.
Comment: @DylanCataldo It sounds like this answered your question. Please consider upvoting it as thanks, and accepting it as having provided the information you needed.
Comment: Thanks so much for taking the time to answer my question! :D
Answer: Wikipedia quotes  some definitions:

The downbeat is the first beat of the bar, i.e. number 1. The upbeat is the last beat in the previous bar which immediately precedes, and hence anticipates, the downbeat.
https://en.wikipedia.org/wiki/Beat_(music)#Downbeat_and_upbeat

The second and fourth are weaker—the "off-beats". Subdivisions (like eighth notes) that fall between the pulse beats are even weaker and these, if used frequently in a rhythm, can also make it "off-beat"
https://en.wikipedia.org/wiki/Beat_(music)#On-beat_and_off-beat

Both quotes point to a website which seems inactive now.
I'm not sure if these definitions are used in a strict way by musicians. I think the most universal are the definitions given at the beginning of the page
https://upload.wikimedia.org/wikipedia/commons/8/82/Metric_levels.svg
which mentions "beats" (which can be strong and weak) and "divisions" – notes in between.
Answer: The only concrete, well established, agreed upon bit is the downbeat. The first beat of a bar - any bar. That reflects what the conductor is doing with his baton. Consider what other strokes he does during a bar of 4/4, and the 4th beat is an upstroke, in order to bring it down at the start of the next bar.
So, in basic terms, beat 1 - downbeat, beat 4 upbeat. But it's never as simple as that. Some say beat 3 is down as well. As in 1 - kick, 3 - snare. Both more emphasised than 2 and 4, so it could be said that 2 and 4 are both upbeat.
If you want to subdivide again, into 8s, then (if you want) you can call 1,2,3,4 the down, and all the &s the ups. I think more important is that whoever you are working with establishes, with you at the time, which bits you're all going to call what. Then you all know. Or - be more specific, and call the beats by their names - 'beat 1', the & of beat 3', etc. Makes a lot more sense!
Comment: Unfortunately, I know from bitter personal experience that "down" doesn't necessarily "reflect what the conductor is doing with his baton."  But that says more about certain conductors than about terminology.
Answer: The "measure" lines were introduced in 17th century due to instruments being able to play short notes.
The notation we're stuck today is the half speed common time (may vary by region).
By definition, first and third (major) divisions are regarded as down beat, 2 and 4th as upbeat.
Subdividing further, we will have the same situation, except that the rhythm is there to support the melody, and we have 3rd and 7th subdivisions defined as "relative" downbeats.
(Kick and snare come later; better notion would be "heavy" and "light" metric division, and a relative "heavy" subdivision)

Common Time Question


What is necessary to transform JSON to JSONP

Question: Simple question, if I have static file like this one(generated JSON using mockJSON web)
http://www.webwrx.sk/clients/data.json.txt
What I need to do with this file to change it to JSONP? Do I need to modify it somehow? How is it different to file like api.flickr.com ?
http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any%20&format=json&jsoncallback=?
I have even added () into that file:
http://www.webwrx.sk/clients/data2.json.txt
Still following code wont work:
    var params = _.extend({
        'method': 'GET',
        'url': this.url,
        'cache': true,
        'dataType': 'jsonp',
        processData: true
    }, options);

    return $.ajax(params);

Thank you for any help.
Answer: The only difference between JSON and JSONP format is the presence of the function call in the latter.
JSON:
[ "foo", "bar" ]

JSONP:
callback([ "foo", "bar" ])

Make sure you have a function of that name (here: callback) defined in your code, as it will be invoked:
function callback(jsondata) {
  console.log("I got this:", jsondata)
}

jQuery abstracts the callback naming thing, so you can simply have "jsoncallback=?" in URI (assuming the server is flexible enough to know to name the function according to a parameter), and pass an anonymous function into the jQuery call. jQuery will assign the function to an autogenerated random name, then replace the question mark in your URI with that name. However, you can't do that if you're reading a static file (it will have a fixed function name, so it can't change it dynamically to the autogenerated name jQuery passes it). Here is a working example with jQuery (not mine).


Do you databind your object fields to your form controls?

Question: Or do you populate your form controls manually by a method?
Is either considered a best practice?
Answer: Well, it depends.  I have tended to use databinding wherever I could - it is darn convenient, but on occasion, I'll populate them manually.  Particularly, I find it useful with controls like the DataGridView to use databinding.  It makes filtering quite simple.
Answer: It really depends from what you are trying to achieve.
Databinding is simple and powerful, but if you need more control or some kind of side effect, you can manually populate control from a method.
Personally, I start with a databinding first, than change it later if it is necessary.
Answer: Generally, if data binding business or DAL objects is possible, I would use it. The old axiom holds true: The most error-free and reliable line of code is often the one you didn't have to write. (Bear in mind, however, that you need to know exactly how that data binding occurs, what its overhead is, and you have to be able to trust the framework and your source objects to be error-free!)
You would, as others have mentioned, manually populate if you needed specific functionality not brought to bear directly by binding, or if there is an issue with data binding business/DAL objects (as occasionally happens with certain 3rd-party controls).


What's are the essential skills that I need to arrange songs to guitar?

Question: I'm a beginner guitarist (started five months ago), my goal is to be a fingerstyle player. On the horizon of two years, I want to be able to arrange songs. So what's are the essential scales and theory that I should learn and practice.
Comment: What type of finger style exactly and what kind of music? Arranging piano music for classical guitar is on a different level than doing jazz standards.
Answer: Well if you're only setting yourself 2 years to learn then I wouldn't bother mastering any exotic scales so I'd just stick with the following scales:

major
natural minor
minor pentatonic
major pentatonic
blues

For theory:

learn about chord building
learn about chord progressions (including cadences) and what notes sound good over a particular chord in a progression (or more simply, over the whole progression)
rhythmic techniques (such as note values, rests, time signatures, tempo/speed, rhythmic patterns, stressed notes/syncopation, types of rhythm [i.e. swing/shuffle], rhythmic cadences, etc...)
learn about song form, in particular 32 bar blues and verse-chorus form
learn about melodic techniques such as phrasing techniques, riffs, licks, runs, contour patterns, etc... there'd be different phrasing standards in different styles

The aforementioned points will teach you musicality but you also need to teach yourself instrumental technique which include dynamics and articulation, i.e. producing particular tones (vowel sounds) by picking the string in a particular way and/or at a particular part of the string (i.e. close to the bridge or neck), picking soft or hard, harmonics, percussive effects, hammer-ons/pull-offs, sliding, etc...
All of the above can be learned quite effectively by learning how they're applied in songs and playing those songs.
There's not much point in looking into anything too advanced in the first two years; it's one thing knowing a scale, or composition technique but then mastering them takes years of effort.
Cheers,
Lost C.


2sxc toolbar not visible after upgrade to DNN 9.6.4

Question: After upgrading DNN from 9.3 to 9.6 and upgrading 2sxc to 11.10.1, the 2sxc toolbar is no longer visible.
Here are the errors returned by the console.
What may have happened?
Thanks
Console errors
Answer: It seems your server is not handing out JS files like it should. Basically JS files should just be simply delivered and work.
So the issue you have is not really related to 2sxc - it's an IIS or web.config issue. Best check the windows server event log to see why it doesn't want to hand out JS files.
Comment: The customer has checked the delivery of the js files on the server, everything seems ok.

The problem continues to exist. The problem now occurs randomly. Sometimes the toolbar appears and other times it doesn't appear.

This is a Load Balancing environment, could it be a problem due to this? Could it be that sometimes the settings are not loaded from the chosen machine?

DNN Version 09.06.04 2sxc Versione 11.22


Formato do Json é válido, mas conceitualmente incorreto. Como argumentar?

Question: Recentemente solicitamos um serviço para uma empresa parceira, para consultar algumas pessoas. O serviço foi concebido do zero, para atender uma demanda particular do sistema nosso. Este é um serviço Rest simples, usando JSON como retorno.
Porém, o resultado do serviço disponibilizado me chamou a atenção. Veja um exemplo:
{
    "73317882484": {
        "nome": "Joaquim"
    },
    "55968857463": {
        "nome": "Maria"
    }
}

Embora seja um Json válido, o desenvolvedor entendeu que o campo de CPF seria uma espécie de chave para agrupar as demais informações da pessoa. Então, ao invés dele criar um campo "cpf" com o valor do CPF, ele adotou o próprio CPF como nome do campo. Também, ao invés de criar um array para cada registro, foi devolvido um objeto só.
Tudo indica que o Json retornado foi manipulado, sem ajuda de framework para ser gerado, pois ficaria esquisito mapear este Json para uma classe Java (por exemplo) sem conhecer todos os possíveis retornos de CPF. Enfim, não faz muito sentido.
Eu esperava, como mencionei antes, algo assim:
[
    {
        "cpf: "73317882484"
        "nome": "Joaquim"
    },
    {
        "cpf: "55968857463"
        "nome": "Maria"
    }
]

A pergunta é: como explicar que o formato mencionado antes não é o adequado para um retorno?
Não achei nenhum tipo de referência sobre este assunto. Em uma breve leitura dinâmica pela RFC também não achei nada associado a isto.
Comment: Talvez um argumento válido seja a semântica: solicitar uma **lista** de pessoas é diferente de solicitar um **mapa** de pessoas. Se tenho interesse no todo, faz sentido eu possuir uma lista, se tenho interesse em informações insoladas, faz mais sentido eu ter um mapa.
Comment: Sendo um JSON válido, qualquer ferramenta que se preze do Java para trabalhar com JSON será capaz de analisar os dados corretamente. O que vejo que é que talvez essa não seja a forma mais fácil para você, por isso questionei, para saber se estava claro para você quais eram as limitações. Estando claro isso, sua resposta estaria pronta.
Comment: Em quais pontos exatamente o JSON deixa de ser adequado?
Comment: Na real dá pra você mapear no Java sim... O que você pode fazer é fornecer uma documentação do retorno esperado e dar exemplos
Comment: @Dherik sim, é possível. No caso você mapearia esse atributo para um `Map` ou algo similar a isso
Comment: @Sorack, nunca tinha visto este tipo de formato antes. É possível ler com o [Jackson](https://github.com/FasterXML/jackson)? Espero que não esteja falando de eu também precisar manipular a String do Json... rs.
Comment: @AndersonCarlosWoss, acredito que respondi sua pergunta na minha pergunta. Qual ponto não ficou claro? Um dos argumentos é que não vejo como seria possível ler isto em um framework de "parser" de json, tendo ao final uma lista de pessoas com o CPF e demais informações.
Comment: @Sorack, fiz um teste aqui, de fato dá sim. É que o Anderson disse, é possível, mas para o meu caso não é um formato conveniente. Novamente, nunca tinha visto esta forma de usar Json antes e imediatamente assumi como "incorreta" (que é o ponto principal da discussão)
Comment: Aparentemente faltou escopo sobre a integração, publique exatamente o trecho que refere-se ao JSON que deveria ser retornado, de repente foi pedido um "JSON válido" e foi apenas nisso que ele se preocupou. Se foi esse o caso, adicione o termo lista à solicitação e mostre um exemplo.
Answer: Um argumento válido: "73317882484" não faz parte de estrutura alguma. Os campos em um objeto JSON visam refletir, principalmente, estrutura. A estrutura compõe-se de nomes, códigos (como o CPF), campos demais, outros objetos, etc.
Você também pode argumentar, já que o serviço foi feito para ser consumido por vocês, que simplesmente serializar os dados de um modo que não seja proveitoso a quem desserializa é contra-producente. Também tem o problema da semântica: está implícito que a chave do campo é o CPF, não explícito.
Se fosse para enviar dados assim, você pode argumentar que um CSV seria mais útil.
Answer: Sintaticamente, isso está ok. Mas o problema aqui é na semântica.
A notação com {} representa um objeto. A notação [] representa uma lista.
Você utiliza este serviço com a intenção de encontrar uma lista de pessoas. E não um objeto que contém as pessoas. Logo, se a ideia é obter como resultado uma lista, então você deveria ter um retorno com [], e não com {}.
Além disso, cada pessoa é um objeto (representado com {}), e nele você espera encontrar as propriedades relevantes de cada pessoa, tais como nome, e-mail, telefone e CPF. Logo, o campo cpf deveria estar dentro do objeto representando a pessoa.
Answer: O formato não está incorreto.  O que você pode fazer é definir uma especificação (JSON Style Guide) e fornecer para a empresa.
Alguns exemplos:
- https://google.github.io/styleguide/jsoncstyleguide.xml
- https://jsonapi.org/

Tudo indica que o Json retornado foi manipulado, sem ajuda de framework para ser gerado, pois seria impossível mapear este Json para uma classe Java (por exemplo) sem conhecer todos os possíveis retornos de CPF. Enfim, não faz sentido.

Essa afirmação está incorreta. É possível gerar/mapear um JSON assim.


Migrate Drupal7 to local, user login link redirect to live, how to redirect it to local?

Question: I have changed cookies name and base URL for my local environment, I have also emptied all cache tables, but still it redirects to the live site.
Like http://server1/mysitename/user to https://www.mysitename/user
Answer: My guess is your using the secure login module.
Either:
drush vset securelogin_base_url "http://server1/mysitename/user"

or
drush dis securelogin

Comment: hey I'm new in drupal.. i think drush is command line argument, and I dont know how its work.. is any different way,??
Comment: Yes drush is a command line tool for Drupal, my second command does pretty much the same as your answer below.  Glad you got the problem solved.
Answer: finally found my answer... by google search.. :)
UPDATE variable SET value = 's:1:"0";' WHERE name = 'securepages_enable';

pass this query in db and flush all cache.. :)


In-place upgrade from Windows Server Standard to Enterprise or Datacenter

Question: We ran into a little issue where Windows Server Standard only supports 32 GB of memory, which is depressing to find out when your server was recently upgraded to 48 awesome GB of memory.
Is it possible to do an in-place upgrade from Windows Server Standard (max 32 GB memory support) to Windows Server Enterprise or Datacenter (max 2TB memory support)?
I tried kicking off the Windows Server 2008 setup.exe from within the OS, which gives me an "upgrade" option.. but when I get to the "Where do you want to install Windows" part of the process, it tells me

The partition you selected might contain files from a previous Windows installation. If it does, these files and folders will be moved to a folder named Windows.old. You will be able to access the information in Windows.old, but you will not be able to use your previous versions of Windows

That's... not... what I had in mind when I clicked "upgrade"!
I really don't want to deal with a clean OS install on our production database sever, and would much rather do an upgrade install if at all possible!
Answer: I know this question was originally regarding Server 2008, but I thought I'd post an easier answer that applies to Server 2008 R2 (and Win7 for that matter).  I got the original info from TechNet Server Core blog post.
Starting with Windows 7 and 2008 R2, it's possible to upgrade editions in-place with the dism utility. You can only go upwards in edition (i.e. Standard to Enterprise) and you can't reverse the change. You'll also need the associated KMS Client Setup Key for the version you're going to.  Here's a link to the list of KMS Client Setup Keys
To determine the installed edition, run:
DISM /online /Get-CurrentEdition
To check the possible target editions, run:
DISM /online /Get-TargetEditions
Finally, to initiate an upgrade, run:
DISM /online /Set-Edition:<edition ID> /ProductKey:XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
For example, to upgrade to Enterprise from a downlevel version, run:
DISM /online /Set-Edition:ServerEnterprise /ProductKey:489J6-VHDMP-X63PK-3K798-CPX3Y
Comment: has anyone been able to upgrade to Server 2k8 R2 SP1 after doing this?  I've been unable to.  see: http://serverfault.com/questions/239366/error-when-installing-server-2008-r2-sp1
Comment: KMS Client Keys (required for KMS-activated OS instances' Product Key in the DISM command): http://technet.microsoft.com/en-us/library/ff793421
Answer: I fired up a VM with Windows 2008 Standard on it, and then upgraded it to Enterprise.  At first I couldn't because I didn't have enough disk space available on the C drive.  It appears that 15-20 Gigs of free space is required.  Once I made the C drive larger it upgraded without issue.
When there wasn't enough space it wouldn't upgrade and would require that I install a new OS much like you said you saw.
After I clicked upgrade, the installer confirmed that I wanted to upgrade then it started the upgrade.  It's still running at the moment, but I'm sure it'll finish eventually.
Comment: In fact, I was able to upgrade one of our "spare" servers 100% remotely. And it WORKED! Rebooted and remoted back into a Windows Server 2008 Enterprise server. Pretty impressive..
Comment: My upgrade finished without a problem.  The only thing I can think of is that maybe your C drive didn't have enough space on it to do the actual upgrade.
Comment: +1 for spinning up a VM and testing it! I had to get to bed, so I couldn't... *smile*
Comment: Huzzah for the tireless pursuit of knowledge.
Answer: Microsoft seems to say so: http://technet.microsoft.com/en-us/library/cc755199(WS.10).aspx
This discussion seems to indicate that it's a matter of starting SETUP.EXE from inside the existing OS, as you did: http://social.technet.microsoft.com/Forums/en-US/winserversetup/thread/a9fb29a1-9cad-4d01-9e65-ce9b2b88232b
I'd say spin up a scratch box and give it a try... (or start a community IT support site and wait for some poor addicted fool to do it and report back on whether or not it works... >smile<)
Comment: What, just because I've got nothing better to do at night but build VMs to test stuff out for people on the net?
Comment: So you calling Denny a fool then? :)
Comment: turns out I must have fat-fingered the "UPGRADE" vs. "INSTALL" button choice. I agree, it's working now.
Answer: The message you get makes sense in the context, that this upgrade procedure is the same one for upgrading Windows Server 2003 to 2008. It's a warning that the old version - in your case the 2008 Standard Edition - cannot be used after the upgrade.
During the upgrade process all files, folders and applications associated with the previously installed Windows version are relocated to a windows.old folder and all user settings stored.
Once this task was completed, a clean installation of the new Windows version is performed and all saved user settings will be migrated to the new environment. A successful upgrade will include all applications, settings and user files from the previous operating system installation - in your case from Windows Server 2008 Standard.
Good luck!
Comment: I think I just made a mistake and clicked the wrong button [upgrade/install] in the dialog the 1st time, because now it's definitely doing an UPGRADE. Not getting the warning.
Answer: As the answer is already here, I just thought I'd be the boring guy by stating that the general opinion on doing upgrades on Windows is that this is a feature reserved for home use and even then as a last resort only.
Wipe and redeploy. There are too many things that can go awry during an upgrade that are not immediately apparent.
But good thing it seems to work, I guess ;p
Comment: Well, in case of stuff like Win2008 Standard to Enterprise it's not really an upgrade, it's just adding some more features, as they are essentially the exact same operating system. Of course, exception is stuff like "Non-Service Pack installation CD on a SP1 System".
Comment: Yeah sure, it might be as little as changing a registry value to gain access to enterprise features and limits I guess... but still ^^
Answer: I ran into some problems when trying to upgrade to Enterprise from Standard because our Product keys worked for both editions. Found the reason in this blog. The blog also recommended to use a MS client setup key to do the upgrade. The keys can be found here.
Comment: Enterprise keys work for Standard Edition too. You do not need to enter a key during installation (applies to Server 2008 or Vista and newer OSes only).


Snap Shot widget for dynamic DOM nodes

Question: I'm using Snap.com service to create snapshots to Wikipedia links on my web page. It works fine with the links in the page when page is loaded. But it doesn't work when new links are created and inserted into the web page via Javascript.
The Snap.com script is called once when the page is loaded:

   ...

Is there a way to reacivate their script after new DOM nodes are created in the document? Or some other way to solve this issue?
Answer: I've found the solution by inspecting Snap.com sources.
The following code forces Snap.com to reprocess the page:
SNAP_COM.shot_main_js_called = false;
SNAP_COM.shot_main_js();

Snap Shot widget for dynamic DOM nodes


Kerastuner for LSTM

Question: I am working on a text classification problem and trying to use Kerastuner to identify the best configuration for my LSTM network. Below is the code for same:
keras Tuner
def build_model(hp):

  num_hidden_layers =1
  num_units = 8
  dropout_rate = 0.1
  learning_rate=0.01

  if hp:
    num_hidden_layers = hp.Int('num_hidden_layers', min_value=2, max_value=100, step=5)
    num_units = hp.Int('num_units', min_value=50, max_value=2000, step=50)
    dropout_rate = hp.Float('dropout_rate', min_value=0.1, max_value=0.5)
    learning_rate = hp.Float('learning_rate', min_value=0.0001, max_value=0.01)
    momentum_rate = hp.Float('momentum_rate', min_value=0.5, max_value=0.9)
    vocab_size = len(tokenizer.word_index)+1
    max_sequence_length = 500
    embedding_size = 300

  model = tf.keras.models.Sequential()
  model.add(tf.keras.layers.Embedding(input_dim=vocab_size , output_dim=embedding_size, input_length=max_sequence_length , weights=[embedding_matrix], trainable=False))

  for _ in range(0,num_hidden_layers):

    model.add(tf.keras.layers.LSTM(num_units))
    model.add(tf.keras.layers.Dropout(dropout_rate))

  model.add(tf.keras.layers.Dense(1, activation='sigmoid'))

  model.compile(
      loss = 'mse',
      optimizer =tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=momentum_rate),
      metrics = [tf.keras.metrics.BinaryCrossentropy(name='binary_crossentropy')]
  )
  return model

class CustomTuner(kerastuner.tuners.BayesianOptimization):
  def run_trial(self, trial, *args, **kwargs):
    kwargs['batch_size'] = trial.hyperparameters.Int('batch_size', 128,1024, step=32)
    super(CustomTuner, self).run_trial(trial,*args,**kwargs)

tuner = CustomTuner(
    build_model,
    objective=kerastuner.Objective('val_loss','min'),
    max_trials=2,
    executions_per_trial=1,
    directory='/dbfs/FileStore/GDPR_Dev/Data/',
    project_name = 'nn_logs_lstm_30062021',
    overwrite=True

The code fails with the below error:
ValueError: Input 0 of layer lstm_1 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 50)
Can anyone please help me with this?
Answer: Currently, your data is two-dimensional (N x M), however, input data should be three dimensional. To solve this you should reshape your input as to a N x M x 1 matrix as follows:
x = np.reshape(x, (x.shape[0], x.shape[1], 1))

If your input was multivariate, then the desired shape of the input would be N x M x K, where k is the number of dimensions

Kerastuner for LSTM


counting events given a period of time in anylogic

Question: I want to plot the number of events (e.g., crimes) every year in a population of agents. This isn't counting the population in a state using a statechart, but an event that I recorded on the field "action" of a transition with rate x (e.g., crime = crime + 1;). So, an agent might have committed 5 crimes, another one 7, and so on, over a year.
I tried resetting the crime variable (crime = 0;) every year, but the plot goes from zero to some number, again to 0, jumping to another number again, and so on...
Any ideas?
Answer: Easy. I just have to set the recurrence time of the plot to 0.999 year instead of 1 year.


Is there a reason not to store data from messaging app in android sms databases?

Question: I built a messaging app that allows users to send and receive sms messages along with other types of messages. Right now I am storing all of the sent and received messages in Android's default databases that hold all sms messages. (content://sms/inbox and content://sms/sent) Is there any reason why this would be a bad idea? I know I could use my own database but unless there is a reason I should I like the simplicity of using the database that already exists on the users phone.
Also will all android devices from all manufacturers have their sms databases in the same place that I will be able to access or will their be issues across different devices and manufacturers?
Comment: As you are creating a replacement app for messaging, and are putting messages into the existing database, the last thing you would want, is someone being able to delete a targets messages. Sql injection prevention is important for ALL databases. I just bring it up, as you are connecting to their message database, and the last thing you want is someone losing messages that are not necessarily anything to do with you app. http://en.wikipedia.org/wiki/SQL_injection . Its mainly an issue if you are inserting the message directly into the DB. `INSERT INTO messagetable VALUES(msgeText)` or something
Comment: one thing to note, is to make sure you havent left it open to sql injection attacks.
Comment: Can you explain further?
Comment: You should write your app in such a way that user won't be able to delete messages which weren't created by your app.
Comment: The idea is that my application would be an sms replacement app, I assumed synchronization with the existing app would be preferred. But that is something to take into consideration
Answer: It is perfectly ok to use existing databases. This is the way many existing messaging apps work.
Comment: Generally the behavior should be consistent across different manufacturers.
Comment: I should have asked this is my question but will all android devices from all manufacturers have their sms databases in the same place that I will be able to access or will their be issues across different devices and manufacturers?
Comment: Thank you @DamianJeżewski I suppose I will have to test across multiple manufacturers to be sure
Answer: I can't answer for all users, but I imagine a significant number of them (myself included) would object to having non-SMS messages stored in the same database as SMS messages.
If I used your app, and then opened up the stock SMS app and saw non-SMS messages there, I'd go on a rampage.
Comment: Well you would be using my app to send sms messages as a replacement for your default sms application. The hope was that if you decide to uninstall the app you wouldn't lose your messages.
Comment: I understand that, but my point is that if, for whatever reason, I open an SMS app, I should see ONLY SMS messages.  If your app combines SMS messages with messages from another source and displays them seamlessly, then that's fine, but it if screws up how other apps show messages (for example, by inserting non-SMS messages into the SMS message database), then bad.
Comment: I understand, thank you for your input, my application would be doing the first, storing them seamlessly.
Comment: There's a difference between displaying seamlessly and storing seamlessly.  Displaying seamlessly doesn't affect anything else on the device.  Storing them seamlessly by using the SMS database will affect other apps, and not in a good way.  Suddenly my stock SMS app will be displaying (for example) Google Talk messages, and that's not expected or desired (in most cases).  If I want to see SMS messages, I use the SMS app, if I want to see all messages, I use an app like yours (that doesn't screw up the SMS database).
Comment: Right now my application is doing both, storing and displaying messages seamlessly
Comment: In my opinion, displaying seamlessly is great, storing seamlessly is not, unless you're using your own database to do it, for the reasons I've stated above.


concatenate dynamic value in nested sql statement java

Question: I tried finding information on it,but there doesn't seem to be examples on it.
I have this line:
long userID = user.getId();
String query = "select userclient.username from twitter_content.userclient where userclient.userid = " +
            "(select follower.followerid from twitter_content.follower where follower.followerid = userclient.userid and follower.userid = "+userID+")";

but Eclipse reads the "userID" as a string,and not as a variable.How can I make Eclipse read "userID" as a variable?
Comment: What does this have to do with Eclipse? What do you mean by _"Eclipse reads the "userID" as a string?"_ Where/how? I don't see a "read" happening anywhere. In fact, all you're doing is assigning 2 variables.
Comment: What I meant was I want the variable userID to be passed as a dynamic value in the where clause (in the last part of the SQL statement),not as part of a string in that SQL statement.But it seems that I had not concatenate the statement properly.
Answer: Best practice would be to use PreparedStatement and input parameters for the placeholder ?.
Example usage (from JavaDocs):
PreparedStatement stmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?");
stmt.setBigDecimal(1, 153833.00)
stmt.setInt(2, 110592)

Applying that example to your case, you would get something like:
// prepare connection "conn" earlier
long userID = user.getId();
PreparedStatement stmt = conn.prepareStatement("select userclient.username from twitter_content.userclient where userclient.userid = (select follower.followerid from twitter_content.follower where follower.followerid = userclient.userid and follower.userid = ?)");
stmt.setLong(1, userID);

Answer: TRy this::
long userID = user.getId();
StringBuilder queryBuilder = new StringBuilder("select userclient.username from twitter_content.userclient where userclient.userid =");
queryBuilder.append("(select follower.followerid from twitter_content.follower where follower.followerid = userclient.userid and follower.userid = ?)");
PreparedStatement stmt = con.prepareStatement(queryBuilder.toString());
stmt.setInt(1, userId);


Do optimization problems written in argmax form represent a function?

Question: If I write
$$\hat{x} = \underset{x}{\text{argmax}}\ f(x,y)$$
can I assume that what is to the right hand side (RHS) of the equal sign is a function in the rigorous sense of the word? Under what conditions does the RHS represent a function, i.e. $\hat{x} = g(x,y)$ for some function $g$?
Comment: One possible way (out of several) to read this notation is that it's equivalent to an assertion $$\hat x \in \{x\in\mathcal{X}\mid \forall_{x^\prime\in\mathcal X}\, f(x,y)\ge f(x^\prime,y)\}$$ where the domain $\mathcal X$ (which, in this example, may depend on $y$) is implicitly understood.  With this understanding you should have little trouble answering your question.
Answer: To view argmax as a function, other than the trivial "constant" function, you would need to make it a function of one or more arguments, which could be, for instance, input data specifying a particular instance of a class of optimization problems.  In your case, y could be the input data, i.e., the argument of the argmax function. But the optimization variable x, would not also be an argument of the argmax function (other than in a trivial sense).
Argmax may not exist. For instance, sup may exist, but not max (you can fix that deficiency by changing to argsup instead of argmax).  Also, the optimization problem may be infeasible, in which case the argmax does not exist.
Argmax itself needs to be clarified as to whether it means an argument value which is a global maximum, or whether it could be a local maximum which is not a global maximum.
And generally (even if argmax is defined to mean only a solution which is a global maximum), it could be a multivalued function, because there may be more than one argument value achieving the global maximum.
If you view the maximum (or sup) objective value as a function, some of these problems go away, for instance, an infeasible maximization problem can be, and customarily is, defined to have optimal objective value = $-\infty$. Also, globally optimal objective value will be unique, even if more than one argument value achieves it. Although optimal objective value would be multivalued if you allow local as well as global optimal objective values.
Some of these matters go away for certain classes of optimization problems, such as convex (local vs. global), strictly convex objective (uniqueness of optimal argument value). For clarification purposes, in this context, convex means when viewed from the perspective of the equivalent minimization problem, i.e., that the objective function being maximized is concave, and the constraint region is convex.
Comment: What I think you're telling me is that if the feasible set is not empty and a unique maximum exists within this set, then there exists a function that returns this value. If there is not a unique maximum then for one input value the RHS would potentially return several different values which a function cannot do.
Comment: There is such a thing as a multivalued function, https://en.wikipedia.org/wiki/Multivalued_function , which is what I was referring to. BTW, regarding "there exists a function that returns this value", the existence of a function doesn't mean that humans, aided by computers, are necessarily able to compute the numerical value(s) of this function which exists.


How do I interpret $y=\sin(9x)$ or other such formulae?

Question: I'm working through Math for Physics and they have a number of formulae like $y=\sin(9x)$ or y=4cos(x/2) or fx=tan(x)/x.  It's been 40 years since I did this stuff.  I thought sine and cosine were for angles but these don't look like angles to me.  And the book talks about radians which always seems to be measured in pi, so they don't seem to be radians.   I'm trying to envision what the example is, rather than just do the math but I can't envision it if I don't know how to interpret it.   How to I interpret these equations?  Is the x an angle, or a radian or something else?
Comment: Is it possible for you to take an online course or a community college course? Your questions are valid but at this level, you are better off with an instructor.
Comment: I looked at the link to the book. Take a look at the sections 1.1 and 1.3. Radian measurement is the natural way to define an angle on.a circle. That should be explained in section 1.3. Make sure you understand 1.1 fully. You want to make the transition from thinking about formulae to thinking about functions. None of the material is filler. Mathematics builds on itself. Even if the material makes sense while reading it, you won't truly understand it until you do some problems.
Comment: Argument for trig functions like sine is an angle. In this case, the angle is $9x$. It does not matter what units we use to measure the angle, it's still the same angle.
Comment: @JohnDouma I'm using Khan Academy along with the book mentioned above.  But this is a question that they just don't seem to answer.
Comment: @JohnDouma I had noticed even before you mentioned it that I have to  understand each section before moving on.  But for some reason I'm just not getting this particular thing.   In section 1.3, it seems to say that all angles are measured with pi as the unit of measuring radians.  Which would be the same as saying measurements of length are measured using feet units of inches.  So I could say that I'm 74 inches tall, or I could say that I'm 6 1/6 feet tall.   So is it y=sin (9pi x) ?
Comment: No. Imagine two rays emanating from the center of.a circle of radius $r$. These rays intersect the circle at two points, say $A$ and $B$. The angle between the two rays is defined to be the ratio of the arc length of the circle between $A$ and $B$ to the radius of the circle. Since the circumference of a circle is $\pi\times\text{diameter}=\pi\times (2r)=2\pi r$, the angle that we normally call $360^{\circ}$ is $\frac{2\pi r}{r}=2\pi$ radians. Therefore, we get that $360^{\circ}=2\pi$ radians which is the same as saying there are $\pi$ radians for every $180^{\circ}$.
Comment: Trig functions take radians as arguments. Therefore, $9x$ is in radians. Also, notice that radians are defined to be arc length divided by radius which is length divided by length which is a pure number. We call them radians but they really have no units.
Comment: @JohnDouma thanks. Now I can envision the question.  9 rad would be a little more than 1 1/2 times around a circle.  9x rad would be some ratio of that.   It took me a while, but now I can envision what the problem is talking about.
Answer: The convention in mathematics and physics is that the arguments are measured in radians, as those are the "natural" units for the trigonometric functions.
For example, only when using radians to measure $x$ does the simple formula for the derivate of the sine hold:
$$ \frac{d}{dx} \sin(x) = \cos(x). $$
As angles measured in radians are dimensionless numbers you don't need to write down a unit (if disambiguation or emphasis is needed, one can of course use $\text{rad}$).
That the quantities you see in problems are given as multiples of $\pi$ has the simple reason that the full circle has an angle of $2\pi$. So e.g. the right angle is $\pi/2$ in radians (and giving such numbers as decimals would be highly inconvenient).
Comment: Do you think someone who says "And the book talks about radians which always seems to be measured in pi, so they don't seem to be radians. " understands what a derivative is? I don't even know what a derivate is.
Comment: I think you've given me two answers.  In the first case you seem to say that I'm dealing with radians, so the problem becomes y=sin(9rad x)    But later you say that the problems are given as multiples of pi, so the problem becomes y=sin(9pi x)      As I said earlier, I'm trying to envision the angles in question.  When I think of pi, I think of 3.14.   So 90 degrees is 1.57rad      As I said, all questions concerning rad seem to be in multiples of pi.  I have yet to see a question that says 9 rad or 3 rad or anything else, unless that's what I'm looking at now.
Comment: It dawned on me in the middle of the night.  I have to stop thinking of pi as 3.14, and just think of it as "1".   What I was trying to do was sort of like if you gave me a measurement of 9 yards, and I was trying to work with 822.96 centimeters.   Sure, it is possible to convert, but it is just not the right way to do it. I should do all of the work in yards; 1/2 yard, 1/3 yard, etc.   Makes much more sense now!  I should think of one pi, two pi(s), three pi(s),    I like thinking of three pies!
Answer: Radian (rad) is a measurement unit for angles,
just like degree (°) is.
You can convert between these units by
$$180°=\pi\ \text{rad}$$
However, the unit $\text{rad}$ is special, because it is
defined as arc length divided by radius.
$$1\ \text{rad}=1\ \frac{\text m}{\text m}= 1$$
So you may omit the unit $\text{rad}$ if you like.

And the book talks about radians which always
seems to be measured in pi, so they don't seem to be radians.

This is a misunderstanding. Radians are not measured in $\pi$.
But the angles being simple multiples or fractions of $\pi\ \text{rad}$
are quite common, for example
$$\frac{\pi}{2}\text{ rad}=90°$$
$$\frac{\pi}{4}\text{ rad}=45°$$

I thought sine and cosine were for angles but these don't look like angles to me.

When you have an expression being an argument to an trigonometric
function (like $9x$ in $\sin(9x)$), then this expression might
interpretable as an angle.
But actually it can be anything which is dimension-less.
Comment: Its funny because you've done exactly what the books do and relate all angles as multiples of pi, rather than simply as radians.   That's fine if we are dealing with angles like 90 or 180 or 270 or 360.  Those are only 4 out of the 360 possible degrees.  What if we are dealing with an angle like 17 degrees?  If I want to do the math on that, I don't think I'd want to put it as a multiple of pi.  I'd just rather use radians on their own, so 17 degrees works out to 0.297 rad.
Answer: Consider the unit circle, i.e., a circle with its center at $(0, 0)$, and a radius of $1$.  Start at the point $(1, 0)$ and move clockwise $\theta$ units of length along the circle.  Then $\sin(\theta)$ is simply the $y$ coordinate of that point, and $\cos(\theta)$ is the $x$ coordinate.

And the angle between the $x$ axis and the line through $(\cos\theta, \sin\theta)$ has a measure of $\theta$ radians.
Note that when $\theta = 2\pi$, you get back to the same point you started $(\cos(2\pi) = 1, \sin(2\pi) = 0)$.  Thus, we say that there are $2\pi$ radians in a circle.  Equivalently, a radian is $\frac{1}{2\pi}$ of a circle, or $\frac{180}{\pi}$ degrees.

Why would we describe as, say, $\frac{\pi}{6}$ radians, instead of $30°$, or
$\frac{1}{12}$ of a turn?  Well, the main reason for that it makes calculus simple.  With radians, we have:
$$\frac{d}{d\theta} \sin(\theta) = \cos(\theta)$$
$$\frac{d}{d\theta} \cos(\theta) = -\sin(\theta)$$
with no awkward extra constants.  If you haven't learned what derivatives area, that's probably not going to make sense to you.  So in the meantime, just think of $\pi$ as a funny symbol for a $180°$ angle.

The argument to $\sin$ or $\cos$ isn't necessarily an angle, though.  Sine waves have the useful property of being smooth, periodic functions, so they're often used to model more general periodic functions.  For example, we could model a location's temperature at a given time as:
$$f(t) = A\sin(2\pi t + \alpha) + B\sin(\frac{2\pi t}{365.2425} + \beta)$$
where:

$t$ = amount of time, in days, since an epoch.
$A$ = estimated difference between daily high and low temperatures.
$B$ = estimated difference between summer and winter temperatures.
$\alpha$ and $\beta$ = constants determined by the time of day ($\alpha$) or year ($\beta$) at which to start the wave.

Thus, you might see $\sin$ or $\cos$ show up in contexts that aren't directly related to geometry.


How to convert hook_filter and hook_filter_tips in Drupal 7?

Question: I have trouble converting my custom modules in D7. Found a how-to here http://drupal.org/node/224333 but not so clear to me. This how my code in D6.
/**
 * Implementation of hook_filter().
 */
function custom_inline_filter($op, $delta = 0, $format = -1, $text = '') {

  switch ($op) {
    case 'list':
      return array(0 => t('Custom Inline Filter'));

    case 'description':
      return t('Substitutes @inline tags with the uploaded inline images of the node.', array('@inline' => ''));

    case 'settings':
      break;

    case 'no cache':
      return FALSE;

    case 'prepare':
      return $text;

    case 'process':
      return custom_inline_substitute($text);
      break;

    default:
      return $text;
  }
}

/**
 * Substitute inline image placeholder comments with inline image divs.
 * This function is usually called by hook_filter.process but also by template.php (used for RSS).
 *
 * @param $content
 * @param $node_id
 * @param $rss
 */
function custom_inline_substitute($content, $node_id = NULL, $rss = FALSE) {

  // Get nid from argument

  if ($node_id) {
    $nid = $node_id;
  }
  // Get nid when a node is displayed

  elseif (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
  }
  else {
    return $content;
  }

  // Instantiate inline image class

  $inlineImg = new CustomInlineImage($nid, $rss);
  return $inlineImg->substitute($content);
}

/**
 * Implementation of hook_filter_tips().
 */
function custom_inline_filter_tips($delta, $format, $long = FALSE) {

  if ($long) {
    return t('You may link to uploaded images within the current node using the wysiwyg editor toolbar icons.
      The Custom Inline Filter is to replace added image placeholders with uploaded inline images.'
    );
  }
  else {
    return t('Use the wysiwyg editor toolbar icons to display uploaded images inline.');
  }
}

Comment: I am relatively new to Drupal and still learning API which a bit new to me.
Answer: The code you should use in Drupal 7 is similar to the following one.
function custom_inline_filter_info() {
  $filters['custom_inline_filter'] = array(
    'title' => t('Custom Inline Filter'),
    'description' => t('Substitutes @inline tags with the uploaded inline images of the node.', array('@inline' => '')),
    'cache' => TRUE,
    'process callback' => 'custom_inline_substitute',
    'tips callback' => 'custom_inline_filter_tips',
  );

  return $filters;
}

function custom_inline_substitute($text, $filter, $format, $langcode, $cache, $cache_id) {
  // …
}

function custom_inline_filter_tips($filter, $format, $long) {
  if ($long) {
    return t('You may link to uploaded images within the current node using the wysiwyg editor toolbar icons.
      The Custom Inline Filter is to replace added image placeholders with uploaded inline images.'
    );
  }
  else {
    return t('Use the wysiwyg editor toolbar icons to display uploaded images inline.');
  }
}

The documentation for the input filter implementations is provided in more than one page:

hook_filter_info()
hook_filter_FILTER_settings()
hook_filter_FILTER_prepare()
hook_filter_FILTER_process()
hook_filter_FILTER_tips()

For the parameters passed to the callbacks defined from an input filter module, see hook_filter_FILTER_settings(), hook_filter_FILTER_prepare(), hook_filter_FILTER_process(), and hook_filter_FILTER_tips().
In particular, it is relevant to know that:

$filter is a filter object, not a string that identifies the input filter; it contains information about the input filter, but what an input filter implementation normally uses is $filter->settings, which is an array of settings defined from the input filter.
$format is a format object, described in filter_format_save(); it doesn't contain information that an input filter normally uses.

To notice that only the first one is actually a hook; the others are callbacks. The documentation shows them as hooks because a limit of the module used to add documentation pages on Drupal.org API: A documentation page is added only if the function is contained in a module (a Drupal core module, or a third-party module), or it is a hook described in a .api.php file.
Comment: After clearing the cache the page generated a fatal error. `Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase->execute()`
Comment: Your code is trying to use an object as if it were a string. Verify you are not using any string operator with an object, or that you are passing an object to a function that is expecting a string.
Answer: hook_filter() has been replaced with hook_filter_info(); the docs page has all the information you need on how to build a valid filter info array for Drupal 7.
hook_filter_tips() was removed in favour of the tips callback property of the array you return from hook_filter_info(). The basic example from the docs page should help it make sense, but there's a more advanced example on the same page if this is too simplistic:
$filters['filter_autop'] = array(
  'title' => t('Convert line breaks'),
  'description' => t('Converts line breaks into HTML (i.e. <br> and <p>) tags.'),
  'process callback' => '_filter_autop',
  'tips callback' => '_filter_autop_tips',
);

Answer: You can compare the D6 and D7 version of the node linke module. It's a filter module that has been ported from D6 to D7.


Binary arithmetic: why hash%n is equivalent to hash&(n-1)?

Question: I have been studying Java HashMap source code, the part of it which decides in what bucket to put an object and saw this change in Java 7 (8) as compared to Java 6.
Additionally I conducted numerous experiments and both expressions yeild the same result:
hash % n
and
hash & (n - 1)
where n - the array length that must be power of 2.

I just cannot figure out why is it true? Is there any theorem or some math laws that prove these statement are equal? Basically I want to understand the inference and prove the equivalence of those two statements.
PS. If n is not a power of 2 number, the equivalence breaks immedeately.
Comment: Think about the bits in `(n - 1)` if `n` is a power of 2 (or `((1 << i) - 1)`, if you want to simplify the constraint on `n`)
Comment: Hint: one less than a power of 2 written in bicimal consists of solely 1 bits. Not much point in saying much more since the "duplicate police" on the Java tag pretty much close everything off.
Comment: @Bathsheba: Only when there's a duplicate. If you think this is a duplicate of another question, I suggest you show which one. Plenty of Java questions *aren't* closed as duplicates.
Comment: @JonSkeet: Although I haven't indulged myself in performing any real analysis on this, I observe that the dupe closures on the Java tag are considerably more lateral than ones in C and C++, to the point where I've pretty much given up contributing on the Java tag. So I see "Only when there's a duplicate" as the intention, but often not followed in many instances.
Comment: @Bathsheba: Whereas I see the opposite - I see lots of duplicate questions being asked and correctly closed as duplicates, but few non-duplicate questions being closed. I certainly don't think it's useful to complain about the "duplicate police" when there's no sign that *anyone* has voted to close this question as a duplicate.
Comment: @JonSkeet: Very well, let's agree to disagree.
Answer: If n is a power of two that mean its binary representation is 10000....,
n-1 for that matter is 1111111... with one less digit.
That means that binary &-ing with (n-1) preserves just exactly the number of bits in k that n-1 has set.
Example n = 8: 1000, n-1 = 7: 111
&-ing for example k = 201: 11001001
k % n = k & (n-1) = 11001001 & 111 = 001 = 1.
%-ing with a power of 2 means that in binary you just strip everything away that is above (including) the only set bit: for n = 8 that means stripping everything over (including) the 4th bit. And that is exactly what the &-ing does at well.

A side effect is that using & is commutative: hash & (n - 1) is equivalent to (n - 1) & hash which is not true for %, the jdk source code in many places uses the later, e.g. in getNode
Comment: Could you please elaborate on this statement "%-ing with a power of 2 means that in binary you just strip everything away that is above (including) the only set bit..", it is not so obvious, you see. I feel like this is the key to understand the entire conversion...
Comment: @AndreasGelever sure, I will do elaborate today evening. In the meantime compare it to mod base 10. for example 34567 % 1000 -> Strip everything above including 1000 -> 567
Comment: Well, I can see that the trick works for numbers like 10, 100, 1000 etc. Which probably can be generalized like ...all numbers multiple of the base of numeral system (but I am not sure about this statement). But it is still intuitive and not apparent for binary system at all... so the question remains open.
Answer: Think about the bits in (n - 1) if n is a power of 2 (or ((1 << i) - 1), if you want to simplify the constraint on n):
If n is, say, 16 (= 1 << 4), then n - 1 is 15, and the bit representation of 15 and 16 (as 32-bit ints) are:
 1 = 00000000000000000000000000000001  // Shift by 4 to get...
16 = 00000000000000000000000000010000  // Subtract 1 to get...
15 = 00000000000000000000000000001111

So just the lowest 4 bits are set in 15. If you & this with another int, it will only allow bits in the last 4 bits of that number to be set in the result, so the value will only be in the range 0-15, so it's like doing % 16.

However, note that this equivalence doesn't hold for a negative first operand:
    System.out.println(-1 % 2);    // -1
    System.out.println(-1 & (2-1));  //  1

Ideone demo
Answer: The arithmetic rule for integer / and % is:
x*(y/x) + (y%x) = y

What about a negative hash -4 and a positive n 8?
8*0 + (-4%8) = -4

Hence modulo maintains the sign.
-4 % 8 = -4
-4 & 7 = 4

Or:
int t = hash%n;
if (t < 0) {
   t += n;
}
assert t == (hash & (n-1));

So in the earlier java with %n hash had to be positive to begin with.
Now hash may be negative, more solid and better hashing.
So that was a sound reason for this subtle change in java source code.

Background:
2n is a 1 followed by n-1 0s (in binary).
2n - 1 is n-1 1s.
Hence for n being a positive power of 2, and some positive number h:
h % n == h & (n-1)

Another usage is to count bits in an int. The class Integer has just such a function.
int bits = 0;
while (x != 0) {
    x &= x - 1;
    ++bits;
}


PowerDNS & Log4j

Question: I'm running a PowerDNS on Linux.
It looks like PowerDNS is vulnerable to the new log4j-exploit. Is there any way I can disable the Log4j?
From my research it looks like you can change the logging method to syslog, but I'm not quite sure on how to do that.
Comment: Why should PowerDNS be vulnerable? It can't contain Log4j, it's not even written in Java.
Comment: That's not PowerDNS, that's a different component. You should clarify that your question is about the REST component, not PowerDNS itself.
Comment: https://help.internetx.com/pages/viewpage.action?pageId=26515072  They write about how they use log4j at "Configuration of the Logging"
Answer: PowerDNS is written in C++, not Java. PowerDNS does not use Log4J.
However, you should always check where your logs go. It is possible that somewhere down the line (for example, in Elasticsearch) they do hit Log4J.
I wrote a blog post about this.

PowerDNS & Log4j


Understanding supervisor strategy in Akka

Question: I'm reading Akka documentation and now I'm at the section about UntypedActors. I decided to try some examples:
Here are my actors:
Parent
private static class MyUntypedActor extends UntypedActor{

    public void onReceive(Object message) throws Exception {
        System.out.println("Recieved: " + message);
    }

    @Override
    public void preStart(){
        getContext().actorOf(AnotherUntypedActor.props()).tell("Process it", getSelf());
    }

    public static Props props(){
        return Props.create(MyUntypedActor.class);
    }
}

Child
private static class AnotherUntypedActor extends UntypedActor{

    public static Props props(){
        return Props.create(AnotherUntypedActor.class);
    }

    public void onReceive(Object message) throws Exception {
        System.out.println("My: " + message);
        throw new RuntimeException("Crashed: " + getSelf());
    }
}

main:
public static void main(String[] args) throws TimeoutException {
    ActorSystem system = ActorSystem.create();
    Inbox inbox = Inbox.create(system);
    ActorRef actorRef = system.actorOf(MyUntypedActor.props());
    inbox.send(actorRef, "Message");
}

so, my child actors experienced failure and I thought the it should have notified the parent somehow.
But what I recieved was this:
Recieved: Message
My: Process it
[ERROR] [07/14/2016 19:05:13.726] [default-akka.actor.default-dispatcher-4] [akka://default/user/$a/$a] Crashed: Actor[akka://default/user/$a/$a#-950392568]

What does the supervision do actually? Child actor had faulted and what? I got just an error message in a log. What does supervisorStrategy mean? It's by default set to
OneForOneStrategy(-1,Duration.Inf,true)

Answer: By using supervisor strategy, you decide what should be done with supervised actor if it fails. You have to override supervisionStrategy() method within your parent actor and define strategy. I.e. (not sure if it's correct since I use Scala for Akka)
@Override
    public SupervisorStrategy supervisorStrategy() {
        return strategy;
    }

    private static SupervisorStrategy strategy =
            new OneForOneStrategy(10, Duration.create("1 minute"),
                    t -> {
                        if (t instanceof SomeException) {
                            return restart();
                        } else {
                            return stop();
                        }
                    });

In this case, if SomeException occurs, actor will be restarted. Otherwise, it will be stopped. You can choose one of four strategies.
Read documentation
Tip: Create specific exceptions!
Comment: So, the principal purpose of the strategy is to define a way of how to react if exception's thrown. And the actual decision's made within the decider function. By default it does nothing (as far as I can tell), right?
Comment: Pretty much. And as far as I remember, default is `Restart`.