text:
Q: Django - ChoiceField - Option Buttons instead of Select box Is it possible to display the option buttons instead of select box (in the admin interface) for ChoiceField? Any suggestions?

A: The following ModelAdmin subclass (in your admin.py) does what you're after:
class PersonAdmin(admin.ModelAdmin):
    radio_fields = {"group": admin.VERTICAL}

HORIZONTAL is also possible.
From the Django docs.

A: There's a snippet on djangosnippets that seems to do something like this for forms given a list of choices, but it doesn't seem to specifically do it for the admin app.  You might be able to either leverage this or the ideas within it to get you the rest of the way though.

A: Yes.
In your admin.py create a ModelAdmin class:
from django.contrib import admin
from django.forms.widgets import RadioSelect ## originally had mistake of django.forms.extras.widgets

class SomeModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
         models.ChoiceField : dict(widget = RadioSelect)
     }

admin.site.register(SomeModel, SomeModelAdmin)

I'm not sure what you mean by "option buttons" rather than select box, but this is how you change it.  You can find the right widget here: http://docs.djangoproject.com/en/dev/ref/forms/widgets/


text:
Q: Node.js / Axios won't connect to localhost I have a cryptocurrency (Nano) node running locally on my computer. It has an RPC API and I've tested that I can successfully make calls to it using curl. E.g.
curl -d '{ "action": "account_balance", "account": "xrb_1aaprwcu9fac1tw3wesud5txb1zuiroti5xfr19bwozitjnnmbcbwpr1w95f" }' localhost:7076
However I'm trying to do the same thing in a node script and keep getting ECONNREFUSED
Here's my node script (the important parts).
const axios = require('axios')
const config = require('./config')

const rpc = axios.create({
  baseURL: 'localhost:7076', // I've also tried 'http://localhost:7076'
  // I've tried with and without proxy settings, I don't understand proxies very well though
  /*proxy: {
    host: '127.0.0.1',
    port: 7077
  }*/
})

function createAddress(accountIndex) {
  // Ensure accountIndex is a string
  accountIndex = accountIndex + ''
  // Get a new private key
  return rpc.post('/', {
    action: 'deterministic_key',
    index: accountIndex,
    seed: config.walletSeed
  })
    // Add to the local wallet
    .then(function(result){
      return rpc.post('/', {
        action: 'wallet_add',
        key: result.private,
        wallet: config.walletId
      })
    })
    // Return the account address
    .then(function(result){
      return result.account
    })
    .catch(function(err) {
      console.log('Error', err)
    })
}

createAddress(52).then(function(address){
  console.log(address)
})

And here's the error.
Error { Error: connect ECONNREFUSED 127.0.0.1:7076
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1170:14)
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 7076,
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'Content-Type': 'application/json;charset=utf-8',
        'User-Agent': 'axios/0.18.0',
        'Content-Length': 117 },
     method: 'post',
     baseURL: 'http://localhost:7076',
     url: 'http://localhost:7076/',
     data: '{"action":"deterministic_key","index":"52","seed":"***"}' },
  request:
   Writable {
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     _events:
      { response: [Function: handleResponse],
        error: [Function: handleRequestError] },
     _eventsCount: 2,
     _maxListeners: undefined,
     _options:
      { protocol: 'http:',
        maxRedirects: 21,
        maxBodyLength: 10485760,
        path: '/',
        method: 'post',
        headers: [Object],
        agent: undefined,
        auth: undefined,
        hostname: 'localhost',
        port: '7076',
        nativeProtocols: [Object],
        pathname: '/' },
     _redirectCount: 0,
     _requestBodyLength: 117,
     _requestBodyBuffers: [ [Object] ],
     _onNativeResponse: [Function],
     _currentRequest:
      ClientRequest {
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: true,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: null,
        _hasBody: true,
        _trailer: '',
        finished: false,
        _headerSent: true,
        socket: [Socket],
        connection: [Socket],
        _header: 'POST / HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/json;charset=utf-8\r\nUser-Agent: axios/0.18.0\r\nContent-Length: 117\r\nHost: localhost:7076\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'POST',
        path: '/',
        _ended: false,
        res: null,
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Circular],
        [Symbol(isCorked)]: false,
        [Symbol(outHeadersKey)]: [Object] },
     _currentUrl: 'http://localhost:7076/' },
  response: undefined }

I feel like I've tried countless variations of configuration. What am I not getting?

A: This is 4 months later but I've been trying to figure out the same thing.
Try changing your instance configuration like this:
  const rpc = axios.create({
    baseURL: 'localhost:7076',
    proxy: false
})

I couldn't find the solution so I ended up digging through axios' code.
I found this on line 89 of /lib/adapters/http.js:
var proxy = config.proxy;
if (!proxy && proxy !== false) {
  var proxyEnv = protocol.slice(0, -1) + '_proxy';
  var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];
  if (proxyUrl) {
    var parsedProxyUrl = url.parse(proxyUrl);
    proxy = {
      host: parsedProxyUrl.hostname,
      port: parsedProxyUrl.port
    };

    if (parsedProxyUrl.auth) {
      var proxyUrlAuth = parsedProxyUrl.auth.split(':');
      proxy.auth = {
        username: proxyUrlAuth[0],
        password: proxyUrlAuth[1]
      };
    }
  }
}

if (proxy) {
  options.hostname = proxy.host;
  options.host = proxy.host;
  options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
  options.port = proxy.port;
  options.path = protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path;...

The way I read it, if there is no proxy entry in your config or if your proxy entry is not false (the boolean). Then it makes the var 'proxy' equal to it's default proxy. So when it gets down to line 110...
if (proxy) {...

...there is a proxy, (the default it just created) and it will use it.
When I added proxy: false to my config axios worked as I expected.

A: Have you attempted to use your direct IP?
Type in your terminal:

netstat

192.168.1.?
Failing this simple answer/explaination, I set-up a Docker VM on my local machine and connect to my personal RPC API via this:
https://hub.docker.com/r/jlmconsulting/upcoind/

A: I was having the same issue, trying to make a request from a nodejs express app on port 8001 to another Nodejs express app running on port 8000 on my machine. What worked for me was to write the request address like so:
const testRequest = async () => {
    try {
    const test = await axios.get('http://localhost:8000/test');
   //rather than just localhost:8000/test
    console.log('TEST', test);
  } catch (e) {
    console.error('TEST ERROR:', e);
  }
};

and it worked. I've seen in your comments that you've tried the same using the config, so I find it strange that it did not work...

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to encrypt and decrypt request and response using SHA512 algorithm I want to encrypt and decrypt the request and response of the web service(KSOAP or JSON) using SHA512 algorithm with private and public keys in android.
Does anyone have an idea on this. I don't have much experience on this. So please excuse me if i am wrong.
i guess the below class is used for encrypting a string. I want to know how to decrypt the string. And also i want to know how to use the private/public keys in this.
public class SHA2Demo {
/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String message = "test";

    MessageDigest messageDigest = null;
    try {
        messageDigest = MessageDigest.getInstance("SHA-512");
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        messageDigest.update(message.getBytes("UTF-16BE"));
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    byte[] digest = messageDigest.digest();

    StringBuffer digestInHex = new StringBuffer();

    for (int i = 0, l = digest.length; i < l; i++) {
        // Preserve the bit representation when casting to integer.
        int intRep = digest[i] & 0xFF;
        // Add leading zero if value is less than 0x10.
        if (intRep < 0x10)  digestInHex.append('\u0030');
        // Convert value to hex.
        digestInHex.append(Integer.toHexString(intRep));
    }

    System.out.println(digestInHex.toString());

}

}
Thanks in advance.

A: Sha512 is a hash, not an encryption. You cannot encrypt anything with it. Use something like RSA or elliptic curves.

A: Sha512 is a hashing algorithm. You can NOT de-hash the response once it is hashed. That's what hash is for.
RSA or AES is what you might be looking for. Other things you may want to consider is Transport level security using SSL.


text:
Q: Уменьшение высоты блока CSS Каким свойством можно уменьшить высоту блока на несколько пикселей? А то у меня такая структура: шапка блока, потом контент блока, потом футер блока, но футер с тенью внизу, и получается что тень обромляется обводкой слева и справа - не красиво, фиксированую высоту не хочется ставить... Подскажите пож-та
A: Если футер внутри блока, попробуйте указать отрицательный margin-bottom для футера.
Это поднимет границу "футеросодержащего" блока на указанное количество пикселей.
A: Высота свойство - height:
Ширина - width:


text:
Q: Data commit fails for "Upsert" / Merge function when calling through Npgsql I am using Npgsql 3.0.3 with Postgres 9.4. Here is my code in Postgres:
CREATE TABLE temp_test
(
  id serial NOT NULL,
  name text,
  CONSTRAINT temp_test_pk PRIMARY KEY (id)
)

and the "Upsert" / merge function that returns the changed record as refcursor:
CREATE OR REPLACE FUNCTION test_save(
    v_ref refcursor,
    iv_id integer,
    v_name character varying)
  RETURNS refcursor AS
$BODY$
DECLARE
  v_ref alias for $1;
  v_id integer := iv_id;
BEGIN

  UPDATE onepm.temp_test
  SET name   = v_name
  WHERE id         = v_id;
  IF NOT FOUND THEN
  INSERT INTO onepm.temp_test
      (name)
  VALUES
      (v_name)
  RETURNING id INTO v_id;
  END IF;

  OPEN v_ref FOR
  SELECT id
       , name
  FROM onepm.temp_test
  WHERE id = v_id;

  RETURN v_ref;
END;

$BODY$
  LANGUAGE plpgsql;

In my .net project I have the following function that returns a IDatareader:
public static IDataReader ExecuteReader()
        {
            NpgsqlConnection conn = new NpgsqlConnection(connectionString);
            conn.Open();

            NpgsqlTransaction _tran = conn.BeginTransaction();

            NpgsqlCommand cmd = conn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT onepm.test_save(@ref, @id, @name)";

            NpgsqlParameter _p = new NpgsqlParameter();
            _p.ParameterName = "@ref";
            _p.NpgsqlDbType = NpgsqlDbType.Refcursor;
            _p.NpgsqlValue = "ref";
            _p.Direction = ParameterDirection.InputOutput;
            cmd.Parameters.Add(_p);

            cmd.Parameters.Add(new NpgsqlParameter("@id", 1));
            cmd.Parameters.Add(new NpgsqlParameter("@name", "test"));

            cmd.ExecuteNonQuery();
            cmd.CommandText = "fetch all in \"ref\"";
            cmd.CommandType = CommandType.Text;

            return cmd.ExecuteReader();
        }

This all works fine, I do receice the inserted or updated record in the reader, except that the data is never committed to the table - no data found in pgAdmin. If I call the same function in pgAdmin everything works fine - records are committed:
SELECT onepm.test_save('v_ref', 1, 'xxxxxx');

FETCH ALL IN "v_ref";

Thankful for any help!

A: Ummm, I think you need to commit the transaction you started...!
Regardless, you may also want to look at PostgreSQL 9.5's new built-in upsert functionality...


text:
Q: wxWidgets wxNotebook flat style tabs So I have a very basic wxNotebook that I am creating and adding just some test pages to right now. The problem is the tabs look like old windows 2000 style, flat boring tabs, is there some reason I can't get them to look like the systems native tabs?
This is compiled under cygwin 32bit wxwidgets compiled with gcc targeting windows with unicode support

I should also mention that no styles other than the default have been applied here so I have not set the style to be nopagetheme or flat

A: This is almost certainly because you don't have a manifest included in your application resources, possibly because you don't have any resources (.rc file) in your build at all or maybe because you didn't include wx/msw/wx.rc from it.


text:
Q: Cookies for shopping cart Laravel I have a view with a foreach, here I have following code:
@foreach($shopGSM as $shopGSM)

{{ $shopGSM->name }}

 $shopGSM->category_id]) }}"><button class="btn btn-primary">+ Add to cart</button>
