Choosing a value for random_state argument in scikit-learn linear regression

Question: A value of 324 is provided without explanation in a linear regression tutorial that I'm following. I checked to see if this was the number of samples, but they did not match.
Edit: My apologies for such an ill-formed question. The random_state argument is for scikit-learn's train_test_split function.
From the documentation, "If int, random_state is the seed used by the random number generator" so I can see that generating a random number is involved
and I'm fairly certain that the utility of generating random numbers is to randomize the samples allocated to training/testing, but what I don't understand is why 324 was chosen.
The tutorial is here: https://www.youtube.com/watch?v=PjbTG5BNzL0&t=601s
Comment: This can't be answered without a link to the tutorial.
Comment: I marked it as a duplicate of another thread that at first sight may seem very different from what you're asking, but it provides *all* the answers for your concerns if you read carefully.
Comment: TLDR; you can pick any value you want, people usually choose for the seed some number they like for whatever reason. IMPORTANT: this is not a hyperparameter, so don't tune it.
Answer: As found in this answer by elyase

If you use random_state=some_number, then you can guarantee that the
  output of Run 1 will be equal to the output of Run 2, i.e. your split
  will be always the same. It doesn't matter what the actual
  random_state number is 42, 0, 21, ... The important thing is that
  everytime you use 42, you will always get the same output the first
  time you make the split. This is useful if you want reproducible
  results, for example in the documentation, so that everybody can
  consistently see the same numbers when they run the examples. In
  practice I would say, you should set the random_state to some fixed
  number while you test stuff, but then remove it in production if you
  really need a random (and not a fixed) split.


How do I create CNAME records in AWS if the domain is hosted elsewhere?

Question: I have a domain that is hosted from a provider other than AWS.  I cannot input the CNAME entries that I need there because I'm using custom nameservers:
ns-743.awsdns-28.net
ns-1077.awsdns-06.org
ns-246.awsdns-30.com
ns-2021.awsdns-60.co.uk
When I try to find anything about updating CNAME entries in AWS, it always seems to be through Route 53, but I don't own any domains in Route 53.  Can someone please point me in the right direction?
Comment: Had you give the real name involved, you would have far better and precise answers. Other than that your DNS provider should be able to help you for your DNS setup.
Comment: If those are your custom name servers then yes, you are using Route 53. What you mean to say is that you have a domain that is **registered** with a different provider than AWS. But AWS is hosting the records according to your custom name servers.
Answer: If you are using ns-743.awsdns-28.net, ns-1077.awsdns-06.org, ns-246.awsdns-30.com, or ns-2021.awsdns-60.co.uk as your nameservers then you "ARE" using Route 53 at some point along the way.
If you are sure those nameserver values are accurate, you'll need to figure out which AWS account is handling those records and edit them in Route 53 because that's where the actual host records will live.

Alternatively, if you want to configure your CNAME, A, etc records in your "other provider", then you'll need to remove those "nameserver" records that point to Route 53 (awsdns) and configure them appropriately for that provider. You can ask the provider (or refer to their docs) for what the default nameserver values are supposed to be.
For example, if you're using Namecheap, you can search Google for "namecheap default nameservers" to find the info without having to contact Namecheap. Do that for whatever your provider actually is. Sometimes you don't even need to know the values and you can just revert to the default in the provider configuration (which will wipe out custom settings).
Comment: "you can search Google for "namecheap default nameservers" to find the info without having to contact Namecheap. " I wouldn't suggest anyone to do that, as you can't vouch in anyway for the accuracy of that information. You should go on the relevant provider website (and you shouldn't need to use Google for that...) and search for information there, or use their control panel or use their support service to raise questions.


Threadlist of TObject with Delphi - How to populate?

Question: From my limited knowledge about this subject, the following code should work. But I have not the expected result:
type
  TClient = class(TObject)
    Host: String;
  end;

var
  Clients: TThreadList;

const
  Hosts: Array[0..5] of String = ('HOST1', 'HOST2', 'HOST3', 'HOST4', 'HOST5', 'HOST6');
var
  I: Integer;
  List: TList;
  Client: TClient;
begin
  try
    for I := Low(Hosts) to High(Hosts) do
    begin
      Client := TClient.Create;
      with Client Do
      try
        Host := Hosts[I];
        List := Clients.LockList;
        try
          Clients.Add(Client);
        finally
          Clients.UnlockList;
        end;
      finally
        Client.Free;
      end;
    end;
  except
    on E:Exception Do ShowMessage(E.Message);
  end;

// RESULT TEST
List := Clients.LockList;
try
  I := List.Count;
  S := TClient(List.Items[0]).Host;
finally
  Clients.UnlockList;
end;
ShowMessage(IntToStr(I));
ShowMessage(S);

My expected result would be 6 and HOST1, but I got 1 and "" (empty)
Please, what I am missing?
Thanks!
Answer: List := Clients.LockList;
try
  Clients.Add(Client); // <--- mistake here
finally
  Clients.UnlockList;
end;

The idiom is that you lock the list with a call to LockList and that returns a mutable list. So you need to call Add on List.
List := Clients.LockList;
try
  List.Add(Client);
finally
  Clients.UnlockList;
end;

That said, TThreadList does offer an Add method that internally uses LockList. The reason that your call to that Add was failing is that you have used the default value of Duplicates which is dupIgnore. And you were passing the same memory address each time.
Why was the memory address the same each time? Well, the other mistake you made was to destroy your TClient objects and refer to them later. I guess the memory manager was re-using the memory that you just deallocated.
You might want to set Duplicates to dupAccept. At the very least you need to be aware that it has a potential impact.
This program produces your desired output:
{$APPTYPE CONSOLE}

uses
  SysUtils, Classes;

type
  TClient = class(TObject)
    Host: String;
  end;

const
  Hosts: Array[0..5] of String = ('HOST1', 'HOST2', 'HOST3', 'HOST4',
    'HOST5', 'HOST6');
var
  I: Integer;
  List: TList;
  Client: TClient;
  Clients: TThreadList;
begin
  Clients := TThreadList.Create;
  Clients.Duplicates := dupAccept;

  for I := Low(Hosts) to High(Hosts) do
  begin
    Client := TClient.Create;
    Client.Host := Hosts[I];
    List := Clients.LockList;
    try
      List.Add(Client);
    finally
      Clients.UnlockList;
    end;
  end;

  List := Clients.LockList;
  try
    Writeln(List.Count);
    Writeln(TClient(List.Items[0]).Host);
  finally
    Clients.UnlockList;
  end;
end.

Or the loop could be simplified even further:
for I := Low(Hosts) to High(Hosts) do
begin
  Client := TClient.Create;
  Client.Host := Hosts[I];
  Clients.Add(Client);
end;

I neglected to perform any deallocations for the sake of a simpler exposition. Obviously in real code you wouldn't leak the way this code does.
Personally I'm not a fan of this class. Not in this age of generics. You really should be looking at TThreadList<T>.
{$APPTYPE CONSOLE}

uses
  SysUtils, Classes, Generics.Collections;

type
  TClient = class
    Host: string;
    constructor Create(AHost: string);
  end;

constructor TClient.Create(AHost: string);
begin
  inherited Create;
  Host := AHost;
end;

const
  Hosts: array[0..5] of string = ('HOST1', 'HOST2', 'HOST3', 'HOST4',
    'HOST5', 'HOST6');

var
  Host: string;
  List: TList<TClient>;
  Clients: TThreadList<TClient>;

begin
  Clients := TThreadList<TClient>.Create;
  Clients.Duplicates := dupAccept;

  for Host in Hosts do
    Clients.Add(TClient.Create(Host));

  List := Clients.LockList;
  try
    Writeln(List.Count);
    Writeln(List.First.Host);
  finally
    Clients.UnlockList;
  end;
end.

Comment: Thank you @David Heffernan for this complete and well explained answer!


Former British colonies and cricket

Question: Some former British colonies, from India to Australia to the nations of the West Indies, have notable cricket teams and a significant number of cricket fans.
However, this is not the same everywhere. While countries such as Canada and Kenya have teams that have played in the World Cup in the past, cricket doesn't seem to excite the same passions that it does elsewhere.
Countries such as Nigeria, Ghana, Malawi and Zambia don't even meet this criterion. The latter two are particularly striking outliers given their proximity to Zimbabwe and South Africa.
Why is this the case?
Comment: Another good example is the USA. It's a major former British colony, and cricket is nearly unheard-of there outside of immigrant communities from *other* former British colonies.
Comment: Cricket is quite an expensive sport to stage - not necessarily in direct cash terms - but in the amount of time that needs to be devoted to the playing of a match. It could be that in countries like Nigeria etc that potential amateurs find it difficult to get enough time off work for an earnest pursual of the sport.  It is hard enough in the UK!
Answer: India, Australia, and the West Indies had a long history of British colonial rule and exposure to cricket, other nations in Africa, like Nigeria, Ghana, Malawi, and Zambia, had different colonial influences or were not as heavily influenced by British culture.
The development and popularization of cricket require adequate infrastructure, facilities, and resources. In some countries, the lack of proper cricket grounds, training facilities, coaching programs, and funding for the sport can hinder its growth. In those countries, other sports have gained a strong foothold and established themselves as the primary focus of sporting interest. For example, in Nigeria, football is the most popular sport and has a massive following. The presence of other highly popular sports can divert attention and resources away from cricket. Also the visibility and media coverage of cricket play a significant role in generating interest and excitement among the masses.
Comment: Please refer this link [How cricket became India's passion](https://www.hindustantimes.com/75th-independence-day/cricket/how-cricket-became-india-passion)

Former British colonies and cricket


Grails apps in docker, installation of spring-security plugins?

Question: A newbie question regarding both Grails app running in Docker, and spring-security-ldap 2.0.1 plugin.
Currently I am running a local Grails apps (not in Docker), installation of  spring-security-ldap 2.0.1 is pretty simple with mainly a added line in BuildConfig.groovy:
    plugins {
        compile ":spring-security-ldap:2.0.1"
    }
After implemented the necessary user details and mapping classes, the first time running the Grails app, the installation of spring-security-ldap is automatically carried out and install a bunch of stuff under the
//src/target/work/plugins/spring-security-ldap-2.0.1/ folder, these are the things that drive the Ldap login support I supposed.
Now, if I were to move my Grails App into a docker container, what is the proper way to get this plugin installation done? Where to specify the resolution and installation of the plugin?
[Update 20180425]
NVM, I just tried it with my changed codes (specifying the LDAP plugins in BuildConfig.groovy), rebuilt the Docker images, and executed it and I can now see the auth login page. That means the plugin had been successfully resolved from external repo and built into the Docker image!
The problem now is, I am not able to log in with the test users:
    org.springframework.security.authentication.InternalAuthenticationServiceException: localhost:389; nested exception is javax.naming.CommunicationException: localhost:389 [Root exception is java.net.ConnectException: Connection refused (Connection refused)]
It has to be about the opening the Docker in/out ports for my local OpenLdap. I will read a bit on Docker documentation for this.
Comment: A @alchn What Grails version are you using?
Comment: Why is this a problem (do you actually have a problem, then please state it)?  Do you want to dockerize your development or running the applicaton?
Comment: Plugins are "resolved" and "installed" at build time.  So if your build is local but you run the built app in a container, there's nothing extra to do.  If you build in a container, then the container needs internet access so the build can find the repositories needed for the build (including your plugin).  The only real change may be in how you deliver configuration and secrets to the application since you probably don't want that info to reside in the Docker image. `ENVIRONMENT` variables are one way to do it.
Comment: @SaqibAhmed I am using Grails 2.4.4.
Comment: @cfrick Yes I want to dockerize my the Grails app, together with the ldap plugin.
Comment: @npskirk The app war would be build in docker. My doubt is, the ldap plugin are auto installed in the '/target/work/plugins' folder, so it won't be pulled into the docker image. I am unsure but assuming, during Docker build time, it would pull the plugin from external repo again (the external access is already working for other dependencies) and put it into '/target', make into war, all in the docker environment. I am not sure where/how do I specify Docker config that execute this line in my BuildConfig.groovy: plugins { compile ":spring-security-ldap:2.0.1" } as if it is in my local.
Comment: To put things in context, this particular Grails app is already up running in QA and Prod on Docker, just without the LDAP integration yet. My task is to add LDAP integration to this app. In my local, I had added the spring security LDAP plugin and done the implementation. I am just wondering how to move/deploy the changes (mostly the plugin part) into a Dockerized environment.
Answer: First of all, create a war file using grails war. It will automatically add all the dependencies in the war file including spring-security-ldap. You don't have to worry about anything regarding dependency injection.
Afterward, you can follow these steps to create and run a docker image:
A) Creating Dockerfile
Create a file named Dockerfile in your project directory with the following content:
FROM tomcat:7.0.86-jre7
WORKDIR /usr/local/tomcat/bin
COPY <path/to/your-war-file> /usr/local/tomcat/webapp/<application-name>.war
CMD ["catalina.sh", "run"]

B) Creating an Image
Simply execute docker build -t <image name>:<image version> . This will create a docker image in your local docker engine.
C) Running the Container
Finally, start your application by executing docker run -p <port you wanna bind>:8080 <image name>:<image version>
If everything goes right, you can now access your application on the port you bound in docker run .. command.
Update
To answer your updated question, when you access localhost inside a container, it doesn't resolve to the localhost of the docker host machine. It resolves to the container itself. So, if you have something running on the host machine (OpenLDAP on port 389 in this case), you'll have to access this by using the IP of the host machine.
A better solution, in this case, is to run OpenLDAP in docker container also. That way, you can access OpenLDAP with its hostname and you won't have to change the IP if it changes.
Comment: "Assuming a Grails 3.x application..." - The question mentions `BuildConfig.groovy` and `...src/target/work/plugins/...`.  That isn't a Grails 3 app.
Comment: Updated the answer for grails 2.4.4. Thank you for notifying.
Comment: Thanks guys for trying to help. Actually building of the war need to be inside of the Docker build, rather than on my local first and copy into Docker, this is to follow the build flow in our QA/Prod environment. But anyhow (please refer to my updated section in Q ) I had gotten this part working, that the LDAP plugin is running from the Grails app from within the container already. Only problem remaining now is that it can't talk/query my OpenLDAP at port 389, so I will need another in/out port bounding for my OpenLdap service. I need to read up Docker documentation for that...
Comment: I updated the answer to your question update. Let me know if you need more detail and/or example. @alchn
Comment: @SaqibAhmed "A better solution, in this case, is to run OpenLDAP in docker container also." <--- Unfortunately I can't do that, bcos eventually the Grails Apps is gonna talk to our corporate existing LDAP server, which would not be inside Docker.  I am just temporarily using a local OpenLdap for development purpose.
Comment: The existing corporate LDAP will/should have a static IP. In that case, you'll hardcode that static IP so it won't cause any problem. `OpenLDAP` in docker is only required in testing.


