Objective C subtraction

Question: When I do this:
NSLog(@"%i",1.5 - 1.00 == 0.5);

I get 1, but when I do this:
NSLog(@"%i",1.33 - 1.00 == 0.33);

I get 0.
Is there any way to get around this?
Comment: Every programmer should understand floating point numbers: http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers In short, 1.33 - 1.00 is not 0.33.
Comment: How many dupes of (variations of) this question have been asked on SO... no effort to use Google... Eh...
Comment: @H2CO3 The problem is that it is hard to explain to Google what you are looking for, unless you know to ask for floating-point precision or something related to it.
Answer: The problem is with the precision of floating-point calculations: you should generally avoid comparing floats and double-precision numbers for equality using == operator, preferring a check for the difference to be smaller than a tiny epsilon (e.g. 1E-9).
#include <math.h>

...

NSLog(@"%i", abs(((1.33 - 1.00) - 0.33) < 1E-9);

The first example works because the numbers are composed of powers of 2: 1 = 2^0, and 0.5 = 2^-1.  The numbers from the second example cannot be decomposed as powers of 2 exactly, so the equality check does not work.

Objective C subtraction


Apache2 (Ubuntu 16.04) subdomain shows main website instead of subdomain website

Question: default.conf
<VirtualHost *:80>
    DocumentRoot /var/www/example
    ServerName example.com
    DirectoryIndex index.php index.html
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot /var/www/subdomain
    ServerName subdomain.example.com
    DirectoryIndex index.php index.html
</VirtualHost>

default-ssl.conf
<IfModule mod_ssl.c>
    <VirtualHost *:443>
        DocumentRoot /var/www/example/public
        SSLEngine on
        SSLCertificateFile      /var/www/Origin.crt
        SSLCertificateKeyFile   /var/www/Key.key

        <FilesMatch "\.(cgi|shtml|phtml|php)$">
                        SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
                        SSLOptions +StdEnvVars
        </Directory>

        # BrowserMatch "MSIE [2-6]" \
        #               nokeepalive ssl-unclean-shutdown \
        #               downgrade-1.0 force-response-1.0
    </VirtualHost>

    <VirtualHost *:443>
        DocumentRoot /var/www/subdomain/public
        SSLEngine on
        SSLCertificateFile      /var/www/Origin.crt
        SSLCertificateKeyFile   /var/www/Key.key

        <FilesMatch "\.(cgi|shtml|phtml|php)$">
                        SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
                        SSLOptions +StdEnvVars
        </Directory>

        # BrowserMatch "MSIE [2-6]" \
        #               nokeepalive ssl-unclean-shutdown \
        #               downgrade-1.0 force-response-1.0
    </VirtualHost>
</IfModule>

If I delete the main site, it loads the subdomain perfectly.
If the main site is enabled the subdomains loads the main site. By load I mean it doesn't redirect, it just loads the main site directory.
Answer: The <VirtualHost *:80> are independent from <VirtualHost *:443> and doesn't inherit any configuration from each other. Both your HTTPS virtualhosts are missing the ServerName directive; the first match gets shown as the default website.


Exterior derivative of 2-forms and divergence

Question: I'm working through A Geometric Approach to Differential Forms. The deriative of a $2$-form $\omega$ in $\mathbb{R}^3$, denoted $d\omega$ and operating on vectors $U, V, W \in T_p \mathbb{R}^3$, is defined as
$$d\omega(U, V, W) = \nabla_U \omega(V, W) - \nabla_V \omega(U, W) + \nabla_W \omega(U, V)$$
where $\nabla_U \omega(V, W)$ denotes the directional derivative of $\omega(V, W)$ in the direction $U$.
Suppose that we have a $2$-form $\omega = f(x, y, z) \ dx \wedge dy + g(x, y, z) \ dy \wedge dz + h(x, y, z) \ dx \wedge dz$. One way to calculate $d\omega$ is to realize that it must have the form $d\omega = a(x, y, z) \ dx \wedge dy \wedge dz$. Geometrically, we can think of $d\omega$ as taking three vectors, calculating the signed volume of the parallelogram formed by those three vectors, and then applying a scaling factor $a(x, y, z)$. So one way to determine $a(x, y, z)$ is to use the above definition of $d\omega(U, V, W)$ to see how it acts on vectors corresponding to a parallelogram of signed volume $1$.
If I take $U = (1, 0, 0)$, $V = (0, 1, 0)$, and $W = (0, 0, 1)$, and I go through the computations, I arrive at
$$d\omega = \left( \frac{\partial g}{\partial x} - \frac{\partial h}{\partial y} + \frac{\partial f}{\partial z} \right) \ dx \wedge dy \wedge dz.$$
This seems to be right as far as I can tell. In particular, the second term is given by $\nabla_V \omega(U, W) = \partial h / \partial y$, with the negative sign coming from the alternating signs in the definition of $d\omega(U, V, W)$. Explicitly, my calculation is
$$\nabla_V \omega(U, W) = \nabla \left( \underbrace{f \begin{vmatrix} 1 & 0 \\ 0 & 0 \end{vmatrix}}_0 + \underbrace{g \begin{vmatrix} 0 & 0 \\ 0 & 1 \end{vmatrix}}_0 + \underbrace{h \begin{vmatrix} 1 & 0 \\ 0 & 1 \end{vmatrix}}_h \right) \cdot V = \frac{\partial h}{\partial y}.$$
Furthermore, I know that there's a connection between the exterior derivative of a $2$-form in $\mathbb{R}^3$ and the operation of the divergence. From, e.g., the Wikipedia description, it seems that divergence is
$$(g, h, f) \mapsto \frac{\partial g}{\partial x} + \frac{\partial h}{\partial y} + \frac{\partial f}{\partial z}$$
where I've ordered $f, g, h$ for consistency with the representation of $\omega$.
The difference here compared to my expression for $d\omega$ is that the term $\partial h / \partial y$ is positive rather than negative.
Whence the difference?
Answer: You are using $dx\wedge dz$ and the wiki page is using $dz\wedge dx$. So there is no difference.
remark: In general for an $n-1$ form, one usually insert some $(-1)$'s to deal with this: a general $n-1$ form $\alpha$ is written as
$$\alpha = \sum_{i=1}^n (-1)^{i-1} \alpha_i dx^1 \wedge \cdots \wedge\widehat{dx^i} \wedge\cdots \wedge dx^n$$
so that
$$d\alpha = \left( \frac{\partial \alpha_1}{\partial x^1}+ \cdots +  \frac{\partial \alpha_n}{\partial x^n}\right) dx^1 \wedge \cdots \wedge dx^n. $$
Comment: Thanks, this is obvious, I should have realized it.


Adding a field to users from a module.install file

Question: Is it possible to add a custom field to users from a module.install file, as it would be done from admin/config/people/accounts/fields?
Answer: It is possible, in the same way forum_enable() adds a new field to the "forum" content type; the only difference is that "entity_type" and "bundle" are both set to "user."
// Create the 'taxonomy_forums' field if it doesn't already exist.
if (!field_info_field('taxonomy_forums')) {
  $field = array(
    'field_name' => 'taxonomy_forums',
    'type' => 'taxonomy_term_reference',
    'settings' => array(
      'allowed_values' => array(
        array(
          'vocabulary' => $vocabulary->machine_name,
          'parent' => 0,
        ),
      ),
    ),
  );
  field_create_field($field);
}

// …

// Create the instance on the bundle.
$instance = array(
  'field_name' => 'taxonomy_forums',
  'entity_type' => 'node',
  'label' => $vocabulary->name,
  'bundle' => 'forum',
  'required' => TRUE,
  'widget' => array(
    'type' => 'options_select',
  ),
  'display' => array(
    'default' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    ),
    'teaser' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    ),
  ),
);
field_create_instance($instance);

You can implement a similar code in the hook_enable() implementation of your module, or in the hook_install() implementation; in the first case, you should check if the field doesn't already exists, or field_create_instance() raises an exception.
To verify the field doesn't already exist, you can use code similar to the following one, where $instance is the same array as used in the previous code:
$prior_instance = field_read_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
if (empty($prior_instance)) {
  field_create_instance($instance);
}

Comment: What method in the install file would I put this in?
Comment: I corrected my answer: The bundle for user fields is "user"; if you don't set it, the code will raise a PHP exception.


Simplify a function for multiple elements

Question: I have multiple modal windows that work with nearly the same function.
I'm asking myself is it possiibe to rewrite the function in the direction that I don't have to repeat the function for each new modal window.
Basicially I have two unique selectors for each modal window:
// Modal window
var $modal1 = $('#modal1');

// button that open the modal window
var $modal1form = $('.openmodel1');

JSFIDDLE
https://jsfiddle.net/n5yc7kgz/1/
And here is the complete code:
jQuery(document).ready(function($) {

  // modal1

  var $modal1 = $('#modal1'),
    $modal1form = $('.openmodel1');

  $modal1form.on('click', function(event) {

    if ($(event.target).is($modal1form)) {
      $(this).children('ul').toggleClass('is-visible');
    } else {
      $modal1form.children('ul').removeClass('is-visible');
      $modal1.addClass('is-visible');
    }

  });

  $('.modalbox').on('click', function(event) {
    if ($(event.target).is($modal1) || $(event.target).is('.close')) {
      $modal1.removeClass('is-visible');
    }
  });
  $(document).keyup(function(event) {
    if (event.which == '27') {
      $modal1.removeClass('is-visible');
    }
  });

  // modal2
  var $modal2 = $('#modal2'),
    $modal2form = $('.openmodel2');

  // Offerform
  $modal2form.on('click', function(event) {

    if ($(event.target).is($modal2form)) {
      $(this).children('ul').toggleClass('is-visible');
    } else {
      $modal2form.children('ul').removeClass('is-visible');
      $modal2.addClass('is-visible');
    }

  });

  $('.modalbox').on('click', function(event) {
    if ($(event.target).is($modal2) || $(event.target).is('.close')) {
      $modal2.removeClass('is-visible');
    }
  });
  $(document).keyup(function(event) {
    if (event.which == '27') {
      $modal2.removeClass('is-visible');
    }
  });

});

Comment: Can you add the code in jsFiddle.net and share the URL
Comment: You can use for loop
Comment: https://jsfiddle.net/n5yc7kgz/1/
Answer: Please see the below code changes. DEMO

I have changed the link class names to match the modal window id
names. i.e #modal1 and .modal1. Hence when u click on the link
,you can get the clicked link s class and apply it as the pop up
window id and open it.
And when u click on close , it looks for the .loginbox-user-modal class and removes the visible class attached to it.

HTML:

        close
        Modal 1

        close
        Modal 1

modal1
//changed the class name to modal1, similar to the modal window id name

modal2

JS
jQuery(document).ready(function($) {

  $('.modal1, .modal2').on('click', function(event) {

    var $modal = $('#'+$(this).attr("class")),
    $modalform = $('.'+$(this).attr("class"));
    if ($(event.target).is($modalform)) {
      $(this).children('ul').toggleClass('is-visible');
    } else {
      $modalform.children('ul').removeClass('is-visible');
      $modal.addClass('is-visible');
    }

  });

  $('.loginbox').on('click', function(event) {
    if ( $(event.target).is('.icon-close')) {
      $('.loginbox-user-modal').removeClass('is-visible');
    }
  });
  $(document).keyup(function(event) {
    if (event.which == '27') {
      $('.loginbox-user-modal').removeClass('is-visible');
    }
  });

});

