calling function with lesser number of arguments in C?

Question: I strangely found that C allows linking of function where argument list doesn't match:
<code>//add.c
int add(int a, int b, int c) {
    return a + b + c;
}
//file.c
int add (int,int); //Note: only 2 arguments
void foo() {
    add(1,2);
}
</code>
I compiled add.c first, then compiled file.c, both got compiled successfully. Strangely, linker didn't give any sort of error or warning, probably the reason is C linker doesn't compare arguments while linking. I'm not 100% sure about it though. Someone please comment on this.
Now, the question is what is the good practice to avoid this situation or get some sort of warning during compilation, because in my project there are lot of functions in different files, and now & then we have to add some extra argument in the function.
Comment: @Dayalrai: no - it's undefined behaviour - almost anything can happen. On many ABIs the stack frame will be incorrect, leading to potentially disastrous consequences.
Comment: I don't want to get into a vote war but upvoted because this is a perfectly reasonable question that will lead an improved understanding of 'C'.
Comment: function will operate as-if it had all the parameter, but the third parameter could just be junk and leads to [UB](http://en.wikipedia.org/wiki/Undefined_behavior).
Comment: You have a double -and inconsistent- declaration. Declarations are only useful at compile time, so the compiler can check that the function is used correctly. If you manage to fool the compiler like you have done, the linker will just find a call to `add()` and code for `add()` and will link them together.
Comment: The correct behaviour is to have an include file that exposes the prototypes (function declarations) that are in a C file. If you have add.c you must have add.h where the functions of add.c are declared as prototypes ... This behaviour allows you to avoid the issue you indicate. You may use `gcc -Wall` to verify all warnings, the option `--pedantic` indicates more warning (but is very boring)
Comment: Can somebody tell me, why did I get downvote? At least I deserve a reason for the downvote.
Answer: Use your header files correctly.
Configure your compiler to emit as many warnings as possible.
Mind the warnings!
add.h
<code>#ifndef ADD_H_INCLUDED
#define ADD_H_INCLUDED
int add(int a, int b, int c);
#endif
</code>
add.c
<code>#include "add.h"
int add(int a, int b, int c) {
    return a + b + c;
}
</code>
file.c
<code>#include "add.h"
void foo() {
    add(1, 2);
}
</code>
Answer: Calling a function with to few arguments leads to undefined behavior as the value of those arguments will be indeterminate.
Answer:
C linker doesn't compare arguments while linking.

That is correct. Unlike C++ linker which considers argument types to be part of a function signature, C linker considers only function names. That is why it is possible to create a situation with undefined behavior simply by supplying a wrong function prototype the way that you show.

what is the good practice to avoid this situation or get some sort of warning during compilation?

Always put prototypes of functions that you are intended to share into a header, and include that header from the places where the function is used and the place where the function is defined. This would ensure that compiler issues a diagnostic message. Treat all compiler warnings as errors. C compilers are often rather forgiving, so their warnings usually indicate something very important.


Como devem ser selecionados os dados de uma tabela através de junções?

Question: Ao usar o SELECT para obter os dados da tabela_A efetuando uma junção com a tabela_B, normalmente, e crendo que a seja a forma correta, utilizamos alguns dos comandos JOIN. Ex:
SELECT codigo, nome FROM tabela_A a
INNER JOIN tabela_B b ON b.fk_tabela_B = a.codigo

Porém, a mesma condição eu consigo obter utilizando a seguinte sintaxe:
SELECT codigo, nome FROM tabela_A a, tabela_B
WHERE b.fk_tabela_B = a.codigo

O primeiro exemplo, possui uma leitura mais fácil, IMO, e o segundo exemplo poupa alguns caracteres.

Mas qual a diferença no uso dos dois?
Há questões de performance ou tratamento diferenciado dos dados obtidos?
Posso dizer que apenas um dos exemplos é a maneira correta de se fazer?
Comment: [Qual a diferença entre unir tabelas por JOIN e WHERE?](http://pt.stackoverflow.com/q/15025/91)
Answer: Os dois exemplos estão corretos, a performance é a mesma bem como os dados retornados serão os mesmos. A diferença que o primeiro poderá ser usado em qualquer sintaxe. Enquanto que o join varia de uma linguagem para outra. Espero ter lhe esclarecido.
No meu caso meus professores da faculdade ensinaram nas duas formas.


Setar data dentro de um ArrayList usando Cursor

Question: Em uma App de finanças o cursor não tem nenhum tipo de getData ou getCalendar.
O que usar ao invés disso?
    public List<Despesa> getLista() {
    Cursor c = getWritableDatabase().query(TABELA, COLUNAS, null, null, null, null, null);
    List<Despesa> lista = new ArrayList<Despesa>();

    while (c.moveToNext()) {
        Despesa despesa = new Despesa();
        despesa.setId(c.getInt(0));
        despesa.setValor(c.getString(1));
        despesa.setData(c.getString(2));
        despesa.setDescricao(c.getString(3));
        despesa.setPago(c.getString(4).equalsIgnoreCase("TRUE"));
        despesa.setIdGrupo(c.getInt(5));
        despesa.setIdSubgrupo(c.getInt(6));
        despesa.setIncluidoEm(c.getString(7));
        despesa.setSincronizado(c.getString(8).equalsIgnoreCase("TRUE"));

        lista.add(despesa);
    }
    c.close();

    return lista;
}

Adapter
public class DespesaAdapter extends BaseAdapter {
private Context context;
private List<Despesa> lista;
ListView listView;

public DespesaAdapter(Context context, List<Despesa> lista){
    this.context = context;
    this.lista = lista;
}

@Override
public int getCount() {
    return lista.size();
}

@Override
public Object getItem(int position) {
    return lista.get(position);
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int position, View view, ViewGroup viewGroup) {
    final int auxPosition = position;

    LayoutInflater inflater = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final LinearLayout layout = (LinearLayout)
            inflater.inflate(R.layout.despesas,null);

    TextView tvNome = (TextView)
            layout.findViewById(R.id.tvDesp);
    tvNome.setText(lista.get(position).getDescricao());

    TextView tvValor = (TextView)
            layout.findViewById(R.id.tvVal);
    tvValor.setText(lista.get(position).getValor());

    ImageButton btEditar = (ImageButton)
            layout.findViewById(R.id.btEdit);
    btEditar.setOnClickListener(new ImageButton.OnClickListener(){

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context, EditaDespesaActivity.class);
            intent.putExtra("valor", lista.get(auxPosition).getValor());
            intent.putExtra("data", lista.get(auxPosition).getData());
            intent.putExtra("descricao", lista.get(auxPosition).getDescricao());
            context.startActivity(intent);
        }
    });

    ImageButton btDelete = (ImageButton)
            layout.findViewById(R.id.btDelete);
    btDelete.setOnClickListener(new ImageButton.OnClickListener() {
        @Override
        public void onClick(View view) {
            DespesaDAO despesa = new DespesaDAO(context);
            despesa.deletar(lista.get(auxPosition));

            layout.setVisibility(View.GONE);
        }
    });

    return layout;
}

}
Comment: Allan, está gravando a data como `String` no banco? Em que formato? Dentro do `getLista`, por que não usa um `DateFormat` para transformar a data de `String` para `Date`? Você também poderia gravar data como `Long` (milisegundos) e usar o `Calendar.getInstance().setTimeInMillis(...)`.
Comment: ambos os campos data e incluidoEm são da classe Calendar. Precisarei mudar?
Comment: Você disse o que quer, mas não está claro sobre o que sabe e o que tem.
Comment: Onde está o Adapter?
Comment: atualizado com Adapter @Rafael
Comment: Estou gravando direto sem formatar, pois fiz pra testar... Como exatamente seria essa conversão de String pra Date? Ou então eu troco de String pra Long e uso o Calendar pra setar em millisegundos, poderia me explicar? @Wakim
Comment: Quando chegar em casa posso montar uma resposta detalhada, mas a principio a coluna que guarda a data no SQLite poderia ser um `long` e você usaria o `Calendar.getTimeInMillis` para pegar o timestamp (Calendar -> long) e gravar. Pra fazer o inverso é só usar o `Calendar.getInstance().setTimeInMillis` (long -> Calendar) para popular seu objeto.
Comment: Fico no aguardo da sua resposta detalhada, como sou iniciante no android não entendi muito o que é para fazer, agradeço desde já. @Wakim
Answer: O cursor tem o metodo "getColumnIndex"
cursor.getColumnIndex(<nome da coluna>)

Geralmente o que se faz é:
cursor.getString(cursor.getColumnIndex(<nome da coluna>)  , tambem pode ser getInt(), getLong(), etc


MySQL on Mac OS X Issues

Question: I installed MySQL from:
http://dev.mysql.com/downloads/mysql/5.0.html#macosx-dmg
I am on OS X 10.5.8.  I open Terminal and do:
cd /usr/local/bin

then:
mysql -u root

I get the following error:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

I have spent the last 2 hours scouring sites looking for an answer that makes sense.  This is a brand new laptop.  I am at a loss.  Here is my .bash_profile:
export PYTHONPATH=/Users/blwatson/pythonpath;/Users/blwatson/pythonpath/bin:$PYTHONPATH

# Setting PATH for MacPython 2.6
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/2.6/bin:${PATH}"
export PATH
export

PATH=/usr/local/mysql/bin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

I am at a loss.  The install order was:
1) Django
2) Python 2.6
3) MySQL 5
Answer: Did you start MySQL?
Comment: I don't know enough to answer that question.
Comment: Well, if you don't know if you started it, you probably didn't.

ps aux|grep mysql

if you didn't install the system preference pane off the DMG, do that, and use it to start MySQL.
Answer: Check that the socket exists at /tmp/mysql.sock. If not, start mysql
sudo /usr/local/mysql/bin/mysqld_safe

Then try logging into the mysql client
/usr/local/mysql/bin/mysql -u root

Comment: OK...so you now have me running.  First, thank you.  Second, what did you do exactly?  Third, will I have to run that mysqld_safe command every time?  I am a Windows guy and new to dev environment on Mac OS X.  Quick learner, but still learning.
Comment: In the DMG is a file called *MySql.prefPane*.  Run that and it will install a System Preferences pane that lets you control whether or not MySql starts on boot.
Comment: Wow...3 hours of frustration reduced to 6 lines of answers from ServerFault users.  Thanks guys.  Now I just have to sort out how to get PythonMySQL sorted.
Comment: I have found the mysql prefpane to be somewhat broken on 10.5, and I havn't even bothered with it on 10.6 (as it will be 32-bit). A better solution to autostart mysql is to create a launch daemon and submit it to launchd as described here:
http://www.macosxhints.com/article.php?story=20080128103022907
Answer: To start MySql go to System Preferences  > MySql > Start
Comment: Because that option is added to the System Preference panel if you install the MySQL package from the official site.
Comment: I do not see MySql in the System Preferences

MySQL on Mac OS X Issues


Java Logging vs Log4J

Question: Is it still worth to add the log4j library to a Java 5 project just to log
let's say some exceptions to a file with some nice rollover settings.
Or will the standard util.logging facility do the job as well?
What do you think?
Comment: See http://stackoverflow.com/a/13144054/603516 for numerous log4j 1.2 locking issues to be considered.
Answer: I'd say you're probably fine with util.logging for the needs you describe.
For a good decision tree, have a look at Log4j vs java.util.logging

Question One :
Do you anticipate a need for any of the clever handlers that Log4j has that JUL does not have, such as the SMTPHandler, NTEventLogHandler, or any of the very convenient FileHandlers?