Geometrical explanation of the Cross Product

Question: Teaching myself multivariable calculus before class starts in August and got stuck with the following two questions which I have no one but you to ask. So any deep explanation would be great!
Show that if $u$, $v$, and $w$ are nonzero vectors and $(u \times v) \times w = 0$, then either: (i) $u$ and $v$ are parallel, or (ii) $w$ is orthogonal to $u$ and $v$.
Using the above solution, show that $u,v, w$ are nonzero and $(u \times v) \times w = u \times (v \times w) = 0$. Show that $u,v$, and $w$ are either mutually parallel or mutually perpendicular.
Comment: Please tell us how far you've gotten. When is the cross product of two vectors $\vec 0$? Also, in the second question, your first "show" is wrong. Try to apply the first question to do the second.
Comment: I think you mean (i) $u, v$ are collinear.
Comment: Isn't there a better tag for this?  This is purely a question of 3d vector algebra; it has nothing to do with vector calculus.
Comment: @Muphrid That may have been the context of the class where the algebra was taught.
Comment: Yeah, I did not mean to criticize the OP in any way; I'm just wondering if there really is a better tag already in use for a question like this.
Answer: The cross-product of two vectors is a 3D vector orthogonal to the two. If the two vectors are not themselves in different directions, there is a whole plane orthogonal to the line spanned by the vector (both span the same one). So, the cross-product is the 0-vector. Conversely, if a cross-product of a vector with $w$ is 0, that vector lies on the same line as $w$. If that vector is not itself 0, it must mean $u, v$ are orthogonal to $w$. If that vector is in fact 0, $u, v$ must sit on the same line.


Rspec issue with should_have_content

Question: I am doing Hartl's Rails tutorial (section 5, listing 5.17) http://www.railstutorial.org/book/filling_in_the_layout#sec-layout_links and am consistently getting a strange series of unexpected errors when I run Rspec. Note that at this stage of the tutorial, one link in the footer partial is intentionally commented out, and the tests should still pass per the tutorial. If I uncomment the the link in the footer partial, the tests all pass, but this doesn't make any sense to me. Anyway, here are the errors:
 rspec ./spec/requests/static_pages_spec.rb:17 # Static pages Home page should not have a custom page title
rspec ./spec/requests/static_pages_spec.rb:7 # Static pages Home page should have the content 'Sample App'
rspec ./spec/requests/static_pages_spec.rb:12 # Static pages Home page should have the title 'Home'
rspec ./spec/requests/static_pages_spec.rb:52 # Static pages Contact page should have the content 'Contact'
rspec ./spec/requests/static_pages_spec.rb:57 # Static pages Contact page should have the title 'Contact'
rspec ./spec/requests/static_pages_spec.rb:26 # Static pages Help page should have the content 'Help'
rspec ./spec/requests/static_pages_spec.rb:31 # Static pages Help page should have the title 'Help'
rspec ./spec/requests/static_pages_spec.rb:39 # Static pages About page should have the content 'About Us'
rspec ./spec/requests/static_pages_spec.rb:44 # Static pages About page should have the title 'About

This does not make any sense, since when I look at the HTML for each of these pages, the content/title are all clearly there. However, when I look more closely at the logs, I notice that there consistently seems to be an error in the footer partial.
2) Static pages Home page should have the content 'Sample App'
     Failure/Error: visit '/static_pages/home'
     SyntaxError:
       /Users/anant/helpondemand/sample_app2/app/views/layouts/_footer.html.erb:10: syntax error, unexpected '<'

 News

              ^
       /Users/anant/helpondemand/sample_app2/app/views/layouts/_footer.html.erb:10: unknown regexp option - l
       /Users/anant/helpondemand/sample_app2/app/views/layouts/_footer.html.erb:11: syntax error, unexpected '<'

            ^
       /Users/anant/helpondemand/sample_app2/app/views/layouts/_footer.html.erb:12: unknown regexp options - av
       /Users/anant/helpondemand/sample_app2/app/views/layouts/_footer.html.erb:13: syntax error, unexpected '<'
       '.freeze;@output_buffer.to_s
        ^
       /Users/anant/helpondemand/sample_app2/app/views/layouts/_footer.html.erb:13: unterminated regexp meets end of file
     # ./app/views/layouts/application.html.erb:15:in `_app_views_layouts_application_html_erb___4305927437372856517_2202294640'
     # ./spec/requests/static_pages_spec.rb:8:in `block (3 levels) in <top (required)>'

Here is the footer partial in question. Note that a link is intentionally commented out. It doesn't make sense that this many errors should be produced, right? In fact, in the tutorial, the link remains commented out, and the tests all pass.
footer class="footer">

    Rails Tutorial
    by Michael Hartl

 <%= link_to "About",   '#' %>

 <%=# link_to "Contact", '#' %>

 News

Any idea what is going on here?
Answer: <%=# is not valid erb.
The only valid way of commenting out bits of erb is
<%# ... %>

If you look carefully at the tutorial it contains

<%#= link_to "Contact", '#' %>

Instead of what you have.

Rspec issue with should_have_content


Joining multiple rows based on a grouping factor

Question: I'm trying to create a SQL query that will left join multiple rows together based on a grouping factor. Hopefully someone can help.
Example Data:
Code

001A

001B

001C

002A

002B

002C

002D

002E

I would want a query that does Where Code LIKE '001%' Then Left Join all the rows.
Resulting in:
Code1   Code2   Code3

001A    001B    001C

In the data there would be variances in the number of codes that it would pick up for example on a Where Code Like '002%':
Code1   Code2   Code3   Code4   Code5

002A    002B    002C    002D    002E

Any help would be much appreciated.
Comment: https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
Answer: You can do this with pivot and some dynamic query:
declare @cols varchar(max), @query varchar(max)

set @cols = stuff((select distinct ',' + quotename(code)
                   from t
                   where code like '002%'
                   for xml path(''), type).value('.', 'varchar(max)')
                  ,1,1,'')

set @query = 'select * from (select code from t)t
              pivot (max(code) for code in (' + @cols + ')) p'
exec(@query)

Fiddle http://sqlfiddle.com/#!6/4da68/10
Comment: That looks like exactly what was after, however how do I modify this so that it is only looking at the "code" column and not picking up any other columns that may be on the table? Thanks.


Mysql Max number of Rows Insert and Select at a time

Question: What is the max number of records can be written and read from Mysql table at a time ? or max number or read and write at a time?
I suppose the data for read and write can vary. If one is reduced then another may go up. But still give some info on it on per second basis or per minute basis.
I am not looking for an exact answer. I am looking for approx answer.
Also, for hardware, think of average shared hosting provider.
Comment: This is a very vague question .... define *at a time* .. the records structure .. the table structure .. insert query .. the hardware ... the OS ... the MySQL version .. the day of the week ... What are you trying to do and what do you want to measure ?
Comment: You can define those thinking average servers.
Comment: yes, I talked about concurrent read and write.
Comment: All talked about one way, i.e insert only. I am interested in read and write at same time.
Answer: There is no limit in mysql itself. However, a limit is placed upon the maximum size of the packet, sent to the server. In case of an INSERT or SELECT, a COM_QUERY packet is sent by the underlying implementation.

The largest possible packet that can be transmitted to or from a MySQL
  5.5 server or client is 1GB.
  When the mysqld server receives a packet bigger than
  max_allowed_packet bytes, it issues a Packet too large error and
  closes the connection. With some clients, you may also get a Lost
  connection to MySQL server during query error if the communication
  packet is too large.