jQuery(document).ready(function($) {

  $('.modal1, .modal2').on('click', function(event) {

    var $modal = $('#'+$(this).attr("class")), $modalform = $('.'+$(this).attr("class"));
    if ($(event.target).is($modalform)) {
      $(this).children('ul').toggleClass('is-visible');
    } else {
      $modalform.children('ul').removeClass('is-visible');
      $modal.addClass('is-visible');
    }

  });

  $('.loginbox').on('click', function(event) {
    if ( $(event.target).is('.icon-close')) {
      $('.loginbox-user-modal').removeClass('is-visible');
    }
  });
  $(document).keyup(function(event) {
    if (event.which == '27') {
      $('.loginbox-user-modal').removeClass('is-visible');
    }
  });

});
.loginbox {
  width: 500px;
  height: 500px;
  background: #fff;
}

.loginbox-user-modal {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #111;
  z-index: 30000;
  overflow-y: auto;
  cursor: pointer;
  visibility: hidden;
  opacity: 0;
  transition: all 0.3s;
}

.loginbox-user-modal.is-visible {
  visibility: visible;
  opacity: 1;
}

.loginbox-user-modal.is-visible .loginbox-user-modal-container {
  -webkit-transform: translateY(0);
  -moz-transform: translateY(0);
  -ms-transform: translateY(0);
  -o-transform: translateY(0);
  transform: translateY(0);
}

.loginbox-user-modal-container {
  position: relative;
  width: 100%;
  max-width: 700px;
  margin: 3em auto 4em;
  cursor: auto;
  box-sizing: border-box;
  margin-top: 50px !important;
  -webkit-transform: translateY(-30px);
  -moz-transform: translateY(-30px);
  -ms-transform: translateY(-30px);
  -o-transform: translateY(-30px);
  transform: translateY(-30px);
  -webkit-transition-property: -webkit-transform;
  -moz-transition-property: -moz-transform;
  transition-property: transform;
  -webkit-transition-duration: 0.3s;
  -moz-transition-duration: 0.3s;
  transition-duration: 0.3s;
}

.icon-close {
  width: 40px;
  height: 40px;
  line-height: 40px !important;
  text-align: center;
  border-radius: 50%;
  font-size: 18px;
  transition: background-color 0.2s;
  cursor: pointer;
  color: #777;
  position: absolute;
  z-index: 1000000;
  right: 24px;
  top: 37px;
}

.icon-close:hover {
  background: #f5f5f5;
}

  close
  Modal 1

  close
  Modal 1

modal1

modal2


Microsoft Excel Security Warning - Pop Up

Question: I am getting this Error when i click a link on an internal company site.
The link is pointing to an excel spreadsheet, but the link does not end in .xls or anything like that.
This works in chrome correctly, but in internet explorer it does not.
The page displays the data in a HTML formatted page, i.e it doesn't look like an excel spreadsheet.
Any thoughts on how to get rid of this error.
I have tried http and https with no luck.
Sorry i cannot post what the page looks like, regardless it is a spreadsheet that is being formatted into a HTML page, for users to view the data.
Thanks
Comment: Why do people vote down, what more can i say?
Comment: Don't let it bother you - I upvoted this.
Answer: Check this information about Office 2013 error from Microsoft: https://blogs.technet.microsoft.com/office_integration__sharepoint/2015/04/20/office-2013-error-certificate-error-the-application-experienced-an-internal-error-loading-the-ssl-libraries-when-opening-files/
Comment: I'm sad... My organization doesn't seem to have a way around this! : |


Printing a Multi-page JPanel

Question: I'm nervous about asking this because I'm scared I'll get told off. I am trying to print a JPanel that is about 4 pages long.  It could be more, the data is from a JDBC MySql query, that could end up being many more that 4. The JPanel I am trying to print is full of other JPanels (with competitors race details on them) that I have added via a ListArray..
Anyway, I have scoured all day through stackoverflow and have found may examples of code that I have tried to implement. The printable class only prints the first page, so I have tried to implement the pageable class, but I just can't seem to get it right. I have tried to implement the Book class but don't know how to add my JPanel to the book. I have looked here, here and many more (I'm only allowed to post 2 links).
Here is my current code (that I got off one of the answers that @madprogrammer gave) -
int printButton = JOptionPane.showOptionDialog(null, scrollPane, "Race Winners", JOptionPane.YES_NO_OPTION,
        JOptionPane.PLAIN_MESSAGE, // no Icon
        null, //do not use a custom Icon
        options, //the titles of buttons
        options[0]); //default button title

if (printButton == 0) {
    try {
        printComponent(pane, true);

        //printComponentToFile(pane, false);

    } catch (PrinterException exp) {
        exp.printStackTrace();
    }

    public static void printComponent(JComponent comp, boolean fill) throws PrinterException {
        PrinterJob pjob = PrinterJob.getPrinterJob();
        //pjob.setPageable(comp);
        PageFormat pf = pjob.defaultPage();
        pf.setOrientation(PageFormat.PORTRAIT);

        PageFormat postformat = pjob.pageDialog(pf);

        if (pf != postformat) {
            //Set print component
            //pjob.setPageable(comp);
            pjob.setPrintable(new ComponentPrinter(comp, fill), postformat);

            if (pjob.printDialog()) {
                pjob.print();
            }
        }
    }

    public static void printComponentToFile(Component comp, boolean fill) throws PrinterException {
        Paper paper = new Paper();
        paper.setSize(8.3 * 72, 11.7 * 72);
        paper.setImageableArea(18, 18, 559, 783);

        PageFormat pf = new PageFormat();
        pf.setPaper(paper);
        pf.setOrientation(PageFormat.PORTRAIT);

        BufferedImage img = new BufferedImage(
        (int) Math.round(pf.getWidth()), (int) Math.round(pf.getHeight()),
        BufferedImage.TYPE_INT_RGB);

        Graphics2D g2d = img.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fill(new Rectangle(0, 0, img.getWidth(), img.getHeight()));
        ComponentPrinter cp = new ComponentPrinter(comp, fill);

        try {
            cp.print(g2d, pf, 0);
        } finally {
            g2d.dispose();
        }

        try {
            ImageIO.write(img, "png", new File("Page-" + (fill ? "Filled" : "") + ".png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static class ComponentPrinter implements Printable, Pageable {
        private Component comp;
        private boolean fill;
        int numPages;
        PageFormat format;

        public ComponentPrinter(Component comp, boolean fill) {
            this.comp = comp;
            this.fill = fill;
        }

        @Override
        public int print(Graphics g, PageFormat format, int page_index) throws PrinterException {

            numPages = (int) Math.ceil(comp.getHeight() / format.getImageableY());
            System.out.print(numPages);

            if (page_index > 0) {
                return Printable.NO_SUCH_PAGE;
            }

            Graphics2D g2 = (Graphics2D) g;
            g2.translate(format.getImageableX(), format.getImageableY());
            //g2.translate(format.getImageableX(), format.getImageableY()- page_index*comp.getPreferredSize().height);

            double width = (int) Math.floor(format.getImageableWidth());
            double height = (int) Math.floor(format.getImageableHeight());

            if (!fill) {

                width = Math.min(width, comp.getPreferredSize().width);
                height = Math.min(height, comp.getPreferredSize().height);

            }

            comp.setBounds(0, 0, (int) Math.floor(width), (int) Math.floor(height));
            if (comp.getParent() == null) {
                comp.addNotify();
            }
            comp.validate();
            comp.doLayout();
            comp.printAll(g2);
            if (comp.getParent() != null) {
                comp.removeNotify();
            }

            return Printable.PAGE_EXISTS;
        }
        @Override
        public int getNumberOfPages() {
            // TODO Auto-generated method stub
            return numPages;
        }
        @Override
        public PageFormat getPageFormat(int arg0) throws IndexOutOfBoundsException {
            return format;
        }
        @Override
        public Printable getPrintable(int arg0) throws IndexOutOfBoundsException {
            // TODO Auto-generated method stub
            return this;
        }
}

This all works, but only prints the first page.  I would REALLY appreciate a nudge in the right direction with this as I'm stumped. TIA :-)
Answer: This is how you print a Component (JPanel) on multiple pages:
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.*;

import javax.swing.RepaintManager;

public class PrintMultiPageUtil implements Printable, Pageable {
    private Component componentToBePrinted;
    private PageFormat format;
    private int numPages;

    public PrintMultiPageUtil(Component componentToBePrinted) {
        this.componentToBePrinted = componentToBePrinted;

        // get total space from component
        Dimension totalSpace = this.componentToBePrinted.getPreferredSize();

        // calculate for DIN A4
        format = PrinterJob.getPrinterJob().defaultPage();
        numPages = (int) Math.ceil(totalSpace .height/format.getImageableHeight());
    }

    public void print() {
        PrinterJob printJob = PrinterJob.getPrinterJob();

        // show page-dialog with default DIN A4
        format = printJob.pageDialog(printJob.defaultPage());

        printJob.setPrintable(this);
        printJob.setPageable(this);

        if (printJob.printDialog())
            try {
                printJob.print();
            } catch(PrinterException pe) {
                System.out.println("Error printing: " + pe);
            }
    }

    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        if ((pageIndex < 0) | (pageIndex >= numPages)) {
            return(NO_SUCH_PAGE);
        } else {
            Graphics2D g2d = (Graphics2D)g;
            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY() - pageIndex * pageFormat.getImageableHeight());
            disableDoubleBuffering(componentToBePrinted);
            componentToBePrinted.paint(g2d);
            enableDoubleBuffering(componentToBePrinted);
            return(PAGE_EXISTS);
        }
    }

    public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
    }

    public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    }

    @Override
    public int getNumberOfPages() {
        // TODO Auto-generated method stub
        return numPages;
    }

    @Override
    public PageFormat getPageFormat(int arg0) throws IndexOutOfBoundsException {
        return format;
    }

    @Override
    public Printable getPrintable(int arg0) throws IndexOutOfBoundsException {
        // TODO Auto-generated method stub
        return this;
    }
}

numPages
I changed the expression for numPages to:
(int) Math.ceil(page.height/format.getImageableHeight())

This divides the total height (height of the jpanel) through the height of one page, thus calculating the number of all pages.
g2d.translate
I did the following change: In this line:
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY() - pageIndex * pageFormat.getImageableHeight());

Changed componentToBePrinted.getPreferredSize().height to pageFormat.getImageableHeight(). A positive value for the first or the second parameter of g2d.translate moves the graphic to the right or down respectively.
.getImageableX() and .getImageableY() help position the graphic so that it doesn't overlap with the padding.
For pageIndex greater than 0, - pageIndex * pageFormat.getImageableHeight() moves the image pageIndex-times the page-height to the top. So the area, that the pageIndex refers to is printed.
original broken source:: https://community.oracle.com
Here is my original answer.

Printing a Multi-page JPanel


create tabs with hook_menu() for custom module

