How to save new line from android?

Question: I am saving data from edit textbox and getting that to save into pdf....It works fine but if i write text into multiline....it takes as single line...and make pdf file with single line...so how can i get the new line to save into pdf??? Here is code which send data for save data...
Intent i = new Intent(AddText.this,GetText.class);
i.putExtra("data",editText.getText().toString());
startActivity(i);

And in next page i am getting data....
String data = getIntent().getExtras().getString("data");

Answer: Try this:
Intent i = new Intent(AddText.this,GetText.class);
i.putExtra("data",(editText.getText().toString()).replaceAll("\\n", "\n"));
startActivity(i);

Answer: use \n whereever you want to use new line. in your code.
for suppose if you want to save pdf with name Android\npdf then you must type like this only and you can get string
Comment: ok....but i am writing content to edit textbox with multline...that i am getting into data...and that data i am saving into pdf file...so now where i have to use `\n`

How to save new line from android?


Is it possible to access ASP.NET anonymous profile for a logged in user?

Question: The ASP.NET membership supports anonymous users and logged in users.
If you call FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); with a true for createPersistentCookie then the user will be logged in automatically when they revisit your site - even after closing the browser. If you don't enable this 'remember me' feature, then the anonymous cookie will still be around when the user visits your site again.
I'd like to do be able to store information in the user's anonymous profile when they are logged in. i.e. I don't want them to remain authenticated on the site if they go away and come back, but I'd still like be able to track certain things - like perhaps a visitCount property in the anonymous profile.
Is there any way to access a user's anonymous profile when they are authenticated. The two cookies exist so it should be possible. I don't want to reinvent half the wheel!
ps. I realize that tracking is skewed if multiple users use the system but thats fine.
Answer: Sure. Simply check the AnonymousId property of the Request and built a ProfileBase.
var anonymousID = Request.AnonymousID;
if (anonymousID != null)
{
    var profile = ProfileBase.Create(anonymousID, false);

    int counter = (int)profile["counter"];
    profile["counter"] = ++counter;
    profile.Save();
}


How to hide web server name and openssh version on linux when scanning server ports?

Question: How to hide web server name and openssh version on linux when scanning server ports?
when i nmap'ed(nmap -A -T4 192.168.40.12) ip server from the outside, the one shows:
Starting Nmap 4.62 ( http://nmap.org ) at 2009-11-05 14:11 IRST
LUA INTERPRETER in nse_init.cc:763: /usr/share/nmap/scripts/robots.nse:4: module 'http' not found:
no field package.preload['http']
no file '/usr/share/nmap/nselib/http.lua'
no file './http.lua'
no file '/usr/local/share/lua/5.1/http.lua'
no file '/usr/local/share/lua/5.1/http/init.lua'
no file '/usr/local/lib/lua/5.1/http.lua'
no file '/usr/local/lib/lua/5.1/http/init.lua'
no file '/usr/lib/nmap/nselib-bin/http.so'
no file './http.so'
no file '/usr/local/lib/lua/5.1/http.so'
no file '/usr/local/lib/lua/5.1/loadall.so'
SCRIPT ENGINE: Aborting script scan.
Interesting ports on 192.168.40.12:
Not shown: 1710 closed ports
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     **OpenSSH 3.9p1** (protocol 1.99)
53/tcp   open  domain  dnsmasq 2.47
80/tcp   open  http    **Apache httpd**
222/tcp  open  ssh     **OpenSSH 3.9p1** (protocol 1.99)
8081/tcp open  http    CherryPy httpd 2.3.0
MAC Address: 00:10:F3:0F:59:B7 (Nexcom International Co.)
Device type: firewall
Running: IPCop Linux 2.4.X
OS details: IPCop firewall 1.4.10 - 1.4.15 (Linux 2.4.31 - 2.4.34)
Network Distance: 1 hop

OS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 8.032 seconds

I modify httpd.conf and change two line
ServerSignature Off
ServerTokens Prod

and restart apache server but it still shows me apache name
Could any one help me on this!
Comment: It would be better just to make sure you have the latest stable version of Apache than go through this much trouble trying to hide the service name. Even without it, good scanners can detect what the software is (particularly something well-used like Apache or IIS) just based on how it responds to requests.
Answer: For the OpenSSH try following:
me@lappy:~# ncat 192.168.0.222 22
SSH-2.0-OpenSSH_5.1p1 Debian-3ubuntu1

Cool no exploits or anything but lets edit it just for fun. First lets make a copy of sshd to work with.
root@mohsen-desktop:~# mkdir tmp
root@mohsen-desktop:~# cd tmp
root@mohsen-desktop:~/tmp# cp /usr/sbin/sshd .

Now let modify it.
root@mohsen-desktop:~/tmp# hexedit sshd

Ok a blue window should have popped up, now look at the bottom and notice the commands. We want to use search so press control+w make sure "Search for text string" is in white hit enter. Now type "OpenSSH" hit enter and you will be directed to the exact part you need to modify.
It will look like this, just change everything that is in red to 0 and you will end up with what i have below. If you want to type something else Press TAB and type what you want into the ascii part, just remember there is no backspace.
00053FE0 6E 64 2D 6C 69 6E 65 00 4F 70 65 6E 53 53 48 5F nd-line.OpenSSH_
00053FF0 35 2E 31 70 31 20 44 65 62 69 61 6E 2D 33 75 62 5.1p1 Debian-3ub
00054000 75 6E 74 75 31 00 25 73 2C 20 25 73 0A 00 4B 52 untu1.%s, %s..KR

It should now look like this.
00053FE0 6E 64 2D 6C 69 6E 65 00 4F 70 65 6E 53 53 48 00 nd-line.OpenSSH.
00053FF0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00054000 00 00 00 00 00 00 25 73 2C 20 25 73 0A 00 4B 52 ......%s, %s..KR

When your done hit control+x to save it, and give it a launch, remember it requires the exact path.
root@mohsen-desktop:~/tmp# /root/tmp/sshd
root@mohsen-desktop:~/tmp# ncat localhost 22
SSH-2.0-OpenSSH

Just make sure you can connect to it and your good to go.
killall sshd
rm /usr/sbin/sshd
mv /root/tmp/sshd /usr/sbin/

For hide web server name you should compile source apache and edite conf file in it.
Comment: While it is a hack, it does answer the question
Answer: I don't believe you can hide the server type from NMap, as it's clever enough to detect software type from handshake negotiation, fault handling etc. As for OpenSSH, from the FAQ:

2.14 - Why does OpenSSH report its version to clients?
OpenSSH, like most SSH
implementations, reports its name and
version to clients when they connect,
e.g.
SSH-2.0-OpenSSH_3.9
This information is used by clients
and servers to enable protocol
compatibility tweaks to work around
changed, buggy or missing features in
the implementation they are talking
to. This protocol feature checking is
still required at present because the
SSH protocol has not been yet
published as a RFC and more
incompatible changes may be made
before this happens.

If you really want to patch SSH to prevent version display, here's how to do it (personally untested), and here's a description of your mentality (security through obscurity, pros and cons) and here's why I think it's no good and why Bruce Schneier thinks it's good sometimes and bad the rest of the time.
Comment: Could you please update the first link? It throws a 404.
Answer: The sshd version string is not configurable at runtime.
You can change it by recompiling OpenSSH after modifying the SSH_VERSION #define, or where it is used in sshd.c :
  snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s%s", major, minor,
      SSH_VERSION, newline);

Answer: It's not a configurable option. In both cases you would need to make changes to the source code.
OpenSSH relies on the version banner in order to negotiate certain features and quirks between the server and client. You can find older patches for such changes like this which you may be able to adapt for newer releases.
For Apache there has been some discussion in the past and more recently about an Off option to ServerTokens which would remove the product name. But I believe it's been vetoed each time. Again you may wish to use or adapt some available patches but you would be out there on your own.
Frankly you would remain more secure, and indeed more reliable than deviating from the release, by just ensuring that the software gets updated when required. Hiding this information might put off some drive-by attackers. But it won't do you any good against blind scripted or more determined attacks.
Answer: For the OpenSSH try following:
In the /etc/ssh/sshd_config file add string:
Banner /etc/ssh/banner

And in the /etc/ssh/banner type something strange, like "MS Telnet Service 1.2" :)
For the Apache service you could try following technique:
In the httpd.conf file write this instructions:
ServerTokens ProductOnly
ServerSignature Off

But after you will view an "Apache" string, without version. If you want more security for the Apache google for the "mod_security".
Good luck!
Comment: @Sergey Kuznetsov setting the banner for sshd doesn't help, because an attacket can see the version, using ssh -vvv name_of_your_server.
Answer: It doesn't seem to recognize the Apache version. However, there are many ways to tell it's Apache, e.g. by looking at server error messages.
Answer: What romandas said.  The bad guys will pwn you if you have an accessible, vulnerable server, regardless of whether you attempt to disguise the software version.  You'll get much better results by:

turning on privilege separation in sshd (UsePrivilegeSeparation — should default to yes)
disabling password login for ssh (PasswordAuthentication no and UsePAM no)

unless you require PAM, then it's more configuration — but you probably don't

making sure Apache is chrooted to nobody or equivalent (User and Group directives in httpd.conf)

and keeping everything up-to-date.  Especially apache.


Cannot publish Website with web reference - SGEN error

Question: I have website (MVC) with one Web reference. Build and run in VS working. But when I tried to publish to disk I get error:
SGEN: error: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
If I remove web reference then publishing working. Where can be a problem? Thanks.
Answer: Ok, I found solutions. I am using Visual Studio 2013. I update to update version 4. After that, publish working perfectly.
Comment: Another solutions:
Disable generate serialization assembly in project properties in build tab.


Can't correctly reference bundle in EntityFieldQuery, field_get_items

Question: I'm using EntityFieldQuery in an attempt to query for specific field values (dates in an event db) then perform some analysis on them.
I've gotten far enough to correctly query and return specific nodes as a result but am getting stuck on field_get_items - I can't get the actual field values out. It appears I am not passing the necessary parameters of the bundle to the function.
Where am I going wrong?
Drupal throws this error on the last line of code starting w $output
"EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7734 of /home4/xxxxx/public_html/xxxxxx/xxxxxx/includes/common.inc)."
Here's my code:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_date', 'value', 'NULL', '!=');
$result = $query->execute();

if (isset($result['node'])) {
  $stories = $result['node'];

  // Get all fields attached to a given node type
  $fields = field_info_instances('node', 'event');

  // Get id of body field
  $field_id = $fields['field_date']['field_id'];

   //echo $field_id... testing, works;

  // Attach a field of selected id only to get value for it
echo field_view_field('node', $stories, 'field_date');

  //Get values of our node field
  $output = field_get_items('node', $stories, 'field_date');
}

I get an error on the last step
Answer: A couple of things...first one is you haven't loaded the nodes. If you change
$stories = $result['node'];

to
$stories = node_load_multiple(array_keys($result['node']));