Reference
When it comes to the number of concurrent read/writes, that depends solely upon the disk in use and the CPU. The faster the mysql server can process queries sent, and faster the read/write speeds, the larger the number of concurrent read-writes.
Comment: Upvoted to the post but looking for more info on concurrent write and read.
Comment: You need to specify the hardware. It depends directly upon server hardware.
Comment: Take for example average shared hosting service provider.


Change taxonomy term field into text field in content-type

Question: Is there a way to transform a taxonomy term field into a simple text field? I need to keep all the terms present in the taxonomy field and have them separated by a comma.
Answer: Eventually, I simply used a PHP script I execute in mysite/devel/php to copy my taxonomy term field value to my new text field:
$nodes = node_load_multiple(array(), array('type' => 'contact'));
foreach($nodes as $node) {
  if ($node != NULL) {
    $tid = $node->field_title['und'][0]['tid'];
    $term = taxonomy_term_load($tid);
    $name = $term->name;
    $node->field_function_title['und'][0]['value'] = $name;
    $node = node_submit($node);
    node_save($node);
  }
}


Android self-signed handshake error

Question: I'm trying to do a POST HTTP request on a HTTPS server with a self-signed certificate. My POST is multipart to allow to send a file (picture or anything else).
I'm still getting the following error:
Error:javax.net.ssl.SSLHandshakeException: Handshake failed:Handshake failed

Here is my source code:
URL url = new URL(PROTOCOL + "://" + host + "/file");
URI uri = new URI(PROTOCOL, null, url.getHost(), url.getPort(), URLEncoder.encode(url.getPath(), "UTF-8").replace("+", "%20").replace("%2F", "/"), url.getQuery(), null);
String authorizationHeader = Hawk.generateAuthorizationHeader(url, "POST", (int) (System.currentTimeMillis() / 1000), Hawk.generateNonce(), url.getPort());

HttpClient client = getHttpClient();

HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Authorization", authorizationHeader);

MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

java.io.File file = new java.io.File(fullLocalFilePath);
entityBuilder.addBinaryBody(fullLocalFilePath, file);

HttpEntity entity = entityBuilder.build();
httpPost.setEntity(entity);

HttpResponse response = client.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
httpEntity.consumeContent();

Comment: Do you have access to the logs of the SSL server ? If so, you should post them too
Comment: Sorry not yet. I could have access but not before some days/weeks. I will restart a bounty if there is no additional answer
Comment: are you able to simply make a get call to the https url ? can you share what is the output of that call ?
Comment: Yes, I can make a simple GET on the url. The output is a standard JSON file.
Answer: I have encountered something like this before, so here's my guess. The issue is that the certificate is using a different domain than where I'm currently using it. In OpenSSL, the domain name is the Common Name which it will ask you when creating the certificate, or if doing it as a parameter, it is the CN. The value of this should be the same as the domain of the server that you are trying to access.
You may try this:
For windows, go to %systemroot%\system32\drivers\etc, edit hosts as an administrator. Add a line something like this <your IP>     mysampledomain.net, then when creating your SSL key/certificate, put mysampledomain.net as the value of the domain name i.e. Common Name in OpenSSL parameters. For linux, the procedure is the same, except that the hosts file is located in /etc/hosts.
Try invoking your code and see if you still get the same error.

Android self-signed handshake error


For which $x\in\mathbb{R}$ does there exist a specific kind of polynomial that maps $x$ between $-1$ and $1$?

Question: Let $\mathcal{P}$ be the smallest set of polynomials containing $-1$ and $1$ such that for each $P,Q\in\mathcal{P}$ we have $XP+(1-X)Q\in\mathcal{P}$. Determine the set $S$ of all $x\in\mathbb{R}$ for which there exists $P\in\mathcal{P}$ such that $P(x)\in(-1,1)$?
It is quite easy to prove that any integer will always be mapped to an odd integer, which gives $S\cap\mathbb{Z}=\emptyset$.
Since $2X-1\in\mathcal{P}$ we find that $(0,1)\subset S$.
Since $-2X^2+4X-1\in\mathcal{P}$ we find that $(1,2)\subset S$.
Since $2X^2-1\in\mathcal{P}$ we find that $(-1,0)\subset S$.
By experimentation and intuition, I suspect that $S=(-\phi,1+\phi)\setminus\mathbb{Z}$ with $\phi=\frac{1+\sqrt5}2\approx1.618$ the golden ratio. I have some idea as to how to prove the right inclusion, but I have absolutely no idea how to prove the left inclusion.
Comment: What is $X$? Is that really $x$?
Comment: $X$ is the identity polynomial. In this context, you can think of it as just being $x$.
Comment: your suspicious is definitely wrong, since the problem is invariant to $x \mapsto -x$.
Comment: I think the problem is not invariant to $x\mapsto-x$, but to $x\mapsto1-x$.
Comment: @SmileyCraft yea, sorry. I think the left inclusion will follow after you prove a very strong statement about $\mathcal{P}$ by induction. One just needs to find that statement...
Comment: I'm doing some computations, and it seems that if you change definition of $S$ to have $P(x) \in [-1,1]$ instead of $P(x) \in (-1,1)$, then $S$ will conjecturally be $[-\phi,1+\phi]$ instead of $(-\phi,1+\phi)\setminus\mathbb{Z}$. Am I wrong about this? I'm asking because, if I'm not wrong, then the $P(x) \in [-1,1]$ question is cleaner imo.
Comment: I would personally expect that $P(x)\in[-1,1]$ would still give $(-\phi,1+\phi)$, but I could be wrong.
Answer: I now know why I could never prove $S = (-\phi,1+\phi)\setminus\mathbb{Z}$. It's false.
That $2X-1,-1 \in \mathcal{P}$ implies $X(2X-1)+(1-X)(-1) = 2X^2-1 \in \mathcal{P}$. Therefore, since $1-2X \in \mathcal{P}$, we have $H(X) := X(2X^2-1)+(1-X)(1-2X) = 2X^3+2X^2-4X+1 \in \mathcal{P}$. But $H(-2.01) \approx 0.88$.
By code, $S$ includes $x = 10.0441$.
Below are what I think all the polynomials of degree at most $3$ in $S$. All of the integers $-2,-1,0,1,2,3$ get mapped to $1$ by some polynomial below.
$-1,1,1-2 x,-1+2 x,-1+6 x-6 x^2,-1+4 x-4 x^2,1-2 x^2,-1+2 x-2 x^2,-1+4 x-2 x^2,-1+2 x^2,1-4 x+2 x^2,1-2 x+2 x^2,1-4 x+4 x^2,1-6 x+6 x^2,1-6 x+12 x^2-8 x^3,-1+6 x^2-6 x^3,1-4 x+8 x^2-6 x^3,1-6 x+10 x^2-6 x^3,1-6 x+12 x^2-6 x^3,-1+2 x+2 x^2-4 x^3,-1+4 x^2-4 x^3,1-2 x+4 x^2-4 x^3,-1+6 x^2-4 x^3,1-4 x+6 x^2-4 x^3,1-6 x+8 x^2-4 x^3,1-4 x+8 x^2-4 x^3,1-6 x+10 x^2-4 x^3,1-2 x^3,-1+2 x-2 x^3,-1+4 x-2 x^2-2 x^3,-1+2 x^2-2 x^3,1-2 x+2 x^2-2 x^3,-1+2 x+2 x^2-2 x^3,-1+4 x^2-2 x^3,1-4 x+4 x^2-2 x^3,1-2 x+4 x^2-2 x^3,1-6 x+6 x^2-2 x^3,1-4 x+6 x^2-2 x^3,1-6 x+8 x^2-2 x^3,-1+2 x^3,1-2 x+2 x^3,-1+6 x-8 x^2+2 x^3,-1+4 x-6 x^2+2 x^3,-1+6 x-6 x^2+2 x^3,1-4 x^2+2 x^3,-1+2 x-4 x^2+2 x^3,-1+4 x-4 x^2+2 x^3,1-2 x^2+2 x^3,1-2 x-2 x^2+2 x^3,-1+2 x-2 x^2+2 x^3,1-4 x+2 x^2+2 x^3,-1+6 x-10 x^2+4 x^3,-1+4 x-8 x^2+4 x^3,-1+6 x-8 x^2+4 x^3,1-6 x^2+4 x^3,-1+4 x-6 x^2+4 x^3,1-4 x^2+4 x^3,-1+2 x-4 x^2+4 x^3,1-2 x-2 x^2+4 x^3,-1+6 x-12 x^2+6 x^3,-1+6 x-10 x^2+6 x^3,-1+4 x-8 x^2+6 x^3,1-6 x^2+6 x^3,-1+6 x-12 x^2+8 x^3$
Comment: Interesting, do you think $S$ could just be $\mathbb{R}\setminus\mathbb{Z}$?
Comment: @SmileyCraft I have no idea. Do you still care? Does this problem come from somewhere interesting..
Comment: @SmileyCraft I mean, I liked the problem cause I thought there would have been something cool going on if the roots were restricted to $[-\phi,1+\phi]$. But otherwise, there's probably no structure and nothing special going on...
Comment: Right, unfortunately I can't remember how I came up with this problem or why I thought $S$ would equal $(-\phi,1+\phi)$.
Comment: It's still pretty interesting though :P I've been messing around with it just now due to your answer. Since any $P\in\mathcal{P}$ maps all integers to odd integers, it would be interesting to know which integers can be mapped to $1$ by some $P\neq1$. If the derivative is non-zero this would show $\mathbb{Z}\subset\overline{S}$. But it would be interesting to find a non-integer number not in $S$. Also, I managed to reason that $\mathcal{P}$ is closed under multiplication.
Comment: I think I remember some of the context. You can turn the problem around intuitively: Fix $x\in\mathbb{R}$ and start with drawing the points $-1,1$. Then you can take any two drawn points $P,Q$ and add point $P+x(Q-P)=xQ+(1-x)P$. The goal is to draw a point between $-1$ and $1$. For example let $x=-2.01$. Draw $-5.02$ from $P=-1$ and $Q=1$. Draw $5.02$ from $P=1$ and $Q=-1$. Draw $7.0802$ from $P=-1$ and $Q=-5.02$. Finally draw $0.878998$ from $P=5.02$ and $Q=7.0802$. I think this context makes it interesting.
Comment: I think the reason I expected $S$ to equal $(-\phi,1+\phi)$ was the following strategy. Draw $P_0$ from $-1$ and $1$. For $i\geq1$ draw $Q_i$ from $P_{i-1}$ and $1$ and draw $P_i$ from $Q_i$ and $-1$. For example let $x=2.1$. Draw $P_0=3.2$ from $-1$ and $1$. Draw $Q_1=-1.42$ from $P_0=3.2$ and $1$. Finally draw $P_1=-0.538$ from $Q_1=-1.42$ and $-1$. Now consider $x=1+\phi$. You will find $P_i=2\phi+1$ and $Q_i=-2\phi-1$ for all $i$. However, if $x$ was even slightly smaller, the sequences would get smaller over time and eventually get between $-1$ and $1$.
Comment: @SmileyCraft To make sure i understand, when $x=-2.01$, we have $xQ+(1-x)P = -2.01Q+3.01P$. Can't you just take $Q=P=1$ to get $1.01$ and then $Q=1.01,P=1$ to get $0.9799$?
Comment: @SmileyCraft See updated answer. A direct way to see $x=2$ can nontrivially yield $1$, note $x=2$ gives $2Q-P$; taking $Q=-1,P=1$ gives $-3$, and then $Q=1,P=-3$ gives $1$.
Comment: When $x=-2.01$ and $Q=P=1$ you get $xQ+(1-x)P=-2.01+3.01=1$,so not $1.01$. And when $x=2$, $Q=1$ and $P=-3$ you get $xQ+(1-x)P=2\cdot1+(-1)\cdot(-3)=5$, so not $1$. By the way, the reason it is interesting to study the goal to draw a point between $-1$ and $1$, is that implies the set of points you can draw is dense in $\mathbb{R}$, while otherwise the set would be discrete.
Comment: @SmileyCraft LOL. I always make the funniest/dumbest mistakes around you. Thanks for explaining the motivation; I find the question interesting now as well! I'm currently on a plane, but will think more about the question soon.
Comment: I made some progress on this with a friend yesterday, and we proved $S$ contains all transcendental numbers. Vaguely speaking, we found a superexponential number of different polynomials of each degree, while the evaluations are bounded only exponentially, forcing them to get arbitrarily close together. However we also experimentally figured out that $1+\phi$ is in fact not an element of $S$, although we could not quite prove it yet. We also proved the set $\mathbb{R}\setminus S$ is discrete. I am not sure when I have the time to write down everything we came up with.
Comment: @SmileyCraft Thanks for the update!! Will let you know if I have any.


