Complete encapsulation without malloc

Question: I was experimenting with C11 and VLAs, trying to declare a struct variable on the stack with only an incomplete declaration. The objective is to provide a mechanism to create a variable of some struct type without showing the internals (like the PIMPL idiom) but without the need to create the variable on the heap and return a pointer to it. Also, if the struct layout changes, I don't want to recompile every file that uses the struct.
I have managed to program the following:
private.h:
#ifndef PRIVATE_H_
#define PRIVATE_H_

typedef struct A{
    int value;
}A;

#endif /* PRIVATE_H_ */

public.h:
#ifndef PUBLIC_H_
#define PUBLIC_H_

typedef struct A A;

size_t A_getSizeOf(void);

void A_setValue(A * a, int value);

void A_printValue(A * a);

#endif /* PUBLIC_H_ */

implementation.c:
#include "private.h"
#include "stdio.h"

size_t A_getSizeOf(void)
{
    return sizeof(A);
}

void A_setValue(A * a, int value)
{
    a->value = value;
}

void A_printValue(A * a)
{
    printf("%d\n", a->value);
}

main.c:
#include <stdalign.h>
#include <stddef.h>

#include "public.h"

#define createOnStack(type, variable) \
    alignas(max_align_t) char variable ## _stack[type ## _getSizeOf()]; \
    type * variable = (type *)&variable ## _stack

int main(int argc, char *argv[]) {
    createOnStack(A, var);

    A_setValue(var, 5335);
    A_printValue(var);
}

I have tested this code and it seems to work. However I'm not sure if I'm overlooking something (like aliasing, alignment or something like that) that could be dangerous or unportable, or could hurt performance. Also I want to know if there are better (portable) solutions to this problem in C.
Comment: @Vality: look again at the code - that would be a link-time optimization; Mabus' reasoning should be sound
Comment: You cannot sensibly do this without recompiling when the struct layout changes as sizeof will be optimized to a compile time constant if you use a VLA or alloca
Comment: @Mabus thanks for posting this. I hadn't thought of using a VLA of chars to provide storage for other types.
Answer: This of course violates the effective typing rules (aka strict aliasing) because the C language does not allow an object of tye char [] to be accessed through a pointer that does not have that type (or a compatible one).
You could disable strict aliasing analysis via compiler flags like -fno-strict-aliasing or attributes like
#ifdef __GNUC__
#define MAY_ALIAS __attribute__((__may_alias__))
#else
#define MAY_ALIAS
#endif

(thanks go to R.. for pointing out the latter), but even if you do not do so, in practice everything should work just fine as long as you only ever use the variable's proper name to initialize the typed pointer.
Personally, I'd simplify your declarations to something along the lines of
#define stackbuffer(NAME, SIZE) \
    _Alignas (max_align_t) char NAME[SIZE]

typedef struct Foo Foo;
extern const size_t SIZEOF_FOO;

stackbuffer(buffer, SIZEOF_FOO);
Foo *foo = (void *)buffer;

The alternative would be using the non-standard alloca(), but that 'function' comes with its own set of issues.
Comment: If you're willing to assume a GNU-C-compatible compiler with `-fno-strict-aliasing`, then rather than ruin optimization of the whole program with that flag, you should put `__attribute__((__may_alias__))` on the type `Foo`. This should achieve the results just for the one type.
Comment: @Mabus: aliasing is symmetric, effective typing is not - the rules are that all objects (think memory locations) have a real type, and accessing them through an expression with incompatible type is UB; anyway, if you only use `buffer` to initialize the `Foo*` and not to read or modify the data, you should be fine
Comment: "a given version only ever comes with a single definition of struct Foo" is true, but it is an incomplete definition of `struct Foo` that does not change with new releases.  `typedef struct A A;` is the global part and only _pointers_ to type `A` are used globally.  The not-"implementation.c" code never sees the inner workings of `A` nor `sizeof(A)`.  The size of `A` is hidden and _could_ be dynamic, hence the global function `A_getSizeOf()`.  OP's scheme looks intriguing as it appears OP can get away with it.
Comment: Why it violates strict aliasing? I thought that a pointer to char can alias with any other pointer without problems.
Comment: @Mabus: a pointer to char may alias anything, but this is the opposite case - a pointer to `Foo` aliasing a character array; it's better to think in terms of effective types: the memory block `buffer` has effective type `char[]`, but you're accessing it as `Foo`
Comment: @Christoph I thought that alias was conmutative. But even if it's not the case, as I'm only going to access the memory trough the pointer, can I ignore aliasing?
Comment: It appears OP wants to extend this to use VLA such that `A_getSizeOf(void)` would not always return the same value in a given executable.  This extension appears to not work with the alternative idea of a global `extern const size_t SIZEOF_FOO;`.  BTW: nice Q & A.
Comment: @chux: as I understood it, he only wants compatibility at link-time when releasing a new version of his code; a given version only ever comes with a single definition of `struct Foo` and thus a constant return value of `A_getSizeOf(void)`
Comment: A_getSizeOf(void) must return the same value in the same executable if implementation.c is statically linked (but in that case I expect that I can change the implementation, recompile only the implementation and relink). However, if implementation.c is part of a shared library, I think that changing the implementation won't break the ABI (I haven't tested that yet). AFAIK the same would happen if A_getSizeOf() is a external variable defined in implementation.c, but I'm not 100% sure.
Comment: In fact, as @chux says, using a function is more flexible, and allows the size to change, but that wasn't planned and I can't imagine a possible use of that (maybe a daemon that can be updated on the fly, with some locking for changing libraries? I don't know if that's possible XD).
Comment: @Mabus  I now see your "VLA" discussion was only with `variable ## _stack[type ## _getSizeOf()]`.  I was thinking you were prepping for  a VLA also in `typedef struct A{ int value; char varray[0] }A;`.
Comment: That's a "flexible array member", not a true VLA.
Answer: I am considering adopting a strategy similar to the following to solve essentially the same problem. Perhaps it will be of interest despite being a year late.
I wish to prevent clients of a struct from accessing the fields directly, in order to make it easier to reason about their state and easier to write reliable design contracts. I'd also prefer to avoid allocating small structures on the heap. But I can't afford a C11 public interface - much of the joy of C is that almost any code knows how to talk to C89.
To that end, consider the adequate application code:
#include "opaque.h"
int main(void)
{
  opaque on_the_stack = create_opaque(42,3.14); // constructor
  print_opaque(&on_the_stack);
  delete_opaque(&on_the_stack); // destructor
  return 0;
}

The opaque header is fairly nasty, but not completely absurd. Providing both create and delete functions is mostly for the sake of consistency with structs where calling the destructor actually matters.
/* opaque.h */
#ifndef OPAQUE_H
#define OPAQUE_H

/* max_align_t is not reliably available in stddef, esp. in c89 */
typedef union
{
  int foo;
  long long _longlong;
  unsigned long long _ulonglong;
  double _double;
  void * _voidptr;
  void (*_voidfuncptr)(void);
  /* I believe the above types are sufficient */
} alignment_hack;

#define sizeof_opaque 16 /* Tedious to keep up to date */
typedef struct
{
  union
  {
    char state [sizeof_opaque];
    alignment_hack hack;
  } private;
} opaque;
#undef sizeof_opaque /* minimise the scope of the macro */

void print_opaque(opaque * o);
opaque create_opaque(int foo, double bar);
void delete_opaque(opaque *);
#endif

Finally an implementation, which is welcome to use C11 as it's not the interface. _Static_assert(alignof...) is particularly reassuring. Several layers of static functions are used to indicate the obvious refinement of generating the wrap/unwrap layers. Pretty much the entire mess is amenable to code gen.
#include "opaque.h"

#include <stdalign.h>
#include <stdio.h>

typedef struct
{
  int foo;
  double bar;
} opaque_impl;

/* Zero tolerance approach to letting the sizes drift */
_Static_assert(sizeof (opaque) == sizeof (opaque_impl), "Opaque size incorrect");
_Static_assert(alignof (opaque) == alignof (opaque_impl), "Opaque alignment incorrect");

static void print_opaque_impl(opaque_impl *o)
{
  printf("Foo = %d and Bar = %g\n",o->foo,o->bar);
}

static void create_opaque_impl(opaque_impl * o, int foo, double bar)
{
  o->foo = foo;
  o->bar = bar;
}

static void create_opaque_hack(opaque * o, int foo, double bar)
{
   opaque_impl * ptr = (opaque_impl*)o;
   create_opaque_impl(ptr,foo,bar);
}

static void delete_opaque_impl(opaque_impl *o)
{
  o->foo = 0;
  o->bar = 0;
}

static void delete_opaque_hack(opaque * o)
{
   opaque_impl * ptr = (opaque_impl*)o;
   delete_opaque_impl(ptr);
}

void print_opaque(opaque * o)
{
  return print_opaque_impl((opaque_impl*)o);
}

opaque create_opaque(int foo, double bar)
{
  opaque tmp;
  unsigned int i;
  /* Useful to zero out padding */
  for (i=0; i < sizeof (opaque_impl); i++)
    {
      tmp.private.state[i] = 0;
    }
  create_opaque_hack(&tmp,foo,bar);
  return tmp;
}

void delete_opaque(opaque *o)
{
  delete_opaque_hack(o);
}

The drawbacks I can see myself:

Changing the size define manually would be irritating
The casting should hinder optimisation (I haven't checked this yet)
This may violate strict pointer aliasing. Need to re-read the spec.

I am concerned about accidentally invoking undefined behaviour. I would also be interested in general feedback on the above, or whether it looks like a credible alternative to the inventive VLA technique in the question.
Comment: The most obvious problem that I see is that if you change sizeof_opaque you can't have binary compatibility. With the VLA implementation, you can change the size of the struct and the compiled programs still work (supposing that you are programming a shared library). Also note that GCC and other compilers have an attribute similar to alignas (aligned), if you prefer to write C99 code with extensions. Also, when you are creating a struct inside another outside your library, you will have to malloc it, in my case, because you don't know the size at compile time.
Comment: @Mabus That's true, changing the size would break binary compatibility. VLA or malloc are probably the only workarounds. On the bright side, composition of opaque structures works nicely when the size is fixed, without the heap. Always tradeoffs! Binary compatibility of libraries is something I need to give (much) more thought to.

Complete encapsulation without malloc


Firebase.auth error with 400 bad request

Question: I found a strange error while I developing system using Firebase with service url contains user data.
User data is below.
    {
      "uid": "kt9Hcp2FbYbBvvIeSHHa1RbvHcv2",
      "displayName": "Anonymous 901",
      "photoURL": null,
      "email": null,
      "emailVerified": false,
      "identifierNumber": null,
      "isAnonymous": true,
      "providerData": [

      ],
      "apiKey": "MyApiKeyString",
      "appName": "MyAppName",
      "authDomain": "my.auth.domain",
      "stsTokenManager": {
        "apiKey": "MyApiKeyString",
        "refreshToken": "refreshTokenString",
        "accessToken": "accessTokenString",
        "expirationTime": 1532451863076
      },
      "redirectEventId": null
    }

I encode the above anonymous user data and include it in the service url.
( http://myserviceurl?userdata=encodedUserData )
Inside the system receives that url, firebase creates a user object with that user data contained in the url.
The purpose of this url is to use specific user's information in any browser.
However, when I call that service url, sometimes system creates user object well, sometimes got error -
400 Bad request errors with
https://www.googleapis.com/identitytoolkit/v3/relyingparty/setAccountInfo?key=MyApiKeyString
And error data is below,
    {
      "error": {
        "code": 400,
        "message": "TOKEN_EXPIRED",
        "errors": [
          {
            "message": "TOKEN_EXPIRED",
            "domain": "global",
            "reason": "invalid"
          }
        ]
      }
    }

Few hours later it works well, I changed nothing though.
I could not find the exact error point, but I suspect error occurs while observing authentication state or before this step.
Here is code snipets
    @bind
    private makeUserLoadingPromise(): Promise<void> {
      let unSubscribe: () => void;
      return new Promise<void>((resolve, _reject) => {
        const onInitialized = this.makeOnInitializedAuthStateChanged(resolve);
        unSubscribe = this.auth.onAuthStateChanged(onInitialized);
      }).then(() => {
        unSubscribe();
        this.auth.onAuthStateChanged(this.onAuthStateChanged);
      });
    }

    @bind
    private makeOnInitializedAuthStateChanged(resolve: () => void) {
      return (user: firebase.User | null) => {
        this.user = user;
        resolve();
      };
    }

    @bind
    private onAuthStateChanged(user: firebase.User | null) {
      this.user = user;
    }

Or maybe it relates with expirationTime?
I couldn't find any hints about this situation.
Any advice would be appreciated.
Answer: It is not clear what you are doing, but it appears that you are using the API incorrectly and insecurely. The plain user object contains a refresh token that is indefinite. Passing it around via URL is a really bad idea.
First don't rely on internal implementations, it is subject to change.
To get the user's information on your backend, the right way to do it, is to get the user's ID token using officially supported API, eg user.getIdToken(), then pass it to your server.
On your server, you verify it via the Firebase Admin SDK: admin.auth().verifyIdToken(idToken). Then you know this is a real authenticated user. If you need the full user info, you can then look it up using the decoded user id in the token: admin.auth().getUser(decodedIdToken.sub).


Worklight 6.1 - error on sending notification to android device on real server

Question: I'm trying to send notification to android device.
On my Worklight Studio I have succeeded to make subscription + notification.
When I trying to do it on real worklight server(on liberty), I have succeeded to make subscription, but I can't send notification.
I'm trying to send notification on browser like that:
http://serverIp:9080/worklighttime/dev/invoke?adapter=PushAdapter&procedure=submitNotification&parameters=[%27user%27,%27text message%27]

At the adapter I added:
<procedure name="submitNotification" securityTest="wl_unprotected" />

And, still I get this error:
 Exception thrown by application class 'com.worklight.core.auth.impl.AuthenticationFilter.doFilter:235'
java.lang.RuntimeException: javax.servlet.ServletException: Can not access development servlets in production mode
at com.worklight.core.auth.impl.AuthenticationFilter.doFilter(AuthenticationFilter.java:235)
at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:194)
at [internal classes]
Caused by: javax.servlet.ServletException: Can not access development servlets in production mode
at com.worklight.core.auth.impl.AuthenticationFilter.doFilter(AuthenticationFilter.java:136)
... 2 more

Answer: Take a look at this part from the error message:

Caused by: javax.servlet.ServletException: Can not access development
  servlets in production mode at
  com.worklight.core.auth.impl.AuthenticationFilter.doFilter(AuthenticationFilter.java:136)

Now see the URL you are using:
http://serverIp:9080/worklighttime/dev/invoke?adapter=PushAdapter&procedure=submitNotification&parameters=[%27user%27,%27text
message%27]

The /dev/ denotes basically a "development servlet", which as the error says - cannot be used when in production. "In production" basically means "any server that is not inside Worklight Studio", Worklight Studio being the development environment.
Try to remove the /dev/ from the URL and see whether this helps, or maybe a different error will then be given.


How to run a forloop in django views.py?

Question: I want to iterate over a queryset and if there is a new user added, I want to add some points for a specific user. To be more clear with what i am building: => I am writing a referral system logic in django.
The referral system works fine now, but what i want to implement is this. When i refer a user which are "user 2" and "user 3", it is stored that I have referred two users, now I have also implemented a way to know if "user 2" or "user 3" which are referred by me: have gotten a new user referred by them ("user 2" or "user 3").
Now what i want to achieve is this, when there is a new user from "user 2" or " user 3 " I want to add a some points to the "user 1" which referred the two user ("user 2" and "user 3") that referred the new users.
I am thinking of using a forloop to iterate over the second_level_recommended, then add the point to the profile but it doesn't seem to work or maybe the code that I wrote was wrong. This is the code that I wrote for the for-loop:
# for i in second_level_recommended:
    profile = Profile.objects.filter(recommended_by=request.user)
    profile.indirect_sign_up = profile.indirect_sign_up =+ 200

This is the code to check for the new users that "user 2" and "user 3" have referred belonging to "user 1"
views.py
my_recommended = Profile.objects.filter(recommended_by=request.user).values_list('user__id', flat=True)
second_level_recommended=Profile.objects.filter(recommended_by__in=my_recommended)

Then there is a forloop in the templates to display the second_level_recommended
NOTE: There is a Profile model which have these fields in it
class Profile(models.Model):
    user = models.OneToOneField(User, ...)
    ...
    code = models.CharField(max_length=100, ...)
    recommended_by = models.ForeignKey(User, ...)

Comment: maybe show us your actual code with the for loop
Comment: @Anentropic Does that forloop that he wrote looks good? it kind off doesn't to me. please look at the forloop!
Comment: @DestinyFranks that is because get doesn't return a QuerySet but a single item as Anentropic said earlier
Comment: @Anentropic do you mean the forloop in the template, or the one i tried writing in the views.py?
Comment: `profile = Profile.objects.filter(recommended_by=request.user)` the filter method returns a queryset not a single item, so `profile.indirect_sign_up` is not going to do anything useful. Try `get` instead of `filter` if you expect only a single item to be returned, that will give you a `Profile` instance instead of a queryset
Comment: `profile.indirect_sign_up = profile.indirect_sign_up =+ 200` if you want to set this to its current value plus 200 just do `profile.indirect_sign_up += 200` and note that it is `+=` and not `=+`
Comment: i tried get but it shows `get returned more than 1 item` and that is because one user can refer multiple users theres a `ForeignKey` on the recommended_by
Comment: yeah `second_level_recommended` is a queryset so the loop should probably be `for profile in second_level_recommended:` and then you don't need the next line (where we discussed `get` vs `filter` - just get rid of it)
Comment: In my opinion I think you need a tree structure to support this. Check django-mptt: https://django-mptt.readthedocs.io/en/latest/index.html
Answer: It's hard to tell if this is exactly what you want without seeing more context of your code, but I will take a stab at answering...
Instead of a for loop, we are going to use this technique: https://docs.djangoproject.com/en/4.0/ref/models/expressions/#f-expressions
(see also https://docs.djangoproject.com/en/4.0/ref/models/instances/#updating-attributes-based-on-existing-fields)
from django.db.models import F

my_recomended = Profile.objects.filter(recommended_by=request.user).values_list('user__id', flat=True)
second_level_recommended=Profile.objects.filter(recommended_by__in=my_recomended)

second_level_recommended.update(indirect_sign_up=F('indirect_sign_up') + 200)

This means we can update all the matched users in second_level_recommended queryset in a single db operation.
Otherwise if you use a for loop it is probably slower, but more importantly you run the risk of a "race condition".
The race condition would be where you fetch the db row into memory, as a Django model instance, update value on the model instance based on the value just fetched, then save it back to the db.  So you can get a problem where someone requests the same view for same or related user at the same time - both requests get the same old value and add 200 to it, but the end result of two requests is just +200 instead of +400.
Using an update query avoids that because the operation is "atomic" in the db - we tell the database to add 200 to each row instead of doing it ourselves one by one in Python code. If two requests come in almost simultaneously the db will ensure they execute serially, so first one +200 and then a second +200.
Comment: @ okay thanks for the answer, let me try it out now


Domain and range of n-ary relations.

Question: For any binary relation $\rho$ between sets A and B, $$\rho=\{ (a,b)\,|\, a\in A\; \wedge\; b\in B \}$$ we define A as the domain and B as the codomain of the relation.
But in case of a finitary n-ary relation (for any arbitrary n) between n sets $A_1,A_2, \ldots ,A_n$, $$\psi =\{ (a_1,a_2,\ldots ,a_n)\,|\,a_1\in A_1 \wedge a_2\in A_2 \wedge \ldots  \wedge a_n\in A_n\}\quad \& \quad \psi\subseteq A_1\times A_2\times\ldots\times A_n$$ How to define domain and codomain?
Answer: The formula you gave for an arbitary relation, namely A×B, is incorrect.
The domain of a relation R is
{ x : exists y with xRy }.
The range of R is
{ y : exists x with xRy }.
A codomain can be any set that includes the range.
As for an n-ary relation, if you must insist to unadvisely think in terms of functions, then view it like a function of n - 1 variables.
A fruitful concept is the k-th component or projection, { x$_k$ : x in R }

Domain and range of n-ary relations.


mysql.user table on mySQL

Question: I use mySQL on Mac OS.
I login mySQL by the command

mysql - u root

then run the command below

select User from mysql.user;

It show the table below
<code>+---------+
| User    |
+---------+
| root    |
| root    |
|         |
| root    |
|         |
| gerrit2 |
| root    |
+---------+
7 rows in set (0.08 sec)
</code>
I don't understand that there're 4 rows has root and 2 rows has no name.
Please explain me.
Thank you!
Comment: You'll get a clearer picture of what's in there if you do `SELECT user, host, password FROM mysql.user`
Answer: The row-defining part in mysql.users is the (host,user) tuple - this means:

You can have permissions without a username, depending on which host you connect from
You can have different permissions with the same username, again depending on the host
Answer: You can have multiple records for the same user in the mysql.user table, since you can have different passwords and/or permissions depending on the host the user connects from. If you run select * you will see the differences.

mysql.user table on mySQL


Examples of PM rings

Question: Def. A ring R is called a pm ring if each prime ideal is contained
in exactly one maximal ideal.
I asked AI to give some examples of pm rings. The answer is:
Examples of PM rings in algebra include:
The ring of integers, ℤ.
The ring of polynomials with coefficients in a field, F[x]....
But in either case $0$ is a prime  ideal that is contained
in infinitely many maximal ideals. Am I missing something?
Comment: Probably your definition should say that a pm ring is one in which every _non-zero_ prime ideal is contained in exactly one maximal...
Comment: Thank you. so Z is not mp ring with the above definition. am i right?
Comment: Well, with the definition you gave, requiring that $\{0\}$ (which is prime in a ring with no zero-divisors) to be contained in just one maximal ideal, $\mathbb Z$ would not be "pm". But with "non-zero prime...", $\mathbb Z$ would be "pm".
Answer: In this article, PM-rings are defined as each prime ideal is contained in a unique maximal ideal,(1) and examples are given. Notably $\mathbb Z$ is not there, and you can it would be there if valid, so I'm fairly certain this is just AI blabber.  The other example it gave is also wrong.
On the other hand, I have seen the condition every nonzero prime is contained in a unique maximal ideal (2) for example in the definition of h-local domains.. Of course, they match when the ring isn't a domain...
Why on earth would you ask AI math questions? It is highly unreliable beyond asking for common definitions.  I once asked it for an example of a division ring not isomorphic to its opposite ring and it said "the quaternions, because the opposite ring of the quaternions is a commutative ring..."
Actual examples would include local rings and zero dimensional rings, and also quotients of $h$-local domains by an ideal other than zero.
Comment: True, the real problem is asking (the current state of) AI entities "delicate" math questions. They've been mostly trained to be in harmony with the (mostly vague!) threads of human pop culture, nothing tooooo delicate. :)
Comment: It just occurred to me that asking an AI about some very delicate/precise mathematical or other things (where tiny details make a huge difference) might be akin to asking a clever, well-educated-in-the-classics, well-spoken person about math... :)  The difference might be (for now) that a really smart generally-educated person would decline to offer an opinion about technical stuff... I hope! :)
Comment: @paulgarrett It's not like asking a person at all. It's an oracle of BS. It _looks_ like cleverness to us because of the (relative) quality and confident delivery. But it's harder to detect because as humans we're used to BS being malicious. This sort of non-malicious mathematically generated BS is a new thing in the human experience.  It's like a better ouiji board
Comment: Hahahaha! :) :)  Very true. In human terms, the track record of BS-ers is that most of them have some malicious component. The "random BS" thing is a bit trans-human. :)
Comment: Maybe "coffee-shop"? :)
Comment: Thank you @rschwieb . Hereafter I ask you that are HI
(human intelligence).:)
Comment: @1400 I guess I was as bit harsh. There's no harm in asking AI... as long as you are fiercely skeptical and thoroughly vet its suggestions yourself.  That (clearly) happened to me once personally too. :)

