text:
Q: Issue with sending email in python Below is the code which works perfectly fine if placed in main script. Send ana email to recipient in outlook
import smtplib
import base64

filename = "/tmp/test.txt"

# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)  # base64

sender = 'webmaster@tutorialpoint.com'
reciever = 'amrood.admin@gmail.com'

marker = "AUNIQUEMARKER"

body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)

# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body,marker)

# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, reciever, message)
   print "Successfully sent email"
except Exception:
   print "Error: unable to send email"

BUt when I call it in funtion
filename = "/tmp/test.txt"
def send_email(filename):

    # Read a file and encode it into base64 format
    fo = open(filename, "rb")
    filecontent = fo.read()
    encodedcontent = base64.b64encode(filecontent)  # base64

    sender = 'webmaster@tutorialpoint.com'
    reciever = 'amrood.admin@gmail.com'

    marker = "AUNIQUEMARKER"

    body ="""
    This is a test email to send an attachement.
    """
    # Define the main headers.
    part1 = """From: From Person <me@fromdomain.net>
    To: To Person <amrood.admin@gmail.com>
    Subject: Sending Attachement
    MIME-Version: 1.0
    Content-Type: multipart/mixed; boundary=%s
    --%s
    """ % (marker, marker)

    # Define the message action
    part2 = """Content-Type: text/plain
    Content-Transfer-Encoding:8bit

    %s
    --%s
    """ % (body,marker)

    # Define the attachment section
    part3 = """Content-Type: multipart/mixed; name=\"%s\"
    Content-Transfer-Encoding:base64
    Content-Disposition: attachment; filename=%s

    %s
    --%s--
    """ %(filename, filename, encodedcontent, marker)
    message = part1 + part2 + part3

    try:
       smtpObj = smtplib.SMTP('localhost')
       smtpObj.sendmail(sender, reciever, message)
       print "Successfully sent email"
    except Exception:
       print "Error: unable to send email"

It send an email with blank sender, recipient and message. The previous code  sends an email with an attachment perfectly fine. I believe I am doing silly mistake in defining the variables but cant make out.
Not sure what am I doing wrong.
Can you please help


text:
Q: Code execution takes more time in Angular I have below line of code in my angular component and it takes more than 5 minutes when record count is more than 100000.
this.getGlobalRecordsCol.map(value => {
        const dataCheck = this.retainPrevSelectedRecords.some(checkArr => checkArr.RecordId === value.RecordID
          && checkArr.Ctr === value.Ctr);
        value.isDisabled = false;
        value.Selected = dataCheck ? false : value.Selected;
      });

Is it possible to optimize this logic to minimize the execution time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Returning PK of gridview when updating or inserting (ASP.NET, C#) I require all changes such as inserts, updates and deletes to a table to be auditted, and I'm using a simple SQLDataSource and GridView with automagically generated INSERT/UPDATE/DELETE statements. Problem is, when a row is updated I want to get the ID (primary key) and put that into the auditting table - but because the only parameters for the UPDATE query is the actual data and not the primary key, I don't know how to access this information. Here is my UPDATE query:
InsertCommand="INSERT INTO [NominalCode] ([VAXCode], [Reference], [CostCentre], [Department], [ReportingCategory]) VALUES (@VAXCode, @Reference, @CostCentre, @Department, @ReportingCategory)"

And here is the codebehind for auditting:
protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
    {
        string fields = e.Command.Parameters[0].Value.ToString() + "," + e.Command.Parameters[1].Value.ToString() + "," + e.Command.Parameters[2].Value.ToString() + "," + e.Command.Parameters[3].Value.ToString() + "," + e.Command.Parameters[4].Value.ToString();
        System.Security.Principal.  WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
        string[] namearray = p.Identity.Name.Split('\\');
        string name = namearray[1];
        string queryString = "INSERT INTO Audit (source, action, item, userid, timestamp) VALUES (@source, @action, @item, @userid, @timestamp)";
        using (SqlConnection connection = new SqlConnection("con string removed for privacy"))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Parameters.AddWithValue("@source", "Nominal");
            command.Parameters.AddWithValue("@action", "Update");
            command.Parameters.AddWithValue("@item", fields);
            command.Parameters.AddWithValue("@userid", name);
            command.Parameters.AddWithValue("@timestamp", DateTime.Now);
            connection.Open();
            try
            {
                command.ExecuteNonQuery();
            }
            catch (Exception x)
            {
                Response.Write(x);
            }
            finally
            {
                connection.Close();
            }
        }
    }

A: Okay, I feel stupid. The ID was located in the WHERE clause of the SQL query of course! And I pasted in the INSERT command for some reason.


text:
Q: Convert Image to Grayscale with array matrix RGB java I'm creating an Image filter program and I want to convert a coloured picture to a grayscale picture with the help of an array matrix.
This is what I have currently:
import java.awt.Color;
import se.lth.cs.ptdc.images.ImageFilter;

public class GrayScaleFilter extends ImageFilter {

    public GrayScaleFilter(String name){
        super(name);
    }

    public Color[][] apply(Color[][] inPixels, double paramValue){
        int height = inPixels.length;
        int width = inPixels[0].length;
        Color[][] outPixels = new Color[height][width];
        for (int i = 0; i < 256; i++) {
          grayLevels[i] = new Color(i, i, i);
        }

        for(int i = 0; i < height; i++){
            for(int j = 0; j < width; j++){
                Color pixel = inPixels[i][j];
            outPixels[i][j] = grayLevels[index];
            }
        }
        return outPixels;
    }
}

It looks like I'm supposed to use this formula: ((R+G+B)/3)
I want to create an array matrix like this:
 Color[] grayLevels = new Color[256];
    // creates the color (0,0,0) and puts it in grayLevels[0],
    // (1,1,1) in grayLevels[1], ..., (255,255,255) in grayLevels[255]

This is the class I'm refering too when I want to use grascale:
public abstract Color[][] apply(Color[][] inPixels, double paramValue);

protected short[][] computeIntensity(Color[][] pixels) {
    int height = pixels.length;
    int width = pixels[0].length;
    short[][] intensity = new short[height][width];
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            Color c = pixels[i][j];
            intensity[i][j] = (short) ((c.getRed() + c.getGreen() + c
                    .getBlue()) / 3);
        }
    }
    return intensity;
}

Any feedback on how I can achieve this? Instead of using outPixels[i][j] = new Color(intensity, intensity, intensity);

A: Build the grayLevels array this way:
for (int i = 0; i < 256; i++) {
  grayLevels[i] = new Color(i, i, i);
}

Then, when you need a certain color, just retrieve it as grayLevels[index].


text:
Q: What is the interpretation of low R-Squared value in Cox Regression Model summary in R? I have a churn dataset which has 79 variables. I commit the cox regression model on the dataset and I get the following result:
Concordance= 0.664  (se = 0.001 )
Rsquare= 0.152   (max possible= 1 )
Likelihood ratio test= 63855  on 16 df,   p=<2e-16
Wald test            = 70941  on 16 df,   p=<2e-16
Score (logrank) test = 75130  on 16 df,   p=<2e-16

Now I am confused as to what I should do to increase my R Squared but it cannot be more than 0.2? What can I infer from this ?

A: Depending on the nature of the data, $R^2$ values in Cox regressions can be quite low. I'm presently working on some clinical survival data for which a model with very good predictive behavior only has an $R^2$ of 0.17. A high $R^2$ would require high precision in predicting the actual times of events, often an unrealistic goal.
The Concordance Index might tell you more about how useful your model is. It is the fraction of pairs of cases in which the actual order of events matches the order predicted by the model. The value of 0.664 shows that you predict the correct order in almost 2/3 of pairs of cases. That might be good enough for your purposes. You also should consider validation and calibration of your model to estimate how well it will generalize to new data, for example with tools provided by the rms package in R.
It might be possible to improve your model, but help on that would require a lot more information about the nature of the data, the predictor variables, the events, and the number of cases. Also, it's somewhat strange that with 79 predictor variables your model only has 16 degrees of freedom. If you did some type of variable selection to reduce the number of variables (e.g., forward stepwise selection) then your results might be suspect and might not generalize well to new samples of data. This classic answer discusses the problems with such variable selection in the context of linear regression, but the issues are the same for Cox regressions.


text:
Q: Как правильно изменить реализацию шаблона репозиторий подгружаемого с помощью интерфейсов для инициализации модели? Доброго времени суток.
Был создан магазин на основе https://github.com/Laracommerce/laracom на ларавел.
В процессе работы было замечено что наряду с подтягиванием реализации под интерфейс вызовом типа:
use App\Shop\Products\Repositories\Interfaces\ProductRepositoryInterface;
связывание которых объявлено в RepositoryServiceProvider (app\Providers\RepositoryServiceProvider.php),
используются прямые вызовы типа use App\Shop\Products\Repositories\ProductRepository;
(например здесь app/Shop/Orders/Repositories/OrderRepository.php)
В коде можно найти несколько подобных примеров и чаще всего прямое указание адреса необходимо для вызова конструкции new Repository(ОбъектМодели).
Не нашел однозначного выхода из данной ситуации, прошу совета тех кто сталкивался с примером качественной реализации.

A: Если я правильно понял, у Вас в коде есть прямые вызовы репозитория, а не через DI, и Вы хотите вызывать его по интерфейсу, а не через new ProductRepository();
Если это так, то вызвать его можно вот так:
$productRepository = app(ProductRepositoryInterface, ['modelObject' => $modelObject]);