Question: since two hours im trying to create tabs in my custom modules backend.
I've tried severals suggestions but couldn't get any of them to work.
this is my current hook_menu() :
    function social_links_menu() {
  $items['admin/config/system/social_links'] = array(
    'title' => 'social_links',
    'description' => 'Configure to fit clients needs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('social_links_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'social_links.admin.inc',
  );

  return $items;
}

I simply want two tabs called: 'tab1' and 'tab2'.
Can someone give me an working example? This should be really simple, but right now it seems impossible
Answer: You need to define a 'root' path which is a normal menu item, and then add another item for each of the tabs. The first of these will inherit the properties of the root item, and the second will define its own callbacks.
Combined with the MENU_LOCAL_TASK and MENU_DEFAULT_LOCAL_TASK type constants, you should get the tabs you expect:
function social_links_menu() {
  $items['admin/config/system/social_links'] = array(
    'title' => 'social_links',
    'description' => 'Configure to fit clients needs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('social_links_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'social_links.admin.inc',
  );

  $items['admin/config/system/social_links/tab1'] = array(
    'title' => 'Tab 1',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10
  );

  $items['admin/config/system/social_links/tab2'] = array(
    'title' => 'Tab 2',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'some_callback',
    'access arguments' => array('some permission')
  );

  return $items;
}

Comment: thanks for the lesson clive! Good explanation. You just saved me a few hours :)


Selenium Proxy Error when intializing webdriver

Question: When using selenium for work behind enterprise firewall, it's necessary to connect to proxy to access internet. However, selenium is returning proxy error even when initializing the webdriver.
from selenium import webdriver

proxy='x.x.x.x:xxx'
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(f'--proxy-server={proxy}')
driver = webdriver.Chrome(options=chrome_options)

Getting 401 unauthorized error even before visiting any webpage.
Answer: After exhaustive search to no avail. Because the webdriver initialization only connects to localhost, it shouldn't need proxy. Adding the '--no-proxy-server' option resolved this issue. This was suggested by chatgpt but not for the right reason.
from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(f'--no-proxy-server')
driver = webdriver.Chrome(options=chrome_options)


Fractional part of rational power arbitrary small

Question: I think that $\{a^n\}$ (where $\{x\}$ is $x \pmod 1$), where $a$ is fixed rational greater than 1 and $n$ is positive integer, is dense in $[0,1]$ is unsolved. However what about $\{a^n\}$ is arbitrary small for some $n$ ($a$ is fixed rational as well).
Comment: If ${a^n}$ is shown to take on arbitrarily small values, for every possible rational (nonintegral) $a>1$, then that would mean that $0$ had been shown to be a limit point of the fractional parts of all the possible choices of base $a$ for the powers $a^n$. If this were known it likely would have appeared on the Wolfram page http://mathworld.wolfram.com/PowerFractionalParts.html but I didn't see it there. The subject seems complex in general.
Comment: seems like you are saying that n is fixed as we vary a. i will try and rephrase the problem
Comment: Actually I see that it means for a fixed $a$ one computes the fractional parts of $a,a^2,a^3,\cdots$ and checks whether that sequence has $0$ as a limit point. This idea of limit points of these sequences (for fixed $a$) is what is discussed on the Wolfram page I linked in my previous comment.
Answer: I think that the wolfram link cited the first result (Vijayaraghavan 1941) incorrectly where it reports that

$\{ (3/2)^n \}$ has infinitely many accumulation points in both $[0, 1/2)$ and $[1/2, 1]$.

The first result actually is

$\{ (3/2)^n \}$ has infinitely many accumulation points in $[0,1]$.

The second result cited by wolfram is by Flatto, Lagarias, Pollington (1995) which is available here: http://matwbn.icm.edu.pl/ksiazki/aa/aa70/aa7023.pdf. In the introduction of this paper by them, it reports that

Vijayaraghavan later remarked that it was striking that
  one could not even decide whether or not $(3/2)^n$ mod $1$ has infinitely
  many limit points in $[0, 1/2)$ or in $[1/2, 1)$.

This paper proved that

$$\limsup\{ (3/2)^n \} - \liminf \{(3/2)^n\} \geq \frac13. $$

A few later results are mentioned (Dubickas 2006, 2008) in Yann Bugeaud's book "Distribution Modulo One and Diophantine Approximation" (for example, p. xi, p. 67 and p. 68).

$\{ (3/2)^n \}$ has a limit point in $[0.238117 . . . , 0.761882 . . .]$ which has length $0.523764 . . .$.
$\{(3/2)^n\}$ has a limit point in $[0, 8/39] \cup
[18/39, 21/39] \cup [31/39, 1]$, of total length $19/39$.
Comment: @MartinSleziak, Thank you very much for putting the links to the papers and the book, also for the bounty.
Comment: Though accepted and rewarded, this answer does not adress the question, which was: "what about $\{a^n\}$ is arbitrary small for some $n$?"
Answer: I will show that
if $a = 1+\sqrt{2}$
then the limit points of
$\{a^n\}$
are $0$ and $1$.
I know that this doesn't tell anything
about rational $a$,
but this might be of use.
Note that this method can show this
for $a$ and $b$ roots of
$x^2-2ux-v = 0$
where $u$ and $v$ are
positive integers such that
$v < 2u+1$.
This case is $u=v=1$;
$u=1, v=2$ also works.
If $a = \sqrt{2}+1$
and
$b = 1-\sqrt{2}$
then
$ab = -1$
and
$a+b = 2$.
Therefore $a$ and $b$
are the roots of
$x^2-2x-1 = 0$.
If $u_n = a^n+b^n$,
then
$u_0 = 2,
u_1 = 2$.
Since
$a^{n+2}
=a^n(a^2)
=a^n(2a+1)
=2a^{n+1}+a^n$
and similarly for $b$,
$\begin{array}\\
u_{n+2}
&=a^{n+2}+b^{n+2}\\
&=2a^{n+1}+a^n+2b^{n+1}+b^n\\
&=2u_{n+1}+u_n\\
\end{array}
$
Therefore
$u_n$ is a
positive integer for all $n$.
Since
$|b| < 1$,
$|b^n| \to 0$.
Since
$b < 0$,
$b^{2n} > 0$
and
$b^{2n+1} < 0$.
Therefore,
since
$a^n = u_n - b^n$,
$\{a^{2n}\}
=\{u_{2n}-b^{2n}\}
=1-b^{2n}
$
so
$\{a^{2n}\}
\to 1
$
and
$\{a^{2n+1}\}
=\{u_{2n+1}-b^{2n+1}\}
=\{u_{2n+1}+|b^{2n+1}\}
=|b^{2n+1}|
$
so
$\{a^{2n+1}\}
\to 0
$.
Therefore
the limits points of
$\{a^n\}$
are $0$ and $1$.
Comment: But does the problem not ask for rational $a$? Quadratic surds are a much easier case.
Comment: I mentioned that in my answer.
Comment: @Oscar :One should say *"this answer is really a comment, but too long for a comment-box"*. But I find it useful to see one way of reasoning, even if the variable *a* is irrational here, how one could possibly approach such a question.
Answer: Edit: sorry, I now realize that the question asks whether 0 is a limit point of $\{a^n\}$. My answer below is not a paraphrase of the question but is something weaker. But I still hope it helps.

Let me rephrase the question:
Let $a$ be a rational greater than 1, is it true that $\lim_{n \to \infty}\{a^n\} = 0$?
When $a$ is an integer, yes, $\lim_{n \to \infty}\{a^n\} = \lim_{n \to \infty} 0 = 0$.
However, When $a$ is a noninteger rational, $\lim_{n \to \infty}\{a^n\} \ne 0$.
Proof by contradiction, assume $\lim_{n \to \infty}\{a^n\} = 0$. let $$ be the denominator of $\{a\}$, we can find an $$ such that $∀ n > $, $\{x^n\} < \frac{1}{aq}$.
Let $ > $, we have
$$\{a^m\} < \frac{1}{aq} \tag{1}\label{1}$$ and
$$\{a^{m+1}\} < \frac{1}{aq} < \frac{1}{q} \tag{2}\label{2} $$
where
\begin{align}
\{a^{m+1}\} &=  \{ (⌊a^m⌋ + \{a^m\}) (⌊a⌋ + \{a\}) \} \\  & = \{ ⌊a^m⌋⌊a⌋ + ⌊a^m⌋\{a\} +  \{a^m\}(⌊a⌋ + \{a\}) \} \\
&= \{⌊a^m⌋\{a\} +  \{a^m\}(⌊a⌋ + \{a\})\} \\
&= \{⌊a^m⌋\{a\} +  \{a^m\}a\} \\
& = \{\{⌊a^m⌋\{a\}\} +  \{a^m\}a\}
\end{align}
where the last step comes from the observation that { + } = {{} + }.
Note $\{⌊a^m⌋\{a\}\}$ is one of $1/, 2/, 3/... (-1) / $, in particular
$$ \frac{1}{q} \le \{⌊a^m⌋\{a\}\} \le \frac{q-1}{q}  \tag{3}\label{3}$$
We have $1/ < \{⌊a^m⌋\{a\}\} +  \{a^m\}a < 1$ by \eqref{1} \eqref{3}, which implies $\{a^{m+1}\} = \{\{⌊a^m⌋\{a\}\} +  \{a^m\}a\} > 1/$ which contradicts \eqref{2}.


window.navigator.standalone in Angular 6 missing?

Question: Window.navigator.standalone is for checking that the website is running in PWA or not, basically, I want to show a message on the website "hey, you can install it as an app too".
but I found no way other than this, especially for iOS Safari.
please suggest in this case what do I do?
const isInWebAppiOS = window.navigator.standalone;
const isInWebAppChrome = window.matchMedia('(display-mode: standalone)')
      .matches;
alert(
      'isInWebAppiOS: ' +
        isInWebAppiOS +
        'isInWebAppChrome: ' +
        isInWebAppChrome
    );

this is what I have been trying.
shareClick() {
    let newVariable: any;
    newVariable = window.navigator;
    debugger;
    const isInWebAppiOS = JSON.stringify(window.navigator);
    const isInWebAppChrome = window.matchMedia('(display-mode: standalone)')
      .matches;
    alert(
      'isInWebAppiOS: ' +
        isInWebAppiOS +
        'isInWebAppChrome: ' +
        isInWebAppChrome
    );
    if (newVariable && newVariable.share) {
      newVariable
        .share({
          title: this.title,
          text: this.description,
          url: window.location.href
        })
        .then(() => console.log('Successful share'))
        .catch(error => console.log('Error sharing', error));
    } else {
      this.dialogService.shareWithData(window.location.href);
    }
  }

Answer: This is how I detect it (same thing I prompt for PWA install in iOS/Safari as well as Chrome in general).
this.isInStandaloneMode = ('standalone' in window.navigator) && (window.navigator['standalone']);


Determine the provider of an email address

Question: I'm trying to implement a "Sign Up" function for my website that allows people to sign up with their enterprise credentials.
I would love for it to be as easy as a textbox that they type their email address into without having to select a provider like "Outlook.com" or "Gmail" or "Salesforce"
Is there a way to sniff out the email provider by the address?
PSEUDO
bool isOutlook = outlookapi.doesaddressexist("firstname.lastname@example.com")
Answer: If you just want to extract the domain name you can use regex and a formula field:
"\\@.*" // returns e.g. @ibm.com