Offset UISlider Min/Max value images

Question: I'm trying to offset the x/y position of a UISlider's min and max value images.
Currently, I'm sublcassing UISlider and am setting the maximum value image like this:
[self setMaximumValueImage:[UIImage imageNamed:@"circle_with_plus"]];

However, I need this image to be closer to the actual UISlider and have little control over visual assets on this project. I've tried using
- (CGRect)maximumValueImageRectForBounds:(CGRect)bounds

However, I'm my min/max value images may change size dynamically so I'm not sure how to properly implement it in this case. Is there a different way to move the asset?
Thanks
Answer: No, there is no other way to reposition the minimum or maximum value images.  maximumValueImageRectForBounds: gets invoked every time the slider lays out its subviews, and laying out the subviews happens whenever you change the maximumValueImage, so it is sufficient to do:
@implementation MyCustomSlider

- (CGRect)maximumValueImageRectForBounds:(CGRect)bounds {
  CGRect r = [super maximumValueImageRectForBounds:bounds];
  r.origin.x -= 3;
  return r;
}

@end

Offset UISlider Min/Max value images


Como adaptar esse código para telas diferentes

Question: Estou com um problema ao utilizar um slider vertical, o Swiper Slider estou utilizando o MouseWheel control.
Meu problema é o seguinte, como ele é um slider vertical, preciso definir um tamanho para o height, então não consigo deixá-lo responsivo.
Exemplo:
Abaixo encontra-se o arquivo css onde defino o tamanho do container que irá comportar os elementos do slider.
.swiper-container { /*esta classe comporta os slides.*/
    width: 100%;
    height: 900px;
    margin-left: auto;
    margin-right: auto;
}

.swiper-slide { /nesta classe encontram-se os compontes do swiper.container.*/
    text-align: center;
    font-size: 18px;
   /* Center slide text vertically */
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
}

Como podem ver, defini o tamanho do height em 900px, é claro que em telas menores ele continuará com 900px, preciso que ele se adeque ao tamanho da tela, isto posso resolver com media-queries, porém tenho mais um problema, vejam o script que efetua a inicialização do slider:
A opção slidesPerView, define quantos slides aparecerão na tela por vez, se eu diminuir o height, continuarão aparecendo 4 slides :/
$(document).ready(function () {
//initialize swiper when document ready
    var mySwiper = new Swiper ('.swiper-container', {
      // Optional parameters
        pagination: '.swiper-pagination',
        direction: 'vertical',
        slidesPerView: 4,
        paginationClickable: true,
        spaceBetween: 30,
        mousewheelControl: true
    })
});

O html coloquei no pen porque se não o post ficaria muito extenso.
Alguma ideia de como resolver?
Também estou aceitando indicações de algum vertical slider melhor.
Estou utilizando o materialize como framework css.
Comment: Ola, Na parte de diminuir ou aumentar o numero de imagens, quais vão ser as regras?
Comment: Então, minha ideia seria para que quando o tamanho da tela for menor que 600px apareçam umas 2 imagens, entre 600 e 1024 4 imagens e maior que isso 5 imagens.
Comment: escondi a publicidade. O que pretende é? https://jsfiddle.net/mrpbLL6a/1/
Comment: Legal! Era isso mesmo. Mas acabei resolvendo usando as media-queries mesmo. Obrigado pela resposta! Mas mesmo assim acho que vou fazer dessa forma que você fez, quatro imagens numa tela de 320px é muito hahaha. Valeu!
Answer: Para ser dinâmico foi criada a função atualiza.
atualiza=function(){
   $('.swiper-container').width($( window ).width());
   $('.swiper-container').height($( window ).height());

   if ($( window ).height()<600){
      mySwiper.slidesPerView=2;
   } else if ($( window ).height()<1024){
      mySwiper.slidesPerView=4;
   } else {
      mySwiper.slidesPerView=5;
   }
};

Essa função tem a tarefa de indicar o tamanho do slider e como indicar quantas fotos deverão ser visualizadas.
Foi criado um trigger para se existir alguma mudança com o tamanho da janela chamar a função atualiza.
$( window ).resize(function() {
   atualiza();
});

O exemplo no jsfiddle.:
jsfiddle.net/mrpbLL6a/1


Check if my app folder has been accessed

Question: Been looking for this problem for about a week now. How to check if a third party app has requested Read/Write permissions for my app's storage folder?
What I have in mind is:
private String TAG = "concernedClass";
private boolean myAppIsRunning;
//myAppIsRunning is set true when the app is in foreground
if(myAppIsRunning){
    //do something
}else if(!myAppIsRunning && (/*code to check if my app's storage folder was accessed*/)){
    Log.v(TAG,"Folder was accessed");
}

What should I replace /*code to check if my app's storage folder was accessed*/ with?
Comment: I don't think that there is a way to do that, if by "accessed" you mean "looked at". The closest thing that I can think of is `FileObserver`, and that requires that your process be continuously running, which is impractical and typically user-hostile.
Comment: @CommonsWare I've updated the question. Can you please help?
Answer:
How to check if a third party app has requested Read/Write permissions for my app's storage folder?

There is no such concept in Android.
If "my app's storage folder" refers to internal storage, third-party apps cannot have access to it.
If "my app's storage folder" refers to external storage, third-party apps can have access to it, but they request access to all of external storage, not something unique to your app.


Issue when performing a segue on a tableview cell

Question: I'm currently learning Swift and trying to perform a segue when the user taps on one of the tableview cells that the app presents. At the moment, whenever the user performs this action, the next view controller is loaded successfully, but it seems that, for some reason, I cannot access any of its UI elements, as each time that I try to do it, I end up getting this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
The error points to the line in which I try to modify the text of one of the labels that are displayed on the next view controller
This is the didSelectRowAt function:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    self.performSegue(withIdentifier: "segue1", sender: self)
}

and this is the prepareForSegue function:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "segue1" {
        let destinationVC = segue.destination as! UserViewController
        let selectedRow = tableView.indexPathForSelectedRow!
        let selectedCell = tableView.cellForRow(at: selectedRow) as! CustomCell

        destinationVC.usernameLabel.text = selectedCell.userName.text //this is where the error is pointing to
        destinationVC.bioLabel.text = selectedCell.bio.text
        destinationVC.userImage.image = selectedCell.photo.image

    }
}

I have no idea about what is causing this problem. My goal is to pass the data from the tapped cell to the next view controller, but this obviously is preventing me from doing so. Does anyone know how I can fix this? Thanks in advance.
Comment: Hi, Mike. Are you using static or dynamic `UITableView` cells?
Comment: I'm using dynamic cells.
Comment: @Mike Vaugh, use `destinationVC.usernameLabel.text = selectedCell.userName.text  ?? " "`
Comment: @aircraft Tried it. Same error.
Comment: @Mike Vaugh, have you log the `selectedRow`? if it is `nil`? if you use deselected
Comment: the selectedrow is not nil, according to the log.
Comment: Mike, please check my answer. I believe I've arrived at a solution if I understand your question correctly.
Answer: Note: I assumed that userName and bio were both UITextFields
Why don't you try something like this?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "segue1" {
        let destination = segue.destination as! UserViewController
        // Use of optional binding to make sure an indexPath exists
        if let indexPath = tableView.indexPathForSelectedRow {
            let cell = tableView.cellForRow(at: IndexPath(row: indexPath.row, section: indexPath.section)) as! CustomCell
            // Notice how we are not directly updating the label as before.
            destination.usernameText = cell.userName?.text
            destination.bioText = cell.bio?.text
        }
    }

}

Now in UserViewController:
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var bioLabel: UILabel!
// What we will be passing the text to instead.
var usernameText: String?
var bioText: String?

override func viewDidLoad() {
    super.viewDidLoad()
    // update the labels with the text from the proper cell.
    usernameLabel?.text = usernameText
    bioLabel?.text = bioText
}

You can just do the same for your image, just different types. This has to do with the outlets not being allocated when used in prepare(for segue:).
Comment: Mate, you fixed it! It's working beautifully now. Thanks a lot. I'll accept your answer shortly.
Comment: Fantastic! Best of luck with your development. @MikeVaugh
Answer: i had great issue with the prepare for segue method when trying the same thing with a UICollectionView.  The 2 are very similar so you should be able to change collectionview to tableview easily.
this is what i did... using variable selectedPack
in the view controller you want to segue to you need to set the variable
// passed packName from PackViewController
var selectedPack: String!

then in the viewcontroller you are selecting the cell
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        // handle the segue to JourneyViewController with variable "selectedPack"
        // not sure why you need to set the storyboard but it works
    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        //create instance of the viewcontroller
    let transportJourneyViewController = storyBoard.instantiateViewController(withIdentifier: "JourneyViewController") as! JourneyViewController
        //value to pass - has been defined in journey
        transportJourneyViewController.selectedPack = INSERT_YOUR_VALUE_TO_PASS
        //present the vc
    self.present(transportJourneyViewController, animated:true, completion:nil)

}

JourneyViewController is the storyboardID and ClassName of the viewcontroller you want to go to.set in the interface builder.
You'll also need to have the tableviewdatasource and tableviewdelegate defined at the top level of your view controllers and in the storyboard itself.
class JourneyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

Comment: I'm primarily looking to fix the issue with the tableview, specifically. However, using the UICollectionView sounds interesting indeed. I'll try it if I'm not able to do it with a tableview. Thanks!
Comment: just change "func collectionView(_ collectionView: UICollectionView" to "func tableView(_ tableView: UITableView"  should work
Comment: and obviously the delegates will have to be changed from "UICollectionViewDataSource, UICollectionViewDelegate" to "UITableViewDataSource, UITableViewDelegate"


Applying PCA to each group of features separately to use it in a predictive model