You'll have the fully loaded node objects available.
The other two things are both related; field_view_field() and field_view_value() both accept a single entity; currently you're trying to pass an array, which it won't like.
A simple loop will fix that:
foreach ($stories as $story) {
  $output[] = field_view_field('node', $story, 'field_date');
}

And similar for field_get_items().
Comment: Thank you for the suggestion, I tried it and still receive the same "Missing bundle property on entity of type node" error. Is it possible that I'm not declaring the EntityFieldQuery correctly?

This content type definitely exists, and I am able to get a result, just not access the field values.
Comment: I edited about a minute ago, any chance you haven't seen that yet?
Answer: If you want to use my sandbox you can use EFQE to directly get field data.
$query = new EntityFieldQueryExtra();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->propertyCondition('status', 1)
  // Use inner join so the != NULL condition can be skipped.
  //->fieldCondition('field_date', 'value', 'NULL', '!=');
  ->getFieldValue('field_date', 'value', 'INNER');
$result = $query->executeEntityBuild();

if (isset($result['nodes'])) {
  $nodes = $result['nodes'];
  foreach ($nodes as $node) {
    echo $node->field_date['und'][0]['value'];
  }
}

No entity load was done in the above query. By using executeEntityBuild it will format the results to look like it was loaded via entity load and its placed under 'nodes'. 'node' will contain the data direct from the query. If you use $query->execute then 'nodes' will not be built.
Comment: Thanks for this, it's actually much easier to understand from a non-drupal dev's perspective and I may use it instead! I believe that @clive did get the specific answer to the question I posted however.


Test statistic for follow up procedure (stepwise step down) of Kruskal Wallis

Question: When conducting a Kruskall Wallis test, it is possible to follow up the procedure with a post hoc test, looking for homogeneous subsets. My question is which statistic is used to perform this procedure (e.g., is it Chi-Square, z, or the original H)?
Comment: You will want to look at Dunn test (1964) as a post hoc to K-W.  I don't understand your question about which statistic is used.
Answer: You are looking for Dunn's test, or the less well known, but more powerful Conover-Iman test. Both post hoc tests (a) perform pairwise comparisons using the same rankings used in the Kruskal-Wallis test (as opposed to just performing a bog-standard rank sum test for each pairwise comparison), and (b) use a pooled variance estimate implied by the Kruskal-Wallis test's null hypothesis. Dunn's test is based on an asymptotic z distribution, while the Conover-Iman test is based on an asymptotic t distribution.
I am unsure what you mean by "stepwise" or "step down", but implementations of both tests for R (dunn.test and conover.test) and for Stata (dunntest and conovertest) include step up and step down family-wise error rate and false discovery rate control for these tests.
References
Conover, W. J. and Iman, R. L. (1979). On multiple-comparisons procedures. Technical Report LA-7677-MS, Los Alamos Scientific Laboratory.
Dunn, O. J. (1964). Multiple comparisons using rank sums. Technometrics, 6(3):241–252.
Comment: Thank very much, really  this is really helpful. To be more precise: I'm using SPSS which offers a stepdown stepwise multiple comparisons procedure to follow up a KW test. See [here](https://www.ibm.com/support/knowledgecenter/SSLVMB_22.0.0/com.ibm.spss.statistics.algorithms/alg_nonparametric_multiple-comparisons_stepwise.htm). This page doesn't really mention which statistic is used to perform the hypothesis tests. Concretely, how would you report this procedure using a statistical formula(e.g., t (5) = 4.32, p < .1). What would take the place of the t when reporting this procedure? Thanks!
Comment: @MartijnGoudbeek Eh... I don't use SPSS, and tend to recommend [R](https://cran.r-project.org/) (it's free, and well documented).
Comment: I know all about R and use it all the time. Great piece of software. But in this case, for all kinds or reasons, SPSS is what I need to use.
Comment: @MartijnGoudbeek SPSS is using methods described in Campbell, G. and Skellings, J. H. (1985). [Nonparametric stepwise multiple comparison procedures](https://sci-hub.tw/). *Journal of the American Statistical Association*, 80(392):998–1003.
Comment: Thanks, that paper is really helpful. From that paper, it seems they're using the same statistic (H) as in the "omnibus" test. Per the paper:  Step 1. The statistic T(k) tests the equality of all k treatments [...]

 Step 2. The statistic T(k-1) is applied to all k subsets of k -
 1 [..]  Etc. Does this make sense?
Comment: $H$ is just the Kruskal-Wallis omnibus test statistic (the nonparametric equivalence of the oneway ANOVA), **and there is no multiple comparisons adjustment for a single omnibus test.** The multiple comparisons procedures enter in for the *post hoc* pairwise tests following a rejection of the Kruskal-Wallis null hypothesis.
Comment: Exactly, so my question still is what the test statistic is that is used in the pairwise tests. I am not trying to be obnoxious here, but  I'm still in the dark. For an ANOVA, you have the F-test, which can be follow by t-test. So what is the equivalent of that t-test here? Thanks again for all your efforts.
Comment: @MartijnGoudbeek I am unfamiliar with the methodology cited in the SPSS documentation. Dunn's test is, I believe, the most common appropriate *post hoc* test.


SQLITE TABLE Create error

Question: I'm working off of an example to learn node.js/sqlite3, shown here: https://github.com/mapbox/node-sqlite3/blob/master/examples/simple-chaining.js
In the example, the table only has only column, and I wanted to extend it so the table has three columns--for username, password, and login count.
So I changed the original code, here:
function createTable() {
    console.log("createTable lorem");
    db.run("CREATE TABLE IF NOT EXISTS lorem (info TEXT)", insertRows);
}

to this:
function createTable() {
    console.log("createTable lorem");
    db.run("CREATE TABLE IF NOT EXISTS lorem (info TEXT, name TEXT)", insertRows);
}

but when trying to fill it with values, I get an error:
~:dev$ node chaining.js
createDb chain
createTable lorem
insertRows Ipsum i

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: SQLITE_ERROR: table lorem has 1 columns but 2 values were supplied
~:dev$

Am I creating the table incorrectly? I referred to the SQLITE api, as well as W3schools, but none seem to indicate that I'm doing it incorrectly.
I've provided my code below:
/**
 * Shows how to use chaining rather than the `serialize` method.
 */
"use strict";

var sqlite3 = require('sqlite3').verbose();
var db;

function createDb() {
    console.log("createDb chain");
    db = new sqlite3.Database('chain.sqlite3', createTable);
}

function createTable() {
    console.log("createTable lorem");
    db.run("CREATE TABLE lorem (info TEXT, name TEXT)", insertRows);
}

function insertRows() {
    console.log("insertRows Ipsum i");
    var stmt = db.prepare("INSERT INTO lorem VALUES (?, ?)");

    for (var i = 0; i < 10; i++) {
        stmt.run("Ipsum " + i, "lala " + i);
    }

    stmt.finalize(readAllRows);
}

function readAllRows() {
    console.log("readAllRows lorem");
    db.all("SELECT rowid AS id, info, name FROM lorem", function(err, rows) {
        rows.forEach(function (row) {
            console.log(row.id + ": " + row.info + ": " + row.name);
        });
        closeDb();
    });
}

function closeDb() {
    console.log("closeDb");
    db.close();
}

function runChainExample() {
    createDb();
}

runChainExample();

Answer: It sounds like the table already exists, possibly from a previous run of your script. The quickest way to test this would be to just change the name of the sqlite database you are creating.
db = new sqlite3.Database('chain.sqlite3', createTable);

to
db = new sqlite3.Database('chain2.sqlite3', createTable);

If that works, then that's the issue. You could also modify your script to first DROP the table before creating it if it exists.

SQLITE TABLE Create error


ios iPA unix executable size 5MB too big

Question: I opened iPA package contents. the executable size is 5MB.
How can I reduce this? This is just a piece of code, I don't see any reason it would exceed even 1MB.
My iPA total size: 10MB
image folder size: 5MB
class code folder: 5MB
library libCorePlot-CocoaTouch.a size: 5MB
xcodeproject size: 8MB
Comment: "Just a piece of code"? What does that mean? How much code? What frameworks do you link to? Why should 5MB even be a problem? 5MB is peanuts by today's standards.
Comment: Is this even your code? Or just some random ipa.
Comment: by piece of code I mean they are just textfiles like .M and .H files
Comment: They are not just text files.  The compiler converts that text to machine code, then it copies (links) in any libraries you are using.
Comment: This question should NOT have been closed
Answer:
This is just a piece of code, I don't see any reason it would exceed even 1MB.

Your executable size is 5MB because you're linking in a library that's 5MB in size. The portion of the final executable that's due to your own code is likely pretty small, but you have to consider the size of the library that you've included.
Unlike system frameworks, which are dynamically linked, third party libraries are statically linked. The whole thing is copied into your executable at link time, which means that each library you add will increase your executable size.

How can I reduce this?

The Core Plot source code is available if you don't already have it, so you could try to pare it down to a more limited form that excludes the things you don't need. For example, if you're not using pie charts in your app, you might remove CPTPieChart.m/h. Core Plot has a lot of features (annotations, animation, etc.) that you might not need in your app, and removing those could help reduce your app's footprint.
If you go this route, you might want to do it by adding a new target to the Core Plot project that includes only the parts you need -- that will make it easier to incorporate updates to Core Plot as they come along.


Do you have an example of hook_menu() access callback?

Question: I have downloaded the examples project, but in the menu_example module all the access callback are set to true.. hard to understand how it works.
In my example, my meno entry should be visible on nodes, but only for roles that have the permissions to edit his own nodes.
I cant find an example a bit more verbose of an access callback.
Do anyone have one?
Answer: Drupal is itself an example of how to write code.
The easier example is aggregator_menu(), which contains the following code.
  $items['admin/config/services/aggregator'] = array(
    'title' => 'Feed aggregator',
    'description' => "Configure which content your site aggregates from other sites, how often it polls them, and how they're categorized.",
    'page callback' => 'aggregator_admin_overview',
    'access arguments' => array('administer news feeds'),
    'weight' => 10,
    'file' => 'aggregator.admin.inc',
  );
  $items['admin/config/services/aggregator/add/feed'] = array(
    'title' => 'Add feed',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_feed'),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'aggregator.admin.inc',
  );

In this case, the access callback is the default (user_access()), and the access arguments are an array containing the string for the permission. The code cannot check more than a permission; if the permissions to check are two, or the conditions to check are not just permissions, then the access callback should be a different one, including a custom one.
node_menu() define some menus that use an access callback different from the default one. The function contains the following code.
  foreach (node_type_get_types() as $type) {
    $type_url_str = str_replace('_', '-', $type->type);
    $items['node/add/' . $type_url_str] = array(
      'title' => $type->name,
      'title callback' => 'check_plain',
      'page callback' => 'node_add',
      'page arguments' => array($type->type),
      'access callback' => 'node_access',
      'access arguments' => array('create', $type->type),
      'description' => $type->description,
      'file' => 'node.pages.inc',
    );
  }

The function that is defined as access callback (node_access()) is the following one:
function node_access($op, $node, $account = NULL) {
  $rights = &drupal_static(__FUNCTION__, array());

  if (!$node || !in_array($op, array('view', 'update', 'delete', 'create'), TRUE)) {
    // If there was no node to check against, or the $op was not one of the
    // supported ones, we return access denied.
    return FALSE;
  }
  // If no user object is supplied, the access check is for the current user.
  if (empty($account)) {
    $account = $GLOBALS['user'];
  }

  // $node may be either an object or a node type. Since node types cannot be
  // an integer, use either nid or type as the static cache id.

  $cid = is_object($node) ? $node->nid : $node;

  // If we've already checked access for this node, user and op, return from
  // cache.
  if (isset($rights[$account->uid][$cid][$op])) {
    return $rights[$account->uid][$cid][$op];
  }

  if (user_access('bypass node access', $account)) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }
  if (!user_access('access content', $account)) {
    $rights[$account->uid][$cid][$op] = FALSE;
    return FALSE;
  }

  // We grant access to the node if both of the following conditions are met:
  // - No modules say to deny access.
  // - At least one module says to grant access.
  // If no module specified either allow or deny, we fall back to the
  // node_access table.
  $access = module_invoke_all('node_access', $node, $op, $account);
  if (in_array(NODE_ACCESS_DENY, $access, TRUE)) {
    $rights[$account->uid][$cid][$op] = FALSE;
    return FALSE;
  }
  elseif (in_array(NODE_ACCESS_ALLOW, $access, TRUE)) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }

  // Check if authors can view their own unpublished nodes.
  if ($op == 'view' && !$node->status && user_access('view own unpublished content', $account) && $account->uid == $node->uid && $account->uid != 0) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }

  // If the module did not override the access rights, use those set in the
  // node_access table.
  if ($op != 'create' && $node->nid) {
    if (module_implements('node_grants')) {
      $query = db_select('node_access');
      $query->addExpression('1');
      $query->condition('grant_' . $op, 1, '>=');
      $nids = db_or()->condition('nid', $node->nid);
      if ($node->status) {
        $nids->condition('nid', 0);
      }
      $query->condition($nids);
      $query->range(0, 1);

      $grants = db_or();
      foreach (node_access_grants($op, $account) as $realm => $gids) {
        foreach ($gids as $gid) {
          $grants->condition(db_and()
            ->condition('gid', $gid)
            ->condition('realm', $realm)
          );
        }
      }
      if (count($grants) > 0) {
        $query->condition($grants);
      }
      $result =  (bool) $query
        ->execute()
        ->fetchField();
      $rights[$account->uid][$cid][$op] = $result;
      return $result;
    }
    elseif (is_object($node) && $op == 'view' && $node->status) {
      // If no modules implement hook_node_grants(), the default behavior is to
      // allow all users to view published nodes, so reflect that here.
      $rights[$account->uid][$cid][$op] = TRUE;
      return TRUE;
    }
  }

  return FALSE;
}