Examples of PM rings


Usando uma função math no vue 2 framework

Question: Estou desenvolvendo uma api no vue.js que tem um botão para calcular a potencia de um determinado numero. Porém quando clico no botão fica estático, nada muda. Tem que fazer alguma mudança no método ou alguma configuração no vue?

{{ numero }}

    <button @click="potencia">Potência 2*</button>

Comment: Sua função retorna o resultado de `Math.pow`. Para onde vai esse valor? O que você gostaria de fazer com o resultado?
Comment: O botao deveria atualizar o valor de {{numero }} dentro da tag .
Ex: se {{numero}} é 3, aperta o botao e {{numero}} fica 9. Entendeu?
Answer: A sua função está retornando o resultado. O JavaScript tratará isso internamente e não saberá que o que deseja é atualizar o valor de this.numero. Para tal, você precisa especificar que deseja alterar o valor fazendo a atribuição:

new Vue({
  el: '#app',
  data: {
    numero: 3
  },
  methods: {
    potencia() {
      this.numero = Math.pow(this.numero, 2)
    }
  }
})

{{ numero }}

  <button @click="potencia">Potência 2*</button>

Comment: Nossa que deslize meu. Muito obrigado!!


Automatic Table creation - Hibernate

Question: I am trying to recreate my Oracle database in SQLite using Hibernate. I have used the hbm2ddl tag value as "create". Still my SQLite DB is not getting created. Could someone please help me with this ? I have posted below my cfg.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class"> org.sqlite.JDBC  </property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.username"></property>
<property name="hibernate.dialect"> org.hibernate.dialect.SQLiteDialect </property>
<property name="connection.url">jdbc:sqlite:resources/newdb.db</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.order_updates">true</property>
<property name="hibernate.order_inserts">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>

Answer: Try to replace this:
  <property name="connection.url">jdbc:sqlite:resources/newdb.db</property>

with:
   <property name="hibernate.connection.url">jdbc:sqlite:resources/newdb.db</property>

You're missing to write hibernate in the property.
And add this line:
  <property name="current_session_context_class">thread</property>

In case you have entity write them like this:
  <mapping class="path.to.your.Entity"/>

Comment: @BB8 are you  created your entity why you interessting to create
Comment: I want to create a embedded database(SQLite) similar to my production database schema every time I run my tool. To get the updated POJO classes I recreate them everytime from production.  My issue is with creating the embedded database from the newly generated POJO classes
Comment: Hi, thanks for your reply. But it still doesn't solve my problem. And as far as my entities are concerned, I generate them automatically after connecting with the Oracle database. So, I don't add them in the cfg.xml file. Instead I add the auto-generated .hbm.xml file as a resource to the configuration object after creating it during runtime.
Answer: I think this is what you need,
First the persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence-unit name="foo-persist" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>com.this.is.entity.foo</class>
    <class>com.this.is.entity.foo</class>
    <class>com.this.is.entity.foo</class>
    <jta-data-source>foo-persist</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
    </properties>
</persistence-unit>

Second is the following class which contains the properties needed by the persistence-unit:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class CommonService {
EntityManager em;
public static final String PERSISTENT_UNIT = "foo-persist";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(Config.PERSISTENT_UNIT);
Map properties = new HashMap();

public Map getProperties() {
    return properties;
}

public EntityManager getEntityManager()  {

    properties.put("javax.persistence.jdbc.url", "");
    properties.put("javax.persistence.jdbc.user", "");
    properties.put("javax.persistence.jdbc.password", "");
    properties.put("javax.persistence.jdbc.driver", "org.sqlite.JDBC");
    properties.put("eclipselink.logging.level", "OFF");
    properties.put("javax.persistence.schema-generation.database.action", "create");
    properties.put("javax.persistence.schema-generation.create-script-source", "META-INF/script.sql");
    properties.put("javax.persistence.sql-load-script-source", "META-INF/script.sql");
    emf = Persistence.createEntityManagerFactory(Config.PERSISTENT_UNIT, properties);
    return em = (EntityManager) emf.createEntityManager();
}
 }

Automatic Table creation - Hibernate


Coxph reference level - dummy variable?

Question: In my experiment I had a treatment gradient with 3 levels. Where level 1 was assumed to be most toxic, level 2 less and level 3 even less. I used CoxPH in R and set level 3 as the reference treatment.
Here arises the problem for me, I also want to compare level 3 with the other two levels and not just set the HR to 1. Because I'm also interested in 'how toxic' level 3 is compared with the other two levels. I have counted number of dead animals per level and time of death.
My thoughts on how to solve this:
Can I set a 'dummy' variable/level with 0 deaths as reference level?
Thank you in advance for helping me with this.
Answer: If your observed values were numbers of dead animals rather than the times to death of individual animals, then a Cox model is not appropriate. A generalized linear model (e.g., binomial regression for dead/alive) is called for.
In any case, your main question still stands. A regression model with a multi-level categorical predictor contains the information needed for all comparisons among its levels. In outline, you use the covariance matrix of the coefficient estimates (provided by the model but often hidden from view; the vcov() function in R can display it) along with the formula for the variance of a sum of correlated variables and appropriate correction for multiple comparisons.
This process is simplified by software tools designed for post-modeling analysis. In R, the car package and the emmeans package are often used for that.
With a simple model as you seem to have, just changing the reference level of the categorical predictor (and adjusting for multiple comparisons) would accomplish the same thing. It's wise to become familiar with the more general tools, as models aren't always so simple.
Comment: To clarify, I also registered time of death. And I have also used the Tukeys Post hoc analysis from the 'emmeans' package. But I wanted to know if I also could use a dummy variable for the cox analyses and get hazard ratios for all 3 levels.
Comment: @asellus that doesn't work for a Cox model as it doesn't have an intercept. What you can get are hazard ratios _between conditions_.  If "level 3" is reference then the coefficients/HRs for "level 1" and "level 2" say directly "'how toxic' level 3 is compared with the other two levels." To get the ratio between "level 1" and "level 2" you could specify one of them as the reference instead. If you want some absolute measure of mortality, use `survfit` or `predict` functions to evaluate differences in things like median survival time or differences in survival at specified times.

Coxph reference level - dummy variable?


How to access list to fill listbox items and show specific items. From CSV

Question: Hello programmers I'm working on a program that takes information from a csv file in the format of
6-Jan-17/19963.80,19906.96,199999.63,19834.08.

I have written the csv information into a list with class properties of String Date, Decimal Closing, Decimal Opening, Decimal High, Decimal Low.
I used a while statement to read each line, separate them by commas and assign them to their correct class property. Then I added the information into the List.
I have added the date to the listbox on my GUI and want to make it so that when a user clicks a certain date. All the values for each of its properties will show up on in some textboxes on the GUI. I'm unsure of how to access the list in my listbox1_SelectedIndexChanged to add the correct values to their textboxes depending on which index is selected. I know I need to return the list somehow but I cant seem to figure out exactly how to do this.
Can someone please provide me with a step in the correct direction with this?
I want to be able to analyze each column of the row and show different results inside my listbox aswell.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace meade_13_5
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            List<DowData> list = new List<DowData>();
            //grab the DJIA csv file using StreamReader
            using (StreamReader sr = new StreamReader("DJIA.csv"))
            {
                string line;
                //Assigns cvs file lines into their role and adds to the List
                while ((line = sr.ReadLine()) != null)
                {
                    //Split the lines by comma
                    string[] columns = line.Split(',');
                    //Create new list for the data
                    DowData theData = new DowData();
                    //Change format of datetime to date
                    string dateString = DateTime.Parse(columns[0]).ToString("dd/mm/yyyy");
                    theData.Date = dateString;
                    theData.Closing = Decimal.Parse(columns[1]);
                    theData.Opening = Decimal.Parse(columns[2]);
                    theData.High = Decimal.Parse(columns[3]);
                    theData.Low = Decimal.Parse(columns[4]);
                    //Adds the values to the list
                    list.Add(theData);
                    //Adds date to the listbox to select
                    listBox1.Items.Add(string.Format("{0}", theData.Date));
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //listBox1.Items.Add(string.Format("{0} | {1} | {2} | {3} | {4}", theData.Date, theData.Closing, theData.Opening, theData.High, theData.Low));

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtClosing.Text = listBox1.SelectedIndex.ToString();
            txtOpening.Text = listBox1.SelectedIndex.ToString();
            txtHigh.Text = listBox1.SelectedIndex.ToString();
            txtLow.Text = listBox1.SelectedIndex.ToString();
        }
    }
}
class DowData
{
    public String Date
    {
        get;
        set;
    }
    public decimal Closing
    {
        get;
        set;
    }
    public decimal Opening
    {
        get;
        set;
    }
    public decimal High
    {
        get;
        set;
    }
    public decimal Low
    {
        get;
        set;
    }

}