Question: I have a large data-set with >100 features. Can I use PCA to reduce the dimension of each group of features instead of t applying PCA to the whole data-set?
For example, if I have 10 demographic features and 10 work-place related features in my dataset, can I apply PCA to the demographic features, extract 2 PCs, do the same to the workplace features and do the final analysis on 4 extracted PCs? How does my described method compare with applying PCA to the entire dataset at once statistically? I only intend to use this approach for an slight increase in interpretability. Is it worth it? what are the pros and cons?
The features in each feature groups are more or less correlated but not necessarily.
Answer: You can certainly do this. For pros, as you have mentioned, the new features may be more interpretable/explainable. With this approach, you'll possibly end up selecting more features to describe the same amount of variance as you are limiting certain linear combinations of cross group features, though this is not necessarily a bad thing.
Comment: +1 I have done exactly this when working with large numbers of chemical analytes.  They tend to fall into groups of common chemical, biological, and/or physical behaviors, such as metals, chlorinated solvents, polynuclear aromatics, and so on; and often each group benefits from its own separate analysis.
Comment: @whuber I similarly was able to separate some climate data into snow-related principal components and rain-related principal components.


What if the ball hits somebody in the head in cricket?

Question: Not too long ago, a cricketer died as the ball hit him in the neck..
So how come there isn't anything between the stands and the sportsmen in cricket, a net or something similar? When somebody hits a 6, it usually lands right in the middle of the crowd. Why doesn't it hit people? Why are the accidents so rare? Are people really just that aware of where the ball is at any given moment?
Comment: There are specific wavers you actually agree to when you buy cricket tickets that removes the liability of stray cricket balls from sport organisers problems.
Comment: During a test match, India vs England, Headingley (2002) Sourav Ganguly hit a six, a spectator trying to catch it was hit on the head so bad, his head was full of blood. Though he was taken to medicos and wasn't a fatal/much serious injury.
So yes spectators too get injured
Answer: People in the stands do occasionally get hit by the ball - as they do in soccer, baseball and any number of other sports.
Accidents are rare because it's a big hit to land a ball into the stands, although it's by no means unusual. When it happens it's a big deal, and so yes, people are more aware of the ball.
The cricketer who died was Phillip Hughes - he was hit by a bouncer bowled at him, not by a ball hit at him by a batsman.
Comment: There was a case of a little girl who was hit by a ball hit by Chris Gayle in an IPL match in Bangalore.
Answer: Obviously accidents happens some times in cricket not only the players. it happens to the audience too.i did a bit of search.take a look at the following links
https://www.youtube.com/watch?v=D2-yA-G5Wjo
https://www.youtube.com/watch?v=zcIVdGP17Qo
https://www.youtube.com/watch?v=3gVQfvJlMnM
and sometime it happens to the on field umpires too..
http://www.espncricinfo.com/other/content/story/805703.html
The following is a list of notable cricket players who died while playing a game, died directly from injuries sustained while playing, or died after being taken ill on the ground.

Always be aware of the ball if your in the ground...


Align and Orign from famo.us example acts differently as in example

Question: I copied the example-code from http://famo.us/university/famous-102/transitionables/1/ ,but get different behaviour in all different browsers (used Chrome 35.0.1916.153 m, Opera 22.0.1471.70, IE 11.0.9600, Firefox 30 (here even the click does not work)).
The greenBackground, redBackground and the toggleSwitch are NOT put on top of each other as in the example, but in the browsers they are put below each other.
I can align them proberly when I change the origin and align parameters, but this should not be necessary.
Any idea, why the behaviour is different ?
Cheers, Rob.
Answer: This could be due to a lack of the famous.css file.  Try including the CDN'd version of the css to your project. CDN link below.
http://code.famo.us/famous/0.2/famous.css


Calculating power of a sample (need a layman's/beginner's definition)?

Question: We have a bi-annual survey and an intended sample size of 1,300. This sample size was determined using Krejcie's means formula for finite populations, and we drew the sample using 2-stage clustering. The data collected is primarily income, the population is quite stable and known (people in a certain industry in a particular area). This is a panel survey, so the same sample of 1,300 will be surveyed every year to directly compare changes in their income.
I have been asked to calculate the power of our sample. I have a basic understanding of what power is, and that you can either calculate the sample size taking into account the power you want, or you can perform an post-hoc power analysis. I know that it is the probability that the test correctly rejects the null hypothesis (H0) when the alternative hypothesis (H1) is true. How, then,  do I perform a power analysis of the sample we currently have?
Answer: It depends on what you are trying to test. But you can look at http://www.statmethods.net/stats/power.html if you are comfortable using R. You can also work backwards and use the power.prop.test() if you are looking at a difference in proportions.
Power is also defined as:
1 - P(Accept H0|Alternative is true)

Where  P(Accept H0|Alternative is true) = beta
So you can use the "pwr" package in R for the difference in means. Here is a little R code and you can change it as necessary:
install.packages("pwr")
?pwr.t.test

The only thing that is tricky is the effect size "d". This is your study, but am I assuming that you are pulling data from the same group twice, so you are going to want to use a paired t-test because the samples are not independent. In addition in R you are going to want to use an alternative statement of "less" or "greater" play around with that, I get confused which one you want here. To calculate the effect size you can look at http://www.statisticslectures.com/topics/effectsizedependentsamplest/. Hope this helps.
Comment: Because "Alternative is true" is usually a complicated situation, requiring at least one parameter for its description, considerably more explanation appears warranted.
Comment: Yes, I'm not following that comment.

At any rate, I am trying to test that income has increased. H0: μ1 = μ2, H1: μ1 < μ2
Comment: @406LQE did any of this help?
Comment: @AdamWarner This is a very delayed response, but I recently found out that calculating the power of our sample is not relevant because we don't have a counterfactual to compare it to and estimate the impact of the work we are doing on our current population. Yours and Upper_Case's responses do make sense, but based on recent discussions it sounds like power calculations are both not applicable to our process and outside of the scope of our budget/abilities (we would need to be able to detect changes of 10-20 cents, because we are comparing income per person per day).
Answer: I agree with Adam Warner that the pwr package in R is probably what you want (if you use R, that is. Other software has analogues), so this is mostly an addendum. That package requires any three of sample size, effect size, significance level, and power, and uses them to calculate the value of the fourth. In your case you have a sample size of 1,300 and your desired significance level should already have been chosen. You've been asked to calculate the power, and so you'll need to choose an effect size for your test to detect as your third argument.
The power of a statistical test depends on sample size, significance level, and the magnitude of the effect you want to be able to detect. Smaller effects are more difficult to identify than larger ones, and so with the sample size and significance level fixed your test will have greater power to detect a difference of 500 dollars than a 50 dollar difference. The effect size you choose is normally based in real-world relevance (a difference of one-one-thousandth of a cent probably doesn't matter) and I can't tell you what difference in income would be meaningful in your study.
Since this is post-hoc calculating power will give you a value describing how capable your study is of detecting a "true" increase in income. You will be reporting the power of your study to identify an effect of size d (or greater) from your sample of 1,300 respondents at your chosen significance level.


Stirling numbers of the second kind - proof

Question: For a fixed integer k, how would I prove that
$$\sum_{n\ge k} \left\{n \atop k\right\}x^n= \frac{x^k}{(1-x)(1-2x)...(1-kx)}.$$
where $\left\{n \atop k\right\}=k\left\{n-1 \atop k\right\}+\left\{n-1 \atop k-1 \right\}$
Comment: Use the recurrence for the Stirling numbers.
Comment: There are some basic proofs at the following [MSE link](https://math.stackexchange.com/questions/422006/).
Answer: The definition of ${n\brace k}$ through the recursion is easily seen to be equivalent to the combinatorial definition "the number of ways for partitioning a set with $n$ elements into $k$ non-empty subsets". $m^n$ can be interpreted as the number of functions from $[1,n]$ to $[1,m]$: if we classify them according to the cardinality of their range, we may easily check that
$$ m^n =\sum_{k=1}^{n}{n\brace k}k! \binom{m}{k} \tag{1}$$
i.e. Stirling numbers of the second kind allow to decompose monomials into linear combination of binomial coefficients. In equivalent terms ${n\brace k}k!$ is the number of surjective functions from $[1,n]$ to $[1,k]$, and
$${n \brace k}k!=\sum_{j=0}^{k}\binom{k}{j}j^n (-1)^{k-j} \tag{2}$$
follows by inclusion-exclusion. $(2)$ is a natural counter-part of $(1)$, and it leads to
$$ {n\brace k} x^n = \sum_{j=0}^{k}\frac{x^n j^n (-1)^{k-j}}{j!(k-j)!} \tag{3}$$
then to:
$$ \sum_{n\geq k}{n\brace k}x^n = x^k\sum_{j=0}^{k}\frac{j^k (-1)^{k-j}}{j!(k-j)!(1-jx)}=x^k\sum_{j=1}^{k}\frac{j^k}{k!}\binom{k}{j}\frac{(-1)^{k-j}}{1-jx}.\tag{4}$$
By residues or equivalent techniques, the last sum can be easily checked to be the partial fraction decomposition of $\frac{1}{(1-x)(1-2x)\cdot\ldots\cdot(1-kx)}$, proving the claim.


FAPI initial checked state for #type => radio

Question: Drupal FAPI reference doesn't have a working example for #type=>radio.  How can I indicate that I want the element to be rendered in a checked state?
<code>$form['my_radio_button'] = array(
  '#type' => 'radio',
  '#default_value' => TRUE,
  '#title' => t('Checked by default.'),
);
</code>
I've tried #default_value TRUE, 1, and different combinations of #value, but nothing seems to work.  Thanks!
Comment: I think that's in there so you can format the actual radio button that's presented within a set of radio buttons.  A singular one wouldn't make much logical sense; what I think you are after is a checkbox...
Answer: I may be totally remembering this wrong,  but I'm pretty sure you want to add "checked" as an attribute.
attributes => array("checked")
Comment: Add the 'checked' attribute (with a value) worked for me, thanks!


Contador de pontos, Android Studio/Java

Question: Fiz um joguinho de Jokenpo no Android Studio (funciona normal), porém, não estou conseguindo contar os pontos (vitórias, empates e derrotas).
A parte do "contador" de pontos que está me confundindo e me travando.
"Acredito que tenha que criar os objetos: vitória, empate e derrota... Acredito que tenha que inicializar eles com o valor 0... Mas eu me perco nessa parte (criar, instanciar, etc)... E por fim, imagino que preciso colocar o contador dentro do meu if, else if e else, para toda vez que entrar na condição correta, somar os pontos e mudar o valor na tela (contando os pontos).
Alguém me ajuda, por favor ?
Segue meu código abaixo:
package com.example.joken;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SyncStatusObserver;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

//criando método para elemento pedra
public void selecionandoPedra(View view) {
    this.opcaoSelecionada("PEDRA");
}

//criando método para elemento papel
public void selecionandoPapel(View view) {
    this.opcaoSelecionada("PAPEL");
}

//criando método para elemento tesoura
public void selecionandoTesoura(View view) {
    this.opcaoSelecionada("TESOURA");
}

//criando método usuário vs máquina
public void opcaoSelecionada(String escolhaUsuario) {
    //testando o clique dos botões
    //System.out.println("item que selecionei: " + escolhaUsuario);

    ImageView imagemResultado = findViewById(R.id.img_oponente);
    TextView textoResultado = findViewById(R.id.txt_resultado);

    //criando objetos para contabilizar os pontos
    TextView contadorVitorias = findViewById(R.id.txt_vitoria);
    TextView contadorEmpate = findViewById(R.id.txt_empate);
    TextView contadorDerrotas = findViewById(R.id.txt_derrota);

    //criando objeto e posições do seu array
    int posicoes = new Random().nextInt(3);//0, 1, 2
    String[] opcoes = {"PEDRA", "PAPEL", "TESOURA"};
    String escolhaOponente = opcoes[posicoes];

    //testando a jogada do oponente (aleatório)
    //System.out.println("item que o oponente escolheu rendomicamente: " + escolhaOponente);

    switch (escolhaOponente) {
        case "PEDRA":
            imagemResultado.setImageResource(R.drawable.img_pedra);
            break;

        case "PAPEL":
            imagemResultado.setImageResource(R.drawable.img_papel);
            break;

        case "TESOURA":
            imagemResultado.setImageResource(R.drawable.img_tesoura);
            break;
    }

    if (escolhaUsuario == "PEDRA" && escolhaOponente == "TESOURA" ||
            escolhaUsuario == "PAPEL" && escolhaOponente == "PEDRA" ||
            escolhaUsuario == "TESOURA" && escolhaOponente == "PAPEL") {
        textoResultado.setText("VOCÊ VENCEU !!!\nPARABÉNS !!!\nUHUUUUUUUUUU");
    } else if (escolhaUsuario == "PEDRA" && escolhaOponente == "PEDRA" ||
            escolhaUsuario == "PAPEL" && escolhaOponente == "PAPEL" ||
            escolhaUsuario == "TESOURA" && escolhaOponente == "TESOURA") {
        textoResultado.setText("EMPATOU !!!");
    } else {
        textoResultado.setText("VOCÊ PERDEU !!!\nHAHAHAHA" +
                "\nBEM FEITO, RECEEEEEEEEBA\nPERDEDOR !!!\nLOOOOOOSER");
    }
}
</code>
}
Answer: Você poderia fazer assim:
<code>public class MainActivity extends AppCompatActivity {

   int empapates = 0;
   int vitorias = 0;
   int derrotas = 0;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       TextView edtResultadoVitoria =  (TextView) findViewById(R.id.txt_vitoria);
       TextView edtResultadoDerrota =  (TextView) findViewById(R.id.txt_derrota);
       TextView edtResultadoEmpate =  (TextView) findViewById(R.id.txt_empate);

   }

   // criando método para elemento pedra
   public void selecionandoPedra(View view) {
       this.opcaoSelecionada("PEDRA");
   }

   // criando método para elemento papel
   public void selecionandoPapel(View view) {
       this.opcaoSelecionada("PAPEL");
   }

   // criando método para elemento tesoura
   public void selecionandoTesoura(View view) {
       this.opcaoSelecionada("TESOURA");
   }

   // criando método usuário vs máquina
   public void opcaoSelecionada(String escolhaUsuario) {
       // testando o clique dos botões
       // System.out.println("item que selecionei: " + escolhaUsuario);

       ImageView imagemResultado = findViewById(R.id.img_oponente);
       TextView textoResultado = findViewById(R.id.txt_resultado);

       TextView contadorVitorias = findViewById(R.id.txt_vitoria);
       TextView contadorEmpate = findViewById(R.id.txt_empate);
       TextView contadorDerrotas = findViewById(R.id.txt_derrota);

       // criando objeto e posições do seu array
       int posicoes = new Random().nextInt(3);// 0, 1, 2
       String[] opcoes = { "PEDRA", "PAPEL", "TESOURA" };
       String escolhaOponente = opcoes[posicoes];

       // testando a jogada do oponente (aleatório)
       // System.out.println("item que o oponente escolheu rendomicamente: " +
       // escolhaOponente);

       switch (escolhaOponente) {
           case "PEDRA":
               imagemResultado.setImageResource(R.drawable.img_pedra);
               break;

           case "PAPEL":
               imagemResultado.setImageResource(R.drawable.img_papel);
               break;

           case "TESOURA":
               imagemResultado.setImageResource(R.drawable.img_tesoura);
               break;
       }

       if (escolhaUsuario == "PEDRA" && escolhaOponente == "TESOURA"
               || escolhaUsuario == "PAPEL" && escolhaOponente == "PEDRA"
               || escolhaUsuario == "TESOURA" && escolhaOponente == "PAPEL") {

           vitorias++;
           contadorVitorias.setText(vitorias);
           textoResultado.setText("VOCÊ VENCEU !!!\nPARABÉNS !!!\nUHUUUUUUUUUU");

       } else if (escolhaUsuario == "PEDRA" && escolhaOponente == "PEDRA"
               || escolhaUsuario == "PAPEL" && escolhaOponente == "PAPEL"
               || escolhaUsuario == "TESOURA" && escolhaOponente == "TESOURA") {
           empapates++;
           textoResultado.setText("EMPATOU !!!");
           contadorEmpate.setText(empapates);
       } else {
           textoResultado .setText("VOCÊ PERDEU !!!\nHAHAHAHA" + "\nBEM FEITO, RECEEEEEEEEBA\nPERDEDOR !!!\nLOOOOOOSER");
           derrotas++;
           contadorDerrotas.setText(derrotas);

       }

   }

}