EDIT
Another option is to use pattern matching in apex. In a second step create a new sObject called "Provider-Domain" add a Text field called "domain". Create an entry for each provider and build a new SOQL query like:
[SELECT Name FROM Provider_Domain__c WHERE Domian__c = :YOUR_EXTRACTED_DOMAIN]

Comment: I appreciate the response, but that wasn't the question. The domain != the provider. IBM.COM could be a mail address from many providers.


Commerce orders - header

Question: On the orders admin page you have options to change fields in your table and sort fields, ect. In the headers option I have 'global: view order form' selected, and above the table there is a box where you can search for order numbers. I want to be able to not only search for order numbers, but also search for customer names, dates, money amounts, ect. Can you add in search criteria to that header?
Answer: Did yout try simply add new filters?
For example, user:

Add Filter Criteria
Chose Filter - User
Search for "name" field
Select "User: Name"
Check "Expose this filter to visitors, to allow them to change"
Click "Apply"

That's all you need to do. I should notice that for amount and date you can expose operator for your own needs.

In the same way you can add SORT CRITERIAS
Comment: Thank you so much - I tried using filter criteria but was selecting one wrong category. It works! Thanks again.
Comment: You are welcome, glad to help!

Commerce orders - header


Upload arquivo via FTP - PHP

Question: Eu estou tentando fazer o upload de arquivos para uma pasta específica do meu servidor da Hostgator, porém eu coloco o caminho exato da pasta e o arquivo não aparece na pasta que setei o caminho, ela aparece na pasta raíz. Segue o código:
'

/*-----------------------------------------------------------------------------*
 * Parte 1: Configurações do Envio de arquivos via FTP com PHP
/*----------------------------------------------------------------------------*/

// IP do Servidor FTP
$servidor_ftp = 'br476.hostgator.com.br';

// Usuário e senha para o servidor FTP
$usuario_ftp = 'hugohs';
$senha_ftp   = 'ajbsistemas2018';

// Extensões de arquivos permitidas
$extensoes_autorizadas = array( '.exe', '.jpg', '.mp4', '.mkv', '.txt', '.png' );

// Caminho da pasta FTP
$caminho = '/public_html/Video';

/*
Se quiser limitar o tamanho dos arquivo, basta colocar o tamanho máximo
em bytes. Zero é ilimitado
*/
$limitar_tamanho = 0;

/*
Qualquer valor diferente de 0 (zero) ou false, permite que o arquivo seja
sobrescrito
*/
$sobrescrever = 0;

/*-----------------------------------------------------------------------------*
 * Parte 2: Configurações do arquivo
/*----------------------------------------------------------------------------*/