Question Two :
Do you see yourself wanting to frequently switch the format of your logging output? Will you need an easy, flexible way to do so? In other words, do you need Log4j's PatternLayout?

Question Three :
Do you anticipate a definite need for the ability to change complex logging configurations in your applications, after they are compiled and deployed in a production environment? Does your configuration sound something like, "Severe messages from this class get sent via e-mail to the support guy; severe messages from a subset of classes get logged to a syslog deamon on our server; warning messages from another subset of classes get logged to a file on network drive A; and then all messages from everywhere get logged to a file on network drive B"? And do you see yourself tweaking it every couple of days?

If you can answer yes to any of the above questions, go with Log4j. If you answer a definite no to all of them, JUL will be more than adequate and it's conveniently already included in the SDK.

That said, pretty much every project these days seems to wind up including log4j, if only because some other library uses it.
Comment: Cheers - Changed it out for a wayback machine one.
Comment: Great questionnaire based answer. To each his own based on needs.
Comment: `Log4j vs java.util.logging` link doesn't work anymore
Answer: I recommend that you use the Simple Logging Facade for Java (SLF4J). It supports different providers that include Log4J and can be used as a replacement for Apache Commons Logging.
Comment: What's wrong with Commons Logging?
Comment: @Bart van Heukelom and comment upvoters - read http://articles.qos.ch/thinkAgain.html
Comment: @Stephen C: Thanks for the info, though I learned that some time ago and am now using SLF4J whenever I can. (My comment was a real question btw, not a conservative remark)
Comment: @Bart, Commons Logging use dynamic discovery of the package to use.  SLF4J use (or used to) need the classes in the backend to load at all.
Answer: Log4j has been around for a long time, and it works very well.  I have no scientific study to back it, but based on what I've seen at a large number of clients, it is easily the logging framework that I see used more than any other.  It has been around for a long time, and not been replaced by the Next Big Logging Framework, which says something.
It is dead simple to set up, and easy to learn the basic appenders (outputs).  There are a whole host appenders that are available, including:

ConsoleAppender
DailyRollingFileAppender
ExternallyRolledFileAppender
FileAppender
JDBCAppender
JMSAppender
NTEventLogAppender
RollingFileAppender
SMTPAppender
SocketAppender
SyslogAppender
TelnetAppender
WriterAppender

Plus others.  It isn't difficult to write your own appender either.  Additionally there is a great deal of flexibility in each of the appenders that allow you to control specifically what is output in your log.
One note, I had a series of classloader problems when I used apache commons logging in addition to log4j.  It was only for one specific application, but I found it simpler to use log4j alone, rather than to have the flexibility offered when using an abstraction layer like commons logging.
See this article for
more details:
Good luck!
Answer: java.util.logging offers a comprehensive logging package without the excess baggage some of the others provide..
Comment: Plus, it is **included by default** and **used by Java itself** (so you will have it anyway!)
Answer: log4j is a much nicer package overall, and doesn't have some of the hiccups that java.util.logging contains.  I'd second that using log4j directly is easier than using the commons logging.
Comment: Can you please be more specific about the hiccups that java.util.logging has ?
Comment: Sure, like the overhead in logging synchronized methods: see https://github.com/playframework/playframework/issues/6958 and https://bugs.openjdk.java.net/browse/JDK-8077846
Answer: I recommend using Apache Commmons Logging as your logging interface. That way you have the flexibility to switch logging implementations anytime you want without requiring any code changes on your end.
Answer: I would go with log4j. The possibilites with log4j is not obsolete at all!

Java Logging vs Log4J


How to allow IFRAME in VS Team Service custom TAB

Question: I have an extension that adds custom TAB in VSTS see image below

It  works perfectly fine in chrome but not in IE see image below for the result:

This the code inside my extension:

Do I need to configure something in the code or in VSTS itself to allow iframe?
Comment: Is the content page site managed by you?
Comment: @Eddie-MSFT You mean `https://samplewebsite.net/` ? yes
Comment: Then try updating that site to allow it to be displayed in other frame: http://stackoverflow.com/questions/14141388/iframe-this-content-cannot-be-displayed-in-a-frame.
Comment: @Eddie-MSFT I tried to embed iframe to another web app not VSTS and it works perfectly fine, do you think VSTS is preventing us to embed IFRAME?
Comment: No, VSTS allow this. "If you have a web page that can be hosted in a an iframe, it can be hosted in Visual Studio Team Services as a hub." This is the description from VSTS document: https://www.visualstudio.com/en-us/docs/integrate/extensions/develop/add-hub
Answer: It looks like the content security policy (CSP) of the site you are trying to embed has configured itself to disallow it to be embedded in a different website.
It's either specifying:
frame-ancestors 'none'

Or it's older equivalent:
X-Frame-Options: DENY

I suspect the latter, as X-Frame-Options is deprecated in favor of CSP and Chrome only partially implements it.


How to query with equalTo in emberfire?

Question: I'm trying to make a trully simple query with Emberfire, but it's not working. No console errors, it just doesn't do a thing.
My versions are Ember 2.2.0, Ember-data 2.2.0 and EmberFire 1.6.1
My data is something like the folowing:
{
  'data':[{
   'element' : 0
  },{
   'element' : 1
  },{
   'element' : 1
  },{
   'element' : 0
  },{
   'element' : 2
  }]
}

And my query in Ember would be something like this:
export default Ember.Route.extend({
  model(){
    return this.store.query('data', { orderBy: 'element', equalTo: 1 } );
  }
});

The results, passing trough an each loop, are looking like this
0 0 1 1 2

