Jquery Validation Not working throwing error $.validation is undefinedj

Question: jQuery validation is working fine on my machine, when i pushed it to test server it won't it's throwing some errors which is kind of surprising.
These are the errors I am getting:

$.validator is null or not an object...

I've never gotten this error before and it throwing an error when I declared a variable like var isValid.
I don't know what to do. I am doing the custom validation methods not in the document.ready(). Does this cause this error? I wonder because all jquery validations are passing and hitting the server side validations.
Comment: Are you sure the paths to jQuery and the Validate plugin are correct ? Providing a link to the problem page would be helpful.
Comment: I just found it...there is mismatching of version for validation plug in and jquery base file..i don't know how it is working on my machine..i don't know..I just changed my jquery file to 1.4.2 and validation plug in to latest one..and its working perfect...thanks for your reply
Answer: Almost always this type of $.<insert-function-here> is a path or typo error, jQuery cannot find the function.  Check your includes and script for typos and verify the paths are correct.
Comment: I just found it...there is mismatching of version for validation plug in and jquery base file..i don't know how it is working on my machine..i don't know..I just changed my jquery file to 1.4.2 and validation plug in to latest one..and its working perfect...thanks for your reply..
Answer: I just found it...there is mismatching of version for validation plug in and jquery base file..i don't know how it is working on my machine..i don't know..I just changed my jquery file to 1.4.2 and validation plug in to latest one..and its working perfect...thanks for your reply.. –


About the trace operator

Question: Consider a smooth ,convex and bounded  domain $K \subset \{ x_1 = 0 \} \subset R^n$ . Let $U \subset R^{n}_+ = \{ x = (x_1,..,x_n)\in R^n ; x_1 > 0\} $ with $K \subset \partial U$ and supoose that $U$ is smooth.
Consider the trace operator $T : W^{1,2}(U) \rightarrow L^{2}(\partial U)$ . Exists $u \in W^{1,2}(U)$ such that $Tu = g$ where $ g= 1 $ on $K$ and zero otherwise ?
i believe that is tru , but i dont know how to prove this..
someone can give me a help ?
thanks in advance
Comment: $\partial \Omega$ or $\partial U$ ?
Comment: $\partial  U $. Sorry . i fixed the error
Comment: Any more conditions on $K$ ?
Comment: -----  ------    No.....
Answer: Consider the set $K' = \{ (x_1,\dots,x_n) \in \mathbb{R^n} | x_1 \in (-1,1) \mbox{ and } (0,x_2,\dots,x_n) \in K \} $. Now consider the function :
$\varphi(x) = \begin{cases} e^{-1/(1-|x_1|^2)}& \text{ if } |x_1| < 1\\
                 0& \text{ if } |x_1|\geq 1
                 \end{cases}$
$\varphi(x)$ occurs in reference to mollifiers, see wiki : http://en.wikipedia.org/wiki/Mollifier
$ u = \chi_{K'} \cdot e^2 \cdot \varphi $ should do the trick !
*Essentially I took a 1 width band on both sides of $K$, and produced a $C_0^{\infty}$-function in transversal manner with the required properties and stitched them together (possible) because $\partial U$ is smooth and measure of this band is finite because $K$ is of finite measure imposed by the fact that $g$ is in $L^2(\partial U)$.
Please correct me if I am wrong. I am just attempting an answer here.

About the trace operator


Multiple ip-adresses setup in server and what are they needed for

Question: Hello i am new to dedicated servers, and i have recently rented one. This server runs CentOS and i have a plesk parallel pannel.
There is only one ip adress configured in PLESK, but i have 2 ip adreses i can use. The two being
xx.xxx.xx.33
xx.xxx.xx.56
I have these two adresses sent to me by email, but i dont know what to do with them. I want to run 1 heavy application on my server, and 2 verry small ones. Now the thing i want to do is set the heavy app on one IP and the other 2 on the second.
Is this type of settup possible, and does this even make sence?
Or are the IP adresses used for other things. Thank you very much.
Answer: It makes no sense. Multiple IP make sense for example for SSL - running multiple SSL applications over the same IP is tricky for some servers - and for other server processes that sort of have no way to identify different instances wit only the domain name (like FTP actually, IIRC).
Comment: Nice response, and that you for pointing me in a direction where the two ip-adresses actually make are used for something. I am going to use SSL connections on my server, so maybe i will use them for that. thanks. +1 and accepted answer
Comment: Note that yuo only need those if you have MULTIPLE ssl certificates. The problem is one of security - HTTP can have multiple sites on one IP address due to host header information in the request. SSL encrypts the request ;) So that info can not be used - dependign on web server design (and IIS had this problem at least before version 7 - not changed since).
Answer: It's reasonable, if the two IPs are tied to two different physical interfaces (i.e. NICs), because then you're splitting the physical load and making sure one high-bandwidth application isn't slowing down two smaller applications.
It being a "dedicated server", however, it's almost certainly virtualized, and those two ip addresses are hosted on the same piece of physical hardware, in which case, you won't see any benefits.
Comment: Thank you for the response, and yes, they are the same machine. So I think this setup is a no-go. +1 for the answer
Answer: If you want the applications to all run on the default HTTP port 80 or HTTPS port 443, and have different hostnames, and work with old or rudimentary HTTP 1.0 user agents, then having different IP addresses could make sense.
Back in the HTTP 1.0 days, user agents didn't send the Hostname: header in their requests, so a single web server with a single IP address hosting multiple virtual websites couldn't tell which virtual website the HTTP 1.0 user agent was asking for if it just did a GET / HTTP/1.0. So if you wanted to host multiple virtual websites on the same single host, you needed to assign separate IP addresses for each virtual website so that your web server could know which virtual website to serve up to the HTTP 1.0 client just by looking at which IP address the client was connecting to.
HTTP 1.0 user agents are probably pretty rare these days, but I still run across the occasional embedded HTTP client or rudimentary script that acts as a simple HTTP client that uses HTTP 1.0 for simplicity's sake.


How to use in multiple inheritance an abstract method

Question: It looks like that there is something that I don't understand about multiple inheritance and abstract methods. I am implementing some hardware functionality in SystemC, with multiple target HWs. I have two different levels of software implementation. The first one is optimized for performance; the second one on its top, has some display, etc. functionality. [Note, in the hardware world "top" refers to the highest level instance which is usually a wrapper or a testbench for the hardware instance]
To actually handle a HW, in scSW I implemented "Hold()". When I want to use it in the higher level (see SW and SW2),
my compiler said
error: 'scHW' is an ambiguous base of 'SW'
 struct SW : scSW, HW { virtual bool Holds(){return scHW::Holds();} };

and
invalid new-expression of abstract class type 'SW2'
     SW2* S2 = new SW2;
                   ^~~
because the following virtual functions are pure within 'SW2':
 struct SW2 : scSW, HW {  };

It also added:
 request for member 'Holds' is ambiguous
     std::cerr << S2->Holds();

I especially do not see, how can a method be pure and ambiguous, at the same time? What do I wrong and what is the correct way of coding what I want?
#include <iostream>
struct Virtual { virtual bool Holds() = 0;};
struct scHW { bool Holds(){return true;}};
struct scSW : scHW, Virtual {};
struct HW : scHW { };
struct HW2 : scHW { virtual bool Holds(){return scHW::Holds();}};
struct SW : scSW, HW { virtual bool Holds(){return scHW::Holds();} };
struct SW2 : scSW, HW {  };

int main()
{
    HW* H = new HW;
    HW2* H2 = new HW2;
    scHW* H1 = new scHW;
    SW* S = new SW;
    SW2* S2 = new SW2;
    std::cerr << S->Holds();
    std::cerr << H->Holds();
    std::cerr <
Holds();
    std::cerr << S2->Holds();
}

Comment: Tip: don't use variable/type names that differ from language/library names only in case e.g., `Virtual`.
Comment: Hmm, this may be more complicated than typical diamond problem
Comment: As a side note, `Holds`'s name suggests it is a getter in general, so you might consider declaring it `const`.
Comment: Also see [How can I avoid the Diamond of Death when using multiple inheritance?](https://stackoverflow.com/q/137282/608639)
Comment: @Yksisarvinen When not using virtual inheritance, it isn't called a diamond
Answer: It's pure and ambiguous at the same time because name lookup and virtual function overriding are mostly orthogonal mechanisms. You see here:
struct scSW : scHW, Virtual {};
struct HW : scHW { };

Looking up Holds in scSW will go into two different base class sub-object (as explained on your previous question). The scHW and Virtual bases. As such, the lookup is ambiguous. Those are two different functions in two different classes that are referred to by the same identifier.
Which not quite so coincidentally is also why Virtual::Holds is not overridden in scSW. The member from scHW is unrelated. There is no virtual function overrider in scSW, so that class remains abstract.
Answer: Looks like you might not want multiple inheritance, and just do:
 struct scHW : Virtual { virtual bool Holds(){return true;}};
 struct scSW : scHW {};
 ...

that way scHW isn't abstract and can be instantiated.
Comment: I definitely want multiple inheritance: Virtual provides the abstract handling,  and scSW the physical one. The abstract function enables other methods of scSW to implement handling a concrete HW without knowing the details of the hardware, in this case different hardware units. In the way you proposed, Virtual provides a 'default' method, and the programmer of the hardware driver is not forced to implement (override) the method.


Ada - Incorrect use of "random"

Question: I'm trying to generate a random Positive in ada in my procedure. For this, I have the following code:
  procedure Inicialize(K: Positive) is
     package rand is new ada.numerics.discrete_random(Positive);
     use rand;
     G: Generator;
     t: Positive;
  begin
     isInitialized:= True;
     reset(G);
     t := random(G); --error for this line
  end Inicialize;

I get the error
incorrect use of "random"

I have no idea, how is this an incorrect use, or what does it even mean. Could someone please elaborate?
Thank you!
Answer: Assuming isInitialized is a global variable, that code looks legal as it stands. It compiles and runs correctly with a current Gnat Ada. Is the full procedure more complicated than this? Could G or random be being redeclared?
I see your earlier question which mentions a package random. So it's likely a name clash between the package name and the procedure name. Removing the 'use rand', or renaming the package, would cure this.
Comment: I see an earlier question which mentions a package 'random'. So it's likely a name clash between the package name and the procedure name. Removing the 'use rand', or renaming the package, would cure this.

Ada - Incorrect use of "random"


Allow user to request resend of activation email

Question: I would like to code a way for a user to request the activation email be resent. Is there a function I can call from within a form-submit hook that will accomplish this?
(using Drupal 7)
Comment: you mean want the admin of the site to resend an activation email to a specific user?!
Comment: No. I would like to create a 'trouble logging in' page, where a unactive user can request the activation email to be resent based on email address
Answer: First you need to create a custom form page using hook_menu() to allow users to enter their emails.
 /**
 * Implements hook_menu().
 */
function custom_user_menu() {
  $items = array();

  $items['user/trouble'] = array(
    'title' => 'trouble logging in',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_user_trouble_logging_in_form'),
    'access callback' => TRUE,
  );

  return $items;
}

Second, you need to create form structure
function custom_user_trouble_logging_in_form($form, &$form_state) {
  $form['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-Mail address'),
    '#size' => 60,
    '#required' => TRUE,
  );

  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Resend activation email'),
  );

  return $form;
}