// Verifica se o arquivo não foi enviado. Se não; termina o script.
if ( ! isset( $_FILES['arquivo'] ) ) {
    exit('

 Nenhum arquivo enviado!
');
}

// Aqui o arquivo foi enviado e vamos configurar suas variáveis
$arquivo = $_FILES['arquivo'];

// Nome do arquivo enviado
$nome_arquivo = $arquivo['name'];

// Tamanho do arquivo enviado
$tamanho_arquivo = $arquivo['size'];

// Nome do arquivo temporário
$arquivo_temp = $arquivo['tmp_name'];

// Extensão do arquivo enviado
$extensao_arquivo = strrchr( $nome_arquivo, '.' );

// O destino para qual o arquivo será enviado
$destino = $caminho . $nome_arquivo;

/*-----------------------------------------------------------------------------*
 *  Parte 3: Verificações do arquivo enviado
/*----------------------------------------------------------------------------*/

/*
Se a variável $sobrescrever não estiver configurada, assumimos que não podemos
sobrescrever o arquivo. Então verificamos se o arquivo existe. Se existir;
terminamos aqui.
*/

if ( ! $sobrescrever && file_exists( $destino ) ) {
    exit('

 Arquivo já existe.
');
}

/*
Se a variável $limitar_tamanho tiver valor e o tamanho do arquivo enviado for
maior do que o tamanho limite, terminado aqui.
*/

if ( $limitar_tamanho && $limitar_tamanho < $tamanho_arquivo ) {
    exit('

 Arquivo muito grande.
');
}

/*
Se as $extensoes_autorizadas não estiverem vazias e a extensão do arquivo não
estiver entre as extensões autorizadas, terminamos aqui.
*/

if ( ! empty( $extensoes_autorizadas ) && ! in_array( $extensao_arquivo, $extensoes_autorizadas ) ) {
    exit('

 Tipo de arquivo não permitido.
');
}

/*-----------------------------------------------------------------------------*
 * Parte 4: Conexão FTP
/*----------------------------------------------------------------------------*/

// Realiza a conexão
$conexao_ftp = ftp_connect( $servidor_ftp );

// Tenta fazer login
$login_ftp = @ftp_login( $conexao_ftp, $usuario_ftp, $senha_ftp );

// Se não conseguir fazer login, termina aqui
if ( ! $login_ftp ) {
    exit('Usuário ou senha FTP incorretos.');
}

// Envia o arquivo
if ( @ftp_put( $conexao_ftp, $destino, $arquivo_temp, FTP_BINARY ) ) {
    // Se for enviado, mostra essa mensagem
    echo '

 Arquivo enviado com sucesso!
';
} else {
    // Se não for enviado, mostra essa mensagem
    echo '

 Erro ao enviar arquivo!
';
}

// Fecha a conexão FTP
ftp_close( $conexao_ftp );'

O arquivo retorna mensagem de envio com sucesso, porém ele em vez de aparecer na pasta "softwares", ele aparece na pasta "public_html".

Tem alguma solução para esse problema ?
Comment: Não tem o resto do código na sua pergunta para verificar se concatenou uma barra no caminho mas acho que falta uma `/`  nesse caminho `**$caminho = '/public_html/softwares/';**` ou mais adiante no código
Comment: Coloquei o restante do código PHP agora, seria isso ?
Comment: fiz isso que você comentou e deu certo, anteriormente tinha feito e não tinha dado certo, obrigado !
Answer: Na figura a pasta a ser considerada é  software e no código está Video mas isso não tem importancia, vou considerar como sendo na pasta Video

Supondo que o valor da variável $nome_arquivo seja imagem1.jpg

Sabemos que o valor da variável $caminho é /public_html/Video
concatenando as duas variáveis, para atribuir esse valor a variável $destino  temos como resultado /public_html/Videoimagem1.jpg
o que explica o porque está sendo salvo na raiz.
Portando a solução é dada no comentário do @LeoCaracciolo
$caminho = /public_html/Video/
sendo assim; $destino=/public_html/Video/imagem1.jpg
Comment: Entendi, exatamente isso que estava acontecendo, obrigado pela explicação

Upload arquivo via FTP - PHP


configure iptables to allow in/out bound connections from the WAN (web) and only a couple pcs on the LAN while blocking anything else

Question: I have a Xen server with several Virtual Machines on it sitting along side normal pcs on my LAN. The VMs host content bound for web access. Httpd is one of them so lets use that as an example.
I would like to configure iptables (or my network) as such:

Allow loopback
<code>-A INPUT -i lo -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
</code>
Allow port 80 In/out-bound connections from/to the WAN (web).
Allow port foo In/out-bound traffic to/from a whitelisted computer on the LAN, while denying the rest of the LAN.
<code>#allow one ip with port foo
-A INPUT -i eth0 -p tcp -s 192.168.0.w --dport foo -m state --state NEW,ESTABLISHED -j ACCEPT
-A OUTPUT -o eth0 -p tcp --sport foo -m state --state ESTABLISHED -j ACCEPT

#block the rest of the lan
-A INPUT -i eth0 -m iprange --src-range 192.168.1.x-192.168.1.y -j DROP
-A OUTPUT -o eth0 -m iprange --src-range 192.168.1.m-192.168.1.n -j DROP
</code>
DENY all other traffic of type.
<code>-P INPUT DROP
-P OUTPUT DROP
-P FORWARD DROP
</code>

Essential I would like my VMs only to be able to talk to the Web and other VMs (in a certain block range on the LAN).  Is this possible just using iptables?  If not how would I achieve this?
My current iptables look as such (most of which was pre-generated by centos):
<code># Generated by iptables-save v1.4.7 on Tue Mar 12 10:43:43 2013
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
# Completed on Tue Mar 12 10:43:43 2013
</code>
Currently with my development boxes I can access my content, but I'm looking to harden my network, and protect my non-server pcs.  And I haven't had enough experience with iptables to trust my self with this.
Thanks in advance.
P.S. I also need to take into consideration network communication between Dom0 and the VMs.
Answer: At the first glance suggested rules seem to be fine. But do not forget to allow DNS-traffic - destination UDP port 53 to your DNS-servers on WAN.
Comment: Thanks for the hint about DNS totally slipped my mind, kinda need that hehehe.

Any help for condition 2? I want to allow every IP request from outside the LAN (of course only after they have forwarded through the router). Should I just block every private internal IP that is not in my required range, with something like this?

-I INPUT -m iprange --src-range 192.168.1.10-192.168.1.13 -j DROP

Or were you saying the pre-generated iptable is sufficient?
Comment: Okay, how many interfaces does your web-server have?
Comment: at the moment one physical, multiple virtual (cause there are different vms right).  I can add more though if required.
Answer: Maybe I answered my own question, was talking this over with a friend. This is what we came up with if it helps anyone.
<code>*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]

-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT

#Loopback
-A INPUT -i lo -j ACCEPT

#DNS Servers
-A INPUT -i eth0 -p udp --sport 53 -j ACCEPT

#SSH conditional
-A INPUT -i eth0 -p tcp -s 192.168.0.x --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
-A OUTPUT -o eth0 -p tcp -d 192.168.0.x --sport 22 -m state --state ESTABLISHED -j ACCEPT

#communicate with some other server on the lan
-A INPUT -i eth0 -p tcp -s 192.168.0.y --dport yp -m state --state NEW,ESTABLISHED -j ACCEPT
-A OUTPUT -o eth0 -p tcp -d 192.168.0.y --sport yp -m state --state ESTABLISHED -j ACCEPT

#HTTP
-A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT

#HTTPS
-A INPUT -i eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT

#Drop other output to my LAN
-A OUTPUT -d 192.168.0.1/24 -j REJECT

-A INPUT -j DROP
-A FORWARD -j DROP
COMMIT
</code>


What is the actual function of the C# project setting "Allow unsafe code"

Question: I was wondering if the C# project setting "Allow unsafe code" applies only to unsafe C# code in  the project itself, or is it necessary to set this option when linking in a native C++ DLL? What about linking in a managed DLL that itself links to a native DLL? What does this option really do, under the hood?
Answer: It has to do with the "unsafe" keyword in C#.  "unsafe" turns off all the checks that would normally happen and allow you to directly access the memory.  it doesn't refer to calling native C++ DLL's or interfaces.
Answer: It allows you to use the "unsafe" block.
unsafe(...)
{
}

Answer: This just relates to the use of unsafe blocks (where pointers can be used). It does not govern P/Invoke.
Answer: Its necessary to use the unsafe { } context.  It used to be required to use sizeof() but in later versions that's no longer true.
You don't need to allow unsafe code if you are externing to another DLL written in another language like C.


Função de "Curtir" sem recarregar a página?

Question: Olá, boa tarde!
Eu estou tendo um problema que eu não to sabendo resolver. Eu não sei programar em JQuery ou Ajax, mas pretendo começar a aprender. Como que eu posso fazer pra fazer com que o seguinte código em PHP funcione em Ajax ou JS? Qual das duas opções é melhor pra realizar essa ação de "Curtir"?

      <form action="like-post.php" method="post">
      <button name="id" value="<?= $post["id"] ?>" class="like-post">Like</button>
      </form>

      <?php
      echo $post["likes"];
      ?>

Código da página like-post:
include("header.php");
include("conecta.php");
include("functions.php");

   $id = $_POST['id'];
   like($conecta, $id);
   header("Location: index.php");
   die();

O que eu quero fazer é com que esse botão assim que clicado ele adicione mais uma curtida ao post. Agradeço desde já!
Answer: Bem vou te dar essa forcinha :
Podemos tirar o form, já que vai ser assíncrono.

  <button name="id" data-id="<?= $post["id"] ?>" class="like-post">Like</button>

<li class="likes" id="<?= $post["id"] ?>">
    <?php
  echo $post["likes"];
  ?>

Arquivo php (like-post.php):
<?php
     echo "123";//esse é o retorno da requisição
?>

Agora o Script
//Quando clicar nos botões com nome id
$( 'button[name="id"]' ).click(function(){
    var that = $( this );
    var valId = that.data( 'id' );

    that.prop('disabled',true);// Evitar overposting com os usuários de dedinho nervoso

    $.ajax({//requisição
        url : 'like-post.php', //url (duuhh)
        data : { id : valId }, //informações que vão no corpo da requisição
        success : ( response ) => {
           //faça alguma coisa com o retorno, pode até ser passar o total de likes pra uma div
          console.log(response); //123
          $( '#'+valId ).html( response );// carrega dentro da

        },
        error : () => {//se der erro no php
            that.prop( 'disabled',true );//deixa o usuário dedar denovo
        }
    })
})

Comment: Muito obrigado! Mas como eu disse, eu não entendo quase nada de js (básico do básico). Como eu posso fazer pra retornar os likes pra uma determinada div?
Comment: O código que eu to usando é um echo $post['likes'] dentro de uma div com a classe "likes"
Comment: @JoãoVictorValentim editei, então `response` é `numeroDeLikes `
Comment: Desculpa, ainda não consegui entender. Dentro da parte de success no arquivo js eu preciso colocar algo? E essa variavel numeroDeLikes eu coloco dentro da div onde eu quero que apareça os likes, certo? Porque eu usei o código acima mas acaba que essa variavel não fica definida..
Comment: @JoãoVictorValentim você atribui o total de likes que vem do seu banco pra ela, editei com um valor fixo.
Comment: Ainda não consegui :/ Mas obrigado pela ajuda. Eu vou começar a dar uma estudada em Ajax e Jquery pra melhorar isso


Receive and send sip in two applications at the same time

Question: I have a softphone X-lite installed on my computer. i wanted to develop a program in C # to see the sip messages it receives and sends. already built a softphone that does this. but I want it in a standalone application. I'm in trouble because I can not use the same port for two aplications ... someone can help me?
Sorry for my bad English...
Comment: Unless you are only using the loopback interface, Wireshark would be a good way to get the SIP flow. It even has a dissector to filter for the SIP protocol.
Comment: You don't have to use the same port for both softphones. UDP 5060 is the default SIP Port but you can use whichever port you want. X-lite lets you specify the local port in its configuration settings so you can easily move it to a different port.
Comment: Thanks for the answers :)

I can not use wireshark because I want to save the SIP messages in a variable for later use in another application.

yes I use two ports, but I want to receive the data coming to my softphone ... just have to use the softphone port 5060 and my application can read messages from the same port... this case also the 5060 ...
Answer: Try using pjsip
it is open source tool. Try and run the pjsua application. It will let you make/receive calls from any port of you choice. It will act as a UAS/UAC. You can also register your X-lite client at this port.
E.g. pjsua --local-port=5090
Detailed usage of pjsua


Como faço para unir dois resultados de uma query?

Question: Estou desenvolvendo uma aplicação em C# e gostaria de saber como faço para unir dois resultados de duas queries SQL em uma só. Tenho o seguinte código:
public List<MalaDireta> ObterMalaDireta()
{
    List<MalaDireta> resultado = new List<MalaDireta>();

    string sql_funcionario = "select id, nome, email from funcionario";
    string sql_fornecedor = "select id, nome, email from fornecedor";

    var conexao = new SqlConnection("string de conexão");

    var comando = new SqlCommand(sql_funcionario, conexao);

    try
    {
       conexao.Open();

       // como eu monto meu comando com as duas queries?

       var dataReader = comando.ExecuteReader();
       while (dataReader.Read())
       {
          MalaDireta m = new MalaDireta();
          m.Nome = dataReader["nome"];
          m.Email = dataReader["email"];

          resultado.Add(m);
       }
    }
    catch
    {
    }
    finally
    {
       conexao.Close();
    }

    return resultado;
}

Answer: Que tal fazer a união através da própria query sql usando o UNION:
select id, nome, email from funcionario
union
select id, nome, email from fornecedor

No seu caso ficaria assim:
string sql_todos = "select id, nome, email from funcionario " +
                   "union "+
                   "select id, nome, email from fornecedor";

Answer: A resposta do @Ecil está adequada, mas acrescento o uso do UNION ALL.
Qual a diferença entre UNION e UNION ALL?

UNION faz uma espécie de DISTINCT, inibindo resultados repetidos
UNION ALL traz todos os resultados, mesmo os com valores repetidos

Existe alguma vantagem no UNION ALL? Em tese, ele é mais eficiente por não aplicar o DISTINCT, isto é, não fazendo  comparação dos valores dos registros.
Então basta uma mudança simples:
string sql_todos = "select id, nome, email from funcionario " +
               "union all "+
               "select id, nome, email from fornecedor";

Este conceito se aplica, pelo menos, ao SQL Server, Oracle, MySQL e PostgreSQL.
Comment: Boa observação. Só acrescento que a escolha entre UNION e UNION ALL depende do resultado que se quer (a pergunta não deixa isso claro).
Comment: Concordo com o @utluiz, boa observação. Neste caso, porém, é bem pouco provável que funcionários também sejam fornecedores e mesmo o sendo, provavelmente teriam id's e emails diferentes.
Answer: Em teoria, basta você repetir o processo de reabrir a conexão, executar a outra query, e passar pelo laço de repetição adicionando os resultados da sua segunda query.
string sql_funcionario = "select id, nome, email from funcionario";
string sql_fornecedor = "select id, nome, email from fornecedor";

var conexao = new SqlConnection("string de conexão");

MalaDireta m = new MalaDireta();
var comando = new SqlCommand(sql_funcionario, conexao);

try
{
   conexao.Open();

   // como eu monto meu comando com as duas queries?

   var dataReader = comando.ExecuteReader();
   while (dataReader.Read())
   {

      m.Nome = dataReader["nome"];
      m.Email = dataReader["email"];

      resultado.Add(m);
   }
}
catch
{
}
finally
{
   conexao.Close();
}

var comando = new SqlCommand(sql_fornecedor, conexao);

try
{
   conexao.Open();

   // como eu monto meu comando com as duas queries?

   var dataReader = comando.ExecuteReader();
   while (dataReader.Read())
   {

      m.Nome = dataReader["nome"];
      m.Email = dataReader["email"];

      resultado.Add(m);
   }
}
catch
{
}
finally
{
   conexao.Close();
}

Answer: Existem duas formas:

Se a estrutura das suas queries forem as mesmas você pode usar um UNION:

var query = "select id, nome, email from funcionario union select id, nome, email from fornecedor";

Você pode enviar as duas queries no mesmo SqlCommand. A Classe DataReader suporta nativamente múltiplos resultados usando o método dataReader.NextResult():
    var comando = new SqlCommand(string.Concat(sql_funcionario, ";", sql_fornecedor), conexao);
    var dataReader = comando.ExecuteReader();
    while (dataReader.NextResult()) {
        while (dataReader.Read()) {
            MalaDireta m = new MalaDireta();
            m.Nome = dataReader["nome"];
            m.Email = dataReader["email"];

            resultado.Add(m);
        }
    }

Answer: Caro, mesmo que alguma mágica oculta possa ser feita para unir os dois readers para readibilidade eu só vejo duas opções:

Põe um union na query e coloca a business logic pro lado do banco. (meio feio)
Pega os dois readers (converte pra Enumerable da entidade) e faz um merge com Linq, pode escrever uns Unit Tests para fazer o codigo responsável
Comment: você poderia me dar um exemplo em código de como seria o `union` ?
Comment: Não é necessário converter os readers para IEnumerable, basta usar o método NextResult() do datareader.
Comment: Faz isso não querido, isso vai de encontro com "mágica oculta" que eu mencionei. Conta 3 meses e outro desenvolvedor e isso vai virar código perigoso. Quando eu mencionei os Enumerables, me refiro aos retornos dos repositórios que ele vai ter. Esse exemplo simplificado o Union resolve, mas se expandir uma vírgula vai aparecer DAL fazendo query pra dois repositórios e confundindo conceito.


How does address operand affect performance and size of machine code?

Question: Starting with 32-bit CPU mode, there are extended address operands available for x86 architecture. One can specify the base address, a displacement, an index register and a scaling factor.
For example, we would like to stride through a list of 32-bit integers (every first two from an array of 32-byte-long data structures, %rdi as data index, %rbx as base pointer).
addl   $8, %rdi                # skip eight values: advance index by 8
movl   (%rbx, %rdi, 4), %eax   # load data: pointer + scaled index
movl   4(%rbx, %rdi, 4), %edx  # load data: pointer + scaled index + displacement

As I know, such complex addressing fits into a single machine-code instruction. But what is the cost of such operation and how does it compare to simple addressing with independent pointer calculation:
addl  $32, %rbx      # skip eight values: move pointer forward by 32 bytes
movl  (%rbx), %eax   # load data: pointer
addl  $4, %rbx       # point next value: move pointer forward by 4 bytes
movl  (%rbx), %edx   # load data: pointer

In the latter example, I have introduced one extra instruction and a dependency. But integer addition is very fast, I gained simpler address operands, and there are no multiplications any more. On the other hand, since the allowed scaling factors are powers of 2, the multiplication comes down to a bit shift, which is also a very fast operation. Still, two additions and a bit shift can be replaced with one addition.
What are the performance and code size differences between these two approaches? Are there any best practices for using the extended addressing operands?
Or, asking it from a C programmer's point of view, what is faster: array indexing or pointer arithmetic?

Is there any assembly editor meant for size/performance tuning? I wish I could see the machine-code size of each assembly instruction, its execution time in clock cycles or a dependency graph. There are thousands of assembly freaks that would benefit from such application, so I bet that something like this already exists!
Comment: General answer #0: Optimization is voodoo, and things like adding instructions or using longer instructions can speed things up in some cases. These behaviors can vary from CPU to CPU; something true on one model may not be true on a newer model. In your case, things can go either way, and there is no good way to predict without simply measuring.
Comment: General answer #1: http://www.agner.org/optimize/ ; http://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-optimization-manual.html
Comment: I know of no such editor as you are asking about. A very complete sampling tool is available from AMD: CodeAnalyst for 32- and 64-bit x86.
Comment: @NayukiMinase, some v useful links. Very worth a browse.  Thanks.
Comment: @Nayuke Minase: optimization is not voodoo though it may appear to be to someone uninformed examining generated assembly code. Neither is it true that "there is no good way to predict without simply measuring." Quality compilers do a very good job of predicting without measuring - simply or otherwise.
Comment: One "instruction" yes, but these are variable length instructions, a similarly interesting question is the size of the instructions as a whole for the task, how much fetching.  the math is fast, one clock so that is not an issue.  examine decisions, when they happen and additional fetches.  Etc, even with that as mentioned above performance is specific to the processor architecture and system.
Answer: The answer to your question depends on the given, local program flow circumstances - and they, in turn, may very somewhat between processor manufacturers and architectures. To microanalyze a single instruction or two is usually pointless. You have a multi-stage pipeline, more than one integer unit, caches and lots more that come into play and which you need to factor into your analysis.
You could try reverse-engineering by looking at generated assembly code and analyzing why the sequence looks the way it does with respect to the different hardware units that will be working on it.
Another way is to use a profiler and experiment with different constructs to see what works well and what doesn't.
You could also download the source code for gcc and see how the really cool programmers evaluate a sequence to produce the fastest possible code. One day you might become one of them :-)
In any case I expect that you will come to the conclusion that the best sequence varies greatly depending on processor, compiler, optimization level and surrounding instructions. If you are using C the quality of the source code is extremely important: garbage in = garbage out.
Comment: One place where testing such as the one (I think) you are proposing is useful is to determine ALU or FPU efficiency when comparing different processors/architectures. You might want to check out this document (http://gmplib.org/~tege/x86-timing.pdf) which shows the rate at which certain x86-architectures can process individual instructions and their degree of parallelism.
Comment: You're right – I should have provided a broader example's context for my question. My intent was to focus on the instruction-level address arithmetic performance (carried out by a dedicated unit, at a different stage of the pipeline, right?) and its comparison to independent, ALU-based calculations executed for the same reason. Nevertheless, the question came out from a wider issue, which I'm going to reveal through an edit.
Comment: The context for your comparison is what the respective units have been up to right up to the point where your instructions are executed. A good compiler producing optimized code will have kept track of which units in the pipeline it has put to work on this or that instruction and also correctly estimate when that work completes. It will try different instruction scenarios to find the one that works best (runs fastest). If you choose a restricted context it will be of little practical use.
Answer: The address arithmetic is very fast and should be used always if possible.
But here is something that the question misses.
At first you can't multiply by 32 using address arithmetic - 8 is the maximal possible constant.
The first version of the code in not complete, because it will need second instruction, that to increment rbx. So, we have following two variants:
inc  rbx
mov  eax, [8*rbx+rdi]

vs
add  rbx, 8
mov  eax, [rbx]

This way, the speed of the two variants will be the same. The size is the same - 6 bytes as well.
So, what code is better depends only on the program context - if we have a register that already contains the address of the needed array cell - use mov eax, [rbx]
If we have register containing the index of the cell and another containing the start address, then use the first variant. This way, after the algorithm ends, we still will have the start address of the array in rdi.
Comment: As I understand it, the complex address operand (and the circuitry lying behind it) was introduced to eliminate the need for the accessory, address-calculating instructions, thus (in many cases) compacting the code and reducing instruction-level dependencies. So, unless I already have a ready pointer, the complex addressing in usually preferable.
Comment: @KrzysztofAbramowicz Exactly. Don't forget to vote and accept the answer you like. ;)
Comment: As for the multiplication, there is no mistake, but the example introduces an (unnecessary) assumption that the `%rdi` strides 8 units per iteration, so the scaling factor is 4, but the data is not accessed linearly. It would have been obvious, if I hadn't forgotten to provide the loop counter advancement instruction for the first variant. I will apply your remarks to my question.


Background color with other size, behind background image

Question: I have a div element which has a PNG image as background and behind that image a background color. The PNG image has a transparant square in the middle and round borders. I want to give the transparant square a color, but problem is that the borders also get this color. Is it possible to change the size of the color only? Or should I use a seperate div for the color and the image?
background-color: #6DB3F2;
background-image: url('MyImage.png');

Comment: Depending on your html
Answer: You cannot change the size of a color. You could, however, make the corners of your PNG opaque with the color you want to have there.


Determine from where is "sh" being run under apache www-data user using using PF or NETSTAT

Question: I am working with a compromised Ubuntu 8.04 Plesk 9.5.4 server. It seems that a script on the server is continuously doing reverse lookups to random IPs on the Internet.
I first spotted it during by using top and then noticed flashes of this coming up continuously:
sh -c host -W 1 '184.108.40.206'
I wrote a this script to interrogate ps every 1 second to see how frequently this script happens:
#!/bin/bash
while :
do
    ps -ef | egrep -i "sh -c host"
    sleep 1
done

The results are that this script runs often, every few seconds:
www-data 17762  8332  1 10:07 ?        00:00:00 sh -c host -W 1 '18.104.22.168'
www-data 17772  8332  1 10:07 ?        00:00:00 sh -c host -W 1 '18.104.22.168'
www-data 17879 17869  0 10:07 ?        00:00:00 sh -c host -W 1 '126.96.36.199'
www-data 17879 17869  1 10:07 ?        00:00:00 sh -c host -W 1 '126.96.36.199'
www-data 17879 17869  0 10:07 ?        00:00:00 sh -c host -W 1 '22.214.171.124'
root     18031 17756  0 10:07 pts/2    00:00:00 egrep -i sh -c host
www-data 18078 16704  0 10:07 ?        00:00:00 sh -c host -W 1 '22.214.171.124'
www-data 18125 17996  0 10:07 ?        00:00:00 sh -c host -W 1 '220.127.116.11'
root     18131 17756  0 10:07 pts/2    00:00:00 egrep -i sh -c host
www-data 18137 17869  0 10:07 ?        00:00:00 sh -c host -W 1 '188.8.131.52'
www-data 18137 17869  1 10:07 ?        00:00:00 sh -c host -W 1 '22.214.171.124'

My theory is if I can see who is launching the sh process or form where it's launched I can isolate the problem further.
Can somebody please guide me using netstat or ps to identify from where sh is being run?
I might get many suggestions that the OS is out of date and so the Plesk, but please bear in mind there are some very concrete reasons why this server is running legacy software. My question is aimed at a advanced Linux systems administrators who have in depth experience with security compromises and using netstat and ps to get to the bottom of it.
UPDATE 26 Oct 14:01 SAST
The command grep -lr 'sh -c host' left in the comments left by @ramruma helped me to quickly find the corresponding website running the script. As it turns out the server is not compromised. What is instead happening is there is a forum in that location produced by Powered by SMF 1.1.2 | SMF © 2006-2007, Simple Machines LLC that does a reverse lookup every time someone accesses the board.
It also turns out that the forum is unmaintained and severely spammed and why we initially thought it's compromised is because many of the reverse lookups pointed to foreign IPs known for spamming. Goodness only knows how a website can execute this command, but for the time being I am going to close the issue as harmless.
With regards to the blanket replies I received about "restore from backup" I came to ServerFault to help isolate the issue and I made it clear in my initial request. Sometimes restoring from backup is impractical or even impossible. It's better to figure out the issue or find the compromise in case it might arise in the future.
Comment: also `pwdx $(pgrep -f host)` and pstree on the parent pid, and lsof to see which files the parent process has open.
Comment: Since it's running as `www-data` user, how about this `grep -lr 'sh -c host' /path/to/the/document/root`?
Comment: it'd be more efficient to have solved this first and then described. See my profile if interested.
Comment: @ramruma, you command has assisted me in finding the exact website strait away where this script is run. I would like to mark your answer as correct, but since you only commented this is impossible.
Answer: While it looks like you've figured out the cause of this problem already, dumping the process table with pstree and a few args would have helped.
Replace your ps command in the loop with:
pstree -apu www-data >> getyousomespam.txt
You'd only want to run this for about 30 seconds due to the wall of text it would generate. This will display all processes owned by www-data, their ancestor processes, all uid transitions along the way (-u), commandline args that you can search on (-a), and PIDs (-p).
Obviously this information would be completely bunk if you've been compromised, but if you haven't (as seems to be the case here), this would provide the paper trail you were looking for...or at least a good start.
Edit:
pstree doesn't concern itself with originating terminals, but if you can isolate things to a persistent ancestor process, having the PID would make it easy to finish the job from there.
Answer: Stop. You're going about this the wrong way. Your server is compromised, you need to disconnect it and restore from a known-good backup. See also How do I deal with a compromised server?


Using $or and $ne Operators Together in MongoDB Query

Question: I am trying to run a MongoDB query to return all documents that don't match one value OR another. After consulting the documentation, I see this example:
{ $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] }

So this is what I tried:
{ $or:  [ { paymentType: { $ne: "full" } }, { $ne: "partial" } ] }

This results in an error:

'unknown top level operator: $ne'

I also tried this:
{ $or:  [ { paymentType: { $ne: "full" } }, { paymentType: { $ne: "partial" }} ] }

... but this simply returns all documents, with no filtering done on the "paymentType" property.
What's the correct syntax here?
Comment: Use `$nin` for match on single field. Something like `{paymentType:{$nin:["full", "partial"]}}`
Answer: Your third version of code syntax is correct.
But the logic seems wrong.
Your query translated to:
paymentType != full or paymentType != partial

This actually always hold true, (since one paymentType value cannot be full and partial at the same time.)
Update

To clarify, what I'm trying to query -- in plain English -- is to return all results where "paymentType" is not "full" or "partial".

In this case you should use $and instead. or $nin is also good.
Remember this law:
not (p or q) <=> (not p) and (not q)

Comment: Then use must use an `$and` instead. Or use `$nin` like suggested above
Comment: To clarify, what I'm trying to query -- in plain English -- is to return all results where "paymentType" is not "full" or "partial".
Comment: This is probably the way to go, as suggested above: {paymentType:{$nin:["full", "partial"]}}
Comment: Good point. If I were to use an operator here, it should be $and, not $or.
Comment: Actually, even better is this, the $nor operator:
{ $nor:  [ { paymentType: { $ne: "full" } }, { paymentType: { $ne: "partial" }} ] }
Comment: Your usecase is completely different than the example :D
Comment: How so? You may be misunderstanding my usecase.
Comment: In my opinion $nin is the way to go in MongoDB.
Comment: Because? What's your reasoning? Why do you think that's the superior choice in all such cases?
Answer: So, thanks to a commenter for pointing out that I could either use $nin or $and but not $or. Another option, which I find the most intuitive in this particular case, is the $nor operator, like so:
{ $nor:  [ { paymentType: { $ne: "full" } }, { paymentType: { $ne: "partial" }} ] }

This will return all documents that don't match either of these values.
Answer: If you need to find all documents which do not match those two values only why don't you simply change the $or to $and? Easiest and shortest is to use the $nin as already suggested but not sure why complicate it with $nor/$or etc.
{ $and:  [ { paymentType: { $ne: "full" } }, { paymentType: { $ne: "partial" }} ] }

will select all documents that don't match either of these values. It reads and understands much easier then the double negation you end up with $nor no?
It says give me all paymentTypes which are not full and not partial. Same if you use the $nin.
Comment: I guess it's partly a subjective preference. For me, mentally, $nor equates more closely with the logic in my mind in this case than $and -- hence why I made the mistake in using $or instead of $and to begin with.
Answer: As per the plain english understanding, you should use
{ $nor:  [ { paymentType: "full" }, { paymentType:  "partial"} ] }

This is the modification to @Muirik's answer as it didn't work for me as you are already using $nor. Thus, you should not use $ne inside.
Thanks.


The command "mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V" failed and exited with 1 during

Question: I have setup my .travis.yml
as:
language: java
script: mvn clean verify

but I get
The command "mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V" failed and exited with 1 during

see
  https://github.com/WolfgangFahl/w3cValidator/blob/master/.travis.yml
What is wrong with this setup? Why is mvn install executed when I ask for mvn verify?
I had expected this to work based on:
https://stackoverflow.com/a/33283409/1497139
and checking the .travis.yml with http://lint.travis-ci.org/
Comment: I am with the same error
Answer: In general, I'd recommend using install: true and placing the commands for the build under the script element.
language: java
install: true
script:
- mvn install

There is an important difference between install and script: if the former fails, the build errors, if the latter one fails, the build fails. See the docs:

If before_install, install or before_script return a non-zero exit code, the build is errored and stops immediately.
If script returns a non-zero exit code, the build is failed, but continues to run before being marked as failed.
Answer: I ended up with this style of yml file:
# this is a java project using maven
language: java
# install
install: mvn install


How to solve this equation? $a^2 \cdot \arcsin(\frac 4a)+4 \cdot\sqrt {a^2-16}=40$

Question: Please, help me solve this equation:
$$a^2 \cdot \arcsin \left(\frac 4a \right)+4 \cdot\sqrt {a^2-16}=40$$
Comment: this is only possible by a numerical method
Comment: are there any real Solutions?
Answer: Say $\frac{4}{a}=u$
Then the given equation becomes
$$\arcsin u + u\sqrt{1-u^2}=\frac{5}{2}u^2$$
Now $u$ must be such that $|u|<1$.
So we can assume that $u=\sin x$ or $\cos x$.
Now see if you can solve this trigonometric equation.
Answer: There may not exist an explicit solution for $a$ in terms of elementary functions.
However, you can apply the Newton-Raphson Method (A numerical method) using a spreadsheet, or with more sophisticated software such as MATLAB:
$$a_{n+1}=a_n-\frac{f(a_n)}{f'(a_n)} \tag{1}$$
You have your function:
$$f(a)=a^2 \cdot \arcsin \left(\frac 4a \right)+4 \cdot\sqrt {a^2-16}-40$$
Differentiating it:
$$f'(a)=\frac{4a}{\sqrt{a^2-16}}-\frac{4}{\sqrt{1-\frac{16}{a^2}}}+2a\arcsin\left(\frac{4}{a}\right)$$
Substituting into $(1)$:
$$a_{n+1}=a_n-\frac{a_n^2 \cdot \arcsin \left(\frac {4}{a_n} \right)+4 \cdot\sqrt {a_n^2-16}-40}{\frac{4a_n}{\sqrt{a_n^2-16}}-\frac{4}{\sqrt{1-\frac{16}{a_n^2}}}+2a_n\arcsin\left(\frac{4}{a_n}\right)} \tag{2}$$
Let us start with an initial value $a_0=11$. You can choose these values by simply 'guessing' a value close to the actual solution.
Now, substitute the value of $a_0$ for $a_n$, and find the value of $a_1$ using equation $(2)$. Continue this iteration until you get closer and closer to the value of $a$.
I get a value of $a\approx 5.52978022$.
Comment: ok i have made a typo
Comment: are you sure of this?
Comment: @Dr.SonnhardGraubner Does this not work for you?
Comment: i can not find this zero
Comment: [Wolfram|Alpha](http://www.wolframalpha.com/input/?i=a%5E2*arcsin(4%2Fa)%2B4*sqrt(a%5E2-16)%3D40) suggests otherwise.
Answer: If you don't care much about precision, then you can get an approximate solution by fixed point iteration instead of Newton-Raphson.
Using @SchrodingersCat's result, we have an equation:
$$u=\frac{2}{5} \left(\frac{\arcsin u}{u} +\sqrt{1-u^2}\right)$$
Take initial guess $u_0=1$ and substitute:
$$u_1=\frac{2}{5} \left(\frac{\arcsin u_0}{u_0} +\sqrt{1-u_0^2}\right)$$
$$u_2=\frac{2}{5} \left(\frac{\arcsin u_1}{u_1} +\sqrt{1-u_1^2}\right)$$
Then we get the following sequence of values (correct digits are highlighted):
$$\color{blue}{0}.6283185307179586$$
$$\color{blue}{0.7}436955340482698$$
$$\color{blue}{0.7}184422024307543$$
$$\color{blue}{0.72}45114408003248$$
$$\color{blue}{0.723}0826224901516$$
$$\color{blue}{0.723}4206633738902$$
$$\color{blue}{0.7233}407802435841$$
$$\color{blue}{0.72335}96627961654$$
$$\color{blue}{0.72335}51996817168$$
$$\color{blue}{0.723356}2546078128$$
$$\color{blue}{0.7233560}052606297$$
$$\color{blue}{0.7233560}641975273$$
$$\color{blue}{0.72335605}02669220$$
$$\color{blue}{0.72335605}35596262$$

Thus, $u \approx 0.72335605$, so $$a=\frac{4}{u} \approx 5.52978$$


How do I remove the "Request New Password" link?

Question: When I visit www.example.com/user, there is a page that shows the login/password and as well as a "Request New Password" tab.
How do I remove this "Request New Password" tab from the user page?
Comment: What are you trying to achieve? Just hide that tab or disable the functionality it provides?
Comment: Disable and hide both ways would be appreciated. I'll make the choice. Thanks!
Answer: The No Request New Password module is probably the easiest way to go, though you'll need to dig for the 6.x releases. This disables any request to user/password, so this path with neither be accessible directly nor display in menus/tabs/links.
Alternatively, you can put its main function into your own custom module:
 /**
  * Implementation of hook_menu_alter().
  */

 function MYMODULE_menu_alter(&$callback) {
     $callback['user/password'] = array('access arguments' => array(FALSE));
 }

Comment: Support for alter hooks in template.php was added in Drupal 7, for Drupal 6 you'll need to put this in a custom module @user3236765
Comment: Hi Thanks, the code you gave above, where exactly in template.php should I place the code? Thanks again!
Comment: Thanks Clive, can the module referred to above work with drupal 6?
Comment: @Clive Thanks, it's been a while since I dealt with D6.
Comment: Me too, I had to check ;) @user3236765 yes that module should work out of the box. Nitpicking - the code in Jaypan's answer is a slightly better solution than what that module does, it will potentially save database access and some cpu cycles, plus it's conceptually the "better" way to solve the problem. It's technically possible for the implementation of `user_access` to change and that method to stop working, or at least start throwing warnings, but it's very unlikely given D6 isn't being actively developed
Answer: You can change the permission so the page is not accessible:
function hook_menu_alter(&$menu)
{
  $menu['user/password']['access callback'] = FALSE;
}

This code will disable the page altogether, so it's not available to anyone.
Answer: If you are already using a custom module (called, for example, custom_module) you can hide the user/password tab using the following code.
function custom_module_menu_alter(&$items) {
  $items['user/password']['type'] = MENU_CALLBACK;
}

This doesn't show the tab, but the path is still accessible to the users who know Drupal has that path.
To hide it and disable it, use the following code.
function custom_module_menu_alter(&$items) {
  $items['user/password']['access callback'] = FALSE;
}

Setting the access callback to FALSE, the tab will not be accessible nor visible to any user, including the user #1.
In the last hook implementation that I shown, using $items['user/password'] = array('access arguments' => array(FALSE)); is wrong since:

Setting the access arguments to an array containing the FALSE value is not the correct way to avoid Drupal checks the user has the permission to see the route/menu.
Using that code, I am literally setting the route definition to an array containing just 'access arguments' => array(FALSE) with all the consequences that could happen if there is another module that re-enables the user/password tab for the currently logged-in user, and that module has hooks invoked after the hooks of your module. (With the example code I shown, this simply happens when the other module is called destiny_change_user_password_tab.)


Need Freemarker method/function to detect US holiday name from a given date

Question: Does anyone know of a Freemarker function/method that returns the name of a US holiday for a given date?
I've written a function to retrieve the previous business day (Mon-Fri) for any given date, but if the previous business day happens to be one of ten recognized holidays at our company, then I need to step back one day from that to then run my getPreviousBusinessDay function.
Here is my getPreviousBusinessDay function:
<#function getPreviousBusinessDay date>
  <#local dateAsEpochMS = date?long>  <#-- Convert date to epoch time in milliseconds -->
  <#local outie = ""/>
  <#local dayOfWeek = date?string("EEEE")>
  <#if dayOfWeek = "Monday">
    <#local outie = dateAsEpochMS - 259200000> <#-- subtract 3 days in milliseconds -->
  <#elseif dayOfWeek = "Sunday">
    <#local outie = dateAsEpochMS - 172800000> <#-- subtract 2 days in milliseconds -->
  <#else>
    <#local outie = dateAsEpochMS - 86400000> <#-- subtract 1 days in milliseconds -->
  </#if>
  <#local outie = outie?number_to_date?string("MMMM d, YYYY")>
  <#return outie>
</#function>

So if you enter "August 1, 2022" (a Monday) into the function:
${getPreviousBusinessDay("August 1, 2022"?date)}

it returns the previous Friday date:
July 29, 2022

That's all well and good, but hence my problem if the previous business day happens to be one of those ten holidays that we're closed.
Any ideas?
Answer: You could create a <#function isBusinessDay(date)>, that returns true for days that aren't weekend days, and not in the set of knows corporate holidays. Then in getPreviousBusinessDay you just step back one day in a loop until isBusinessDay(date) returns true.
But, where/how is the information about the corporate holydays stored? Also it will be different each year, so it's something that will have to be updated time to time.
BTW, doing logic like this in templates is bad practice. I would create some service in Java that can answer all these questions, and just call that.
Also be careful with substracting one day in millies. That can break if you are using a time zone that day light saving, and you date-time is near midnight.


Should the validation set have the same ratio in the categories as the whole data?

Question: I'm currently working on a classification problem. The variable Y in 70% of cases is 0 and in 30% of cases is 1.
Does my validation set have to have this same proportion?
I ask because after using random forest and training my model I get this prediction values with the training set:
<code>               precision    recall  f1-score   support

         0       0.92      0.92      0.92      1485
         1       0.88      0.88      0.88       949

avg / total       0.91      0.91      0.91      2434
</code>
and these with the validation set:
<code>            precision    recall  f1-score   support

         0       0.88      0.68      0.77       890
         1       0.09      0.25      0.13       110

avg / total       0.79      0.64      0.70      1000
</code>
That is to say there is overfitting in the label 1. The only thing that occurs to me that can happen is that this badly built validation set. I already tried to modify the hyperparameter but always presents the same phenomenon
Answer: Unbalanced data (specifically unbalanced labels) can certainly be a problem. But whether it is in your case depends on your application and what you are trying to do. Here is a nice discussion on when it can be a problem from another SO thread. Potential strategies can be weighting, stratification, evaluation metrics that balance precision-recall, etc.. but it will depend on your objective.
Comment: thank you for your answer. My first strategy will be to adjust the validation set. Should the validation set have the same ratio in the categories as the whole data?
Comment: Yes, it is likely that you should stratify on your label when you create your partions for training and validation. But there could still be worries about external validity to think about as well.


Easier way to prove convergence of $\sum_{n=1}^{\infty} \frac{n^{\frac{1}{3}}}{n^{\frac{5}{3}} -3}$?

Question: I was trying to prove the convergence of the series
$$
\sum_{n=1}^{\infty} \frac{n^{\frac{1}{3}}}{n^{\frac{5}{3}} -3}
$$
My original approach was to try and bound the sequence $a_n =  \frac{n^{\frac{1}{3}}}{n^{\frac{5}{3}} -3}$ by some sequence $b_n = \frac{1}{n^k}$ for some $k >1$ and for all $n > N$ (given some fixed natural number $N$). The idea here is that the series of such $b_n$'s would converge by the p-series test, and hence, by the comparison test we could conclude that our original series converges. The problem I encountered is that bounding the series in such a way gives very little breathing room for the possible values of $k$. In fact, for as soon as $k = 1.4$ the inequality
$$
\frac{n^{\frac{1}{3}}}{n^{\frac{5}{3}} -3} < \frac{1}{n^{1.4}}
$$
is no longer true for sufficiently large $n$. My solution was to bound the sequence $a_n$ by a sum of p-series instead of just one p-series. I managed to prove that
$$
 \frac{n^{\frac{1}{3}}}{n^{\frac{5}{3}}-3} < \frac{1}{n^{\frac{4}{3}}} + \frac{1}{n^{\frac{5}{3}}} \qquad \forall n \ge 4
$$
which is enough to prove convergence using the comparison test since $\zeta\left(\frac{4}{3}\right) + \zeta\left(\frac{5}{3}\right) < \infty$. However, even though this works, proving the above inequality is not as simple as I would like, but I couldn't think of an easier way to prove the convergence.

Can anyone think of an easier (or more direct) way to prove the convergence of the series in question? Any convergence test works, it doesn't necessarily have to be by direct comparison. Any and all thoughts are welcome. Thank you!
Comment: $\dfrac{n^{1/3}}{n^{5/3}-3} \sim \dfrac{1}{n^{4/3}}$ for $n \to \infty$, so you can use the limit comparison test.
Comment: You just need enough breathing room on the wrong side of $1$. The same idea that made you guess $1.4$ could have pulled you to $1.3$, which would have worked. Besides, $\frac{5}{3} - \frac {1}{3} = \frac {4}{3} \approx 1.33$, so that would have been the reasonable cutoff, and explains why you were close but not close enough.
Answer: Usually, the short way uses asymptotic equivalence, which requires the general term of the series to be ultimately positive,  which is the case here. Remember equivalence is compatible with multiplication and division (but not with addition nor subtraction):

$n^{\frac53}-3\sim_\infty n^{\frac53}$, so
$$\frac{n^{\frac{1}{3}}}{n^{\frac{5}{3}} -3}\sim_\infty\frac{n^{\frac{1}{3}}}{n^{\frac{5}{3}}}=\frac 1{n^{\frac{4}{3}}},$$
which is a convergent $p$-series.


How to call the object method (not class method) using reflection in scala

Question: I'd like to call the object main method using reflection in scala. But it did not works, the following 2 lines of code will through exception that I could not create the object using reflection.
val clazz = Class.forName(job.runnerClass)
val runnerClass = clazz.newInstance()

Comment: Got the solution here http://stackoverflow.com/questions/3039822/how-do-i-call-a-scala-object-method-using-reflection?rq=1
Comment: Feel free to delete your own question if it's a duplicate of another. This saves reviewers work determining if it's a duplicate and closing it.
Answer: First you have do use an $ at the end of your class name, because scala objects always end with $.
You can then find the object instance in a field called MODULE$
val class = Class.forName(name)
val objectInstance = class.getField("MODULE$").get(class).asInstanceOf[YOURCLASSTYPE]


count(distinct(col_name)) not working in my sql

Question: I am newbie in mysql, for learning i am using sample database of w3schools. in that i want to create a view which will for each supplier, list the supplier name, the count of distinct products by the supplier (PCount), the count of distinct product categories by the supplier (CCount).
here is my table structures
Suppliers                             Products
--------------------            ----------------------------
SupplierID                             ProductID
SupplierName                           ProductName
ContactNumber                          SupplierID
Address                                CategoryID
City                                   Unit
PostalCode                             Price
Country
Phone

What i have try is
SELECT s.SupplierName, COUNT(DISTINCT(p.ProductID)) as PCount, COUNT(DISTINCT(p.CategoryID)) as CCount FROM Suppliers as s
right join Products as p
on s.SupplierID = p.SupplierID

this is only giving me single SupplierName not all the supplier details with distinct product and distinct category.
Any help would be much appreciated.
Comment: You need to `GROUP BY s.SupplierName`
Comment: The duplicate uses a different aggregate function (`GROUP_CONCAT` versus `COUNT`) but the principle is the same
Comment: @Nick i did not get your last comment.! you mean to say i can use any one of them.?
Comment: No, what I meant was that the reason the query in the duplicate didn't give the expected result was due to the lack of the `GROUP BY` clause, and that is the same reason that your query doesn't give the expected result.
Answer: Give this a shot:
SELECT s.SupplierName,
    COUNT(p1.ProductID) AS PCount,
    COUNT(DISTINCT p2.CategoryID) AS CCount
FROM Suppliers s
    LEFT JOIN Products p1 ON s.SupplierID=p1.SupplierID
    LEFT JOIN Products p2 ON s.SupplierID=p2.SupplierID
GROUP BY s.SupplierName
ORDER BY s.SupplierName


Run all migrations from the beginning for a Heroku app

Question: I want to run every migration for an app on Heroku (using postgres db). It is ok to drop the db and all existing data for the app.
Yes, this isn't how migrations are meant to be used. Long story, not relevant to the question or that interesting :)
Answer: This is current as of November 2014. A lot of answers are outdated since the commands PG supports have changed.
$ heroku pg:reset DATABASE
Then you will be prompted to confirm by typing the name of your app.
$ heroku run rake db:migrate


How many solutions are there to the equation $x_1+x_2+x_3+x_4+x_5=30$ with restrictions using generating functions?

Question: How many solutions are there to the equation $x_1+x_2+x_3+x_4+x_5=30$ where
$a) 2 \leq x_1 \leq 4$, and $3 \leq x_i \leq 8$, for all $2 \leq i \leq 5$.
$b) 0  \leq x_i$ for all $1 \leq i \leq 5$, with $x_2$ even and $x_3$ odd.
Attempt 1:
So far with part $a$ I have this:
$\frac{(x^2+x^3+x^4)(x^3+x^4+x^5+x^6+x^7+x^8)^4}{(1-x)}$
I'm struggling with how to go further from where I am at by using generating functions. I don't know how I would deal with the case where $x_2$ is even and $x_3$ is odd.
Attempt 2:
I've followed  the videos posted before and here's where I'm at now:
Part a:
$[x^{30}](x^2+x^3+x^4)(x^3+x^4+x^5+x^6+x^7+x^8)^4=[x^{30}]x^2 \frac{1-x^3}{1-x} x^{12} (\frac{1-x^6}{1-x})^4 = [x^{16}] \frac{1-x^3}{1-x} (\frac{1-x^6}{1-x})^4 = [x^{16}] (1-x^3)(1-x)^{-2}(1-x^6)^4(1-x)^{-4}$
Part b:
$[x^{30}](1+x^2+x^4+...)(x+x^3+x^5+...)(1+x+x^2+...)^3 = [x^{30}] \frac{1}{1-x^2}x \frac{1}{1-x^2}(\frac{1}{1-x})^3 = [x^{29}](1-x)^{-2}(1-x)^{-3}$
I believe I need to do something like at this mark, but I'm not sure how to apply it to my problem.
Answer: The theory is rather ... computationaly extensive.
Check out these 2 videos, they should give a full explanation
https://youtu.be/-drdeNMoe8w
https://youtu.be/ZyUb5UxBA9Q
being even means, that the generating function's part related to this x will be something like $(x^0 + x^2 + x^4 + x^6 +...)$
For odd - similar scenario: $x^1 + x^3 + x^5 + x^7 + ... $
the generating function for (a) would be correct if you removed the denominator.
the generating function for (b) should look like this I believe:
$(1+x+x^2+x^3+...)^3(x+x^3+x^5+x^7+...)(1+x^2+x^4+x^6+...) =
x(1-x)^{-3}(1-x^2)^{-2}$
Comment: I understand the problem more thanks to the videos, but can you help with what I need to do from where I'm at in attempt 2?
Comment: you lost the square power for one of the x in your original's post edit.
Comment: Regarding the process of deriving the answer, well, it does look rather long if following the video, but I guess it is doable. You need to ask yourself a question, how do you get 29th power, using the provided function.