There are three points to notice:

The arguments declared with "access arguments" will be passed to the function in the same order; the function uses a third parameter because it is not used only access callback.
The function returns TRUE if the user has access to the menu, and FALSE if the user doesn't have access to the menu.
An access callback can also be used when a menu should be shown only in specific circumstances.
Comment: When declaring a custom `access callback` function, it appears it must live in your `.module` file, because Drupal can't seem to find it in the `file` declaration (at least for me).
Answer: Edit: I missed the part about the "edit own node" permission, because then you must not only check the permission but also if that node belongs to the current user. I've updated my example below but I'm leaving the above explanation as it was.
Is your menu entry below node/nid (e.g. node/1234/something)? Then you probably don't even need a custom access callback.
If you define your menu path like the following example, it will only call the access callback  (and therefore your page callback), if you're viewing a valid node.
'node/%node/something'

This means that it will call node_load(1234) for the above example and only continue if a valid node object is returned. So you can define your permission with access arguments as usual.
That said, writing an access callback is really simple. It's just a function that will receive whatever arguments you defined in access arguments. For example, the default access callback is user_access() and when you define your access arguments like 'access arguments' => array('a permission string'), it will result in the following call: user_access('a permission string').
If you have multiple arguments, these will be passed as second, third and so on argument to your function. To access the currently active node, you can use menu_get_object().
So you could write your access callback like this, but again, you might not even need to create one.
function yourmodule_access_check() {
  global $user;
  $node = menu_get_object();

  return $node && $node->uid == $user->uid && user_access('edit own ' . $node->type . ' content');
}

Instead of hardcoding the permission string, you could pass it as an argument to the function or whatever you want to do.
Comment: could never achieve last example : with `$items['node/%node/edit']['access callback'] = 'admin_access_only'; ` and `$node = menu_get_object();` in the callback fn, `$node` never returned anything. I used instead `$node = node_load(arg(1));`  which worked... Further explanations would be really welcome


Russell's shoes and socks

Question: In a Wikipedia article, I'm reading the following (emphasis is mine):

Informally put, the axiom of choice says that given any collection of bins, each containing at least one object, it is possible to make a selection of exactly one object from each bin. In many cases such a selection can be made without invoking the axiom of choice; this is in particular the case if the number of bins is finite, or if a selection rule is available: a distinguishing property that happens to hold for exactly one object in each bin. To give an informal example, for any (even infinite) collection of pairs of shoes, one can pick out the left shoe from each pair to obtain an appropriate selection, but for an infinite collection of pairs of socks (assumed to have no distinguishing features), such a selection can be obtained only by invoking the axiom of choice.

I don't understand why we can pick out shoes but cannot pick out indistinguishable socks from an infinite collection. Can't we, out of a pair of socks, pick out a random sock? Can someone please clarify what this excerpt above is trying to say?
The whole concept of the axiom of choice seems "artificial" to me.
Comment: "Can't we, out of a pair of socks, pick out a random sock?" One way to think about this is that the axiom of choice is exactly the thing that tells us that we can make "random" choices. Remember that the way axiomatic set theory works (roughly) is that we try to express our intuitions about sets through formal axioms; one of those intuitions (arguably) is that we can, in fact, "make unlimited random choices," and the axiom of choice is the axiom which corresponds to this intuition.
Comment: Just give me an infinite collection of pairs of socks, and I'm going to show you why the axiom of choice is necessary.
Comment: @NoahSchweber What is the principal difference between choosing a sock from a finite collection and an infinite one? I don't get this.
Comment: For finite sets you can prove the AC from the other ZF axioms by induction. For infinite sets, it is proved that AC is logically independent of ZF, so you may have a world with AC and a world with the negation of AC. My attempted joke above was trying to tell you that intuition fails us when we deal with infinite sets. (Think for example about a box with an infinite number of apples: you can take out the apples, eat one of them and put them back in the box and nothing will be missing.. how inuitive is that?)
Comment: @Momo To me your example with apples is much more intuitive than with socks. If we have an infinite collection of socks and an infinite collection of shoes, then I don't understand why we can pick out distinguishable shoes, but can't do so with indistinguishable socks. I don't get what indistinguishability has to do with picking out socks or other items.
Comment: @Momo: If you want to do this, you need to be a bit more accurate. I can give you labeled socks, where each pair has a distinct left and right sock. Or socks with toe sockets, so you can tell which one is the left and which one is the right.
Comment: What you can't do is make an uncountably infinite number of arbitrary choices.  What you can do is make *one* arbitrary choice ("pick the left shoe") and apply it to all choices ("always pick the left shoe")
Comment: @fleablood: No, what you can't do is any infinite number of arbitrary choices.
Comment: Um.... that's what I said.
Comment: @fleablood: Do you not see the word "uncountably" both here and in your answer?
Answer: The first thing to remember is that you are always in the context of a proof of something. You want to prove that something exists. Be it a choice function, or a set, or whatever.
And proofs are finite. So if you have an infinite family of sets, and you've managed to prove that they are all non-empty, you still can't go "one by one" and choose from it, as you would have done if you only had five sets to choose from. This is what the axiom of choice comes to formalize, it is an apparatus for making infinitely many choices at once.
But sometimes, as luck would have it, you can specify which element you want to choose from each set. If all the sets are sets of natural numbers, you can specify the least element; or the least even element if it exists, and the third smallest odd element if there are no even numbers, and the least odd numbers if that doesn't work either. There are many ways to actually specify choices here, and many more which you cannot even fathom in their complexity.
This is the situation with the family of pairs of shoes. We have a rule, to specify, choose the left shoe of all the pairs; or choose the left shoe from this pair, and the right shoe from any other pair; or choose the left shoe if the shoes are black, and otherwise choose the right shoe. And so on and so on.
Sometimes, however, there is no reason to prefer one element of the set over another. This is what happens with socks. While they are different, socks have no inherent properties to set them apart from one another (for posterity, assume plain white socks that have never been worn). So the only way to specify a choice is indeed by an arbitrary choice. But an arbitrary choice is "a line in the proof". Because it is utilizing something called "existential instantiation". And the finiteness of the proof means that we can only apply that rule finitely many times before we need to resort to something better.

Two remarks:

I'm slightly bending the truth here, in favor of clarity of intuition. There is an issue with internal finiteness and meta-finiteness, which $\sf ZF$ itself can bypass, but that can be ignored until a better grasp of choice and set theory is developed.

You can't choose "randomly". You need to prove there is a choice function, and choosing "randomly" is exactly postulating the existence of a choice function. If you do not assume the axiom of choice, then there is no reason for such a function to even exist.
(And "random" is something which implies some probability distribution to it, the correct word to use would be "arbitrary".)
Comment: The digits are distinguishable, so your example falls into the shoes case.
Comment: I'd think of the following analogy to a function choosing socks arbitrarily. Any irrational number has infinitely many digits after the comma. That is, $\pi = 3.1415x_5x_6x_7\dots x_n\dots$. We can think of $f(n) = (x_n)_{n=1}^\infty$ as some choice function that chooses infinitely many digits by some rule. Thus there should exist a choice function to pick out a sock from an infinite set of indistinguishable pairs.
Comment: @sequence: I have no idea what you mean in that comment.
Comment: @sequence: (1) Choice functions should not be thought as some kind of a rule for choosing, since we tend to think in a framework where there are only countably many rules. (2) Your argument amounts to "the identity function is continuous everywhere, therefore we should except every function to be continuous".
Answer: The thing you are trying to invoke here is the principle of finite choice. (this is not a standard name)
In most forms of logic, one of the basic things you can do with a nonempty set1 $S$ is that you can introduce a variable $s$ that denotes an element of $S$.
For example, this is invoked if you say "Let $s \in S$..."
Note that no actual "choice" is performed here; $s$ is just a formal symbol. And this is fine; sometimes we don't care what element is chosen, sometimes we can't make an explicit choice, and yet other times we want to exhibit an argument that works with every possible choice. And those times we actually get around to making a "choice", we can substitute that choice in for $s$.
Now, you can do this repeatedly: e.g. "Let $a \in A$. Let $b \in B$. Let $c \in C$. Let $d \in D$." The thing is, logic is finitary; any thread of reasoning has finite length, and thus we only have room to work with finitely many sets and introduce finitely many symbols.
Now, we might solve this by having some family of sets $S_n$. The same limitation applies; we can say "Let $s_1 \in S_1$. Let $s_2 \in S_2$. Let $s_3 \in S_3$." But still, we only have space to do this finitely many times.
I hope I've belabored this point enough that you can recognize "Let $s_n \in S_n$ for all $n$" is a qualitatively different thing from the above. It's something new, that cannot be justified from finite choice alone!
Let's call this the principle of infinite choice.
Now, some people think the principle of infinite choice is an obviously acceptable logical principle. Others think it's obviously nonsensical.
Modern logic tends to be conservative on this — it does not include the principle of infinite choice, instead preferring to defer the issue to set theory, where the axiom of choice lets you emulate this form of reasoning, by the device:

Let $s$ be an element of the set of choice functions on the family of sets $\{ S_n \}_n$. For all $n$, define $s_n$ to be the $n$-th component of $s$.

So, if the set of choice functions is nonempty, we can emulate the principle of infinite choice by making a single choice from the set of choice functions.
And that is why set theory has the axiom of choice: to ensure the set of choice functions is nonempty.

Addendum: I stated the above in the language of "families" of things since that's usually easier to read. But if you're unfamiliar, families can be formalized in terms of functions:

A family of things indexed by the set $I$ is simply a thing-valued function whose domain is $I$
The $i$-th component of a family given by the function $f$ is simply $f(i)$

Notationally, if $X$ is a family, we tend to write $X_i$ for the $i$-th component. And to introduce the family itself, we mimic a notation from sequences; e.g. the notation $\{ X_i \}_{i \in I}$ to indicate that $I$ is the index set and that $X_i$ is the $i$-th component. $\in I$ can be dropped if the domain is clear or irrelevant.
1: or type or class or whatever similar thing is relevant
Comment: To me, intuitively, I absolutely see no reason how a finite process of choosing $n$ elements form $n$ sets is logically different from the process of choosing infinitely many elements from infinitely many sets, one element from each set. But can you please clarify the following?: (1) What is the $n$-th component of $s$ (i.e. what kind of a component does a function $s$ have?)?

(2) "to ensure the set of choice functions is empty"

Did you mean "non-empty"?

(3) Does $\{S_n\}_n$ mean an $n$-th collection of $n$ sets $S$, $n$ sets per each collection?
Comment: @sequence: Since you're unfamiliar, I've explained how to formalize the notion of "family" in terms of functions.
Answer: I think the idea of the shoes vs. socks is that shoes can have a rule.
If you have an uncountable number of {0,1} sets you can say "always pick 1" or "always pick 0" or (I think; I could be wrong) "take a 1-1 function between the reals and the sets and take the sixth digit of the real numbers decimal expansion".
What you can't do is say "arbitrarily pick one number from one set, one after another".  You can't say this because there are uncountably many sets and we can't choose them one after another.
Therefore, although it seem intuitive that we should, we can not say "arbitrarily choose a number from each of the uncountably many sets".  We can arbitrarily choose a discrete number of times, and we can, via induction, arbitrarily do it a countable number of times (I think), but we can't say "arbitrarily choice from each set individually despite the fact that the sets themselves are stacked infinitely dense and we can't individually list them all".
However if the items in the sets are distinguishable, we can make one arbitrary decision and apply it to all the sets.  Such as "always pick 1".
Comment: I think an infinite set of pairs of socks is not an uncountable set. Why would it be such?

Russell's shoes and socks


When to use complement when finding probability

Question: In a scientific study there are 8 guinea pigs, 5 if which are pregnant. If 3 are selected at random without replacement, find the probability that are all pregnant?
And the answer is 5/28.
But when finding the probability that none are pregnant, the answer is 1/56 since (3/8)(2/7)(1/6) = 1/56.
Why can't we use complement upon solving this? And subtract 1 from 5/28?
Answer: There a 5 guinea pigs that are pregnant. On the first draw, you have a 5/8 chance of selecting a pregnant one. What do you think the chances are on the second draw?
For your part of the question "why can't I use the complement rule?". You can, but it's not as simple as $P(\bar{A}) = 1- P(A)$. What you have (1/56) is the probability of drawing NO pregnant guinea pigs. The complement of "drawing NO pregnant guinea pigs" is "at least one guinea pig is pregnant".
Comment: Nice answer (+1). Appeared while I was writing about the hypergeometric distribution.
Comment: Thanks! I've seen a few of your answers recently. I think your inclusion of R is a nice touch :)
Answer: Short answer: The probability of getting 3 pregnant guinea pigs when 3 are chosen at random from the 8, is
$$\frac{{5 \choose 3}{3 \choose 0}}{{8\choose 3}} =  \frac{5}{28} = 0.1786.$$
Computations in R:
choose(5,3)/choose(8,3)
[1] 0.1785714
5/28
[1] 0.1785714

More detail: Let $X$ be the number of pregnant guinea pigs in a sample of 3 chosen at random without replacement from the 8 in the study. Then $X$ has a hypergeometric distribution with PDF:
$$P(X = k) = \frac{{5 \choose k}{3 \choose 3-k}}{{8\choose 3}},$$
for $k = 0,1,2,3.$ We can use the PDF function dhyper in R to make
the distribution table.
k = 0:3;  pdf = dhyper(k, 5,3, 3)
cbind(k, pdf)

     k        pdf
[1,] 0 0.01785714
[2,] 1 0.26785714
[3,] 2 0.53571429
[4,] 3 0.17857143

About complements: The reason you can't take the complement as you propose, is that the complement of "no (0) pregnant guinea pigs" is not "all (3) pregnant guinea pigs." There are other possible outcomes: specifically, either 1 or 2 pregnant. The complement of "no pregnant guinea pigs" in the sample is "at least one pregnant guinea pig."
$$P(X \ge 1) = 1 - P(X = 0).$$
Bar graph of PDF: Here is a graph of the hypergeometric PDF of $X.$


Problema de array em C, onde está o erro?

Question: Tenho o seguinte problema para resolver:

Cheguei nessa solução:
    #include <stdio.h>
int main()
{

    double numeros[99];
    double resultante[49];

    int i, j;

    for (i = 0; i <= 99; i++)
    {
        scanf("%d",&numeros[i]);
    }

    for(i=0;i<=49;i++)
    {
        resultante[i] = numeros[i]*numeros[100-i];
    }

    for(i=0;i<=49;i++)
    {
        printf("%d",resultante[i]);
    }

    return 0;
}

Gostaria de saber por que esse código não está funcionando, os retornos são estranhos, parecem-se com endereços, mas não tenho certeza.
Answer: Em primeiro lugar se são 100 elementos você deve declarar double numeros[100], resultante[50]; e não 99 e 49 como declarou. Note que para 100 elementos o índice do array irá variar de 0 até 99.
Faltou calcular a soma como pedido no problema.
#include <stdio.h>
int main() {
    double numeros[100], resultante[50], soma=0;
    int i, j;
    for (i = 0; i <= 99; i++) {
        scanf("%d",&numeros[i]);
    }
    for(i=0;i<=49;i++) {
        resultante[i] = numeros[i]*numeros[99-i];
        soma += resultante[i];
    }
    for(i=0;i<=49;i++) {
        printf("\t%d",resultante[i]);
    }
    printf("\nSoma: %d\n", soma);
    return 0;
}

Comment: pode responder a minha pergunta? https://pt.stackoverflow.com/questions/469237/identificar-registros-sequenciais-de-cada-usuário


How to run a python script with its environment from another script with another environment?

Question: I have two scripts: script1.py and script2.py
script1 has its environment (say, python 2), and script2 has its own environment (say, python 3).
How can I make script 1 invoke script 2, with its corresponding environment?
Thanks
Comment: so, did you solve?
Comment: @LeonardoMiquelutti no. Had to resort to creating a new process and communicating through a message bus. not a good solution, but a working solution is better the a beautiful nothing
Comment: I had to split my script into 3 parts (python 3, 2, and 3 again) but managed to run them all through a single command line. Totally agree with the beautiful nothing part @Gulzar :)
Answer: A workaround I can think of right now is os.system used to execute other files.
example:
script1.py
#!/usr/bin/env python3
import os

os.system("script2.py")

and
script2.py
#!/usr/bin/env python2

print "script 2 running..."

print "script 2 running..." is great example since python2.X uses print without parentheses and python3.X uses print() with parentheses
It's important to take note of the shebangs (#!/usr/bin/env python3 and #!/usr/bin/env python2) on both scripts which point to the correct entepreters/env for both scripts
os.system can also be used with arguments, like os.system("script2.py data.txt"), which is great if you want to run another script with arguments.
Comment: Will this also work in windows the same way? just specify the relevant path in the start of each script?
Comment: @Gulzar Possible with [Python Launcher for Windows](https://docs.python.org/3/using/windows.html#python-launcher-for-windows).
Comment: @Gulzar it should be


Como mudar a cor de uma div parent relativamente ao tamanho das childs

Question: Tenho uma div parent e 4 div's child e gostaria de mudar a cor da border da div parent relativamente ao tamanho das div child. Para exclarecer melhor colocou abaixo uma imagem com um exemplo do que falo.

As cores rosa e vermelho são só para exemplificar o tamanho das divs child e a border à esquerda pertence à div parent. Gostaria que me respondessem em jquery.
Edit:
Segue o código solicitado. É a border cinzenta da div parent que eu quero mudar a cor com o tamanho das suas divs child.

$(".timeline").css({
 "border-left" : "5px solid lightgray",
 "padding-left" : "10px"
}).children().css({
 "margin-bottom" : "5px",
 "padding" : "5px",
 "border" : "2px solid black"
});

  <bold name="10 3 2017 9:10">Block 1 </bold>

  <bold name="10 3 2017 10:30">Block 2 </bold>

  <bold name="10 3 2017 12:30">Block 3 </bold>

     <bold name="10 3 2017 13:50">Block 4 </bold>

Edit 2:

A segunda div começa então acaba a margin.
Comment: Poste o código se possível, fica mais fácil de te ajudarem.
Comment: @BrunoRomualdo editei a pergunta e coloquei o código.
Comment: Só pra entender, você quer que elas mudem no `:hover` ou que sempre estejam com a cor da borda alterada
Comment: Sempre, porém cria apenas com o tamanho de 1 div child
Comment: Entendi, como uma borda mas separada da div certo?
Comment: Ja te mando um JsFiddle perae ;)
Comment: Só mais uma pergunta, pra que precisa da borda cinza se ela vai ser cobrida?
Comment: Isso é para fazer uma especie de timeline em que preciso da borda cinza para a dita timeline e quero que fique doutra cor quando a etapa esteja completa.
Answer: Funcionalidade interessante!
Podias fazer isso assim:

const divs = [].slice.call(document.querySelectorAll('body > div'));
// máximo de children
const max = Math.max.apply(Math.max, divs.map(div => div.children.length));

divs.forEach(div => {
  div.style.borderColor = `rgba(255, 0, 0, ${div.children.length / max})`;
});
div {
  border: red 2px solid;
  padding: 10px;
  background-color: #eee;
  margin: 5px;
}