</code>
Eu criei variáveis que são iniciadas com valor 0 e vão ser incrementas quanto as condições do if fossem atendidas, se for empate incrementa o empate, se for derrota incrementa a derrota e no caso da vitória incrementa a vitória depois seta o valor da variável no Edit Text.
Eu sugiro vc colocar as algumas funcionalidades em classe separadas, ajuda na manutenção e na organização ex: colocar uma classe para o usuário onde ficaria a escolha dele (tesoura, papel ou pedra) e outra onde ficaria a escolha da maquinha e na main você deixaria a logica para saber quem foi o vencedor e o placar, Mas isso é só uma sugestão.
Espero ter ajudado! ;)

Contador de pontos, Android Studio/Java


How to use VST (virtual instruments) on a live gig

Question: I am a seasoned keyboardist playing mainly live gigs (Soul, Funk, Rock, Pop). I am very impressed by the capabilities of VST instruments, so I am wondering if it would be possible to use them in a live setup (my equipment today consists of multiple "classical" keyboards).
So, I would like to know

What is the minimum setup to use VST on a live gig, hardware- and software-wise (please supply a complete list, including MIDI and audio stuff etc.)?
Is there any software tailored specifically to live performances? I don't really care about recording.
Optimally, I would like to define presets for two keyboards in advance (e.g. upper keyboard = organ sound A, lower keyboard = piano sound B), and activate them with as little fuss as possible. How can this be done?
How would you control the volume in such a setup? Dragging sliders with the mouse before your solo seems a bit impractical...
Answer:
What is the minimum setup to use VST on a live gig, hardware- and software-wise (please supply a complete list, including MIDI and audio stuff etc.)?

Hardware:

Any system capable of running a plug-in host (PC, laptop, tablet, mobile).
Audio and MIDI interface that is compatible with that system.

Software:

A plug-in host (the program that will host the VST and/or AU and/or other plug-in format).
Virtual instruments.

The minimal specs of the system will depend on the virtual instruments that you'll use. A simple subtractive synth will run in almost anything, but a robust sampler might need more RAM and disk space. You'll need to consult the minimum specs of your virtual instruments for this detail.
The minimal specs will also depend on how many instruments and processes you want to run at the same time. Unless you want to go nuts, something like Intel Core i5-4690K and 8GB 1600Mhz DDR3 RAM should be more than enough. You might need a lot less than this, but that setup would leave a reasonable room for expansion if you ever feel like going more crazy.
Test your vst setup with different systems, see if the systems can handle it (check latency, CPU usage, and if any artifacts are being induced), and write down the specs of those systems. This will give you a good idea of what you need and what to expect from different specs. You want your setup to run absolutely flawlessly: no artifacts, ultra low latency, and no CPU usage peaking near the limit.
Choosing the correct system for your needs (Mac, PC, Mobile, Laptop, OSX, Windows, Android, iOS, Linux, processor, RAM, etc) is crucial here.
Also, if you are very serious about this, you might want to consider having a backup system in case your main one fails. Consider having more than one if you can afford it.

Is there any software tailored specifically to live performances? I don't really care about recording.

There are many options, but I think the best one right now (and by far) is Ableton Live. It was tailored for live performance, everything is agile and intuitive. It is so much more than a plug-in host, so it leaves a lot of room for creativity. "Can we do this live?" With Live the answer is almost always "yes". Even if you imagine a device that doesn't exist, you can build it with MAX for Live.
One think that I love about Live for live performances is the Instrument Rack. You can layer many instruments in one single track, and have macros control different parameters from different instruments at once. This can be done in most plug-in hosts (in the form of multiple tracks and MIDI mapping), but nothing comes close to how fast, easy, and live-friendly Live implements it.
Check other options (BitWig and Mainstage come to my mind), but chances are that Ableton Live is exactly what you want.

Optimally, I would like to define presets for two keyboards in advance (e.g. upper keyboard = organ sound A, lower keyboard = piano sound B), and activate them with as little fuss as possible. How can this be done?

This is very easy to do, and most VST hosts can handle it (I can't think of one that wouldn't). Exactly how to do it will depend on your host, but it will almost always be more or less like this:
Make each keyboard send MIDI from a different channel, and make each virtual instrument receive MIDI only from the channel you want. Set the organ sound to receive MIDI only from channel 1, and set the piano sound to receive MIDI only from channel 2. Set upper keyboard to send MIDI through channel 1, and set lower keyboard to send MIDI through channel 2. Upper keyboard -> MIDI channel 1 -> organ sound, lower keyboard -> MIDI channel 2 -> piano sound.
To activate/deactivate you arm/unarm the MIDI track. You can do this from a control surface, if your keyboard has buttons that send MIDI you can have each keyboard have its own activate/deactivate button, which will be mapped to the arm/unarm function of the MIDI track.

How would you control the volume in such a setup? Dragging sliders with the mouse before your solo seems a bit impractical...