Third, validation step (check if user email already registered)
/*
 * Validation function
 */
function custom_user_trouble_logging_in_form_validate($form, &$form_state) {
  $account = user_load_by_mail($form_state['values']['mail']);

  if(!$account) {
     form_error($form['mail'], t('Invalid user email'));
  }
}

Fourth, resend user activation email on form submission.
/*
 * Submit function for the 'Re-send welcome message'.
 */
function custom_user_trouble_logging_in_form_submit($form, &$form_state) {
  global $language;

  $destination = array();

  if (isset($_GET['destination'])) {
    $destination = drupal_get_destination();
    unset($_GET['destination']);
  }

  $account = user_load_by_mail($form_state['values']['mail']);
  $user_register = variable_get('user_register', 2);

  switch ($user_register) {
    case 0:
      $op = 'register_admin_created';
      break;
    case 1:
      $op = 'register_no_approval_required';
      break;
    case 2:
      $op = 'register_pending_approval';
      break;
  }

  $mail = _user_mail_notify($op, $account, $language);
  if (!empty($mail)) {
    watchdog('user', 'Welcome message has been re-sent to %name at %email.', array('%name' => isset($account->realname)? $account->realname : $account->name, '%email' => $account->mail));
    drupal_set_message(t('Welcome message has been re-sent to %name at %email', array('%name' => isset($account->realname)? $account->realname : $account->name, '%email' => $account->mail)));
  } else {
    watchdog('user', 'There was an error re-sending welcome message to %name at %email', array('%name' => isset($account->realname)? $account->realname : $account->name, '%email' => $account->mail));
    drupal_set_message(t('There was an error re-sending welcome message to %name at %email', array('%name' => isset($account->realname)? $account->realname : $account->name, '%email' => $account->mail)), 'error');
  }
  $form_state['redirect'] = $destination;
}

Note: custom_user is the name of the module that I used. You can change to whatever you like.
Answer: The previous answer will not work. _user_mail_notify states that "By default, we always notify except for canceled and blocked.
Here is an implementation that notifies the user when they try to log in and sends them another email at that time using a custom user_mail_notify. "cgps_my_misc" is the name of a custom module.
<?php

function cgps_my_misc_form_alter(&$form, $form_state, $form_id)  {

  switch ($form_id)  {
    case 'user_login_block':
          $form['#validate'][] = 'cgps_my_misc_user_login_name_validate';
          break;
  }
}

function cgps_my_misc_user_login_name_validate($form, &$form_state) {
  if (!empty($form_state['values']['name']) && user_is_blocked($form_state['values']['name'])) {

    drupal_get_messages('error'); //Purges drupal core error message so we can set out own
    form_set_error('cgps_my_name', t('The account %name has not been activated.', array('%name' => $form_state['values']['name'])));

    $user = user_load_by_name($form_state['values']['name']);

    $mail = cgps_my_misc_user_mail_notify('register_no_approval_required', $user);

    if (!empty($mail)) {
      watchdog('user', 'Welcome message has been re-sent to %name at %email.', array('%name' => isset($user->realname)? $user->realname : $user->name, '%email' => $user->mail));
      drupal_set_message(t('Welcome message has been re-sent to %name at %email', array('%name' => isset($user->realname)? $user->realname : $user->name, '%email' => $user->mail)));
    } else {
      watchdog('user', 'There was an error re-sending welcome message to %name at %email', array('%name' => isset($user->realname)? $user->realname : $user->name, '%email' => $user->mail));
      drupal_set_message(t('There was an error re-sending welcome message to %name at %email', array('%name' => isset($user->realname)? $user->realname : $user->name, '%email' => $user->mail)), 'error');
    }
  }
}

function cgps_my_misc_user_mail_notify($op, $account, $language = NULL) {
    $params['account'] = $account;
    $language = $language ? $language : user_preferred_language($account);
    $mail = drupal_mail('user', $op, $account->mail, $language, $params);
  return empty($mail) ? NULL : $mail['result'];
}


Lebesgue measure inequality

Question: I have some trouble in proving that if C is a closed set and A an open set (both in $R^n$ with euclidean metric) with $C \subseteq A$, then $ |C|\le |A|$ where |#| indicates the Lebesgue measure.
Edit: obviously A is bounded
This is my attempt:
$d(C,R^n ∖ A)\gt 0$ because the function $x→d(x,R^n∖A)$ defined on the compact set C is continuous, therefore it has a minimum m(>0). Let H be a pluri-rectangle that contains C, if we divide it in n-rectangles each one with diameter less than m/2 and we sweep aside those that do not have elements of C we obtain a pluri-rectangle H' contained in A and that contains C. Hence by definition of measure of open and closed sets we have $|C|\le|H'|\le|A| $.
Is it correct?
thanks in advance
Answer: Let $B:=A \setminus C$. Prove that
B is open, hence measurable, and $A=C \cup B$ and that $C \cap B= \emptyset$.
It follows that $|A|=|C|+|B| \ge |C|$.
Comment: Thanks, but I've used $|C|\le|A|$ to prove that $|A|\ge |C|+|B|$. I thought of this: $d(C, R^n \backslash A)>0$ because the function $x \to d(x, R^n \backslash A)$ is continuous and defined on the compact set C, therefore it has a minimum m(>0).
Let H be a pluri-rectangle that contains C, if we divide it in n-rectangles each one with diameter less than m/2 and we sweep aside those that do not have elements of C we obtain a pluri-rectangle contained in A and that contains C. Does it seems correct to you?
Comment: Why the downvote?  What  is wrong with  my  answer?
Comment: I didn't downvote...
Comment: Indeed I don't have enough 'reputation' to vote, or at least my votes aren't displayed publicly

Lebesgue measure inequality


How can i save multiple click counters in localstorage?

Question: I have several counters, how can I store all values in the store? And is this even possible in this example?
I created a code snippet here:

document.addEventListener('click', function(event) {
  if (event.target.dataset.counter != undefined) {
    event.target.value++;
  }
});
Counter: <input type="button" value="1" data-counter>
Another counter: <input type="button" value="2" data-counter>
And another counter: <input type="button" value="2" data-counter>
Comment: Do you want to cache all the counts after clicking once, or to cache the count of the current click?
Comment: I want to cache current numbers of click to localstorage
Answer:

document.addEventListener('click', function(event) {
  if (event.target.dataset.counter != undefined) {
    event.target.value++;
    window.localStorage.setItem(event.target.name, event.target.value);
  }
});
Counter: <input type="button" value="1" name="counter1" data-counter> Another counter: <input type="button" value="2" name="counter2" data-counter> And another counter: <input type="button" value="2" name="counter3" data-counter>

Use localStorage.setItem function to cache it when you clicking.
Answer: You could give your buttons IDs and use an object to store the values as key value pairs (where each key is an ID corresponding to a button). Then you can use JSON.stringify() and JSON.parse() when storing and retrieving that object from the localStorage.
As localStorage doesn't work here in stack snippets, see this codepen for a working example.
var clickStore = window.localStorage.getItem('clickStore') || '{}';
clickStore = JSON.parse(clickStore);

console.log(clickStore);

Object.entries(clickStore).forEach(([key, value]) => {
  var btn = document.querySelector(`#${key}`);
  if (btn) {
    btn.value = value;
  }
});

document.addEventListener('click', function(event) {
  if (event.target.dataset.counter != undefined) {
    event.target.value++;
  }
  clickStore[event.target.id] = parseInt(event.target.value, 10);
  console.log(JSON.stringify(clickStore));
  window.localStorage.setItem('clickStore', JSON.stringify(clickStore));
});

Comment: Thank you! But how can i use this when instead id="counter1" and id="counter2" i got same class with this buttons?
Comment: You need some kind of unique reference, otherwise you'll have trouble assigning the value to each button. The number of buttons might change in the future, so the index of each element based on just the class or data attribute won't work.
Answer: One approach to this is to set up  an object in memory and then to update that object whenever you update any of the counters.
Working Example:

// Grab dataCounter Buttons
const dataCount = document.getElementsByClassName('data-count')[0];
const dataCounters = [... document.querySelectorAll('[data-counter]')];

// Initialise dataCountObject
let dataCountObject = {};
dataCounters.forEach((dataCounter, i) => {
  dataCountObject['dataCounter' + i] = parseInt(dataCounter.value);
});
console.log(dataCountObject);

// Increment both dataCounter and dataCountObject
const incrementCount = (event) => {

  if (event.target.dataset.counter != undefined) {

    let index = dataCounters.indexOf(event.target);
    dataCountObject['dataCounter' + index]++;
    event.target.value++;
    console.log(dataCountObject);
  }
}

// Attach Event Listener to dataCount
dataCount.addEventListener('click', incrementCount, false);
<form class="data-count">
Counter: <input type="button" value="1" data-counter>
Another counter: <input type="button" value="2" data-counter>
And another counter: <input type="button" value="2" data-counter>
</form>

Then, if at any time you want to save to localStorage you can serialize the object into a string using:
let dataCountJSON = JSON.stringify(dataCountObject);

and then you can add the JSON string to localStorage:
localStorage.setItem('dataCount', 'dataCountJSON');

Comment: Yes, thank you, but i don't know how to implement localstorage into this code...
Comment: See the last line of the answer above. It's that simple.
Comment: Unfortunately, saving data after refreshing the page does not work for me...
Comment: Which browser are you using?
Comment: Chrome... Here is a code [link](https://codepen.io/ultimatejupiter/pen/wvvpVBw)


Separate permissions for form access and form submit

Question: I have a module on a website, called members, and 2 roles: "low admin" and "manager". They have permissions: 'low admin tasks' and 'manager tasks'. Every low admin has access to both permissions.
There is an edit member form. Manager must be able to view the data, but not be able to update. Low admin can do both operation. Here is the code:
function members_menu()
{
       $items = array();

       //members_edit calls members_edit_form
       $items['members/edit'] = array(
           'page callback'    => 'members_edit',
           'access arguments' => array('manager task'),
           'type' => MENU_CALLBACK,
           );

       return $items;
}

function members_edit_form($form, &$form_state, $data_array = NULL)
{
    //here I prepare the fields
    ...

    //submit button is shown only for the low admin
    if (user_access('low admin tasks'))
    {
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
            );
    }

}

function members_edit_form_submit($form, &$form_state)
{
    if (user_access('low admin tasks'))
    {
        //save to the database
    }
}

Is it possible to remove the condition from members_edit_form_submit and set somewhere (maybe in members_menu), that only users with 'low admin tasks' privilege can call members_edit_form_submit?
Answer: It's an odd use-case where certain roles can view the form itself, but not submit it. Perhaps better to allow non-privileged users to view the rendered form output instead of the input form.
That way, you can put the access check on the menu callback for the form itself.
Anyway, have you considered putting the access check into the form validate function?
e.g
function members_edit_form_validate($form, &$form_state)
{
  if (!user_access('low admin tasks'))
  {
    form_set_error('submit', t('Sorry, you do not have access to update this form'));
  }
}