Only works the orderBy part, not the equalsTo.
Any suggestions?
Comment: I found that question [link](http://stackoverflow.com/questions/27877612/firebase-no-index-defined) that solves part of my problem. Now I don't fall on Firebase warning adding the needed security rule. Now comes the funny part. As I can see, if I try to query with equalTo : 0, it returns all the available positions. Maybe it's parsing the query as a false, trying to do an exact match with false, and then everything is not exactly false, so... everything matches.
If the desired search is other value it works fine.
Any clue? (more htan adding an empty position at the begining :D)
Comment: What if u parsed it to a string :D ?
Comment: Let me go away backwards, getting into a bush like Homer, please.
Lot of thanks. Anyway, it's a little bit ankward to "stringify" numbers just for that...
Comment: Well it does seem like it parses it as false. "ankward"
Comment: @LowloDesign I emailed the [Firebase + Ember] google group and they let me know this is a bug. I was trying to pass `false` but looking at the code `0` would be treated the same way:
"Looks like you found a bug!

We are not correctly detecting when you pass `false`.

https://github.com/firebase/emberfire/blob/5858d4ce9f533d5faa1f86f53a1271d1be077b59/addon/adapters/firebase.js#L315-L317

I will get this sorted ASAP."
Comment: Thanks for asking them @Aaron !
Finally I overcame the problem modifying the model, turning day data type from number to string. But I'm still thinking it's a nonsense, and they told you it's a bug, so I wasn't too away... Ping me back if they update you.
Answer: There is an Ember addon for querying a firebase search.
You can check it out here:
https://www.npmjs.com/package/ember-emberfire-find-query

How to query with equalTo in emberfire?


How can I trigger an action to draw on a canvas immediately after the template loaded?

Question: I want to draw on a canvas in a template immediately after the template loaded, so I think I need a suitable hook (event) to do it but I could not find one.
I read the answer for How can I trigger an action, when a template is loaded in ember? and I tried to use "setupController" event to do it but it did not work.
template.hbs
<canvas id="lyric-editor" width="200" height="200"/>

route.js
import Ember from 'ember';
export default Ember.Route.extend({
  setupController: function() {
    var canvas = document.getElementById('lyric-editor');
    console.log(canvas:" + canvas);
    // the result is null, it means the template is not loaded at this time.
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = 'white'; // Color of the bars
    ctx.fillRect(50, 50, 40, 40);
  }

There are beforeModel method and afterModel method in the Ember.route class so I expected something like afterTempalteLoad method.
Any hints are appreciated, Thanks in advance!
Answer: I would create a component (by using ember g component canvas-component in the terminal) and in the component use the didInsertElement hook.
So in canvas-component (or whatever you choose to call it)
didInsertElement() {
   this._super(...arguments);

   const canvas = this.$();
   console.log(canvas:" + canvas);
}

I definitely recommend reading through the ember docs about components
Comment: Thank your quick answer, Iguchi. It works perfectly and the link is very useful, I'll read it through.


How to mouse hover, highlight, and get properties of the DOM objects in a web page from external domain

Question: I am trying to develop a web application which has functionality similar to the Element Selector in developer tools in Chrome.
I need to open any URL from other different domains, inside a container in my app, and the page should appear exactly as it appears in normal browser, with all it styles. Then I should be able to hover over the elements in the opened page, highlight it, and display some property information about this element.
I created a simple Angular app and used Iframe tag to open the third party page.  But, when I try to attach event handlers, with addEventListener, to the DOM elements in the Iframe, I get the cross-domain error message.

Uncaught DOMException: Blocked a frame with origin
  "http://localhost:4200" from accessing a cross-origin frame.

I read some posts in stackoverflow like "Cross site contents cannot be read by JavaScript" and "If you don't have control over the framed site, you cannot circumvent the cross-domain policy." For more details check the links:
Get DOM content of cross-domain iframe
Cross domain iframe issue
Following is my code:

function frameLoad() {
    let frame = document.getElementById("pFrame");
    let iframeWindow = frame.contentWindow;
    iframeWindow.addEventListener("mouseover", mouseOver, true);
    iframeWindow.addEventListener("mouseout", mouseOut, true);
    iframeWindow.addEventListener("click", onClick, true);
}

Do you have any advice or maybe suggest different technique to solve this problem?
Thanks
Answer: Have you tried looking the Mozilla Goggles project ?
It has an integrated editor, and their inspector seems to be very powerful.
Plus it don't require any application on your computer.


Openvpn multiple client same gateway

Question: I have two clients that need to connect to one OpenVPN server. Is it possible to use the same gateway for both clients in the ifconfig parameter?
Client A config file
[...]
ifconfig 10.0.0.2 10.0.0.1

Client B config file
[...]
ifconfig 10.0.0.3 10.0.0.1

The situation on the server is the following:
tun0
inet 10.10.0.1 destination 10.10.0.2

tun1
inet 10.10.0.1 destination 10.10.0.3

Now all is working fine but might it give some problem time going on?
I was told to use different gateway like this:
Client A config file
[...]
ifconfig 10.0.0.2 10.0.0.1

Client B config file
[...]
ifconfig 10.0.1.2 10.0.1.1

But I thought different gateway are needed just for routing purpose, if I want to add a route and forward my traffic on a specific tun interface I indeed need different gateway or the server does not know which one to send the packets, but if I don't need a specific route can I use my first configuration?
Thank you
Answer: Typically, a point to point interface, such as tun0 or any other tunnel-like interface needs a local address only for tunnel management purposes or a particular tunnel identification.
Think about a tunnel interface as a remote attached endpoint. This interface has two ends - you and the other end. In general, there's no need to use any addresses on interfaces like this when only two parties connected are involved in data exchange - you can just send a packet over this interface and it will be delivered to the other end, it has no other way around.
Things get a little more complicated if some third-party needs to be able to reach your remote attached endpoint. To get to this endpoint they'll need a remote address as a packet destination. Remote side, conversely, uses your local address in order to identify it's version of the other end when it needs to, i.e. it installs default route to it; however it could use the tunnel interface itself as the route destination without even knowing your local address and it would still work.
So unless you need to identify your tunnel interface by it's local endpoint (i.e. to use it as a source address for certain dynamic routing protocol scenarios over the tunnel) you could use any address you wish as the local address on the tunnel - it doesn't even need to be on the same subnet as the remote address.
Comment: Thank you! So if I got it right, the local adress of my interface eg. 10.0.0.1 is needed by my client just to send packets to my OpenVPN server, once the packets reach my server, my server will send the packets on the internet hiding my ip adress and then send them back to my client (I use openvpn with post routing masquerade iptables just to hide my client ip address). So if I have two clients connected to my openvpn server and they independent from each other, and my purpose is to only hide their IP adresses without using any routing protocol, I can specificy same gateway (10.0.0.1)for both.
Comment: Yes, that's exactly it.
Comment: Ok thank you very much, I was struggling about it because I was told that multiple interfaces can't have same ip address (and that's true as well it might cause collision or others issue), so I was wondering how could it work since "ifconfig" on my openvpn server gives the following:

tun0 (windows machine)
inet 10.0.0.1 netmask 255.255.255.255  destination 10.0.0.2

tun1 (linux machine)
inet 10.0.0.1 netmask 255.255.255.255  destination 10.0.0.3
Answer: It is possible and correct. The gateway parameter defines the configuration on the client which is used to send data to the VPN, to be possible to define routing as usual in IP. Once the packet is sent to the OpenVPN process, it takes care of its routing (until it leaves some other OpenVPN process).
In particular, you define:
ifconfig 10.10.0.3 10.10.0.1

The only result of this command is like you run the following commands on the client:
ip address add 10.10.0.3 dev tun0
ip route add 10.10.0.1 dev tun0

That's all. Other clients, a server, external systems — nobody else knows about this client configuration.
The only thing where gateway is used is to write routes towards VPN like this:
ip route add 192.168.0.0/24 via 10.10.0.1

e.g. to set this network to be accessible through VPN. For instance, the route to VPN server and other clients is done like this. Of course, if you have several clients, you may use the same gateway address on them (and you do this naturally, for example, for neighbour computers in the same LAN).
The same thing is applicable to a server as well. For example, I run several VPNs on a single machine (one is via UDP, the other is via TCP on port 443 with port-share option — to be able to sneak through firewalls that block usual ports but allow 443 and even check if there is a webserver). Those servers both have the same local address configured, and differ by remote (that makes possible to set which VPN I route packet through).
Now about problems that you'll encounter. With full-blown Linux OpenVPN no problems, of course. If you are going to use "OpenVPN Client", be it Linux, Windows, iOS/iPadOS/macOS or Android client, it depends on which topology you set. In net30 topology they will reject such configuration as invalid. In this case, client address and its remote should belong to the same /30 subnet.
Comment: Thank you! Then if I use a Windows host machine and a vmware Linux in bridged mode and on the Windows I set 10.0.0.2 as ip adress and 10.0.0. 1 the gateway, then on the Linux I set 10.0.0.3 as ip adress and 10.0.0.1 as the gateway and my purpose is only to send packets over vpn to hide the public ip adress on both Windows and Linux machine I should not encounter any problem right? On the server ifconfig command shows (tun0 10.0.02 via 10.0.01 (Windows), tun1 10.0.03 via 10.0.0.1 (Linux)). Its working fine but I just had the doubt that having two 10.0.0.1 for different interfaces could be bad
Comment: You overthink the problem. The "hiding" has nothing to do with this at all. It is all defined on server through which you are going to route packets (usually VPN server). If you don NAT there, IP addresses of clients will be hidden.
Comment: Ok thank you it's all more clear now, so having this conf

`Client A conf file
remote
dev tun
ifconfig 10.0.0.2 10.0.0.1
redirect-gateway autolocal
dhcp-option DNS 188.8.131.52
secret secret.txt`

`Server A conf file
dev tun
ifconfig 10.0.0.1 10.0.0.2
secret static.key`

`Client B conf file
remote
dev tun
ifconfig 10.0.0.3 10.0.0.1
redirect-gateway autolocal
dhcp-option DNS 18.104.22.168
secret secret.txt`

`Server B conf file
dev tun
ifconfig 10.0.0.1 10.0.0.3
secret static.key`

it's a correct configuration and shouldn't get any problems in using it.

Openvpn multiple client same gateway


Comparing Numpy and Matlab array summation speed

Question: I recently converted a MATLAB script to Python with Numpy, and found that it ran significantly slower. I expected similar performance, so I'm wondering if I'm doing something wrong.
As stripped-down example, I manually sum a geometric series:
MATLAB version:
function s = array_sum(a, array_size, iterations)
    s = zeros(array_size);
    for m = 1:iterations
        s = a + 0.5*s;
    end
end

% benchmark code
array_size = 500
iterations = 500
a = randn(array_size)
f = @() array_sum(a, array_size, iterations);
fprintf('run time: %.2f ms\n', timeit(f)*1e3);

Python/Numpy version:
import numpy as np
import timeit

def array_sum(a, array_size, iterations):
    s = np.zeros((array_size, array_size))
    for m in range(iterations):
        s = a + 0.5*s
    return s

array_size = 500
iterations = 500
a = np.random.randn(array_size, array_size)
timeit_iterations = 10
t1 = timeit.timeit(lambda: array_sum(a, array_size, iterations),
                   number=timeit_iterations)
print("run time: {:.2f} ms".format(1e3*t1/timeit_iterations))

On my machine, MATLAB completes in 58 ms. The Python version runs in 292 ms, or 5X slower.
I also tried speeding up the Python code by adding the Numba JIT decorator @jit('f8[:,:](i8, i8)', nopython=True), but the time only dropped to 236 ms (4X slower).
This is slower than I expected. Am I using timeit improperly? Is there something wrong with my Python code?
EDIT: edited so that the random matrix is created outside of benchmarked function.
EDIT 2: I ran the benchmark using Torch instead of Numpy (calculating the sum as s = torch.add(s, 0.5, a)) and it runs in just 52 ms on my computer!
Comment: @Divakar I think recent numba versions support some of the array allocation functions. @ LorenzForvang your test only performs element-wise operations, which are not implemented in BLAS as far I know (that is not to say they should be slower in numpy).
Comment: You have `nopython=True`, but aren't you using NumPy funcs there?
Comment: @Divakar yes, I'm using NumPy functions there. This page (http://numba.pydata.org/numba-doc/dev/reference/numpysupported.html) lists many NumPy functions are supported by Numba in nopython mode. But the run time is the same whether I set `nopython` to True or False.
Comment: @kazemakase good point! I removed the reference to BLAS
Comment: Btw, fun fact: I changed the iteration to perform a matrix dot product `s = r * s` in Matlab and `s = r @ s` in Python. Matlab was still faster but only by a factor of 1.5.
Comment: What BLAS is your Python/Numpy linked to? OpenBLAS, ATLAS, Intel MKL?
Comment: @GertVdE Intel MKL
Answer: From my experience, when using numba's jit function it's usually faster to expand array operations into loops. So I tried to rewrite your python function as:
@jit(nopython=True, cache=True)
def array_sum_numba(a, array_size, iterations):
    s = np.zeros((array_size, array_size))
    for m in range(iterations):
        for i in range(array_size):
            for j in range(array_size):
                s[i,j] = a[i,j] + 0.5 * s[i,j]
    return s

And out of curiosity, I've also tested @percusse's version with a little modification on the parameter:
def array_sum2(r, array_size, iterations):
    s = np.zeros((array_size, array_size))
    for m in range(iterations):
        s /= 2
        s += r
    return s

The testing results on my machine are:

original version run time: 143.83 ms
numba jitted loop version run time: 26.99 ms
@percusse's version run time: 61.38 ms

This result is within my expectation. It's worthing mentioning that I've increased timeit iterations to 50, which results in some significant time reduction for numba version.
In summary: The Python code can still be significantly accelerated if you use numba's jit and write the function in loops. I don't have Matlab on my machine to test, but my guess is with numba the python version is faster.
Answer: Since you are updating the same variable suitable for inplace operations, you can update your function as
def array_sum2(array_size, iterations):
    s = np.zeros((array_size, array_size))
    r = np.random.randn(array_size, array_size)
    for m in range(iterations):
        s /= 2
        s += r
    return s

This has given the following speed benefit on my machine compared to array_sum
run time: 157.32 ms
run time2: 672.43 ms

Comment: thank you, this sped up my code, though not quite as dramatically. Run time on my machine dropped from 292 ms to 259 ms with Numpy (4X MATLAB), and from 236 ms to 185 ms with Numpy+Numba (3X MATLAB).
Comment: @LorenzForvang That sounds strange indeed. Are you using NumPy+MKL ? I usually go for Cython actually.
Comment: yes, numpy.show_config() shows libraries = ['mkl_intel_lp64', 'mkl_intel_thread', 'mkl_core', 'iomp5', 'pthread'] for blas_mkl_info and lapack_mkl_info
Answer: Times include the randn call as well as the summation:
In [68]: timeit array_sum(array_size, 0)
16.6 ms ± 436 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [69]: timeit array_sum(array_size, 1)
18.9 ms ± 293 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [70]: timeit array_sum(array_size, 20)
55.5 ms ± 131 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [71]: (55-16)/20
Out[71]: 1.95

So it's 16ms for the setup, and 2ms per iteration.  Same pattern with 500 iterations.
MATLAB does some JIT compilation.  I don't know if that's the case here or not.  I don't have MATLAB to test.  In Octave (no timeit)
>> t = time(); array_sum(500,0); (time()-t)*1000
ans =  13.704
>> t = time(); array_sum(500,1); (time()-t)*1000
ans =  16.219
>> t = time(); array_sum(500,20); (time()-t)*1000
ans =  82.346
>> t = time(); array_sum(500,500); (time()-t)*1000
ans =  1610.6

Octave's random is faster, but the per iteration sum is slower.
Comment: @hpaulj I get the following timings in Matlab: 0, 1, 20, 500 iterations -> 4.77, 5.15, 10.13, 133.6 ms. (I guess we see jit effects for larger numbers of iterations)
Comment: This means 1000ms for 500 iterations and more or less negligible 16ms for the setup. (In Matlab the picture is similar: 5 ms setup time). So most of the difference comes from the iteration which is the question, isn't it?
Comment: @kazemakase, Is the MATLAB per iteration time consistent regardless whether you run 1, 20 or 500 iterations in a call?
Comment: @hpaulj with 500 iterations, the 16 ms setup becomes negligible. In any case, I made the random matrix a function parameter so that doesn't impact the test. I got 58 ms in MATLAB, 292 ms in Python, 229 ms in Python + Numba. I do not have Octave set up, but I'll trust that it's slower than MATLAB and Python.


ks test for discrete distributions

Question: I have a two samples of data of very different length, think train and test sets for a machine learning model. The data is binary and I'd like to know if the two have a comparable distribution of values. The data is also very imbalanced (~5% of 1s).
As per comment a summary of the data:

sample 1: 950 0s and 50 1s
sample 2: 90 0s and 10 1s

So what the resampling / bootstraping is trying to answer, if i resample from sample 1, how probably is a distribution as observed in sample 2.
As the KS test can only be applied to continuous distributions, I figured I could bootstrap the data and take their mean (share of 1s) and then compare the distribution of these means with a KS test.
Is this a reasonable approach, any literature on how to tackle this? How can I decide how many samples to use and how often to resample?
Background is I'd like to implement this in python and automate this test. My current approach:
def bootstrap_ks(x1,x2,col):
    xv1 = pd.DataFrame(np.random.choice(x1, size=[100,1000] )).mean()
    xv2 = pd.DataFrame(np.random.choice(x2, size=[100,1000] )).mean()
    xv1.plot.hist(alpha=0.2, bins=50)
    xv2.plot.hist(alpha=0.2, bins=50)
    plt.title(col)
    plt.show()
    return stats.ks_2samp(xv1,xv2)

Comment: Bootstrapping won't magically produce continuous distributions.  That indicates this approach is doomed.  A better question would describe the data and ask *how* to compare them.  Consider editing your post accordingly.
Answer: Statistical distributional tests of two samples of 0s and 1s should not be done via ks-test but can easily done via Fisher's exact test or Chi-Squared-Test-of-Independence. I am not familiar enough with Python, but basically if you sample 80:20 from one group and 90:10 from the other that can be displayed in a contingency table:
         `0` `1`
Group 1  80  20
Group 2  90  10

And these are usually tested via on of tests mentioned above.
Note that these tests will answer whether there is significance which is "enough proof of difference". What is considered "enough evidence" depends heavily on the sample sizes you take.
You have not explained why you want to investigate this but you might want to consider plotting the distribution of odds ratios or something else more meaningfull then $p$-values.

How can I decide how many samples to use and how often to resample?

The number $n$ of resamples is high enough, if many resamplings of size $n$ deliver return values that are close enough. Choose a sample size $n$, e. g. $n = 500$, resample 10 times with $n$ resamples and judge depending on the range of return values, if that was precise enough for you. If not of if in doubt, increase $n$ substantially and start over.
Comment: Great. It was to be expected that you could find these implemented in Python easily. Prefer Fisher's exact test for smaller samples and $\chi^2$ for larger ones, with lots of middle ground where both perform very similar.
Comment: Turns out `scipy` has a `stats.fisher_exact` which does the trick and `stats.chi2_contingency` functions that do the trick nicely.

ks test for discrete distributions


Como usar GROUP_CONCAT na cláusula WHERE, com números?

Question: Bom dia.
Tenho as seguintes tabelas numa base MySQL:
BOIS
------------
| id | boi |
------------
| 12 | 77  |
| 22 |  8  |
| 14 | 12  |
------------

BOIS_MANEJO
---------------------
| id | fk_boi| peso |
---------------------
|  1 |   14  |  217 |
---------------------
|  2 |   22  |  217 |
---------------------
|  3 |   14  |  250 |
---------------------

A seguinte Query me trás todos os ids dos bois.
    SELECT *
FROM bois
WHERE
    id NOT IN(
    SELECT CONCAT("'", GROUP_CONCAT(DISTINCT(m.fk_boi) SEPARATOR "','"), "'") FROM bois_manejo AS m
    )

Eu obtenho o ID 12 somente com as seguintes fórmulas.
    SELECT id
FROM bois
WHERE
    id NOT IN(14, 22)
# OU id NOT IN('14', '22')

Como posso usar o GROUP_CONCAT com números, ou como posso resolver essa situação?
Obrigado desde já.
Comment: Qual é o resultado esperado?
Comment: @FilipeL.Constante, o resultado esperado é o ID 12. É o único que não está na tabela bois_manejo.
Comment: Não entendi o motivo de você tentar uma outra forma, uma vez que já tem o select que lhe traz o resultado esperado..
Comment: @FilipeL.Constante, eu não tenho o SELECT que trás o 12. Se está falando do SELECT que deu certo (o segundo) ele dá certo só porque eu sei os códigos que estão lá. O objetivo da query é me trazer os resultados conforme há mudança na base/alimentação da tabela. O primeiro select me trás todos os IDs.
Comment: @E.Coelho qual a entrada e saída que você espera?
Comment: Então, pelo que eu entendi, você precisa fazer um select que traga um resultado com base em uma alteração de uma outra tabela, no caso (bois_manejo), é isso? Consegue ser um pouco mais claro na sua dúvida? :)
Comment: @Sorack, como pode ver, estou tentando fazer com que a cláusula WHERE pegue todas as Foreng Keys que existem na tabela bois_manejo (com um DISTINCT) e me entregue todos os IDs que não constam em bois_manejo. No exemplo o único ID que não está na tabela bois_manejo é o 12.
Comment: @FilipeL.Constante fk_boi é uma Foreng Key relacionada ao ID da tabela boi. Eu preciso trazer só os IDs dos bois que não foram pesados/manejados ainda. :)
Comment: Tudo bem, eu entendi a estrutura da tabelam eu não entendi como eu sei que  eles foram ou não foram pesados/manejados ainda! hehe :)
Comment: @E.Coelho você tem a necessidade de utilizar obrigatoriamente o group_concat?? existe alguma problema em usar outras alternativas??
Comment: Bom dia, @Oliveira. Estou aberto a alternativas. Até o momento estou preso nessa. :)
Answer: A subquery retorna os registros que possuem relacionamento entre a tabela bois e bois_manejo pelo id e fk_bois respectivamente pelo INNER JOIN. Nesse cenário os registros que estão em bois mas não estão em bois_manejo não estarão no resultado da query e poderá comparar com o NOT IN, dessa forma o id 12 será apresentado.
SELECT * FROM bois WHERE id NOT IN(SELECT bois.id FROM bois INNER JOIN bois_manejo ON bois.id = bois_manejo.fk_boi)