@endforeach

My question here is how do I make a cookie to see what products my user has clicked? Really new to this, so I'am happy if anyone can help me?

A: In your controller's method (or closure) that responds to the route eindwerk.shoppingcart when that link is clicked, you would add code there to create the cookie and then return it with your next view.
You can check the docs here to see how to do just that... https://laravel.com/docs/5.2/requests#cookies
I would recommend doing a little more research because usually cookies are not the way to go for this.  If you want to store the cart on a session by session basis, then you can use the session.  If you want to store the cart per user and require a login, then you'd store everything in the database.  There should be some pretty good cart tutorials out there specifically for Laravel to get you started.


text:
Q: How do I take the last item on a list and display that value I have a school project that requires me to take values from a text document and send them to a different text document(In sorts just simplifying the text document). I need to be able to find lines with certain information(already done) and then take just the last value in that list. This is all coded with Python.
The value I'm taking is an IP address so it will always be an integer. However, some of the IP values have parenthesis around them and if possible I also need to remove just the parenthesis and keep the IP inside of them.
:for i, line in enumerate(searchlines):
    if "Nmap scan report for" in line:
        for l in searchlines[i:i+1]: IPlog.write(l)
        print:

A: For displaying the last element of the list.
element = searchlines[-1]
element = searchlines[-1:]


text:
Q: Find $a$ such that $\log _{2}^{2}x-{{\log }_{\sqrt{2}}}x=a-\sqrt{a+{{\log }_{2}}x}$ has exactly $2$ solutions
Find $a$ so that equation $\log _{2}^{2}x-{{\log }_{\sqrt{2}}}x=a-\sqrt{a+{{\log }_{2}}x}$ has exactly $2$ solutions.

My approach: Since that $$\log_{2}(x)=\frac{\ln(x)}{\ln(2)} \quad \text{and} \quad \log_{\sqrt{2}}(x)=\frac{\ln(x)}{\ln(\sqrt{2})}$$
then, we can re-write the equation as $$\left(\frac{\ln(x)}{\ln(2)}\right)^{2}-\left( \frac{\ln(x)}{\ln(\sqrt{2})}\right)^{2}=a-\sqrt{a+\frac{\ln(x)}{\ln(2)}}$$
Let $t:=\ln(x)$ so the equation above we can re-write in terms  of $t$ as $$\left(\frac{1}{\ln(2)}t\right)^{2}-\left( \frac{1}{\ln(\sqrt{2})}t\right)^{2}=a-\sqrt{a+\frac{1}{\ln(2)}t}$$
Then, the idea that I was thinking is squaring both sides of the equation, but there appears an equation of degree 4 that is difficult to solve. How could I continue from there? or maybe a simpler approach?

New approach: Using the point out of @Ross Millikan and since that $$\log_{\sqrt{2}}(x)=\frac{\log_{2}(x)}{\log_{2}(\sqrt{2})}=2\log_{2}(x)$$
and let $t:=\log_{2}(x)$ so the equation can be we-write in terms of $t$ as $$t^{2}-2t=a-\sqrt{a+t} \implies t^{2}-2t\color{blue}{+1}=a-\sqrt{a+t}\color{blue}{+1} \implies (t-1)^{2}=a+1-\sqrt{a+t}$$
or maybe $$ t^{2}-2t=a-\sqrt{a+t} \overset{y^{2}=a+t}{\implies} (y^{2}-a)^{2}-2(y^{2}-a)=a-y^{2}$$
solving a little the expression above we can see that $$y^{4}-2y^{2}a+a^{2}-2y^{2}+2a-a+y^{2}=0$$
how can I solve this?

A: Edit: @mathlove noticed problems with my initial solution. My effort to resolve those problems ended in a major revision of the solution. Please comment if you find mistakes in this new version.
Let's take off from where you calculated that $t^2-2t=a-\sqrt{a+t}$ . Our aim is to find a value (or values) for $a$ such that the above equation has exactly 2 real answers for $t$. Let's also keep in mind the implicit constraint that
$$a+t \ge 0 \Rightarrow t \ge -a \qquad(1)$$
This is because the given problem includes $\sqrt{a+t}$ . An important implication of (1) is that if $a$ is negative then $t$ should be positive, and if $t$ is negative then $a$ should be positive.
Another constraint that is derived from our starting equation is that
$$t^2-2t \le a \qquad (2)$$
where the equality holds when $a+t=0$. Besides, (2) means that if $a < 0$ then $t^2-2t=t(t-2) < 0$ , which implies that $0 < t < 2$.
And two other constraints, which we can derive from (2) are
$$t^2-2t+1 = (t-1)^2 \le a+1 \qquad (3)$$
$$0 \le (t-1)^2 \le a+1 \Longrightarrow a \ge -1 \qquad (4)$$
Alright, here we go:
$$t^2-2t=a-\sqrt{a+t}$$
$$t^2-t=a+t-\sqrt{a+t}$$
$$t^2-t+\frac{1}{4}=a+t-\sqrt{a+t}+\frac{1}{4}$$
$$(t-\frac{1}{2})^2 = (\sqrt{a+t}-\frac{1}{2})^2$$
$$t-\frac{1}{2} = \pm(\sqrt{a+t}-\frac{1}{2})$$
So we have two (quadratic) equations
$$t-\frac{1}{2} = +(\sqrt{a+t}-\frac{1}{2}) \Rightarrow t^2 = a+t \qquad (5)$$
and
$$t-\frac{1}{2} = -(\sqrt{a+t}-\frac{1}{2}) \Rightarrow (t-1)^2 = a+t \qquad (6)$$
Let's look more carefully at (5). The solutions to this quadratic equation are
$$t_1 = \frac{1 + \sqrt{1+4a}}{2} , t_2 = \frac{1 - \sqrt{1+4a}}{2}$$
For these solutions to exist, we should have $a \ge -\frac{1}{4}$.
Consider $t_1$. There seems to be no problem with $t_1$ for $-\frac{1}{4} \le a$ . In this range of $a$ , $t_1$ seems to satisfy constraints (1),(2),(3) and (4).
Now consider $t_2$. If $a > 0$ then by constraint (2) we should have:
$$t_2^2 - 2t_2 \le a$$
$$(\frac{1 - \sqrt{1+4a}}{2})^2 - 2(\frac{1 - \sqrt{1+4a}}{2})= \frac{-1+2a+\sqrt{1+4a}}{2} \le a$$
$$-1+2a+\sqrt{1+4a} \le 2a$$
$$\sqrt{1+4a} \le 1$$
$$1+4a \le 1$$
$$a \le 0$$
which is a contradiction with our assumption of $a > 0$. So, $t_2$ does not exist for $a > 0$. There seems to be no problem with $t_2$ for $-\frac{1}{4} \le a \le 0$ . In this range of $a$ , $t_2$ seems to satisfy constraints (1),(2),(3) and (4).
Note that if $a = -\frac{1}{4}$ then $t_1=t_2=\frac{1}{2}$.
Let's now look at (6). The solutions to this quadratic equation are
$$t_3 = \frac{3 + \sqrt{5+4a}}{2} , t_4 = \frac{3 - \sqrt{5+4a}}{2}$$
For these solutions to exist, we should have $a \ge -\frac{5}{4}$ , but we also have the stricter constraint (4), which requires that $a \ge -1$.
Consider $t_3$. If $a > 0$ then $t_3$ violates constraint (3). So, $t_3$ does not exist for $a > 0$. On the other hand, if $-1 < a \le 0$ then by constraint (1) t should be non-negative and by the implication of constraint (2) we should have $0 \le t \le 2$. But applying this range of $a$ in the calculation of $t_3$ results in $2 < t_3$, which is in contradiction with constraint (2). Finally, note that if $a=-1$ then $t_3=2$ , but this result violates constraint (3). Therefore, it seems that $t_3$ is not a solution to the equation for any value of $a$.
Now consider $t_4$. It seems that for $a \ge -1$ , $t_4$ satisfies constraints (1),(2),(3) and (4).
Note that although in the formula we get $t_3=t_4=\frac{3}{2}$ for $a=-\frac{5}{4}$ , these are not solutions of the main equation, because the value of $a=-\frac{5}{4}$ violates constraint (4).
Now let us see in what conditions $t_1$ or $t_2$ might be equal to $t_4$. From $t_1 = t_4$ it follows that $a=-\frac{1}{4}$. Also, from $t_2 = t_4$ it follows that $a=-\frac{1}{4}$. So at $a=-\frac{1}{4}$ , $t_1=t_2=t_4=\frac{1}{2}$.
Summing up our above analyses, we can see that
$t_1$ exists for  $-\frac{1}{4} \le a$
$t_2$ exists for  $-\frac{1}{4} \le a \le 0$
$t_3$ does not exist
$t_4$ exists for $-1 \le a$
Therefore, for $a > 0$ , the equation has exactly two distinct solutions ($t_1 , t_4$).

A: Consider the function $$f(x)=\left(\log_2 x\right)^2-\log_{\sqrt 2} x-a+\sqrt{a+\log_2 x},$$ defined for all $x\ge 2^{-a}.$ Then we find that $$f'(x)=\frac{1}{2x\log_e 2\cdot \sqrt{a+\log_2 x}}\left(4\log_2 x\sqrt{a+\log_2 x}-4\sqrt{a+\log_2 x}+1\right).$$ Letting $M=\log_2 x,$ we see that $f'(x)=0$ whenever $16(M+a)(M-1)^2=1,$ or in other words when $$g(M)=16M^3+16(a-2)M^2+16(1-2a)M-1=0,$$ which is to say, when $\log_2 x =m,$ for some real number $m$ a root of the cubic in $M.$ This happens either once or thrice.
Now for exactly two roots of the original equation we must have a unique solution to the cubic. We find that the discriminant of $g'(M)$ is given by $$\Delta=16^2(a-2)^2-3\times 16\times 16(1-2a)=16^2(a+1)^2>0$$ for all real values of $a.$ Thus to ensure a unique solution we must have that $$g\left(\frac{a-2+|a+1|}{3}\right)g\left(\frac{a-2-|a+1|}{3}\right)>0.$$ This gives us a preliminary condition on $a.$
Now for the values of $a$ satisfying the inequality above we have ensured that $f'(x)$ vanishes exactly once, namely whenever $x=2^m,$ where $m=m(a)$ is the unique solution of $g(M)=0.$ Finally, since for $x\to +\infty,$ we have that $f(x)>0$ and for $x=2^{-a}$ we have that $f(x)=a(a+1),$ it follows that if $a=-1$ or $a=0$ we already have one root, and if these values of $a$ satisfy the previous condition then we have found two values of $a.$ On the other hand if $-1<a<0$ then there cannot be two roots if $a$ also satisfies the previous condition.
This leaves us with the case when $a<-1$ or $a>0,$ so that $f(2^{-a})>0.$ Thus in this case there are also exactly two roots provided the previous condition is satisfied and also the minimum value $f(2^m)$ is negative. This gives us a further condition on $a,$ namely that $(m-1)^2-(1+a)+\sqrt{a+m}<0.$
In summary we must have that $a$ satisfies the following conditions:
(1) $g\left(\frac{a-2+|a+1|}{3}\right)g\left(\frac{a-2-|a+1|}{3}\right)>0,$
and exactly one of the following:
(2) $a=-1$ or $a=0,$
or
(3) $a<-1$ or $a>0$ and $(m-1)^2-(1+a)+\sqrt{a+m}<0.$
Given these, then $f(x)=0$ has exactly two roots.
PS. Note that the conditions are to be selected as (1) and (2) or (1) and (3).