You can do it from a control surface. If your keyboards don't have knobs or sliders you can get a control surface with knobs and/or sliders, and assign them to whatever you want, including volume.
If you plan to have a lot of tracks, you'll make your life a lot easier by getting something with motorized faders. Something like Bheringer's BCF2000 or X-Touch.
Comment: Forget about the BCF2000. It's crap. The X-Touch series has the faders, knobs and displays from the X32 series, which are *very* good!
Comment: @JörgWMittag Yeah I've noticed mixed opinions of the BCF2000. Mine has lasted several years, and still works great, but I've also known of defective devices. This contrast seems to be common in low-end devices (the BCF2000 might be the cheapest control surface with motorized faders). There's a lot of options in the control surface market, and it's worth to invest in the mid to high end equipment.
Comment: +1 for Ableton.. it's great for live performance. As for a specific computer, if it's in your budget the Macbook Pro is pretty much the standard for live music these days as it's pretty bulletproof (this coming from a PC guy). Of course you can also use a PC laptop if the specs are sufficient, it just isn't as popular for live music. I haven't tried it yet, but there are a lot of good synth apps out there for iOS so an [iPad](https://www.youtube.com/watch?v=VDJOhfyWYUQv) might be enough for your needs.
Comment: You may want to check out the video on how Ableton Live is used for Depeche Mode live performances as well: https://www.youtube.com/watch?v=YvuCp1lZIBw
Comment: Don't forget the latency of your chosen audio interface can make a big difference here.  For years I played around with VST's through my standard sound card only, and got quite annoyed with latencies ranging from 50-200ms.  With a nice firewire interface I have managed around 3-5ms (depending on sample rate); it is like night and day.  Not to say you have to use firewire - that's nearly obsolete now - but make sure you do some homework on whatever you pick up.
Answer: I don't have much experience in this area, but I can recommend Apple Mainstage, a $30 app for Macs that works with any number of MIDI controllers attached to a single Mac computer.
Mainstage does everything you ask for in your answer except work with VSTs. If that's a dealbreaker for you, you will need to look for different software, unfortunately. Instead of using VSTs, Apple's music software uses Audio Units, which are a different standard for software synthesizers. Mainstage comes with several AUs and hundreds of presets for them, and many major synthesizers like Massive and FM8 are available as AUs.
Using Mainstage, a minimal, complete setup for a live performance would be:

The MIDI keyboard you play
A computer running OSX
An amplifier or speaker
A USB or MIDI cable between the keyboard and computer
An audio cable between the computer and speaker

Mainstage can't record what you perform, but you said in your answer that you're not looking for that functionality. The software lets you configure the software synths you're controlling, then play them live.
Mainstage lets you set up multiple software synths configured in different ways ahead of time, then switch between them quickly during performances. I believe that you can set Mainstage up so that it will switch between configurations based on MIDI signals, so you wouldn't even need to reach over to your computer to do so.
And finally, Mainstage also lets you control parameters like volume and panning using MIDI controllers as well as by using the computer directly.