В таком случае будет подключена забинденная реализация интерфейса.


text:
Q: How to add multiple of the same provider I'm happy with the "Online Accounts" of Ubuntu 17.10; having all accounts I need calendar/reminder data from in one place. But unfortunately, I have multiple accounts for, for example, Microsoft. But, I can't seem to add more than one account to my online accounts. I can add an account, no problem, but when I try to add another one, it pops up a new window, but it shows the "approval" part of the account I already added.
Is there a solution or workaround to add more than one online accounts of the same provider?
Any ideas?

A: After adding an account click on that provider again, and you'll see an option to 'Use Another Account'
But I think it's only possible with Google.


text:
Q: Simple example of JQuery Address to manage application state I'm using the jQuery Address library to re-write my URL depending on what the user is doing in the page. The intention is to allow users to bookmark pages and come back later. The page never refreshes as all server interaction is done via ajax.
jQuery Address is writing URLs like this:
http://localhost:9000/#/u/scott_tiger
I need a to set up a route in Play to be able to route that request through to the appropriate controller. So I set this up:
GET     /#/u/{username}                Controller.showUser

This doesn't work though, the route definition gets ignored. I've tried loads of things such as trying to escape the "#" and replacing it with a variable that I've populated with Character.toString(35). None of this works.
Does anyone know how I can either define the route properly or get jQuery Address not to write the "#".
EDIT: The "#" doesn't get sent to the server does it. Doh! OK, question is revised.

A: No. The # and the part of the URL after that is not sent to the server. So your play app on the server will never see such URLs.
HTML5 solution
You need to handle these URLs on the client side using JavaScript. In modern browsers with good HTML5 support, you can modify the address without reloading the page. See Manipulating the browser history on how to do it for these browsers. And see When can I use... for browser support.
#-URLs
On Internet Explorer and older versions of other browsers you need to use # URLs and use JavaScript to load the state (e.g. get the user page /u/scott_tiger in your example). See How to run a JavaScript function when the user is visiting an hash link (#something) using JQuery? for how to do this in JavaScript. Also if a user bookmarks a page with a #-URL you need to reload the state.
See also: What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?
JavaScript libraries
You may use JavaScript libraries to handle this for you history.js is an example. Also bigger frameworks like Backbone.js handle this.

Does anyone know how I can get jQuery Address not to write the "#".

If you don't write the #-part of the URL, the state can not be linked. So you can not get back to e.g. Scott Tigers profile page if you bookmark the page, because the URL is only http://localhost:9000/ and you will arrive on the front page, while the user though he would arrive on the profile page.

A: Armed with my new understanding of URLs (thanks @Jonas) I realised that I'd missed half of the story.
I'm using JQuery Address to change the URL depending on what you click in the application. This works great and on lots of browsers. What I was missing was using JQuery Address to watch for external address changes (bookmarks, history, back/forward) and respond accordingly. i.e. set the page up correctly by firing the appropriate Ajax calls and rendering that data appropriately.
Changing the address
$.address.title("new title describing application state");
$.address.parameter("q", "val1");
$.address.parameter("g", "val2");
$.address.update();

Restoring the state
$.address.externalChange(function(event) {
    var val1 = event.parameters["q"];
    var val2 = event.parameters["g"];
    // do something with those values
});


text:
Q: SQLAlchemy One-to-Many relation with repeated property I will admit I am very new to SQLAlchemy and SQL in general. I am trying to get have a Match which references two Players, where Player.matches back references to any Match where they are either Match.PlayerA or Match.PlayerB.
class Player(Base):
    __tablename__ = "players"
    id = Column(Integer, primary_key=True)
    matches = relationship("Match")

class Match(Base):
    __tablename__ = "matches"
    id = Column(Integer, primary_key=True)
    playerA_id = Column(Integer, ForeignKey("players.id"))
    playerB_id = Column(Integer, ForeignKey("players.id"))

    playerA = relationship("Player", foreign_keys=playerA_id, back_populates="matches")
    playerB = relationship("Player", foreign_keys=playerB_id, back_populates="matches")

The current error I cannot resolve:

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join
condition between parent/child tables on relationship Player.matches -
there are multiple foreign key paths linking the tables.  Specify the
'foreign_keys' argument, providing a list of those columns which
should be counted as containing a foreign key reference to the parent
table.


text:
Q: PHP - Highcharts - PDF Estou usando Mpdf para fazer com que alguns valores que guardei em SESSIONS no php se tornem um relatório, até ai tudo bem, mas a pagina que quero transformar em relatório possui gráficos Js, do Highcharts, não sei como exportar esses gráficos diretamente para o relatório que sera em pdf.
Site: http://carboncal.org/view/brasil/
Passos: Clique em Carbono por filtro(menu) >> calcular carbono >> WHRC

A: Infelizmente o mpdf não suporta javascript, então para que você possa mostrar um highchart no seu pdf você terá que exportar ele em formato de imagem.
Um exemplo disto seria:
var hightchart = $('#container').highcharts().getSVG(); // Pega o highcharts e transforma em SVG.

Envia o resultado por ajax para o php, e depois incluía no seu mpdf:
$html = "Olha um gráfico: ". $_POST['hightchart '];

include 'lib/mpdf/mpdf.php';
$mpdf = new mPDF();
$mpdf->WriteHTML($html);
$mpdf->Output('exemplo.pdf', 'I');

Exemplo: Transformando gráfico em imagem
Documentação: Highcharts Chart.getSVG

A: Pra gerar PDF tenta usar uma biblioteca chamada wkhtmltopdf, é um projeto interessante que transforma em PDF a página renderizada pelo webkit, motor de renderização do Google.
Caso os gráficos fiquem vazios, tente desabilitar as animações do highcharts.


text:
Q: CSS3 not transitioning ease-out with CSS Circular Progress Bars My transition, well, doesn't transition.
https://gist.github.com/TadahTech/0915cd6fc22fa27a94a4
I am completely unsure why there isn't a transition happening, but I assume it's a
simple answer. I've been staring at this for too long and was hoping for some fresh eyes on the issue.
section.progress-container {
    display: block;
    height: 200px;
    width: 200px;
    margin: 2em auto;
    position: relative;;
}

circle#empty {
    stroke: #EDEDED;
    stroke-width: 2em;
}

circle#percent-loaded {
    transition: stroke-dashoffset 1.6 ease-in;
    transition-delay: 1s;
    stroke: blue;
    stroke-width: 2em;
}

The JS
$(function() {

  calculateProgress = function(percentLoaded) {
    var $percentLoadedCircle = $("circle#percent-loaded");

    var radius = $percentLoadedCircle.attr("r");

    var circumference = Math.PI * (radius * 2);

    var arcPercent = ((100 * percentLoaded) / 100);

    var arcLengthOffset = arcPercent * circumference;

    $percentLoadedCircle.css({
      strokeDashoffset: arcLengthOffset
    });
  }
  calculateProgress(100);
});

Index page
<!DOCTYPE html>

    <title>Countdown Test Site</title>
    <meta name="viewport" content="width=device-width, initial-scale=0.1" />
    <link rel="stylesheet" type="text/css" media="all" href="css/style.css">

        <svg height="240" width="240" viewport="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
            <circle id="empty" r="100" cx="120" cy="120" fill="transparent" stroke-dasharray="629" stroke-dashoffset="0"></circle>
            <circle id="percent-loaded" r="100" cx="120" cy="120" fill="transparent" stroke-dasharray="629" stroke-dashoffset="0"></circle>
        </svg>


text:
Q: Wrap text to quote it later in the same document I was wondering if there's a way to do the following:

*

*to wrap an excerpt of text in an environment and to label it;

*to quote it (entirely) later in the same document, via a \ref command or similar.

By doing so, one could modify the wrapped text, without having to update all of the later references to it in the document.
I'm aware that a simple workaround would be to use \input{} both in the first and in the later occurrences of the wrapped sentence; I only wanted to know if there's  something more specific.
More in detail, my purpose is to wrap some text that I have to cite in an answer letter to the reviewer of a submitted paper.
Suppose I wrote in a first version of the paper that:
it is clear that 2+2=5

Now the reviewer makes me pay attention to the fact that there's an error. I correct it and:
1 - in the revised version of the paper I write:
\wraptext{twoplustwo}{it is clear that 2+2=4}

provided that \wraptext{}{} is the command I was looking for;
2 - in the answer to the reviewer, I specify:

the error has been corrected, as you can see in the following reported excerpt:

\citewrappedtext{twoplustwo}

again provided that \citewrappedtext{} is the command to recall the excerpt.
This way, one can later modify again the sentence:
\wraptext{twoplustwo}{it is obvious that 2+2=4}

without having to correct the quotes, too.

A: While the answers "use a command" or "use an environment" seem to be obvious, here's a solution "with batteries included" (@GitHub, ZIP archive):
\documentclass{scrartcl}
\pagestyle{empty}