Comment: Interesting, but your code didn't work until I changed NULL to ''. Like this: `form_set_error('', t('Sorry, you do not have access to update this form'));` Why is that?
Comment: Thanks, normally you pass the element name there,  you could pass the submit name, though docs showed default NULL appeared ok. Answer updated to pass empty string instead.


Page reachable if user connected or not.

Question: I am currently working on a website with MVC5 and Identity.
I have a page which is reachable when a user is connected (with an account) but also when he is not. If he is connected I want to display some information .
If he is not connected I want to display less information and I want to invite him to log in.
I don't know how to implement such a page. I have this controller :
   [Authorize]
    public class PController : Controller
    {
        private int UserId;

        public ActionResult Index(int userId ) {
            UserId = Convert.ToInt32(((ClaimsIdentity) User.Identity).FindFirst("test").Value);
            PModel model = new PModel(UserId);
            return View(model);
        }
    }

and my model :
public class PModel {
    public int UserId { get; set; }
public PModel(int userId) {

    ........
    }

In both cases, I would like to call the Index method, and do the processings according to the connexion in the model :
  public PModel(int userId) {
      if(userConnected) {

         } else {

         }
  }

I don't know whether it's possible like this.
Answer: You don't do this in your model (typically). If you want to use the default forms authentication model that comes with ASP.net, you need to set it up in your web.config and provide appropriate login/logout actions etc.  In the config, you have something like this:
<authentication mode="Forms">
   <forms loginUrl="~/Account/LogOn" timeout="30" name=".MySite" protection="All"/>
</authentication>

The Authorize attribute on your action will stop the code within that method from running if the user is not authenticated.  The forms authentication code will redirect the user to the 'loginUrl' specified in your web.config if they come directly to a page in your site without logging in.

From your comment, I have misread your question.  You will need to remove the Authorize attribute altogether then, and you can set your model userConnected property based on the Request.IsAuthenticated property in the controller.
Comment: Thank you for your answer. I don't want to directly redirect the user. He can view my page even if he is not authenticated ; just the information in the page will be different. I want only one page, but with different content depending on whether the user is authenticated or not.


IPV6 Bind/DNS DHCP

Question: We are run the one event in that there 7000 people are visiting, with Laptop to provide then internet access.
We thought of setting up IPV6 DNS/DHCP all this people will be use LAN cable to get connected to Linux Server (centos/RHEL/Fedora) that will be connected to switch.
Question is we are not able setup DNS /DHCP using IPV6 if any one has done this kind of configuration kindly share the step by step implementation plan it will really appreciate.
Thanks a lot :)
Answer: Step 1:

make sure you have production-quality IPv6 connectivity

Step 2:

configure your routers/firewalls

Step 3:

let your routers/firewalls send out RAs (Router Advertisements)

advertise not-managed, no-other-configuration
advertise the routed prefix with (a)utoconfiguration flag enabled

Now you already have IPv6 connectivity. You don't need DHCPv6 because you use SLAAC (Stateless Auto Configuration) and DNS requests still go over IPv4, but connectivity is there.
Step 4:

configure a stateless DHCPv6 server

advertise IPv6 DNS resolvers
if your ISP doesn't provide them you can use the public Google DNS resolvers (see http://code.google.com/intl/nl-NL/speed/public-dns/docs/using.html)

change the RAs

Set the other-configuration flag so the clients know that there is a stateless DHCPv6 server

How to exactly configure everything depends on the hardware and software you use. You didn't specify that so I can't help you with the details...
Comment: and if you can, filter out any RAs accidentally (or otherwise) spewed out by your clients...
Comment: Thank you so much for you quick solution for our issues. Internet link got IPV4 address on Cisco Router -->Linux (centos 6.2-DHCPD/DNS)eth0-->eth1-->switch--->7000 user will get they ethX via cat 6 cable.
Comment: If your internet link doesn't have IPv6 then don't offer it to your clients. It will only cause trouble because they *will* then try to connect to the internet with IPv6.

IPV6 Bind/DNS DHCP


Alterar bgcolor de acordo com a class

Question: Por enquanto não possuo muitos conhecimentos em JS e gostaria de tirar uma dúvida...
Preciso alterar o bgcolor de acordo com a class 'active'.
Por exemplo: "se a class 'active' estiver junto com 'banner-bg-1', a cor do body será 'orange'"
Segue o código de exemplo:
https://jsfiddle.net/79kzvnnu/13/
Comment: Você pode usar o evento `slid.bs.carousel` ao invés de `slide.bs.carousel`
Comment: Pelo que vi o .active fica "pulando" do banner-bg-1 para o banner-bg-2, mas vc quer que só no banner-bg-1 o background fique orange?
Comment: Uma coisa tão simples.... Não me apercebi desse detalhe. Agradeço aos comentários e a disposição de todos!
Seguindo o conselho do Valdeir, deu tudo certo!
Só substituir o 'slide.bs.carousel' por 'slid.bs.carousel' e deu certo!
Obrigado
Answer: Talvez você possa fazer dessa forma, em vez de verificar a classe ativa no elemento, vc pode pegar diretamente pelo evento de slide qual elemento que está ativo, e setando um data-attribute no html vc pode determinar qual cor é referente a cada item. dessa forma você não precisa mudar seu javascript a cada cor diferente, só seta o data-bg no html.

$(document).ready(function() {
  //seta fundo referente a ao item active por default.
  trocaFundo("orange");

  $('#banner').on('slide.bs.carousel', function(ev) {
    $('body').addClass('animating');
    trocaFundo(ev.relatedTarget.dataset.bg);
  });

  function trocaFundo(color) {
    $('body').css({
      background: color
    });

  }
});
body.animating {
  background: "orange";
  transition: background .7s ease-out;
}

.carousel-inner {
  height: 250px;
}