Comment: Muito obrigado, @Oliveira. Eu não sabia que isso era possível. A cláusula IN lê os valores de uma espécie de array retornado, ou lê somente os números? Eu posso usar essa opção quando estiver lidando só com números? Outra coisa: esse modelo é mais eficiente em relação ao processamento?
Comment: @E.Coelho, nesse caso é comparado apenas pela coluna id da tabela bois, o IN permite verificar se o valor de uma coluna está presente em uma lista de elementos, mas vc pode comparar com outras colunas, no caso a alternativa o operador Exists https://pt.stackoverflow.com/questions/62925/not-in-ou-not-exists-qual-usar/63279
Comment: Show de bola, @Oliveira! Muito obrigado por compartilhar teu conhecimento e nos ajudar. Tudo de bom! (Ah... toma cuidado com o Obiwan - dissestes que és apenas um padawan - porque o cara mente pacas! hehehe)
Answer: Você pode fazer de maneira mais simples, e mais eficiente, utilizando a cláusula NOT EXISTS:
SELECT * FROM bois
WHERE NOT EXISTS (SELECT * FROM bois_manejo WHERE bois_manejo.fk_boi = bois.id);


Send tmux command from remote inside ssh session to local instance

Question: The goal is to send tmux command to the local running tmux from the remote server. not to run to different instances of tmux.
Inside tmux we ssh to a server that doesn't run tmux
local>tmux send-key C-p  # works
local>ssh user@remote
user@remote> tmux send-key C-p # this will try to find tmux instance on remote. but we want to send it the local instead.

I can't use keybinding because this will run from inside script.
Comment: OpenSSH 6.7 and newer has UNIX domain socket forwarding.
Comment: tmux communicates with the shell via unix socket, so you can't send that key within that remote shell session, unless you ssh back to local ->
Comment: Are you running OpenSSH 6.7 or newer?
Comment: 6.6 I can update if that solve the problem
Answer: No Linux Distro or version was specified so this answer assumes a relatively new version of SSH.
If the tmux "default" socket is being used on the local host but not on the remote host, tmux should just work by forwarding the unix socket from the remote host:
ssh -R/tmp/tmux-$UID/default:/tmp/tmux-${REMOTE_UID}/default remote

REMOTE_UID should be set manually to the UID of the remote user but UID is usually set automatically in the environment.
Ideally, a unique (non-default) tmux socket name should be chosen to avoid conflicts:
local> tmux -L foo
remote> ssh -R/tmp/tmux-$UID/foo:/tmp/tmux-${REMOTE_UID}/foo remote
remote> tmux -L foo send-key C-p

Playing around with TMUX_TMPDIR environment might give a more transparent and polished experience and work around having to know the UID but that depends on the requirement and might be overkill for just a script.
Comment: @Devenv: https://github.com/tmux/tmux/issues/462 is related to a socket over a shared directory.  The story is different for SSH forwarded Unix sockets since SSH works as a "proxy" and just forwards requests which should work in most cases (unless MSG_OOB or some other system-specific OOB functionality is required.)
Comment: Are you sure this works? I've read that you can't connect tmux sockets...
Comment: It works on my systems (Devuan ASCII, CentOS 7).  What do you mean by "you can't connect tmux sockets"?  Why not try it and leave some useful feedback?
Comment: https://github.com/tmux/tmux/issues/462
Comment: Also, rudeness is not appreaciated in this community, I just asked if you are sure (read: tried it or is it a guess), "It works on my systems" would be enough... I don't currently have access to any machine to check, once I do I'll leave feedback.
Comment: @Devenv: No one is rude here.
Comment: @Devenv: Not trying to be rude.  I'm sorry if you interpreted that way.  Was just asking you to just try it if in doubt and submit your findings which would have either supported or contradicted mine.  That would be more useful to the op.
Comment: Yepm works, thanks you. Doesn't help my issue directly (unrelated to OP question), but I can work something out of it :)


Exibir avisos com PHP

Question: Estou fazendo uns scripts para uma loja e desejo ajudar com alertas, ou melhor, mensagens que serão exibidas após processamento dos formulários. Quero algo mais do tipo atual, seria possível em PHP? Alguém ajuda?
header("location:" . $_SERVER["HTTP_REFERER"]);
-> O AVISO/MENSAGEM SERIA AQUI <-
exit;

Comment: Já pensou em usar JavaScript?
Comment: Podes enviar o formulário em ajax e receber o retorno por json informando uma mensagem, isso também é javascript.
Comment: hoje ao me cadastrar aqui no site ele mostrou uma aviso no topo, uma barra laranja com uma frase: Conclua o registro para sua conta (X), isso me ajudaria.
Answer: Tipo Atual... Jquery plugin gritter, muito prático:
Veja aqui
E aqui
Chama o plugin assim:

'

Depois usa assim:
$.gritter.add( { title: 'Atenção!', text: 'Erro ao executar tarefa no servidor!', time: 7000, class_name: 'gritter-light', image: '/img/erro.png', });