One of the ways: choose 0 of $x^2$'s and 29 of x: ${-2 \choose 0}*{-3 \choose 29}$
Another way: choose 1 of $x^2$'s and then the remaining 29-2 = 27 of x: ${-2 \choose 1}*{-3 \choose 27}$
You have to basically sum all the possible ways.
Answer: Both your problems have finite number of solutions and are easily solved by brute force, e.g. in Mathematica:
Comment: I appreciate the help, but I'm trying to solve my problem using generating functions.
Comment: @cosmicbrownie I see, perhaps you can elaborate a bit on the desired form of the solution in the question?


Folder Redirection issue (showing warning all the times that it's going to use TEMP profile)

Question: I was playing with Folder Redirection feature of Microsoft.
the only domain controller is under: Windows Server 2008 R2
the workstation is: Windows 7 Enterprise.
I have set GPO, Folder Redirection for Documents only.
Also, I didn't set profile roaming.
Now, when I log in to the Workstation, I see (in Properties) that Redirections are really working. However it's using TEMP profile anyways, even though I set FR only for Documents. not for Desktop nor any other folder I also didn't set up Profile Roaming.
WHy is it showing me this? I am missing something?
Answer: Copy all the user profile folder from \Users\%UserName% to the new location.
When you set up Folder Redirection in a user that have been already logged on a machine Windows will create the new user folder but it wont have all files that user needs like NTUSER.DAT.
So, If the original folder for that user was created in C:\Users, you have to copy that folder to the new path.


How to change scheduler date format in *_node_form

Question: When I go to fill a *_node_form I find that Scheduler module only have this date format "Y m d" "H:m:s" and I would like to have "d m Y" "H:m:s".
I'm looking to the module and I don't find anyway, also , I have make a dpm with $form, And I don't find anyplace to change the date format.
Can be done this?
Thanks
Oskar
Answer: I find it the url is: admin/config/content/scheduler
The strange is that it doesn't have a "configuration" link in module page list.
Oskar