.carousel-indicators {
  text-align: center;
  bottom: 0;
  right: 0;
  left: 0;
  width: 100%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">

orange/laranja

grey/cinza

Comment: Uau Israel, simplesmente sensacional sua solução!
O código ficou até mais simples e semântico de se entender.
Preciso estudar mais JS hahaha
Obrigado, abraços!
Comment: Opa, obrigado amigo! Estamos aqui pra ajudar. Bons estudos!
Answer: O evento slid.bs.carousel ocorre depois de o slide ficar ativo.
$('#banner').on('slid.bs.carousel', function (ev) {
    mudaBG();
});

Alterar bgcolor de acordo com a class


Question about functions and input/output

Question: So I am given a formula $f(x) = {1\over(x^2-2)}$. I need to determine if it is a function for f: $\mathbb{R} \to\mathbb{R}$ and if it is a function for f: $\mathbb{Z}\to\mathbb{R}$
For the first part, I said that it wasn't a function because it is undefined for $-\sqrt2$ and $\sqrt2$. Is this correct? I realize that for each input, there can only be one output, but what if there is no output? My instructor never went over this.
For the second part, it is a function, as every input produces an output (regardless if it is unique) that is in $\mathbb{R}$.
Are these answers correct?
Answer: You are correct and seem to understand the issue well.
Answer: You are correct in both of your assertions.  The numbers $x = \pm \sqrt{2}$ are real numbers that are not integers for which the expression $f(x)$ is not defined.
More formally, write $\operatorname{Dom}(f)$ for the natural domain of the function $f$, namely, the set of real numbers for which the function is defined.  For this particular function,
$$
\begin{align}
\operatorname{Dom}(f) &= \left\{ x \in \Bbb{R} \mid x^2 \ne 2 \right\} \\
&= \left\{ x \in \Bbb{R} \mid x \ne \pm \sqrt{2} \right\} \subset \Bbb{R}\\
\end{align}
$$
and
$$
\operatorname{Dom}(f) \cap \Bbb{Z} = \Bbb{Z}.
$$


Drupal 8 ajax callback in form_alter only works on a specific server configuration

Question: I'm writing because I have spent the last few days investigating what seems to be a real conundrum and I'm pretty much at my wit's end.
I have a very simple Drupal 8 form_alter which creates a set of two dropdowns during user registration. user picks an option from the first one, and then the second is populated based on that first choice. both dropdowns' options are pulled from an external database.
problem is: the ajax callback runs smoothly on my webhost, but not on the client's. instead, I get the following error on Firebug:
AjaxError:
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /user/register?ajax_form=1
StatusText: OK
ResponseText:

Drupal.AjaxError.prototype = new Error();
-----------------------------^

and here's the code:
databases configuration
$databases['default']['default'] = array (
  'database' => 'mydatabase',
  'username' => 'mydatabase_username',
  'password' => 'mydatabase_password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);
$databases['external']['default'] = array (
  'database' => 'myexternaldatabase',
  'username' => 'myexternaldatabase_username',
  'password' => 'myexternaldatabase_password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

mymodule.info.yml
name: My Module
type: module
description: 'User registration form customisation'
package: mypackage
core: 8.x

mymodule.module
<?php

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if ($form_id == 'user_register_form') {
    // Switch to external database
    \Drupal\Core\Database\Database::setActiveConnection('external');

    $db = \Drupal\Core\Database\Database::getConnection();

    $query = $db->select('table1', 't1');
    $query->fields('t1', array('field1', 'field2'));
    $query->orderBy('field1');
    $table1 = $query->execute()->fetchAllKeyed();

    // Switch back to default database
    \Drupal\Core\Database\Database::setActiveConnection();

    $options = array(
      '0' => t('Choose a Value'),
    );

    $options = $options + $table1;

    $form['field_table1'] = array(
      '#type' => 'select',
      '#title' => t('Select from Table 1'),
      '#options' => $options,
      '#ajax' => array(
        'callback' => '_mymodule_dropdown_callback',
        'wrapper' => 'mymodule-dropdown-2',
        'event' => 'change',
        'progress' => array(
          'effect' => 'fade',
          'message' => t('Loading...'),
        ),
      ),
    );

    $form['field_table2'] = array(
      '#type' => 'select',
      '#title' => t('Select from Table 2'),
      '#prefix' => '
',
      '#suffix' => '
',
      '#options' => array(0 => 'Choose from Table 1 first'),
      '#default_value' => '0',
    );

  }
}

function _mymodule_dropdown_callback(array $form, \Drupal\Core\Form\FormStateInterface &$form_state) {

  $values = $form_state->getValues();
  $field1 = $values['field_table1'];

  // Switch to external database
  \Drupal\Core\Database\Database::setActiveConnection('external');

  $db = \Drupal\Core\Database\Database::getConnection();

  $query = $db->select('table2', 't2');
  $query->fields(
    't2',
    array(
      'field1',
      'field2',
      'field3',
    )
  );
  $query->condition('field1', $field1);
  $query->orderBy('field2');
  $table2 = $query->execute()->fetchAllKeyed(1, 2);

  // Switch back to default database
  \Drupal\Core\Database\Database::setActiveConnection();

  unset($form['field_table2']);

  $form['field_table2'] = array(
    '#type' => 'select',
    '#title' => t('Select from Table 2'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#default_value' => '0',
  );

  $default = array('0' => t('Choose a Value'));

  $form['field_table2']['#options'] = $default + $table2;
  return $form['field_table2'];

}

from what I could gather, the problem is a difference in server configuration between my webhost and the client's, but I have no idea what to look for. I scoured the web but came up empty.
if anyone would be willing to point me to the right direction, or if you need more clarification on the servers' configurations, please let me know (I felt it would be overkill to simply dump a lot of server configuration here).
any help is greatly appreciated. thank you in advance.
kind regards,
Luciano
Answer: well, as it turns out, there was a problem with AJAX in Core prior to version 8.2. here's an example from the (awesome) support at Drupalize.me:
https://www.drupal.org/node/2619878
as for the reason why it was working on my server configuration, it's (probably) because they have upgraded PHP in a rather odd fashion (applying patches for example) and that caused some functionality to "work" where it wasn't, er, supposed to.
it also helped that I looked at the error logs and meddled with the code in core, but you know -- you're not supposed to hack core.
anyway it seems like this issue has been fixed as of Drupal 8.2, so I'm closing this ticket for now.


.htaccess + subdomain + redirect

Question: Just wanted to know how we can redirect the subdomain to domain.
I have two domain which in pointing to my rails application and a subdomain

www.xyz.com
www.xyz.info
example.xyz.com

Now when the user access www.xyz.info the example.xyz.com page should open up but the address bar should be  www.xyz.info.
So is it possible to redirect?
Thanks
Abhi
Answer: One approach should be to use a reverse proxy, using mod_proxy. In the configuration of www.xyz.info put
<code>ProxyPass / http://example.xyz.com/
</code>
However, I think it would be much easier to just deploy the rails application twice, i.e. put the configuration that you have in example.xyz.com also into www.xyz.com.

.htaccess + subdomain + redirect


Facebook auto post module not posting to my FB page

Question: When user comments on a particular node the comment title and comment body should be automatically posted to my Facebook page. For this I have used Facebook autopost. I have added my appid in fb_autopost configuration page and it displays the list of pages I manage and I have selected required page. Used below rules for auto posting comment in facebook
{ "rules_facebook_autopost_" : {
    "LABEL" : "Facebook Autopost ",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "fb_autopost_entity", "comment" ],
    "ON" : { "comment_insert--comment_node_theme_display" : { "bundle" : "comment_node_theme_display" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "facebook_publication",
            "param_type" : "link",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-facebook-message" ],
          "value" : "[comment:title]"
        }
      },
      { "publish_to_facebook" : {
          "USING" : { "publication" : [ "entity-created" ], "pages" : "1575855786569558" },
          "PROVIDE" : { "facebook_publication_id" : { "facebook_publication_id" : "Facebook publication returned ID" } }
        }
      },
      { "drupal_message" : { "message" : "success" } }
    ]
  }
}

After saving the comment it throws below error and comment not posting in Facebook.

Facebook SDK threw an error: OAuthException: (#200) The user hasn't
  authorized the application to perform this action

How can I achieve this or Is there any other way to do this. Thanks
Answer: Finally found the answer.
In admin/config/services/fbpermissions need to give Publish pages permission for users.
Answer: I never used this module before, so i just found this.
Please follow this page instruction for configuration
https://www.drupal.org/node/1914896


Qual a melhor maneira de organizar um diretorio para um projeto web?

Question: Qual a melhor maneira de organizar os diretorios para um projeto PHP de desenvolvimento web?
Answer: Podes escolher uma framework e normalmente ao criares um projecto ela fará esse trabalho por ti, mas um bom "boilerplate" seria:
<code>app/
   styles/
   scripts/
   views/
        home.html
        etc...
   assets/
       fonts/
       imagens/
 config/
</code>
Comment: Tem toda a razão, eu só estava a dar uma ideia para quem nunca se teve de organizar... Esta estrutura muda de pessoa para pessoa e de framework para framework..não há maneira correcta.
Comment: Não existe uma resposta correta para a sua pergunta, pois é baseada em opiniões, as pessoas fazem da maneira que lhes parecer mais conveniente.
Comment: eu digo isso porque por exemplo se quero organizar meu projeto para distribuicao do fonte, desenvolvimento e tambem de produção. qual seria o melhor metodo?
Comment: eu usaria uma pasta client/ com tudo o que precisasse, e depois compilava e minificava tudo para uma pasta build/, que so teria um main.css, main.js, e o resto que fosse preciso, tudo pre-processado e minificado.


Survey Sampling: What am I missing with this plan?

Question: Working off a fairly limited statistical understanding, so apologies in advance if this question is ludicrously basic.  This has to have happened to other people who have successfully solved this issue, but searching for what I think are relevant terms is getting me things like "Karlin's Conjecture for Random Replacement Sampling Plans," and I'm starting to panic.
Attempting to contact 1000 people for a survey.  Plan was to get a list of the target population, draw a random sample of 1000, then contact those people.  Problem was that the original list contained people who weren't actually part of the population, so our random sample of 1000 only contained around 650 people we could actually contact.  For time & budgetary reasons, filtering the entire original list so it only contains our target population is impossible.
How do we fix this?  One option is to take a second random sample of 1000, filter for the people who actually are in our target population, then contact everyone who fits the bill (guessing around 1300 total from both samples?).
Another option is to take a second random sample of 1000, filter for the people who actually are in our target population, take the resulting list of 1300 and randomly contact 1000 of them.
A third option is to throw the original sample back in to the list, take a larger initial random sample (1500-2000 people?), and contact everyone from that sample who meets our criteria.  For time and sanity reasons we'd like to avoid this if possible.
All of these feel somehow "off" to me, given my incredibly basic statistical education.  So, gurus: what am I missing?  Is there a fourth option that makes more sense?  Will our results be statistically valid given any of the above approaches?  And does this affect our analysis in any way?
Answer: This is a very common situation, and usually one just plans for a larger initial sample size, so that once ineligible subjects are thrown out, the desired sample size is reached. In your case it appears that ~65% of the original list qualifies. So to get 350 more qualifying subjects you need to draw a random sample of about 540. In fact, depending on how you do the filtering, you could keep drawing additional random samples of size 1 until you get the required number of qualifying subjects.
Comment: +1 It's a straightforward sampling problem and this is a straightforward solution.
Answer: I hate answering a question with a list of questions, but I hope thinking about some of these issues will give you some insight as to the best way to proceed. The first two questions are mainly for clarification as it wasn't clear from reading your question:

Have you already obtained a list of 1000 people?
Have you already collected 650 samples?
If you have already collected your survey data, did all 650 people who qualify for your survey actually complete it? Even if they qualify, I have to imagine some # of those people will not complete your survey for a variety of reasons. You'll need to account for some additional attrition to reach your goal of n = 1000.
What are the costs associated with obtaining a larger list?
Are the costs of collecting the data sufficiently high enough to dissuade you from obtaining "extra" sample above you target of n = 1000?
Do you really need n = 1000? What are the negative effects of n = 900? n = 700?
Are there high start up costs to collecting the data in phases?
How is your survey administered? Can you build in the filtering system into the survey? i.e. "If answer to question 1 == yes, then terminate"?
Does your survey contain any temporal elements that may introduce bias if you conduct the survey in two/three/four phases? i.e. are people going to respond or behave differently if they answer the survey in December vis a vis March?

Without knowing more of the specifics of your survey and the population in question, the most straight forward approach in my opinion would be to obtain a random sample that is sufficiently large enough to account for the people who won't qualify and those who won't take your survey. This sounds like option three that you described above. If you already have n = 650, then I would recommend obtaining a list large enough to collect the remaining 350 samples. Does your survey contain demographic data or other benchmarks that you can use to compare across groups (waves of data collection) to see if you have introduced any bias into your data?


What special kind of IMAP mailbox is "email@example.com."?

Question: Preparing an IMAP server migration and checking for connected components of users sharing mailboxes, we stumbled over a some unusual ACL patterns observed when running listaclmailbox * in cyradm (server is running Cyrus IMAP 2.5.6):
firstname.lastname@example.com.:
  anyone lrs

Obviously, alice shared something readable to any user logged in. We're unused to this syntax: usually, we expected something like
user.alice.foo:
  alice lrswipkxtecda
  bob lrs

when alice shared her mailbox user.alice.foo with bob. What is the @ indicating, why is there a trailing dot .?
Answer: I think you have a folder user.alice.!foo in mailboxes.db, and either there's a bug in 2.5.x, or you switched on virtual domains at some point.
The '!' character is used as the domain separator, which makes the folder name ambiguous.
This folder is probably invisible to user alice right now.

What special kind of IMAP mailbox is "foo@user.alice."?


IIS 7 - Get id site variable batch script

Question: I am deploying a website using TFS i have a batch script that encrypts web.config file at the moment i have the id of the site hardcoded in.
QUESTION: How could i get the Website ID of the website that is being deployed and put it into the script #
I tried to pass in the application name but The encryption doesn't work. It needs the site id.
Also i can see the Site ID by calling the command
appcmd.exe list site SomeSite

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -pe "connectionStrings" -app "/" -site "2"

Answer: for anyone intrested i have solved it like this, I used applicationHost.Config file to search for the site name and assign the id that the site uses.
FOR /f "usebackqtokens=1-5delims=<=> " %%a IN ("%WinDir%\System32\Inetsrv\Config\applicationHost.Config") DO (
if "%%a"=="site" if "%%b"=="name" if "%%~c"=="SiteName" set siteid=%%~e
)
echo Website ID = %siteid%
pause
CALL %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -pe "connectionStrings" -app "/" -site %siteid%
if %errorlevel% neq 0 exit /b %errorlevel%
pause


Rendering two different objects using opengl ES for android

Question: In my program I am rendering a simple triangle and a textured cube, Individually both work fine but when i call the respective draw methods together , the texturing of cube doesn't show.
The onSurfaceCreated function is as shown below:
public void onSurfaceCreated(GL10 gl, EGLConfig eglConfig) {
        cub.loadGLTexture(gl, this.context);
        //gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glShadeModel(GL10.GL_SMOOTH);
        gl.glClearColor(0.5f, 0.5f, 0.5f, 0.5f);
        gl.glClearDepthf(1.0f);
        gl.glEnable(GL10.GL_DEPTH_TEST);
        gl.glDepthFunc(GL10.GL_LEQUAL);
        gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
}

The onDrawFrame is as shown below:
public void onDrawFrame(GL10 gl) {
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glLoadIdentity();
    GLU.gluLookAt(gl, 0, 0, -5, 0, 0, 0, 0, 2, 0);
    tri.draw(gl);
    gl.glRotatef(-90, 1, 0, 0);
    gl.glTranslatef(-6, 0, 0);
    cub.draw(gl);
}

Comment: Why -ve vote for this Question??
Comment: Would someone please answer this question? it is important..
Comment: Where is the source for the `draw` methods of your objects? That's the most important part.
Answer: I got the answer. Actually i just had to clear the color of the 2D model before binding the 3D model to its texture.Thanks everyone.


image of $\mathbb N$ and $\mathbb Q$ of a set-function

Question: Consider the set-function $ f: \mathcal{P}(\mathbb R) \to [0, + \infty]$ with $$f(A) = \sup \left\{ \sum_{x \in B} \frac{1}{1+|x|^2} : B \subset A , B \quad \text{is finite} \right\}$$
Which of the following is finite:
(a) $f(\mathbb N)$
(b) $f( \mathbb Q)$
(c) $f(\mathbb Q \cap (0,1) )$
Thank's in advance!
Answer: hint: to think about b and c, consider the sequence
1/2, 1/3, 1/4, 1/5, 1/6, 1/7, ...
plugging in more and more terms of that sequence into your sum, what do you get? It should look like a familiar series from a calculus course. Can that series converge? (Hint: is the general term going to zero?)
To think about a, plug in the sequence 1, 2, 3, 4, ...
Does that sum converge? That's all the natural numbers, so if that sum converges, then you win.
EDIT: in each case, we have an infinite series that either diverges or converges. So to express this in terms of finite sets $B$, pick finite sets $B_n$ that exhaust my sequence, e.g. in the example with b and c, look at $B = \{1/2\}$, then $B = \{1/2, 1/3\}$, then $B = \{1/2, 1/3, 1/4\}$, then $\ldots$.  The supremum over all the sets $B$ will be (at least as large as) the sum of the infinite series since we can pick $B$ containing as many of the terms of the infinite series as we like.
Comment: Can you write a little more clear how I write the set $B$ in each case?
Comment: O.K I got it about (b) and (c). But for (a) I consider the sequence $ B_n= \{1,2, \cdots ,n\}$ and then $ f(\mathbb N) \geq \sum_{k=1}^{\infty} \frac{1}{1+k^2}$ and then?
Comment: Well, not just $\geq$. Since we've exhausted all of $\mathbb{N}$ with these sets, really the supremum will just be equal to the infinite sum, so if that infinite sum converges, you win, and if it diverges, you lose.
Comment: which converges so I win! Thank you very much for your time!


Twitter widget does not scroll WITH the page on IE

Question: I'm sure a lot of people use the twitter widget that twitter provides.
Here's the code twitter provides:

You can see an example here that while using IE the site updates (the twitter widget) doesn't scroll with the page while using IE: http://apumpkinpatch.com/
EDIT:
I on IE7, for some reason there are two vertical scrollbars and It appears under all the other content now after i played with the z index... I can't explain the double scrollbars on IE it's really weird. I'm typically a mac user so i dont know what the double vertical scrollbars are about
I think the class for the widget is .twtr-doc according to the inspector. Anyone know if there is a css attribute I should be adding to it to stop this from happening in IE?
Works fine in CHrome and FF.
Comment: Did you see my solution below?
Answer: Works fine in my IE.
Im using v8.
Comment: I on IE7, for some reason there are two vertical scrollbars and It appears under all the other content now after i played with the z index... I can't explain the double scrollbars on IE it's really weird. I'm typically a mac user so i dont know what the double vertical scrollbars are about
Answer: The double scroll lines appear because the body container is set to overflow:auto. If you remove that rule only the window will scroll now.
However the layout issues that then follow after you make this fix, are inside the iframe code and so not editable by you.
Comment: Ah thanks! I thought that was nessissary to allow the page to scroll. But it works just fine without it and it fixed the double bars on IE. Thanks!
Comment: Happy to help. Please could you vote the answer up as well? Thanks.


Is it possible to print values during collect without modifying return type?

Question: I have a code segment something like this:
def test() : Seq[Int] =
  List("A", "B", "C") collect {
    case "A" => 1
    case "B" => 2
    //case _ => println(_)
  }

Now I would like to print specific values (just for debugging) on the output without adding any elements to the resulting collection. If I uncomment the commented line, Scala infers the value of the expression to Seq[Any], which is completely understandable.
Anybody got any hints how to do this? Thanks in advance!
Answer: def skipped: Nothing = throw new Exception("Oops, not skipped after all!")

List("A", "B", "C") collect {
  case "A" => 1
  case "B" => 2
  case x if { println(x); false } => skipped
}

object PrintSkip {
  def unapply(a: Any): Option[Any] = {
    println(a)
    None
  }
}

List(Some("A"), None, Some("C")) collect {
  case Some("A") => 1
  case None => 2
  case Some(PrintSkip(_)) => skipped
}

Comment: @KimStebel - No, no.  Look more carefully.  `case _ =>` has type `Unit`.  We need type `Nothing`.  But we never reach that point because the conditional is always false.
Comment: Very clever. Since `Nothing` is a subtype of all other types, `skipped` can fill any hole.
Answer: flatMap
List("A", "B", "C") flatMap {
    case "A" => List(1)
    case "B" => List(2)
    case x => println(x); Nil
}

collect/flatten
List("A", "B", "C").collect {
    case "A" => Some(1)
    case "B" => Some(2)
    case x => println(x); None
}.flatten

Answer: With collect, no need for wrapping things in an Option.
List("A", "B", "C").collect(new PartialFunction[String, Int] {
  def apply(s:String):Int = s match {
    case "A" => 1
    case "B" => 2
  }

  def isDefinedAt(s:String) = {
    try {
      apply(s)
      true
    } catch {
      case e:MatchError => { println(s); false }
    }

  }
})

Comment: While you do avoid using `Option`, this adds an annoying amount of duplication, and relies on performing an effect whenever `collect` invokes `isDefinedAt`, which is creepy (though intriguing).
Comment: What I mean by duplication is that in `apply` you match on `"A"` and `"B"`, and then in `isDefinedAt` you check for `== "A"` and for `== "B"`.


How to I add a counter to this while loop

Question: I need to add a counter to my while loop, so that I can know how many times the loop iterated.
var popSize = 100;
var endSize = 200;

var x = popSize / 3;
var y = popSize / 4;

while (popSize < endSize)
{
    popSize = popSize + x - y;
    popSize++;
}
console.log(popSize);

Comment: By adding another variable, for example, `counter`, to the variable declarations, initialized to zero, and increment it inside the loop. Your current loop appears to use `popSize` for (at least) two different purposes. Adding a new variable is no different than how you've already used several.
Answer: var counter = 0;

while (popSize < endSize)
{
    popSize = popSize + x - y;
    popSize++;
    counter++;
}

console.log(counter);

Answer: Store the iterations in a variable and increment it inside the loop:

var popSize = 100;
var endSize = 200;

var iterations = 0
var x = popSize / 3;
var y = popSize / 4;

while (popSize < endSize) {
  iterations++;
  popSize = popSize + x - y;
  popSize++;
}
console.log(popSize);
console.log('iterations', iterations)


Prove we cannot make a homeomorphism from [0, 1] to ℝ by contradiction.

Question: So start off contradiction proofs by assuming the opposite.
So we assume f is a homeomorphism from ℝ to [0, 1].
Since f is a surjection, there exists some  ∈ ℝ with $f() = 0$.
Let $x_1 =  – 1$ and $x_2 =  + 1$.
Since f is an injection, and since $x_1≠ x_2 ≠ $,we know that $f(x_1) ≠ f(x_2) ≠ 0$.
Let $M = min \{ f(x_1), f(x_2) \}$.
I know I have to use the intermediate value theorem at some point but I'm stuck at the next step.
Comment: $f(x_1)$ and $f(x_2)$ are both strictly positive, and since $f$ is continuous that will violate some other property of $f$. Try drawing a sketch of the situation!
Comment: I looked at that but had a hard time understanding how they got to $f(x')=f(y')$
Comment: Think of a homeomorphism $f: \Bbb R \to [0, 1]$ and use the Intermediate Value Theorem on that, noting that for some $x, f(x)=0$.
Comment: Once you have  $f (a)=0$ the (connected) graph has to come up on both sides of  $a $, so won't pass the horizontal line test.
Answer: Homeomorphisms are continuous. Continuous functions map compact sets to compact sets. $[0,1]$ is compact. $\mathbb{R}$ is not compact. Thus there is no continuous function from $[0,1]$ to $\mathbb{R}$ that has image all of $\mathbb{R}$.
Answer: Suppose we have such a homeomorphism.  By Heine-Borel, the compact subsets of  $\mathbb R $ are those that are closed and bounded.  Thus $[0,1] $ is compact and  $\mathbb R $ isn't  (unbounded).  Contradiction.

One can use connectedness  (IVT) to prove that there's no continuous injection from  $\mathbb R $ to $I $.  Or going in the other direction, one can just remove an endpoint to get that there's no continuous surjection.
One can also argue from compactness that there's no continuous surjection from  $I $ to $\mathbb R $.


IIS FTP service - download timeouts and restarts getting the data twice

Question: We have an IIS FTP site on a Windows Server 2003 x64 machine.
Application Layer Gateway service is disabled (so http://support.microsoft.com/kb/931130 does not apply). Windows Firewall service is disabled as well. Connection timeout for the FTP site (there is only one) is set to 1,200 seconds = 20 minutes.
An external client can connect to the site, list directory contents and download small files. When a client attempts to download a large file (eg, if the download continues for 3 minutes, which is still under 20 minutes, but relatively long), the server sends all data, then the connection times out, the client issues REST / RETR commands attempting to restart the download since after the last byte (which I believe should succeed and receive exactly 0 bytes), and the server behaves as if the client tried to restart after byte 0, that is, it sends the entire file all over.
Any ideas on how to fix this?
Answer: Try downloading the file from the server itself and then try downloading the file from the same network as the server. If it works on the server then you may have a network issue, if it works from the network then you may have a firewall or router issue.
Comment: The download works both from the server and from another machine on the same network, but that can be only because the download goes too fast to hit the timeout that normally occurs. I don't have a file that is big enough to download locally for more than about 20 seconds, so I can't say for sure whether the timeout issue will occur in either of the above cases. Any other ideas? Thanks for the reply.
Comment: Put a file on the FTP server that's big enough to take 3 minutes or more from the server and the local network. The key is to try to replicate the problem internally to determine if it's related to the server, the local network, the router\firewall, or something between your network and the client.


Create variables during for loop

Question: I want to create n variables from a vector of n length
for example if the vector is this:
v<-c(1:5)

The outcome should be:
x1
x2
x3
x4
x5

I was thinking about a for loop
for (i in 1:length(v)){
  x<-i
  names(x)<-paste(names(x),i)
}

but this is not how the names() function works
This is a very simplified example, I know that what I do here is more easy to achieve, but the functions in the for loop are more complex
Thanks!
Comment: what should the variables contain?
Answer: Use assign:
for (i in 1:length(v)) {
    assign(paste0('x', i), i)
}

Create variables during for loop


Solving inequality with partial sum of binomial coefficient

Question: Given an integer $n$ and another one $m \leq n$, I am trying to get a tight upper and lower bound for the parameter $k \leq n$ such that the following inequality involving a partial sum with binomial coefficients (let's say "binomial partial sum") holds:
$$\sum\limits_{i=0}^{k} {{n}\choose{i}} \leq 2^m \leq \sum\limits_{i=0}^{k+1} {{n}\choose{i}}$$
That is to say : the largest $k$ up to which the binomial partial sum is the closest to $2^m$
I have already found a trivial upper bound (see below), but it seems very rough... And I keep failing for the lower bound.
My question : Is it possible to get a tighter upper bound and a tight lower bound ?
Trivial upper bound
To get a trivial upper bound for $k$ :

we consider the known upper bound $\sum\limits_{i=0}^{p} {{n}\choose{i}} \leq (n+1)^{p}$ for the binomial partial sum
we rewrite the equation by using this bound in order to get what we want :

$$\sum\limits_{i=0}^{k} {{n}\choose{i}} \leq (n+1)^{k} \leq 2^m$$

Which leads to the following upper bound :

$$k \leq \frac{m}{\log(n+1)}$$
Trivial lower bound (fail)
To get a trivial lower bound for $k$ :

we consider the known lower bound ${(\frac{n}{p})}^{^p} \leq {{n}\choose{p}}$ for the binomial coefficient which leads also to ${(\frac{n}{p})}^{^p} \leq \sum\limits_{i=0}^{p} {{n}\choose{i}}$ for the binomial partial sum
we rewrite the equation by using this bound in order to get what we want :

$$2^m \leq {(\frac{n}{k+1})}^{^{k+1}} \leq \sum\limits_{i=0}^{k+1} {{n}\choose{i}} $$

which leads to :
$$ m \leq (k+1)\log (n) - (k+1)\log (k+1) $$
But I'm stuck here : I fail in grouping the $k$ together :-(
Comment: Maybe related: [Sum of 'the first k' binomial coefficients for fixed n](http://mathoverflow.net/questions/17202/sum-of-the-first-k-binomial-coefficients-for-fixed-n).
Answer: Handy hint.
You can use special functions for the lower bound. Indeed, the equation
\begin{equation}
y = a x - x \ln x
\end{equation}
with $x=k+1$, $y=m \ln 2$ and $a=\ln n$, rewrites as
\begin{equation}
-y\, \text{e}^{-a} = \left(\ln x - a\right) \text{e}^{\ln x - a} \, ,
\end{equation}
which is of the form $Y = X \text{e}^X$. The solutions of such equations are given by $X = W(Y)$, where $W$ denotes the Lambert $W$-function (see e.g. the Wikipedia page). Thus, the equality case of the lower bound is
\begin{equation}
k+1 = n\exp\left(W\!\left(-\frac{m \ln 2}{n}\right)\right)\, .
\end{equation}


Get the t function to work in a custom php file

Question: I am having a custom hand coded PHP page within a Drupal module that loads in a fancybox.
I want the Drupal t() function to work in it. What should I include in the file to make it function?
Comment: Are you including the PHP file from a module?
Answer: Include these lines in your php file
<code>define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
</code>
Comment: I guess that depends on how he includes the file. His question is a bit vague about how that is handled. If he, for example, has a php file as a POST callback and the file just happens to be in the module directory, then it wouldn't get any Drupal functionality at all.
Comment: If the page is loaded from a module, I would imagine that Drupal is already bootstrapped, surely?
Comment: @hampusn This is what esafwan asked.
Comment: @Mathankumar The question doesn't actually state if the file is loaded through Drupal or just with a standard `require/include` call.
Answer: By default the t() function is accessible from any custom module.
You shouldn't have to include any other files/code.


how can I http post a JSON file using an excel on both Windows and Mac

Question: I currently have a spreadsheet where a macro creates a JSON string and posts it to a web service using HTTP. On windows this code works fine for this:
Private Sub pvPostString(sUrl As String, sString As String, sFileName As String, Optional ByVal bAsync As Boolean)

    Const STR_BOUNDARY  As String = "3fbd04f5-b1ed-4060-99b9-fca7ff59c113"
    Dim nFile           As Integer
    Dim baBuffer()      As Byte
    Dim sPostData       As String
    Dim connUrl         As String

    sPostData = sString

    '--- prepare body
    sPostData = "--" & STR_BOUNDARY & vbCrLf & _
        "Content-Disposition: form-data; name=""uploadfile""; filename=""" & Mid$(sFileName, InStrRev(sFileName, "\") + 1) & """" & vbCrLf & _
        "Content-Type: application/octet-stream" & vbCrLf & vbCrLf & _
        sPostData & vbCrLf & _
        "--" & STR_BOUNDARY & "--"
    '--- post
    With CreateObject("MSXML2.XMLHTTP")
        .Open "POST", sUrl, bAsync
        .SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & STR_BOUNDARY
        .Send pvToByteArray(sPostData)
    End With

End Sub

However on the latest Mac Excel I get an error "ActiveX component can't create object". This makes sense as MSXML2.XMLHTTP is a Microsoft solution, however it means I need to find a replacement function.
I've done lots of googling on this matter and from what I have read I may be able to achieve this using query tables. However, I have tried all sorts of configurations but with no joy. For example if I try the following then I get the error "Invalid web query"
With ActiveSheet.QueryTables.Add(Connection:=connUrl, Destination:=Range("C30"))
        .PostText = myJSONString
        .RefreshStyle = xlOverwriteCells
        .SaveData = True
        .Refresh
End With

This makes sense as JSON isn't valid post text, though at the same time posting a lengthy JSON file as post text doesn't really seem like the right solution.
Ideally I would like to post the JSON as a file so that it can be referenced on the server by $_FILES[]. Though from what I've read it isn't clear on how to do this (or if it is possible at all).
tldr; Ultimately my objective with this is to have a function that allows me to post a lengthy JSON string via http that will work on both Windows and Mac. I would really appreciate any help on this.
Answer: VBA-Web (previously Excel-REST) supports both Windows in Mac in v4.0.0 and allows you to GET, POST, PUT, PATCH, and DELETE from VBA. I haven't tried it with file uploads, so I'm not sure it will work in your case, but I'd give it a try. Here's a sample:
' Replace with the following
' With CreateObject("MSXML2.XMLHTTP")
'     .Open "POST", sUrl, bAsync
'     .SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & STR_BOUNDARY
'     .Send pvToByteArray(sPostData)
' End With

' Client for executing requests
Dim Client As New WebClient
' Generally set Client.BaseUrl here, but it's not required

' Request for setting request details
Dim Request As New WebRequest
Request.Method = WebMethod.HttpPost
Request.Resource = sUrl
Request.ContentType = "multipart/form-data; boundary=" & STR_BOUNDARY

' Execute request and store response
Dim Response As WebResponse
Set Response = Client.Execute(Request)


Python2: Importing same function from multiple files

Question: I am using Python 2.7 and I am making a simple grader in Python. What this grader does is following:

Iterates over all the folders and imports the folder as a module by adding init.py
Run one of the methods and compare the output to a predefined output
If the output is same then assign True as result else False
Move to the next student and import his/her code again

Now all the students have the same file name 'test.py' and the same function name - let's say add
My ISSUE - It seems like when Python imports from the method from the first student's code, it is being carried the same for other students as well.
Sample Code
<code>## get the output of the function
output = 5

subdirectories = "contains the directory where all student codes are"

# find python files inside each directory
# copy the init file and run the code
c = 0
for student in subdirectories:
    copyfile(src, os.path.join(student,'__init__.py')) # to make the folder a package
    os.chdir(student)

    from test import * # test is the file name

    # this line below evaluates the same function again and again instead of importing the new method from a different student file
    output_student = eval( functionName + '('+functionArguments+')')
</code>
Question - How can I import a method with the same name from multiple Python files, each time overwriting the function definition.
Comment: Sounds like a bad idea. I think you should go back to the drawing board. If you need each student to implement a specific function, which you then execute in a generic context, maybe it should be the other way around. i.e. you implement a function which is called passing in each student specific function (i.e strategy pattern). Then there is no need for what you are proposing.
Comment: then how come I can check what their outputs are and then compare to what I should have.
Comment: so functionName is something like 'add', 'subtract' etc. This I am taking via the command line. functionArguments I am taking in the script.
Answer: I think import_module() will do what you want.
<code>from importlib import import_module
...
module = import_module(<module_to_import>)
output_student = module.functionName(functionArguments)
</code>


How rare is an inside-the-park grand slam home run?

Question: Michael A. Taylor hit an inside-the-park Grand Slam on Friday, September 8, 2017.  How rare is this event compared to other rare events in baseball?
Answer: I can't find stats on this rare event but the last inside-the-park grand slam happened in September 2015. The last one before that was in 1999. So it is a pretty rare event. An inside the park grand slam is usually caused by an outfielder making a mistake of some sort that is not considered an error. As a very unusual note, the outfielder involved in the 2015 homer was none other than Michael Taylor. Yep, the same Michael Taylor who hit one recently.
As a side note, in 1956 Roberto Clemente actually did even better. He hit an inside the park grand slam walk off homer.
Comment: What about the list in [this website](https://www.baseball-fever.com/forum/baseball-almanac-baseball-fever-website/baseball-fever-exclusives/175-inside-the-park-grand-slams?threadid=3641) is this correct or not.
Comment: @RamchandraGiri, Well I guess so. That seems like a lot to me especially since there are several in a single year on that list. But the person who made the list claims its comprehensive so I guess it is.  One thing to note about the older dates is that some ball parks didn't have fences back before 1910 I think. So that increased the numbers then.
Comment: Many article that I read mention about the same thing that this becoming rare because of stadium size.
Comment: Good job on finding that list. I googled and found many links but didn't see that one.


What does $\Sigma$ suppose to mean conceptually in logic and model theory?

Question: I was learning logic through these notes and I was trying to understand what the conceptual purpose was of defining $\Sigma$ in the context of truth (rather than the context of provability).
In contrast, I think the reason why $\Sigma$ is defined in the context of provability is 100% clear to me. If provability is just a $n$ length sequence of propositions until we arrive at the goal proof $p_n=p$ by using only propositional axioms, elements in $\Sigma$ or/and Modus Ponens (MP), then its seems very plausible that more proofs should be reachable if we allow more propositions to be considered, i.e. the ones in $\Sigma$. However, in this context things are just 100% about symbol games and truth has no relation to provability. So $ \Sigma \vdash p$ makes sense to me.
But when we try to define what $ \Sigma \vDash p$ is suppose to mean conceptually, its not clear to me. I understand what the statement means (it means that $p$ is true over all models of $\Sigma$, which means that for all truth assignments on the atoms $A$ all proposition $p \in \Sigma$ are true). What seems to me is that saying $\Sigma \vDash p$ only adds a quantifier over all truth assignments i.e.
$$ \forall t, t: A \to \{0,1\}, s.t \forall p \in \Sigma, f_p(t) = 1$$
where $f_p : \{0,1\}^A \to \{0,1\}$.
I don't understand why thats an interesting thing to consider by its own. I guess I am wondering if this vocabulary was developed only for the completeness theorems in propositional logic (i.e. showing the equivalence of proof and truth). Or if there is a conceptual idea that this language is trying to model that I am missing (since the meaning of $ \Sigma$ seems a lot more meaningful/important while in the context of truth it seem arbitrary).
Am I missing something?
Comment: To underscore what Noah said below, if you look at most modern books about model theory, they won't so much as *define* a deductive system for first order logic. The completeness theorem provides an easy and rather pleasing rationalization for the purely semantic compactness theorem that is the workhorse for first order model theory, but most texts opt to prove compactness directly rather than go into the 'ugly' details of syntactic 'symbol games'. Of course that's just the perspective of model theory, but model theory is a big, important field of logic.
Comment: $\Sigma \vDash \varphi$ formalizes the paramount logical concept of [valid argument](https://en.wikipedia.org/wiki/Validity_(logic)) i.e. [logical consequence](https://en.wikipedia.org/wiki/Logical_consequence).
Answer: Short version: the semantic approach is both a useful tool in proving facts about deductions, and is the more fundamental of the two when we're studying structures as opposed to deductions (which is something that in fact logic does).

First, let me motivate $\models$ in a purely pragmatic way. Suppose I want to prove a statement of the form "$\Gamma\not\vdash\varphi$." This is a "purely syntactic" claim - it's all about deductions - but the apparatus of formal proof doesn't make it too easy: I have to somehow rule out all possible deductions.
This isn't insurmountable, but the "semantic approach" - that is, using interpretations and $\models$ - often improves things greatly. Specifically, by the soundness theorem it's enough to show $\Gamma\not\models\varphi$. This can be done by coming up with a counterexample - a single interpretation satisfying $\Gamma$ but not satisfying $\varphi$. Note that we've shifted the focus from proving something about all possible proofs to finding a single counterexample; it should be clear why this is at least potentially useful!

Here's a quick test: can you think of a way to show that $$\{p\vee q, r\rightarrow (p\rightarrow q), q\leftrightarrow\neg p, \neg q\vee(r\rightarrow p)\}\not\vdash (p\wedge q)\vee r$$ that's faster than just writing down (and checking) the counterexample interpretation $p=\top, q=\perp, r=\perp$?

Even the other direction can benefit from a semantic approach: if I want to show that $\Gamma\vdash\varphi$, by the completeness theorem it's enough to show that $\Gamma\models\varphi$. But now I'm arguing about interpretations, and I can reason about them mathematically as usual. And this sort of reasoning is often much shorter than actually writing out a full formal deduction.

This may feel a bit dubious, but you've probably already done it a lot - this is exactly what you're doing when you use truth tables to argue that a sentence is a validity! You're showing that any possible truth assignment to the atomic sentences makes the given sentence true. This is a semantic argument, and the completeness theorem is what makes it okay.

So even if all you care about is the "syntactic side," the semantic approach is still valuable.

Next, let me try to motivate $\models$ "from the ground up." Logic is about more than one thing - we're interested in describing structures as much as we are in analyzing proofs. When we're doing the former, "$\models$" is the inherently-meaningful thing to look at, and "$\vdash$" is a related thing which may or may not be useful at any given point. This isn't necessarily clear when you're only familiar with propositional logic, since the notion of "structure" there is so limited, but in more complicated logics - e.g. first-order (or predicate) logic - the notion of interpretation (or "structure") is much more interesting. A structure in the sense of first-order logic is basically a set together with some relations, functions, and constants. For example, all the algebraic structures you're familiar with - groups, rings, fields, ... - are examples of first-order structures.
Questions about these are then often equivalent to questions about $\models$. Here's a silly example: the purely mathematical question

"Is every group of order $99$ abelian?"

can be rephrased as

"Does $\{\alpha_{asso}, \alpha_{id},\alpha_{inv},\alpha_{99}\}\models\forall x,y(x*y=y*x)$?"

where $\alpha_{asso}$ is the associativity axiom, $\alpha_{id}$ is the identity axiom, $\alpha_{inf}$ is the inverses axiom, and $\alpha_{99}$ says "there are $99$ elements in the domain." Each of these can in fact be written as first-order sentences - this is a good exercise.
Indeed, the semantics often comes first. In first-order logic, we usually begin with the idea of a first-order structure and $\models$, and we justify our choice of proof system via the soundness and completeness theorems.

In fact I believe this is how it historically developed as well (that is, with a more-or-less specific "intended semantics" from the beginning). Meanwhile, I don't know but I suspect that the opposite in fact is true of propositional logic: that at least a large part of the deductive apparatus (e.g. "From $a$ and $b$, infer $a\wedge b$") existed prior to any serious discussion of truth assignments as objects in their own right.

Basically, the point is that logic is not only the "mathematical study of deductions" (or similar). Logic also looks at how we use formal languages to analyze structures, and classes of structures, and etc. In this context, the thing we're really interested in (having fixed a language, and a way of interpreting that language in terms of the structures we're studying - that is, a notion of semantics) is "$\models$" - and "$\vdash$," if anything, becomes a useful tool.
Comment: Re: first-order structures, it's important to add that first-order semantics isn't the end of the story: many natural mathematical objects - like topological spaces - don't really fit into this framework. This is one reason why we may want to consider logics even beyond first-order logic. The study of general logics from a semantic perspective is **abstract model theory**. This is a very technical subject, but [this collection](https://projecteuclid.org/euclid.pl/1235417263) contains a wealth of material on the topic (albeit at a very advanced level). (cont'd)
Comment: There are also lots of reasons to be interested in logics beyond first-order logic for purely syntactic reasons; there are also reasons both syntactic and semantic to be interested in *weaker* logics!


How to use html in Laravel Nova resource title

Question: I'm stuck with putting a html output in Laravel 7 & nova 3.8
according to: https://nova.laravel.com/docs/3.0/search/global-search.html#title-subtitle-attributes
i try to make a function that put a html image in front of some resource on index pages:
public function title()
{
    return "country.".png' >";
}

I read that laravel 7 use {!! !!} ( https://laravel.com/docs/7.x/blade#displaying-data )
But if i use it in resource file in app/nova/some-resource.php php gives error.
How to easy put a image based on country field in resource title ?
--
update 23.08.2020
I tried to create a Text field in my resource as it can have ->asHtml()
and i have a nice flag image on index and detail view
public function fields(Request $request)
{
    return [
(...)
Text::make('Country Flag',
            function () {
            return "country.".png' >";
        })->asHtml(),
(...)
]};

and in title i changed to:
public function title()
{
    return $this->country_flag.' '.$this->name;
}

Result is that title looks like
''' '.$this->name // it looks like $this->country_flag = '';

Answer: The only wat to achieve goal of use html in field as i found:
Instead of just belongsTo i used Stack to use html in Text and data from other needed fields:
Stack::make('Details', [
            Text::make('Country',
            function () {
                $flaga = DB::table('companies')->where('id', $this->company_id)->first();
                return "country.".png'> ".$flaga->country;
            })->asHtml()
            ->sortable(),

            BelongsTo::make('Company')
                ->default(function ($request) {
                    return $request->user()->company_id;
                })
                ->sortable(),
        ]),

And i have some html with flag image and company id in single field on resource without even touching resource $title
Answer: try this:
// for index
public static function label()
{
    // input your logic to show label
    return 'Your Label Index';
}

Comment: in witch files ?
when i puuted it in my resource file  app/nova/some_resource.php
it give error:
        Error
Using $this when not in object context (View: /var/www/html/my_app/vendor/laravel/nova/resources/views/layout.blade.php)
Comment: yes its error, because `$this->country` not define in index resource. maybe add your logic to get this country
Comment: I adapt Your advice to my code. html putted into return of Your function is also html protected.
Your code output change navigation bar displayed name to text given in that function I need it in title, not label. And also I need a html not a plain text.


can we make a software or solution( not a windows store app) on windows 8 using VS-2012

Question: actually i working on a Application that is going to be build for windows 8 surface and desktop but we want this not to be on store but as a business solution. but i want my app to be tested by testers but i am not getting how to provide then my full package so that they can test it. any idea is appreciated.
Comment: So a Metro app but without it having to be in the appstore?
Comment: You mean [sideloading](http://technet.microsoft.com/en-us/windows/jj874388.aspx)?
Comment: @RogerRowland i mean i wantmy app to be tested on different computer..also this app is like a bussiness solution
Comment: @tanuj_loop on windows phone you have the beta option for the store but this seem to be not feasible on Windows RT as it say [here](http://social.msdn.microsoft.com/Forums/windowsapps/en-US/f4ce5ca0-58dd-4239-a545-e382a360d777/can-windows-store-app-also-provide-beta-testing-process-like-wp8), anyway for enterprise closed application I thinik you can check [this](http://msdn.microsoft.com/en-us/library/windows/apps/jj657971.aspx)
Comment: It is pretty unlikely that you'll still be interested in a side-loading solution once you find out the cost of the required key.  Only pursue this if a number like three thousand doesn't make you blush.  Testing must be done by a temporary dev key, acquired when you build the app and valid only on the machine on which you build.
Answer: In Visual Studio 2012, with your Windows Store project selected, go to Project -> Store -> Create App Package...
Tell it that you do not want to upload the app package.
This will create a folder for your app that includes the .appx, the .cer, and a .psd (PowerShell script). Zip up this folder and send it to your testers. They just need to run the PowerShell script by right clicking it and clicking "Run in Powershell...". It will prompt them for a Developer's License (which they will need), but this will be retrieved automatically after signing in with their development account.


Maximum Likelihood estimators in linear models

Question: Consider two simple linear models.
$y_{1j}=\alpha _1+\beta_{1}x_{1j}+\epsilon_{1j}$ and
$y_{2j}=\alpha _2+\beta_{2}x_{2j}+\epsilon_{2j}$  , $ j=1,2,\ldots,n>2$ where $ \epsilon_{ij} \sim N(0,\sigma^2)$
I have two questions.
1 ) Show that the point on the $x$-axis where the two lines intersect is given by $x_0={\alpha_1-\alpha_2 \over \beta_2-\beta_1}$
2)Obtain the maximum likelihood estimators of $\sigma^2$ and $x_0$
For question 1) what I did was,
Supposing at $x_0,y_0$ the two lines intersect I substituted $x_0,y_0$  to the two equations.But then what happens to the error terms.Can I suppose that the errors in estimating  $x_0,y_0$ from both equations are the same?
For 2)
$y_{ij}$ has a Normal distribution.
I calculated $E(y_{1,j})$   and $E(y_{2,j})$ separately.Can I say that $E(X_{1j}) = E(X_{2j})$
and  $E(y_{1,j}) = E(y_{2,j})$.
  Thereby I obtained $E(y_{ij})={\beta_2\alpha_1-\beta_1\alpha_2 \over\beta_2-\beta_1}$
Similarly $V(y_{ij})=\sigma^2$
Then joint probability density function for $y_{ij}$ is $\prod_{i=1}^2\prod_{j=1}^n {1\over\sqrt {2\pi\sigma^2}}$$
e^{{-(y_{ij}-\mu})^2} / 2\sigma^2$ where $\mu= {\beta_2\alpha_1-\beta_1\alpha_2\over\beta_2-\beta_1}$. Is this a correct joint p.d.f for $y$?
Does $x_0$ also has a normal distribution. Is $V(x_0)=0$. I don't understand how to obtain MLE for $x_0$ .
Can someone please help me to do this please
Comment: The model uses the terms $\beta_{ij}$. In that case what do you  mean by $\beta_1$ and $\beta_2$?
Comment: @ved : Sorry that was a mistake.I corrected it
Comment: Assume x's are constants.
Answer:
suppose the errors are zero to find the "ground truth" intersection point.
In a vector-matrix notation this problem can be augmented to reflect all measurements: ${\bf{y}}={\bf{H}} \boldsymbol{\theta}+\boldsymbol{\epsilon}$, where ${\bf{y}}$ is a $2n \times 1$ column vector of all $y$'s concatenated,$\boldsymbol{\theta}=(\alpha_1,\beta_1,\alpha_2,\beta_2)^T$ and ${\bf{H}}$ is a $2n \times 4$ block matrix given by

\begin{equation}
{\bf{H}} = \begin{pmatrix}
{\bf{H_1}} & {\bf{0_{n \times 2}}}\\
{\bf{0_{n \times 2}}} & {\bf{H_2}}
\end{pmatrix}
\end{equation}
where ${\bf{H_1}}$ and ${\bf{H_2}}$ are $n \times 2$ Vandermonde matrices and are given by
\begin{equation}
 {\bf{H_1}}=\begin{pmatrix}
{\bf{1}}_{n \times 1} & {\bf{x_1}}
\end{pmatrix}
\end{equation}
\begin{equation}
 {\bf{H_2}}=\begin{pmatrix}
{\bf{1}}_{n \times 1} & {\bf{x_2}}
\end{pmatrix}
\end{equation}
and the augmented error vector is of size $2n \times 1$ ,$\boldsymbol{\epsilon} \sim {\mathcal{N}}({\bf{0}}, \sigma^2 {\bf{I}}_{2n})$.
Thus, the Maximum Likelihood (ML) estimator for $\theta$ for this problem is given by the least squares (LS) estimator and is
\begin{equation}
\widehat{\boldsymbol{\theta}}_{ML} = ({\bf{H}}^T{\bf{H}})^{-1} {\bf{H}}^T {\bf{y}}
\end{equation}
so we get the ML estimation for the four parameters $\widehat{\boldsymbol{\theta}}_{ML}=(\widehat{\alpha}_{1_{ML}},\widehat{\beta}_{1_{ML}},\widehat{\alpha}_{2_{ML}},\widehat{\beta}_{2_{ML}})^T$ and by the invariance property of the ML estimator we get the ML estimator of $x_0$:
\begin{equation}
{\widehat{x}}_{0_{ML}} = \frac{\widehat{\alpha}_{1_{ML}} - \widehat{\alpha}_{2_{ML}}}{\widehat{\beta}_{2_{ML}} - \widehat{\beta}_{1_{ML}}}
\end{equation}
To complete the question the sample covariance $\sigma^2$ is derived by differentiating the joint log likelihood PDF and is given by
\begin{equation}
{\widehat{\sigma}}^2_{ML} = \frac{1}{N} \left \| {\bf{y}} - {\bf{H}} \boldsymbol{\widehat{\theta}}_{ML} \right \|^2_2
\end{equation}


I am trying to take 1020 to the 275th power, and modding that by 1073, but java wont output the right answer

Question: i am working on a decoder, and i need to take 1020 to the 275th power, and mod that by 1073, but when i do try that, it wont print out the correct answer
    double decoded = (1020^275)%1073;

That is the code i am trying, but it will print out 751, and its supposed to print 4, anyone have any tips?
Comment: `^` is not an exponentiation operator.
Comment: "*`1020^275`*" - this is not the power function, but the bitwise xor. Even if it were the power function, the `275`th power of `1020` would be a number with `825` digits (at least). No way to fit this in a `double`.
Comment: Search for *modular exponentiation*.
Answer: ^ is the xor operator; however, 1020 to the 275th power is a HUGE number and will overflow even if using double or long, so it should be represented by BigInteger:
System.out.println(BigInteger.valueOf(1020).pow(275).mod(BigInteger.valueOf(1073)));

Output:
4

Note: I used BigInteger#mod, but BigInteger#remainder will return the same value in your case (as you're only dealing with non-negative values).
Comment: Definitely recommend `BigInteger` over `BigDecimal` if you know integers are all that is required.
Answer: Try this out:
BigDecimal remainder = new BigDecimal(1020).pow(275).remainder(new BigDecimal(1073));
System.out.println(remainder);

After applying remainder, it can be converted to long as its max value will be 1072(in this case):
remainder.longValueExact();

Comment: what data type do i save it as
Comment: BigDecimal. Double/Long cannot be used as ti will overflow with this huge number.

It can be converted to long value with remainder.longValueExact()
Answer: You can use BigInteger.pow() followed by BigInteger.mod().
However the BigInteger class specifically includes in operation for your task: BigInteger.modPow():
System.out.println(BigInteger.valueOf(1020).modPow(BigInteger.valueOf(275), BigInteger.valueOf(1073)));

gives 4.
Answer: double is bounded and has precision limitations, try:
System.out.println(Math.pow(1020, 275));  // Infinity

Usually, you should use BigDecimal or BigInteger to manipulate big numbers,
BigDecimal bigDecimal = new BigDecimal(1020);
bigDecimal = bigDecimal.pow(275);
bigDecimal = bigDecimal.remainder(new BigDecimal(1073));
System.out.println(bigDecimal); //4

Answer: Xor is differ from power function. 2 ^ 3, The output of an XOR gate is true only when exactly one of its inputs is true. If both of an XOR gate's inputs are false, or if both of its inputs are true, then the output of the XOR gate is false.
double maximum value = 1.7976931348623157E308
Actually (1020^275) = 2.3176467070363862212063591722218e+827 which greater than double maximum value.

Go with BigDecimal.

System.out.println(new BigDecimal(1020.0).pow(275).remainder(new BigDecimal(1073)));


Show in a maximal planar graph every face is a triangle.

Question: So I argue by contradiction as follows.
Assume there exists a face in which there are more than three edges, Then the face must be a cycle, IF the face is four edges, then  we can one edge and this will divide it into two triangle, if the face has 5 edges then it's a pentagon and if wee add two edges we will divide it into three triangles, if the face has six edges then we can add three edges and this will divide the face into four triangles. In general, For a face with $n >3$ edges, We can add $n-3$ edges to divide it into triangles.
If there exists a face with less than three edges , then we just have maybe two edges (THIS IS NOT EVEN A FACE ?). Right because the least number of edges required for a face is three because I am not dealing here with multi-edges (and so avoiding loops).
But  I feel my argument is not rigorous enough, How can I improve and make it more convincing.
Answer: You basically have the idea for the proof.
Let graph $G$ be simple and that $V(G) \geq 3$. Assume we have a non-triangulated face $F$. Since $V(G) \geq 3$, we have $|V(F)| \geq 3$. Then since $F$ is non-triangulated, there exists three vertices $x,y,z \in V(F)$ where $xy \in E(F)$, $yz \in E(F)$ and $xz \not \in E(G)$. Then we can add in the edge $xz$ and still have a planar graph. So for every non-triangluated face we can increase the number of edges and preserve planarity, thus the maximum number of edges is obtained when every face is triangulated.
Comment: How is the outer face a triangle?
Comment: what do you mean? If the outer face isn't a triangle, we can add extra edges which makes it a triangle and increases the number of edges we have.
Comment: What does it mean that the outer face is a triangle?
Comment: In a plane drawing of a graph $G$, the outer face is a triangle if it comprises of three vertices which are mutually adjacent.


Merging C Callergraphs with Doxygen or determining union of all calls

Question: I have a collection of legacy C code which I'm refactoring to split the C computational code from the GUI. This is complicated by the heavily recursive mathematical core code being K&R style declarations. I've already abandoned an attempt to convert these to ANSI declarations due to nested use of function parameters (just couldn't get those last 4 compiler errors to go).
I need to move some files into a pure DLL and determine the minimal interface to make public, which is going to require wrapper functions writing to publish a typed interface.
I've marked up the key source files with the Doxygen @callergraph markup so informative graphs are generated for individual functions. What I'd like to do beyond that is amalgamate these graphs so I can determine the narrowest boundary of functions exposed to the outside world.
The original header files are no use - they expose everything as untyped C functions.
There are hundreds of functions so simple inspection of the generated callergraphs is painful.
I'm considering writing some kind of DOT merge tool - setting DOT_CLEANUP=NO makes Doxygen leave the intermediate DOT files there rather then just retaining the png files they generated.
I'm not obsessed by this being a graphical solution - I'd be quite happy if someone could suggest an alternative analysis tool (free or relatively cheap) or technique using Doxygen's XML output to achieve the same goal.
A callergraph amalgamated at the file level does have a certain appeal for client documentation rather than a plain list :-)
Comment: Could You please paste some input examples (I understand there are DOT and XML formats)?
Comment: Unfortunately not without client approval and I probably lack time - off to the US in about 24 hours.

I solved the problem a different way anyway - the algorithmic code is no longer being published as an interface. Instead, the business logic from the GUI is being moved into the same DLL and the only external coupling is commands and property notifications, a much narrower concern!
Comment: Could You... paste some anonymized examples? The problem is interesting as "how to split a program in two in a way where the connection is thin"
Answer: In your Doxyfile, set
GENERATE_XML = YES

and then you can find your call graph in the XML files. For each function marked with the callergraph, you'll find <referencedby> elements in the output that you can use. Here's a sample from one of my C files:
  <memberdef kind="function" id="spfs_8c_1a3"
             prot="public" static="yes" const="no" explicit="no"
             inline="no" virt="non-virtual">
    <type>svn_error_t *</type>
    <definition>svn_error_t * init_apr</definition>
    <argsstring>(apr_pool_t **ppool, int *argc, char const *const **argv)</argsstring>
    <name>init_apr</name>

    <location file="src/spfs.c" line="26" bodystart="101" bodyend="120"/>
    <referencedby refid="spfs_8c_1a13" compoundref="spfs_8c"
                  startline="45" endline="94">main</referencedby>
  </memberdef>

So for every memberdef/referencedby pair, you have a caller-callee relationship, which you can grab via XSLT:
<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="text"/>

    <xsl:template match="/">
        <xsl:apply-templates select="//memberdef[@kind eq 'function']"/>
    </xsl:template>

    <xsl:template match="memberdef">
        <xsl:variable name="function-name"
                      select="concat(definition, argsstring)"/>
        <xsl:for-each select="referencedby">
            <xsl:value-of select="concat(./text(), ' calls ', $function-name, '
')"/>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

Which gives you a line per caller-callee like this:
main calls svn_error_t * init_apr(apr_pool_t **ppool, int *argc, char const *const **argv)

You'll want to tweak that XSLT and then partition that directed graph in the way that cuts across the fewest edges. Woo hoo, an NP-complete problem! Luckily, there are lots of papers on the subject, some are here: http://www.sandia.gov/~bahendr/partitioning.html
Answer: I had a similar requirement.
Wrote a perl script to merge a set of dot files into a single dot file.
https://github.com/bharanis/scripts/blob/master/doxygen_dot_merge.pl
merge multiple doxygen generated dot files.
This is useful for generating a call map for a file or a bunch of files.
1) This command is to be run from outside the html directory where doxygen puts all the html, dot and map files.
2) This command assumes flat directory structure used in doxygen
   CREATE_SUBDIRS         = NO
3) doxygen prefixes the source filename to the name of the output dot files. One dot file is generated per function
4) provide the list of doxygen generated dot files to be merged.
eg:
./doxydotmerge.pl  `ls html/ssd_*_8c*_cgraph.dot  | grep -v test | grep -v buf`

Answer: You could use Scientific Toolworks to see your system-wide call graph.
If you want to automate the analysis and the cutting, you might consider
the DMS Software Reengineering Toolkit. It can compute full call graphs for C
(complete with points-to analysis for function pointers), and has been
proven for systems of 35 million lines of code.  It will
produce full system DOT files to inspect; they are pretty big but you can
pick out subsets to look at.  See flow analysis and call graphs.