div > p {
  display: inline-block;
}

1

2

3

4

5

6

7

1

1

2

3

A ideia é usar a opacidade do rgba. Sabendo a div que tem mais descendentes podemos fazer as contas entre 0 e 1
Comment: A minha resposta recebeu um `-1`. Seria interessante saber porquê, no caso de haver algo errado na resposta :)
Comment: Blz @Sergio não entendi como sua resposta ficou igual a da foto que ele deu de exemplo, ja tiro o `-1` caso explique.
Answer: Use css para fazer isso.
deixe suas divs de dentro da classe .timeline com position: relative
div.timeline > div {
  position: relative;
}

e com um pseudo elemento ::after ou ::before voce pode fazer uma borda 'fake' e estilizá-la como quiser e css
div.timeline > div::before {
  content: '';
  width: 5px;
  height: 135%;
  background-color: #000;
  position: absolute;
  left: -17px;
  top: -2px;
}

Veja esse JSFiddle que fiz como exemplo.
Comment: Será possivel fazer com que o height da margin que mudamos a cor fosse até ao topo da div de baixo?
Comment: Desculpa não entendi direito sua dúvida pode explicar?
Comment: Vou editar a pergunta para ser mais específico. :)
Comment: Você quer que a borda falsa (preta) cubra toda a borda cinza?
Comment: Eu quero que a borda preta acabe onde começa a segunda div, que tem borda cinza, é isso que me está a dar problemas.
Comment: Vou atualizar o JSFiddle e o css da resposta.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/66537/discussion-between-bruno-romualdo-and-bruno-gibellino).


Removing Rows and Columns in .dat file using python

Question: I'm wondering if there's a simple method for deleting particular rows and columns in python. Apologies if this is a trivial question.
To give some context, I'm currently writing a script to automate a series of linux commands(specifically ciao Chandra telescope analysis commands), part of which saves the output of a certain command to a .dat file. At present the output has included some rows and columns which I don't want in there...
E.G the data currently looks like:
Data for Table Block HISTOGRAM
<code>--------------------------------------------------------------------------------
ROW    CELL   RCENTRE              RHALFWIDTH           AREA                 COUNTS               SUR_BRI

     1      1          1.016260150          1.016260150        12.9783552105                    0                    0
     2      1          3.048780450          1.016260150        38.9350656315                  1.0     0.02568378873336
     3      1          5.081300750          1.016260150        64.8917760526                  1.0     0.01541027324001
     4      1          7.113821050          1.016260150        90.8484864736                  1.0     0.01100733802858
     5      1          9.146341350          1.016260150       116.8051968946                    0                    0
     6      1

-------------------------------------
-------------------------------------
</code>
I want to remove the first few rows which incorporate the "Data for Table Block Histogram" and dashes, and also the first two columns which begin with "ROW" and "CELL"?
Thanks in advance
Answer: Assuming your separator is tabulation or that you don't need the exact same distance between columns at the end, and assuming the interesting lines begin with a number (as shown in your example) you could write something like that:
<code>def cutFile(fname, firstWantedColumn):
    """Keep wanted lines and colums: detect lines beginning with number and keep input columns"""
    f=open(fname, "r")
    lf = f.readlines()
    f.close()

    txtOut = ""
    for l in lf:
        if l[0].isdigit(): #detect if first char is a number
            txtOut += "\t".join(l.split()[firstWantedColumn:]) + "\n"
    g = open(".".join(fname.split(".")[:-1]) + "_cutted" + fname.split(".")[-1])
    g.write(txtOut)
    g.close()

cutFile("myFile.dat", 2)
</code>
Edit: this is a bruteforce solution, maybe you were talking about an advanced and oneliner solution but I'm not sur this exists.


Create a new categorized variable from a continuous variable, then use an interaction of both variables in Logistic Regression

Question: I'm a stat newbie and not good at English, but I will try my best to explain my problems.

First, I have a dependent variable (y) and 5 independent variables (x1, x2, x3, x4, x5)
x1 and x2 are categorical. x3, x4, x5 are continuous (integer).
Focus on x5, its histogram looks like this:

Then, I categorize x5 using 5 as a cutpoint and call this new categorical variable x5_cat
Next, I use x1, x2, x3, x4, x5 and an interaction between x5 and x5_cat as independent variables to predict y by logistic regression
Code in R looks like this: glm(y ~ x1 + x2 + x3 + x4 + x5 + x5:x5_cat, data = train, family = 'binomial')

Because of my limited knowledge of statistics, I can't explain why my solution is wrong. Can anyone help me ?