A: Somewhat oddly, this becomes easier by first eliminating $a$.  Using your substitution for $t$, let $b=\sqrt{a+t}$.  Then $a=b^2-t$ and the equation becomes
$$t^2 - 2t = b^2 - t - b$$
Or $$
0 = t^2 - b^2 - (t - b)
  = (t-b)(t+b-1)
$$
At this point it might be tempting to get back to $t$ by replacing $b$ with $\sqrt{a+t}$.  Don't do it.  When solving equations with radicals, it's almost always better to solve for the value of the radical instead of solving for the original variable.  The reason is that constraint on $b$ is just $b\ge0$, which is very convenient.  So keep solving for $b$ by getting rid of $t$ with $t = b^2-a$.
$$
\begin{cases}
(b^2 - b - a)(b^2 + b - a - 1)=0\\[2ex]
b\ge0
\end{cases}
$$
The 4 solutions for $2b$ and the requirement for $b\ge0$ are:

*

*$1-\sqrt{1+4a}$,  where $-1\le4a\le0$

*$1+\sqrt{1+4a}$,  where $-1\le4a$

*$-1+\sqrt{5+4a}$,  where $-4\le4a$

*$-1-\sqrt{5+4a}$, never non-negative

Whenever root 1 is valid, so are roots 2 and 3.  So, aside from degenerate roots, the only way to just have two roots is with roots 2 and 3 but not 1.  So, $a>0$
Degenerate Roots
It is important to remember that roots can be degenerate.  While we established that for $-1\le4a\le0$, there are 3 roots, we cannot eliminate that range just yet.  What if there's some value of $a$ in that range where 2 of the 3 roots are equal.
There are two possibilities

*

*$b_1 = b_2$
Then, $4a = -1$ and the third root $b_3$ equals the other two so we will have a triple degenerate root and only 1 distinct root.

*$b_3 = b_1$ or $b_3=b_2$
Then $-1+\sqrt{5+4a} = 1 \pm\sqrt{1+4a}$
But, since $$(\sqrt{5+4a}\pm\sqrt{1+4a})(\sqrt{5+4a}\mp\sqrt{1+4a})=4$$
If $\sqrt{5+4a}\pm\sqrt{1+4a} = 2$, then $\sqrt{5+4a}\mp\sqrt{1+4a} = 2$ from which it follows that $\sqrt{1+4a}=0$ and again we would end up with a triple degenerate root.
This leaves us with $a>0$ as the solution


text:
Q: How to append to an immutable List? When I run below code the size of userList is 0. I expect it to contain objects of type User as I am appending to them below. I'm not appending to the List userList correctly ?
object SimilarityData {

  val userList = List.empty[User]
  case class User(id: String, nCoordinate : Int)

  def getUsers(): List[User] =
    {

      userList :+
        new User("1", 101010101) :+
        new User("2", 111011101) :+
        new User("3", 101010101) :+
        new User("4", 101110101) :+
        new User("5", 101110101) :+
        new User("6", 101011101) :+
        new User("7", 101010101) :+
        new User("8", 101010101) :+
        new User("9", 111000111);

      userList
    }

  def main(args: Array[String]) {
    println(userList.size)
  }

}

A: *

*List is prepend-oriented data-structure. Appending to it has O(n) complexity, while prepending - O(1)

*List is an immutable data-structure, that's why you can't modify an existing value, but you can get a new value based on it. Think of String or Int.

Taking the above into account, to achieve optimal results you should update your code to the following:
  def getUsers : List[User] =
    new User("1", 101010101) +:
    new User("2", 111011101) +:
    new User("3", 101010101) +:
    new User("4", 101110101) +:
    new User("5", 101110101) +:
    new User("6", 101011101) +:
    new User("7", 101010101) +:
    new User("8", 101010101) +:
    new User("9", 111000111) +:
    userList

A: Appending to an immutable List appends the element to a new List. Since userList is immutable it is and will always be List.empty which is what it was assigned.
To get the size of userList after appending users return the new List that was created with the appends to get the right size. In Scala the last line in a method is the return value. Since userList :+ ... returns a new List this is equivalent to assigning userList to some return value and returning that.
object SimilarityData {

  val userList = List.empty[User]
  case class User(id: String, nCoordinate : Int)

  def getUsers(): List[User] =
    {
      userList :+
        new User("1", 101010101) :+
        new User("2", 111011101) :+
        new User("3", 101010101) :+
        new User("4", 101110101) :+
        new User("5", 101110101) :+
        new User("6", 101011101) :+
        new User("7", 101010101) :+
        new User("8", 101010101) :+
        new User("9", 111000111);
    }

  def main(args: Array[String]) {
    println(getUsers.size)
  }

}

Run it:
scala> SimilarityData.main(Array[String]())
9


text:
Q: Javascript or CSS fix for 100%  that doesn't fill page when IE11 is zoomed I have a scrolling <div> that is supposed to fill the visible area of the page:
<div id=allcontent style="width:100%;height:100%;overflow:scroll">
   (all page content)
</div>

When I zoom in with ctrl+ IE11, there is extra space below and to the right of my div, where I see the <body> background color.
I would like to resize the "allcontent" div to fill the page when IE zooms in, but I can't find a way to get the actual page size using javascript.
Is there either:

*

*a way to get the real page size from IE11 after clicking ctrl+, or

*a way to specify the <div> dimensions in CSS that will cause it to resize correctly with the page?
I have tried all sorts of measurements like ocument.body.clientWidth but not found anything that applies to the newly visible area outside of my <div>.
Even weirder: the page slowly scrolls to cover up the (wrongly) exposed body color.

A: The problem was the "auto zoom to viewport width" feature of IE11. The fix was to add the following to my CSS:
@media screen {
  @-ms-viewport {
    width: device-width;
  }
}

Microsoft: Internet Explorer... automatically scales content when the window is narrower than 1024 pixels... in cases where this automatic scaling is not needed or desired, the device-width keyword... signifies that the page is optimized to work well regardless of the width of the device.
I found the answer in this question.


text:
Q: How to convert a HttpResponse to an image in Django? just like screenshot I want a png file and some dynamic values as response for a view, and which is working fine. Now I need to convert this httpresponse to an image to upload to the s3 bucket. Just like taking a screenshot of the HttpResponse. Is there any package ? I tried imgkit and html2image, it didnt work well.
def home(request):
    im_io = io.BytesIO()
    im = Image.open(r'test.png')
    im.save(im_io, 'png', quality=70)
    im_io.seek(0)
    im_io_png = base64.b64encode(im_io.getvalue())
    context = im_io_png.decode('UTF-8')
    img_tag = mark_safe(f"<img src='data:image/png;base64, {context}'/>")
    return render(request, 'api/home.html',{'img_tag': img_tag})

A: I don't get what you wanna exactly todo... Do you wan't to put your image into the template, or return HttpResponse with file?
Basically your code should work fine I think, I used similar base64 converter in my project:
def get_file_data(file_path):
    """Get data of a file."""
    with open(file_path, 'rb') as f:
        data = f.read()
        f.close()
        return data

@register.simple_tag
def to_base64(path):
    """Convert to base64."""
    file_path = find(path)
    ext = file_path.split('.')[-1]
    file_str = base64.b64encode(get_file_data(file_path)).decode()
    return f'data:image/{ext};base64,{file_str}'

You can try to rewrite your logic to match my code.
But, if you need to return FileResponse, you can do this way:
return FileResponse(
    ContentFile(
        file_buffer.getvalue(),
        'YourImageName.extension'
    ),
    as_attachment=True,
)

Check it out.


text:
Q: Flattening 3D list of words to 2D I have a pandas column with text strings. For simplicity ,lets assume I have a column with two strings.
s=["How are you. Don't wait for me",  "this is all fine"]

I want to get something like this:
[["How", "are","you"],["Don't", "wait", "for", "me"],["this","is","all","fine"]]

Basically take each sentence of a document and tokenism into list of words. So finally I need list of list of string.
I tried using a map like below:
nlp=spacy.load('en')
def text_to_words(x):
    """ This function converts sentences in a text to a list of words

    """

    global log_txt
    x=re.sub("\s\s+" , " ", x.strip())
    txt_to_words= [str(doc).replace(".","").split(" ") for doc in nlp(x).sents]

    #log_txt=log_txt.extend(txt_to_words)

    return txt_to_words

The nlp from spacy is used to split a string of text into list of sentences.
log_txt=list(map(text_to_words,s))

log_txt

But this as you know would put all of the result from both the documents into another list
[[['How', 'are', 'you'], ["Don't", 'wait', 'for', 'me']],
 [['this', 'is', 'all', 'fine']]]

A: You'll need a nested list comprehension. Additionally, you can get rid of punctuation using re.sub.
import re

data = ["How are you. Don't wait for me",  "this is all fine"]
words = [
    re.sub([^a-z\s], '', j.lower()).split() for i in data for j in nlp(i).sents
]

Or,
words = []
for i in data:
    ... # do something here
    for j in nlp(i).sents:
        words.append(re.sub([^a-z\s], '', j.lower()).split())

A: There is a much simpler way for list comprehension.
You can first join the strings with a period '.' and split them again.
[x.split() for x in '.'.join(s).split('.')]

It will give the desired result.
[["How", "are","you"],["Don't", "wait", "for", "me"],["this","is","all","fine"]]

For Pandas dataframes, you may get an object, and hence a list of lists after tolist function in return. Just extract the first element.
For example,
import pandas as pd

def splitwords(s):
    s1 = [x.split() for x in '.'.join(s).split('.')]
    return s1

df = pd.DataFrame(s)
result = df.apply(splitwords).tolist()[0]

Again, it will give you the preferred result.
Hope it helps ;)


text:
Q: PHP exec() causes connection timeout when using nohup I have a class executing a python script using the exec() function in PHP. It gives me a timeout even tho i'm using nohup to run in in the background.
Server is running on 4GB memory and is an LXC container with centOS 8. Web engine is nginx.
Any ideas?
<?php

class Deployment {

  private $clusterName;
  private $vendor;
  private $nodeIP;
  private $password;
  private $cmd;

  public function task($clusterName, $vendor, $nodeIP, $password) {

    $this->cmd = escapeshellcmd('python3 /usr/share/nginx/python/script.py --ip '.$nodeIP.' --password '.$password);

    // Execute Job here
    exec($this->cmd);
  }

  // Method used to execute the python engine
  private function exec($cmd = null){
     if(!$cmd){
         throw new Exception("No command given");
         die('No command given');
     }
     shell_exec("/usr/bin/nohup ".$cmd." > /dev/null 2>&1 &");
  }
}

The error i'm getting:
2020/11/25 01:00:26 [error] 109#0: *5 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 192.168.10.225, server: _, request: "POST /dev/html/deploy.php HTTP/1.1", upstream: "fastcgi://unix:/run/php-fpm/www.sock", host: "172.16.10.202", referrer: "http://172.16.10.202/dev/html/deploy.php"