Answer: You can set the DisplayMember property of listBox1 to Date, and instead of doing listBox1.Items.Add(string.Format("{0}", theData.Date), just do listBox1.Items.Add(theData).
In private void listBox1_SelectedIndexChanged(object sender, EventArgs e) you can then do (Requires C#9/.NET 5 or higher):
if(sender is ListBox { SelectedItem: DowData dataItem } )
{
    txtClosing.Text = dataItem.Closing.ToString();
    txtOpening.Text = dataItem.Opening.ToString();
    txtHigh.Text = dataItem.High.ToString();
    txtLow.Text = dataItem.Low.ToString();
}

A more compatible version of the above would be:
var lstSender = sender as ListBox;
if(lstSender != null)
{
    var dataItem = lstSender.SelectedItem as DowData;
    if(dataItem != null)
    {
        txtClosing.Text = dataItem.Closing.ToString();
        txtOpening.Text = dataItem.Opening.ToString();
        txtHigh.Text = dataItem.High.ToString();
        txtLow.Text = dataItem.Low.ToString();
    }
}


How to play these chords?

Question: I'm trying to play "Sweet Home Alabama". What confuses me is when I see things like 0h2p0 and 0h2(x4). What are those, and how do you play them?
Comment: [This](http://tabs.ultimate-guitar.com/l/lynyrd_skynyrd/sweet_home_alabama_tab.htm) tab seems to be a better fit for that song, but you'll still need the answer to this question.
Answer: It means that you have to hit the string in the 2nd fret wirh your finger and then raise it inmediately, I mean, h = hammer on (hit the string) p = pull off (raise the finger). Watch this video about hammer on and pull off http://www.youtube.com/watch?v=d5sXDHVl0R0
Edit:
This one is better http://www.youtube.com/watch?v=hN9zZd07Kio&feature=fvwrel
Comment: @Ruben you can edit your answers and add additional information to them if you need to. No need to answer a question twice.
Answer: Quick tip for the pull off technique.  Dont just let go or raise the finger you are pulling off with or the note will you pull off to will be quiet or may not sound.  You need to pull your finger down slightly when you pull off (away from the neck and slightly towards the floor) so the finger almost picks the string as it pulls off producing a clearer note.  If you watch the video closely you will see the tutor is doing this or if you like try this video http://www.justinguitar.com/en/IM-154-LegatoScales.php for a clearer explanation
Answer: These h and p indicade a legate passage, that means you play the notes without hitting the string with pick.
h stands for hammer on, and
p stands for pull of
for example you have - 0h2 - To play this you need to pick your string and then hammer on the second fret to let the second note ring. - 4p2 is the other way around, pick the string while hold the fourth fret and then pull off from the string (in a gentle downwards motion) to let the note of the second fret ring.
This might require some practice first, but you'll get used to it soon.
Have fun :D

How to play these chords?


Does Apple Developer account have a limit on how many accounts it can mange?

Question: We develop whitelabelled apps. To comply with apple guidelines, we make our customers create their own apple developer account and then they invite our account to manage theirs (bcs according to apple guidelines it is the content owner that needs to submit the app to the appstore, not the developer of whitelabelled solution).
So far I manage cca 60 accounts (all of them invited one account that I am the Account Holder for). Everything worked fine (other than it makes automation little bit more challenging), until I wasnt able to find one of the teams in the teams list on apple dev portal.
So on appstore connect I saw that I am member of this team with access to dev resources (apple dev portal). But in the apple dev portal this team was not in the list of teams to choose from.
I have left some other teams then, and this team suddenly appeared in the list of teams to choose from.
Conclusion I made is that there is a limit on how many accounts you can manage from one account. I have asked apple if that is true, but it has been several days and no answer (I posted a bug report through their bug reporter, and I also sent this question to them through web form on their site).
Has anyone encountered this limit? if so, do you have information on how big this limit is? And how did you solve this whole situation? Did you create a new apple id that your customers invite to manage their accounts now?
I am kinda lost now, and apple being silent about this (and the fact that I have not found this documented anywhere) isnt really helping.
Comment: Update April 2019: Just an observation: One Apple ID is now member of 80+ teams. Not sure if they changed anything or it depends on when the Apple ID was created.
Comment: And do you mean teams in appstore connect, or developer portal?

Bcs in my experience this limit was only on dev portal, on appstore connect this issue did not manifest for me
Comment: As both team are now linked (unification of the teams earlier this year), I have access to both for more than 60+ teams
Comment: @Max what is your experience now? Anyone reached 100+?
Answer: Yes, there is a team limit of 60 teams per Apple ID. You will need to create a new Apple ID and get your invites on that. (Have currently ~ 5 examples of that, so it's definitely not a bug) And yes, there is no official documentation of that.
Answer: We hit the limit the other day. We removed ourselves from some older accounts so I can't confirm the exact figure, but we have a user that is currently a member of 495 teams, so I expect the limit as of March 2022 is 500 teams.
Beware that App Store Connect is not efficient at all when it comes to this volume, so you'll be waiting more than ten seconds for some API calls to be made to the backend when you load a page (10s is the time-to-first-byte and the total size of the response is about 100KB, so it's a backend delay rather than the connection).
I would recommend sharing across multiple accounts long before you hit the limit.
Comment: is there any official document?
Comment: Not as far as I am aware, @BhargavB.Bajani


Regional Persistent Disks on GKE

Question: I have a scenario where I've got a containerized app with a single config file that I need to store outside of the container for relatively infrequent read/write access. A simple way to do this is to use a regional persistent disk which I'd then mount on my pod using a PersistentVolume and PersistentVolumeClaim.
However, persistent disks can only replicate data between two zones. Our GKE's run on at least three zones and have automated maintenance enabled so the nodes could float between zones. If the pod starts up on a node in one of the zones that doesn't match where the persistent disk is stored, it'll just hang.
How does GKE support this? Am I missing something obvious or is the only way to make failover between all zones and nodes in a region to use a managed storage service like FileStore or GCSFuse?
Thanks!
Answer: For your use case, I'd suggest using GCS Fuse (we will actually be including this with GKE soon so you won't need to install the CSI driver yourself).  Filestore is a good option as well, but the min size in 1TB.
To answer the question on regional PD, your pod/container would be limited to the two zones used by the regional PD.

Regional Persistent Disks on GKE


How do I implement structural Equals for an F# class?

Question: In C# I would implement Equals for a class with structural equality like this:
public override bool Equals(object obj)
{
    if (this == obj)
    {
        return true;
    }

    var other = obj as MyType;
    if (other != null)
    {
        return someField == other.someField &&
            someOtherField == other.someOtherField;
    }

    return false;
}

In F# we have records for this, but if we want to use inheritance a type must be implemented.
What is the equivalent Equals implementation in F#?
Comment: much the same as C#?
Comment: just override equals - can be done in F#?
Comment: F# records implicitly implement `IStructuralEquatable` and override `Object.Equals` unless overriden by the definition.
Comment: Yes, but what would the body of the override look like?
Comment: I would like to see an example implementation to help me learn the language. Also a direct translation may not be the best way to do it in F#. e.g. is `null` treated differently?
Answer: As mentioned in the comments, you just need to override Equals. The compiler will also tell you that it is a good idea to override GetHashCode.
One neat trick is that you can just take all the relevant fields of your class, create tuples with them and then compare the tuples (or take hash code of the tuple). This makes the implementation much easier than if you were doing this by hand:
type Person(name:string, age:int) =
  member x.Name = name
  member x.Age = age
  override x.GetHashCode() =
    hash (name, age)
  override x.Equals(b) =
    match b with
    | :? Person as p -> (name, age) = (p.Name, p.Age)
    | _ -> false

Person("Joe", 42) = Person("Joe", 42)

Comment: @sdgfsdh : That's presumptuous – C# has tuples too. ;-]
Comment: @sdgfsdh: For a local variable you shouldn't need any type annotation, just use `Tuple.Create`'s type inference. `return Tuple.Create(this.name, this.age) == Tuple.Create(other.Name, other.Age)`
Comment: Thanks @ThomasPetricek; that trick with tuples is exactly the kind of thing a C# developer doing a direct translation would not consider.
Comment: @TomasPetricek You are better off requiring strict types equality. Just checking `is a` relationship is not enough unless class is sealed.
Comment: @ildjarn But imagine the type annotations!
Comment: @sdgfsdh In C# you can use anonymous types: `new { field1, field2 }` In both F# and C# you need to pay attention to how these fields are compared then though...


Pull constant out of summation

Question: In the solution of my homework there's this step that I don't understand:
$$\begin{align}\mathsf {Var}[X] & = \sum_{k=1}^{n}\dfrac{n(k-1)}{(n-k+1)^2}\\ &= n \sum_{k=1}^{n}\dfrac{(n-k)}{k^2}\\&= n^2 \sum_{k=1}^{n}\dfrac{1}{k^2}-n \sum_{k=1}^{^n}\dfrac{1}{k}\end{align}$$
I would have thought, that when I pull $n$ out of the $\sum$ that I'd just get:
$n\sum_{k=1}^n\frac{(k-1)}{(n-k+1)^2}$.
Also I don't understand the second line. Could someone please tell me what steps are missing and how they solved this? Thanks!
Answer: They've just preformed the distribution and substitution at the same time rather than two steps.
$$\begin{align}\mathsf {Var}[X] & = \sum_{k=1}^{~~n}\dfrac{n(k-1)}{(n-k+1)^2} &&\text{as given}
\\ &= n\sum_{k=1}^n\dfrac{(k-1)}{(n-k+1)^2} &&\text{distribution}
\\ &= n \sum_{k=1}^{n}\dfrac{(n-k)}{k^2} && \text{substitution: } k\gets n-k+1 \\&= n \sum_{k=1}^{n}\dfrac{n}{k^2}-n \sum_{k=1}^{n}\dfrac{k}{k^2}&&\text{commutation and association}\\&= n^2 \sum_{k=1}^{n}\dfrac{1}{k^2}-n \sum_{k=1}^{n}\dfrac{1}{k}&&\text{distribution and rationalisation}\end{align}$$
Comment: @Cherry It is fine, because: $$\begin{split}\sum_{k=1}^n g(k)&=\sum_{n-k+1=n-1+1}^{n-n+1} g(k)\\&= \sum_{j=n}^1 g(n-j+1)\\&=\sum_{k=1}^n g(n-k+1)\end{split}$$
Comment: Thanks! Why can I just substitute n-k+1 as k? Deosn't it change the result if I do so?
Answer: Alternatively, note that the summation is reversed:
$$\begin{align}\color{red}{\mathsf {Var}[X]} & \color{red}{= \sum_{k=1}^{n}\dfrac{n(k-1)}{(n-k+1)^2}}\\
&=n\left(\frac{1-1}{n^2}+\frac{2-1}{(n-1)^2}+\frac{3-1}{(n-2)^2}+\cdots+\frac{n-2-1}{3^2}+\frac{n-1-1}{2^2}+\frac{n-1}{1^2}\right) \\
&=n\left(\frac{n-1}{1^2}+\frac{n-2}{2^2}+\frac{n-3}{3^2}+\cdots+\frac{2}{(n-2)^2}+\frac{1}{(n-1)^2}+\frac{0}{n^2}\right) \\
&\color{red}{=n \sum_{k=1}^{n}\dfrac{(n-k)}{k^2}}\\
&=n \sum_{k=1}^{n}\left(\dfrac{n}{k^2}-\frac{k}{k^2}\right)\\
&\color{red}{= n^2 \sum_{k=1}^{n}\dfrac{1}{k^2}-n \sum_{k=1}^{^n}\dfrac{1}{k}}.\end{align}$$

Pull constant out of summation


How do I solve the following equality-constrained quadratic program?

Question: I am trying to minimize:
$$(x_1-k_1)^2 + (x_2-k_2)^2 + (x_3-k_3)^2 +\ldots+ (x_n-k_n)^2$$
subject to following equality:
$$B = 1 + x_1 + x_2 + x_3 + x_4+\ldots+x_n.$$
Is there  a closed form solution for this?   I found the  case where $n=2$ using Lagrange multipliers and could do the same for case $n=3$, but does anyone see a simple solution?
Wikipedia gives this solution, but I'm not sure if the matrix has an inverse so I'm weary of going down that route.  Also inverting matrix takes some computer time and may not be feasible for solving different instances of the problem thousands of times.
Also, I put $B$ above as a constant, which it is, but I'm interested in the case where $B = (1+k_1)\times(1+k_2)\times\ldots\times(1+k_n)$, but I'm not sure if that makes the problem easier.  My intuition is that it does not and just complicates things.
Comment: The matrix has an inverse because it is $I_n$.
Comment: welcome to MSE, please use [Mathjax](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-qu%E2%80%8C%E2%80%8Bick-reference) to have a readable formate of your question.
Answer: We have a quadratic program
$$\begin{array}{ll} \text{minimize} & \|\mathrm{x} - \mathrm{k}\|_2^2\\ \text{subject to} & 1_n^T\mathrm{x} = c\end{array}$$
where $c = -1 + \displaystyle\prod_{i=1}^n (k_i+1)$. Using a Lagrange multiplier,
$$\mathcal{L} (x,\lambda) := \frac{1}{2}\|\mathrm{x} - \mathrm{k}\|_2^2 + \lambda (1_n^T \mathrm{x} - c)$$
Taking the partial derivatives and finding where they vanish,
$$\nabla_x \mathcal{L} = \mathrm{x} - \mathrm{k} + \lambda 1_n = 0_n \qquad \qquad 1_n^T \mathrm{x} = c$$
Hence,
$$1_n^T \mathrm{x} - 1_n^T \mathrm{k} + \lambda 1_n^T 1_n = 0_n$$
and
$$\lambda = \dfrac{1_n^T \mathrm{k} - c}{n}$$
Thus, the minimum is attained at
$$\mathrm{x} = \mathrm{k} + \left(\dfrac{c - 1_n^T \mathrm{k}}{n}\right) 1_n$$
and the minimum is
$$\|\mathrm{x} - \mathrm{k}\|_2^2 = \left\|\left(\frac{c - 1_n^T \mathrm{k}}{n}\right) 1_n \right\|_2^2 = \frac{\left(c - 1_n^T \mathrm{k}\right)^2}{n}$$
Comment: @mathreadler I have no idea what you're talking about. This is a QP with a linear equality constraint. Using a Lagrange multiplier is enough. It seems to me that you don't understand the difference between hard constraints and soft constraints.
Comment: I'm with @RodrigodeAzevedo on this one. This is, in fact, a rather trivial equality constrained least squares problem, well known to have a closed-form solution obtained via Lagrange multipliers.
Comment: Would the downvoter care to explain the reasoning for the downvote for this answer in particular? I can understand the downvote for the other one.
Comment: $\lambda(1_n^Tx-c)$ won't work for an equality constraint. You need something that is an increasing function of the modulus so you get a minimum at 0.
Comment: @mathreadler I don't think so.
Comment: The term has no minimum at all, it's a plane that can get arbitrarily much negative the lower the mean value of x is. It could maybe be useful if you had an inequality constraint, to encourage (increasingly large negative values in the allowed area), but for an equality it won't work.
Comment: Yes using a multiplier is enough, but that choice of function won't work unless the problem you are trying to solve has an **in**equality constraint. It's trivial really. Pretend you remove the function to minimize and accept any point on the equality constraint. Then minimizing $\lambda(1_n^Tx-c)$ is not gonna get you anywhere near the equality constraint, but it would if you had for example $\lambda\|1_n^Tx-c\|$ or $\lambda(1_n^Tx-c)^2$.
Comment: @mathreadler Won't work? The minimizer I found **does** satisfy the given equality constraint.
Answer: You can rewrite the constraint as:
$$0= 1-B +\sum_{i=1}^nx_i$$
and then turn it into a cost function:
$$\lambda\left\|1-B+\sum_{i=1}^{n}x_i\right\|_2$$
If we want to we can rewrite this with matrices, $\bf 1$ being the column vector full of ones:
$$\min_{\bf x} \left\{ \|{\bf x}-{\bf k}\|_2 + \lambda\|1-B+{\bf 1}^T{\bf x}\|_2\right\}$$
You will probably get better faithfulness to the constraint if you solve a sequence of linear problems using  for example iterated reweighting approach replacing the 2-norm with another norm for the constraint term:
$$\min_{\bf x} \left\{ \|{\bf x}-{\bf k}\|_2 + \lambda\|1-B+{\bf 1}^T{\bf x}\|_k\right\}$$
you could aim for different $k$, but I think $k=1$ would be a good choice.

EDIT I erroneously claimed that 1-norm term in this case would be the Lasso method, but as pointed out below in comments, in that case the 1-norm is of course applied on the $\bf x$ vector alone. Even as the constraint is in fact a scalar the $k$ norm is still relevant as the deviation for the constraint would be punished differently from the terms in the least-squares term.
Comment: There simply is no reason to do this. The problem has an analytic solution.
Comment: That's not a correct form of the lasso, besides. In a proper lasso, the $1$-norm is applied to the raw variables $x$, not a linear function thereof. Furthermore, because that quantity is a scalar, the specific norm $k$ is *irrelevant*; in every instance it reduces to an absolute value. The problems with this answer are myriad and I would strongly recommend removing it.
Comment: $k$ is still irrelevant. For *any* $k$, $\|1-B+1^Tx\|_k=|1-B+1^Tx|$. It doesn't matter at all what $k$ you choose.
Comment: Why are you taking the $2$-norm of a scalar?
Comment: Because I want to measure and regulate it's size. Isn't that usually why you take the norm?
Comment: Why not just take the square or the absolute value?
Comment: Because it fits better into the framework with matrices and vectors.
Comment: Yes, you are right on the lasso claim. It was actually wrong.


Why does the Google Analytics module restrict uid?

Question: When I try to insert the <code>[current-user:uid]</code> token for a custom dimension in the Google Analytics module, it gives me an error that this is a forbidden item.
However, reading through the GA Terms of Service, I can only find a vague statement saying only "non-personally identifiable information" is allowed.
The GA module is the only documentation I have found that explicitly states the uid is forbidden.
Wouldn't an id be allowed because Google has no way of retrieving the Drupal user's information?
Does anyone have a reference to where in the GA policy they disallow uid?
Answer: There is nothing specific in the GA documentation that forbids it. There is actually a section in the GA Help which explains how to use user ids: Benefits of using the User ID feature, so using user ids is not forbidden by GA at all.
Why it doesn't work in the GA Drupal module is because of this paragraph, as stated by one of its developers (found here):

If you upload any data that allows Google to personally identify an individual, your Google Analytics account can be terminated, and you may lose your Google Analytics data.
Comment: So it's a little bit of a gray area? It's disabled in the module because some countries may not allow it and there was a decision by the developers to err on the side of caution and disallow the id, even though it's technically allowed?
Comment: I can not speak for the developers, but in my eyes yes, they try to be on the save side. Not sure if there are countries where it is forbidden - it is possible. However, unless it is forbidden in your country (and you inform people you are using GA/cookies on your site) I am not sure how this could be a legal problem even if it is forbidden in the users country. A lot of sites obviously use GA's user id feature.
Comment: I found another link that seems to corroborate this: https://davidsimpson.me/2013/10/17/identifying-your-users-in-google-analytics-while-complying-with-section-7-of-the-terms-of-service/ If the id is sent to Google and has a public api that google can access it would be a violation, but if it's behind authorization it should be ok.


Complement of a nowhere dense set

Question:
Prove:
  If $A$ is nowhere dense subset of a topological space $X$, then $X \setminus A$ is
  dense in $X$

This question is already appeared  in this site but I'm mention again here is for check my proof.
Here's my try:
$A$ is nowhere dense means $\text{Int}(\overline{A})=\phi$
In order to prove $X \setminus A$ is dense, we prove every point of $X$ is either a point of $X \setminus A$ or  a limit point of $X \setminus A$.
Let $x \in X$ be arbitrary. If $x \in X \setminus A$, then we are done. So assume $x \notin X \setminus A$. That is $x \in A$. In this case we prove $x$ is a limit point of $X \setminus A$
Since $A \subset \overline{A}$ implies $x \in \overline{A}$ . Also we know $\text{Int}A \subset \text{Int}(\overline{A})(=\phi,\text{by hypothesis})$, so $\text{Int}A =\phi$
So we write, $$x \in \overline{A}=\overline{A} \setminus \phi =\overline{A} \setminus \text{Int}A=\partial(A)=\overline{A} \cap \overline{X\setminus A} $$
Hence $x \in \overline{X\setminus A}$ and so $x$ is a limit point of $X\setminus A$
Is this correct? Any suggestions must be appreciated!
Answer: Your proof is correct. In fact $X \setminus  A$ is dense in $X$ if and only if $\text{Int}(A) = \emptyset$ because $\overline{X \setminus  A} =  X \setminus \text{Int}(A)$.
Comment: Thanks!..........
Comment: Linking Related Question: https://math.stackexchange.com/questions/1630165/prove-that-if-a-set-is-nowhere-dense-iff-the-complement-of-the-closure-of-the-se

Complement of a nowhere dense set


MySQL servers for an attendance system

Question: I'm building an attendance system. There are about 20 places where people will check in and check out using a MIFARE 1K card. It will use MySQL as the database. The system will display something like "#ID IN: 800AM" the first time the user checks in and "#ID OUT: 400PM" when the user checks out. For this to work, all the databases need to be synchronized with each other all the times.
For an example, if user A went to location #1 to check in but by the time the user wants to return home, the server at location #1 went down, the user needs to go to location #2 or the nearest server to check out. The server at location #2 should display '#ID OUT: 400PM" and not "#ID IN: 400PM" since the user is already checked in.
So, what should I use to ensure this idea will work? My main concern is with the network (other department manages it) which is very unpredictable. It just love to go down anytime it wants to.
Update
LOL, I didn't realize my question was not clear. I just noticed it when it was pointed out, sorry about that.
My real question is, how can I configure my MySQL to be synchronized with each other (20 servers)? MySQL cluster? (I tried reading about it, but I'm not sure if it's the right thing to do.)
My current setup (first phase):

Local database for each server
OS: Slackware
A main server that keeps track of which staff is at which server
A web based front end for the user to see their history (which connects to the server based on their records)

Main Pros

No worries about network problems since it is a local database

Main Cons

A user can only check in and out at the same server. Databases and servers are not connected with each other.
Have to add the user to each server if the users want to check in at different locations. Which means, if the user wants to go to location A, the user must be checked out from location A first and then check in at location B. The server at location B didn't know that the user has checked in before at A.

By the way, I've already centralized my NTP to a local server. About the network, let's just say, I don't have the authority to make changes so that the network will be better. The network won't effect all 20 servers at once, usually, just a few of them for several times a week.
If there are anything else you would like me to answer, please just ask.
Answer: I think you are asking: how can I have multi-master databases with automatic failover. If this is not your question, then please clarify. If this is your question, then read on.
I have in fact written a web application for the very same thing, except it doesn't use Mifare 1K cards, it uses simple barcode cards (it's called LATRIX and is available from sourceforge, I hope this isn't too much plugging here).
The main issue here is that if your network connection to the actual computer running the frontend goes down, you are a bit stuffed. You could of course run a local database, and implement some sync mechanism back to a master database, but as long as the sync isn't working (due to absence of network), you have no chance of getting this right.
Therefore the very first thing to do is to make sure you have reliable network connectivity. Without that you are always going to struggle. The LATRIX does not use local databases or multi-master databases, it simply checks that the network connection to the database server is working. If not, the frontend terminal goes passive (i.e. users cannot check in our out), because I could not figure out a suitable solution for unavailable network connections.
Comment: LATRIX looks good, but due to my different work environment, a lot of things need to be customized, that's why I developed my own application.
Comment: I would have been very interested in helping with the customization, but of course I respect your decision. None of this does, however, distract from the basic problem you have: reliable networking.
Comment: Even after reading all your added information I still think there is no real solution for those cases where a network connection goes down and a user moves from one location to another. One thing you could try (but that would also require changes to the network) is setting up alternative routes, so that if one particular route between a location and the main server goes down, that location server will try and use another route.
Answer:
It just love to go down anytime it wants to

When some smart people designed the internet, it was to provide a robust comunications medium which would continue to operate even in the event of all-out nuclear war. While this may pose some issues for snipe-bidding on ebay, a lot of the historic application protocols are still very effective.
You've provided lots of information about what your system is intended to do, but you've not asked any specific questions. Assuming that you're asking how you keep the clocks in sync, then the best way to do this is using network time protocol (NTP). Note that almost every application reads the OS clock to get the time (but this is not necessarily the same thing as the HARDWARE clock). While we may live in different time zones time is passing at the same rate for all of use. The link above gives you an introduction to how it works. There are lists of free servers available on the internet - or you can run your own (most GPS devices provide very accurate clock data).
You've not mentioned what OS you are running this all on.
BTW if you're still using Microsoft based operating systems then you can set the time from another SMB machine using 'net time \server /set' - but this is not nearly as sophisticated / accurate as NTP.

MySQL servers for an attendance system


Train data selection for model comparison

Question: Let I have data to compare two models.

My first model wil be based on Arificial Neural Network(ANN)
My second model will based on linear regression(LR)

For the ANN, I have to divide data into 3 parts:

Train data
Validation data
Test data

For LR, I have to divide data into 2 parts(since I dont need Validation data):

Train data
Test data

And finaly I will compare performance two models using test data.
But, I am confused how should I select Train data for LR.
I mean for LR, should be same train data of ANN. Or should it consist of both Validation data of ANN and train data of ANN.
Thanks a lot.
Answer: An Apples to apples comparison will see two models trained on the same amount of data.  To select between your linear model and your neural network, you will use the validation set (which means whatever set you use as validation for your network, you have to use the same set for your linear model).
The model with the lowest loss on the validation set is likely the model you will choose.  From there, you use the selected model on the test set to get a final estimate of out of sample performance.  You touch the test set once and only once.
Comment: What would you validate with the linear model? Variable selection? Ridge/LASSO/elastic net hyperparemeters? It sounds like the OP would just fit the $\hat{\beta}_{ols} = (X^TX)^{-1}X^Ty$ and then predict out-of-sample.
Comment: @Dave The validation set is used for model selection.  Train the network and the linear model on the train set.  Which model is better?  Use the validation set to answer that.  This sort of data splitting is not preferable (see Harrell's RMS book for more) but unless OP wants to cross validate a neural network this would be the most straight forward way to compare the two.
Comment: I need Validation data set only for ANN for determining the optimum hyper parameters. But I dont need Validation data for LR. Models will be compared using test data. So I am confused. Test data is ok. They will be similar. But what about Train data. For ANN obvious. The determined Train data. But i am confused with the Train data for LR. Should that include the Validation data of ANN.
Comment: @oercim The models should not be compared using the test set.  The entire point of the test set is to provide an out of sample estimate of performance which is not influenced by any other information (like a different model's performance on the same data).  What your proposing is wrong -- benignly so, but ultimately wrong.
Comment: @Demetri Pananos I want to mean that, by validation stage I select the parameter tuned ANN. That is my first model. Then I model LR. This second model. Then by using same test data(out of sample) I compare their performance. Is this wrong. I am confused.


Javascript hotel price/availability calendar

Question: I'm trying to create a Javascript calendar which will show the price and availability of hotel rooms by date. Similar to this example (see Availability tab), however mine needs to show prices and availability for three different room types on each date.
So far I've tried out the Availability Calendars and Rooms modules, but both would require significant work to adapt to my needs.
I've also been looking into using a straight-forward calendar module. First I tried Calendar, however this reloads the page when moving to the next/previous month which won't do. Then I tried Fullcalendar, but I can't figure out how to make multi-day items appear as separate daily items (they appear as one item spanning many days), and there's also a problem rendering the calendar on a quicktab (it only shows the next/previous buttons and not the calendar until you actually click next or previous).
So I'm looking for some ideas on how to proceed...
PS I'm using Drupal 7.15
Answer: I figured it out using the standard Calendar plugin. You need to create the view as normal, then I created a custom block which embeds the view 6 times, calling it with a different month argument each time. Then I added some javascript magic to hide and show the calendars as required.
Create the block - PHP
/**
 * Implements hook_block_info().
  */
function viajes_block_info() {
  $blocks['viajes_room_prices'] = array(
    'info' => t('Viajes: Room prices and availability calendar'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $blocks;
}

/*
 * Implement hook_block_view()
 * Display the search form in a block
 */
function viajes_block_view($delta = '') {
   $block = array();

switch ($delta) {
    case 'viajes_room_prices':
        $block['subject'] = t('Disponibilidad de habitaciones');
                    $block['content'] = viajes_room_prices();
                    break;
    }

    return $block;
}

function viajes_room_prices() {
$MONTHS_TO_SHOW = 6;
$hotel_nid = arg(1);

//js is already added by the reservation form code, no need to add it again
//drupal_add_js(drupal_get_path('module', 'viajes') . '/js/hotels.js');
drupal_add_js(array('viajes_room_price' => array('max_months' => $MONTHS_TO_SHOW)), 'setting');

//previous/next controls
$ret =
'

' . t('Previous') . '

' . t('Next') . '

';

//calendars
for ($i=0; $i<=$MONTHS_TO_SHOW-1; $i++) {
    $date = strtotime(date('Y-m-d').' +'.$i.' month');

    $ret .=
    '

' .
            date('F',$date) . ' ' . date('Y',$date) .
        '

' .
            views_embed_view('room_prices', 'page_1', $hotel_nid, date('Y',$date).'-'.date('m',$date)) .
        '

';
}

return $ret;
}

The Javascript
(function($) {
Drupal.behaviors.viajes = {
    attach: function(context, settings) {
           /*
        * Room price/availability calendar
        */

        //next button click
        $('#viajes-rooms-next', context).click(function() {
            var curr = getCurrent();

            //re-enable previous button if we've just left the first month
            if (curr == 0) {
                $('#viajes-rooms-previous', context).removeClass('disabled');
            }

            //disable next button if we've just arrived at the last month
            if (curr == (getMaxMonths() - 2) ) {
                $(this).addClass('disabled');
            }

            //roll the calendar if we're not on the last month
            if (curr < (getMaxMonths() - 1) ) {
                $('#viajes-rooms-month-'+curr, context).addClass('hidden');
                $('#viajes-rooms-month-'+(curr+1), context).removeClass('hidden');
            }
        });

        //previous button click
        $('#viajes-rooms-previous', context).click(function() {
            var curr = getCurrent();

            //disable previous button if we've just arrived at the first month
            if (curr == 1) {
                $(this).addClass('disabled');
            }

            //re-enable next button if we've just left the last month
            if (curr == (getMaxMonths() - 1) ) {
                $('#viajes-rooms-next', context).removeClass('disabled');
            }

            //roll the calendar back if we're not on the first month
            if (curr > 0) {
                $('#viajes-rooms-month-'+curr, context).addClass('hidden');
                $('#viajes-rooms-month-'+(curr-1), context).removeClass('hidden');
            }
        });

        //get currently visible month
        function getCurrent() {
            for (i=0; i<=(getMaxMonths()-1); i++) {
                if (! $('#viajes-rooms-month-'+i, context).hasClass('hidden')) {
                    return i;
                }
            }
        }

        //wrapper for the max_months setting
        function getMaxMonths() {
            return Drupal.settings.viajes_room_price['max_months'];
        }

    }
}
})(jQuery);

Just make sure you have the following classes in your CSS:
.disabled a {
pointer-events: none;
    cursor: default;
color: #979797;
}

.hidden {
    display: none;
}


Blogger: Uncaught ReferenceError $ is not defined

Question: I am following the tutorial here: http://tympanus.net/codrops/2013/04/30/text-opening-sequence-with-css-animations/
I'm trying to add this to a Blogger XML template. The script doesn't work, I keep getting an error in my Chrome Console saying it's not defined, but as far as I can tell it is. Here is what I'm using:

Hello...

I'm Draven Xarcell Vestatt

I Provide

Organzied Creative Services

Through

Xarcell Studios

My jQuery call is at the end of the document:


Como selecionar linhas numa tabela?

Question: Estou trabalhando num sistema web e gostaria de criar uma tabela interativa numa página. Acima da tabela, tenho 4 botões e gostaria de dar funcionalidade a eles. Gostaria de poder selecionar uma linha da tabela para editar ou visualizar ou selecionar múltiplas linhas da tabela para excluir. Também gostaria que as alterações feitas visualmente na tabela se refletissem no banco de dados.
Estou utilizando HTML, CSS e JavaScript, além do framework Bootstrap. Pesquisei um pouco e descobri que a biblioteca jQuery e o plug-in DataTables poderiam me ajudar, mas não tenho ideia de como usá-los.
O código abaixo contém a tabela e os botões superiores.

    <button class="btn btn-default" type="button">
         Add
    </button>
    <button class="btn btn-default" type="button">
         Remove
    </button>
    <button class="btn btn-default" type="button">
         Edit
    </button>
    <button class="btn btn-default" type="button">
         View
    </button>

        ID
        Name
        Version
        Status
        Priority
        Date modified

        RF-1
        Sign in
        1.0
        Finished
        High
        2 May 2017

        RF-2
        Sign out
        1.0
        Finished
        High
        2 May 2017

Comment: Já viu esse plugin do Jquery? https://datatables.net/
Answer: veja se o código abaixo pode te dar uma noção de como fazer algumas coisas que você procura.
Para excluir, você clicaria em editar, então abriria a janela com os dados editados e você faz o que quiser (alterar/excluir/salvar)

    <button class="btn btn-default" type="button">
         Novo
    </button>
    <button class="btn btn-default" type="button">
         Excluir Selecionados
    </button>

        Selecionar
        ID
        Name
        Version
        Status
        Priority
        Date modified
        Ação

        <INPUT type="checkbox" id="RF-1" name="chk1"/>
        RF-1
        Sign in
        1.0
        Finished
        High
        2 May 2017
        Editar

        <INPUT type="checkbox" id="RF-2" name="chk2"/>
        RF-2
        Editar
        1.0
        Finished
        High
        2 May 2017
        Editar

Como selecionar linhas numa tabela?


Codificação mysql

Question: Eu tenho os dados no banco, no charset utf-8, e quero exportar a listagem em .csv, porém quando dou um select ele me retorna os dados assim por exemplo "Administração de Imóveis e Locação".
Como faço para ele retornar os dados no select acentuados corretamente?
PS. Estou usando HeidiSQL.
Comment: Tá usando PHP??
Answer: Tente fazer sua consulta assim:
SELECT convert(campo USING latin1) FROM tabela

Com mais de 2 campos
SELECT convert(campo USING latin1), convert(campo2 USING latin1) FROM tabela

campo - é a informação que queres listar.

Codificação mysql


What is the proper way to monitor and control a device with delayed feedback?

Question: I'm having trouble controlling the position of a real-world device using a UISlider. The device accepts directional commands (retract or extend) but not a command for an absolute position. It reports its current position when queried.
For example, if the device is at position 50 and I set the desired position with a UISlider to 25, the program commands the device to head in the direction towards 25. It may take several seconds so I repeatedly query it, and once it reaches 25 I command the device to stop. My current (untested) code looks like this:
<code>    func sliderMoved(_ label : UILabel, openCharacteristicNum : Int, closeCharacteristicNum : Int, sender: UISlider){
        let actuatorPosition = getActuatorPosition(label)

        // run this on a background thread
        DispatchQueue.global(qos: .background).async {
            if (actuatorPosition > sender.value) {
                // stop closing and start opening
                self.writeValue(closeCharacteristicNum, value: 1)
                self.writeValue(openCharacteristicNum, value: 0)
                while actuatorPosition > sender.value {
                    actuatorPosition = getActuatorPosition(label)
                }
                // stop opening
                self.writeValue(openCharacteristicNum, value: 1)
            }
            else if (actuatorPosition < sender.value) {
                // stop opening and start closing
                self.writeValue(openCharacteristicNum, value: 1)
                self.writeValue(closeCharacteristicNum, value: 0)
                while actuatorPosition < sender.value {
                    actuatorPosition = getActuatorPosition(label)
                }
                // stop closing
                self.writeValue(closeCharacteristicNum, value: 1)
            }
        }

    }
</code>
This feels like a very inefficient way to solve the problem (I'm not a fan of blocking threads with while loops) but I'm having trouble coming up with a better way.
Comment: The device is rather 'dumb'. It can accept a directional command but not a command to move to an absolute position, so it doesn't actually know when it has reached it's destination. I've edited the question for clarity.
Answer: I ended up using a timer to regularly monitor the position of the device, which was much better than using while-loops.


Can't transfer software RAID-5 volume from Windows Server 2008 R2 to Windows 7

Question: I have a very strange problem with MS SW RAID-5 volume.
On a workstation, I have Windows Server 2008 R2 with System volume (HW RAID 1) and Data volume (SW RAID 5, consisting of 4 disks).
I wanted to install Windows 7 Ultimate there, so I replaced both system disks and performed clean installation of Windows 7; then I went to Disk Management and imported those 4 foreign dynamic disks - everything was OK, but after the import, the RAID-5 volume was Failed, I didn't even see original volume's name - and what's even stranger, menu items "Repair volume" or "Reactivate volume" aren't there!
When I return original drives with Windows Server 2008 R2 and reimport back these disks, volume is OK; I checked this volume by chkdsk, no problems; I did full diagnostics of all drives - but I'm unable to enable this RAID-5 in Windows 7.
Thanks for any advice or pointer, I'm quite frustrated.
Answer: Windows 7 Professional does not support RAID5 volumes out of the box, only RAID 1.
Answer: What you're seeing is a limitation of the version of Windows. No version of Windows 7 supports software RAID-5. Microsoft finally added support for software RAID-1 in Windows 7 Professional, Enterprise, and Ultimate, but not RAID-5.


Functional Equations with Taylor Series

Question: I am stuck on the functional equation
$$f(f(x))+f(x)=e^x$$
Somebody has suggested to me in the past that I can use Taylor Series to solve some of the harder functional equations, but I'm not sure how to use that to solve this. Help?
If Taylor Series is not the way to go for this functional equation, can somebody tell me what method I should use?
In general, can anybody recommend a few different methods that would be good to keep in mind when dealing with functional equations like this in which functional iteration is present?
Thanks!
Answer: I don't know whether there is a simple solution for the function, but I can show how one would use a Taylor expression here.
First, let us suppose there is a value $q$ which is a fixed point of the function f(x)
$$
f(q)=q
$$
If we fill this in the relation we find:
$$
f(f(q)) + f(q) = f(q) + q = 2 q = e^q
$$
The numerical value would be $q\approx0.693147$.
Since we are interested in a smooth function $f(x)$ we know that we could in principle make a Taylor expansion at any point $x$. If we use the fixed point we would have something like:
$$
f(q+\delta) = q + \sum_{i=1}^\infty a_i \delta^i
$$
with some still unknown coefficients $a_i$. Having assumed a smooth function $f(x)$ there is at least a small range of values for $\delta$ where the series converges.
We can now insert this expansion into the relation we have and work all terms out up to some order ${\cal O}(\delta^n)$ and group terms with the same power of $\delta$. The first few terms would be :
$$
2 q + \left(a_1 + a_1^2\right) \delta + \left(a_2 + a_1 a_2 + a_1^2 a_2\right) \delta^2 + \dots = e^{q+\delta} = e^q + e^q \delta + e^q \frac{\delta^2}{2} + \dots
$$
and since for any small $\delta$ this should be the same on both sides we get a lot of equations in the unknown values $a_i$. The lowest order is
$$
2 q = e^q,
$$
which already assumed. The next one is
$$
a_1 + a_1^2 = e^q = 2q
$$
from which we find
$$
a_1 = \frac{1 \pm \sqrt{1 + 8 q}}{2}
$$
The sign is not too important and only determines whether we choose $x$ to go to the left or the right. The next equation we get is
$$
a_2 + a_1 a_2 + a_1^2 a_2 = \frac{1}{2} e^q = 2 q
$$
We can now insert the solution obtained for $a_1$ (or combine the equations) and determine that
$$
a_2 = \frac{q}{1 + 2 q}
$$
This procedure can be continued arbitrarily far and in this particular problem(!) the first equation you encounter for $a_k$ is always linear and easy to solve.
Unfortunately going from a "determined" function in terms of a local Taylor expansion to a closed expression, is in general not so easy.
A typical strategy to solve this type of problems would be to start looking for fixed points or symmetries that can be exploited.

Functional Equations with Taylor Series


Measures of dissimilarity (distance) between character vectors in R

Question: I have a seemingly easy question which however is troubling me a bit.
I have couples of vectors made up of nominal attributes. They can be of different length and sometimes some of the attributes in one might not be included in the other. See a and b as two potential examples.
               a
1  mathematician
2       engineer
3  mathematician
4  mathematician
5  mathematician
6       engineer
7  mathematician
8  mathematician
9  mathematician
10 mathematician
11 mathematician
12      engineer
13 mathematician
14 mathematician
15      engineer

               b
1      physicist
2        surgeon
3      physicist
4        surgeon
5      physicist
6      physicist
7        surgeon
8        surgeon
9      physicist
10     physicist
11 mathematician

Do you have in mind a measure (an index) that could summarize the dissimilarity between them? The type of measure I am looking for is something like the Euclidean distance, but for qualitative vectors.
One option I thought of is to actually compute the Euclidean distance among the categorical vectors earlier transformed into frequency vectors. In this way, they would become quantitative and would be of the same length. But my question is, do you find this a sound approach?
More generally, is there a R package that tackles these type of distances? Can you suggest other distances suitable to the case of nominal variables?
Many thanks!
Comment: is `tm::dissimilarity` helpful?
Comment: Maybe you could elaborate further: what are you going to do with the measure? What have you tried and why what you have tried is not satisfactory?
Comment: @carloscinelli Thank you for your answer. The reason why I am trying to do this is that I need to compare group composition taking into account (controlling for, if you want) the size of the group.
Comment: @TylerRinker very interesting package.
Answer: I've only come across the unalikeability coefficient.
http://www.amstat.org/publications/jse/v15n2/kader.html
Weird name, intuitive approach, and incredibly simple implementation. For example:
> table(a)
a
     engineer mathematician
            4            11

> unalike(table(a))
[1] 0.391

> table(b)
b
mathematician     physicist       surgeon
            1             6             4
> unalike(table(b))
[1] 0.562

It is clear just by eye-balling that b would be more dissimilar, and this coefficient gives a more quantitative measure.
There are some examples in the paper which I will calculate for you here:
> unalike(3,7)
[1] 0.42
> unalike(5,5)
[1] 0.5
> unalike(1,9)
[1] 0.18

The formula in this function is based on the paper I linked you to above:
unalike <- function(...) {

  props <- c(...)
  zzz <- 1 - sum(((props) / sum(props)) ** 2)
  zzz <- round(zzz, 3)

  return(zzz)
}

Let me know how your thing goes since this is a small side project for me as well.
Comment: In that case, what about a kappa statistic? The only adjustment you'd need to make is to account for the fact that one vector has three categories and the other only has two. For example, think of the vectors as ratings from 1-3 from two different raters. One rater used all three levels but the other only used two.
Comment: But this measures variability **within** a vector, not the distance **between** two vectors, doesn't it?
Comment: @rawr For how simple it is, I find it interesting. Thanks a lot for suggesting it!
Answer: I am not sure this is a programming question, because you do not know what you want to do yet, so we can't offer a solution. I think the main question here is what are you going to use this measure for, because you can measure dissimilarities in a lot of different ways, some will be good for what you want and some will not.
But trying to answer anyway, there is the utils::adist function and there is also a package called stringdist (these are the ones I have used before). But it seems that they are not quite what you want, based on your question, because they will measure the distance for each character string, and not for the whole matrix. But you could use them to have some ideas about how to measure the distance between the two vectors. For example, one measure could be how many changes you would have to make in vector a so it turns to vector b.
Comment: Yeah, try to be more specific, but in the meantime leave the question here for a while, maybe someone will come up with a better answer.
Comment: I am continuing from above. You're right, this is not a strictly programming question and it's generic. I thought it was useful to ask it here because, as there are functions and packages made for computing distances between numeric vectors, it could be the case that there were something also for nominal attributes. But probably not... Thanks for the suggestion anyways.
Answer: Thank you for keeping this open.
One option, which appears to have become available after this discussion, is R's qualvar (Gombin) package.  The package provides functions for each of Wilcox's (1967, 1973) Indices of Qualitative Variation.  Included with the package is a useful vignette summarizing implementation and results.  I have found in limited experience that index selection requires some brute-force testing with actual and simulated data.


how to get the total unanswered questions in mysql

Question: I have two tables, answerstbl and questionstbl. All questions are inserted in questionstbl and so as answeres in the answerstbl. Now, I want to get questions that are NOT YET answered by anybody by referring to the answerstbl. This is my query:
 "SELECT * FROM questionstbl LEFT JOIN answerstbl ON answerstbl.qu_id=questionstbl.qu_id
  GROUP BY ans_id"

However, the result is the question with answers.
Does anybody know?
Comment: Take a look at https://stackoverflow.com/questions/5706437/whats-the-difference-between-inner-join-left-join-right-join-and-full-join
Answer: So you want all the questions where that question id does not exist in the answers table......
SELECT Q.*
FROM questionstbl Q
WHERE NOT EXISTS(SELECT 1 FROM answerstbl A WHERE A.qu_id = Q.qu_id )

or like this....
SELECT Q.*
FROM questionstbl Q
WHERE
  Q.qu_id NOT IN (SELECT qu_id FROM answertbl)

Answer: You can use NOT IN comparison operator.
Query
Select * from questionstbl
where qu_id not in(
    select distinct qu_id from answerstbl
);

Answer: the condition to be check should be entered based on the fields in your table, if you could specify your table fields the condition could be filled in.
Query
select
questionstbl.qu_id as questionId,
answerstbl.ans_id as answersId,
from questionstbl, answerstbl
LEFT JOIN answerstbl ON answerstbl.qu_id=questionstbl.qu_id
where (condition to check questions that are NOT YET answered)
GROUP BY ans_id;

Answer: Something like this:
SELECT * FROM questionstbl WHERE qu_id NOT IN (SELECT qu_id FROM answerstbl)

Answer: Another option can be:
Select questions.qu_id, questions.question from questions INNER JOIN answers where questions.qu_id <> answers.qu_id

Above query result all questions fom questions table that are not yet answered. However, there is one mistake in your query, you want to get questions with no answers and you are grouping them with respect to answer id (where answer id does not exist for those questions).


Disable Kafka Session Timeout

Question: I am trying to step though the source code of Apache Camel to identify the source of a bug. I keep getting this error despite having configured a StringDeserializer for the consumer:
org.apache.kafka.common.errors.SerializationException: Can't convert key of class [B to class org.apache.kafka.common.serialization.StringSerializer specified in key.serializer
Caused by: java.lang.ClassCastException: [B cannot be cast to java.lang.String
    at org.apache.kafka.common.serialization.StringSerializer.serialize(StringSerializer.java:28)

When I try to step through Camel to try to figure out how the deserialized String is still ending up as a byte array, Camel keeps on shutting itself down because the Coordinator thinks the Consumer is dead:
20:45:04.171 [kafka-coordinator-heartbeat-thread | rtp-creditor-receive-payment] INFO  o.a.k.c.c.i.AbstractCoordinator - [Consumer clientId=consumer-1, groupId=rtp-creditor-receive-payment] Marking the coordinator rtp-demo-cluster-kafka-0.rtp-demo-cluster-kafka-brokers.rtp-reference.svc.cluster.local:9092 (id: 2147483647 rack: null) dead

How do I completely disable all timeouts so that I can step through the source code without worrying about the consumer getting marked as dead?
Comment: I think the problem here is that you dont specify a key serializer when putting messages and try to deserialize with StringDeserializer and becasue key serialized as byte array it cant be deserialized with StringDeserializer. So you should specify StringSerializer on producer side.
Comment: @alper I wish that were the case, but the string is being serialized just fine. The same topic can be consumed by other non-camel consumers just fine.
Comment: you could set timeouts in order to avoid being kicked, but I propose you other way around. create a parallel thread and pass him the reference of your consumer. in that thread, loop indefinitely, calling to poll() in intervals (each 30 seconds, f.e). Debug your other thread meanwhile.
Answer: Though you cannot disable all timeouts between a Kafka cluster and its consumers, you can modify a few properties to be very long:

group.max.session.timeout.ms - This is the max session timeout for any consumer. The default is five minutes. Set this to around max integer, such as 2100000000, in the broker properties file usually named server.properties.
max.poll.interval.ms - This is similar to the session timeout, and will mark a consumer as dead if there is no poll within this interval. Set this to a value less than request.timeout.ms as well, such as 1900000000.

From Apache Camel, you'll want to set the following properties:

consumerRequestTimeoutMs - This is the max time to wait for a response from the client. Set this to 2000000000.
sessionTimeoutMs - This is likely the session timeout that is marking your consumer as dead. This should be set to a value less than request.timeout.ms. So, something like 1900000000.

There may be a few more, found here, any with timeout or ms would be good ones to look at.

Disable Kafka Session Timeout


c++ getline doesn't get the input

Question: i am trying to input a line and then an integer then a line again however when it the last cin gets the line it and i press enter it crashes or outputs randomly to the infinity. whats wrong?
int main(){
    string a= "", b = "";
    int n1 = 0, n2 = 0;

    getline(cin, a);
    cin >> n1;

    //when i input the next like it outputs randomly without continuing with the next like why?
    getline(cin, b);

    //it doesn't let me to input here coz it's outputting some random strings.
    cin >> n2;
    return 0;
}

I appreciate for your help, thanks.
Comment: Don't mix `getline` with `cin >>` type input. It never works as you expect.
Comment: `it crashes or outputs randomly` I have a feeling you aren't showing the code you are using because there's no way the code above should crash or even output. In any case `getline(cin, b);` doesn't do what you think it does, you probably have a newline in your buffer left over from  `cin >> n1;`, so `getline(cin, b);` reads that newline, and then `cin >> n2;` tries to read whatever you expected to be read into `b` and presumably fails.
Comment: its not actually crashing but outputting random text.
Comment: For these kinds of questions, you should have copy-and-pasted your exact input, as your code will "work" for some inputs and not others.
Answer: You need to consume the newline character.
int main(){
    string a, b;
    int n1, n2;

    getline(cin, a);

    cin >> n1;
    cin.get(); // this will consume the newline
    getline(cin, b);

    cin >> n2;
    cin.get(); // this will consume the newline
}

std::getline will consume the newline for you.
Here's example usage:
21:42 $ cat test.cc
#include <iostream>
#include <string>

using namespace std;

int main(){
    string a, b;
    int n1, n2;

    getline(cin, a);

    cin >> n1;
    cin.get(); // this will consume the newline
    getline(cin, b);

    cin >> n2;
    cin.get(); // this will consume the newline

    std::cout << a << " " << b << " " << n1 << n2 << std::endl;
}
✔ ~
21:42 $ g++ test.cc
✔ ~
21:42 $ ./a.out
hello
4
world
2
hello world 42

Comment: thanks, while ago i dont use c++ and i forgot cin.get(). Thanks you bro.
Comment: `get` can be problematic... it reads exactly one character, so if there's any trailing whitespace after the number then you won't have consumed the "newline" as intended.  Walt's suggestion to use `ignore` is more robust, though ignoring input's dangerous too: using `skipws` then checking the next character is a newline is more robust.  The OP's code doesn't do any error checking though, so the benchmark's low.
Comment: I would tend to use getline exclusively, but he wanted the reason it wasn't working.
Comment: i didn't know i could input numbers without treating them as string. however when i used ignore it ignored the next cin. why does it happens @TonyD?
Comment: @kobbycoder: without seeing your actual input and attempt to use ignore, it's hard to say.  A working version's available [here](http://coliru.stacked-crooked.com/a/96602c91d25ad266) for reference/comparison.
Comment: @TonyD This is a bit out of scope.
Answer: For your case after your cin you should use cin.ignore() rather than cin.get() like this:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Comment: i used ignore before however it skipped the 3rd cin

c++ getline doesn't get the input


Erro "E2034 Cannot convert 'TByteDynArray *' to 'TByteDynArray'"

Question: Preciso realizar uma integração com Sistema Horus (Saúde), utilizando C++ Builder. Já importei o .cpp do web service de Homologação disponibilizado para meu projeto. Estou com problemas nos métodos utilizados para envio dos dados, onde o mesmo espera um ByteDynArray. Tentei converter meu XML conforme um exemplo encontrado, mas não está dando certo. Segue código:
    TMemoryStream *memStream;
    TByteDynArray *myByteArray = new TByteDynArray();

    XMLHorus->SaveToStream(memStream);
    myByteArray->set_length(memStream->Size);

    if(memStream->Size > 0)
        Move(memStream->Memory, myByteArray, memStream->Size);

    RecebeDadosWS *integracao = GetRecebeDadosWS(true, "http://220.127.116.11/horus-ws-basico/RecebeDadosWS?wsdl", HTTPRIO1);
    integracao->recebeDados(myByteArray);`

Porém, ele emite :

E2034 Cannot convert 'TByteDynArray *' to 'TByteDynArray'
E2342 Type mismatch in parameter 'source' (wanted 'const
  TByteDynArray', got 'TByteDynArray *')

Método do WebService:
virtual horus_ws_resposta* recebeDados(const TByteDynArray source) = 0;
Caso alguém já tenha feito essa integração, seria ainda melhor.
Comment: O que a tag *rstudio* está fazendo nesta pergunta?
Comment: Título editado: O problema não é com o webservice é a conversão das variáveis.
Answer: Simples: nos dois casos você está esquecendo de dereferenciar o ponteiro. Você tem que passar o tipo TByteDynArray, porém está passando TByteDynArray*. No caso você não está nem usando-lhe como um ponteiro, então seria melhor que você o declarasse como variável normal ao menos que estejas usando um garbage-collector.
Outra coisa: é melhor que tenhas implementado horus_ws_resposta* recebeDados(const TByteDynArray ) pois parece que estás tentando chamar uma função virtual pura.