I'm not sure what alternatives are available for Windows, but I'm willing to bet that they exist, and that they have exactly the same functionality as Mainstage does. I would be very surprised, for example, if any serious live performance software required a more elaborate setup than what I described or didn't have the ability to switch between instruments and control parameters using MIDI.
Comment: My answer recommends one piece of software. I'm only recommending Mainstage because it's the only software like this that I'm familiar with, not because it's necessarily the best. It's Mac-only and doesn't work with software synths, but I bet some looking around will find PC alternatives. For example, [this thread on Reddit](http://www.reddit.com/r/WeAreTheMusicMakers/comments/194flx/alternatives_to_mainstage_for_live_performance/) discusses some alternatives.
Answer: You want Cantibile. Or Forte (Brainspawn not the notation Forte...).  They will not only host your VSTs with whatever patches you want for each song and create signal chains for VST EFX, But they will also let you create Set Lists, trigger background Audio files, and have cool features like programmable midi keys so you can trigger things like start and stop as well as step forward or back thru your set list all from your keyboard so your laptop doesn't even have to be visible on stage.  I have both and slightly favor Cantibile, but compare features for your purposes.
All you need is a good audio interface to get good quality audio out to your amplification.  Tons of USB boxes will do it for you.  If you are running lots of instruments and have a sound man, you may want an interface with more pairs of outputs than just a single stereo pair so your sound man can tweak levels separately.  Shop accordingly and read the reviews online first with a focus on reliability for the interface(s) that seem like a fit for you.
You'll set volume levels via slider for each VST separately, including any audio tracks being triggered.  Plus an overall volume.  Once you get everything right song to song it stays there so there shouldn't be a need to tweak other than at first when you set up for a new gig.
I run two MIDI channels from two keyboards, as well as a MIDI guitar and a MIDI EWI AND GET EXACTLY WHAT I WANT FOR IT ALL ON EVERY SONG WITH NO FUSS.
This is what you want software wise, it's not overkill like some DAW with a million other features you won't use unless you're triggering tons of loops like doing an Ableton Live performance.
I run everything from it from Omnisphere (best thing on the planet in my opinion), Trilian, Iris, Razor, all the Native Instruments, the Cakewalk synths, Alchemy, Hans Zimmers Zebra version, and even old ones like the Korg stuff such as the M1...
It just works.
Good luck!
Answer: It's been several months since "googol analytics" posted a question regarding using VSTs in a live setting. If you're still looking for a solution, take a look at the Muse Research Receptor standalone unit.  This is a dedicated unit for VST plugins. I have a couple of keyboard midi controllers hooked up to the unit.  I use it on all my live gigs.  Go to the Muse Research website to get more info on the unit.
Answer: Apple Mainstage will drive plug-in instruments. Most VSTs on the OS X platform are also delivered in the form of Audio Units. These are directly supported in Mainstage.


how do i highlight jqgrid row when new record added in a grid

Question: I have a flagger table in which manually records inserted. I want to reload jqgrid after every 2 min and when new records added then wants to highlylight it. How to do this?
Answer: Your question consist from two parts: 1) reloading the grid every 2 min and 2) highlighting of the new added record.
For grid reloading you can easy implement with respect of setInterval JavaScript function. Here you can find an code example. If you use editing you should not refresh the grid during a row is in editing. Simple setting global boolean variable at the beginning of editing and clearing at the end of editing can help to solve the problem. Inside of function used in setInterval you can test the global variable and skip the grid reloading if the grid is in editing.
To highlight the row you can use jQuery UI effect with "highlight" parameter. See here.
Comment: 1) reloading the grid every 2 min is achived. thankx for it. 2)In second task. I checked the record count and save it in TempData["recordCount"], when new record added then i checked it with TempData record variable, and if TempData["recordCount"] is < to recordCount from db means that new data has been added in the table. Now, how can i change the rows of newly added record in jqgrid. I found the code of highlight but not understanding where i have to place it and how?
Comment: @farhan: If I understand you correct now you mean that you want not just highlight "new records added" (added on the client side), but the rows **added on the server side**. In the case I would suggest you to use `userdata` part of the server response. It'is just *any additional data* which will be send from the server to jqGrid. Inside of `loadComplete` you can read the information and highlight or select (in case of `multiselect:true`) the some rows.
Comment: @farhan: See [here](http://stackoverflow.com/questions/3848815/how-to-read-userdata-in-jqgrid/3849513#3849513), [here](http://stackoverflow.com/questions/3564898/jqgrid-programatically-select-grid-row/3571392#3571392) and [here](http://stackoverflow.com/questions/3128837/json-and-jqgrid-what-is-userdata/3128934#3128934) for additional information.


HIde node in view when field message is equal

Question: Can I hide a node in a view when they have a specific message? Like, if the message: "Please don't show this node" is equal with specific field content then hide him in the view, else show him?
Is there an option for this?
Comment: No I don't think you'll find an option for that. What do you mean by 'message' exactly?
Comment: I have jQuery countdown now, if this is ended, there is an message. This shows "You are to late". This works all, but I created a view also and this take al the nodes from a content type. What I want is that the node is not showing up in this view when the jQuery countdown is ended. But I have no idea how.
Comment: Ok...what method are you using to populate the field in the backend when the jQuery countdown finishes? AJAX I would guess, but is it part of the jQyery countdown module or have you implemented it yourself?
Comment: It is an Auction module with a jQuery countdown. When the auction ended hide the node in the view.
Comment: If the countdown is based on the start / end date of the auction, you should be able to have the View filter on auctions that are only happening between those dates.
Comment: Could you tell me how?
Answer: Just an idea if you can try...
As per my point of view you may try to use flags with the timer? whenever the countdown is ended invoke a flag and you can use this flag in views.If the flag is invoked do not show the content else it will be visible.


Nginx real_ip module doesn't work in some conditions

Question: So I have Nginx proxy and some servers running behind it. I need to know real users IP not proxy, so I using real_ip module. Everything is working as expected, but if I configure vhost like subdomain.domain.com backend getting Nginx proxy IP.
Here is my Nginx config sample
<code>set_real_ip_from  192.168.2.0/24;
real_ip_header    X-Forwarded-For;
real_ip_recursive on;

upstream srv1 { server 192.168.2.12:80; }

server {

        listen       80;
        server_name  dev.somedomain.com;

        location / {
         proxy_pass  http://srv1;
       }

}

server {

        listen       80;
        server_name  somedomain.com;

        location / {
          proxy_pass  http://srv1;
        }

}
</code>
So if I go to somedomain.com backend receiving real IP, no problems here.
But for dev.somedomain.com backend receiving proxy IP!
And this is only shortened example, same situation with different domains and subdomains...
I just don't see whats is wrong here...
Comment: Requests to somedomain.com are going directly to upstream. Requests to the subdomain are going to nginx. Upstream has to process the X-Forwarded-For header for it to get the original client ip.
Comment: I don't get it, I mean I know this, but I doing it already in first 3 lines of example...Or I don't get what you tried to say.
Answer: Ok so it seams my mistake, everything is fine with this configuration, I need extra step in backend to complete my task, as for specific example I needed to set option in backend server (litespeed web server) option "Use Client IP in Header" I must be accidentally disabled it.


MongoDB, how to group documents

Question: My collection has data like this:
[
  {
    "code": 1,
    "location": "1 QUEEN STREET",
    "_id": "1",
  },
  {
    "code": 1,
    "location": "2 KING STREET",
    "_id": "2"
  },
  {
    "code": 2,
    "location": "1 QUEEN STREET",
    "_id": "3"
  },
  {
    "code": 2,
    "location": "2 KING STREET",
    "_id": "4"
  },
  {
    "code": 2,
    "location": "2 KING STREET",
    "_id": "5"
  }

]

Looking for out that would group documents by "location" and have a set of codes added to each document that contains the count for each unique code.
Output would be like this:
[
  { "location": "1 QUEEN STREET", "codes":["code1":1,"code2":1]},
  { "location": "2 KING STREET", "codes":["code1":1,"code2":2]}
]

I tried queries like these:
aggregate([{ $group : { _id : "$location", codes: { $addToSet: "$code",count: { $sum: 1 } } } }])

aggregate([{ $group : { _id : "$location", codes: {$group:{_id:"$_code",count:{$sum :1}}} } }])

Thanks for any help.
Comment: Please put hole document here, not just array.
Comment: Your expected output is not a  good one how about making `codes` an array of values instead of array of subdocuments?
Comment: @Styvane yes an array of values would be fine. I can edit the question to reflect your feedback.
Comment: @VaibhavPatil sorry, ignore the [  ]   array,   it should just be each { }  one is a document not an array of documents
Answer: aggregate(
[
    { $group : {
            _id : { location: "$location", code: "$code"},
            count: { $sum:1 }
        }
    },
    { $group: {
            _id: "$_id.location",
            codes: {$addToSet: {"code":"$_id.code", "count":"$count"}}
        }
    },
    { $project: { location: "$_id", codes: 1, _id: 0}},
]
)

Result:
{ "codes" : [ { "code" : 1, "count" : 1 }, { "code" : 2, "count" : 1 } ], "location" : "1 QUEEN STREET" }
{ "codes" : [ { "code" : 1, "count" : 1 }, { "code" : 2, "count" : 2 } ], "location" : "2 KING STREET" }

Note: Youre desired output cannot be achived, thhere is a format error on the elements in the list, you should use a dict, {}.
Answer: You can use two $group steps inside an aggregate operation. In first you are counting the number of docs per code and per location. Next one you only look at location, and $push the count along with the corresponding code into an array
[
{$group: {_id: {code: '$code', location: '$location'}, count: {$sum: 1}}},
{$group: {_id: '$_id.location', codes: {$push: {code: '$_id.code', count: '$count'}}}}
]

MongoDB, how to group documents


Generating a timeline in LilyPond

Question: I would like to insert a timeline at the top of my LilyPond score that shows every second. This could look something like this:
<code>#(set-default-paper-size "a3landscape")
#(set-global-staff-size 18)

\paper {
indent = #0
ragged-right = ##f}

#(define timeline '((snare default #f  3)))

    click = \drummode {
    \set DrumStaff.drumStyleTable = #(alist->hash-table timeline)
    {
    sn8^\markup \center-align "00:00"
    8^\markup \center-align "00:01"
    8^\markup \center-align "00:02"
    8^\markup \center-align "00:03"
    \pageBreak
    }
    }

    <<
    \new DrumStaff \with {
      instrumentName = "Timeline"
      shortInstrumentName = "time"
      \override StaffSymbol.line-count = #1
      \override BarLine.bar-extent = #'(-1 . 1)
      \omit Voice.BarLine
      \hide NoteHead
      \hide Flag
      \hide Beam
      \omit Clef
      \omit TimeSignature
      \hide LedgerLineSpanner
      \omit BarNumber
    }
    { \click }
    >>
</code>
Instead of inserting each second manually into the file (or using Python to generate the content of the "click" variable [see above], i.e. a long text file that I would then insert into LilyPond), I would like to generate a function that outputs ascending seconds (in the format mm:ss, where m stands for minute and s for second - 02:23 means: 2 minutes and 23 seconds) and places them above the notes.
So a function where I say, for example, "Start at minute 00:00 and go in one-second increments up to minute 10:00 and write the seconds above my note stems."
My Scheme knowledge is far too limited for me to be able to write something like that. But maybe someone here will be kind enough to help me out?
I would be extremely grateful for any tips!
Answer: Maybe something like this?
<code>#(set-default-paper-size "a3landscape")
#(set-global-staff-size 18)

\paper {
indent = #0
ragged-right = ##f}

#(define timeline '((snare default #f 3)))

clickrange =
#(define-music-function (from to step) (number? number? number?)
   #{
     $@(map (lambda (time)
              (let ((minutes (quotient time 60))
                    (seconds (remainder time 60)))
                #{
                  \drummode {
                    \scaleDurations #step {
                      sn8\tweak self-alignment-X #CENTER
                         ^\markup #(format #f "~2,'0d:~2,'0d" minutes seconds)
                    }
                  }
                #}))
            (iota (floor (/ (- to from) step)) from step))
   #})

\layout {
  \context {
    \DrumStaff
    \type Engraver_group
    \name TimeStaff
    \alias DrumStaff

    \override StaffSymbol.line-count = #1
    \override BarLine.bar-extent = #'(-1 . 1)
    \omit Voice.BarLine
    \hide NoteHead
    \hide Flag
    \hide Beam
    \omit Clef
    \omit TimeSignature
    \hide LedgerLineSpanner
    \omit BarNumber
    drumStyleTable = #(alist->hash-table timeline)
  }
  \context {
    \Score
    \accepts TimeStaff
  }
}

<<
  \new TimeStaff \with {
    instrumentName = "Timeline"
    shortInstrumentName = "time"
    \textLengthOn
  }
  {
    \clickrange #0 #(* 2 60) #1
    \clickrange #(* 2 60) #(* 4 60) #2
  }
>>
</code>
It would also be possible to create a custom engraver for this. This has the advantage that Lilypond would be able to determine the actual time from Metronome markings.

Generating a timeline in LilyPond


Rigid structure of $\operatorname{Vec}(G)$

Question: Apparently if $G$ is a finite group $\operatorname{Vec}(G)$ is a Rigid monoidal category (whereby I mean the category of graded vector spaces over a group $G$). I struggle to see why it is rigid. It is easy to see that that some objects are rigid by taking the dual of for example $V_g$ (Where I mean the vector space $V$ localized at $g$) to be $V^*_{g^{-1}}$ and the evaluation and coevaluation to be the same as that in Vec. However when you take direct sums of these elements I don't see how you can extend this rigidity as you won't have something localized at $1$. How could you extend this to a rigid structure on all of the category?
Comment: I suppose you mean finite-dimensional vector spaces.
Comment: the monoidal category of graded vector spaces over a group $G$
Answer: Just use $0$ on the components that don't have grading $1$ when defining the (co)evaluation.  For instance, if $V=V_g\oplus V_h$ is nontrivial in two degrees $g$ and $h$, define the dual $V^*$ to be $V^*_{g^{-1}}\oplus V^*_{h^{-1}}$ where $V^*_{g^{-1}}=(V_g)^*$ and $V^*_{h^{-1}}=(V_h)^*$.  The evaluation is then the map $V\otimes V^*\to k$ which is the evaluation map for $V_g$ on $V_g\otimes V^*_{g^{-1}}$, the evaluation map for $V_h$ on $V_h\otimes V^*_{h^{-1}}$, and simply $0$ on the other summands $V_g\otimes V^*_{h^{-1}}$ and $V_h\otimes V^*_{g^{-1}}$.  Similarly, the coevaluation is the map $k\to V\otimes V^*$ which is given by the coevaluations for $V_g$ and $V_h$ on two of summands of $V\otimes V^*$ and is $0$ on the others.


Grid Problem Proof

Question:
I have a 2x2 grid square say, I can fit a shape like this:

  Such that there is one missing square. I can arrange this in any way so that the missing square can be located anywhere. I can do the same for a 4x4 or a 8x8 or a 16x16 square. In fact, I can do this for any square $2^k$ x $2^k$ for integer $k$ (positive). Prove the previous statement by any method.

Supposing it holds for a $2^k$x$2^k$ square. Prove the property for: $4(2^k)\times$ $(2^k)$
I realized that:
$4(2^k)\times(2^k) = (2^k)\times(2^k) + (2^k)\times(2^k) + (2^k)\times(2^k) + (2^k)\times(2^k) $
Meaning if the missing spot was in either of the far corners (different corners) another square of $4$ can be formed, of which, a trimino can fit, hence leaving one blank square.
(1) Is this an accurate proof by induction?
(2) Is there a way to do this using contradiction?
Comment: The sentence starting "Meaning if..." is not clear, especially what you mean by "another square of $4$ can be formed." Could you clarify? And do you really need to use induction? You could easily do a proof by cases: the orientation in your graph works for all unit squares not on the right or top borders of the large square, and you can use other orientations for those.
Answer: The sequence
"Meaning if the missing spot was in either of the far corners (different corners) another square of 4 can be formed, of which, a trimino can fit, hence leaving one blank square."
is not a proof. Note that the missing square can be ANYWHERE.
Here is a Hint:
To prove the inductive step $P(n) \Rightarrow P(n+1)$ do the following:
Divide the $2^{n+1} \times 2^{n+1}$ square in $4$ squares of size $2^n \times 2^n$.
The missing tile is in one of these four. By $P(n)$ this can be tiled by your "chair" shape.
Now, you can put another chair in such a way that it covers one corner from each of the remaining three $2^n \times 2^n$ squares. Now you can use again $P(n)$.
I suspect that this is what you were trying to describe in the above proposition, but the way it is written it doesn't say this....
Comment: this is what I was trying to say. but if the missing space is in the middle then $4(2^k x 2^k)$ cannot have only one missing spot.
Comment: @Lebes What do you mean in the middle?

Grid Problem Proof


Checking file existence on FTP server

Question: Is there an efficient way to check the existence of a file on a FTP server? I'm using Apache Commons Net. I know that I can use the listNames method of FTPClient to get all the files in a specific directory and then I can go over this list to check if a given file exists, but I don't think it's efficient especially when the server contains a lot of files.
Answer: listFiles(String pathName) should work just fine for a single file.
Comment: Thanks for your fast answer, I check the FTPFile[] array length to know if the file exists.
Comment: It may return a lot  of data if `pathName` is a directory containing a lot of files.
Answer: Using a full path to a file in listFiles (or mlistDir) call, as the accepted answer shows, should indeed work:
String remotePath = "/remote/path/file.txt";
FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);
if (remoteFiles.length > 0)
{
    System.out.println("File " + remoteFiles[0].getName() + " exists");
}
else
{
    System.out.println("File " + remotePath + " does not exists");
}

The RFC 959 in the section 4.1.3 in the part about the LIST command says:

If the pathname specifies a file then the server should send current information on the file.

Though if you are going to check for many files, this will be rather ineffective. A use of the LIST command actually involves several commands, waiting for their responses, and mainly, opening a data connection. Opening a new TCP/IP connection is a costly operation, even more so, when an encryption is used (what is a must these days).
Also LIST command is even more ineffective for testing an existence of a folder, as it results in a transfer of a complete folder contents.

More efficient is to use mlistFile (MLST command), if the server supports it:
String remotePath = "/remote/path/file.txt";
FTPFile remoteFile = ftpClient.mlistFile(remotePath);
if (remoteFile != null)
{
    System.out.println("File " + remoteFile.getName() + " exists");
}
else
{
    System.out.println("File " + remotePath + " does not exists");
}

This method can be used to test an existence of a directory.
MLST command does not use a separate connection (contrary to LIST).

If the server does not support MLST command, you can abuse getModificationTime (MDTM command) or getSize (SIZE command):
String timestamp = ftpClient.getModificationTime(remotePath);
if (timestamp != null)
{
    System.out.println("File " + remotePath + " exists");
}
else
{
    System.out.println("File " + remotePath + " does not exists");
}

This method cannot be used to test an existence of a directory.
Comment: Please note that as of 3.8.0 of Apache commons-net, both `mlistFile` and `getModificationTime` will return `null` if the used commands (MLST or MDTM) are not recognized by the FTP server (though hiding the possible existing of a file whilst returning `null`): https://github.com/apache/commons-net/blob/rel/commons-net-3.8.0/src/main/java/org/apache/commons/net/ftp/FTPClient.java#L3010 https://github.com/apache/commons-net/blob/rel/commons-net-3.8.0/src/main/java/org/apache/commons/net/ftp/FTPClient.java#L1857
Answer: The accepted answer did not work for me.
Code did not work:
String remotePath = "/remote/path/file.txt";
FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);

Instead, this works for me:
ftpClient.changeWorkingDirectory("/remote/path");
FTPFile[] remoteFiles = ftpClient.listFiles("file.txt");

Comment: That's just a peculiarity of your particular FTP server. For majority of servers, there's no difference between the two code snippets.
Answer: public boolean isDirectory(String dstPath) throws IOException {
    return ftpsClient.changeWorkingDirectory(dstPath);
}

public boolean exists(String dstPath) throws IOException {
    if (isDirectory(dstPath)) {
        return true;
    }
    FTPFile[] remoteFiles = ftpsClient.listFiles(dstPath);
    return remoteFiles != null && remoteFiles.length > 0;
}

Comment: One wouldn't expect a function like `exists` to have side effects.
Comment: I would like to always use absolute path instead of working directory
Comment: Fine. But please clearly acknowledge this constraint in your answer.

Checking file existence on FTP server