A: The problem was that I renamed my private function to exec() without thinking about this beeing an actual built-in PHP function.
This is the part of code I changed:
// Execute Job here
    $this->execTask($this->cmd);
  }

  // Method used to execute the python back-end engine
  private function execTask($cmd = null){
     if(!$cmd){
         throw new Exception("No command given");
         die('No command given');
     }
     shell_exec("/usr/bin/nohup ".$cmd." > /dev/null 2>&1 &");
  }


text:
Q: Powershell Passing Argument to background job I have a script with the following parameters:
[Parameter(ParameterSetName="FromPipe", Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [string[]]$ComputerName,
[Parameter(ParameterSetName="FromPipe", Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [string[]]$AppName,
[Parameter(ParameterSetName="FromPipe", Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [string[]]$key,
[Parameter(ParameterSetName="FromPipe", Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [string[]]$setting,

I want to run this script in the background but I've struggled with getting the arguments in. This script is a module. I can successfully run it from the command line with
start-job -InitializationScript {Import-Module ConfigureServer.psm1} -ScriptBlock {Get-ConfigureServerInput} -ArgumentList "google.com","Test1","Test2","Test3","-Verbose"

But here is the actual code in my script for starting the job:
$JobObj = New-Object PSObject
$JobObj | Add-Member -type NoteProperty -name ComputerName -value $($obj.ComputerName)
$JobObj | Add-Member -type NoteProperty -name AppName -value $($obj.AppName)
$JobObj | Add-Member -type NoteProperty -name key -value $($obj.key)
$JobObj | Add-Member -type NoteProperty -name setting -value $($obj.setting)
$JobObj | Add-Member -type NoteProperty -name Verbose -value $true
Write-Verbose "Starting job: -Name $JobName -FilePath Job-ConfigureServer.ps1 -ArgumentList $($JobObj)"
#Start-Job -Name $JobName -InitializationScript {import-module ConfigureServer.psm1} -ScriptBlock {Get-ConfigureServerInput} -ArgumentList $($JobObj) | Out-Null
#Start-Job -Name $JobName -InitializationScript {import-module ConfigureServer.psm1} -ScriptBlock {Get-ConfigureServerInput @ARGS} -ArgumentList $($JobObj) | Out-Null
Start-Job -Name $JobName -InitializationScript {import-module ConfigureServer.psm1} -ScriptBlock {Get-ConfigureServerInput -ComputerName $($obj.ComputerName) -AppName $($obj.AppName) -key $($obj.key) -setting $($obj.setting) -Verbose}
Start-Job -FilePath TestJob.ps1 -ArgumentList $($obj)

The uncommented Start-Job just runs a test script that dumps $args.
"Arguments: $($args.count)"
$args

Which results in:
PS E:\Powershell\ConfigureServer> get-job | receive-job
Arguments: 1

ComputerName : server.bogus.com
AppName      : iis
key          : default site
setting      : cert
RunspaceId   : 5c72401e-3cb1-4f44-b0e1-c370c8a3c200

Arguments: 1
ComputerName : fbravo
AppName      : Net
key          : IP
setting      : 10.11.12.13
RunspaceId   : 80b2095c-6129-4d7c-8e89-528cf93ce975

Arguments: 1
ComputerName : tfs.bogus.com
AppName      : edamame
key          : DLL
setting      : edamame.dll
RunspaceId   : f7727c69-121c-4a59-b646-a4f0eac53e7d

Arguments: 1
ComputerName : falpha
AppName      : IIS
key          : IP
setting      : 1.1.1.1
RunspaceId   : cd182911-d4a6-4bfd-ba4b-103ebaab20a3

Arguments: 1
ComputerName : web.bogus.com
AppName      : Net
key          : IP
setting      : 192.168.100.102
RunspaceId   : 03d6130c-46d1-483d-833c-781720fcc0cf

How do I format my Start-Job to successfully pass the arguments?
I've tried various formats of Start-Job with -FilePath, listing the arguments instead of passing an object, etc.
They all end up blocked waiting for user input prompting for the parameters.


text:
Q: Spatial distribution for intensity The paper Evanescently coupled multimode spiral spectrometer describes a novel approach to designing a spectrometer based on a waveguide. When I approached the authors with a question about the theory behind it I got back a somewhat cryptic response that I don't fully understand. Can anyone explain the following in mathematical terms i.e. explain what equations are being used.
In particular, what does "project" mean in:

Then you project that input field onto the modes of the waveguide.

The full text of the reply I got is:

To get the spatial distribution, you need to assume some spatial distribution of the input field at the input facet of the multimode waveguide. Then you project that input field onto the modes of the waveguide. Next, you use the ODE to find how each waveguide mode will propagate in the spiral, as explained in the supplementary information:
"We modeled the wave propagation in the spiral waveguide using the approach in [36, 37]. First we ignored the mixing of waveguide modes with different orders, which allowed us to simulate individual modes separately by solving the following two coupled equations:"
(If you don't have Comsol you will need to somehow figure out how to estimate the propagation constants and coupling coefficients for each waveguide mode)
After you solve the ODE for each waveguide mode, you know the superposition of the modes at the output of the waveguides. That will give you the spatial distribution at the output.

A: I don't think so. Firstly the instruction says field not intensity. The transverse field distributions of the waveguide modes (TE and TM together) form a complete orthogonal set of functions. So you can express the input transverse field distribution as a linear combination of the modes . That gives you the amplitude of the all the modes so you can predict the transverse field distribution in the output plane Note that it won't be the same because the modes will add up with different phases because of their different phase velocities.


text:
Q: Генерация меню WordPress Подскажите, пожалуйста, как можно сделать, чтобы меню генерировалось следующим способом: вместо тега "a" был тег "div". Ссылка записывалась в data-href='www.site.com', а название страницы в этом теге. Как и в каком файле можно реализовать такую идею?

         Title Link

Title Link

И можно сделать, чтобы была галочка, чтобы можно было выбирать каким способом размещать ссылку?

A: HTML-код меню можно поправить фильтром.
Добавьте в functions.php темы.
/**
 * Filters the HTML list content for navigation menus.
 *
 * @param string   $items The HTML list content for the menu items.
 * @param stdClass $args  An object containing wp_nav_menu() arguments.
 *
 * @return string
 */
function wp_nav_menu_items_action( $items, $args ) {
    $items = str_replace( '<a href=', '<div data-href=', $items );
    $items = str_replace( '', '
', $items );

    return $items;
}

add_action( 'wp_nav_menu_items', 'wp_nav_menu_items_action', 10, 2 );


text:
Q: How can I create a button that changes its background image to represent its states How can I create a button that changes its background image to represent the default, pressed or focused states?

A: Quite easy to do using a selector.
Create a new xml file inside the drawable folder containing the following:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/drawable_selected" android:state_selected="true"></item>
    <item android:drawable="@drawable/drawable_pressed" android:state_pressed="true"></item>
    <item android:drawable="@drawable/drawable_default"></item>

</selector>

Then refer to this selector in your Button:
<Button
     android:id="@+id/button"
     android:background="@drawable/selector_you_just_made"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:text="Button" />

More documentation and other possible states can be found here.

A: XML drawable:
<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/button_pressed"
              android:state_pressed="true" />
        <item android:drawable="@drawable/button_focused"
              android:state_focused="true" />
        <item android:drawable="@drawable/button_default" />
     </selector>

Button:
<Button
    android:id="@+id/button_send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage"
    android:background="@drawable/button_custom"  />

Here in section Custom background is more info


text:
Q: Remove a slide in Swiper React I want to remove the first slide in react with swiper js. I looked in the API and found swiper.removeSlide(slideIndex), but that doesn't seem to work. I am using the useSwiper hook. But still, I am getting 'swiper.removeSlide is not a function'. Anyone
how I could handle this?
import React, { useEffect } from "react";
import { useSwiper } from "swiper/react";

const DeleteSlide = ({}) => {
  const swiper = useSwiper();

  useEffect(() => {
    setTimeout(() => {
      swiper.removeSlide(0);

      swiper.activeIndex = 0;
      swiper.initialSlide = 0;
    }, 9000);
  }, []);

  return <></>;
};

export default DeleteSlide;

A: You need to import 'Manipulation' module.
import SwiperCore, { Manipulation } from 'swiper';

SwiperCore.use([ Manipulation ]);

This works for me.

A: I think if you are passing the array of images for swiper then while passing the array, you can use array.slice(1, images.length-1) so the first image will be excluded


text:
Q: Elasticsearch fuzziness gave results that not match the levenstein distance I try to implement fuzzysearch like explained here
{
  "query": {
     "match" : {
        "term": {
          "query" : "At what age do dogs go into heat?",
          "fuzziness": "5"
        }
     }
  },
  "size" : 20
}

gives me results as:

*

*What does it mean when a dog is in heat? (distance - 23)

*What does it mean when a dog is in heat? (distance - 29)
etc

My index is
"db-terms": {
    "aliases": {},
    "mappings": {
        "properties": {
            "term": {
                "type": "text",
                "analyzer": "english"
            }
        }
    },

What am I doing wrong ?


text:
Q: Nested FPifeq : Extra \fi error I want to have a command Unit with 1 parameter that return :

*

*nothing if the parameter is 1

*- if the parameter is -1

*the parameter in any other case

The goal is to show x and -x instead of 1*x* and -1*x* in my randomly generated exercices.
Here is the command I made :
\newcommand\Unit[1]{\FPifeq#1{1}{}\else\FPifeq#1{-1}{-}\else#1\fi\fi}

However, it generate the following error
Extra \fi

Minimal example :
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[french]{babel}
\usepackage[T1]{fontenc}
\usepackage{geometry}
\geometry{hmargin=1cm,vmargin=1cm}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{fp}

\begin{document}

\newcommand\Unit[1]{\FPifeq#1{1}{}\else\FPifeq#1{-1}{-}\else#1\fi\fi}

\Unit{2}x \Unit{1}x \Unit{-1}x

\end{document}

A: You don't need fp for that. TeX can do integer comparison with \ifnum. This:
\documentclass{article}
\newcommand\Unit[1]{%
  \ifnum#1=1
    % nothing
  \else
    \ifnum#1=-1
      -%
    \else
      #1%
    \fi
  \fi}
\begin{document}
\Unit{2}x \Unit{1}x \Unit{-1}x
\end{document}

produces 2x x -x.

If you want to use fp, then you need to hide the second test in another macro. Apparently fp doesn't like nested conditionals:
\newcommand\Unit[1]{%
  \FPifeq{#1}{1}%
    % nothing
  \else
    \UnitInner{#1}%
  \fi}
\newcommand\UnitInner[1]{%
  \FPifeq{#1}{-1}%
    -%
  \else
    #1%
  \fi}

However, I recommend you use expl3 and it's own FPU. It's much more flexible and allows you to easily compose nested conditionals:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewExpandableDocumentCommand \Unit { m }
  {
    \fp_compare:nF { #1 == 1 }
      {
        \fp_compare:nTF { #1 == -1 }
          { - }
          { #1 }
      }
  }
\ExplSyntaxOff
\begin{document}
\Unit{2}x \Unit{1}x \Unit{-1}x
\end{document}

A: The macro \FPifeq doesn't like to be nested in a conditional, because it is not a conditional. Its structure is basically

*

*do some comparisons that eventually help to decide whether to execute \FP@testtrue or \FP@testfalse, which make \ifFP@test equal to either \iftrue or \iffalse;

*set \ifFPtest equal to \ifFP@test;

*release \ifFPtest in the input stream.

However, TeX does not recognize \FPifeq as a conditional, so with your macro
\FPifeq#1{1}{}\else\FPifeq#1{-1}{-}\else#1\fi\fi

the following happens

*

*when #1 is 1, then \ifFPtest is \iftrue, and we end up with
\iftrue{}\else\FPifeq#1{-1}{-}\else#1\fi\fi

Now {} will be left in the input stream and the \else will remove everything up to the matching \fi. Oh, no! Another \fi remains!

*when #1 is not 1, then \ifFPtest is \iffalse, and we end up with
\iffalse{}\else\FPifeq#1{-1}{-}\else#1\fi\fi

Now everything up to \else is removed and we remain with
\FPifeq#1{-1}{-}\else#1\fi\fi

but TeX remembers it has removed an \else. Then everything will work well, because at the end of the job of \FPifeq either \iftrue or \iffalse will result. The trailing \fi corresponds to the \else removed in advance, so it doesn't harm.
There are a few glitches in your code: it should be {#1} throughout, otherwise a value such as 12 would take 1 as the first argument to \FPifeq and 2 as the second argument.
You could fix the nesting problem by doing
\newcommand{\FPeq}{TT\fi\FPifeq}
\newcommand\Unit[1]{%
  \if\FPeq{#1}{1}%
    % do nothing
  \else
    \if\FPeq{#1}{-1}%
      -%
    \else
      #1%
    \fi
  \fi
}

This is an old trick that uses \if to make the problem above vanish; if \if is expanded, it sees TT\fi, which results in a true test and \FPifeq will be executed; if it is in skipped text, it will correctly match a corresponding \else or \fi.
However, the usage of \FPifeq has bad consequences on the final output. Let's see an example:
\documentclass{article}
\usepackage[nomessages]{fp}

\newcommand{\FPeq}{TT\fi\FPifeq}
\newcommand\Unit[1]{%
  \if\FPeq{#1}{1}%
    % do nothing
  \else
    \if\FPeq{#1}{-1}%
      -%
    \else
      #1%
    \fi
  \fi
}

\begin{document}

$\Unit{2}x$ $\Unit{1}x$ $\Unit{-1}x$

$2x$ $x$ $-x$

\end{document}

Can you see the problem? The working of \FPifeq creates an empty math atom, so the minus sign is treated as a binary operator rather than a unary, if leading the polynomial.
The problem does not show with Phelype Oleinik's code using expl3.


text:
Q: #if statment to array of macros in Swift I set a target macros under TARGETS -> Target's Name -> Build Settings -> Other Swift Flags as 'Target#1' and for the other target as 'Target#2'. Now I have an #if statement that is checking which target is currently running and I want to do something different to each one of those targets, it goes like that:
#if Target#1 || Target#2
DoSomething()
#endif

or
#if Target#1
DoSomething()
#elseif Target#2
DoSomethingElse()
#endif

What I want to do is to make it a little bit easier to edit in one place instead of multiple locations inside my code, instead of adding to each #if statement the target's name, I just want to check if the macro is inside an array of macros. Something like that:
#define TARGETS_FOR_OPTION_1 [Target#1, Target#2, Target#3]
#define TARGETS_FOR_OPTION_2 [Target#4, Target#5, Target#6]

#if TARGETS_FOR_OPTION_1
DoSomething()
#elseif TARGETS_FOR_OPTION_2
DoSomethingElse()
#endif

Is that possible in Swift?

A: Rather than scattering your conditional checks all over your code base, refactor using the Replace Conditional with Polymorphism technique.

*

*Make a protocol that describes the operations that need to be done differently between different contexts

*For each context you need to support, implement one conformance of the protocol

*Make one centralized place that owns the "switching logic" which picks between the various objects. It will contain all your macros.

*All other areas of your code base just use the switching logic to obtain an object that's appropriate for the context (without them needing to know what that means, exactly), whose methods they can just call.

Suppose the example was calling system APIs on Windows, macOS and Linux. You might have 3 conformances to your "SystemAPI" protocol, each of which calls system-specific logic. For this reason, you'll need to make sure that the windows file is only a member of your windows target, the macOS file is only a member of your macOS target, and so on.
Alternatively, you could have all files be members of all targets, but you'd need to wrap their contents in #if/#endif so that they're effectively empty for targets besides the one they're intended for.
Also, in the file that contains the switching logic, you'll need to use these conditionals to filter out references to the code that doesn't exist. E.g. the Linux target can't reference the Windows conformance (since it won't exist)


text:
Q: Desktop in AWS ubuntu bionic instance I've created a EC2 instance in AWS with Ubuntu 18.04 bionic, and I'm connected with it using Putty Successfully.
But I only can see (use) the terminal and don't know how to deploy (either download or install) bionic desktop. I need it in order to install some programs in which graphical interface is required.

A: As you can see here it is possible. I don't use AWS, so I could not say if it is acceptable to have a server instance and install desktop packages and services to it.
I think, you should to ask Amazon support before installing any desktops to it.
Amazon guide gives the next instructions:

Note: These instructions apply only to Amazon Linux 2. To confirm
  which version you're running, run the command:
cat /etc/os-release

sudo amazon-linux-extras install mate-desktop1.x
sudo bash -c 'echo PREFERRED=/usr/bin/mate-session > /etc/sysconfig/desktop'
echo "/usr/bin/mate-session" > ~/.Xclients && chmod +x ~/.Xclients
sudo yum install tigervnc-server
vncpasswd
vncserver :1
sudo cp /lib/systemd/system/vncserver@.service /etc/systemd/system/vncserver@.service
sudo sed -i 's/<USER>/ec2-user/' /etc/systemd/system/vncserver@.service
sudo systemctl daemon-reload
sudo systemctl enable vncserver@:1
sudo systemctl start vncserver@:1

Connect to the GUI using the VNC

*

*Install the TigerVNC software on your local computer, if it's not already installed. TigerVNC is available for Linux, Windows, and
  macOS. See the TigerVNC website to access the download.

*On your local computer, use SSH to connect to your instance while creating a tunnel to forward all traffic on local port 5901/TCP
  (VNC) to the instance's VNC server.


text:
Q: jquery full calender Currently my page has a jQuery Full Calendar and a button at the bottom of the page. The user selects a start and end date on the calendar by clicking and dragging, and clicks the button at the bottom of the page. I want to get the start and end date of the current selection on the jQuery full calendar in the button click function. Can any one tell me how I could grab the event start and event end date in the button click function.
Any help is appreciated.

A: Have you looked at the docs:
http://arshaw.com/fullcalendar/docs/event_data/startParam/
I assume one of the following can help you:
startParam, endParam, eventClick


text:
Q: Unity Raycasting problem in some part of the scene I started doing some simple stuff in Unity (goal is to make a great game) so I made a simple Player Controller.
public class PlayerController : MonoBehaviour
{
    public float walkingSpeed;
    public float jumpSpeed;
    public bool jumpFlag = false;
    public float maxJumpDistance = 1.0f;
    Rigidbody rb;
    Collider col;
    Vector3 playerSize;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        col = GetComponent<Collider>();
        playerSize = col.bounds.size;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        WalkHandler();
        JumpHandler();
    }

    void WalkHandler()
    {
        float horizonstalAxis = Input.GetAxis("Horizontal");
        float verticalAxis = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(-horizonstalAxis * walkingSpeed * Time.deltaTime, 0, -verticalAxis * walkingSpeed * Time.deltaTime);
        rb.MovePosition(transform.position += movement);
    }

    void JumpHandler()
    {
        float jumpAxis = Input.GetAxis("Jump");
        //Debug.Log(jumpAxis);
        if (jumpAxis > 0)
        {
            bool isGrounded = CheckGrounded();
            if (jumpFlag != true && isGrounded)
            {
                jumpFlag = true;
                Vector3 jumpVector = new Vector3(0, jumpSpeed * Time.deltaTime, 0);
                rb.AddForce(jumpVector, ForceMode.VelocityChange);
            }
        }
        else
        {
            jumpFlag = false;
        }

    }

    bool CheckGrounded()
    {
        Vector3 checkerPoint = transform.position + new Vector3(0, -playerSize.y / 2, 0);
        bool grounded = Physics.Raycast(checkerPoint, -Vector3.up, maxJumpDistance);
        return grounded;
    }

I came across a wierd problem. In some parts of the scene my method JumpHandler is not working. After reaching some z coordinates, the CheckGrounded returns False instead of True, even though the Raycast direction is set down.
Can anyone help?


text:
Q: Dynamically scaling set of coordinates in a dictonary This is the dictionary I am trying to get into a scaling/dynamic dictionary.
koordinatstring = {
    CoordinateTitle:
    {
        PositionTitle:
        {
            "X": Xvalue,
            "Y": Yvalue
        },
        PositionTitle:
        {
            "X": Xvalue,
            "Y": Yvalue
        },
    }
}

I'm trying to create a loop that will let me create exactly as many sets of coordinates that will look like this:
PositionTitle:
{
     "X": Xvalue,
     "Y": Yvalue
},

Where PositionTitle and "X": Xvalue and finally "Y": Yvalue are variables I get from other sources.
And at the end I dump all this as a Json.
To Clarify.
I am looking to iterate through a loop that when I tell it too either through a set of hotkeys, like ctrl-4 or E the loop will terminate and continue to on with other code I might have.
But while the loop runs, it should be able to create anything from
koordinatstring = {
    CoordinateTitle:
    {
        PositionTitle:
        {
            "X": Xvalue,
            "Y": Yvalue
        },
    }
}

as a dictonary to this:
koordinatstring = {
    CoordinateTitle:
    {
        PositionTitle:
        {
            "X": Xvalue,
            "Y": Yvalue
        },
        PositionTitle:
        {
            "X": Xvalue,
            "Y": Yvalue
        },
        PositionTitle:
        {
        "X": Xvalue,
        "Y": Yvalue
        },
        PositionTitle:
        {
        "X": Xvalue,
        "Y": Yvalue
        },
    }
}

I believe you would call this scale ability or something similar when it comes to programming.

A: Use collections.namedtuple,
from collections import namedtuple

Point = namedtuple('Point', 'x y')

pt1 = Point(2.0, 3.0)


text:
Q: Is there an alternative widget to listbox? I am trying to create a messaging program for fun. I intend to use this with friends and family, so I want to treat it as I am making actual software that will be used by others.
After thinking about the future of the project, I realized that images, videos and gifs should be shared over the application, without having to lead to external sites like giphy (I don't mind embedding videos though).
Currently, I am using a Listbox to display the messages, but that comes with a lot of limitations. Mainly in presentation, no messaging programs select messages like a cell in a spreadsheet. But also in future functions, you cannot add an image to Listbox, you cannot add a video or gif (also you aren't technically adding planned things to the Listbox, just whatever data is sent to the client as I am using sockets).
In short, I need a widget that can share text, video (most standard formats like mp4), audio (mp3, wav, ogg, etc.) and images (jpg, png, gif). This widget also should be easy to use for my sort of program, which is just a messaging application.
If this very specific widget doesn't exist, then what could I do to fulfill the above instead?


text:
Q: UCanAccess: unexpected token from spaces I'm trying to insert numbers/text into a table, but when the program tries to insert the text, I get the error
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.2 unexpected token: EX1 required: )
Here is my relevant code:
try (Connection conn = DriverManager.getConnection(
   "jdbc:ucanaccess://" + dbPath
   +   ";newdatabaseversion=V2010"
   )) {
   DatabaseMetaData dmd = conn.getMetaData();
     try (ResultSet rs = dmd.getTables(null, null, tableName, new String[] { "TABLE" })) {
          try (Statement s = conn.createStatement()) {
                ResultSet resultSet;
                String tableName = "Database";
                s.executeUpdate("CREATE TABLE " + tableName +" ( [SUBJID]
                INTEGER, [PARAMCD] TEXT, [PARAM] TEXT, [AVAL] DOUBLE)");
                String s1="Text Ex1";
                String s2="Text Ex2";
                int a=3;
                double b=2;
                resultSet = s.executeQuery("SELECT * FROM " + tableName);
                s.executeUpdate("INSERT INTO " + tableName
                    + " ( SUBJID, PARAMCD, PARAM, AVAL)"
                    + " VALUES ( "+ a+", " + s1 + ", " + s2 +" , " + b +" )");

It looks to me that the error is caused when a blank space appears. I've tried changing s1 to "TextEx1" and s2 to "TextEx2", which gives me the error of net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.2 user lacks privilege or object not found: TEXTEX1.
Thanks in advance for any help anyone can offer.

A: You want to do something like this:
String sql = "INSERT INTO [" + tableName + "] (SUBJID, PARAMCD, PARAM, AVAL) VALUES (?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, a);
ps.setString(2, s1);
ps.setString(3, s2);
ps.setDouble(4, b);
ps.executeUpdate();


text:
Q: neural network - Predict MNIST digits only with one neuron in the output layer Is it possible to create a neural network where we have one neuron in the output layer which can directly predict digit from NMIST dataset after trainining. eg, if we give digit 3 as input, the output layer neuron should give output value close to 3.
Note: There might be any number of neurons with any number of hidden layers.
Thanks in advance.
This is what I have tried using Tensorflow.
import tensorflow as tf
from mnist import MNIST
import numpy as np

inputs = tf.placeholder(tf.float32, shape=(1, 784))
labels = tf.placeholder(tf.float32, shape=(1, 1))

logits = tf.layers.dense(inputs, 1)
loss = 9.0 * tf.sigmoid(logits) - labels # As we want predicted value in [0 - 9]

train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

init = tf.global_variables_initializer()

with tf.Session() as sess:
  sess.run(init)
  mnist = MNIST()
  for i in range(100001):
    data, label =  mnist.get_train_data()
    lab = np.zeros((1,1), np.float32)
    lab[0][0] = label
    _, _loss, _logits= sess.run([train_op, loss, logits], feed_dict={inputs: np.reshape(data, (1, 784)), labels: lab})
    if i%5000 == 0:
      print("Step: %d Loss: %6f <== logits %s, Actual: %6f" % (i, _loss, str(_logits),  label))

Step: 0 Loss: -0.436195 <== logits [[ 0.02835961]], Actual: 5.000000
Step: 5000 Loss: -6.999933 <== logits [[-11.80182171]], Actual: 7.000000
Step: 10000 Loss: -2.999990 <== logits [[-13.7065649]], Actual: 3.000000
Step: 15000 Loss: -4.999864 <== logits [[-11.09644413]], Actual: 5.000000
Step: 20000 Loss: -5.000000 <== logits [[-17.01583481]], Actual: 5.000000
Step: 25000 Loss: -2.999971 <== logits [[-12.66251564]], Actual: 3.000000
Step: 30000 Loss: -2.999927 <== logits [[-11.72266102]], Actual: 3.000000
Step: 35000 Loss: -0.999898 <== logits [[-11.38729763]], Actual: 1.000000
Step: 40000 Loss: -7.000000 <== logits [[-17.59585381]], Actual: 7.000000
Step: 45000 Loss: -3.000000 <== logits [[-17.72655296]], Actual: 3.000000
Step: 50000 Loss: -5.000000 <== logits [[-16.65830421]], Actual: 5.000000
Step: 55000 Loss: -6.999999 <== logits [[-15.97771645]], Actual: 7.000000
Step: 60000 Loss: -3.000000 <== logits [[-17.10641289]], Actual: 3.000000
Step: 65000 Loss: -4.999984 <== logits [[-13.26896667]], Actual: 5.000000
Step: 70000 Loss: -5.000000 <== logits [[-19.57778549]], Actual: 5.000000
Step: 75000 Loss: -2.999995 <== logits [[-14.30502892]], Actual: 3.000000
Step: 80000 Loss: -2.999982 <== logits [[-13.13857365]], Actual: 3.000000
Step: 85000 Loss: -0.999971 <== logits [[-12.63682747]], Actual: 1.000000
Step: 90000 Loss: -7.000000 <== logits [[-19.08620071]], Actual: 7.000000
Step: 95000 Loss: -3.000000 <== logits [[-19.23719406]], Actual: 3.000000
Step: 100000 Loss: -5.000000 <== logits [[-17.85402298]], Actual: 5.000000

A: It is possible of course, but it is not a good idea. Digit recognition is a classification problem. By only using a single output neuron you are proposing to treat it as a regression problem. The implicit assumption you are making is that numbers that are close to each other numerically also look similar. This is obviously not the case. For instance, 3 and 5 look more similar than 3 and 4 as the bottom part is the same.

A: I agree with @Geerth, but want to add just one bit. Indeed, it's real if you use regression model instead of classification. But regression models assume that your input is ordered (you can use any order, for example 1,2,3.... or 1,3,2,5,4 or any other and your model will have different parameters).
"Introduction to Statistical Learning" book has some good ideas about it (and it's free).


text:
Q: change UIButton click area after adding image programmatically I'm using a UIButton as a link, theres a change there will be no image so I have it set to 0 height but its a loose priority so when I add an image it will expand. Issue is the clickable area isn't expanding with the image being added.
Currently Im trying to add the image like this.
    [self.advertisementButton sd_setBackgroundImageWithURL:[NSURL URLWithString:url]
                                                  forState:UIControlStateNormal];
    [self.advertisementButton setFrame:self.advertisementButton.imageView.bounds];
    [self.advertisementButton layoutIfNeeded];

A: First you download your image, then set you button frame with the image size.
Here you are taking the button's imageView property to set the button frame
// Download like
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: @"imageurl"]];
    UIImage *image = [UIImage imageWithData: imageData];

// Set frame like
    [advertisementButton setFrame:CGRectMake(advertisementButton.frame.origin.x, advertisementButton.frame.origin.y, image.size.width , image.size.height)];


text:
Q: Convert R dataframe into h2o object - error: Provided column type ordered is unknown I am running the following code in R
library(h2o)
h2o.init()

df <- as.h2o(diamonds)

and get back the following error:
ERROR: Unexpected HTTP Status code: 412 Precondition Failed (url = http://localhost:54321/3/Parse)

water.exceptions.H2OIllegalArgumentException
 [1] "water.exceptions.H2OIllegalArgumentException: Provided column type ordered is unknown.  Cannot proceed with parse due to invalid argument."
 [2] "    water.parser.ParseSetup.strToColumnTypes(ParseSetup.java:240)"
 [3] "    water.api.ParseHandler.parse(ParseHandler.java:21)"
 [4] "    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)"
 [5] "    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)"
 [6] "    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)"
 [7] "    java.lang.reflect.Method.invoke(Method.java:498)"
 [8] "    water.api.Handler.handle(Handler.java:60)"
 [9] "    water.api.RequestServer.serve(RequestServer.java:462)"
[10] "    water.api.RequestServer.doGeneric(RequestServer.java:295)"
[11] "    water.api.RequestServer.doPost(RequestServer.java:221)"
[12] "    javax.servlet.http.HttpServlet.service(HttpServlet.java:755)"
[13] "    javax.servlet.http.HttpServlet.service(HttpServlet.java:848)"
[14] "    org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)"
[15] "    org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:501)"
[16] "    org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)"
[17] "    org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:427)"
[18] "    org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)"
[19] "    org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)"
[20] "    org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)"
[21] "    org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)"
[22] "    water.webserver.jetty8.Jetty8ServerAdapter$LoginHandler.handle(Jetty8ServerAdapter.java:119)"
[23] "    org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)"
[24] "    org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)"
[25] "    org.eclipse.jetty.server.Server.handle(Server.java:370)"
[26] "    org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)"
[27] "    org.eclipse.jetty.server.BlockingHttpConnection.handleRequest(BlockingHttpConnection.java:53)"
[28] "    org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:984)"
[29] "    org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1045)"
[30] "    org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:861)"
[31] "    org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:236)"
[32] "    org.eclipse.jetty.server.BlockingHttpConnection.handle(BlockingHttpConnection.java:72)"
[33] "    org.eclipse.jetty.server.bio.SocketConnector$ConnectorEndPoint.run(SocketConnector.java:264)"
[34] "    org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)"
[35] "    org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)"
[36] "    java.lang.Thread.run(Thread.java:748)"

Error in .h2o.doSafeREST(h2oRestApiVersion = h2oRestApiVersion, urlSuffix = page,  :

ERROR MESSAGE:

Provided column type ordered is unknown.  Cannot proceed with parse due to invalid argument.

It is not very clear what is wrong.

A: The diamonds dataset (at least the one from ggplot2) includes variables of the ordered class:
> str(diamonds)
Classes 'tbl_df', 'tbl' and 'data.frame':   53940 obs. of  10 variables:
 $ carat  : num  0.23 0.21 0.23 0.29 0.31 0.24 0.24 0.26 0.22 0.23 ...
 $ cut    : Ord.factor w/ 5 levels "Fair"<"Good"<..: 5 4 2 4 2 3 3 3 1 3 ...
 $ color  : Ord.factor w/ 7 levels "D"<"E"<"F"<"G"<..: 2 2 2 6 7 7 6 5 2 5 ...
 $ clarity: Ord.factor w/ 8 levels "I1"<"SI2"<"SI1"<..: 2 3 5 4 2 6 7 3 4 5 ...
 $ depth  : num  61.5 59.8 56.9 62.4 63.3 62.8 62.3 61.9 65.1 59.4 ...
 $ table  : num  55 61 65 58 58 57 57 55 61 61 ...
 $ price  : int  326 326 327 334 335 336 336 337 337 338 ...
 $ x      : num  3.95 3.89 4.05 4.2 4.34 3.94 3.95 4.07 3.87 4 ...
 $ y      : num  3.98 3.84 4.07 4.23 4.35 3.96 3.98 4.11 3.78 4.05 ...
 $ z      : num  2.43 2.31 2.31 2.63 2.75 2.48 2.47 2.53 2.49 2.39 ...

> sapply(diamonds, class)
$carat
[1] "numeric"

$cut
[1] "ordered" "factor"

$color
[1] "ordered" "factor"

$clarity
[1] "ordered" "factor"

$depth
[1] "numeric"

$table
[1] "numeric"

$price
[1] "integer"

$x
[1] "numeric"

$y
[1] "numeric"

$z
[1] "numeric"

The error message seems to suggest that h2o does not support that class. You should convert them to a different class first, e.g. factor or character.


text:
Q: Ember Restore State when Routing I have a application controller with a input bound to searchTerms and on click I am routing to search-results route. The code is from a book
Rocknrollcall.Router.map(function() {
    // Add your routes here
    this.route('search-results', {
        path: 'search/:term'
    });

  });

});
Rocknrollcall.ApplicationController = Em.ObjectController.extend({
       searchTerms: '',
       actions: {
       submit: function() {
          this.transitionToRoute('search-results',this.get('searchTerms'));
        }
     }
   });
In the route I am returning some data I am rendering in search results
Rocknrollcall.SearchResultsRoute = Ember.Route.extend({
  model: function (query) {
     // ajax call
     return {artists: artists, songs: songs}
   });

}

});
Everything works fine. If I go from index and enter say tom I go to this URL
"http://localhost:9000/#/search/tom"
with all data.
However the point is when I put the URL directly in browser I do get the data. But the search term input box in the application template is empty. I would like to populate that also somehow. My question is what is the best solution to do so in Ember properly?
Let's try to elaborate a bit. The search term input is in application template
                <script type="text/x-handlebars" data-template-name="application">
                      {{input action="submit" type="text" class="search-input" placeholder="Search for artists or song names" valueBinding="controller.searchTerms"}}
                       <button {{action "submit"}} class="btn btn-primary"></button>
                      {{outlet}}
                </script>

Now if the user kind of bookmarks the URL with the search term and comes back the outlet is properly rendered by going through the route model. However the search term input which is bound to a variable in the application controller is empty because I did not restore it . I would like to know how to restore the input in the application template with the search term in URL when directly going to "http://localhost:9000/#/search/tom"? Or Is it a good idea to move the input  to the child template in this case artists that is rendered in the outlet?
JSBin URL: http://jsbin.com/kopovikibi/1/edit?html,js,output

A: In your model hook, right before your return the JSON data, just call
this.controllerFor("application").set("searchTerms", query.term);

This will modify the textfield in the application template, because it is bound to the searchTerms property of your application controller.
Working solution here


text:
Q: Nexus 3 Docker Content Selector selects too many images I am using Nexus 3 as a docker repository and want to create a user that has only read-only access to a specific docker image (and its related tags)
For this I created a Content Selector with the following query (The name of the image is test for demonstration purposes):
format == "docker" and path =~ "^(/v2/|/v2/library/)?(test(/.*)?)?$".
Then I created a Privilege with the action read, bound that to a role and added it to the user.
All is well, when I use the limited user I can fetch the image and not push.
However, I can still pull images I should not be able to pull.
Consider the following: I create an image called testaaa:1 on the docker registry. Afterwards I docker login to the registry using my user with read-only access. I am suddenly able to pull docker pull hub.my-registry.com/testaaa:1 even though according to the query I should not be able to.
I tested the query in a Java Regex Tester, the query would not select testaaa. Am I missing something? I am having a hard time finding clues on this topic.
EDIT: Some more testing reveals that my user is actually able to pull all images from this registry. The Content Selector query I used is exactly the one suggested by the Sonatype documentation Content Selectors and Docker - REST API vs Docker Client

A: I have figured it out. The issue was not the Content Selector query, but a capability that I previously added. The capability granted any authenticated user the role nx-anonymous which lets anyone view any repository in Nexus. This meant that any authenticated user was allowed to read/pull any image from the repository.
This error was entirely on my part. In case anyone has similar issues go have a look in the Nexus Settings -> System -> Capabilities and check if there are any capabilities that give your users unwanted roles.


text:
Q: Exception 'illegal buffer' thrown in protobufjs I am using protobufjs to manage my data over an API. It works perfectly most of the time but in one instance of a message I get an 'illegal buffer' exception. This is thrown by some internal code in the library. I am pasting here the Chrome debugger visual while stopped at a breakpoint se to the throw statement.
Chromer debugger output
As you can see, Chrome tells me that the buffer is indeed an Uint8Array (of 755 bytes). Why the if statement resolved into false and cause the throw statement to be executed? Both "buffer instanceof Uint8Array" and "Array.isArray(buffer)" are true.
UPDATE
I wrote some code (eseentailly copied it from protobufjs and simplified it):
function test() {
    var data = new Uint8Array([10, 9, 18, 7, 99, 111, 110, 110, 101, 99, 116, 16, 1]);
    testProtobuf(data);
}

function Reader(buffer) {
    this.buf = buffer;
    this.pos = 0;
    this.len = buffer.length;
}

var create_array = function (buffer) {
    console.log(buffer);
    if (buffer instanceof Uint8Array || Array.isArray(buffer))
        return new Reader(buffer);
    throw Error("illegal buffer");
}

function testProtobuf (data) {
    try {
        create_array(data);
    }
    catch (e) { console.log('Exception')};
}

When I call test(), which calls testProtobuf, which in turn calls create_array no exception is thrown. I also call testProtobuf from my onmessage method in the real code. In this case, an exception is still thrown. As you can see, I log the buffer on the console. Both logs are identical (I made sure the test data was the same).
Here is the Chrome console:
Console output in Chrome

A: I found a solution for this problem here:
Sample.deserializeBinary(Array.from(buffer));

And there is an example from my typescript code:
const arrayBuffer = await res.arrayBuffer();
const array = new Uint8Array(arrayBuffer);
const response: Uint8Array = (Array.from(array) as unknown) as Uint8Array;
rpcImplCallback(null, response);

A: You need to massage the response a little bit before it's ready to be tested/decoded ..
const lResponse = await res.arrayBuffer();
const lResponseData = ProtoModel.decode(new Uint8Array(lResponse));


text:
Q: Google Analytics: break up reporting by sub sections I have a Website (MOSS 2007) that has multiple URLS which is tracked by Google Analytics using the following code:
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-11111111-1']);
  _gaq.push(['_setDomainName', 'none']);
  _gaq.push(['_setAllowLinker', true]);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

This has been added to the Master Pages.  We now want to break down the reporting so instead of just reporting for the entire site we can see information for different subsites.  I could define a separate Analytics ID and have completely separate data, but is there a better way to somehow "tag" the analytics hits so we view either the entire site's information or just SubSite1, SubSite2, etc?  The sites we want to do this for have their own master pages, so applying unique code to just the subsites is not a problem.

A: You've described a key use case for a Google Analytics feature beta released in Nov '08, called "Advanced Segments".
In essence, you can hide all of your data from the current data view (as well as any subsequent data views) except for one or more of your "sub-sites."
To configure:

*

*From the main Dashboard view (first page after you select Account, then Profile), In the upper right hand corner, you'll see a drop-down menu labelled Advanced Segment. Click the right corner to open the menu and you'll see two check-box menus side-by-side, Default Segments on the left and Custom Segments next to it, which should be empty at the moment

*Click Create a new advanced segment (to the left of Default Segments)

*To create an Advanced Segment, you need to specify a name, a dimension or metric, a condition, and a value

*Dimension/Metric: you select the appropriate one by finding it in the nav panel to the left and dragging it into the outline box marked "dimension or metric"

*In this case, you probably want the Dimension called Page under the Content heading. (This dimension is actually the URL.) With your cursor on the grid at the left edge of the "Page" Dimension, drag it up and to the right so that it is inside the "dimension or metric" box

*Doing that will cause Condition and Value to appear

*Condition:  you might want to select Starts With

*Value: something like: "/subdirectory_of_subsite/" (without the quotes)

*Name: give the segment a Name in the text box near the bottom

*I would recommend not clicking on "Create Segment" or "Create and Apply to Report"--yet. Instead, first click Test Segment (middle righthand side of the page) to make sure it works (i.e., it successfully collected pages)

*To view data using the Advanced Segment, you have to go into the AS menu and click the checkbox next to that Advanced Segment then uncheck the All Visits checkbox in the Default Segments

*Close the AS menu and you are back at the main Dashboard view, which will show you the usual view except that the plots show data only for the Advanced Segment you just created and selected.
A few quirks about Advanced Segments: (i) the are the only GA customization i am aware of that is user-account specific; in other words, everyone who wants to view the data using the AS you just created will have to create it manually. It won't appear in the Profile (as a Custom Filter would for instance); and (ii) AS are superior to Filters in at least one respect--they take effect immediately and creating them and settting/unsetting them no matter how many times, has no permanent effect on your data stored by Google.

A: If you do have a situation where you have multiple analytics IDs and you want to create reports that show the charts and graphs from the different sites or sub-sites on a single page, you can try Megalytic.  It's a custom reporting tool for Google Analytics.  Disclaimer:  I am a founder.


text:
Q: "Attempting to register an unknown factory" in model test I have these models in an ember-cli app:
var PuzzleRound = DS.Model.extend({
    year: DS.attr('number')
});

var Puzzle = DS.Model.extend({
    puzzleRounds: DS.hasMany('puzzleRound', {async: true})
});

And here's my test from tests/unit/models/puzzle-test.js:
import {
    moduleForModel,
    test
} from 'ember-qunit';
import PuzzleRound from 'weather-roulette/models/puzzle-round';

moduleForModel('puzzle', 'Puzzle', {
    // Specify the other units that are required for this test.
    needs: ['model:puzzleRound']
});

test('it exists', function() {
    var model = this.subject();
    // var store = this.store();
    ok(!!model);
});

I get this error when running ember test:
Attempting to register an unknown factory: `model:puzzleRound`

I'm using ember-cli 0.1.1, Ember.js 1.7.0, Ember Data 1.0.0-beta.11. Does anyone have anything I can try to fix this?

A: I just tried out this code with ember-cli 0.0.44 and I got the same error that you did.
I renamed both references to the puzzleRound model path to puzzle-round and then your test passed for me. So:
DS.Model.extend({
  puzzleRounds: DS.hasMany('puzzle-round', {async: true})
});

and
moduleForModel('puzzle', 'Puzzle', {
  needs: ['model:puzzle-round']
});

I knew that the hyphenated style was preferred over the camelCase style, but I'm not sure when this became mandatory. This requirement may be specific to ember-cli or ember-qunit.

A: I was looking for a solution similar to this one for awhile, and did not see any mention of my solution so I thought I would post here anyways. It's quite simple really: make sure that the controller you're referencing is actually there.
// my-ember-application/tests/unit/controllers/index/bar-test.js
moduleFor('controller:index/bar', 'My Bar Test', {
    beforeEach() { .. }
});

test('it exists', function (assert) {
    assert.ok(true);
});

This code would reference a controller at this location:
my-ember-application/app/controllers/index/bar.js


text:
Q: Automorphisms in unit disk Let $\mathbb{D}=\{|z|<1,\ z\in\mathbb{C}\}$. Are there any other automorphisms in $\mathbb{D}$ except the Blaschke factor $\displaystyle B_{a}(z)=\frac{z-a}{1-\overline{a}z},\ a\in\mathbb{D}$?
I denote with $\overline{a}$ the complex conjugate of $a$.
Thank you for your time,
Chris

A: $f(z) = ze^{i\theta}$ for $\theta \in \mathbb{R}$, the rotations are also conformal automorphism of $\mathbb{D}$.
In fact, if you denote $\Psi_a$ for $a \in \mathbb{D}$ as the Blaschke factor above, you can prove that all conformal automorphism are of the form $f(z) = \Psi_a(z)e^{i\theta}$.


text:
Q: Selenium (argument --headless) + (marionette = False) I'm trying to scrap pages with javascript using python. I'm a total beginner at this so I've read lots of tutorials. I've finally found that I needed selenium, beautiful_soup, and the firefox webdriver. So I've done a function (I'm adding the relevant modules too).
import bs4
import requests
from urllib.request import Request
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

def page_souping_js(url):
    options = Options()
    options.add_argument("--headless")
    driver = webdriver.Firefox(firefox_options=options)
    driver.get(url)
    complete_page = driver.page_source
    driver.close()
    page_soup = soup(complete_page,"html.parser")
    return page_soup

which seemed to work fine until I tried to make a .exe file with it (using pyinstaller) and run it on another computer (It works fine on my computer) where I've got this error:

selenium.common.exceptions.SessionNotCreatedException : Message: Unable to find a matching set of capabilities

So I've read once again on the subject and "fixed" my code :
def page_souping_js(url):
    cap = DesiredCapabilities().FIREFOX
    cap["marionette"] = False
    options = Options()
    options.add_argument("--headless")
    driver = webdriver.Firefox(capabilities=cap, firefox_options=options)
    driver.get(url)
    complete_page = driver.page_source
    driver.close()
    page_soup = soup(complete_page,"html.parser")
    return page_soup

since I've made that change, though, the browser opens, even if I've added the argument "--headless".
1. Are these two, capabilities and firefox_options, incompatible?
2. if I need set "marionette" to False is there a way to execute this function without the browser opening? Or is there another around this problem?
Hopefully someone'll have an answer to this.

A: Ok apparently this problem is caused by the fact that the user had a very outdated version of firefox on his machine. The capabilities do not have to be set to anything that isn't default, but the browser should be updated.

A: I can't speak about the compatibility of capabilites and firefox_options, but I've had some success with this:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from bs4 import BeautifulSoup

def page_souping_js(url):
    options = Options()
    options.set_headless(True)
    driver = webdriver.Firefox(firefox_options=options)
    driver.get(url)
    complete_page = driver.page_source
    driver.close()
    page_soup = BeautifulSoup(complete_page, "lxml")
    return page_soup

This should return the source html without opening the browser. Putting this through PyInstaller didn't seem to cause any issues either.
Side note, the official import statement for BeautifulSoup (according to the official documentation) is from bs4 import BeautifulSoup.

A: make sure you are using this path to firefox.exe file inside "App" folder. 'path\to\FirefoxPortable\App\Firefox\firefox.exe'
for 64-bit version use this path:
'path\to\FirefoxPortable\App\Firefox64\firefox.exe'


text:
Q: Prevent JsonTextReader from consuming the stream during deserialization I'm using Json.Net to consume some seekable streams.
// reset the input stream, in case it was previously read
inputStream.Position = 0;
using (var textReader = new StreamReader(inputStream))
{
    using (var reader = new JsonTextReader(textReader))
    {
        deserialized = serializer.Deserialize(reader, expectedType);
    }
}

However, this method 'consumes' the stream, meaning the first contained valid Json token is removed from the stream.
That it very annoying. And meaningless, stream Position is provided to emulate a consumption, and 'reading' generally implies 'not modifying'.
Of course, I can dump the stream into a MemoryStream to protect my precious source stream, but that's a huge overhead, especially when doing trial-and-error on a deserialization.
If there is a way to to just 'read' and not 'read-and-consume', thanks for your help, I could not find documentation about that (and I hope this post will help others to google the solution ^^).

A: JsonTextReader is a forward-only reader, meaning it cannot be set back to a position earlier in the JSON to re-read a portion of it, even if the underlying stream supports seeking.  However, the reader does not actually "consume" the stream, as you said.  If you set the CloseInput property on the reader to false to prevent it from closing the underlying reader and stream when it is disposed, you can position the stream back to the beginning and open a new reader on the same stream to re-read the JSON.  Here is a short program to demonstrate reading the same stream twice:
class Program
{
    static void Main(string[] args)
    {
        string json = @"{ ""name"": ""foo"", ""size"": ""10"" }";
        MemoryStream inputStream = new MemoryStream(Encoding.UTF8.GetBytes(json));

        JsonSerializer serializer = new JsonSerializer();

        using (var textReader = new StreamReader(inputStream))
        {
            for (int i = 0; i < 2; i++)
            {
                inputStream.Position = 0;

                using (var reader = new JsonTextReader(textReader))
                {
                    reader.CloseInput = false;

                    Widget w = serializer.Deserialize<Widget>(reader);

                    Console.WriteLine("Name: " + w.Name);
                    Console.WriteLine("Size: " + w.Size);
                    Console.WriteLine();
                }
            }
        }
    }
}

class Widget
{
    public string Name { get; set; }
    public int Size { get; set; }
}

Output:
Name: foo
Size: 10

Name: foo
Size: 10

Fiddle: https://dotnetfiddle.net/fftZV7

A: A stream may be consumed once read. The solution could be to copy it to a memory or file stream as below:
MemoryStream ms = new MemoryStream();
inputStream.CopyTo(ms);
ms.Position = 0;
using (var textReader = new StreamReader(ms))
(...)

Please let me know if it works.


text:
Q: Regex to match exactly one comma separeted strings Example:
src: anyword, anyword, anyword

I want to check if src contains only one comma separated strings like given in example
I wrote (.[^\s*]+,.*[^,\s*]+$) this but it's failing with some scenarios
For me, following scenarios are not valid
src: abc, ,1232
src: ,abc, dasf

demo: https://regex101.com/r/UyQ5KX/1

A: You may use
: *[^\s,]+(?:, *[^,\s]+)*$

Or, to allow more whitespaces than just space between words:
:[^\S\n\v\f\r\u2028\u2029]*[^\s,]+(?:,[^\S\n\v\f\r\u2028\u2029]*[^,\s]+)*$

See the regex demo
If there must be 1+ non-colon chars from the start of string till the colon, you may add ^[^:]+ before the patterns above.
Details

*

*^ - start of string

*[^:]+  - 1+ chars other than :

*: - a colon

*[^\S\n\v\f\r\u2028\u2029]* - 0 or more occurrences of only horizontal whitespaces

*[^\s,]+ - 1 or more occurrences of characters other than whitespace and comma

*(?:,[^\S\n\v\f\r\u2028\u2029]*[^,\s]+)* - 0 or more occurrences of

*

*, - a comma

*[^\S\n\v\f\r\u2028\u2029]* - 0 or more occurrences of only horizontal
whitespaces

*[^\s,]+ - 1 or more occurrences of characters other than whitespace and comma

*$ - end of string.


text:
Q: Analytics along with OLTP Database I have a primary use case where I want to have a transactional relational database for which I am using Postgres.
I also need to run frequent aggregate queries (count, sum, average) on the data. These statistics cannot be precomputed as there are multiple filters for search that we have to provide.
I was initially thinking of using Redshift as a secondary storage, which can serve these queries, but then I would also need to build a system to keep the data in sync between the two storages.
Is there a better way to achieve this?

A: Take a look at AWS DMS, you can set this up to keep a near real time replica of your Postgres data on Redshift.
It is reliable and requires minimal maintenance (e.g. if you add new columns to your source data).
Read both of these carefully, especially limitations and requirements.
https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.PostgreSQL.html
and
https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Redshift.html
Unless you need them, I recommend excluding text (and other large object) columns from the sync. this can be done easily by setting a flag, or can be tailored column by column.
The source Postgres database does not have to be held on AWS.


text:
Q: ASP.NET Core Web API with OData controller needs to use fluent API for composite key I have an existing API that now has tables in the database it uses which have to have a composite key.
I used fluent API to define the keys in the dbcontext.
protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
        //relationship modeling
        modelBuilder.Entity<Reports>().HasMany(r => r.Screenshots).WithOne().HasForeignKey(r => new { r.ReportId, r.itemTypeId });
        modelBuilder.Entity<Images>().HasOne(s => s.Reports).WithMany(s => s.Screenshots).HasForeignKey(s => new { s.ReportId, s.itemTypeId });
        modelBuilder.Entity<EpicReportsChildList>().HasOne(e => e.Reports).WithMany(e => e.EpicReports).HasForeignKey(e => new { e.TemplateId, e.parentTypeId });
        modelBuilder.Entity<Images>().HasOne(s => s.EpicReports).WithMany(s => s.Screenshots).HasForeignKey(s => new { s.ReportId, s.itemTypeId });

    }

I have the startup file with the following:
private IEdmModel GetEdmModel()
    {
        var oDatabuilder = new ODataConventionModelBuilder();
        oDatabuilder.EntitySet<Reports>("reports");

        return oDatabuilder.GetEdmModel();
    }

The API is returning the following error:
Entity type EpicReportsChildList has composite primary key defined with data annotations. To set composite primary key, use fluent API.

A:
Entity type EpicReportsChildList has composite primary key defined
with data annotations. To set composite primary key, use fluent API.

As the error message said, perhaps you are configuring the composite primary key both using the data annotations or the fluent API method.
From the EF Core Keys document, we can find that: Composite keys can only be configured using the Fluent API; conventions will never setup a composite key, and you can not use Data Annotations to configure one.
So, please check the related model and try to remove the data annotations: [Key] attribute or [ForeignKey] attibute.
More detail information about configure relationship with composite key, you could check the following articles (The many to many relationship joining table was configured to use  the composite primary key, you could refer to them):
EF one to many on part of composite primary key
Configure Many-to-Many Relationships in Entity Framework Core
Configuring Many To Many Relationships in Entity Framework Core


text:
Q: Theories requiring dual continuous and discrete constructs Over the years there have been questions of a similar ilk on MO (e.g., Q1, Q2, Q3) concerning theories in which either continuous constructs or discrete constructs preceded the development of the other or in which one but not both are present.
I've always been fascinated by quantum mechanics in which notions of the continuous and discrete are necessarily complementary in understanding the math and physics. For example, to characterize the motion of a particle trapped between two walls with a set of discrete, possible energy or momentum states, one has to introduce a continuous probabilty amplitude with the distance between the walls being an integral multiple of the period (or half-period) of the probability wave. The presence of both the discrete and continuous are a necessity to developing a mathematical understanding. The same applies to understanding electrons and the periodic table and the diffraction patterns in the double-slit Young experiments.
A related example is Fourier transform theory in which the discrete Dirac delta and mono-frequency, continuous waves of infinite extent are a necessary duality, not an expediency.
Question:
In what other theories are dual discrete and continuous constructs a necessity?
In response to some comments:
Read Wiki, or better, Feynman's QED for the layman, for a clear explanation of how the iconic double-slit experiment displays the central mystery of QM--the dual wave and particle nature of quantum mechanical objects (wavicles). In a nutshell, a wave-like interference/ diffraction scattering pattern develops for an ensemble of electrons that separately pass through the double-slit over time, each one leaving an isolated  discrete mark on the recording material.
Electrons are fermions whose continuous probability wave amplitudes negate each other (Pauli exclusion principle) when possessing the same state values (unlike bosons. such as photons, who tend to coalesce allowing for the existence of lasers) so that only two electrons with opposite spin can occupy a given orbital of an atom. This accounts for the lack of a classical collapse of the system and the existence of the periodic table.

A: The Pontryagin dual of the unit circle are the integers.
This implies that the (square integrable) functions on the unit circle are described by a countable sequence of numbers (actually their Fourier coefficients). This is useful e.g. in Harmonic analysis or very practical areas like signal/communication theory. Is it really necessary? I don't know, but understanding how linear filtering of signals work without Fourier series seems quite impossible to me.

A: Decimal (or binary, etc.) representations of lengths along the real line. We intuitively understand the real line as a continuous construct drawn by hand yet to understand the embedded lengths and their relationships, we introduce decimal reps, a series of discrete numbers from zero to nine that represent a resolution of the length into the discrete components $10^{n}$ for the integers $n$, positive and negative--for rational numbers, a finite series or a periodic infinite series, depending on the basis; or for irrational numbers, a non-periodic infinite series. To understand these resolutions, we fall back to the continuous real line.