\newcommand\declquotedtext[2]{\expandafter\def\csname quotedtext@#1 \endcsname{#2}}
\newcommand\defquotedtext[2]{\declquotedtext{#1}{#2}#2}
\newcommand\usequotedtext[1]{\csname quotedtext@#1 \endcsname}

\begin{document}
  \defquotedtext{test}{This is a test text.}

  \declquotedtext{later}{And this is a text declared for later use.}

  This is something completely unrelated.

  \usequotedtext{test}

  \usequotedtext{later}
\end{document}

The command \defquotedtext will accept a label and contents, define the label (for use in \usequotedtext) and print the contents (to avoid repetition). As suggested by Ruben, \declquotedtext will do what \defquotedtext does, without printing the contents:

As usual with commands, be careful with spaces after \defquotedtext and \usequotedtext.
Actually, I assumed that this has been packaged somewhere...
With credits to: What exactly do \csname and \endcsname do?

A: Doing this with an environment is quite easy, by using environ.
The actual implementation depends on what you really have in mind. What I propose can even go in a secondary file that's \input at \begin{document}. The order of the text snippets is unimportant.
\documentclass{article}

\usepackage{environ}

\makeatletter
\NewEnviron{storequote}[1]{%
  \@ifundefined{storequote@\detokenize{#1}}
    {\global\expandafter
     \def\csname storequote@\detokenize{#1}\expandafter\endcsname
     \expandafter{\BODY}}
    {\@latex@error{storequote error: key `\detokenize{#1}' already used}{\@ehd}}%
}
\newcommand{\getstoredquote}[1]{%
  \@nameuse{storequote@\detokenize{#1}}%
}
\makeatother

\begin{document}

\begin{storequote}{funny}
This is a funny quotation.
\end{storequote}

\begin{storequote}{bad}
This is a bad quotation.
\end{storequote}

\begin{storequote}{funny}
This will raise an error.
\end{storequote}

Some text just to call ``\getstoredquote{bad}'' and
some other text for calling ``\getstoredquote{funny}''.
Enough.

\end{document}


text:
Q: How can I reduce space at top of an algorithm? I want to locate my algorithm at the bottom of two-column paper as compact as possible.  On top of the algorithm I see an empty space line, is it possible to remove it, or decrease the space?
my code:
\documentclass[10pt,journal,compsoc]{IEEEtran}
\usepackage{float}
\usepackage{lipsum}
\usepackage{algorithm}
\usepackage{algorithmicx}
\begin{document}
\title{Bare Demo of IEEEtran.cls for\\ IEEE Computer Society Journals}
\markboth{Journal of \LaTeX\ Class Files,~Vol.~14, No.~8, August~2015}%
\IEEEraisesectionheading{\section{Introduction}\label{sec:introduction}}
\IEEEPARstart{T}{his} demo file
\lipsum*[100]

\begin{algorithm}[!bp]
    \caption{The submitJob Function}
    \label{algo-cost}  % \hspace*{\algorithmicindent}
    \vspace*{0.5mm}
    \hspace*{0.45cm} \textbf{Input:} {\(x_{s}, x_{n}\)} \\
    \hspace*{0.45cm} \textbf{Output:} {Returns calculated cost}
    \begin{algorithmic}[1]
        \State{}\(x \gets \phi[p_{n}]\)
        \State{}\(y \gets \phi[d_{n}]\)
    \end{algorithmic}
\end{algorithm}
\lipsum
\end{document}

output (bottom left corner of the page):

Here as you can see there is an empty space on top of the algorithm. When I use \vspace*{-2mm} it did not help. In some cases the space is two lines.

A: This space is governed by \textfloatsep, as can be seen from the general layouts package/documentation (section 6.2 Detailed float layout):

\textfloatsep defines the typical space or separation between the text and a top/bottom float (other, "internal" floats have a separation defined by \intextsep). You'll find the following definition of \textfloatsep within IEEEtran.cls:
\textfloatsep 1.55\baselineskip plus  0.2\baselineskip minus  0.4\baselineskip

This is quite large (1.55\baselineskip), for whatever reason. You can adjust this to suit your needs somewhere in the preamble. Using a smaller primary length/gap like
\textfloatsep = 1\baselineskip plus 0.2\baselineskip minus 0.4\baselineskip

results in a slightly smaller gap (because there's still a small stretch/shrink; the = is optional):

\documentclass[10pt,journal,compsoc]{IEEEtran}

\usepackage{lipsum}
\usepackage{algorithm,algorithmicx}

\textfloatsep = 1\baselineskip plus 0.2\baselineskip minus 0.4\baselineskip

\begin{document}
\title{Bare Demo of IEEEtran.cls for\\ IEEE Computer Society Journals}
\markboth{Journal of \LaTeX\ Class Files,~Vol.~14, No.~8, August~2015}%
\IEEEraisesectionheading{\section{Introduction}\label{sec:introduction}}
\IEEEPARstart{T}{his} demo file
\lipsum*[100]

\begin{algorithm}[!bp]
  \caption{The submitJob Function}
  \vspace*{0.5mm}
  \hspace*{0.45cm} \textbf{Input:} {\(x_{s}, x_{n}\)} \\
  \hspace*{0.45cm} \textbf{Output:} {Returns calculated cost}
  \begin{algorithmic}[1]
    \State{}\(x \gets \phi[p_{n}]\)
    \State{}\(y \gets \phi[d_{n}]\)
  \end{algorithmic}
\end{algorithm}

\lipsum

\end{document}

Adjust it to suit your needs, but know that this is something that is set globally. Also, if this is for a journal submission, such changes are often overridden by the publisher.

A: The issue is that the place indicator is [bp!] so the compiler will arrange things before hand and isn't able to apply spacing tools after, because the positions of the environments in the code aren't the same as in the output. For example just changing the placeholder to [h] produces the following output:

It doesn't have the double spacing like before. And it also allows \vspace{} to function as expected because the placing of the figure relative to the text is unambiguous.
%Example of uncomfortably narrow spacing

\lipsum*[100]
\vspace{-0.2cm} %Now it works as expected
\begin{algorithm}[h]
    \caption{The submitJob Function}
    \label{algo-cost}  % \hspace*{\algorithmicindent}
    \vspace*{0.5mm}
    \hspace*{0.45cm} \textbf{Input:} {\(x_{s}, x_{n}\)} \\
    \hspace*{0.45cm} \textbf{Output:} {Returns calculated cost}
    \begin{algorithmic}[1]
        \State{}\(x \gets \phi[p_{n}]\)
        \State{}\(y \gets \phi[d_{n}]\)
    \end{algorithmic}
\end{algorithm}
\vspace{-0.2cm} %Text afterwards also works as expected
\lipsum

Output:


text:
Q: mailbox extension yii error Tried to install mailbox yii extension, followed install instructions, but got error. Dont know how to fix. This is link to extension http://www.yiiframework.com/extension/mailbox/
Here is error trace:
Alias "mailbox.MailboxModule" is invalid. Make sure it points to an existing PHP file and the file is readable.

Z:\home\localhost\www\Kare2Match\framework\YiiBase.php(316)

304         if($isClass && (class_exists($className,false) || interface_exists($className,false)))
305             return self::$_imports[$alias]=$className;
306
307         if(($path=self::getPathOfAlias($alias))!==false)
308         {
309             if($isClass)
310             {
311                 if($forceInclude)
312                 {
313                     if(is_file($path.'.php'))
314                         require($path.'.php');
315                     else
316                         throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file and the file is readable.',array('{alias}'=>$alias)));
317                     self::$_imports[$alias]=$className;
318                 }
319                 else
320                     self::$classMap[$className]=$path.'.php';
321                 return $className;
322             }
323             else  // a directory
324             {
325                 if(self::$_includePaths===null)
326                 {
327                     self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
328                     if(($pos=array_search('.',self::$_includePaths,true))!==false)

+  Z:\home\localhost\www\Kare2Match\framework\YiiBase.php(196): YiiBase::import("mailbox.MailboxModule", true)

+  Z:\home\localhost\www\Kare2Match\framework\base\CModule.php(282): YiiBase::createComponent("mailbox.MailboxModule", "mailbox", null, array("userClass" => "PersonAbstract", "userIdColumn" => "k2m_internal_id", "usernameColumn" => "nickname"))

+  Z:\home\localhost\www\Kare2Match\framework\web\CWebApplication.php(337): CModule->getModule("mailbox")

+  Z:\home\localhost\www\Kare2Match\framework\web\CWebApplication.php(276): CWebApplication->createController("mailbox")

+  Z:\home\localhost\www\Kare2Match\framework\web\CWebApplication.php(141): CWebApplication->runController("mailbox")

Need help with it.

A: This is a tough one to help on because the solution is actually provided right there in your output: "Make sure it points to an existing PHP file and the file is readable."
So the first thing to check it where is the alias "mailbox.MailboxModule" located and where does it point? Is it to an existing PHP file? If yes, then do the file's permission allow the web server to read it?
To find the alias try a text search through your code. To find the file's permissions go into terminal and do an ls /path/to/theFile.php (on Mac or Linux... Windows, I don't know) If you are working over FTP you can often right click on a file and get a context menu to find out more info about a file's permissions.
To understand file permissions read this.

A: Hey Just Add 'class' property to module 'mailbox' in /protected/config/main.php as follows:
'modules' => array(

   'mailbox'=>
    array(
            'class' => 'application.extensions.mailbox.MailboxModule',
            ..............
            ..............
            'userClass' => 'User',
            'userIdColumn' => 'id',
            'usernameColumn' =>  'username',

    );

If you find this answer is helpful, please vote this one for others to get it easily.

A: Here is another solution:
I think, you have placed 'mailbox' extension in /protected/extensions/. Please place 'mailbox' extension in '/protected/modules'. it resolves your problem.


text:
Q: When to use an array over a pointer, or vice versa My understanding is that pointers can be used, among other things, to allow for you to dynamically allocate memory when you need it (and know how much you need) instead of allocating it statically with arrays upfront.
I struggle with determining when its better to save the computation time of dynamic allocation and opt for a larger memory footprint vs. having a larger memory footprint and using some computation time to allocate only the memory I need.
Can someone shed a little light on this subject? Are there any general rules that might help?

A: Generally, you want to use an array when you know either the total size of the data you'll deal with, or at least a maximum size of data. This is especially applicable if you don't really expect tremendous variation in the size -- if (for example) the variation is from 10 to 20 items, it's probably easiest to just allocate 20 regardless and be done with it (unless each item is really big).
If you have a lot less idea of the size of the data ahead of time, or (and important possibility) might easily be dealing with too much to plan on putting on the stack, dynamic allocation becomes much more useful. The major weakness of dynamic allocation are that if you're ever going to need to know the size, you need to keep track of it yourself, and it's up to you to ensure that you free the memory when you're done with it. Many (especially of the difficult, nagging) problems in C come down to using memory after it was freed, or forgetting to free memory when you were done with it.

A: You should use dynamically allocated memory when:

*

*you don't know how much of memory you will need at compile time

*the amount of memory varies when running

*you need large amounts of memory

You should use statically allocated memory when:

*

*you know the size in compiling time

*the amount of needed memory is low

Using dynamically allocated memory needs the usage of System Calls, this is when you program ask something to the operating system. You have a speed penalty because the process is likely to loose the "processing time" that is given to another process. There are a lot of things that the OS needs to do to accomplish the call. Doing a system call for asking memory is a process much heavier than just writing to an array stored in the process stack.

A: You use a dynamic container when your data is dynamic, or you need to pass the data from different areas of your program.
1 - Dynamic data
Say you've got a list of your neighbors. They build a new house on your street, and you've got to add a guy to the list, but you only allocated enough space for 15 neighbors. This dynamic memory would allow you to increase the size of that container. That's not really how it works. Actually, it finds a new chunk of memory of the necessary size and then copies the old container over.
Or another example. Say you're writing a program that keeps track of an address book. One of your users has ten contacts. Another user is a corporation and there are 50,000 employees that all need to be stored in this address book. You don't want to allocate 50000 spaces for the user who has ten contacts, so you allocate exactly how much you need.
2 - Passing data
When you allocate static data, it is placed on the stack and then inaccessible after out of scope. So if you call some function which generates your array, and then pass the memory address of the array back to its caller, you'll get a runtime error. This is because after that function is exited, the array is out of scope, and it therefore popped off the stack.
However, if you allocate it dynamically, it goes on the heap, and doesn't get free'd until you free it or until the program exits. So you can just keep a pointer to the beginning of the array and use it all throughout your program without worrying about it going out of scope until you want it to.

A: Arrays are simply contiguous chunks of memory. When you declare an array, you have a pointer
int foo[5];

foo (without an index) is a pointer to the first element in that array.
foo[0] = 1;
*foo = 1;

Those do the same thing, as do:
foo[1] = 2;
*(foo + 1) = 2;

When you create an array using int foo[5]; you're creating on the stack. This is local to the current function and once you return from the function it is no longer valid. If you malloc() memory, you're creating the array on the heap (and have a pointer to it)
int *foo = malloc(sizeof(int) * 5);
foo[0] = 1;
*foo = 1;

You have to manage this memory yourself, and free() it when you're done with it:
free(foo);

A: Although this question has an accepted answer. Let me talk about a slightly different thing. In C sometimes you can use an array with size determined at runtime. For example:
void foo (int a[], int n) {
    int buf[n];
    /* do something with buf[] */
}

This kind of arrays get allocated in the stack and is of variable size. The difference from doing malloc is that you do not have to free() the memory; that is taken care of when the function call exists. Of course this also means that you possibly cannot return the address of the array.


text:
Q: web api windows authentication unauthorized on foxxl I hope somebody can help me with the following issue, I have been working on a mvc4 web api running on .net 4.0 and ef code first. I am trying to use basic authentication in combination with the authorize attribute. It works on my Azure trial and also on Localhost but i cant get it to work on foxxl hosting and it keeps asking me for credentials which seem to be invalid when i try it on the foxxl hosting. For testing i am not using https so but this will be included in release version.
Here is some sample code that i have added for basic authentication:
Web config
<system.web>
    <customErrors mode="Off" />
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="Windows" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager defaultProvider="DefaultRoleProvider">
      <providers>
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </roleManager>

    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <add name="BasicAuthHttpModule" type="KlantenBestand.BasicAuthHttpModule, KlantenBestand"/>
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

TestController
        [Authorize]
        public HttpResponseMessage Get()
        {

            String name = HttpContext.Current.User.Identity.Name;

            return Request.CreateResponse(HttpStatusCode.OK, name);
        }

BasicAuthHttpModule
public class BasicAuthHttpModule : IHttpModule
    {
        private const string Realm = "KlantenBestand";
        private static KlantenBestandContext db = new KlantenBestandContext();

        public void Init(HttpApplication context)
        {
            // Register event handlers
            context.AuthenticateRequest += OnApplicationAuthenticateRequest;
            context.EndRequest += OnApplicationEndRequest;
        }

        private static void SetPrincipal(IPrincipal principal)
        {
            Thread.CurrentPrincipal = principal;
            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = principal;
            }
        }

        private static bool CheckPassword(string username, string password)
        {
            var company = db.Companies.FirstOrDefault(u => u.EmailAdress.Equals(username));

            return company != null && company.Password.Equals(Md5Hash(password));
        }

        private static bool AuthenticateUser(string credentials)
        {
            bool validated = false;
            try
            {
                var encoding = Encoding.GetEncoding("iso-8859-1");
                credentials = encoding.GetString(Convert.FromBase64String(credentials));

                int separator = credentials.IndexOf(':');
                string name = credentials.Substring(0, separator);
                string password = credentials.Substring(separator + 1);

                validated = CheckPassword(name, password);
                if (validated)
                {
                    var identity = new GenericIdentity(name);
                    SetPrincipal(new GenericPrincipal(identity, null));
                }
            }
            catch (FormatException)
            {
                // Credentials were not formatted correctly.
                validated = false;

            }
            return validated;
        }

        private static void OnApplicationAuthenticateRequest(object sender, EventArgs e)
        {
            var request = HttpContext.Current.Request;
            var authHeader = request.Headers["Authorization"];
            if (authHeader != null)
            {
                var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);

                // RFC 2617 sec 1.2, "scheme" name is case-insensitive
                if (authHeaderVal.Scheme.Equals("basic",
                        StringComparison.OrdinalIgnoreCase) &&
                    authHeaderVal.Parameter != null)
                {
                    AuthenticateUser(authHeaderVal.Parameter);
                }
            }
        }

        // If the request was unauthorized, add the WWW-Authenticate header
        // to the response.
        private static void OnApplicationEndRequest(object sender, EventArgs e)
        {
            var response = HttpContext.Current.Response;
            if (response.StatusCode == 401)
            {
                response.Headers.Add("WWW-Authenticate",
                    string.Format("Basic realm=\"{0}\"", Realm));
            }
        }

        public void Dispose()
        {
        }

        public static string Md5Hash(string password)
        {
            MD5 md5 = new MD5CryptoServiceProvider();

            //compute hash from the bytes of text
            md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(password));

            //get hash result after compute it
            byte[] result = md5.Hash;

            StringBuilder strBuilder = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                //change it into 2 hexadecimal digits
                //for each byte
                strBuilder.Append(result[i].ToString("x2"));
            }

            return strBuilder.ToString();
        }
    }

EDIT
I also tryed adding the authentication lines to my web.config because my hosting said this would solve the issue. But when i do that and run it localhost it gives me the following error: This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".
<system.webServer>
    <security>
      <authentication>
          <anonymousAuthentication enabled="false" />
          <basicAuthentication enabled="true" />
          <windowsAuthentication enabled="false" />
      </authentication>
    </security>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <add name="BasicAuthHttpModule" type="KlantenBestand.BasicAuthHttpModule, KlantenBestand"/>
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

A: Look at your web.config.
<authentication mode="Windows" />

It is set to Windows Authentication. You will need to remove that line.


text:
Q: QCustomPlot QCPItemEllipse position I have a QCustomPlot Graph with the center (0,0) i want to add an ellipse item around all the data on the graph but there i am only able to set the top left and bottom right positions of the ellipse, this shows almost in the center of the graph but its a bit off because im not able to set the center off the ellipse as center isnt a position its an anchor
does anyone know how i would be able to set the center of my ellipse item to (0,0)?
    QCPItemEllipse *ellipse = new QCPItemEllipse(ui->customPlot);
    ellipse->setAntialiased(true);
    ellipse->topLeft->setCoords(lowestX, highestY);
    ellipse->bottomRight->setCoords(highestX, lowestY);

A: Man, the position of ellipse's center is determined by it's top-left and bottom-right points.
E.g. center.x == (topLeft.x + bottomRight.x)/2 and center.y == (topLeft.y + bottomRight.y)/2. That's how ellipses work in math :).
In your code, center will be in (0,0) if (lowestX + hightX) == 0 & (lowestY + hightY) == 0.
Or maybe I'm not getting what are you talking about?
If you want to move center of ellipse in easy way, you can create class derived from QCPItemEllipse with field QCPItemTracer *mCenterTracer and with following stuff in constructor:
mCenterTracer->setStyle(QCPItemTracer::tsNone);

topLeft->setParentAnchor(mCenterTracer->position);
bottomRight->setParentAnchor(mCenterTracer->position);

topLeft->setCoords(-xRadius/2.0, -yRadius/2.0);
bottomRight->setCoords(xRadius/2.0, yRadius/2.0);

So method for moving center (without changing radiuses) will look like:
void FreakingEllipse::moveCenter(double x, double y) {
    mCenterTracer->position->setCoords(x, y);
}

By the way, you can add following if you want your ellipse to have constant radius in pixels, while it's center is still stick to plot coordinates:
topLeft->setType(QCPItemPosition::ptAbsolute);
bottomRight->setType(QCPItemPosition::ptAbsolute);


text:
Q: Visitor groups using Viewed Pages criterion not working I am working on a page which should use visitor groups to personalize its contents. However, I cannot seem to get the Visited Page criterion to match.
I assume that the Visited Page criteron uses the class EPiServer.Personalization.VisitorGroups.Criteria.ViewedPagesCriterion, which stores the viewed pages in the HttpContext session with the key EPiServer:ViewedPages. Unfortunately, the session key doesn't seem to be added at all when I enter the specified pages.
Has anyone got any idea why it isn't working?

EDIT: I have now tried to implement the Criterion myself, bascially using the decompiled code from EPiServer.Personalization.VisitorGroups.Criteria.ViewedPagesCriterion. It turns out that the criterion subscribes to a VisitedPage event which is supposedly raised when a page is visited. By debugging, I have determined that the event subscription is successful, but the event handler is never called. This means that, for some reason, EPiServer does not raise the event.
I tried to subscribe to the StartRequest event instead, and in this case the handler is called. This begs the question: Why is the VisitedPage event not raised when visiting pages?

A: The VisitedPage event is fired only when a page is shown through a controller which has the ViewedPageCriterionAttribute. The base controller  EPiServer.Web.Mvc.PageController<T> provided by EPiServer has this attribute, so the it works when controllers inherit from this controller.
If you do not wish to use PageController, the attribute has to be used on your custom controller:
[ViewedPageCriterion]
public class MyController<T> : Controller<T> where T : IDefaultModel
{
    // controller implementation
}


text:
Q: How to make my dynamic GAE python website (which uses AJAX POST query extensively) Google Searchable I am developing a website using GAE Python. It has only a few html pages which are available using Django template. The website allows you to search for bus tickets by selecting country, state, city, date, type of bus and other parameters. I use AJAX POST to send all these criteria to the server side(python). The server side performs a NDB query and returns the available bus operators with details for the selected date. This information is returned as JSON data. After the user clicks on a bus operator, I open a popup on the same page and retrieve and display more details using AJAX POST again in the same way.
The URL at the top of my page remains throughout:
http://localhost:8080/search

[right now the website is not complete and so not online, therefore "localhost"]
Problem: I want to make all the bus operators search results on my website google searchable (actually, searchable by any search engine if possible). In other words, I want Google to somehow index my dynamic search result page so that when people search for bus on google, my website and my search page should come in the google search results
I tried Google search and found the following but could not understand the solution.
I did not understand stuff about hash fragment since I have used AJAX POST query string only which do not come in URL like hash fragments.
https://developers.google.com/webmasters/ajax-crawling/docs/specification
http://coding.smashingmagazine.com/2011/09/27/searchable-dynamic-content-with-ajax-crawling/
How to make google search dynamic pages of my site
Hash tag, query string, and Ajaxified search results
I am a novice here and would appreciate any help

A: Search engines will index your results only if they find links to them. In this case, you want these links to be SEO-friendly. There are plenty of articles on how this can be accomplished.
Simply adding a hashtag to your URL after you display the results is easy, but it will not achieve anything.
One solution is to create a site map file and submit it to Google. You can list the most popular (or all, if you don't have too many) results from your database in this site map. In this case you need links in this site map to read like:
myDomain.com/search/?city=London

or
myDomain.com/search/#London

In both cases, your servlet or your app should be able to process this link when a user hits it directly, and display the correct results to a user.


text:
Q: Why do we write "Fourier's law" but "Soret effect"? Can you explain why do we write e.g. Fourier's law, Ohm's law, Newton's law of cooling, etc. but Soret effect, Dufour effect instead of Soret's effect, Dufour's effect? What is the principle?

A: The only authority I've been able to find on this particular question is The Oxford Style Manual (2003), which provides this summary:

12.1.6 Eponymic designations
Names identified with specific individuals may be treated in several ways. Traditionally a disease, equation, formula, hypothesis, law, principle, rule, syndrome, theorem, or theory named after a person is preceded by the person's name followed by an apostrophe and an s [examples omitted]; ... An apparatus, coefficient angle, constant, cycle, effect, function, number, phenomenon, process, reagent, synthesis, or field of study named after a person is usually preceded by the name alone or its adjectival form [examples omitted]. Eponymic anatomical or botanical parts may incorporate the name either as a possessive [examples omitted] or adjectivally [examples omitted]. Something named after two or more people is known by the bare surnames, joined by an en rule [examples omitted].

Regrettably the Oxford manual doesn't explain how this distribution of possessive and nonpossessive forms arose. Bu clearly Fourier's law, Ohm's law, and Newton's (various) laws fall into the traditional "disease, equation, formula, hypothesis, law, principle, rule, syndrome, theorem, or theory" group, while Soret effect and Dufour effect fall into the traditional "apparatus, coefficient angle, constant, cycle, effect, function, number, phenomenon, process, reagent, synthesis, or field of study" category.
Eponymic designations of diseases and syndromes, however, are rapidly moving out of the former category and into the latter, according to Oxford. I hope to examine this phenomenon shortly in another question.
As for your follow-up question about the law of Arrhenius, the same section of The Oxford Style Manual says this:

any variation follows the normal rules governing possessives (Charles's law, Descartes's rule of signs, Archimedes' principle, Chagas's disease, Fajan's rules) [cross-reference omitted].

Why the lack of an s after the apostrophe in Archimedes' principle? The Oxford Style Manual again (at 5.2.1):

Use an apostrophe alone after classical [such as Demosthenes] or classicizing [such as John Duns Scotus] names ending in s ...

Arrhenius may sound like a classicized name, but it's actually the last name that Svante August Arrhenius (1859–1927) of Sweden was born with. Therefore, the approved (by Oxford) way to handle the name of of his eponymic law is "Arrhenius's law."


text:
Q: exposing functions without cluttering ls() I have a package that generates some functions when you call an initialize function. I create these functions in the parent.frame of initialize(), which I guess is the global environment. I want to emulate the normal package behavior that allows you to directly call a function from a package after loading it, but without having to see those functions when you list your workspace contents using ls(). For example, doing
library(ggplot2)
ls()

doesn't return geom_line, geom_point, etc., but you don't have to use :: to call those functions. They are exposed to the user but do not live in the global environment.
Is there a clever way for me to do the same thing for functions generated by the call to initialize, e.g. by defining environments or namespaces in zzz.r and the onLoad or onAttach hooks? I thought of trying to set the function environments to the package namespace, but it seems that you cannot modify the package namespace after it is loaded.
EDIT the package I'm working on is here: https://github.com/mkoohafkan/arcpyr. The arcpy.initialize function connects to Python using PythonInR, imports the arcpy package, and then creates interfaces for a list of functions. I'll try to create a simplified dummy package later today.

A: So I eventually found a solution that uses both environments (thanks @ssdecontrol!) and attach.
f = new.env()                   # create the environment f
assign("foo", "bar", pos = f)   # create the variable foo inside f
ls()                            # lists f
ls(f)                           # lists foo
attach(f)                       # attach f to the current environment
foo                             # foo can now be accessed directly
## bar
ls()                            # but still only shows f
rm(f)                           # can even remove f
foo                             # and foo is still accessible
## bar

Of course, there are some risks to using attach.
I redid the arcpyr package to use environments instead, but you can get the old behavior back by doing
arcpy = arcpy_env()
attach(arcpy)


text:
Q: Cloud Firestore updating a modified document I got a list of items in my Angular (4) app using angularFire2 and Cloud Firestore to get an Observable:
private itemCollection: AngularFirestoreCollection<Item>;
items: Observable<ItemId[]>;
constructor(private readonly afs: AngularFirestore) {
  this.itemCollection = afs.collection<Item>('items');
  this.items = this.itemCollection.snapshotChanges().map(actions => {
  return actions.map(a => {
    const data = a.payload.doc.data() as Item;
    const id = a.payload.doc.id;
    return { id, ...data };
    });
  });

I then list this Observable in my component with a *ngFor and an async Pipe:
<span *ngFor="let item of items | async">

This works great, and when I add a new item it automatically shows in the list. Nevertheless when I update the score of an item, the Observable updates, but I still see the older version of the item (not the updated one with the new score). If I hit refresh I see then the updated version.
I update the score of an item this way:
updateItem(id: string, score: number): void {
  this.collectionRef.doc(id).update({ score });

}
What can I do to see automatically the updated item in the Observable when I update the score of an item?

A: Angular's observable didn't work like that. You need to provide value to an observer to refresh observable. you will need to overwrite your variable to initiate refresh. Like this:
updateItem(id: string, score: number): void {
  this.collectionRef.doc(id).update({ score });
  this.items = [already updated items document]
}

I hope I'm right :)


text:
Q: SAGA hydrology toolbox Error: select a library I am having trouble getting the SAGA hydrology toolbox running. Here when I try to fill sinks in the DEM a series of errors are flagged in the log file. This includes for 'select a library', 'DEM' and 'input file'. Load grid also fails (see log file below).
I'm using SAGA 2.3.2 and QGIS 3.4.3

Processing algorithm…
Algorithm 'Fill sinks' starting…
Input parameters:
{ 'DEM' : 'C:/Users/cbroderick/Downloads/srtm_35_02_ASCII/srtm_35_02.asc', 'MINSLOPE' : 0.01, 'RESULT' : 'C:/Users/cbroderick/AppData/Local/Temp/processing_f1fe9d24ac6c4b08972f8ddd5f612ef7/5ba9f4f078044c1bae470dfcd5f06f6e/RESULT.sdat' }

io_gdal 0 -TRANSFORM 1 -RESAMPLING 3 -GRIDS "C:/Users/cbroderick/AppData/Local/Temp/processing_f1fe9d24ac6c4b08972f8ddd5f612ef7/4d7bb3df467f4247aa6359cb5b93f904/srtm3502.sgrd" -FILES "C:\Users\cbroderick\Downloads\srtm_35_02_ASCII\srtm_35_02.asc"
ta_preprocessor "Fill Sinks (Planchon/Darboux, 2001)" -DEM "C:/Users/cbroderick/AppData/Local/Temp/processing_f1fe9d24ac6c4b08972f8ddd5f612ef7/4d7bb3df467f4247aa6359cb5b93f904/srtm3502.sgrd" -MINSLOPE 0.01 -RESULT "C:/Users/cbroderick/AppData/Local/Temp/processing_f1fe9d24ac6c4b08972f8ddd5f612ef7/5ba9f4f078044c1bae470dfcd5f06f6e/RESULT.sdat"

C:\WINDOWS\system32>set SAGA=C:/PROGRA~1/QGIS3~1.4/apps\saga-ltr

C:\WINDOWS\system32>set SAGA_MLB=C:/PROGRA~1/QGIS3~1.4/apps\saga-ltr\modules

C:\WINDOWS\system32>PATH=C:\PROGRA~1\QGIS3~1.4\apps\qgis\bin;C:\PROGRA~1\QGIS3~1.4\apps\Python37;C:\PROGRA~1\QGIS3~1.4\apps\Python37\Scripts;C:\PROGRA~1\QGIS3~1.4\apps\qt5\bin;C:\PROGRA~1\QGIS3~1.4\apps\Python27\Scripts;C:\PROGRA~1\QGIS3~1.4\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\system32\WBem;C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\site-packages\pywin32_system32;C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\site-packages\numpy\.libs;C:/PROGRA~1/QGIS3~1.4/apps\saga-ltr;C:/PROGRA~1/QGIS3~1.4/apps\saga-ltr\modules

C:\WINDOWS\system32>saga_cmd io_gdal 0 -TRANSFORM 1 -RESAMPLING 3 -GRIDS "C:/Users/cbroderick/AppData/Local/Temp/processing_f1fe9d24ac6c4b08972f8ddd5f612ef7/4d7bb3df467f4247aa6359cb5b93f904/srtm3502.sgrd" -FILES "C:\Users\cbroderick\Downloads\srtm_35_02_ASCII\srtm_35_02.asc"
Error: select a library
____________________________

##### ## ##### ##
### ### ## ###
### # ## ## #### # ##
### ##### ## # #####
##### # ## ##### # ##
____________________________

SAGA Version: 2.3.2 (64 bit)

68 loaded tool libraries (630 tools):
- climate_tools
- contrib_perego
- db_odbc
- db_pgsql
- docs_html
- garden_3d_viewer
- garden_fractals
- garden_games
- garden_learn_to_program
- garden_webservices
- grid_analysis
- grid_calculus
- grid_calculus_bsl
- grid_filter
- grid_gridding
- grid_spline
- grid_tools
- grid_visualisation
- imagery_classification
- imagery_isocluster
- imagery_maxent
- imagery_photogrammetry
- imagery_segmentation
- imagery_svm
- imagery_tools
- io_esri_e00
- io_gps
- io_grid
- io_grid_image
- io_shapes
- io_shapes_dxf
- io_table
- io_virtual
- pj_georeference
- pj_geotrans
- pj_proj4
- pointcloud_tools
- pointcloud_viewer
- shapes_grid
- shapes_lines
- shapes_points
- shapes_polygons
- shapes_tools
- shapes_transect
- sim_cellular_automata
- sim_ecosystems_hugget
- sim_erosion
- sim_fire_spreading
- sim_hydrology
- sim_ihacres
- sim_qm_of_esp
- sim_rivflow
- statistics_grid
- statistics_kriging
- statistics_points
- statistics_regression
- ta_channels
- ta_compound
- ta_hydrology
- ta_lighting
- ta_morphometry
- ta_preprocessor
- ta_profiles
- ta_slope_stability
- table_calculus
- table_tools
- tin_tools
- tin_viewer

type -h or --help for further information

C:\WINDOWS\system32>saga_cmd ta_preprocessor "Fill Sinks (Planchon/Darboux, 2001)" -DEM "C:/Users/cbroderick/AppData/Local/Temp/processing_f1fe9d24ac6c4b08972f8ddd5f612ef7/4d7bb3df467f4247aa6359cb5b93f904/srtm3502.sgrd" -MINSLOPE 0.01 -RESULT "C:/Users/cbroderick/AppData/Local/Temp/processing_f1fe9d24ac6c4b08972f8ddd5f612ef7/5ba9f4f078044c1bae470dfcd5f06f6e/RESULT.sdat"
Error: input file [C:/Users/cbroderick/AppData/Local/Temp/processing_f1fe9d24ac6c4b08972f8ddd5f612ef7/4d7bb3df467f4247aa6359cb5b93f904/srtm3502.sgrd]
Error: DEM
____________________________

##### ## ##### ##
### ### ## ###
### # ## ## #### # ##
### ##### ## # #####
##### # ## ##### # ##
____________________________

SAGA Version: 2.3.2 (64 bit)

____________________________
library path: C:\PROGRA~1\QGIS3~1.4\apps\saga-ltr\modules\
library name: ta_preprocessor
library : Preprocessing
tool : Fill Sinks (Planchon/Darboux, 2001)
author : Copyrights (c) 2003 by Volker Wichmann
processors : 4 [4]
____________________________

Load grid: C:/Users/cbroderick/AppData/Local/Temp/processing_f1fe9d24ac6c4b08972f8ddd5f612ef7/4d7bb3df467f4247aa6359cb5b93f904/srtm3502.sgrd...
failed

Usage: saga_cmd ta_preprocessor 3 [-DEM <str>] [-RESULT <str>] [-MINSLOPE <double>]
-DEM:<str> DEM
Grid (input)
-RESULT:<str> Filled DEM
Grid (output)
-MINSLOPE:<double> Minimum Slope [Degree]
Floating point
Minimum: 0.000000
Default: 0.010000

C:\WINDOWS\system32>exit
Execution completed in 13.51 seconds
Results:
{'RESULT': 'C:/Users/cbroderick/AppData/Local/Temp/processing_f1fe9d24ac6c4b08972f8ddd5f612ef7/5ba9f4f078044c1bae470dfcd5f06f6e/RESULT.sdat'}

Loading resulting layers
The following layers were not correctly generated.

C:/Users/cbroderick/AppData/Local/Temp/processing_f1fe9d24ac6c4b08972f8ddd5f612ef7/5ba9f4f078044c1bae470dfcd5f06f6e/RESULT.sdat

You can check the 'Log Messages Panel' in QGIS main window to find more information about the execution of the algorithm.

A: The version of the saga-ltr package compiled in the stand-alone installer of QGIS 3.4.3 has that bug. It can't read the io_gdal library.
This specific bug was already fixed in version 2.3.2-4 of that package.
Also you will have some other important issues in that version. Many of that already fixed too.
I do not know how to update the package in the stand-alone version.

I recommend you perform a complete uninstall (this includes removing registry keys and the C:\Users\YourUser\AppData\Roamming (and Local)\QGIS 3.4 folders after uninstalling), and using the OSGeo4W Network installer instead.
When a new version of a package comes out, it may be possible that it has some issue, errors that are reported and corrected in the following days, but that the stand-alone installer does not allow or becomes quite complicated to repair.
With the Network installer you can perform a basic installation first, of QGIS, GRASS and SAGA, and then periodically run the Setup tool in advanced mode to keep all the packages updated. The same as installing or uninstalling specific packages quite easily.
It is true that one sometimes finds a problem that is difficult to solve, and would rather have kept QGIS 3.2 working somewhere, for example. It is the disadvantage of staying updated. Also take my advice as what it is, and decide whether to take it or let it go.

A: I have troubles with the SAGA algorithm Edge Detection (Vigra) because the error referred in this post is happening.
I have QGIS 3.18 (installed with OSGeo4W) and the SAGA version is 2.3.2-4. I see that in some posts, in this version, the algorithms worked. However in my case still fo not working.
What can be the solution?


text:
Q: How to Interpolate in Circular Meshgrid I am trying to get an interpolated "Heatmap" (circular/polar cords) for 5 Samples on a laboratory table of r=85 mm. What i wanted to get is an interpolated "Map". The Samples have different positions on the table and i have a dB-Value for every Sample (so to call the z value/coordinate). Is it possible to interpolate over the entire circular meshgrid so that a get something like a Heatmap for the whole table?
I am currently stuck at this and have no idea how to go on.
Here is the Code I have written so far, but it doesn't look the way i expected.
from pylab import *
import numpy as np
from scipy.interpolate import griddata

# Points within the circle (radius 85mm) corresponding to the sample
position on a circ. measuring table of r=85mm
max_r = 85
max_theta = 2*np.pi
number_points = 5
points = np.array([[64,(-6/8)*np.pi], [64,(6/8)*np.pi], [0, 0],[60,
(-2/8)*np.pi],[60, (2/8)*np.pi]])  # [r,theta] of the specific Sample
position

# The Measured Values in dB-Scale ("z"-Values) for the five Samples
values = [-38.469016,-38.159216 ,-36.763974,-36.208431 ,-36.004596]

# create grid
theta = np.linspace(0.0, 2*np.pi, 50)
r = np.linspace(0, max_r, 50)
grid_r, grid_theta = np.meshgrid(r, theta)
data = griddata(points, values, (grid_r, grid_theta), method='cubic',
fill_value=0)

# Create a polar projection
ax1 = plt.subplot(projection="polar")
ax1.pcolormesh(theta, r, data.T)
ax1.set_rmax(85)
plt.show()

I am thankfull for every help.
Best regards
Bastian
Here are two plots, one with the right position of the samples on the meshgrid,one from the code above.


text:
Q: Tracking the point of intersection of a simulated time series with a specific value over many runs in OpenBUGS I have an OpenBUGS model that uses observed data (y.values) over time (x.values) to simulate many runs (~100000) with new estimates of y-values (y.est) for each run. The observed data exhibit a pronounced decline from a maximum value.
I want to keep track of the length of time it takes for each run to decline from the maximum abundance (T.max) to 10% of the maximum abundance (T.10%). Because the maximum abundance value changes from run to run, 10% of that maximum will also vary from run to run, and thus T.10% will vary from run to run.
Setting a parameter to store T.max is easy enough, that doesn't vary from run to run because the maximum value is sufficiently greater than any other value.
What I can't figure out, is how to store the intersection of the y-est values and T.10%.
My first attempt was to determine whether each y-est value is above or below T.10% using the step() function:
above.below[i] <- step(T.10% - y.est[i])

This generates a string of ones and zeros for each y.est value (e.g., 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, etc.) If each run simply declined continuously from a maximum to a minimum, I could use the rank() function to  determine how many above.below[i] values occur above T.10%:
decline.length <- rank(above.below[1:N], 0)

In this example, decline.length would be equal to the number of '0's in the string above, which is 9. Unfortunately, the y-est values occasionally display periods of growth following their decline below T.10%. So, the vector of above.below values can look like this: 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, etc. Thus, decline.length would equal 14 rather than 9, given the subsequent 0s in the vector.
What I want to do, is figure out how to store only the number of '0's in above.below prior to the first '1'; above.below[1:10] rather than above.below[1:N]. Unfortunately, it's not always the 10th time step in which the first '1' occurs, so I need to make the maximum extent of the range of above.below vary from run to run during the simulation.
I'm struggling to accomplish this in OpenBUGS since it's a non-procedural language, but I think it can be done, I just don't know the trick to do it. I'm hoping someone more familiar with the step() and rank() functions can lend some expert advice.
Any guidance is much appreciated!

A: Two solutions offered to me:
1) Calculate the cumulative sum up to each time step:
for (i in 1:N){
    above.below[i] <- step(T.10% - y.est[i])
    cum.above.below[i] <- sum(above.below[1:i])
}

decline.length <- rank(cum.above.below[1:N], 0)

2) Calculate whether each year is above or below the threshold directly, without 1s and 0s:
for(i in 1:N){
    above.below[i] <- step(T.10% - y.est[i])
    dummy[i] <- above.below[i] * i + (1 - above.below[i]) * (N+1)
}

decline.length <- ranked(dummy[], 1)

So dummy is i when above.below is 1, and dummy is N+1 when above.below is 0.


text:
Q: Measurement error in one indep variable in OLS with multiple regression Suppose I regress (with OLS) $y$ on $x_1$ and $x_2$. Suppose I have i.i.d. sample of size n, and that $x_1$ is observed with error but $y$ and $x_2$ are observed without error. What is the probability limit of the estimated coefficient on $x_1$?
Let us suppose for tractability that the measurement error of $x_1$ is "classical". That is the measurement error is normally distributed with mean 0 and is uncorrelated with $x_2$ or the error term.

A: Suppose you true matrix is $X^*=\begin{bmatrix} x_1^{*} & x_2 \end{bmatrix}$, but you observe $x_1=x_1^*+v$.
Then the OLS coefficient on $x_1$ has the following probability limit:
$$\mathbf{plim} \hat \beta_{x_1|x_2}=\beta \left[1-\frac{\sigma^2_v}{\sigma^2_{x_1^*}\cdot(1-R^2_{x_1^*,x_2})+\sigma^2_v} \right]=\beta \left[1-\frac{1}{1+\frac{\sigma^2_{x_1^*}}{\sigma^2_v}\cdot(1-R^2_{x_1^*,x_2})} \right]$$
where $R^2_{x_1^*,x_2}$ denotes the $R^2$ from the auxiliary regression of $x_1^*$ on $x_2$.
This means the coefficient is still attenuated, but generally less so than in the single regressor case. The bias gets worse as collinearity with $x_2$ increases.
Here $x_2$ can contain more than one variable measured without error, so this formula is pretty general. The coefficient(s) measured without error will be inconsistent in the direction determined by $\Sigma_{X^*X^*}$.
You can find this formula (without proof, but surrounded by much auxiliary wisdom) in equation (5) in Bound, John & Brown, Charles & Mathiowetz, Nancy, 2001. "Measurement error in survey data," Handbook of Econometrics, edition 1, volume 5, chapter 59, pages 3705-3843.
They cite these two older papers:

*

*Levi, M.D. (1973), "Errors in the variables bias in the presence of correctly measured variables", Econometrica 41:985−986.

*Garber, S., and S. Klepper (1980), "Extending the classical normal errors-in-variables model", Econometrica 48:1541−1546.

A: The solution to this problem is in Wooldridge's "Introductory Econometrics" (Chapter 9 Section "Measurement Error in an Explanatory Variable", p320 in the 2012 version) and in Wooldridge's "Econometric analysis of cross-section and_panel data" (Section 4.4.2, p73 in the 2002 version). Here is the takeaway.
Consider the multiple regression model with a single explanatory variable $x^*_K$ measured with error :
$$y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + ... + \beta_K x^*_K + \nu$$
And with "classical" assumptions, mainly that $\nu$ is uncorrelated to $x^*_K$ and $\nu$ is uncorrelated to $x_K$.
The measurement error is $e_K = x_K - x^*_K$ with $\text{E}(e_k) = 0$. The classical assumption implies that $\nu$ is uncorrelated to $e_K$
We want to replace $x^*_K$ with $x_K$ and see how this affects OLS estimators, w.r.t. assumptions on the relationship between the measurement error $e_k$ and $x^*_K$ and $x_K$.
The first case, which is not the OP case but I present briefly for the sake of completeness, is when $\text{Cov}(e_K, x_K) = 0$. Here OLS using $x_K$ instead of $x^*_K$ provides consistent estimators even if it inflates the error variance of the estimations (and thus of the estimators).
The case of interest is when $\text{Cov}(e_K, x^*_K) = 0$ and is called "classical in variables error" in the econometric literature. Here :
$$\text{Cov}(e_K, x_K) = \text{E}(e_Kx_K) = \text{E}(e_Kx^*_K)+ \text{E}(e^2_K) = \sigma^{2}_{e_{K}}  $$
and :
$$
\text{plim}(\hat{\beta}_k) = \beta_K \left( \frac{\sigma^{2}_{r^{*}_{K}}}{\sigma^{2}_{r^{*}_{K}}+ \sigma^{2}_{e_{K}}}  \right) = \beta_KA_K
$$
where $r_K$ is error in :
$$
x^*_K = \delta_0 + \delta_1 x_1 + \delta_2 x_2 + ... \delta_{K-1} x_{K-1} + r^*_K
$$
$A_K$ is always between 0 and 1 and is called the attenuation bias: If $\beta_K$ is positive (reps. negative), $\hat{\beta}_K$ will tend to underestimate (reps. underestimate) $\beta_K$.
In the multivariate regression, it is the variance of $x^*_K$ after controlling (netting) for the effects of the other explanatory variables, that affect the attenuation bias. This latter is worse as $x^*_K$ is colinear with the other variables.
In the case where $K=1$, i.e., the simple regression model where there is only one explanatory variable which is measured with error. In this case :
$$\text{plim}(\hat{\beta}_1) = \beta_1 \left( \frac{ \sigma^{2}_{x^*_1} }{\sigma^{2}_{x^*_1} + \sigma^{2}_{e_1}} \right)$$
The attenuation term, always between 0 and 1 becomes closer to 1 as $\sigma^{2}_{e_1}$ shrinks relatively to $\sigma^{2}_{x^*_1}$. Note that in this special case, $r^*_K = x^*_1$.
The $\text{plim}(\beta_j)$ for $j \neq K$ is complicated to derive in this framework, except in the case where $x^*_k$ is uncorrelated to other $x_j$, thus $x_k$ is uncorrelated to other $x_j$, which leads to $\text{plim}(\hat{\beta}_j)=\beta_j$.

A: In the situation that you describe, the true model is like this:
$y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + u$
now, you can observe $y$ and $x_2$ but you cannot observe $x_1$. However you can observe
$z = x_1 + \epsilon$
moreover we assume that $\rho(\epsilon,u)=0$
So, if we consider the simplification where $\beta_2 =0$ is possible to show that the OLS estimator for $\beta_1$ is like
$\theta_1 = \beta_1  V[x_1]/(V[x_1] + V[\epsilon]) $
Then the absolute value of $\theta_1$, in expected term and/or plim,  is lower than of $\beta_1$. Then $\theta_1$ is biased (incorrect and inconsistent) for $\beta_1$. This kind of bias is known as attenuation bias. More $V[\epsilon]$ increase, more serious the problem become.
Now, for multivariate case the matrix algebra notation is usually used. Then in vector form we achieve $E[\theta]\neq \beta$  and/or  plim $\theta \neq\beta$
Note that here you can consider that even if only one variable is endogenous, for measurement error or other problems, all parameters become biased. The direction of bias for any $\theta_i$ depends from correlations among variables and the sign of the first moments. Special cases exist, for example if the variables are all orthogonal the bias does not spread.
In your case, two variables ($\beta_1$ and $\beta_2$ different from $0$), you can estimate a regression like
$y = \theta_0 + \theta_1 z + \theta_2 x_2 + v$
here $\theta_1$  suffer from attenuation bias (on $\beta_1$) but also $\theta_2$ is biased (for $\beta_2$). In special case where $z$ and $x_2$ are orthogonal, for $\theta_1$ the problem remain but $\theta_2$ become correct and consistent.


text:
Q: How to get a vertical scroll bar on Google Dashboard Category Selector My Problem
I have a Google visualization dashboard in a Google site. When the user selects the drop down menu (CategorySelector) the very first item is automatically selected and populated on the dashboard (in this example "//Khara Hais Local Municipality"). This only happens when there are multiple entries in the drop down menu which go past the bottom of the webpage. With a short list of items (e.g 5) I don't get the problem.
The Code
The dashboard is embedded in the site as an XML gadget. Long story, but Google site won't let me embed the HTMLdirectly, so it has to be wrapped in XML.
Proposed Solution
I think the best way to resolve this is to minimise the number of entries in the category selector with a vertical scroll bar, but I dont know how to code this in the Google visualization. Any help would be great


text:
Q: How to load a finetuned sciBERT model in AllenNLP? I have finetuned the SciBERT model on the SciIE dataset. The repository uses AllenNLP to finetune the model. The training is executed as follows:
python -m allennlp.run train $CONFIG_FILE  --include-package scibert -s "$@"

After a successful training I have a model.tar.gz file as an output that contains weights.th, config.json, and vocabulary folder. I have tried to load it in the allenlp predictor:
from allennlp.predictors.predictor import Predictor
predictor = Predictor.from_path("model.tar.gz")

But I get the following error:

ConfigurationError: bert-pretrained not in acceptable choices for
dataset_reader.token_indexers.bert.type: ['single_id', 'characters',
'elmo_characters', 'spacy', 'pretrained_transformer',
'pretrained_transformer_mismatched']. You should either use the
--include-package flag to make sure the correct module is loaded, or use a fully qualified class name in your config file like {"model":
"my_module.models.MyModel"} to have it imported automatically.

I have never worked with allenNLP, so I am quite lost about what to do.
For reference, this is the part of the config that describer token indexers
"token_indexers": {
            "bert": {
                "type": "bert-pretrained",
                "do_lowercase": "false",
                "pretrained_model": "/home/tomaz/neo4j/scibert/model/vocab.txt",
                "use_starting_offsets": true
            }
        }

I am using allenlp version
Name: allennlp
Version: 1.2.1
Edit:
I think I have made a lot of progress, I have to use the same version that was used to train the model and I can import the modules like so:
from allennlp.predictors.predictor import Predictor
from scibert.models.bert_crf_tagger import *
from scibert.models.bert_text_classifier import *
from scibert.models.dummy_seq2seq import *
from scibert.dataset_readers.classification_dataset_reader import *

predictor = Predictor.from_path("scibert_ner/model.tar.gz")
dataset_reader="classification_dataset_reader")
predictor.predict(
  sentence="Did Uriah honestly think he could beat The Legend of Zelda in under three hours?"
)

Now I get an error:

No default predictor for model type bert_crf_tagger.\nPlease specify a
predictor explicitly

I know that I can use the predictor_name to specify a predictor explicitly, but I haven't got the faintest idea which name to pick that would work

A: I have seen a lot of people having this problem. Upon going through the repository code, I found this to be the easiest way to run the predictions:
python -m allennlp.run predict /path/to/saved_model/model.tar.gz /path/to/test.txt\
  --include-package scibert --use-dataset-reader\
  --output-file /path/to/where/you/want/predict.txt\
  --predictor  sentence-tagger --batch-size 16

What did I add? The predictor sentence-tagger. Once you go through the repository, you would find that the registered predictor is sentence-tagger. Although the DEFAUL_DICT of the taggers contain sentence_tagger. A lot of confusion, right? Tell me!
This answer also saves you from writing a predictor.


text:
Q: check for EMAIL format in ROW and return value inside SELECT query I have a table called user_data and few columns like LOGIN_NAME
The column LOGIN_NAME may contain "emailformat@email.com" or just a "username"
I need to know if it is possible for me to run a select query and return emailAddress if row has email type format else return userName if it is a non-email format.
example - (I am trying to created a JSON format with this) :
Here signInType is userName since Markus Dave is a non-email format (LOGIN_NAME which is a row was having a value Markus Dave ->
        {
          "signInType": "userName",
          "issuerAssignedId": "Markus Dave"
        }

Here signInType is emailAddress since follyrichard@gmail.com is a email format (LOGIN_NAME which is a row was having a value follyrichard@gmail.com
            {
              "signInType": "emailAddress",
              "issuerAssignedId": "follyrichard@gmail.com"
            }

Here is a query that I could produce :
SELECT 'signInType' AS signInType
        , LOGIN_NAME AS issuerAssignedId
        FROM USER_DATA
        FOR JSON AUTO;

For signInType field, I need to use the same field LOGIN_NAME and check if it is email or not and then prepare according to it.
I have 10 users in the table, I need to create 10 field JSON.

A: You should be able to use a case expression:
SELECT (CASE WHEN LOGIN_NAME LIKE '%@%' THEN 'emailAddress' ELSE 'userName' END) as signInType,
       LOGIN_NAME AS issuerAssignedId
FROM USER_DATA
FOR JSON AUTO;


text:
Q: Angular 5 --prod --aot build issue with ngCli In My project ng build command executing successfully and running as well.
But when I build ng build --prod --aot, build is successful but not running.
Error: StaticInjectorError[n]:
  StaticInjectorError[n]:
    NullInjectorError: No provider for n!
Please help.


text:
Q: How does the ssh-keygen .pub format work with .pem files? The ssh-keygen command generates .pub files which it describes as "public key files", but they are a totally different format to most "public key files" I've usually seen, which are in PEM format.  The ssh-keygen-style files look like this:
ssh-rsa AAAAB3NzaC1... user@host

... whereas the PEM files look like this:
-----BEGIN CERTIFICATE-----
MIIGZjCCBU6gAwIBAgIDCIrNMA0GCSqGSIb3DQEBBQUAMIGMMQsw...
-----END CERTIFICATE-----

Are these two formats interchangeable, or are they performing a fundamentally different purpose?  I came across this problem because I wanted to get the RSA2 key fingerprint of my PEM-encoded public key file, but the method usually suggested to do it (ssh-keygen -l) says that my PEM-encoded file "is not a public key file".
By the way, I'm aware of this answer, but it doesn't cover the .pub files generated by ssh-keygen.

A: OpenSSH key pairs are not PEM or any other x500 standard. New versions of OpenSSH can use X.509 PEM keys, but that's another ball of wax separate from ssh-keygen, and has to be configured explicitly. As best I know, no major implementation of SSH uses the exact same key formats as any other.
As Zoredache notes, if you're using something other than OpenSSH (deus iuvo vos), then it could be darn near anything.


text:
Q: Not able to read Impala view correctly using Spark SQL I am trying to read an Impala view from Spark Scala program using SparkSQL API.
My code is like this
val sparkSession: SparkSession = SparkSession.builder().appName("HiveLoader").master(new Sparkconf().get("spark.master", local[*]).getorCreate()

sparkSession.conf.set("spark.sql.crossJoin.enabled", true)

val df = sparkSession.sql("Select * from view1")

where view1 is the view in Impala which is created by joining two or more Impala tables. The above code is not reading the complete view and it's not giving the correct result. For example, the count of this view in Impala is 410234 but it's reading only 371 records.