Edited :
The cutpoint cuts x5 into 2 categories that change from a non linear distribution into 2 nearly linear distributions, one is positive and another is negative slope. I think the coefficient of the interaction term can tell me whether there is a different effect of x5 on y when x5 is below the cutpoint and when x5 is above the cutpoint.
Comment: [Categorizing continuous variables is almost always a bad idea.](http://stats.stackexchange.com/a/41233/1352) Don't do it unless you know what you are doing.
Comment: @Cha.Po  what you are referring to would be something like a spline for x5 with at least a knot at x5=5. This is indeed a solution for non-linear associations, but is definitely not tested by dichotomizing x5. Look into spline functions (R has multiple packages which allow such additions to glms)
Comment: Why do you want to fit the interaction between a continuous variable and a categorised form of it?
Comment: @mdewey The cutpoint cuts x5 into 2 categories that change from a non linear distribution to 2 nearly linear distributions, one is positive and another is negative slope. I think the coefficient of the interaction term can tell me whether there is a different effect of x5 to y when x5 is below the cutpoint and when x5 is above the cutpoint.
Answer: Without knowing why you want to create an interaction it's hard to give you a full answer, so I will give you a general one.
Creating dummy variables out of interval data usually needs some theoretical (or technical) reasoning behind it. So if $x_5$ is delay in minutes of trains, you might want to create a dummy in which: $x=\begin{cases} 1, &\text{if x > 5}. \\ 0, &\text{else}. \end{cases}$
If a delay of 5 minutes or more is penalized by the train authority. In this example, any delay between 0 and 5 minutes have no real difference. The cut-point is what we care about.
An interaction is the multiplication of two variables, which means that we have a reason to believe that the effect of $x_1$ on $y$ is varies according to the values of $x_2$. In such a case, we may say that (using a common example) that the effect of adding sugar to water ($x_1$) on sweetness ($y$) varies depending of stirring ($x_2$).
Using a base variable ($x_5$) and interacting it with a dummy version of itself ($x_{5cat}$) doesn't make very much sense. Assume we are regressing a continuous, a dummy and interaction variables:
$\hat{y}=a+\beta_1x_1 + \beta_2x_2 + \beta_{12}x_1x_2$
the meaning of $\beta_1$ is that this will be the addition (or raise in log odds or whatever) to $\hat{y}$ with every unit increase in $x_1$, when $x_2=0$ (because of the interaction term). $\beta_2$ is the average difference between category $1$ and category $0$ when $x_1=0$.
So here is the problem. If $x_2$ if a dummy of $x_1$, than $\beta_2$ is not defined because category $1$ does not exist when $x_1=0$
Comment: According to your example and your explanation, now I understand the point that there is a problem "If x2 is a dummy of x1, then β2 is not defined because category 1 does not exist when x1=0". But, I have a further question: Is it possible to remove β2x2 from the equation ? Does the new equation (y=a+β1x1+β12x1x2) make sense ?

It's just like I want to tell that x1 has a different pattern when its value is above and below the cutpoint. I want to measure the different effect caused by the different pattern in x1.
Comment: The rule is that an interaction cannot be in a regression model without its components.


Is this Bilinear form inner product

Question:
$$Q(x,y)=x^{T}\begin{pmatrix}
     1      & 1 \\
      1        & 2
    \end{pmatrix} x$$

Can this Bilinear form be a inner product in $\mathbb{R}^2$?
It is easy to see it is symmetric, but how can I proof it is always positive?
Comment: A symmetric $2\times2$ matrix gives a positive definite form, iff its diagonal entries are positive, and its determinant is positive. Ok, if you are new to bilinear forms than that piece of information may not be very useful (in that your teacher may not appreciate the argument).
Comment: Yes, that's equivalent to the form being positive definite (and works also for bigger square matrices).
Comment: @JyrkiLahtonen so when do I need to check is the eigenvalues are positive?
Comment: @JyrkiLahtonen just to be sure also about $\mathbb{C}$?
Answer: x^2 + 2xy + 2y^2 = (x+y)^2 + y^2.

Is this Bilinear form inner product


Can you specify a generic type that subclasses another generic type _and_ a concrete interface?

Question: I have a family of domain models, each of which has a subclass that extends it and implements a specific interface, like this (Cloneable is not the interface in question, it's for example purposes only):
class A{}
class B extends A implements Cloneable{}

class C{}
class D extends C implements Cloneable{}

I want to create a generic type signature that will enforce this pairing, I've tried this which FAILS:
<T1,T2 extends T1 & Cloneable> void f ( T1 t1, T2 t2 ){}

but I get message in my IntelliJ IDE "Type parameter cannot be followed by other bounds"; it still FAILS if I switch the order around to:
<T1,T2 extends Cloneable & T1> void f ( T1 t1, T2 t2 ){}

I get the message "Interface expected here."
Confusingly, both of these signatures WORK:
<T extends A & Cloneable> void f( A a, T t ){}
<T1,T2 extends T1> void f ( T1 t1, T2 t2 ){}

Is this just a weird limitation of Java's generic type system that I cannot have a generic class (ie T2) extend both another generic class (ie T1) and a concrete interface (eg Cloneable)?
tl;dr: So, why won't <T1,T2 extends Cloneable & T1> void f ( T1 t1, T2 t2 ){} compile: is it a limitation of the Java generic syntax or am I using the wrong syntax?
Comment: @ArtB See the edit to that question (which had a bounty) and my answer. It's a little confusing I know. The second linked post is more obviously a duplicate.
Comment: possible duplicate of [Java generics - Make Generic to extends 2 interfaces](http://stackoverflow.com/questions/13101991/java-generics-make-generic-to-extends-2-interfaces) and [Why can't I use a type argument in a type parameter with multiple bounds?](http://stackoverflow.com/questions/197190/why-cant-i-use-a-type-argument-in-a-type-parameter-with-multiple-bounds)
Comment: Yes, another weird and unfortunate limitation of Java typing that you can't do intersection type constraints if a type variable is involved.  The reason given is apparently to avoid "certain problematic cases".
Comment: @PaulBellora While the answer may be the same, my question is different from the one of two interfaces.
Comment: @JudgeMental It seems compile time checkable so I really would be curious to the actual specifics involved.
Answer: The answer is in JLS 4.4:
TypeParameter:
    TypeVariable TypeBoundopt

TypeBound:
    extends TypeVariable
    extends ClassOrInterfaceType AdditionalBoundListopt

AdditionalBoundList:
    AdditionalBound AdditionalBoundList
    AdditionalBound

AdditionalBound:
    & InterfaceType

The & Cloneable is an AdditionalBound, which can only be used in an AdditionalBoundList. An AdditionalBoundList can only be used after ClassOrInterfaceType. And T1 is a TypeVariable, not a ClassOrInterfaceType.
So, yes, it's a limitation of the Java generic syntax.
Answer:
<T1,T2 extends Cloneable & T1> void f ( T1 t1, T2 t2 ){}
I get the message "Interface expected here."

From the jls 4.4. Type Variables:

Every type variable declared as a type parameter has a bound. If no
  bound is declared for a type variable, Object is assumed. If a bound
  is declared, it consists of either:
- a single type variable T, or

- a class or interface type T possibly followed by interface types `I1 & ... & In`.

It is a compile-time error if any of the types I1 ... In is a class
  type or type variable.

So, for an expression <T extends C & I> void test(T t), I should be an interface.
Comment: `I` in the original question was `Cloneable`, which is an interface. The problem was in the `C`, which must be a class or interface (but not a type variable).
Comment: @yshavit, please, take a look at the start of my answer, where i quoted one of his question. He actually had two question. I pasted the question with `>` code by with `<` it was hiding the `` part in the post. :)
Comment: don't be, it is my fault that i could not paste it correctly :)


loop over NxNxN array in python and replace all values matching a criterion

Question: I have an nxnxn matrix which I want to loop over and replace all values < 1E-35 with 1E-35.
          for i in range(N):
              for j in range(N):
                  for k in range(N):
                      if data[i][j][k] < 1E-35:
                          data[i][j][k] = 1E-35

Doesn't seem to work.
Edit: I worked it out. It was both the indentation and incorrect indexing [i][j][k].
Problem remains: this loops from 0 to N-1 of the NxNxN data? When I do data.min() I still get values ~ 1E-101 which should be 1E-35 after the loop. Am I doing the for loop wrong?
Comment: Perhaps a few more details.  In what way does it not seem to work?  Also you may want to fix the indentation of your if statement.  What is the datatype of `data`?
Comment: Griff -- If you worked it out, post it as a solution (if others haven't already) and accept it when SO allows.  That way, if someone else comes along with the same problem, they'll be able to benefit from what you learned.  If someone has already posted a good answer (or even a better answer then you worked out yourself), feel free to accept.
Comment: Sorry, I have amended it - it just seems so basic and that it would have been asked somewhere else if I had looked harder.
Answer: It looks to me like you are using numpy in which case, you may want np.where:
data = np.where(data < 1e-35,1e-35,data)

Alternatively, you could use fancy indexing:
data[ data < 1e-35 ] = 1e-35

Comment: @AshwiniChaudhary -- Yep.  You can even do fun slicing:  `data[1:6,3:2,4:8:2]`.  If you ever need work with arrays as first-class objects in python, numpy is **AWESOME**.
Comment: `data[i,j,k]` is valid in numpy?


How to get higher weight range for vocabulary

Question: I found the line in the taxonomy.admin.inc, but i didn`t want to change it in the core. So, How can I get it in my module to override the #delta of the vocabularies?
With the function I didn`t get a solution:
function <MYMODULE>_form_alter($form, $form_state, $form_id) {
  if ($form_id == "taxonomy_overview_vocabularies") {
    foreach ($form as $vocabulary) {
        if(isset($vocabulary['weight']['#delta'])) {
            $vocabulary['weight']['#delta'] = 20;
        };
    };
};

Answer: Remember to pass value by reference.
function <MYMODULE>_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "taxonomy_overview_vocabularies") {
    foreach ($form as &$vocabulary) {
      if (isset($vocabulary['weight']['#delta'])) {
        $vocabulary['weight']['#delta'] = 20;
      }
    }
  }
}

Comment: Thx for your answer. Hmm, thats doesn`t solve the problem. The delta is changed in the array, but the weight select list in the vocabulary is still from -10 to 10 ... any other idea?
Comment: I found the copy I copy from you has missing close bracket. I fixed it and tried in my local environment, it does work. Could you try again?
Comment: haha, sry i forgot one referenced value! great, thx a lot!


nginx serving only / but not any other files

Question: I have two docker containers as below:
nginx ==> working as proxy web server (nginx web server)
dist  ==> working as a php-fpm container

And this is my dist.conf:
server {
    server_name dist.me.com;
    root /var/www/html;

    location / {
        # try to serve file directly, fallback to index.php
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass dist:9000;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        internal;
    }

    location ~ \.php$ {
        return 404;
    }

    error_log /var/log/nginx/dist_error.log;
    access_log /var/log/nginx/dist_access.log;
}

The issue is if I enter dist.me.com, it shows my index.php contents fine. But if I enter dist.me.com/index.php or dist.me.com/index2.php, I get error 404 Not Found.
I tried changing some values of conf file but it did not help me.
Both index.php and index2.php exist in /var/www/html path.
Comment: It seems that's exactly what your `dist.conf` is designed to do. Notice that the `location ~ ^/index\.php(/|$)` block is marked as `internal`, and the `location ~ \.php$` block simply returns 404.
Comment: Try removing `internal` **and** changing `~ ^/index\.php(/|$)` to `~ \.php(/|$)`
Comment: @RichardSmith I tried removing `location ~ \.php$ { return 404; }` but it did not help me. By `... block is marked as internal`, I tried removing `internal;` line but did not help me. Could you help me more?
Comment: @RichardSmith that worked, thanks:) Please write this as an answer so that I can vote you up for this favor
Answer: Your existing dist.conf is designed to block URIs ending with .php. The internal directive prevents a location from being directly accessed, and there is also a location which explicitly returns 404 for any URI ending with .php.
You need to change the location rule, remove the internal directive, and delete the location block which follows it.
For example, replace location ~ ^/index\.php(/|$) { ... } and location ~ \.php$ { ... } with the single location block as follows:
location ~ \.php(/|$) {
    fastcgi_pass dist:9000;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $realpath_root;
}


Does it make sense to compare different imputation techniques?

Question: My supervisor suggests that I impute the missing data in my dataset through various methods (namely complete cases, k-nearest neighbors, last observation carried forward and multiple imputation with predictive mean matching) and compare the derived estimates to choose the most appropriate one. Does it make sense to do so if I'm not doing a simulation study for method comparison or is it an overkill? Is it more common to just go for an algorithm with an established performance such as MICE?
(Chances are, he just wants me to practice but I wonder what a common way of doing it is when the focus is on the actual research question)
Comment: What do those abbreviations mean (please description include in the body). Then, is MICE a method or a name of a program?
Comment: @ttnphns, thanks for the suggestion, edited the body. I meant MICE as a method (Multiple Imputation by Chained Equations)
Answer: In an ideal world, the method of handling missing data would be specified as part of the design of the experiment. We could imagine a shady researcher who attempts every known method for missing data adjustment and then reports the one which gives the largest treatment effect. This would be a form of p-hacking and lead to incorrect estimates, confidence intervals, and hypothesis tests. Pre-specifying the method to use avoids this danger, and thinking about potential problems in advance is good practice.
On the other hand, one often does not know in advance the exact properties of the missing data, whether MCAR, MAR, or NMAR are more plausible, the amount of missing data, any strange patterns of missingness, and so on. That makes choosing a method in advance difficult. The assumptions of the chosen method will always need to be checked after data has been collected, and violations of those assumptions may lead us to change methods.
Another issue is sensitivity analysis. We would like that the final results don't depend strongly on the choice of method we used. The simplest way to assess this is to try different methods and see if the results differ. If all methods give similar results then we can report that other methods were considered and found to be similar. If the results are different then choosing the best one to use is difficult. The best approach would probably be to report all of the methods, but that makes it difficult to interpret the results, especially difficult for anyone who isn't familiar with the different methods.
Personally, I would recommend comparing the complete case analysis with one alternate method at a minimum, and varying the parameters used in that alternate method. If there isn't too much missing data and the results are similar it's probably okay to stop there. If there are any notable differences between those two methods or if the amount of missing data is larger, say >10% missing or a certain group is missing more, then it's probably worth examining in more detail. In general I wouldn't be concerned if a research tried many different methods, as long as that's reported clearly.
Comment: Thanks for such an elaborate answer! As a very fresh PhD student, I had no idea it may be considered shady. Could you please elaborate on why it's the case? I was under the impression that finding the most favourable imputation method (i.e. the one that yields the most accurate imputed values) is desirable (as opposed to p-hacking).
Comment: That's the "good" definition of "most favourable"; there's another definition - "gives me the best-looking study results" - that is akin to p-hacking.
Comment: @jbowman 's second definition is what I was thinking of, I've edited to clarify. Trying different imputation methods to find the most accurate may lead to overfitting the data, but it's probably balanced out by the more accurate imputation values. Hard to say. Train-Test splitting or Cross Validation can be used as well, but get computationally prohibitive.
Comment: Ah now I see, you meant choosing the imputation method that yields the values most 'desirable' for the study outcome. Makes perfect sense. Thanks for the answers you both, very helpful!


how to compare oledb datareader with a textbox data?

Question: i want to compare oledb datareader data with a textbox data something like this cod.
i have textbox named textbox7 ... the datareader have more than one mobile_no
OleDbCommand ol_com = new OleDbCommand();
OleDbDataReader reader;
ol_com.CommandText = "select [mobile_no] from student_info";
reader = ol_com.ExecuteReader();
if (reader.Equals(textbox7.text))
{
  up_st_lbl2.Text = "error";
 }
 else
 {
    //do something
 }

any one can help me please?
Answer: You are trying to compare the actual OleDbDataReader object with the TextBox string value, which will obviously not return true ever. You need to compare the column value of your query with the text box. You might also consider putting a WHERE clause in your sql to filter out unnecessary rows. Please read this article to get a basic understanding of how to perform data access with MS Access - http://msdn.microsoft.com/en-us/library/ms971485.aspx
if ((string) reader["[mobile_no]") == textbox7.Text)
{
// error
{

Comment: thank you for your answer ... your answer gives me error say 'No data exists for the row/column.'? can you solve this for me please
Comment: i solve this error know it gives error 'indexoutofrange exception was unhandled' in [card_id]?


Can't attach css to table element

Question: I have a D8 module that uses the 'table' element to which I want to apply a css file residing in the modules-root folder.  The module runs well without the css. However when I 'attached ' the css I get a PHP error: "LogicException: You are not allowed to use css in #attached."
The idea is to add classes (e.g. siteOK, ...) to each row of the table as it's built.
So far, all the methods I've examined for doing this shows the syntax I've used.  Any ideas as to what I'm doing wrong?
../drupal8/modules/Custom/check_website/check_website.css:
<code>    .siteOK{
    background-color:#fcfcfc;
}
</code>
../drupal8/modules/Custom/check_website/src/Form/CheckWebsiteForm.php:
<code><?php

    /**
     * @file
     * Contains \Drupal\check_website\Form\CheckWebsiteForm.
     */
    namespace Drupal\check_website\Form;

    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;
    use PDO;

    require 'check_website.config';

    /**
     * Implements an example form.
     */

class CheckWebsiteForm extends FormBase
{

    /**
     * {@inheritdoc}
     */
    public function getFormId()
    {
        $headers = get_headers('http://cto.vermont.gov/');
        return 'check_website';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state)
    {

        $spawnedSites = $this->_getSiteList(); //

        $form['spawnedSites'] = array(
          '#type' => 'table',
          '#caption' => 'Spawned Website Table',
          '#header' => array('Name', 'Title', 'Created By', 'Site ID', 'Palette'),
        );

        $form['spawnedSites']['#attached']['css'][] = array(
          drupal_get_path('module', 'check_website') . '/check_website.css',
        );

        foreach ($spawnedSites as $value)
        {
            $rowColor = $this->_getSiteStatus($value['name']);

            // the ROW level of the table
            $form['spawnedSites'][$value['siteid']]['#attributes']['class'][] = $rowColor;

            $form['spawnedSites'][$value['siteid']]['name'] = array(
              '#type' => 'textfield',
              '#title' => t('Name'),
              '#title_display' => 'invisible',
              '#size' => 10,
              '#default_value' => $value['name'],
            );
            $form['spawnedSites'][$value['siteid']]['title'] = array(
              '#type' => 'textfield',
              '#title' => t('Title'),
              '#title_display' => 'invisible',
              '#size' => 10,
              '#default_value' => $value['title'],
            );
            $form['spawnedSites'][$value['siteid']]['createdby'] = array(
              '#type' => 'textfield',
              '#title' => t('Created By'),
              '#title_display' => 'invisible',
              '#size' => 10,
              '#default_value' => $value['createdby'],
            );
            $form['spawnedSites'][$value['siteid']]['siteID'] = array(
              '#type' => 'textfield',
              '#title' => t('Site ID'),
              '#title_display' => 'invisible',
              '#size' => 10,
              '#default_value' => $value['siteid'],
            );
            $form['spawnedSites'][$value['siteid']]['palette'] = array(
              '#type' => 'textfield',
              '#title' => t('Palette'),
              '#title_display' => 'invisible',
              '#size' => 10,
              '#default_value' => $value['palette'],
            );
            $a = 1;
        }

        $form['url'] = array(
          '#type' => 'url',
          '#title' => t('URL:'),
          '#size' => 100,
        );

        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
          '#type' => 'submit',
          '#value' => $this->t('Check'),
          '#button_type' => 'primary',
        );

// /////////////////////////////////////////////////////////////////////////////
        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state)
    {
        $a = 1;
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state)
    {
        $urlString = $form_state->getValue('url');
        $headers = get_headers($urlString);

        if (!$headers) {
            drupal_set_message($this->t('No Server at this URL'));
        }
        else {
            $headers0Tokens = explode(" ", $headers[0]);
            switch ($headers0Tokens[1])
            {
                case '200':
                    drupal_set_message($this->t('Server and page found'));
                    break;
                case '204':
                    drupal_set_message($this->t('Server is there but page has no content'));
                    break;
                case '404':
                    drupal_set_message($this->t('Server is there but page not found'));
                    break;
                case '403':
                    drupal_set_message($this->t('Server is there but page forbidden'));
                    break;
            }
        }
    }

    function _getSiteList()
    {
        $pdo = new PDO(sprintf('mysql:host=%s;dbname=%s', COMMANDER_DBHOST, COMMANDER_DB), COMMANDER_DBUSER, COMMANDER_DBPASS);

        $sth = $pdo->prepare('SELECT name, title, createdby, siteid, palette FROM site ORDER BY siteid');
        $site = new \stdClass();
        $sth->bindColumn(1, $site->name);
        $sth->bindColumn(2, $site->title);
        $sth->bindColumn(3, $site->createdby);
        $sth->bindColumn(5, $site->siteid);
        $sth->bindColumn(16, $site->palette);
        $sth->execute();

        $ret = array();

        $ret = $sth->fetchAll(PDO::FETCH_ASSOC);

        return $ret;
    }

    function _getSiteStatus($name)
    {
        $urlString = 'http://' . $name . '.vermont.gov';
        $headers = get_headers($urlString);

        if (!$headers) {
            $rowColor = 'noSerever';
        }
        else {
            $headers0Tokens = explode(" ", $headers[0]);
            switch ($headers0Tokens[1])
            {
                case '200':
                    $rowColor = 'siteOK';
                    break;
                case '204':
                    $rowColor = 'siteNoContent';
                    break;
                case '404':
                    $rowColor = 'siteNoPage';
                    break;
                case '403':
                    $rowColor = 'siteForbidden';
                    break;
            }
        }
        return $rowColor;
    }

}
</code>
Answer: In Drupal 8, assets such as CSS and JS are not added directly anymore, but via an asset library.
See the relevant documentation here:
Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module
Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

Can't attach css to table element


Use calendar to display anniversary

Question: I've a site that collects historical events.
I would to use calendar to display a block with events of actual the months (that, obviously, could be events in every year, also in XIX century).
How should I set the contextual filter to do this?
Generically I need a calendar of anniversary..
Thanks,
Sergej
Answer: The date module can be used to set up recurring events. An event on a specific date can occur multiple times. There's a basic tutorial at http://www.bentedder.com/recurring-calendar-setup-in-drupal-7/

Use calendar to display anniversary


Question about the proof of Harnack's inequality in Evans and Gilbarg's PDE book

Question: I have some trouble in understanding the proof of Harnack's inequality. Since I have consulted two books, I explained my three questions one by one.
In Evans' book Partial Differential Equations, 2nd Edition, On page 33, Line 5, Evans wrote that:" Since $V$ is connected and $\overline{V}$ is compact, we can cover $\overline{V}$ by a chain of finitely many ball $\{B_i\}_{i=1}^N,$ each of which has radius $r/2$ and $B_i\cap B_{i-1}\not=\emptyset$  for $i=2,\dots,N.$" My question in this part is that: How to construct such a chain of finitely many balls? This is my first question.  For example, suppose that the $\overline{V}$ is as the set below:

That is to say, $\overline{V}$ is the set bounded by the line segments of $AB, BC, CD, DE, EF, FG, GH$ and $HA.$ And suppose that the radius $r/2$ happens to be $3/2.$ How could I construct a chain of finitely many balls $B_i ~~(i=1,\dots,N)$ of radius $3/2,$ such that
$$\overline{V}\subset \cup_{i=1}^N B_i \text{ and } B_i\cap B_{i-1}\not=\emptyset, i=2,\dots,N.$$
I have tried using Heine-Borel Theorem, but is able to find a famyly $\mathcal{F}$ of finitely many balls of radius $3/2$ such that $\mathcal{F}$ covers $\overline{V}.$
Since I have not understand  what Evans wrote, I tried to read Gilbarg and Trudinger's book Elliptic Partial Differential Equations of Second Order. On page 16, proof of Theorem 2.5., just below the formula (2.9), they wrote that: "Now let $\Omega'\subset\subset\Omega$ and choose $x_1,x_2\in\overline{\Omega}'$ so that $u(x_1)=\sup_{\Omega'} u, u(x_2)=\inf_{\Omega'} u.$ Let $\Gamma\subset\overline{\Omega'}$ be a closed arc joining $x_1$ and $x_2$ and ... $\Gamma$ can be covered by a finite number $N$ (depending only on $\Omega'$ and $\Omega$) of balls of radius $\mathit{R}.$" As to this part of proof, I have two questions.  The first is that: Why $x_1$ and $x_2$ can be joined by an arc $\Gamma?$ Since we know that the connectedness of $\overline{\Omega'}$ does not necessarily imply the pathwise (or arcwise) connectedness of it, I can not find a method to construct such an arc, especially when $x_1 $ or $x_2$ is on $\partial\Omega'.$
My second question is: Why $N$ is not dependent on $x_1, x_2, $ or in another way, on $u?$  Since $x_1, x_2$ have been chosen, then we can construct the arc $\Gamma,$ thus, I think the number $N$ will depend on the coordinates of $x_1, x_2,$ hence on $u.$
Can anyone help me about the above three questions?
Answer: Okay, so the first part (the chain of balls) comes from the fact that in a metric space, compactness $\iff$ totally bounded.
The definition of totally bounded, is that $\forall\epsilon\gt 0,\exists x_1,...,x_n: V\subset\cup_{i=1}^n B_\epsilon( x_i)$.
Following directly from this we see that such a chain exists.
To construct one with your example, start at the top, and work your way down in intervals of say $1/2$, taking balls of radius $3/2$, when you get to the bottom, go left taking more balls, then when you get to the end, go all the way right until everything is covered.
Second part:
When we take $\overline{\Omega}'$ this set is compact, which means that a continuous function $u$ must attain it's minimum and maximum on this set, I.e. there are such $x_1,x_2$ that we may construct an arc between.
The reason that the set of finite balls depends on $\Omega', \Omega$ and not $x_1,x_2$ is because the "shape" and "length" of the arc depend on the shape of $\Omega'$, and the shape of $\Omega'$ depends on the shape of "$\Omega$.
Also, the values $x_1,x_2$ are dependant upon $\Omega'$ as well.
Comment: I have proved the total boundedness part. My concern is that how to construct such a chain of $\{B_i\}_{i=1}^N$  such that  $B_i\cap B_{i+1}\not=\emptyset, i=1,2,\dots,N-1.$
Comment: Yes, see my edit :)
Comment: By the result of Henno Brandsma, see here http://math.stackexchange.com/questions/44850/locally-constant-functions-on-connected-spaces-are-constant/44938#44938, I have solved all my questions.


Strings: é pertinente usar 'aspas' simples para ganho de performance no PHP ou isso é insignificante?

Question: Sei que isso era até listado como boas práticas no passado, mas com o PHP nas suas últimas versões (7 e 8) que são mais rápidas ainda faz algum sentido essa "boa prática" na hora de concatenar strings?
A pergunta não é sobre a diferença entre aspas simples e dupla, é sobre questão de performance do uso das aspas simples em comparação a aspas duplas.
Comment: Relacionado ao passado, com teste de desempenho: https://pt.stackoverflow.com/questions/4652/diferen%C3%A7a-entre-aspas-simples-e-duplas-em-php#answer-417874
Answer: Mesmo no PHP 5.x não havia praticamente diferença, então não tem muito o que debater sobre algo que mudou no PHP7.x ou 8.x.
Só serão "lentas" (e provavelmente será algo mínimo que não teria significado relevante) se que executasse um número irreal de operações por segundo, talvez se fosse um loop rodando milhões de strings por segundo e que provavelmente fossem escritos manualmente para serem muito grandes, mas um cenário assim é bastante improvável, e mesmo que ocorra de precisar escrever algo assim, então provavelmente o problema com o seu código não serão as aspas, mas como ele está sendo escrito no geral. De qualquer forma se estiver curioso você mesmo pode fazer um teste e notar que muda e tem ganho de performance.
Agora escrever variáveis simples, strings simples, "embarcar HTML", etc, em situações normais aspas duplas e simples terão praticamente a mesma performance.
Talvez seja importante ressaltar que muitos mitos se formaram em volta de linguagens e APIs, um exemplo são histórias como exemplo de pessoas que afirmavam para não usar require ou include, o que talvez fosse um pouco diferente apenas quando se tratando de require_once e include_once, mas é tão infima a diferença, que usar os construtores _once quando pertinente não seria nenhuma desvantagem.
O objetivo de usar aspas simples não é sobre performance, é sobre no que ela se difere das aspas duplas e do heredoc, fora evitar que algo como $foobar se torne uma "concatenação" para string atual, as aspas simples também são usadas quando você não deseja que sequências de escape para caracteres especiais expandidos.
Resumindo, a questão não é exatamente performance, isso só vai afetar em um cenário muito especifico (e provavelmente exagerado sem motivo). O que de fato mata a performance são esses frameworks web que tentam reinventar a roda, aonde o PHP já faz as coisas naturalmente, eles querem reinventar o PHP, nesses cenários de frameworks, a maioria que testei em uma requisição simples consome pelo menos 4MB de memória, enquanto escrever algo em PHP puro, consome uma média de 600kB de memória, um hello world simples na maioria dos frameworks costuma responder entre 10 a 50 pessoas por segundo (valor aproximado), escrever um hello world em PHP puro, costuma responder de 800 a 1000 pessoas por segundo

só pra constar, eu fiz benchmark desses valores todos, com 5 frameworks diferentes e PHP normal, para quem me conhece sabe que é algo que sempre bato na tecla, benchmark. Como os testes foram feitos para ilustrar uma documentação minha não tenho como trazer eles para cá, mas logo separo testes em PHP 7.3+ (isso inclui o 8.x) e até mesmo em PHP5.6.
Sugiro que se tiver interesse em ver alguns recursos específicos testados, você possa acessar o site https://www.phpbench.com/

Resumindo, em PHP puro, por segundo você conseguirá responder muito mais requisições HTTP por segundo, então se preocupar com string de aspas duplas, quando existem gargalos de problemas maiores que as pessoas se envolvem, não estou afirmando para não usarem frameworks, estou só mostrando que aspas duplas nunca foi de fato um problema, só será em um cenário quase irreal (que citei no começo da resposta, sobre escrever uma string gigante manualmente e ainda fazer uma série de operações em loop).
Comment: @Benilson o problema é que no PHP infelizmente existe escape dentro de aspas simples. Acaba tendo um parser envolvido no treco, infelizmente matando um pouco a "pureza" dessas strings também (apesar disso poder ser resolvido teoricamente na "compilação" e não na execução de fato) - https://ideone.com/DYSHZO. Mesmo assim, por diversas razões, se não é pra ter interpolação, o adequado é sempre `'` simples mesmo - nem que seja só por uma "questão filosófica" :D - Num mundo "ideal" a simples seria totalmente sem escape, para fazer mais sentido.
Comment: Só uma duvida: essa história de ser mais rápido vem de existir alguma diferença (mesmo que insignificante) de performace entres os tipos de aspas?
Comment: @raphael deve ser daquela mesma história, que na época do PHP4 e começo do 5, cercavam a comunidade PHP: "include é mais rápido que require". Sim, contavam muito essa história, é mito, mas na época todo mundo acreditava, também tinha o outros mitos e pérolas que lembro de ter ouvido, justamente de pessoas que nunca se deram ao trabalho de por em pratica algo para confirmar, mas adoravam propagar suas teorias, lembro de ouvir algumas vezes pessoas dizerem: "OOP é mais rápido que procedural".
Comment: @raphael na teoria deveria haver, pois nas aspas duplas existe uma carga maior de processamento, pois o php precisa ficar verificando a cada caracter da string se existe um `$`, caso exista tem que verificar se ele está escapado ou não, para substituir ou não pelo conteúdo de uma variável, talvez fizesse alguma diferença na época do computador 386 ou 486, mas com a evolução dos computadores, é insignificante, mesmo ocorrendo mais processamento. Pessoalmente prefiro usar aspas simples quando não existem variáveis embutidas na string e aspas duplas quando possuem, para padronizar.
Comment: @Benilson é exatamente o que respondi, se precisa talvez escrever algo que vá usar o cifrão, ou algo que por acaso "case" com uma das *sequências de escape para caracteres especiais expandidos*, mas não deseja tal resultado seja convertido, use as aspas simples, até evitará possiveis enganos. Eu mesmo intercalo entre aspas duplas e simples, se for echo eu vou direto para o uso da virgula `,`, ex: `echo 'foo: ', $foo, 'bar: ', $bar;` e em algumas situações especificais (geralmente relacionado a sequências de escape para caracteres especiais expandidos (como \t, \n, etc), eu uso aspas duplas.
Comment: E só pra constar @Benilson, PHP5 foi lançado próximo a descontinuação dos processadores i486 (uma média de 2 a 3 anos entre o processador e a versão 5) , duvido muito que era algo para se considerar em servidores na época, e mesmo provavelmente em um teste nesse processador você iria notar uma diferença mínima.
Comment: poderia incorporar tudo isso desses comentários na resposta? Ai fica mais completo e termina o assunto.
Comment: @raphael mas já não está, na resposta eu falei sobre as sequências de escape para caracteres especiais expandidos (exemplos: \t, \n, etc) e sobre versões não mudarem (logo no começo da resposta, aonde falo de php5.x), pois mesmo antes já não tinha quase diferença. Qual parte você está sentindo falta exatamente?
Comment: sobre ser algo vindo do PHP4 e virar uma boa prática difundida, mesmo não significando um ganho real de performance no código. Seria mais um contexto de onde vem.
Comment: @Bacco sim, mas esse caso também existe para aspas duplas, eu citei o que seria um processamento a mais, que não ocorre no caso das aspas simples, mas como foi citado na resposta e no meu comentário anterior, o processamento a mais é irrelevante.


A Double Integral For Calculus I

Question: I stumbled upon this questions and really messed around with it for more than half an hour but did not get any where. I checked back and forth and do not think I copied the question incorrectly.
Question:   Evaluate the double integral:   $\displaystyle \int_{1}^{2} \int_{\frac{1}{y}}^{y} (x^2+y^2)dxdy$ by using the substitution: $x = \frac{u}{v}, y = uv$.
I drew the "region" bounded by the limits of the integral in both $xy$ and $uv$ coordinates but still don't see the "rectangle" that is supposed to come out.
Comment: $z=x^2+y^2$ is a 3D paraboloid. Where you look for rectangles?
Comment: While visualizing a function often is useful, in this case pure calculus method is enough.
Comment: Yes, $z = x^2+y^2$ is a paraboloid in space. But I was talking about the region on the ground where we integrate.
Comment: To solve the first integral you consider the plane $x=constant$ The intersection of this plane with a paraboloid is not a rectangle.
Answer: Wouldn't this just be $\int_1^2\int_{1/y}^y(x^2+y^2)dxdy=\int_1^2\frac{y^3}{3}+y^3-(\frac{3}{y^3}+y) dy$?
In doing so we're treating the inner integral as simplifying the area in a sense to something of a single variable. If I did the algebra correctly after full evaluation the integral should equal $\frac{263}{24}$.
Comment: I could have gone in the same direction as you did, but it ask specifically for the substitution $x = \frac{u}{v}, y = uv$.
Comment: I'm sorry, I totally missed that part!

A Double Integral For Calculus I


Is there any book that consists of notations from various composers and suits my skill level?

Question: I am an intermediate violinist pursuing grade 4 from ABRSM. I am interested in playing classical music. Is there any book that consists of notations from various composers and suits my skill level? If yes, can you please let me know the name and publication?
Answer: I'm pretty sure that old exam books are (certainly were) available from ABRSM. All the grade 4 pieces will be of similar playing standard - they change every 2 years. If the pieces themselves are not still available, there will be a list of earlier ones from AB. Try Trinity as well.
Comment: I follow this approach, great fun. Each ABRSM exam list contains three pieces for each of three sections from which you choose one for the exam. But if you are just looking for pieces all 9 will be suitable. They also list another 9 not included in the book which you could look for separately.
Answer: Perhaps, but someone else's opinion of the difficulty of a piece (especially an advanced musician of many decades) may not be as helpful as you think. As a teacher my biggest challenge has been selecting pieces of the right level, and I'm sorry to say that I don't get it right as often as I would like.
Check out this link, consisting of a list of graded violin studies. I am not terribly familiar with the violin repertoire, but based on what I know of the composers and recognizing some of the works on this list, it looks about right to me:
http://www.violinmasterclass.com/en/graded-repertoire/violin-methods-and-etudes
Keep in mind that many (or most) of these works may be available completely for free: http://imslp.org/
You can put them on Kindle or iPad. Or, if you prefer paper, you can print them out and add them to your own book of repertoire.
Hope this helps! Good luck.


Qt QTextStream to QList item

Question: I would like to fill QList directly using QTextStream.
I have this code working right:
QList<int> str;

QFile file_read1("C:/Programs/file.txt");
if(file_read1.open(QFile::ReadOnly))
{
    QTextStream read1(&file_read1);
    read1.seek(0);
    int i=0;
    int aux=0;
    while (!read1.atEnd())
    {
        read1>>aux;
        str.append(aux);
        //read1>>str[i];  //I'd like to use something like this
        //i++;
    }
}

return a.exec();
}

And I wonder why the commented code inside the while loop doesn't work correctly when uncommented (and read1>>aux;str.append(aux); commented). I can use it, but str.count() returns 0 and str.isEmpty is true even if I can read values using str.at(i).
I there another solution like the commented one where I dont need to use the auxiliary variable aux ?
Answer: //read1>>str[i];  //I'd like to use something like this

Yes you can, T & QList::operator[](int i) in your case returns an int &, which is exactly what the stream output operator needs. But you need to have enough space in the list, because unlike append() the [] operator will not increase the size to the list, try to access an invalid index and your app crashes. This is why count is 0 and isEmpty is true. Being able to read from it is a a lucky coincidence, and likely undefined behavior.
Unfortunately, QList doesn't come with a resize() method, nor with a constructor which can set the size. You can still reserve() but that will only help you with avoiding reallocations. It will not increase the size of the list, only the capacity, so as far as the list is concerned, even if you reserve and are able to read and write using the [] operator, its size will remain 0. You can simply go for QVector instead. It has both a QVector(int size) constructor, and a void resize(int size) method. And will be more efficient in your case, since QList reserves capacity at both ends. QList was invented as a sort of a "jack of all trades" but in some cases it is useless.
Note that you can still effectively resize the list by using reserve(n) and appending an n count of dummy integer values, if you are really set on using it instead of a vector.
template<class T>
void resizeList(QList<T> & list, int newSize) {
    int diff = newSize - list.size();
    T t;
    if (diff > 0) {
        list.reserve(diff);
        while (diff--) list.append(t);
    } else if (diff < 0) list.erase(list.end() + diff, list.end());
}

You can also read1 >> str[i++]; and save a line of code.

Qt QTextStream to QList item