Comment: @Aragão votos negativos são feitos por diferentes usuários, cada uma das pessoas que negativou pode ter tido um motivo diferente, posso lhe dar umas dicas? O motivo da maioria ter negativado (estes votos não foram arbitrários) Independente do seu código está certo no funcionamento dele, o correto seria explicar o uso do redirecionamento combinado ao um `alert`, o que você fez foi apenas dar uma alternativa ao `alert`, outra coisa, não somos um fórum, o StackOverflow é uma plataforma de Q&A, pergunta e resposta, então geralmente a resposta tem ser ao problema que o autor está enfrentando...
Comment: ... Que no caso é um problema de trabalhar códigos backend com frontend. Eu acho que este é o motivo de tantos votos negativos, é normal acontecer este tipo de coisa, os votos negativos não são malignos eles apenas expressam opiniões. Espero que entenda a plataforma da comunidade e talvez refaça a sua resposta (se bem que não recomendo, pois esta pergunta é uma clara duplicata de http://pt.stackoverflow.com/q/54345/3635 e por este motivo não vale muito a pena responder). Seja bem vindo @Aragão, participe, com o tempo irá entender o funcionamento do Q&A StackOverflow e ...
Comment: Embora este link possa responder à pergunta, é melhor incluir as partes essenciais da resposta aqui e fornecer o link para referência.  As respostas apenas por link podem ser invalidadas se a página com o link for alterada.
Comment: Clique no botão [edit] e coloque no corpo da sua resposta
Comment: Transpus seu comentário para o corpo da sua resposta, veja o que pode melhorar.
Comment: ... não vai conseguir usar outro tipo de comunidade
Comment: Estaa tentando fazer isso, mas como sou novo aqui não sabia direito como comentar com código, o comentario anterior ficou meio bagunçado, vou tentar novamente.
Comment: Só uma dúvida, não seria o caso de apenas fazer um `alert()` usando o JS mesmo?
Comment: Corrigi o código, por que perdi tantos pontos desse jeito? Não é só um alert, conforme a pergunta ele quer algo diferente!!
Comment: Na verdade eu não entendo muito das linguagens em questão, eu perguntei justamente para tentar entender. Eu acho que sobre os pontos perdidos é por talvez haver alguma confusão no entendimento da pergunta.
Comment: Se não entende das linguagens em questão, como afirmar que houve confusão? O que faltou pra mim foi conhecimento do uso da ferramenta do fórum e não do uso das linguagens e da resposta que foi corrida. Quem tira esses pontos de forma tão arbitrária assim?

Exibir avisos com PHP


Question safe withdraw/deposit using AspectJ

Question: I have question regarding making a bankAccount class implement safe withdraw/deposit function. So far it will print log when you make a withdraw or deposit to the bankAccount class. Anyway my question is how to implement the safety e.g. you cannot withdraw more money than what you have currently in your bankAccount. If I'm not allowed to implement that safety in the bankAccount class, and want to implement it to an AspectJ.
I have the following now. As can be seen the withdraw is done regardless if the if-statement is true or false. Therefore I had to in the else statement deposit back the amount of money, so it would not turn negative. Can this be done in some nicer way possibly?
pointcut checking(BankAccount ba, float x):
    call(* BankAccount.withdraw(..)) && target(ba) && args(x);

before(BankAccount b, float x) : checking(b, x) {
    if(b.getBalance() >= x) {
        System.out.println("Account changing. $" + x + " withdrawn...");

    } else {
        System.out.println("Account does not have. $" + x + " to withdrawn...");
        b.deposit(x);
    }

}

Answer: I'd say this would be better handled by an around advice, which can prevent proceeding to the normal invocation and substitute some other action instead if the transaction shouldn't be allowed.
The code for the around advice should be basically similar to what you wrote for before, except in the if block you'd have to call proceed to continue into the normal execution, and in the else block you'd no longer need the call to deposit.
Comment: So that's what around() is supposed to be used for. It is quite hard to understand when to use which advices, since there are no good documentation.


How to prove this inequality about a family of sets with certain property

Question: Let $A_1,\cdots,A_m\subset[n]$ be such that if $A_i\cap A_j=\emptyset$,then $A_i\cup A_j=[n]$.Prove that $m\leq2^{n-1}+\binom{n-1}{[\frac{n-2}{2}\,\,]}$.I already know that we can take a maximal family of intersecting sets,say $B_1,\cdots,B_k$(It is obvious that $k\leq2^{n-1}$).And because it is maximal,by using the condition ${A_i}$ satisfies,one obtain that $A_i$ is either $B_j$ or $B_j^{\,c}$ for some $j$.Thus we can denote $A_1\cdots A_m$ as $B_1\cdots B_k,B_1^c,\cdots,B_s^c$.Note that $B_1^c,\cdots,B_s^c,B_1,\cdots,B_s$ is an anti-chain,by Sperner's Lemma we have$2s\leq\binom{n}{[\frac{n}{2}]}$.Thus we get a inequality which is closed to the inequality we want to porve.But I don't know what to do after this.
Comment: There was a typo that I wrote some $m$ as $n$.Now it is corrected.Thank you for pointing it out @kodlu.
Answer: I've now figured out how to prove it.Ant this is a brief answer.
We can use such a theorem:
Theorem(Bollobas):If $C_1,\cdots,C_m $ is an intersecting antichain in $[n]$ such that $max{C_i}\leq\frac{n}{2}$,then
$\sum_{i=1}^m\frac{1}{\binom{n-1}{|A_i|-1\,\,\,}}\leq1$.
The proof of the theorem is given by considering cyclic permutations,quite similar to the proof of Erdos-Ko-Rado theorem.
We can use this theorem to prove the desired inequality.By swapping some $B_i$ and $B_i^c$,we can assume $max\{|B_1|,\cdots,|B_s|\}\leq\frac{n}{2}$.By applying the theorem we obtain the desired inequality


Reopening "Customers by orders Total Only Shows 5"

Question: I voted to reopen the below question. Here's my reasoning:

It is regarding the Magento admin panel reports
It asks why a report behaves a certain way
It can have a single, canonical answer

Because of the above I feel that it fits well into the format of this site. If it were asked why the developers chose to make it work a certain way it would be off-topic, the question is asking how to extend the report. I will attempt to answer myself.
In the meantime any thoughts from the community on why this may or may not belong?
Customers by Orders Total only shows 5
Answer: I still feel it as an off-topic, since it is not clear for me.
The depicted behaviour may cause due to customization in the site. No hint about any customization that done to the site. Without seeing the code, I suspect it will be difficult to help him out. Again this is my personal opinion.
If the question is clear for you, then we are waiting for your answer so that you can clearly justify your act.
Thanks phil
Edit
I would also like to mention that, I had such situations before. Questions which were closed as off-topic seems relevant and clear for me. In those cases, I immediately contacted moderators and let them know about that. In most of the cases, moderators will immediately open the question for us, if we let them know that we really want to answer that question.
It is good to see that, being a moderator you came forward to discuss a question that you have opened with proper reasoning. You can do that without having a prior notice to anyone. Much appreciated. Kudos.
But we are expecting an answer from your part, so that the thread in this question no longer remain un-answered (I think a re-opened question will not come on the top of Magento recent activity page. So there is no-way to follow this change !!).
Comment: This is a built in report and it does, indeed, only show the top five sorted by revenue descending. Editing this behavior is a bit tricky and may help some understand Magento deeper. Therefore the purpose and tone of this is very clear to me.
Comment: The answer is now live on the question.
Comment: @philwinkle  please see the edit.
Answer: I have opened another question in response to this one which I feel better represents what happened here - pileon close votes.
Please lend your feedback over here:
Let's review our guidelines for "off topic"


kernel virtual address translation

Question: Considering Linux and 32 bit x86 arch there is 3:1 divide of the accessible 4GB address space. The user space is allocated 0-3 Gb while 3-4 Gb is allocated to kernel.
How does a virtual address that is greater than 3Gb and hence lies into the kernel address space is transformed to the physical address? Does page tables would come into picture?
Answer: There is some information in Mel Gorman's book Understanding the Linux Virtual Memory Manager.
The short answer: Yes, the kernel sets up page tables to translate physical address 0 to virtual address 3 GiB.  (Section 3.7.1).  This includes the physical location the kernel was loaded to (usually 1MB on x86).
Comment: That simple mapping makes the implementation of virt_to_phys() easy: as you said, just subtract PAGE_OFFSET.  But paging is enabled-- this allows the translation of virtual addresses to physical in hardware, as instructions are fetched and data is accessed.
Comment: Thanks for the answer. After doing some googling I found that there is a #define PAGE_OFFSET which is 3GB ( configurable ) and the kernel virtual address has one to one mapping to physical address obtained by simply subtracting PAGE_OFFSET from kernel virtual address and hence no use of page tables. please correct me if I am wrong.
Comment: I got your point. Page tables are always used when paging is enabled regardless the virtual address belongs to kernel or user space. (Alas!!! I cant vote up as it requires minimum of 15 points)
Comment: My 0.2: one might wonder- if we use paging in the kernel won't it slow things down? Yes but this is mitigated in a modern OS like Linux by: (a) pinning down kernel mapping TLB entries, (b) modern processors have large-ish TLBs, and (c) using large/huge pages for the kernel mappings (Transparent Huge Pages?).

kernel virtual address translation


Multivariable Calculus: Evaluating a Line Integral Using Green's Theorem With Single Differentiable

Question: here's a question I'm working on.
We have this integral over a region and we wish to use Green's Theorem to evaluate it.
$\int_D x\ln(y) dx$
$D:1\leq x \leq 2, e^x \leq y \leq e^{x^2}$
Here's how I set it up, I'm not sure if I'm correct at setting it up, but if I am, then I may have made an arithmetic mistake somewhere. The answer given is $\frac{-17}{12}$
$\int_D x\ln(y)dx + 0dy$
Where I take $x\ln(y)$ as $P$ and $0$ as $Q$.
Is this correct?
Comment: so far so good.
Answer: As per comments, your start was correct.
Spoiler alert -- complete solution below!
I'm not sure of the $P$ and $Q$ in your notation, so I'll use notation I'm familiar with and let you join the dots. Write Green's theorem for the vector field $\mathbf{F}(x,y) = F_1(x,y)~\mathbf{i}+F_2(x,y)~\mathbf{j}$ as:
$$\oint_C\mathbf{F}\cdot d\mathbf{r} = \oint_CF_1~dx+F_2~dy=\iint_R\left(\dfrac{\partial F_2}{\partial x}-\dfrac{\partial F_1}{\partial y}\right)~dx~dy$$
where $R$ is the region enclosed by the curve $C$.
You have a region $D: 1\le x\le2,e^x\le y\le e^{x^2}$. Writing $C$ as the boundary,
$$\begin{eqnarray}
\oint_Cx\ln(y)~dx&=&\oint_Cx\ln(y)~dx+0~dy\\
&=&\int_D\left(\dfrac{\partial}{\partial x} 0 - \dfrac{\partial}{\partial y}x\ln(y)\right)~dx~dy\\
&=&\int_1^2\!\!\int_{e^x}^{e^{x^2}}0- \dfrac x y~dy~dx\\
&=&\int_1^2\left[x\ln(y)\strut\right]_{y=e^x}^{e^{x^2}}~dx\\
&=&\int_1^2x(x^2)-x(x)~dx\\
&=&\left[\dfrac14x^4-\dfrac13x^3\right]_1^2 = (4-\dfrac83)-(\dfrac14-\dfrac13)=\dfrac{48-32-3+4}{12}=\dfrac{17}{12}
\end{eqnarray}$$


Calling function inside if condition is synchronous or asynchronous?

Question: i have a method :
function checkNestedfield(obj /*, level1, level2, ... levelN*/ ) {
  var args = Array.prototype.slice.call(arguments, 1);

  for (var i = 0; i < args.length; i++) {
    if (!obj || !obj.hasOwnProperty(args[i])) {
      return false;
    }
    obj = obj[args[i]];
  }
  return true;
}

while calling inside if condition getting me correct result but how should i know whether it will execute correctly every time.
So calling function inside if condition is async or sync process?
for eg:
if (checkNestedfield(someObj, 'stringValue')) {
  console.log('true')
} else {
  console.log('false')
}

Comment: Welcome to SO! I'm a bit confused: what about this code suggests that it wouldn't be entirely synchronous? What is the code supposed to accomplish and how are you defining "correctness" here?
Comment: It's synchronous and will be called every time, otherwise it won't know whether to execute the *else* block or not.
Comment: some people actually mix up what synchronous and asynchronous code is
Answer: You could use a try/catch logic in order to 'catch' if the function return some error or not, as show next:
let nestedField = false;

function checkNestedfield(obj /*, level1, level2, ... levelN*/ ) {
  let args = Array.prototype.slice.call(arguments, 1);

  for (let i = 0; i < args.length; i++) {
    if (!obj || !obj.hasOwnProperty(args[i])) {
      throw "myException"; // Give control to the 'catch' sentence
    }
    obj = obj[args[i]];
  }
  return true;
}

try (
  checkNestedfield(someObj, 'stringValue');
) catch (e) {
  console.log('Log the error here');
}

This way if your checkNestedfield function fails, you could handle the error in whatever way you want. This behavior es always synchronous and will be called every time.
Hope this helps.


How to begin combinatorial proof of $\sum_{k=1}^n k \binom nk^2 = n \binom{2n-1}{n-1}$

Question: The question states to give a combinatorial proof for:
$$\sum_{k=1}^{n}k{n \choose k}^2 = n{{2n-1}\choose{n-1}}$$
Honestly, I have no idea how to begin. I want to do a two-way counting proof, looking at the LHS and the RHS correct? Any help would be greatly appreciated.
Comment: @nikita2: "Combinatorial proof" means no induction.
Comment: Did you try induction?
Comment: See also:
[A combinatorial proof of the identity: $\sum_{k=1}^n k \binom{n}{k}^2 = {n}\binom{2n-1}{n-1}$?](https://math.stackexchange.com/q/2561029) and
[Combination proof $\sum_{k=1}^nk\binom{n}{k}^2=n\binom{2n-1}{n-1}$](https://math.stackexchange.com/q/685308)
Answer: We have a group of $2n$ people, $n$ female and $n$ male.  We want to select a committee of $n$ people, including a female Chair.
We can select the Chair first. There are $n$ ways to do this. For each of these ways, there are $\binom{2n-1}{n-1}$ ways to choose the rest of the committee. Thus there are $n\binom{2n-1}{n-1}$ ways to choose a committee with female Chair.
We now count the number of committees with female Chair in a different way. The committee will have a total of $k$ females, where $k$ ranges from $1$ to $n$, and $n-k$ males.
We can select $k$ females and $n-k$ males in $\binom{n}{k}\binom{n}{n-k}$ ways. For each of these ways, the Chair can be chosen from the $k$ females in $k$ ways. Thus there are $k\binom{n}{k}\binom{n}{n-k}$ ways to make a committee with $k$ females, including a female Chair, and $n-k$ males.
Finally, note that $\binom{n}{n-k}=\binom{n}{k}$, and sum over all $k$ from $1$ to $n$. The number of committees with female Chair is $\sum_{k=1}^n k\binom{n}{k}^2$.
Comment: @alexthebake:  Because we are making a committee of $n$ people. If we have $k$ females, we must have $n-k$ males.
Comment: Can you briefly describe how you thought this story up? I'm simply curious.
Comment: Why is it $n-k$ males instead of $2n - k$ males?
Comment: @alexthebake: You are trying to select $n$ people in total, so since there already $k$ females, there must be $n-k$ males.


Does convergence in every $L^p$ imply convergence in $L^\infty$?

Question: Consider a sequence of functions $(f_n)$ on a probability space $(X,\mu)$ such that
(i) $f_n \to f$ in $L^p$ for every $p\in [1,\infty)$
(ii) $f,f_1,f_2,\cdots\in L^\infty$ and they are uniformly bounded in $L^\infty$ by $\Lambda\in [0,\infty)$, i.e.
$$\|f\|_\infty,\|f_1\|_\infty,\|f_2\|_\infty,\cdots\le \Lambda.$$
Does then $f_n\to f$ in $L^\infty$?
Answer: Let $t(x) = \max(0, 1-|x|)$, let
$f_n(x) = t(nx+n)$. Then $f_n \to 0$ for $p < \infty$ but $\|f_n\|_\infty = 1$ for all $n$.
Comment: Is the $+n$ necessary? If one uses [this](https://math.stackexchange.com/questions/51502/if-f-k-to-f-a-e-and-the-lp-norms-converge-then-f-k-to-f-in-lp) I think one can get away with $f_n(x)=t(nx)$.
Comment: @0ßelö7: It is not necessary but the pointwise convergence is everywhere instead of ae.
Comment: Yeah, that's fine. Thanks.


Executescalar query code issue

Question: Im trying to return the member id in this query below. If i run the query as just as a query i get 20 but when i exectute the code it returns a zero. What am i doing wrong here?
public int GetMemberID(string guid)
   {
       string strConectionString = ConfigurationManager.AppSettings["DataBaseConnection"];
       string StrSql = "SELECT MemberID FROM MEMBERS WHERE (Guid = @GuidID)";

       int memberId;
       using (var connection = new SqlConnection(strConectionString))
       using (var command = new SqlCommand(StrSql, connection))
       {
           command.Parameters.Add("@GuidID", SqlDbType.Int).Value = guid;
           memberId = (int)command.ExecuteScalar();
       }

       return memberId;

   }

Comment: http://stackoverflow.com/faq#howtoask -- read the end of the section.
Answer: The guid variable is not an int.
command.Parameters.Add("@GuidID", SqlDbType.VarChar).Value = guid;

Answer: Your paramter @GuidID is an Int type?
Make sure it is right.

Executescalar query code issue


How to use cache set and get to store time cron ran?

Question: We have a new requirement where we need to run a job on a daily basis. We have setup cron to run every 1 hour. The goal is to have cron ron every 1 hour, but we want a specific job to run only if 1 day (24hours) has past since last run.
We used to use the Variables table to store the time the job was last run, but we need to change this to use the cache table. Below is the code (mymodule.module) we were reviewing, but it is not creating a cache table and not storing the appropriate date. So we need assistance in figuring out if we are using the correct logic so the job runs once everyday.
Note: $cache->data below is actually the last time the job ran.
mymodule_cron() {
     $data = '';
     if($cache = cache_get('last-run')) {
         $data = $cache->data;
         if($data <= strtotime('-1 day')) {
               //call helper function to perform some logic
               _some_func();
               $data = time();

               //set update date in cache
               cache_set('last-run', $data, 'cache'));
         }
    }
 }

Answer: I don't think there is something wrong on cache_get() and cache_set(). It seems a logic problem. In your code the cache is never set if a cache is not found.
/**
 * Implements hook_cron().
 */
function mymodule_cron() {
  $data = '';

  if ($cache = cache_get('last-run')) {
    $data = $cache->data;
    if($data <= strtotime('-1 day')) {
      //call helper function to perform some logic
      _some_func();
      //set update date in cache
      cache_set('last-run', time(), 'cache'));
    }
  }
  else {
    // set cache if there is no cache.
    cache_set('last-run', time(), 'cache'));
  }
}

Answer: I would suggest storing this sensitive data to Drupal variables instead of cache because cache can be wiped by arbitrary code (which probably happens in your case).
Instead of cache_get and cache_set use variable_get and variable_set accordingly.
Comment: @JimmyKo so i just need to store the time the job last ran and would prefer not to create a variable in the variable table for this. We are okay with the data being cleaned after cache clear. Considering that i still need some help with the code provided above to make sure it is the correct code.
Comment: Yes we have the logic for the variable, but we found that the variable table has gotten very big so we thought the cache route would be good. The way the helper function runs is that it will update data only when there is a certain criteria met. It will not hurt us if the data is wiped so we still need assistance in figuring out how to get it store correctly in cache.
Comment: @sf_admin819 instead of variables get/set you. Many contrib modules are using a separate table to store their settings. But if you only have only less then 5 values, please don't feel hesitate to use variable table.
Comment: @sf_admin819 I posted in answer. Please check.
Comment: @JimmyKo yes that seemed to work! i was missing that portion to create it if it wasn't there.


JVM languages for J2ME platform

Question: I'm currently writing an embedded application for J2ME environment (CLDC 1.1 configuration and IMP-NG profile). Being spoiled by all those new features in JVM-based languages (Groovy, Scala, Clojure, you name it), I was considering using one of them for my code.
However, most of the mentioned languages require pretty decent JVM environment. Most so-called "dynamic" languages require the VM to have reflection. Many ask for annotations support. None of the above features are available under J2ME.
From what I found, Xtend looks like a viable options, as its compiler spits out plain Java, not bytecode, and doesn't require any library for runtime needs. Of course, the generated Java code also must meet some requirements, but Xtend webpage looks promising in this regard:

Xtend just does classes and nothing else
Interface definitions in Java are already nice and concise. They have a decent default visibility and also in other areas there is very little to improve. Given all the knowledge and the great tools being able to handle these files there is no reason to define them in a different way. The same applies for enums and annotation types.
That's why Xtend can do classes only and relies on interfaces, annotations and enums being defined in Java. Xtend is really not meant to replace Java but to modernize it.

Am I right and it is possible to compile Xtend-generated code for J2ME platform, or there are some constructs that will not work there?
Alternatively, can you recommend any other "rich" Java modification language that can be run on J2ME?
Update: Knowing that the "compiler" producing results as another source code is called transcompiler, one can also find Mirah, a tool which requires no runtime library and specific Java features.
Answer: Xtend's generated code uses google guava heavily. If that is compatible to the J2ME, Xtend could be the language of your choice. I'm not aware of anything that prevents from using it on other platforms that provide a dedicated development kit (e.g. Android).
Comment: Well, then it could be a problem... Guava advertises itself as "Google Core Libraries for Java 1.6+" :(
Answer: In addition to being able to generate Java source, Mirah recently added support for javac's --bootclasspath option, which allows you to generate your bytecode against a non-standard version of the java core classes, e.g. LeJOS.
It's still a little fresh, but it'd be nice to have more people using it on different javas.

JVM languages for J2ME platform


How do you play this part?

Question: There's a capo on 4 but I'm still having trouble playing this part:
Comment: I think there's some mistake or incorrect tabbing...
Comment: This is non-sense. Note that the two lowest notes are identical, so you can leave out the note on the low E string and just play the two perfect fifths on A, d, and g. Where's that tab from?
Comment: It's impossible unless you are a freak of nature and have fingers as long as your arms.
Comment: What exactly are you having difficulty with, the stretch?  Do you have smaller hands?
Comment: I think more context is needed for a useful answer. What music is this?  Where can we look at the full score? Clearly, as others have stated, there is something wrong with this example.
Answer: Both the fretted 6th fret on the E String, and the fretted note at the 1st fret are exactly the same, therefore just don't play that note, unless you have an eight inch long little finger.
Answer: AS E & A not strummed put capo on 5

How do you play this part?


Question about the limit of a sequence.

Question: I am stuck on the following problem to find the limit of the sequence $a_n=\frac{(n!)^2 \cdot (2n)!}{(4n)!}$. I show $\lim_{n \rightarrow \infty} |\frac{a_{n+1}}{a_n}| < 1$, thus $a_n \rightarrow 0$. However, I would like to figure out a more algebraic way of doing this, although I am stuck on how to simplify this expression. Could someone offer a hint on how to get started, not a full solution please.
Thank you.
Comment: Hint: [Stirling's approximation](https://en.m.wikipedia.org/wiki/Stirling%27s_approximation) should help you get rid of those factorials and get more convenient expressions.
Comment: (Note: it is an approximation, but for large n it is a tight approximation; the relative error is negligible. So it will give you exact results regarding the asymptotic scaling of a_n, even if it is an "approximation".)
Answer: At the request of the OP, we present herein a purely algebraic way forward.
HINT:
Let $a_n=\frac{(n!)^2\,(2n)!}{(4n)!}$.  Then, we can write
$$\begin{align}\log(a_n)&=2\log(n!)+\log((2n)!)-\log((4n)!)\\\\&=2\sum_{k=1}^n\log(k) +\sum_{k=1}^{2n}\log(k)-\sum_{k=1}^{4n}\log(k)\\\\&=2\sum_{k=1}^n\log(k)-\sum_{2n+1}^{4n}\log(k)\end{align}$$
SPOLIER ALERT:  Scroll Over the Highlighted Area to Reveal the Full Solution

\begin{align}\log(a_n)&=2\log(n!)+\log((2n)!)-\log((4n)!)\\\\&=2\sum_{k=1}^n\log(k) +\sum_{k=1}^{2n}\log(k)-\sum_{k=1}^{4n}\log(k)\\\\&=2\sum_{k=1}^n\log(k)-\sum_{2n+1}^{4n}\log(k)\\\\&=2\sum_{k=1}^n\log(k)-\sum_{k=1}^{2n}\log(k+2n)\\\\&\le 2n\log(n)-2n\log(2n+1)\\\\&=-2n\log\left(2+\frac1n\right)\\\\&<-2n\end{align}Inasmuch as $\lim_{n\to \infty}e^{-2n}=0$, we find that $$\lim_{n\to \infty}a_n=0$$
Comment: Thank you for your solution, this clears my question up and also gives me "tricks" for solving such problems in the future +1, and accepted answer.
Comment: You're welcome Joseph!  My pleasure.  And thank you for accepting the answer.  -Mark
Answer: Start with this and simplify
$$
\frac{a_{n+1}}{a_n}
=
\frac{((n+1)!)^2 \cdot (2(n+1))!}{(4(n+1))!}
\cdot
\frac{(4n)!}{(n!)^2 \cdot (2n)!}\\
=
\frac{((n+1)n!)^2 \cdot (2n+2)(2n+1)(2n)!}{(4n+4)(4n+3)(4n+2)(4n+1)(4n)!}
\cdot
\frac{(4n)!}{(n!)^2 \cdot (2n)!}
$$
Comment: @Ihf yes, my mistake I fixed it. $\frac{a_{n+1}}{a_n}=\frac{n^2+2n+1}{64n^2+64n+12} \rightarrow \frac{1}{64}$ as $n \rightarrow \infty$. I used this fact to show $L < 1 \rightarrow a_n \rightarrow 0$
Comment: @Joseph, exactly!

Question about the limit of a sequence.


Problema ao Tratar uma lista de Objetos na jsp

Question: Estou tento problemas para tratar uma lista que vem do meu controller em minha jsp
acredito não estar usando a forma correta para tratar e percorrer essa lista
segue meu controller que cria a lista.
@RequestMapping(value = "/show/{id}", method = RequestMethod.GET)
public ModelAndView viewPesquisar(@PathVariable("id") Long id, ModelMap model, HttpServletRequest request) {

    LOGGER.debug(" O id a ser consultado é {}", id);

    List<Ito> optional = itoService.findByIdFetchAll(id);

    if (optional.isEmpty()) {

        LOGGER.debug(" Não foi possivel localizar o Tipo com o Id:{}", id);

        throw new BusinessException("Não foi possivel Localizar o Tipo de Projeto");
    }

    List<Ito> listaCompletaNomeItos = itoService.findByIdFetchAll(id);

    model.addAttribute("listaCompletaNomeItos", listaCompletaNomeItos);

e a jsp onde devo tratar a lista.

Comment: E o que é que acontece? E o que é que você espera? Especifique seu problema, por gentileza.
Comment: entao quando eu tento subir dessa forma a lista não vai ate o meu view
Comment: eu preciso dessa lista para poder criar um elemento dentro da view que tenha o nome e o id desse mesmo objeto
Comment: consegue debugar esse js ou visualizar o resultado de: listaNomeItos?
Comment: consigo debugar o js porem o resultado da lista e vazio por que parece que a informação não subui entende
Comment: E quando tu depura isso: model.addAttribute("listaCompletaNomeItos", listaCompletaNomeItos) tem resultado a variavel?
Comment: ate ai a informação chega o problema esta dai para cima
Answer: Vejo que no controller sua lista recebe os objetos mas no jsp ela chega vazia.
Verifica se estás chamando a taglib do jstl no jsp.
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Se o jsp estiver sem ela a página não saberá ler a variável que vem do controller.
Comment: então João a tenho essa e outras taglibs na pagina sim amigo mesmo assim o erro continua.
Answer: Bom pessoal agradeço a ajuda mais consegui resolver utilizando o forEach muito obrigado


Reset windows 7 local admin password on encrypted drive

Question: I have lost administrator password on a windows 7 laptop running bitlocker.
I know bitlocker recovery password for this PC and can access BIOS setup.
I need to reset administrator password without removing HDD from the laptop.

Is there a way to do so without having to decrypt the drive first ?
If not, how can I decrypt the drive given the fact that I cannot login as admin to the machine ?

I am considering to boot Linux on a USB drive and run a copy of Windows 7 from Linux via Virtual box. Then try to decrypt laptop HDD from this copy of Windows 7.
I hope there is an easier way... If not, please tell me if you think this idea will fail or not.
Thank you :-)
Answer: You can use a WinPE USB stick to boot but it must include the winpe-vmi package:
To create an image that can decrypt your first computer you'll need another computer with WAIK installed.
1.1 How to create a WinPE image that suits your needs: http://technet.microsoft.com/en-us/library/dd744533(v=ws.10).aspx
1.2 You should include the winpe-wmi package when adding packages.
Dism /image:C:\winpe_x86\mount /Add-Package /PackagePath:"C:\Program Files\<version>\Tools\PETools\<architecture>\WinPE_FPs\winpe-wmi.cab"

Dism /image:C:\winpe_x86\mount /Add-Package /PackagePath:"C:\Program Files\<version>\Tools\PETools\<architecture>\WinPE_FPs\en-us\winpe-wmi_en-us.cab"

You'll need both: the language neutral and the language specific (en-us) package. version can be Windows OPK or Windows AIK (WAIK).
1.3 Boot your first computer (the one where the password is lost) with WinPE and execute the following command:
cscript %systemroot%\system32\manage-bde.wsf –unlock Volume : -rk PathToExternalKeyFile: \ External Key File Name

If the Recovery Key is damaged or missing, you can still unlock the volume. To do this, type the following command at the command prompt:
cscript %systemroot%\system32\manage-bde.wsf –unlock Volume : -rp Numeric Recovery Password

source:
http://social.technet.microsoft.com/Forums/en-US/w7itprosecurity/thread/984ca855-43ae-487c-ae6e-edd955b5d956/


Create a permanent list of a content type

Question: I have a content type named "clients" which can be filtered within a view and all can be selected using bulk operations.
What I would like to do is take the filtered list in the view and copy it to a permanent list of content on my site. So that it is saved and can be accessed at a later date without having to go through the filter options again.
For example, to store a list of clients all from one country, say Germany, to a list of these clients named Germany.
Any ideas how I would do this?
Answer: Views Save module can help you. The module page says

This projects allows admins to add a "Save" button to their views (on
  a per-view basis). This button allows logged-in visitors to save their
  current exposed filter settings on the site, so they can later return
  to the same page. The saved views are stored per user, and can be
  listed with Views themselves, to provide users with an overview of all
  their saved views. Saved views can also be overwritten with new
  settings.
Anonymous users are offered a way to log in or register when trying to
  save a view – if they do, the view is saved to their (possibly new)
  account, otherwise it is purged after a while.


Calculate update frequency in R data

Question: I have several clients sending data to a server, on the server we have a log that tracks client id and sending time like this
ClientID, Time
"client_1",1548736876
"client_2",1548736800
"client_1",1548737070
"client_1",1548737249
"client_2",1548738902
...

I would like to calculate the average update interval for all clients
for client_1: ((1548737249-1548737070) + (1548737070 - 1548736876))/2
for client_2: (1548738902-1548736800)
avg = (client_1 + client_2)/2
How it can be done in R?
Comment: @NelsonGon, the final result is just avg. time, not a table
Comment: Could you add a table showing your expected output?
Answer: You can use data table like this
ClientID <- c("client_1", "client_2", "client_1", "client_1", "client_2")
Time <- c(1548736876, 1548736800, 1548737070, 1548737249, 1548738902)
df <- data.table(ClientID = ClientID, Time = Time)
df

   ClientID       Time
1: client_1 1548736876
2: client_2 1548736800
3: client_1 1548737070
4: client_1 1548737249
5: client_2 1548738902

Calculate Difference of time per client ID
diffdf <- df[, .(difftime = diff(Time)), .(ClientID)]
diffdf

   ClientID difftime
1: client_1      194
2: client_1      179
3: client_2     2102

Calculate Avg of time per client ID
Avgdf <- diffdf[,.(Avg = mean(difftime)), .(ClientID)]
Avgdf

   ClientID    Avg
1: client_1  186.5
2: client_2 2102.0

Calculate Final Avg
TotalAvg = mean(Avgdf$Avg)
TotalAvg
1144.25

Comment: @vinh can you please accept my answer if it solved your problem

Calculate update frequency in R data


Insert a value of 1 on users table that is referencing admin table hibernate

Question: I am trying to save a value of 1 on users table that is referencing an admin table with a foreign key of adminId on the users table
In my User.java I have this
@OneToOne
    @JoinColumn(name = "adminId")
    Admin admin;

this is the getter and setter for the above mapping to the user.java referencing the admin table
public Admin getAdmins() {
        return admin;
    }

    public void setAdmin(Admin id) {

        this.admin = id;
    }

In my DAO class of SpringBoot application, I am persisting to the users table like this
public void save(User user) {
         Admin admin = (Admin)getSession().createQuery("from Admin a where a.adminId = ?")
                .setParameter(0, 1);
                user.setAdmin(admin);

        getSession().save(user);
    }

EDITTED:
this is how I am trying to save a user
public void save(User user) {
      long id = 1 ;

        Admin admin = (Admin)getSession().createQuery("from Admin a where a.adminId = ?").setParameter(0, 1).list().get(0);
        user.setAdminz(admin);

        getSession().save(user);
    }

this is my controller code for saving action
@RequestMapping(value = "/create-user", method = RequestMethod.POST)
    public ModelAndView createUser(HttpServletRequest request,
                                   HttpServletResponse response,
                                   @RequestParam String name,
                                   @RequestParam String email) {
        try {
            // create new user object
            User user = new User();
            user.setName(name);
            user.setEmail(email);
            user.setTimestamp(new Date().getTime());

            // save user in db (if new)
            if (_userDao.getByEmail(email) == null) {
                _userDao.save(user);
            }

when I try to save I get this error
com.xxx.MainController       [0;39m [2m:[0;39m Exception in creating user:

I have modified my mapping to this not to accept nullable
@OneToOne
    @JoinColumn(name = "adminId",nullable = false)
    Admin admin;

If I remove nullable = false annotation, NULL value is saved into the adminId field of the user table.
Please what am I doing wrong? Kindly assist.
Answer: You have to execute your query
Admin admin = (Admin)getSession().createQuery("from Admin a where a.adminId = ?").setParameter(0, 1);

Your IDE should warn you about this line because you cant cast Hibernate Query to your Admin type as long as if you didn't implement it to your Admin class, if you did that, that is so wrong...
This code is not best practice for getting single element but you have to execute your query with list() method. and get your element from list.
Admin admin = (Admin)getSession().createQuery("from Admin a where a.adminId = ?").setParameter(0, 1).list().get(0)
//Warning! If list is empty, there will be an error.

If you want to pick single element from db with using hibernate(and map with an entity) i recommend you to use this code.
Admin admin = getSession().get(Admin.class, 1);

Comment: The method getCurrentSession() is undefined for the type UserDao >>>> this is error I am getting now
Comment: ok. I am doing this Admin admin = (Admin)getSession().get(Admin.class, 1);
Comment: MainController   Exception in creating user  >>>>> do I show my controller code for save


Comparing Different Types of Survival Models

Question: Suppose there is a system in which individuals are measured only at discrete time points (e.g. blood pressure is measured once every year) and these individuals have the ability to transition between multiple states (e.g. disease free, disease stage 1, disease stage 2, death by disease of interest , death by comorbidity, lost to follow up  etc.) until one of the absorbing states is reached or the period of study is over. The goal of the analysis is to understand what how different cohorts of patients and patient characteristics contribute to the transitions between these states.
I am trying to understand what types of Survival Models are generally used for this type of problem.
At first I thought that perhaps the competing risk model might be suitable seeing as there are "competing absorption states" (e.g. death by disease of interest vs death by comorbidity) - but I am not sure if a multistate/multistate-survival model is better suited for these types of problems.
Another approach that I have been considering is using several multinomial logistic regression. For example, if there are "n" states and "k" absorbing states  (i.e. "n - k" non-absorbing states):

Isolate all rows of data in "state 1" and create a multinomial logistic regression model where the outcomes are "state 1, state 2, state 3... state n"
Repeat this process and create "n - k" multinomial logistic regression models

Thus, as a recap:

Approach 1: Discrete Competing Risks Model
Approach 2: Discrete Multistate Survival Model
Approach 3: Multinomial Logistic Regression

Can someone please comment which of these approaches (or perhaps some other approach) is generally used for these types of Discrete Time problems?
Thanks!
Answer: A multinomial regression at a single evaluation time for a multi-state survival problem has the same limitation that a single binomial regression has for single-event survival models: it doesn't nicely handle censored survival times prior to the single evaluation time. Treating "censored" (loss to follow up) as a separate state poses an interesting problem: if censoring can be predicted by the same covariates that are associated with outcome, then censoring is presumably informative and the standard assumption of non-informative censoring in survival analysis doesn't hold. You would have to do more extensive modeling.
I don't see that separate single multinomial regressions based on each of the non-absorbing states, as suggested in the question, would be appropriate.
You can, however, analyze discrete-time survival data as a series of binomial, ordinal, or multinomial regressions at each of the observation times. The data need to be formatted properly, so that only those who are still at risk are included in the regression at an observation time. Censoring is then handled by the omission of individuals without an event time from regressions at times after the censoring time. Tutz and Schmid describe the rationale. The discSurv package in R provides tools for formatting data in a way that allows application of standard regression methods to discrete-time data.
Strict competing-risks models assume that all non-initial states are absorbing states. If you are modeling multiple disease stages or back-and-forth transitions among states, a competing-risks model won't work. Tutz and Schmid only seem to describe multinomial models for competing risks scenarios; I don't think that they cover back-and-forth transitions between states at all.
That leaves multi-state models, which can take several forms.* You might treat such a model as a series of multinomial models in time, as in the example you cite in a comment, but if back-and-forth transitions are allowed between states (unlike the unidirectional transitions in that example) that could become messy. You might as well use Markov-type transition models that are designed for such data.
The R "Multi-state models and competing risks" vignette is a good introduction. For panel data like you seem to have (same individuals followed over a set of discrete time periods), Section 6 of the vignette recommends the msm package. I don't regularly deal with discrete-time survival data and I don't have experience with that package, however, so I can't provide an informed opinion about its suitability.

*Even a simple standard survival model can be considered "multi-state" if you allow for two states (initial state and absorbing event state) to be called "multi." To that extent, some of this discussion is terminological rather than substantive.
Comment: @stats_noob a multinomial wouldn't handle back-and-forth transitions between states. You also need to make sure that the "Independence of Irrelevant Alternatives" assumption is met. See the [UCLA web page](https://stats.oarc.ucla.edu/r/dae/multinomial-logistic-regression/). I haven't used the `msm` package myself, but the vignette to which I linked suggests that it's a good choice.
Comment: @ EdM: thank you for your answer! If I dont have censoring in my data, the multinomial approach might be suitable?  The other question - if you have measurements at discrete times - is this msm package well suited?
Comment: @ EdM: Thank you for your reply! I am trying to understand your points
Comment: 1)  is it possible to test whether the "Independence of Irrelevant Alternatives" assumption is present in the data?
Comment: 2) why is a multinomial not able to handle back-and-forth transitions? I found this tutorial here which shows how to fit multinomial regression models to this kind of problem: https://hesim-dev.github.io/hesim/articles/mlogit.html . If I use "time spent in state" as a predictor variable - why would the multinomial  not be able to handle back-and-forth transitions?
Comment: 3) I have been reading about the msm package in R - it looks very comprehensive and well documented ... the only thing I am not sure about if this package is able to handle "discrete survival times". did you have an opinion on this? If I have discrete survival times, should I just go ahead and "assume" they are continuous?
Comment: 4) Have you heard about the Discrete Survival package in R : https://cran.r-project.org/web/packages/discSurv/discSurv.pdf ? I am trying to evaluate if this package is a good fit for the problem I am working on ... I am not sure if this package is able to handle multi-states or if its just the classical survival set up. Something is provided about "multispell" ... but I am not sure yet what this means
Comment: one more point: If I say that "lost to follow up" is a state - I am now effectively dealing with a problem with no "censoring?
Comment: @stats_noob I've edited the question to deal with most of what you raised in these comments. My reaction against a multinomial model was what I inferred from your question to be a _single model at some point in time_ based on each of the non-absorbing states as a reference. A _series_ of such models _over time_ is OK in principle, just as simple discrete-time survival is implemented as a series of binomial regressions over time. I can't say whether that's the most efficient formulation of such modeling, particularly if there are transitions among multiple non-absorbing states.
Answer: Offering a different perspective on the matter, this is a common issue in cancer clinical trials. The typical endpoint is PFS or progression-free survival - it is a composite endpoint of death and disease progression. Disease progression is surveilled by conducting periodic scans. So with a 3 (or 6) month interval between scans, if disease progression is detected, we have no idea at which exact timepoint the cancer grew - as early as the day after the previous scan to the day prior to the current scan. This interval censoring problem is well explored.
What's desired in this case is a consistent association measure to make inference that the survival is better in one group - provided the proportional hazards assumption is met. So this motivates the hazard ratio from a Cox proportional hazards model. What we also desire is a measure of person-time follow-up so that we can approximate the population-based incidence density by dividing events to follow-up.
In analyzing the data, the event timepoint is, for PFS events, date of death or cancer scan showing disease progression. For controls, they are censored back to latest evaluable scan, and subjects can be censored if they miss a certain number of scans because the interval censoring becomes intolerable.
You can do some relatively simple simulations to show that the extent of bias is relatively small and the power of the statistical test is acceptable and, most favorably, the analysis model is easy to specify, fit, replicate, and understand.


Can $2^k + 2^j$ be expressed as $2^n$?

Question: If we are given $j,k \geq 0, j> k$ and $j,k$ are integers, can $2^j + 2^k$ be ever expressed as $2^n$ where $n \geq 0$ and is an integer?
What I said:

Suppose it can. Then for some $0 \leq n \in \mathbb{N}: 2^j + 2^k = 2^n$. We know that $j>k$ so $j=k+s$ for some $0 < s \in \mathbb{N}$. So: $2^j + 2^k = 2^{k+s} + 2^k = 2^k \cdot 2^s + 2^k = 2^k \cdot (2^s + 1)$. We see that $2^s + 1$ can be an even number only if $s=0$ but we know that $s > 0$, thus we have that $2^j + 2^k$ which is an even number is equal to an odd number (even * odd), thus it can't be.

Is that correct?
Comment: An even number times an odd number is still even... but you *can* finish this proof by dividing both sides of your equation $2^k(2^s+1) = 2^n$ by $2^k$.
Comment: Oh wow, thanks.
Answer: No, $2^k + 2^j$ has two bits set while $2^n$ has only one.
Comment: But isn't this problem basically asking a weaker version of "why is the binary representation unique"? So using the uniqueness of binary representation is close to circular logic....
Comment: Can you please explain what are "bits sets"?
Comment: Express both numbers in base 2. Each digit is a bit. A bit is set when it is 1.
Comment: I agree with @N.S.
Comment: @N.S., perhaps.
Answer: An even number times an odd number is still even... but you can finish this proof by dividing both sides of your equation $2^k(2^s+1)=2^n$ by $2^k$.

Can $2^k + 2^j$ be expressed as $2^n$?


50% Width Responsive Design Issue

Question: I'm searching for a way to be able to scroll in this page
http://bijusi01.businesscatalyst.com/shoes.html
I've been playing a bit with the css by adding some code in the header but the scrolling doesn't work (probably because of the position: fixed; but it's the only way I've found to make it responsive for now). Here is the code I added in the head :
#u1760_img {
    height: auto;
    width: 50%;
    float: right;
    z-index: 1;
    left: 0;
    position: fixed;
    margin: auto;
    top: 135px;
}
#u1765_img {
    height: auto;
    width: 50%;
    float: left;
    right: 0;
    text-align:right;
    position: fixed;
    margin: auto;
    z-index: 1;
    top: 135px;
}

Comment: You are WAY over-complicating things. Look, it's simple: [demo](http://jsfiddle.net/p7Pax/). The important thing to remember is that whitespace will screw up 50% width layouts, so make sure there are no spaces between the elements.
Answer: Scrolling Doesn't work:
Have you wondered why?
Because of this line of code:
position: fixed;

Why does this make scroll stop? Actually its not stoping the scroll, but instead the position of it is locked! The scoll is working, when you have a look at the scroll bar, but the image's position is fixed. You can use position: absolute to minimize this effect.
50% width for images:
When you use 50% width for the images, you are actually letting the image have the 50% width of the nearest parent element with some width. For example:

.someclass {
  width: 500px;
}

Now when you set image with to width: 50%; it will fill 50% of the div; that's its parent. If you have not set any, then the body will be filled with 50%. And so on.
The only issue that I found was:
The position: fixed. This was causing some issues, and one is nonscroll-ness, actually it is scroll, you can try giving a gradient background to the page, and when you'll scroll you'll see the changes!
Make some changes in your CSS:
#u1760_img {
height: auto;
width: 50%;
float: right;
z-index: 1;
left: 0;
position: fixed;
margin: auto;
top: 135px;
}
#u1765_img {
height: auto;
width: 50%;
float: left;
right: 0;
text-align:right;
position: fixed;
margin: auto;
z-index: 1;
top: 135px;
}

Instead of this, try using this:
img {
  width: 50%; // set the width
  position: absolute; // but still, its not the only way to position images
  top: 135px;
}

Note that I have not specified some CSS properties, why? z-index isn't necessary unless you have some elements which you want to overlap. So you won't require this one.
Secondly, I have not set height to auto, because browser will do that for us automatically :)
You are making a hell lot of other assumptions too, such as text-align, float: left, right: 0;. Try avoiding them in the beginning.
When you'll set image's width to 45%, the next image will come just infront of the first image so you won't have to write classes for each of them and the browser will automatically fit the images there for you!
Not sure, but still have this too
I am not sure whether you want this or not, but still I am going to write for information.
You can use media queries to create dynamic pages that would work on mobiles, like a mobile version of your website. You can also try using width: 50% (which you actually are) to make the browser always fit the image in it when it is resized down.
References:
http://css-tricks.com/css-media-queries/
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries
resize images using % in css
https://developer.mozilla.org/en-US/docs/Web/CSS/position
https://developer.mozilla.org/en-US/docs/Web/CSS/z-index

50% Width Responsive Design Issue