Q:

Generalization to higher dimension of $e^r \not \in \mathbb Q$

The following is well known and not difficult to prove:
$$\forall r \in \mathbb Q^*,  e^r \not \in \mathbb Q.$$
See for instance https://proofwiki.org/wiki/Exponential_of_Rational_Number_is_Irrational
Could this be generalized with the following result, for $n\geq 2$:
$$\forall M \in \mathrm{GL}(n,\mathbb Q),  \exp(M) \in \mathrm{GL}(n,\mathbb R)\setminus \mathrm{GL}(n,\mathbb Q)?$$
If yes, do you have any proof or reference?

A:

The answer seems to be yes.
The proof uses the Lindemann-Weierstrass theorem; specifically, we will use the following result:

If $a_1, \ldots, a_n$ are distinct algebraic numbers, then $e^{a_1}, \ldots, e^{a_n}$ are linearly independent over the algebraic numbers.

In particular (taking $a_1=0$), this means that no non-trivial linear combination of $e^{a_2}, \ldots, e^{a_n}$ over the algebraic numbers is an algebraic number when the powers are all non-zero.
Let us break down the proof into steps.  Let $\overline{\mathbb{Q}}$ be the field of algebraic numbers.  Recall that it is algebraically closed.  Let $M\in \operatorname{GL}(n, \mathbb{Q})$.
Step 1.
There exists a matrix $P\in \operatorname{GL}(n, \overline{\mathbb{Q}})$ and non-zero algebraic numbers $\lambda_1, \ldots, \lambda_r$ such that
$$PMP^{-1} = J_{n_1}(\lambda_1) \oplus \ldots \oplus J_{n_r}(\lambda_r),$$  where
$$
 J_{n_i}(\lambda_i) =
    \begin{pmatrix}
      \lambda_i & 0 & 0 & \cdots & 0 \\
      1 & \lambda_i & 0 & \cdots & 0 \\
      0 & 1 & \lambda_i & \cdots & 0 \\
      \vdots & \vdots & \vdots & \ddots & \vdots \\
      0 & 0 & 0 & \cdots & \lambda_i
    \end{pmatrix}
$$
is a Jordan block.  This is because $\overline{\mathbb{Q}}$ is algebraically closed.
Step 2.
$$
\operatorname{exp}(M) = P^{-1} \Big(\operatorname{exp}\big(J_{n_1}(\lambda_1)\big) \oplus \ldots \oplus \operatorname{exp}\big(J_{n_r}(\lambda_r)\big) \Big)P.
$$
Step 3.
For each $i\in \{1,\ldots, r\}$, there is a nilpotent matrix $N_i$ such that $J_{n_i}(\lambda_i) = N_i + \lambda_i I_n$, where $I_n$ is the $n\times n$ identity matrix.
Step 4.
For each $i\in \{1,\ldots, r\}$,
$$
\operatorname{exp}\big(J_{n_1}(\lambda_1)\big) = e^{\lambda_i}\operatorname{exp}(N_i).
$$
This is because $N_i$ and $\lambda_i I_n$ commute.
Step 5.
We have that $\operatorname{exp}(N_i) \in \operatorname{GL}(n_i, \mathbb{Q})$.  This is because the sum $\sum_{j\geq 0} \frac{N_i^j}{j!}$ is finite when $N$ is nilpotent.
Step 6.
Putting all the previous steps together, we get
$$
\operatorname{exp}(M) = P^{-1} \Big(e^{\lambda_1}\operatorname{exp}(N_1) \oplus \ldots \oplus e^{\lambda_r}\operatorname{exp}(N_r)  \Big)P.
$$
The entries of this matrix are $\overline{\mathbb{Q}}$-linear combinations of $e^{\lambda_1}, \ldots, e^{\lambda_r}$.  Since $\operatorname{exp}(M)$ is non-zero, at least one of these linear combinations is non-zero.  By the Lindemann-Weierstrass theorem, it cannot be an algebraic number.
Thus $\operatorname{exp}(M)$ has an entry that is not an algebraic number.  In particular, is does not lie in $\operatorname{GL}(n, \mathbb{Q})$.


Q:

Accessing Keyboard API

I am looking to intercept keyboard events in a Mac app.
I would like the user to initiate a "record" activity which will copy the keystones and then a "stop" activity.
Is that possible via Cocoa's Mac API?

A:

Have a look at the NSEvent method addLocalMonitorForEventsMatchingMask:handler:. This will allow you to receive events (specifically keyDown events in your case) that occur in your app, and you can then do whatever you want with the keystrokes that the method returns. Here is a simple example of how to use that method:
self.keystrokes = [NSMutableString string];
    [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:^NSEvent* (NSEvent* event){
        NSString *keyPressed = event.charactersIgnoringModifiers;
        [self.keystrokes appendString:keyPressed];
        return event;
    }];

A:

To intercept all keyboard input (and also mouse if you want it) check out the Quartz Events API. This post has some code demonstrating usage of the API.


Q:

In what cases is it required to restart JBoss server?

While any change is done to a deployed/live application, what are the cases when we need to 'restart' the 'JBoss server'?
viz.
  - if just hot-swap of some(.js/.css/.jsp) file is done.
  - if some class is replaced.
  - if I replace the complete .war file.
    ...etc.

A:

I guess you could restart just the deployed application, and not the entire JBoss AS. You can find some more information about this in the JBoss community.
Also some other interesting information regarding this can be found in this question:
Deploying java class files without restarting JBoss
If you copy a new war file onto the server it should redeploy it automatically if that functionality is enabled. This will cause the application to restart, but not the entire server. Depending of caching settings on different levels (browser, proxies etc) you might be able to swap some files without doing anything else, but this can be a bit tricky to control, hence restarting the application is probably the best way to make updates.
Hope it can help you forward.


Q:

Присвоить значение элементу массива

Только начал изучать С++, возникла сложность. Необходимо присвоить определенному элементу массива значение. Делаю так:
    for (int i = 0; i < 256; i++) {
    if (&inp_str[i] == "=" && &inp_str[i + 1] == "=") {
        out_str[start_out] = "=";
        start_out++;
    }

При попытке присвоить значение элементу массива возникла ошибка:

[bcc32 Error] File1.cpp(18): E2034 Cannot convert 'char const[2]' to 'char'
  Full parser context
    File1.cpp(11): parsing: int main(int,char * *)

Как правильно нужно сделать? Спасибо за внимание

A:

ну если я правильно понял то массивы у тебя char?
Если да то вот пару ошибок у вас.
Во первых вы сверяете 1 символ из массива со строкой!
В С++ в двойных кавычках это строка! к ней добавляется завершающий нуль символ.
То есть вы сверяете символ из массива с 2 символами из строки "=".
В С++ символ должен быть в одинарных кавычках '='.
А то у вас получается что вы сверяете к примеру символ '=' с 2 символами '=' и '\0'.

Во вторых вы берёте не символ из массива, а пытаетесь получить адрес  адрес ячейки массива в которой хранится символ и сверить со строкой.
Символ & в С++ означает взятие адреса.
Ваш код должен выглядеть примерно так.
for (int i = 0; i < 256; i++) {
    if (inp_str[i] == '=' && inp_str[i + 1] == '=') {
        out_str[start_out] = '=';
        start_out++;
    }
}

У вас в сообщении ошибки так и написано что компилятор не может с конвертировать символ из массива в 2 символа из строки "=" что бы потом сверить их.


Q:

Laravel API requests with CSRF token

I am creating a website using the Laravel framework where I am using jQuery instead of Vue. And I am wondering which approach is best to use when executing post requests securely when already logged in.
I am currently using Laravel's default authentication and web/routes to display correct views when logged in.
And now for a smoother user experience I want to use jQuery POST requests instead of submitting a form so I can retrieve JSON and do the necessary changes without a website reload.
Have some experience with JWT and OAuth2, but is this really necessary in this case?
Found this thread: https://stackoverflow.com/a/44106621/2906013 which explains that it's bad practice sending the CSRF-token in the POST-request header since REST API's are stateless. But this state is already set when the user is logged in, so I don't understand the harm this can cause in my case?
What makes this so different from a JWT token? Both of them is a token representing a logged in user or am I wrong (CSRF token is session token in Laravel if I am not wrong) ?
Want to make sure the website is secured properly, so all feedback is highly appreciated.

A:

In my personal openion it depends on how do you categorise your ajax request and project structure in general. Is your project entirely restful? Like all requests need to be RESTful and there is no login directly? In that case your application is stateless and each request will need some sort of authentication which will not be ideal way doing through csrf_token.
For example, if you use a 3rd party API, you never login actually but you use JWT or OAUTH tokens to make sure your request is authenticated.
Now in your case, if you have entire website basically following the non-restful redirect strategy, and maintaining session then it is stateful. The session is what maintaining its state. So for simple form saving if you want to use ajax instead of refreshing the page, sending csrf_token would be totally alright.
Internally laravel is not much concerned about how you are sending the POST request in this case, if it is via refresh-submit or an ajax. So ideally nothing is changing just you will return json instead of a redirect and handle it in javascript.
The security of this will depend upon how properly you validate your post request in controller, how do you make sure invalid data is not sent to server etc.


Q:

Nothing happen when refreshing the main Frame (JAVA)

I try to show a ( Logged in ) message when a user is succefully connected but nothing happen when a do a repaint(). you can take a look to the code :
public class MainFrame extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;
    private static final int FRAME_HEIGHT = 400;
    private static final int FRAME_WIDTH = 250;
    private static final String TITLE = new String("TweeX");
    private static String TWITTERID = new String();
    private static String TWITTERPW = new String();
    private boolean logged = false;
    private JTextField loginField = new JTextField(10);
    private JPasswordField passField = new JPasswordField(10);
    private JButton login = new JButton("Connect");
    private GridBagConstraints c = new GridBagConstraints();
    private String UserStatus = new String("Please login...");

    /*
     * Constructor !
     */
    MainFrame() {

        setSize(FRAME_WIDTH, FRAME_HEIGHT);
        setTitle(TITLE);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setResizable(false);
        loginUser();
    }

    /*
     * Login Forms
     */
    protected void loginUser() {

        this.setLayout(new GridBagLayout());

        //add Login Fiels + Label
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.insets = new Insets(5, 5, 5, 20);
        c.gridy = 0;
        add(new JLabel("Username:"), c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 0;
        add(loginField, c);

        //add Password Fiels + Label
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 1;
        add(new JLabel("Password:"), c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 1;
        add(passField, c);

        //add Login button
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 2;
        add(login, c);

        //add listener to login button
        login.addActionListener((ActionListener) this);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 3;
        add(new JLabel(UserStatus), c);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        TWITTERID = loginField.getText();
        TWITTERPW = passField.getText();
        Twitter twitter = new TwitterFactory()
                .getInstance(TWITTERID, TWITTERPW);
        logged = true;

        try {
            twitter.verifyCredentials();

        } catch (TwitterException e1) {
            logged = false;
        }
    }

    protected void connect() {
        if (logged) {
            UserStatus = "Loged In :)";
            repaint();
        }
    }

    static public void main(String[] argv) {
        new MainFrame();
    }
}

A:

Assuming verifyCredentials() doesn't block the EDT indefinitely, you'll need to make your anonymous JLabel a field and use setText() in connect(), whenever it gets called. Calling repaint() should be superfluous. For example,
private JLabel label = new JLabel("Please login...");
...
protected void loginUser() {
    ...
    add( label, c);
    setVisible(true);
}
...
public void actionPerformed(ActionEvent e) {
    ...
    logged = true;
    connect();
}
...
protected void connect() {
    ...
    label.setText("Loged In: ");
    ...
}


Q:

mix use of regular class and ng-class

Want to generate different icons in an ng-repeat:

...

How can I specify only one of the classes using ng-class?
If I wrote:

Then the generated output is

and of course the icon does not show on page.

A:

Don't use angular expression. This works:

(See plunker with example on the p tag: http://plnkr.co/edit/AUN81QF0COtYMeedBygJ?p=preview )
You can put various inputs in ngClass, you can see them in:
https://docs.angularjs.org/api/ng/directive/ngClass
The arguments section has a brief description about them.


Q:

Monitor the resource usage by VMs in KVM

I am planing to write a resource monitoring code using some API for vms running on kvm. I have already tried libvirt but I have other issues with it(vms started with qemu-kvm are not visible). Is there any other library similar to libvirt that can help me out? Thanks !
Sethu

A:

in libvirts' defence - it's a management and monitoring system, if you run something outside it, how can it keep track?
Anyhow, without knowing what exactly you want to monitor it's hard to provide advice. In general, I would run a monitoring agent inside the guests to report the guests' own take on resource use, and also check resources allocated to the VM CPU threads using top, systemtap and the likes
There's also the kvm_stat package, and quite a few additional tools, so everything really depends on what you need to know. Every monitoring tools adds a bit of overhead, so monitoring absolutely everything is usually an overkill


Q:

Using mustache.js to add a content-container for all pages of a static website

I want to build a static website where the content of every page is surrounded by the same content-container (navbar, footer, etc). To do that i want to use a templating engine like mustache.js to define my content-container and then render the template with the pages content inserted into the content-area of the template.
This is what i have in mind:
// Template

Website

Navbar here

{{{content_html}}}

Footer here

The problem i am stuck with is where to put the different parts. The only solution that comes to my mind is:

Put Template and Rendering/Insertion code into a render_template.js file
Put the content of the page into a site_content.html file
Call the render and insertion functionality while passing the correct content html from the actual site.html

Is there a way to put the content HTML into the actual site.html and use that for rendering the template?

A:

I don't think this is the purpose of mustache. MustacheJs should be used to create element templates which are completed by variables values from a js object, not by full html pages (for example the template is the html structure of a user detail page and the variables which are inserted by mustache are the infos specific for the user like first-name, last-name,... In this case we can re-use the same template to display different users).
In your case if you can't use a dynamic language (like php, python or whatever), I would do this a bit different.
I would make separate html pages for each redondant part of your page (ex: header, navbar, footer). Then I would make all of your content pages where you will let a build process include the redondant parts (for exemple with GruntJS you can use this plugin : https://github.com/vanetix/grunt-includes)
Another way would be to use a js framework which handle component templating and includes, but this seems to be very complicated if you just need to include some html parts in pages.


Q:

How to use MCLAG for In Service Software Upgrade (ISSU)

In following video, the CTO of Arista claims that they use Multi Chassis Link Aggregation (MCLAG) setup for In Service Software Upgrade (ISSU) with zero down time on their switches
https://www.youtube.com/watch?v=VdJZq4dRjf4
Specifically, the claim is from 19.30s to 19.58s
Anyone knows how this is done? There are many network vendors who threw lot of resources in building ISSU and looks like Arista achieved two goals by developing MCLAG feature.

A:

I think he's referring to "zero downtime" if you're connected to multiple switches. If you're only connected to Switch A, and I reload that switch for a software update, you're obviously going to lose connectivity. However, with multi-chassis-LACP, you have multiple connections to the "fabric", so a reload of a single switch will not cause a drop.
This is not unique to Arista. Many vendors have this capability.


Q:

How to use data from two Google Fusion tables?

I'm trying to create a google map of "service areas" in USA & Canada, stumbled upon this fusion table layer stuff & thought it would work out great, but I am having problems.

I cannot create a fusion table & make it public without paying google, no way around that, I'll use existing public tables.
I need to apply styles to the fusion table layer, BUT I am loading 2 fusion tables (layers) & the API only allows styles to be added to one layer.

Here is my code:
  <script>
    function initMap() {
      // Styles a map in night mode.
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 40.237395466608156, lng: -93.68512878417971},
        zoom: 3.9,
        styles: []

      });

      var usa_geometry = new google.maps.FusionTablesLayer({
        query: {
          select: 'geometry',
          from: '1ZZ8j0NDbs2dilcQWjLh9xI7qIJso6DgYAoGTbA',
          where: "STATE IN ('North Dakota', 'Minnesota', 'Wisconsin', 'Ohio', 'Indiana', 'Iowa', 'Illinois', 'Kentucky', 'Missouri', 'Tennessee', 'Arkansas', 'Florida', 'Alabama', 'Mississippi', 'Louisiana', 'Texas', 'Oklahoma', 'Kansas', 'Nebraska', 'South Dakota')",
        },
        styles: [
          {
            polygonOptions: {
            fillColor: "#006db7",
            strokeColor: "#006db7",
            fillOpacity: ".5",
          },
        }],

        map: map,
        suppressInfoWindows: true
      });

      var canada_geometry = new google.maps.FusionTablesLayer({
        query: {
          select: 'geometry',
          from: '1auwG6s4axorHR-QAX3UDXL544pSEXlbxmyu6xvJC',
          where: "Place IN ('Quebec', 'Ontario', 'Manitoba')",

        },
        styles: [
          {
            polygonOptions: {
            fillColor: "#006db7",
            strokeColor: "#006db7",
            fillOpacity: ".5",
          },
        }],

        map: map,
        suppressInfoWindows: true
      });

    };

  </script>

So:

Is there a way to use the fusion table polygon data locally? i.e. export the CSV and load that?
Is there a way to load data from (join) 2 fusion tables in one map layer?
is there another option I am overlooking?

A:

Is there a way to use the fusion table polygon data locally? i.e. export the CSV and load that?

Yes, a Fusion Table can be downloaded as KML, which you can use third-party apps/libraries such as toGeoJson to load in the app as GeoJSON.

Is there a way to load data from (join) 2 fusion tables in one map layer?

You'd have to merge the tables through the Fusion Tables UI into one Fusion Table and load that layer.

is there another option I am overlooking?

Yes, as the first part of your message is incorrect: "I cannot create a fusion table & make it public without paying google...."
You can create Public or Unlisted Fusion Tables without having to pay Google.
Also, when going to your created Fusion Table in the UI, selecting Tools->Publish and selecting "Get HTML and JavaScript", you'll see the following undocumented option "options" for the FusionTablesLayer:
layer = new google.maps.FusionTablesLayer({
  map: map,
  heatmap: { enabled: false },
  query: {
    select: "col12",
    from: "1ClpNLfPQnhEex1KvGg5FrHPgzXgSu1ZvFEL9a2l1",
    where: ""
  },
  options: {
    styleId: 2,
    templateId: 2
  }
});

You can use that options to override the default styling that the Javascript API applies and use the style you defined in the Fusion Tables UI.
Here is a simple sample JSBin showing the Fusion Table style defined in the Javascript for usa_geometry while the Fusion Table style defined in the Fusion Tables UI for canada_geometry:


Q:

Why does not Hibernate set @DynamicInsert by default

Could anyone explain to me why Hibernate does not set the @DynamicInsert annotation by default and allow entities to generate an INSERT based on the currently set properties?
What's the reason for not using @DynamicInsert and, therefore, including all entity properties by default?

A:

The dynamic inserts and updates are very useful for two reasons:

reducing OptimisticLockException false positives on non-overlapping write-concern property sets
avoiding some processing overhead related to updating indexes

However, the dynamic insert/update have drawbacks as well:

you cannot reuse server-side and client-side prepared statements
it reduces the likelihood of benefiting from batch updates since the statement might change from one entity to the other.

So, there is no good way or bad way. It just depends on your data access patterns to figure out which of these two makes sense for a given entity.

A:

Because it doesn't add any significant performance improvement to skip null fields when inserting an entity.
To the contrary, it can decrease performance because, instead of being able to always use the same prepared statement to insert a row in a table, and be able to execute several inserts into a single batch, Hibernate must create a specific prepared statement for each entity to insert, which depends on the fields that are null and the fields that are not.
So, more complexity, for a reduced performance.

A:

What @jb-nizet said.
Also, dynamic-insert="true" is a bad idea in my book.
Skipping null fields from the generated SQL, soon you will find yourself in a situation where you will be declaring columns not null default which in fact causes the persistent data to be different than the entity data that hibernate knows about. This will cause frustration and likely make you resort to expensive session.refresh() calls.
For example suppose column
MESSAGE varchar(64) not null default ''

and you save an entity with null value for the property that is mapped to this column.
With dynamic-insert you will end up with an entity that has null value for the property message in-memory while at the same time the corresponding database row has ''.
I hope I made sense. Especially if you are considering dynamic-insert for such a scenario (to get away from having to set all properties for not null columns and rely on a default constraint), think again.


Q:

Making an int value of 100 change throughout the code?

import java.util.Random;
import java.util.Scanner;

public class Game2 {
    public static void main(String [] args) {

        Scanner bri = new Scanner(System.in);
        Random r = new Random();

        int roll1 = 1 + r.nextInt(6);
        int roll2 = 1 + r.nextInt(6);
        int rsum = roll1+roll2;
        int bal = 100;
        int bet;
        String wager;

        System.out.println("High n' Low");
        System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-");
        System.out.println("");
        System.out.println("Your balance is: "+bal+" $");
        do
        {
        System.out.println("");
        System.out.println("Enter an amount to bet (0 to quit): ");
        bet = bri.nextInt();

        if (bet > bal)
        {
            System.out.println("You don't have that much money Try again.");
            System.exit(0);
        }
        if (bet == 0)
        {
            System.out.println("Goodbye!");
            System.exit(0);
        }

        System.out.println("Place a wager. High, Low or Sevens? (H/L/S): ");
        wager = bri.next();

        System.out.println("");
        System.out.println("Roll #1: "+roll1);
        System.out.println("Roll #2: "+roll2);
        System.out.println("Roll Total: "+rsum);

        if (wager.equalsIgnoreCase("H"))
        {
        if (rsum >= 8)
        {
            System.out.println("");
            System.out.println("You win! Your new balance: "+(bet*1+bal)+"$");
        }
        else
        {
            System.out.println("You lost! Your new balance: "+(bal-bet)+"$");
        }
        }
        if (wager.equalsIgnoreCase("L"))
        {
        if (rsum <= 8)
        {
            System.out.println("");
            System.out.println("You win! Your new balance: "+(bet*1+bal)+"$");
        }
        else
        {
            System.out.println("You lost! Your new balance: "+(bal-bet)+"$");
        }
        }
        if (wager.equalsIgnoreCase("S"))
        {
        if (rsum == 7)
        {
            System.out.println("");
            System.out.println("You win! Your new balance: "+(bet*4+bal)+"$");
        }
        else
        {
            System.out.println("You lost! Your new balance: "+(bal-bet)+"$");
        }
        if (bal <= 0)
        {
            System.out.println("You're out of money, goodbye!");
            System.exit(0);
        }
        }
        }while (bal > 1);

}
}

I am looking to have int bal = 100 change and keep a persistently changing value when I have my if statements calculate the new balance. But it seems to keep reverting back to the value of 100 after going through a loop.

A:

You are not changing value of bal variable anywhere...you are only printing the calculated value just assign it to bal
  if (wager.equalsIgnoreCase("H"))
            {
            if (rsum >= 8)
            {

                System.out.println("");
//assign it as and then print it
    bal =(bet*1+bal)
                System.out.println("You win! Your new balance: "+bal +"$");
            }


Q:

how to create a line in d3?

I have managed to create a line chart in d3 but now need to overlay a couple of horizontal lines and vertical lines.  Here is what the chart looks like:

Here is the code:
 <!DOCTYPE html>
    <meta charset="utf-8">
    <style>

    body {
      font: 14px sans-serif;
    }

    .axis path,
    .axis line {
      fill: none;
      stroke: #000;
      stroke-width: 1.5px;
      shape-rendering: crispEdges;
    }

    .line {
      fill: none;
      stroke: steelblue;
      stroke-width: 3.5px;
    }

    .dot {
      stroke: blue;
    }

    .grid .tick {
        stroke: lightgrey;
        opacity: 0.7;
    }
    </style>
    <body>
    <script src="https://d3js.org/d3.v3.js"></script>
    <script>
          var tests = <?php echo $tests; ?>;
          console.log("tests=" +JSON.stringify(tests));
          var events = <?php echo $events; ?>;
          console.log("events=" +JSON.stringify(events));

    var margin = {top: 50, right: 20, bottom: 60, left: 90},
        width = 900 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;

    var x = d3.time.scale()
        .range([0, width]);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .ticks(d3.time.years,1)
        //makes the xAxis ticks a little longer than the xMinorAxis ticks
        .tickSize(10)
        .orient("bottom");

    var xMinorAxis = d3.svg.axis()
        .scale(x)
        .ticks(d3.time.months,1)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var line = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.total_km); });

    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    // function for the y grid lines
    function make_y_axis() {
      return d3.svg.axis()
          .scale(y)
          .orient("left")
          .ticks(5) //somehow this makes the y-axis grid draw every other line, rather than every line
    }

    var data = [];
    function DataPoint(x,y) {
        this.date_time = x;
        this.total_km = y;
    }

    var lowerLimit;
    var upperLimit;
    function loadData() {
        for (i=1; i < tests.length; i++) {
            var test = tests[i];
            console.log("x="+test[0]+", y="+test[1]);
            data.push(new DataPoint(test[0],test[1]));
            lowerLimit = test[2];
            upperLimit = test[3];
        }
    }
    loadData();
    console.log("data1="+JSON.stringify(data));

    function processData(data) {
        data.forEach(function(d) {
            console.log("d.date_time="+d.date_time +", d.total_km="+d.total_km);
            d.date = new Date(d.date_time);
            console.log("d.date=" +d.date);
        });

        //using imported data to define extent of x and y domains
        x.domain(d3.extent(data, function(d) { return d.date; }));
        y.domain(d3.extent(data, function(d) { return d.total_km; }));

        // Draw the y Grid lines
        svg.append("g")
            .attr("class", "grid")
            .call(make_y_axis()
                .tickSize(-width, 0, 0) //causes the line to be drawn the full width of the chart
                .tickFormat("")
            )

        //draw the data line
        svg.append("path")
            .datum(data)
            .attr("class", "line")
            .attr("d", line);

        //draw the upper limit
        var minDate = new Date(data[0].date_time);
        console.log("minDate="+minDate +", x(minDate)="+x(minDate));
        var maxDate = new Date(data[data.length-1].date_time);
        console.log("maxDate="+maxDate +", x(maxDate)="+x(maxDate));
        svg.append("line")
            .attr("class", "x")
            .style("stroke", "red")
            .style("stroke-dasharray", "3,3")
            .style("opacity", 0)
            .attr("x1", x(minDate))
            .attr("y1", y(upperLimit))
            .attr("x2", x(maxDate))
            .attr("y2", y(upperLimit));

    //creating a group(g) and will append a circle and 2 lines inside each group
    var g = svg.selectAll()
            .data(data).enter().append("g");

       //The markers on the line
         g.append("circle")
             //circle radius is increased
            .attr("r", 4.5)
            .attr("cx", function(d) { return x(d.date); })
            .attr("cy", function(d) { return y(d.total_km); });

    svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(0," + height + ")")
          .call(xAxis)
          .selectAll(".tick text")
          .call(wrap, 35);

    svg.append("g")
        .attr("class","xMinorAxis")
        .attr("transform", "translate(0," + height + ")")
        .style({ 'stroke': 'Black', 'fill': 'none', 'stroke-width': '1px'})
        .call(xMinorAxis)
        .selectAll("text").remove();

    svg.append("text")      // text label for the x-axis
            .attr("x", width / 2 )
            .attr("y",  height + margin.bottom)
            .style("text-anchor", "middle")
            .text("Date");

    svg.append("text")      // text label for the y-axis
            .attr("y",30 - margin.left)
            .attr("x",50 - (height / 2))
            .attr("transform", "rotate(-90)")
            .style("text-anchor", "end")
            .style("font-size", "16px")
            .text("Tryglycerides (mg/dL)");

    svg.append("text")      // text label for chart Title
            .attr("x", width / 2 )
            .attr("y", 0 - (margin.top/2))
            .style("text-anchor", "middle")
            .style("font-size", "16px")
            .style("text-decoration", "underline")
            .text("Tryglyceride Levels");

    svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
  };
  processData(data);
</script>

I want to create horizontal line at 149 for the upper limit where you want the triglyceride levels to be below.  I try to create that line in the "draw the upper limit" section.  But no line is drawn.

A:

Well I'm not real happy with this solution, but it works.  Could not figure out why the svg.append("line") command failed to display a line, so I used the svg.append("path") command instead.  I added the following code:
var data2 = [];
data2.push(new DataPoint(data[0].date_time,149));
data2.push(new DataPoint(data[data.length-1].date_time,149));
svg.append("path")
    .datum(data2)
    .attr("d", line)
    .style("stroke", "red")
    .style("stroke-dasharray", "3,3")

Then I modified the DataPoint code to this:
function DataPoint(x,y) {
    this.date_time = x;
    this.date = new Date(x);
    this.total_km = y;
}

Now the chart has a red dashed line representing the tryglyceride upper limit:


Q:

Generating a link to a controller action in Play Framework 2.3

I'm working on a Play application and need to generate links in a mixed Scala-HTML view that call controller actions. I found this question from a couple years ago that's similar to my situation, but the provided answers don't work for me.
The elements are generated in a loop so I can't manually insert the argument to the controller action, but nothing I've tried has worked. This is the line I have now:
ID: @{var fhirID = <processing for ID>; fhirID}

The accepted answer to the question I linked earlier effectively uses this structure too:
My link with some string

My issue here is twofold:
1) How can I have the variable fhirID passed to the controller action? My generated link simply has the text "fhirID" instead of what's generated by the first part of the statement.
2) Is the @routes.Users syntax correct? When I click the generated link, it literally attempts to render a page at /myapp/@routes.Users.fhirUserDetails(fhirID)
I realize I'm probably missing something very basic here- thanks for any advice!

A:

The problem seems to be not the @routes syntax (which you have completely correct) but rather a case of the Twirl engine not seeing where code ends and HTML begins (or something like that anyway...)
The line you've included, which has both a var and a semicolon, made me suspect this, and I've been able to reproduce the problem when I use that style.
My recommendation is to use the @defining helper rather than var to get a scoped variable for use in your links, as follows:
ID: @defining(<processing for ID>) { fhirID =>
  fhirID
}

You can nest @defining blocks as deeply as you like if necessary, although it's probably better to make a call out to a reusable block if there's a lot of logic. I think this style makes for more-readable templates and also somehow looks more like "real Scala" :-)


Q:

mySQL: is this a form of recursion (or co-dependence)?

I have been intrigued by a problem on SQLZoo. It is a "greatest-n-per-group" problem. I would like to understand how the engine is operating.
A table called bbc contains the name, region of the world and population of each country:
bbc( name, region, population)
The given task is to select the most populous country of each region, showing its name, the region and population.
The solution provided is:
SELECT region, name, population FROM bbc x
  WHERE population >= ALL
    (SELECT population FROM bbc y
        WHERE y.region=x.region
          AND population>0)

1. Main Question. I am finding this a bit of a mind twister. I would like to understand how the engine processes this, because at first blush it seems there is some kind of co-dependence (x depending on y, and y depending on x). Does the engine follow some kind of recursion to produce the final selection? Or am I missing something, such that either x or y is actually fixed?
2. Secondary Question. Oddly, when I pull the "AND population>0" out of the parenthesis and leave it on its own at the bottom, one of the regions (Europe / Russia) goes missing from the 8 results. Why? I don't understand that.
And indeed, when I try the query on the world database (available from the mySQL website on the same page as Sakila), the behavior is different:
With population > 0 out of the parentheses, I get 6 regions. Six is the right number in this database, because "SELECT continent FROM country GROUP BY continent" reveals seven continents, of which one is Antarctica, which includes 5 "countries", all with a 0 population.
So that seems right.
SELECT continent, `name`, population FROM country X
WHERE population >= ALL
(SELECT population FROM country Y
WHERE Y.`Continent` = X.`Continent`)
AND population>0

On the other hand, when I pull "population > 0" back into the parentheses as on SQLZoo, I also get 5 countries with a zero (the countries "belonging to Antarctica"). It doesn't matter if I specify x.population or y.population, I get zeroes.
continent      name                                          population
-------------  --------------------------------------------  ------------
Antarctica     Antarctica                                               0
Antarctica     French Southern territories                              0
Oceania        Australia                                         18886000
South America  Brazil                                           170115000
Antarctica     Bouvet Island                                            0
Asia           China                                           1277558000
Antarctica     Heard Island and McDonald Islands                        0
Africa         Nigeria                                          111506000
Europe         Russian Federation                               146934000
Antarctica     South Georgia and the South Sandwich Islands             0
North America  United States                                    278357000

Very much looking for insights on these questions!
Wishing you all a beautiful week.
:)
Notes:

For reference, the problem is number 3a on this page:
http://old.sqlzoo.net/1a.htm?answer=1
A thread mentioning the "greatest-n-per-group" problem for the same query:
MySQL world database Trying to avoid subquery
The world database is available here: http://dev.mysql.com/doc/index-other.html

A:

Main Question. I am finding this a bit of a mind twister. I would like to understand how the engine processes this, because at first
  blush it seems there is some kind of co-dependence (x depending on y,
  and y depending on x). Does the engine follow some kind of recursion
  to produce the final selection? Or am I missing something, such that
  either x or y is actually fixed?

This isn't recursion. See this from the MySQL docs.  Their solution to the problem is equivalent to this
SELECT region, name, population FROM bbc x
  WHERE population =
    (SELECT max(population) FROM bbc y
        WHERE y.region=x.region
          )

Secondary Question. Oddly, when I pull the "AND population>0" out of the parenthesis and leave it on its own at the bottom, one of the
  regions (Europe / Russia) goes missing from the 8 results. Why? I
  don't understand that.

Slight changes (as suggested by ypercube above) work
SELECT region, name, population FROM bbc x
  WHERE population >= ALL
    (SELECT population FROM bbc y
        WHERE y.region=x.region
          AND population IS NOT NULL)

This query
SELECT region, name, population FROM bbc x
  WHERE population is null

Returns a row.  Not sure why population should be nullable, but didn't take a good look at the rest of it.  Otherwise, the query should work fine without the >0
Also, this is different from the greatest-n-per-group.  In that problem you seek to find the top N items instead of just the top one.


Q:

i have  links that were working but for some reason have stopped

I have a unordered list in my HTML with 5 lists that all had  with links on them that were working fine. It was working fine until I added another unordered list, but i have no links inside it. I even gave it a separate class.
Here is my markup/CSS:

ul {
    margin: 0;
    list-style-type: none;
    color: white;
    diplay: block;
    padding-top: 20px;
    padding-left: 350px;
    font-family: "Economica", sans-serif;
    font-size: 28px;
    text-decoration: none;
}
ul li {
    padding-left: 45px;
    padding-right:45px;
    display: inline;
    text-decoration: none;
}
ul li a:hover {
   font-weight:bold;
   color:grey;
}
a {
   text-decoration: none;
   color:white;
}

 Ice Arena

                Home

                Gallery

                Order Form

                The Arena

                Contact Us

I've only added the code regarding the list and area of my problem.

A:

Add position: relative; to ul, otherwise other elements are above it and prevent the link behavior.

ul {
  margin: 0;
  list-style-type: none;
  color: white;
  diplay: block;
  padding-top: 20px;
  padding-left: 350px;
  font-family: "Economica", sans-serif;
  font-size: 28px;
  text-decoration: none;
  /* added */
  position: relative;
}

ul li {
  padding-left: 45px;
  padding-right: 45px;
  display: inline;
  text-decoration: none;
}

ul li a:hover {
  font-weight: bold;
  color: grey;
}

a {
  text-decoration: none;
  color: white;
}

Ice Arena

Home

Gallery

Order Form

The Arena

Contact Us


Q:

Is it safe to apply to a company backed by the same investors as my current company?

Let's say that I work at a company backed by a VC firm. It is safe to apply to a different company in which that VC firm has also invested?
I know that VCs often hold networking events for founders, and these circles can be tight-knit, with many professional relationships and friendships. Is there a significant risk that a founder from the company that I apply to could know a founder from my current company, and email him or her (or even mention it at an in-person meeting), risking trouble at at my current workplace?
I'm asking specifically about very small companies - about 20 employees or less, where the founders will be involved in any hiring process. At a larger company that is VC-backed (say, AirBNB, which is backed by A16Z and others),  I know that the founders won't even be remotely involved in these decisions.

A:

So for sure the founders know each other.  You don't know how tight they are.  They are going to see your resume and immediately know the company.  Would they call the founder and give them a heads up?  It is not that far fetched.  If they want to hire you they will not call.  If they don't want to hire you they might give your founder a heads up.  Risk is low but not zero.


Q:

Инструкция из while выполняется до проверки условия.

К примеру есть цикл do while(назовем его вторым) и в нем инструкции :

cin >> c;
cout << "Неправильный символ! Повторите ввод.\n";

И есть перед ним цикл do while(первый) и его инструкции :

cout << "Введите название файла\n";
getline(cin, filename);

Так вот, после завершения первого цикла, во втором начинает выполняться сначала инструкция cout << "Неправильный символ! Повторите ввод.\n";, а не инструкция cin >> c;, а потом уже после проверки условия, выполняется как положено.
Ещё есть третий цикл, просто while, с условием while(getline(cin, str)) и внутри cout << "Неправильные данные! Повторите ввод.\n";. И в нем тоже как будто игнорируется условие и сразу исполняется инструкция, а на следующий раз уже нормально.
Есть ли этому какое-то объяснение?
UPD
Вот пример кода :
    #include <iostream>
    #include <string>
    using namespace std;
int main()
{
    char c;
    do
    {
        cin >> c;
    }
    while(c != '+');

    string str_input;
    while(getline(cin, str_input))
    {
            cout << "2";
    }
    return 0;
}

После того как ввести +, сразу выводится 2, хотя должно же условие сначала выполниться.

A:

Вот это спрашивалось много раз уже.
cin >> c;

оставляет \n в потоке
надо выполнить вот такое перед  while(getline(cin, str_input))
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'));


Q:

How to show loading image before Action is completed ASP.Net MVC 5

This is an ASP.Net MVC 5 project.
I have a simple javascript/jQuery as follow:

As you can see, there is a jQuery .load method which calls SearchSingular action in the Search controller when the focus is out from HTML element with id = textBox. This works well, except that the SearchSingular action execution may sometimes take time to finish.
Thus, I want to show a loading image when the load is not finished. Is there any way to do this?

A:

Turn it into a callback
// Somecode to display a image

$("#commentDiv").load("../Search/SearchSingular?phrase=" + phrase, function() {
  // Somecode to remove image
});

A:

You can use a loading image while div contents load
("#loadingImage").show();
$("#commentDiv").load("../Search/SearchSingular?phrase=" + phrase, function(){

  $("#loadingImage").hide(); // hide the image after loading of div completes

});

Div for your loading image


Q:

Can you print a pdf file using ITextSharp (c#) ? If yes how?

I have an ASPX page which builds a report. I have a print button which builds a pdf file using ITextSharp. Now I want to print that file.
I have two questions:
How do I print it with out even saving the file ?
and If I can't do this, can I at least print the saved file ?
Thanks in advance.

A:

You cannot use iTextSharp to print PDF document. iTextSharp can be only used for reading or building PDF's.
What you can do is to show it to the user and then he can choose to print it or not.
Here is a sample how to push PDF document to user via C# ASP.NET: How To Write Binary Files to the Browser Using ASP.NET and Visual C# .NET

A:

@Jared. Well what we did was to start the acrobat reader with printing parameters after we saved it on the file system. Something like:
   ProcessStartInfo newProcess = new ProcessStartInfo(pdfPath, dfArguments);

   newProcess.CreateNoWindow = true;
   newProcess.RedirectStandardOutput = true;
   newProcess.UseShellExecute = false;

   Process pdfProcess = new Process();
   pdfProcess.StartInfo = newProcess;
   pdfProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
   pdfProcess.Start();
   pdfProcess.WaitForExit();

(please note this is not the actual code we used I got this from here) this should get you started.
For initializing adobe acrobat with printing parameters see this.
Hope it helps.


Q:

Vector of structs with const members?

Let's say I have
#include <string>
#include <vector>
using namespace std;

struct Student
{
    const string name;
    int grade;
    Student(const string &name) : name(name) { }
};

How do I, then, keep a vector of students?
int main()
{
    vector<Student> v;

    // error C2582: 'operator =' function is unavailable in 'Student'
    v.push_back(Student("john"));
}

Is there even a way to do this, or must I allocate all the students on the heap, and store a pointer to each of them instead?

A:

The simple answer is: you can't.  If you have const member variables, then the compiler can't supply a default copy-assignment operator.  However, many of the operations that std::vector provides need to make assignments, and therefore require a (public) copy-assignment operator.
Your options are:

Make name non-const.
Write your own copy-assignment operator, and think of a way to deal with "copying" a const member.

A:

You can't. Your type violates the "Assignable" requirement for standard containers.
ISO/IEC 14882:2003 23.1 [lib.container.requirements] / 3:

The type of objects stored in these components must meet the requirements of CopyConstructible
types (20.1.3), and the additional requirements of Assignable types.

From table 64 (Assignable requirements):

In Table 64, T is the type used to instantiate the container, t is a value of T, and u is a value of (possibly const) T.
expression: t = u; return type: T; post-condition: t is equivalent to u

In theory, a std::vector equivalent could choose to do destruction and copy construction in all cases, but that's not the contract that has been chosen. If reallocation isn't required, then using the contained type's assignment operator for things like vector::operator= and vector::assign might be significantly more efficient.

A:

A vector often needs to move elements around.  Every time a vector needs to grow when you call push_back() it reallocates memory to keep itself contiguous, and copies all the existing elements into the new space.  Also if you call insert() or remove() elements must
be shifted. For vector to be able to do all that the elements must be copy-assignable, which means that the type you store in the vector must have the assignment operator defined.
Generally, if you define a class, the compiler will generate the assignment operator for that class for you.  However, there are cases when the compiler is unable to do that.  One of these cases is when the class has constant members (note that pointers-to-const are ok).
So, in your case, the problem is the const string name.  It prevents the compiler from generating operator=(), which in turn prevents vector from compiling, even though you do not actually use assignment on its elements yourself.
One solution is to make name non-const.  The other is to write your own Student::operator=(), in some way that makes sense.  The third way is, as you have pointed out, to use a vector of pointers rather than a vector of objects.  But then you have to handle their allocation and de-allocation.
P.S. The other case when the compiler cannot generate operator= is when your class has members that are references.


Q:

slack slash commands show response only to channel

slack provides only two types of responses:

ephemeral = make the command and response shown to the user only.
in_channel = make the command and response shown to all users in channel.

ephemeral example:

in_channel example:

Question:
how can i make a slash command show response only in channel and not show both command and response?

A:

ok so i found my question's answer, it is said in slack's api that

The only user-facing difference between immediate responses and delayed responses is that "in channel" delayed responses will not include the initial command sent by the user. To echo the command back to the channel, you'll still need to provide a response to Slack's original visit to your invocation URL.

reference https://api.slack.com/slash-commands#responding_to_a_command


Q:

Unable to create folder and display Image using WP7 Emulator

I am new to wp7 development trying with a simple example ie..
I have an image control and 2 buttons one is for loading image and displaying it in the image control and the other is for saving that image to new folder which I need to create.
I have the below code and I am not getting any errors but the problem is I am unable to create the directory and save the existed image to that folder.
I am unable to see the directory as well as the Image after saving it.
Can we see the folder in the emulator(Or)It is only possible that we can see the created directory on the windows phone?
Imports System.IO
Imports Microsoft.Phone.Tasks
Imports System.IO.IsolatedStorage
Imports System.Windows.Media.Imaging

Partial Public Class Page1
    Inherits PhoneApplicationPage

    Public Sub New()
        InitializeComponent()
        photoChooserTask = New PhotoChooserTask()
        AddHandler photoChooserTask.Completed, AddressOf photoChooserTask_Completed
    End Sub
    Dim photoChooserTask As PhotoChooserTask
    Private Sub photoChooserTask_Completed(sender As Object, e As PhotoResult)
        Dim bmp As System.Windows.Media.Imaging.BitmapImage = New System.Windows.Media.Imaging.BitmapImage()
        bmp.SetSource(e.ChosenPhoto)
        Image1.Source = bmp
        Dim originalFilename = Path.GetFileName(e.OriginalFileName)
        SaveImage(e.ChosenPhoto, originalFilename, 0, 100)

    End Sub
    Public Shared Sub SaveImage(ByVal imageStream As Stream, ByVal fileName As String, ByVal orientation As Integer, ByVal quality As Integer)
        Using isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()
            If isolatedStorage.FileExists("NewPics\fileName") Then
                isolatedStorage.DeleteFile("NewPics\fileName")
            End If

            If Not isolatedStorage.DirectoryExists("NewPics") Then
                isolatedStorage.CreateDirectory("NewPics")
            End If

            'isolatedStorage.CreateDirectory("NewPics")
            'Dim fileStream As New IsolatedStorageFileStream("fileName", FileMode.Create, isolatedStorage)
            Dim fileStream = isolatedStorage.CreateFile("NewPics\" + fileName)
            Dim bitmap = New BitmapImage()
            bitmap.SetSource(imageStream)

            Dim wb = New WriteableBitmap(bitmap)
            wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, orientation, quality)
            fileStream.Close()
        End Using
    End Sub
    Private Sub Button1_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
        Try
            photoChooserTask.Show()

        Catch ex As System.InvalidOperationException

            MessageBox.Show("An error occurred.")
        End Try
    End Sub
End Class

Can anyone say me where I am making mistake?

A:

The code is perfect, the problem is that silverlight uses "isolated storage" for storing files, which is, as the name implies, a completely isolated storage. A file or directory created by your application will be accessible only from your application.
I think the emulator is storing the isolated storage files only in memory, since it doesn't have to keep them after a restart. If you want to easily see inside your application's isolated storage you could use a tool like Wp7 Explorer: http://wp7explorer.codeplex.com/


Q:

How do you iterate row index and find the group with the maximum determinant from the dataset in python?

I want to get the 7 index values from my dataset whose group will give me the maximum determinant of |Matrix.T*Matrix| which should be a 6 by 6 matrix.(as my no. of columns is 6).
Dataset:
Serial_no,A,B,C,D,E,F
1,0.379,-0.588,-1.69,-0.0135,0.083,-0.0297
2,-0.144,0.278,0.354,-0.000672,-0.0228,0.014
3,0.295,-0.157,-1.63,-0.00451,0.0778,-0.00969
4,0.371,-0.623,-4.98,-0.000253,0.0872,-0.0109
5,0.369,-3.11,-8.3,-0.0000105,0.0871,-0.0327
6,0.369,-0.899,-7.19,-0.0000177,0.0872,-0.0109
7,0.383,-1.04,-2.76,-0.00418,0.089,-0.033
8,0.369,-1.04,-8.3,-0.00000263,0.0871,-0.0109
9,-0.124,0.421,0.679,0.00246,-0.0216,0.0133
10,0.37,2.15,-17.1,0.000244,0.0871,0.0109
11,0.369,5.61,-14.9,0.0000352,0.0872,0.0327
12,0.369,1.45,-11.6,-0.000000963,0.0872,0.0109
13,0.369,3.53,-9.41,-0.00000186,0.0872,0.0327
14,0.369,6.44,-17.2,0.000513,0.0872,0.0327
15,-0.11,-2.57,4.11,-0.000127,-0.0209,-0.0131
16,-0.11,-2.76,4.43,-0.000606,-0.0211,-0.0132
17,0.37,0.761,-6.09,0.0000571,0.0871,0.0109
18,0.3678,1.45,-3.88,0.00209,0.0865,0.0325
19,0.381,-2.46,-19.4,-0.00274,0.0874,-0.0111
20,0.369,4.36,-11.6,-0.000003,0.0872,0.0327
21,-0.111,-1.74,2.79,0.000000903,-0.0209,-0.0131
22,-0.111,-1.91,3.05,-0.000000953,-0.0209,-0.0131
23,0.368,2.28,-6.09,0.000164,0.0871,0.0327
24,-0.11,-0.913,1.46,-0.0000412,-0.0209,-0.0131
25,-0.111,-1.08,1.73,-0.0000101,-0.0209,-0.0131
26,-0.144,-0.278,0.354,0.000672,-0.0228,-0.014
27,0.344,-0.344,-2.76,-0.00202,0.0877,-0.0107
28,0.369,3.11,-8.3,0.0000105,0.0871,0.0327
29,0.383,1.04,-2.76,0.00418,0.089,0.033
30,-0.124,-0.421,0.679,-0.00246,-0.0216,-0.0133

import pandas as pd
import numpy as np

#importing t dataset with pandas
df=pd.read_csv('Dataset.csv')
df = df.set_index('Serial_no')
X=df.iloc[:,:]

I tried this but not getting the row index values of the matrix
N = 7
def my_det(df,i):
    mat = df.iloc[i:i+N]
    return np.linalg.det(mat.T @ mat)

all_det = [my_det(df,i) for i in range(len(df)-N)]

print(np.argmax(all_det))
# 7

print(np.max(all_det))

dataset:

A:

I couldn't resist. Here is a solution using Laplace and Cauchy-Binet formulas. And a brute force one for validation.
Sample run:
 [55.67740601  0.61391687]

This output indicates that on your 30x6 example the brute force and smart solutions gave the same answer and that the brute force took 55.7 seconds while the smart one took 0.6 seconds.
Code:
import numpy as np
import pandas as pd
import itertools as it
import io

def brute_force(A):
    return max(map(list,it.combinations(range(len(A)),7)),
               key=lambda s: np.linalg.det(A[s].T@A[s]))

def smart(A):
    N = len(A)
    # binomial coefficients
    bcs = np.zeros((7,N+1),int)
    # determinants for jxj minors j=1..6
    dets = [A[:,0]]
    bcs[0] = np.arange(N+1)
    # subsets of size j for j=1..7
    combs = [bcs[None,0]]
    for j in range(1,7):
        # extend bcs, combs
        bcs[j] = bcs[j-1].cumsum()
        combs.append(np.zeros((j+1,bcs[j,-j-1]),int))
        combs[-1][0,bcs[j,1:-j-1]] = 1
        combs[-1][0] = combs[-1][0].cumsum()
        for i in range(N-j):
            combs[-1][1:,bcs[j,i]:bcs[j,i+1]] = combs[-2][:,:bcs[j-1,i+1]]
        # use Laplace's formula to compute j+1xj+1 minors
        # the tricky bit is getting the indexing right...
        idxs = np.zeros((j+1,bcs[j,-j-1]),int)
        idxs[1:] = bcs[np.arange(j)[::-1,None],combs[-1][:-1]+1].cumsum(0)
        idxs[-2::-1] += bcs[np.arange(j)[:,None],combs[-1][-1:0:-1]].cumsum(0)
        if j<6:
            dets.append(np.einsum('ji,ji->i',(A[combs[-1]+np.arange(j,-1,-1)[:,None],j])*(-1)**np.arange(j+1)[:,None],dets[-1][idxs]))
        else:
            # use Cauchy-Binet to calculate the M^T M determinants
            d62 = np.square(dets[-1])
            d7 = d62[idxs].sum(0)
            # find index of max, translate back to subset
            return combs[-1][::-1,d7.argmax()]+np.arange(7)

a = """
Serial_no,A,B,C,D,E,F
1,0.379,-0.588,-1.69,-0.0135,0.083,-0.0297
2,-0.144,0.278,0.354,-0.000672,-0.0228,0.014
3,0.295,-0.157,-1.63,-0.00451,0.0778,-0.00969
4,0.371,-0.623,-4.98,-0.000253,0.0872,-0.0109
5,0.369,-3.11,-8.3,-0.0000105,0.0871,-0.0327
6,0.369,-0.899,-7.19,-0.0000177,0.0872,-0.0109
7,0.383,-1.04,-2.76,-0.00418,0.089,-0.033
8,0.369,-1.04,-8.3,-0.00000263,0.0871,-0.0109
9,-0.124,0.421,0.679,0.00246,-0.0216,0.0133
10,0.37,2.15,-17.1,0.000244,0.0871,0.0109
11,0.369,5.61,-14.9,0.0000352,0.0872,0.0327
12,0.369,1.45,-11.6,-0.000000963,0.0872,0.0109
13,0.369,3.53,-9.41,-0.00000186,0.0872,0.0327
14,0.369,6.44,-17.2,0.000513,0.0872,0.0327
15,-0.11,-2.57,4.11,-0.000127,-0.0209,-0.0131
16,-0.11,-2.76,4.43,-0.000606,-0.0211,-0.0132
17,0.37,0.761,-6.09,0.0000571,0.0871,0.0109
18,0.3678,1.45,-3.88,0.00209,0.0865,0.0325
19,0.381,-2.46,-19.4,-0.00274,0.0874,-0.0111
20,0.369,4.36,-11.6,-0.000003,0.0872,0.0327
21,-0.111,-1.74,2.79,0.000000903,-0.0209,-0.0131
22,-0.111,-1.91,3.05,-0.000000953,-0.0209,-0.0131
23,0.368,2.28,-6.09,0.000164,0.0871,0.0327
24,-0.11,-0.913,1.46,-0.0000412,-0.0209,-0.0131
25,-0.111,-1.08,1.73,-0.0000101,-0.0209,-0.0131
26,-0.144,-0.278,0.354,0.000672,-0.0228,-0.014
27,0.344,-0.344,-2.76,-0.00202,0.0877,-0.0107
28,0.369,3.11,-8.3,0.0000105,0.0871,0.0327
29,0.383,1.04,-2.76,0.00418,0.089,0.033
30,-0.124,-0.421,0.679,-0.00246,-0.0216,-0.0133
"""

df = pd.read_csv(io.StringIO(a),index_col=0)

from time import perf_counter as pc
T = []
T.append(pc())
xb = brute_force(df.to_numpy())
T.append(pc())
xs = smart(df.to_numpy())
T.append(pc())

assert (xs==xb).all()
print(np.diff(T))


Q:

Draw a sudoku board using line drawing characters

This is code golf. For this challenge, I will accept a method (you don't need a full program), but the method signature does count towards the byte count and I want to see the full signature (not a lamdba). The input for the method is an integer array with 81 elements. The output/return value from the method is a string that represents the array as an ascii sudoku board.
If you're using an esoteric language or something that absolutely doesn't have methods, you can adapt, but if the language supports this at all I want to see something might actually be plugged into a "real" ungolfed program, even if the method body itself is a pain to work with. The requirement is not meant to block languages like Jelly or 05AB1E, but to make it easier for languages like Java to build something that makes sense for that platform.
For the input, integer values 1-9 should have obvious meanings. A 0 should always be interpreted as a blank cell. You may also interpret anything else outside the 1-9 range as a blank cell, but this is not required. Positioning from the array to the puzzle starts at the top left and fills each row from left to right before moving to the next row.
For the boxes, I want double lines around the outside and between each 3x3 region, and single lines between other cells. These should be drawn with line drawing characters (if your I/O format represents strings as a sequence of bytes rather than a sequence of characters, you should represent them in a well-known encoding such as UTF-8 or codepage 347).
For this challenge, I am NOT asking you to generate the sudoku puzzle. That is the input for the function. I am NOT asking you to solve the puzzle. I'm just asking you to produce a string to "draw" what you're given (in as few bytes as possible).
Example Input:
Values for the array:
{ 8, 5, 0, 0, 0, 2, 4, 0, 0, 7, 2, 0, 0, 0, 0, 0, 0, 9, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 7, 0, 0, 2, 3, 0, 5, 0, 0, 0, 9, 0, 0 ,0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 7, 0, 0, 1, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 6, 0, 4, 0}

The values can use whatever mechanism is natural for your language: int[], ArrayList, sequence, tuple, string of digits, whatever, as long as you have a value in the input for every cell (no maps for only populated cells to positions). Remember that the input is supplied... it is not part of your byte count. But the input might represent any sudoku puzzle, and the puzzle might not even have a valid solution. You do get to assume that puzzle is printable. You won't get something with 82 elements, for example.
You also get to assume a reasonable fixed-width font.
Corresponding Output:

╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗
║ 8 │ 5 │   ║   │   │ 2 ║ 4 │   │   ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ 7 │ 2 │   ║   │   │   ║   │   │ 9 ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║   │   │ 4 ║   │   │   ║   │   │   ║
╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣
║   │   │   ║ 1 │   │ 7 ║   │   │ 2 ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ 3 │   │ 5 ║   │   │   ║ 9 │   │   ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║   │ 4 │   ║   │   │   ║   │   │   ║
╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣
║   │   │   ║   │ 8 │   ║   │ 7 │   ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║   │ 1 │ 7 ║   │   │   ║   │   │   ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║   │   │   ║   │ 3 │ 6 ║   │ 4 │   ║
╚═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╝

A:

Python 3, 232 bytes
Thanks to those who helped to golf this down.
Encryption within encryption...
q=lambda x,y:x+y+x+y+x
r=lambda a,b,c,d,e:a+q(q(b*3,c),d)+e+"\n"
print(((r(*"╔═╤╦╗")+q(q("║ %d │ %d │ %d "*3+"║\n",r(*"╟─┼╫╢")),r(*"╠═╪╬╣"))+r(*"╚═╧╩╝"))%eval(input())).replace(*"0 "))

Try it online!
To be golfed.

A:

C (gcc), 398 395 291 bytes
Saved 3 bytes by working through the string reversed, and 104 (!) bytes thanks to Leaky Nun.
#include<locale.h>
#define q(x,y) x y x y x
#define D L"╝"q(q("═══","╧"),"╩")"╚"q(q("\n║"q(q(" & ","│"),"║")"║","\n╢"q(q("───","┼"),"╫")"╟"),"\n╣"q(q("═══","╪"),"╬")"╠")"\n╗"q(q("═══","╤"),"╦")"╔"
i;f(int*t){setlocale(LC_ALL,"");for(i=721;i--;)wprintf(L"%lc",D[i]%19?D[i]:*t++?48+t[-1]:32);}

Try it online!
C (gcc), 395 bytes
I'll keep this here so its more evident as to how the program works.
#include<locale.h>
#define A L"\n╢───┼───┼───╫───┼───┼───╫───┼───┼───╟"
#define B L"\n║ & │ & │ & ║ & │ & │ & ║ & │ & │ & ║"
#define C L"\n╣═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╠"
#define E B A B A B
#define D L"╝═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╚"E C E C E L"\n╗═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╔"
i;f(int*t){setlocale(LC_ALL,"");for(i=721;i--;)wprintf(L"%lc",D[i]%19?D[i]:*t++?48+t[-1]:32);}

Try it online!
Working with unicode in C is... costly. Takes input as an int* as shown in the link and in the specification.
I'm going to see if I can save bytes using some number magic instead of hardcoding the string.

A:

PHP, 297 bytes
<?for(;$l<19;$l++)echo$l&1?strtr(vsprintf(str_pad("",67,"║ %d │ %d │ %d "),array_slice($_GET,9*($l/2^0)-9,9)),0," "):str_pad([╔,╟,╠,╚][$b=$l?$l<18?$l%6<1?2:1:3:0],108,strtr("11101110111".[╦,╫,╬,╩][$b],[[╤,═],[┼,─],[╪,═],[╧,═]][$b])).[╗,╢,╣,╝][$b],"
";

Try it online!
Expanded
for(;$l<19;$l++)  # loop thrpugh lines
  echo$l&1 # Output
    ?strtr(
        vsprintf(str_pad("",67,"║ %d │ %d │ %d ") # formated string for lines with numbers
        ,array_slice($_GET,9*($l/2^0)-9,9)) # nine items of the input array
      ,0," ") #replace zeros with space
    :str_pad([╔,╟,╠,╚][$b=$l?$l<18?$l%6<1?2:1:3:0] # start character non number lines and switch number four cases
      ,108 # fill too 108 bytes
      ,strtr("11101110111".[╦,╫,╬,╩][$b] # with string
        ,[[╤,═],[┼,─],[╪,═],[╧,═]][$b]))  #replace ones and zero with the two character in array chosed
    .[╗,╢,╣,╝][$b] # end row with chosen character
  ,"
    "; # end line with new line

used functions for both versions
vsprintf , strtr , str_pad , array_slice , array_chunk
PHP, 313 bytes
<?$r=($s=str_pad)(╔,108,($t=strtr)(($p=11101110111).╦,[╤,═])).╗;foreach(array_chunk($_GET,9)as$v)$r.=$t(vsprintf($s("
",68,"║ %d │ %d │ %d "),$v),0," ").(++$k%9?$k%3?$s("
╟",109,$t($p.╫,[┼,─])).╢:$s("
╠",109,$t($p.╬,[╪,═])).╣:"");echo$r.$s("
╚",109,$t($p.╩,[╧,═])).╝;

Try it online!


Q:

Add object on image Picker photo display (swift3)

The code below is code for just taking a standard photo using image picker. I am working on a app that masks a photo. So What I am trying to do is block out some of the image picker with a box. So the user knows that they should not put there face in the area with a box over it.

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate  {
var currentImageView: UIImageView?
var imagePicker: UIImagePickerController!
let maskView = UIImageView()

@IBOutlet var letImageVIEW: UIImageView!

@IBOutlet var finalImage: UIImageView!
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    self.dismiss(animated: true, completion: nil)
    self.currentImageView?.image = image

}
@IBAction func takePhotoLeft(_ sender: Any) {
    self.currentImageView = self.letImageVIEW
    imagePicker =  UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .camera
    present(imagePicker, animated: true, completion: nil)

    }

A:

You can use UIImagePickerController property cameraOverlayView. Try this.
@IBAction func takePhotoLeft(_ sender: Any) {

    self.currentImageView = self.letImageVIEW
    imagePicker =  UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .camera

    let blockView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 150))
    blockView.backgroundColor = UIColor.red
    imagePicker.cameraOverlayView = blockView
    imagePicker.showsCameraControls = false

    present(imagePicker, animated: true, completion: nil)
}


Q:

How to show objects inside html elements like console?

I wanna show the whole object inside a paragraph called "demo", and i want the object to be shown similar to the way that it will be in the console. But instead of that it returns "[object object]" inside the paragraph.
Is there a way to show it like console.log method inside the paragraph?.
Here is my code :

var obj = {
  subobj: {prop1: "value1", prop2: "value2", prop3: "value3"},
};

var var1 = "subobj";

function func() {
  for (x in obj) {
    if (var1 == x) {
      // i want it to be shown like the console.log method
      // console.log(obj[x])
      document.getElementById("demo").innerHTML = obj[x];
    }
  }
};

func()

A:

You can just stringify the whole object rather than looping through each key/value pair and put the result in a pre element:
function func(obj) {

  // null refers to an optional replacer function which we won't
  // use in this instance. 2 is an optional parameter to set the
  // indentation, in this case 2 spaces
  var json = JSON.stringify(obj, null, 2);
  document.getElementById("demo").innerHTML = json;
};

OUTPUT
{
  "subobj": {
    "prop1": "value1",
    "prop2": "value2",
    "prop3": "value3"
  }
}

DEMO


Q:

SQL join for two tables, with same column names on Python

There are already a few questions with the same problems, I have all they looked, but still no solution found.
I would like to merge and count from two tables, the column with the same name (device_id).
column names: events and gender_age_train
import pandas as pd
from sqlalchemy import create_engine # database connection

db_engine = create_engine('sqlite:///devices-train.db')

join_devices = pd.read_sql_query('SELECT device_id, count(device_id), gender_age_train.device_id, count(gender_age_train.device_id) FROM events JOIN gender_age_train on events.device_id = gender_age_train.device_id GROUP BY device_id', db_engine)

print join_devices

the python output is:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) ambiguous column name: device_id [SQL: 'SELECT device_id, count(device_id), gender_age_train.device_id, count(gender_age_train.device_id) FROM events JOIN gender_age_train on events.device_id = gender_age_train.device_id GROUP BY device_id']

A:

You need to fully qualify the device_id column since, as you noted, it appears in both tables. It's worth noting that it's a tad pointless to select both events.device_id and gender_age_train.device_id as they are equal (according to the join condition). Selecting one of them should suffice:
SELECT   e.device_id, COUNT(*)
FROM     events e
JOIN     gender_age_train g on e.device_id = g.device_id
GROUP BY e.device_id


Q:

System.FormatException of a string

I'm getting System.FormatException: Input string was not in a correct format when running this method.
The values of the fields:
arrayName = "requester";
fieldList = "\"name\" : \"shimshon\""; // "name" : "shimshon"

public override string ToString()
{
   var val = string.Format("\"{0}\" : { {1} }", arrayName, fieldList);

   return val;
}

the expect result of the method is
"requester" : { "name" : "shimshon" }

What is wrong with this format?

A:

I think you want:
var val = string.Format("\"{0}\" : {{ {1} }}", arrayName, fieldList);

Note the doubled {{ and }} which is the escape sequence necessary to get braces literally into the output.


Q:

Initializing dialog with class/object instance data?

I have a dialog and some of it's static text controls should be updated during runtime, the data, that is text, lives in an instance of the class object and is dinamicaly changed.
the class has a button or menu that start the dialog, but how do I pass that data to dialog if dialog procedure is a separate function independed of a class:
the class has the data:
class A
{
    public:
        int data = 1; // pass this data to dialog
}

INT_PTR CALLBACK DlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
      switch(uMsg)
      {
           case WM_INITDIALOG:
                SetWindowText(GetDlgItem(hDlg, IDC_STATIC), std::to_string(input class A data here));
      }
}

Is the only way to make the data static member or is there some better standard prcedure to pass data to dialog from an instance of object?

A:

DialogBoxParam() last parameter is passed as the lParam to WM_INITDIALOG.
You can pass a pointer to your class there.


Q:

Java Hibernate connection to database timed out after few minutes

Hibernate loses connection to the database after a few minutes and sends such an error:

org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN:
SQL Error: 0, SQLState: 08S01 paź 18, 2018 11:17:40 PM
org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR:
The last packet successfully received from the server was 363 452
milliseconds ago.  The last packet sent successfully to the server was
363 493 milliseconds ago. is longer than the server configured value
of 'interactive_timeout'. You should consider either expiring and/or
testing connection validity before use in your application, increasing
the server configured values for client timeouts, or using the
Connector/J connection property 'autoReconnect=true' to avoid this
problem.

I added autoreconnect=true but it did not work and the error still occurred.
Then I created DatabaseConnectionController which has the following function:
public static EntityManagerFactory getEntityManagerFactory() {

    if (entityManagerFactory != null && entityManagerFactory.isOpen()) {
        return entityManagerFactory;
    } else {
        return requestNewConnection();
    }
}

The problem still occurred and I started to search for answers in google, I added a few lines to persistance.xml:
<property name="hibernate.dbcp.validationQuery" value="SELECT 1" />
<property name="hibernate.dbcp.testOnBorrow" value="true" />
<property name="hibernate.dbcp.validationInterval" value="60000" />
<property name="hibernate.dbcp.testOnReturn" value="true" />

It also did not solve my problem.
Hibernate does not automatically reconnect to the database the first time it just send error message, but when it is sent the second query automatically reconnects to the database.
How can I set it to reconnect automatically after disconnection or how can I catch this error and repeat the query in the code?

A:

The problem is that databases will drop idle connections. How long can a connection be idle depends on your DB's configuration. In order to fix this you need to use a connection pool, like c3p0. To use it, you would need to add the following dependencies in your Maven.
<!-- c3p0 -->
<!-- Session manager -->
<!-- Check that the version works for you -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-c3p0</artifactId>
    <version>5.2.12.Final</version>
</dependency>

Then you need to add the following configurations to your hibernate.cfg.xml.
<!-- c3p0 -->
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.timeout">600</property>
<property name="hibernate.c3p0.max_size">25</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.max_statement">0</property>
<property name="hibernate.c3p0.acquireRetryAttempts">1</property>
<property name="hibernate.c3p0.acquireRetryDelay">250</property>

This should be enough to keep creating new connections and solve your connectivity issues.


Q:

Detect when smart watches are visiting a web page

Smart watches are getting web browsers and although it may not be the optimal device to use to browse the web a few people will probably use them. What I would like to do is to detect if someone visits a web page with a smart watch.
I would like to do this with either PHP or javascript or a combination of the two.
How could I check to be mostly sure that it is a smart watch visiting the web page?

A:

Screen size and user agent are the two most common routes for detection.  User agent would depend on the watch.


Q:

How to show more of the datasource fields in the Kendo UI popup editor, but not in the grid

Looks like this has been "sorta" asked - but not quite.  So here goes...
Have a Kendo UI grid.  Working great.  Want to edit in a "popup" the record that is selected. That works great as well.  However, there are many more fields in the record than what I am showing in the grid.
So can someone explain how to create a full edit form in the popup, and not have to display all the fields in the grid?
Using PHP for this.
Thanks in advance...

A:

You need to use the editable.template option of the grid. You have to implement it in JavaScript though.


Q:

Fixed-point iteration complex-valued function

I have the complex-valued function
\begin{equation}
f(z) = \frac{1}{1 + a(1 - z)}, \quad 0 < a < 1, ~ |z| \le 1.
\end{equation}
For $|z| \le 1$ we have $|f(z)| \le 1$. Further, $z = f(z)$ has  a single root in $|z| \le 1$, namely $z = 1$.
Define the sequence $z_n = f(z_{n - 1}), ~ n = 1,2,\ldots$ and set $|z_0| \le 1$. I want to show that $\lim_{n \to \infty} z_n = 1$.
Could anyone point me to some references? This should be easy, but I am not well-versed in complex-analysis nor in fixed-point iterations.

A:

HINT.- First at all you have to prove that $$\left|\frac{a}{(1+a(1-z))(1+a(1-w))}\right|\le K\lt 1$$ for $f(z)$ be a contraction, i.e. $|f(z)-f(w)|\le K|z-w|$. The corresponding fixed point in the complet metric space $|z|\le 1$ is the limit of iterated $fofof....fof(z_0)$ for any arbitrary $z_0$ in the unit ball $|z|\le 1$.
Since $z_1=f(z_0),z_2=f(z_1),....,z_n=f(z_{n-1})$ one has
$$|z_2-z_1|\le K|z_1-z_0|\\|z_3-z_2|\le K|z_2-z_1|\le K^2|z_1-z_0|\\.....\\|z_{n+1}-z_{n}|\le K^n|z_1-z_0|$$ It follows the Cauchy sequence $\{z_n\}$ because $$|z_{n+p}-z_n|\le |z_{n+p}-z_{n+p-1}|+|z_{n+p-1}-z_{n+p-2}|+.....+|z_{n+1}-z_n|$$
$$|z_{n+p}-z_n|\le (K^{p-1}+K^{p-2}+.....+K+1)K^n|z_1-z_0| \le\frac{K^n}{1-K}|z_1-z_0|$$ (we know that $\sum_{k=0}^{k=\infty}K^i=\frac{1}{1-K}$ and $K^n$ tends to $0$).
Hence $\{z_n\}$ has a limit $z$ and, because $f$ is continuous, if $z_n\to z$ then $f(z_n)\to f(z)$.
On the other hand, the uniqueness of this fixed point is clear because if $z$ and $w$ were distinct fixed points then one has the contradiction $$|z-w|\le K|z-w|\lt |z-w|$$ We finish with the fixed point $z=1$ having in hand and because of the uniqueness.


Q:

UIButton touchUpInside action firing multiple times per click

I have three buttons set up in Interface Builder, each tied via touchUpInside to btnSelection:
- (IBAction)btnSelection:(id)sender {
    NSLog(@"tag: %i", [sender tag]);
}

In my console, the first click registers correctly (after a second or so delay, which seems a bit weird) but any subsequent touch of any of the 3 buttons results in first logging the previous tag value, then logging the new tag.
Touch #1 (btn w/ tag=0):
tag:0
Touch #2 (btn w/ tag=1):
tag:0
tag:1
Touch #3 (btn w/ tag=2):
tag:1
tag:2
and so on.
I can't figure out why two events are being logged each time (with the first being the previously touched button.

A:

One possible reason is that if you hooked up your button to the event, and then copied that button and hooked up the event again, you might be calling your btnSelection function twice.
In interface builder, check to see that you only have one callback to btnSelection


Q:

Comparing Colors

I'm manipulating an excel file (using  Interop). I'm trying to check the background color of a specific cell.
if (xlWorkSheet.Cells[1,j+1].Interior.Color == System.Drawing.Color.Red)
{
    cell1.Interior.Color = System.Drawing.Color.Red;
}

'Operator '==' cannot be applied to operands of type 'double' and
  'System.Drawing.Color

I'm not even sure If this error make sense because I have this code which I can use it just fine. So If I can assign, why can't I compare?
cellHeader.Interior.Color = System.Drawing.Color.Red;

A:

To elaborate on David Smith's answer:
if (xlWorkSheet.Cells[1,j+1].Interior.Color.Equals(System.Drawing.Color.Red))
{
    cell1.Interior.Color = System.Drawing.Color.Red;
}

Certain types in c# cannot be compared using the == operator. It works for a few types, but anything other than primitive types generally use the .Equals() method instead. It serves the same purpose, but works in many more scenarios.
See here for more:
https://www.c-sharpcorner.com/UploadFile/3d39b4/difference-between-operator-and-equals-method-in-C-Sharp/


Q:

Select a file on an open Windows Explorer

I have the following cod that will start a Windows Explorer with a file selected and maximize Explorer. It then will look for the Windows Explorer and minimize it. I did the maximize-minimize so that I would not have to do this manually (lazy, I know). I have this set up in my code to trigger only when the folder is not open. If it is open, then just run the minimize part. Here's the code:
If Not FolderIsOpen Then
    Dim curProcess As Process = New Process()
    With curProcess
        With .StartInfo
            .FileName = "explorer.exe"
            Dim MinimizeName As String = RegScoringWorkbookName.Replace(".xlsm", ".zip")
            .Arguments = String.Format("/select, ""{0}""", MinimizeName)
            .WindowStyle = ProcessWindowStyle.Maximized
        End With
        .Start()
    End With
    Thread.SpinWait(100000000)
    For Each IWindow As InternetExplorer In SHWindows
        If IWindow.Name = "Windows Explorer" Then
            Dim GetURIPath As New Uri(IWindow.LocationURL)
            If GetURIPath.LocalPath.ToLower.Equals(FolderName) Then
                ShowWindow(CType(IWindow.HWND, IntPtr), SW_SHOWMINIMIZED)
                Exit For
            End If
        End If
    Next IWindow
Else
    For Each IWindow As InternetExplorer In SHWindows
        If IWindow.Name = "Windows Explorer" Then
            Dim GetURIPath As New Uri(IWindow.LocationURL)
            If GetURIPath.LocalPath.ToLower.Equals(FolderName) Then

                'Code here to select the targeted file

                ShowWindow(CType(IWindow.HWND, IntPtr), SW_SHOWMINIMIZED)
                Exit For
            End If
        End If
    Next IWindow
End If

So, my question is, can Explorer be told to select a file on an already opened Windows Explorer?

A:

You could just shell it out.
Dim i = Shell("explorer /select, C:\Folder\File.exe", AppWinStyle.NormalFocus)


Q:

Write the implementation to pass this test

Given the following test, implement an addOne function in C# so it passes, without any modification to the test. TIP: Yes, it is possible.
[TestMethod]
public void TheChallenge()
{
    int a = 1;

    addOne(a);

    Assert.IsTrue(a == 2);
}

EDIT: clarified the Assert to avoid confusion. The value of a should be 2; there's no trick there.

A:

Ummm, simply provide an implementation of AssertTrue that doesn't throw anything?
void addOne(int a){}

void AssertTrue(bool b) { }

You never specified what testing framework is used here. It looks like MSTest, but I fired up a new test project and AssertTrue doesn't exist, so I took the liberty of implementing it myself.
EDIT
This solution might be what you were fishing for:
void addOne(int x)
{
  unsafe
  {
    int* i = &x;
    i += 4;
    *i += 1;
  }
}

I feels pretty fragile, but it works on my box consistently. It probably depends heavily on the compiler, so hopefully it is reproducible elsewhere.


Q:

Going live with PHP SDK: Error 401 Unauthorized

After all the neccesary steps in Sandbox/Demo account my Integrator key was marked Live and I attached it to live account.
I am using DocuSign PHP SDK so I changed API username, API password, API account ID and Host to Live account credentials according to this guide - Post Go Live steps.

Anyway I am getting error 401 Unauthorized when attempting to create Envelope (or anything else).

A:

Solution:
When going live while using DocuSign PHP SDK, set Host parameter to https://eu.docusign.net/restapi or any other subdomain provided by DocuSign that suits you best (eu, na1 ,na2, etc...).
Explaination:
When working with DocuSign PHP SDK, you don't need to do login request to retrieve baseUrl parameter for your actual request (ex: creating Envelope). Instead you set Host parameter right at the beginning of your code and don't care about baseUrl anymore.
And that is where the problem lies. WITHOUT SDK, you first do login request to https://www.docusign.net/restapi/v2/login_information to get back your baseUrl paramater (ex: https://eu.docusign.net/restapi/v2/account/1234/envelopes) and use that for actual request. So when working WITH SDK, set the subdomain of Host parameter to eu, na1, na2 or any other valid value provided by DocuSign right away.
I found the solution thanks to this answer: https://stackoverflow.com/a/44119359/3970975


Q:

Can I Force A ASP.Net Website to Show Time in A Specific Time Zone?

I have a client request that all times be displayed in Pacific Time Zone, regardless of client settings. I'd like to avoid a scenario where I have to call a function for every time display and instead have a single point where I can make the switch.
I'm thinking a custom culture might do the trick, but I wanted to ask before I set off down a potentially blind alley (or miss something trivially easy).

A:

You could use TimeZone.GetUTCOffset() and DateTime.UtcNow()
Basically get the UTC Time and offset that based on the timezone you are interested in.
Kindness,
Dan


Q:

Range.End() Confuzzlement

I have a general question regarding the Range.End() property in VBA.  I've read up on the property
here, but I'm still confused. Example:
    With ws
       lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
       MsgBox ("Last row for xlUP is: " & lastRow)
    End With

Why is the xlDirection xlUp? Why isn't it xlDown? Is it starting from the bottom row and going up then? I know this is wrong cause I used it on my code (and cause everyone uses xlUp when finding the last used row), but I don't know why. Could someone please explain?

A:

End(xlDown) searches from the top down finding the last used cell before a blank cell.  But that might not be the very last used cell if there are blank cells in the data.  Do it your self manually: highlight a column that contains data intermixed with blanks and then press ctrl down - it will go to the cell before the first blank cell.
On the other hand End(xlUp) searches from the bottom of the range upwards for the first used cell that is before a blank cell.  This will always be the last used cell in the range because we started at the bottom.


Q:

scss compilation issue in angular lib created using angular-cli

Created(ng build my-lib) an angular lib with global scss then bundled into one file and copied to lib's folder.
dist-lib/my-lib/lib/sass/my-lib.scss

Now my-lib.scss imports some resources like
@font-face {
    font-family:"Roboto Regular";
    font-weight:normal;
    font-style:normal;
    src: url("../resources/fonts/roboto-regular/Roboto-Regular.eot?") format("eot"),  /* IE9 Compat Modes */
         url("../resources/fonts/roboto-regular/Roboto-Regular.woff") format("woff"), /* Pretty Modern Browsers */
         url("../resources/fonts/roboto-regular/Roboto-Regular.ttf") format("truetype");  /* Safari, Android, iOS */
}

I copied the resources folder to my lib at location
dist-lib/my-lib/lib/resources
                             /fonts
                                   / roboto-regular/Roboto-Regular.eot

Now in my Application's styles.scss file I am importing my-lib.scss file like this
@import "../dist-lib/my-lib/lib/sass/my-lib";

But this is showing error
ERROR in ./src/styles.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./src/styles.scss)
Module Error (from ./node_modules/postcss-loader/src/index.js):
(Emitted value instead of an instance of Error) CssSyntaxError: D:\SK\Study\Angular\AngularLib\MyLib\dist-lib\my-lib\lib\sass\my-lib.scss:10:9:
Can't resolve '../resources/fonts/roboto-regular/Roboto-Regular.woff' in 'D:\SK\Study\Angular\AngularLib\MyLib\src'

   8 |     font-style:normal;
   9 |     src: url("../resources/fonts/roboto-regular/Roboto-Regular.eot?") format("eot"),  /* IE9 Compat Modes */
> 10 |          url("../resources/fonts/roboto-regular/Roboto-Regular.woff") format("woff"), /* Pretty Modern Browsers */
     |         ^
  11 |          url("../resources/fonts/roboto-regular/Roboto-Regular.ttf") format("truetype");

I guess the resources are getting resolved relative to file src/styles.scss instead of relative to dist-lib/my-lib/lib/sass/my-lib.scss
What is the solution for this?

A:

As I am building/serving my project through Angular-Cli, so the plugins/loaders that it uses to deal scss was not resolving the issues of relative (to the library itself) URLs (url(../)).
To solve this I created fonts.css not fonts.scss that I ship with the library. And end user has to import this fonts.css as well.
And this is working now, though this does not sound a good solution, I got this workaround till the time.
Update : Providing font.scss
@font-face {
    font-family: 'Proxima Nova';
    src: url('../assets/fonts/proxima-nova-light/ProximaNova-Light.eot');
    src: url('../assets/fonts/proxima-nova-light/ProximaNova-Light.eot?#iefix') format('embedded-opentype'),
        url('../assets/fonts/proxima-nova-light/ProximaNova-Light.woff2') format('woff2'),
        url('../assets/fonts/proxima-nova-light/ProximaNova-Light.woff') format('woff'),
        url('../assets/fonts/proxima-nova-light/ProximaNova-Light.ttf') format('truetype'),
        url('../assets/fonts/proxima-nova-light/ProximaNova-Light.svg#ProximaNova-Light') format('svg');
    font-weight: 300;
  }

  @font-face {
    font-family: 'Proxima Nova';
    src: url('../assets/fonts/proxima-nova-regular/ProximaNova-Regular.eot');
    src: url('../assets/fonts/proxima-nova-regular/ProximaNova-Regular.eot?#iefix') format('embedded-opentype'),
        url('../assets/fonts/proxima-nova-regular/ProximaNova-Regular.woff2') format('woff2'),
        url('../assets/fonts/proxima-nova-regular/ProximaNova-Regular.woff') format('woff'),
        url('../assets/fonts/proxima-nova-regular/ProximaNova-Regular.ttf') format('truetype'),
        url('../assets/fonts/proxima-nova-regular/ProximaNova-Regular.svg#ProximaNova-Regular') format('svg');
    font-weight: 400;
  }

  @font-face {
    font-family: 'Proxima Nova';
    src: url('../assets/fonts/proxima-nova-medium/ProximaNova-Medium.eot');
    src: url('../assets/fonts/proxima-nova-medium/ProximaNova-Medium.eot?#iefix') format('embedded-opentype'),
    url('../assets/fonts/proxima-nova-medium/ProximaNova-Medium.woff2') format('woff2'),
    url('../assets/fonts/proxima-nova-medium/ProximaNova-Medium.woff') format('woff'),
    url('../assets/fonts/proxima-nova-medium/ProximaNova-Medium.ttf') format('truetype'),
        url('../assets/fonts/proxima-nova-medium/ProximaNova-Medium.svg#ProximaNova-Medium') format('svg');
        font-weight: 500;
  }

  @font-face {
    font-family: 'Proxima Nova';
    src: url('../assets/fonts/proxima-nova-bold/ProximaNova-Bold.eot');
    src: url('../assets/fonts/proxima-nova-bold/ProximaNova-Bold.eot?#iefix') format('embedded-opentype'),
        url('../assets/fonts/proxima-nova-bold/ProximaNova-Bold.woff2') format('woff2'),
        url('../assets/fonts/proxima-nova-bold/ProximaNova-Bold.woff') format('woff'),
        url('../assets/fonts/proxima-nova-bold/ProximaNova-Bold.ttf') format('truetype'),
        url('../assets/fonts/proxima-nova-bold/ProximaNova-Bold.svg#ProximaNova-Bold') format('svg');
    font-weight: 700;
  }

As I have used font.scss that will be compiled to font.css file as the lib build process using this script
"build-lib-fonts": "node-sass --include-path scss ./projects/project/src/lib/styles/_fonts.scss ./dist-lib/project/styles/fonts.css",


Q:

Vuetify password confirmation not working

I need to create a registration mask and I want to make sure that the two passwords the user types in are identical before continuing but I cannot figure out how to do it in Vuetify.
I have tried creating a rule for it but it doesn't seem to work.
This is my code:
Template:
    <v-row>
      <v-col>
        <v-flex md5>
          <v-text-field v-model="pw1"
            label="Password"
            type="password"
            :rules="pwdRules"
          ></v-text-field>
        </v-flex>
      </v-col>

      <v-col>
        <v-flex md5>
          <v-text-field v-model="pw2"
            label="Confirm Password"
            type="password"
            :rules="pwdConfirm"
          ></v-text-field>
        </v-flex>

      </v-col>
    </v-row>

Script:
export default {
    data: () => ({
      pwdRules: [ v => !!v || 'Password required' ],
      pwdConfirm:[ v => !!v || 'Confirm password', v => v === this.pw1 || 'Passwords do not match'],
    }),

The funny thing is if I use this code snippet v => v === this.pw1 || 'Passwords do not match' it even makes Vuetify ignore the first rule which checks if the field is empty or not. If I delete this snippet the rule works correctly and checks if the field is empty but it obviously doesn't check if the two passwords are identical.

A:

Vue component's data must be a function, not an arrow function since an arrow function doesn’t have a this. From Vue.js docs:

Don’t use arrow functions on an options property or callback, such as
  created: () => console.log(this.a) or vm.$watch('a', newValue =>
  this.myMethod()). Since an arrow function doesn’t have a this, this
  will be treated as any other variable and lexically looked up through
  parent scopes until found, often resulting in errors such as Uncaught
  TypeError: Cannot read property of undefined or Uncaught TypeError:
  this.myMethod is not a function.

You are referencing pw1 and pw2 which are not defined in data.

Here is Codepen


Q:

Jquery keypress issues

Ive been going round and round with this so I am hoping someone can assist me.
I have two functions in my code. The first works fine. You can click on the displayed value enter the info into the input field that displays and press enter and it works. The second when you click the value it shows the input but when you press enter it hangs the page and then it refreshes. However the cookie is stored.
Any ideas why the first one is working correctly but the second is making the page hang and refresh?
$(document).ready(function() {

    $('#userTo').click(function() {
        if($(this).children('[name=userTo]').length == 0) {
            $(this).html('<input type="text" name="userTo" size="3" value="<?php echo (abs((int)        $_COOKIE['user_for']) ? abs((int) $_COOKIE['user_for']) : $ir['userid']); ?>" style="font-size: 12px;font-family: Tahoma;padding:0;margin:0;text-align: center;" />');
            $('[name=userTo]').focus();
        }
    });

    $('#userTo').keypress(function(e){
        if(e.which == 13){
            var username = $('[name=userTo]').val();
            $.ajax({
                type: "GET",
                url: "donate.php",
                cache: false,
                data: "username=" + username,
                success: function(data){
                    if(data == 'null') {
                        alert('That user dosen\'t exist.');

                        $('[name=userTo]').focus();
                    } else {
                        $.cookie("user_for", username);
                        $('#userTo').html(data);
                    }
                }
             });
          }
     });
});

and this is the second function.
$(document).ready(function() {

    $('#credits').click(function() {
        if($(this).children('[name=credits]').length == 0) {

            $(this).html('<input type="text" name="credits" size="3" value="<?php echo (abs((int)   $_COOKIE['user_credits']) ? abs((int) $_COOKIE['user_credits']) : $ir['d_credits']); ?>" style="font-size: 12px;font-family: Tahoma;padding:0;margin:0;text-align: center;" />');
            $('[name=credits]').focus();
        }
    });

    $('#credits').keypress(function(e){
        if(e.which == 13){
            var d_credits = $('[name=credits]').val();
            $.ajax({
                type: "GET",
                url: "donate.php",
                cache: false,
                data: "d_credits=" + d_credits,
                success: function(data){
                    if(data == 'null') {
                        alert('That user dosen\'t exist.');
                        $('[name=credits]').focus();                               } else {
                        $.cookie("user_credits", d_credits);                                  $('#credits').html(data);
                    }
                }
            });
         }
    });
});

A:

There's a lot of cleanup you could do in your code, but the main thing is: If you don't want the page to refresh when you hit enter in a form, you need to prevent the browser's default keypress handler from firing when you hit enter. As it is right now, your handler function will run first and do your ajax GET, and then the default handler will run, which will (probably) submit the form.
$('#credits').keypress(function(e) {
    if(e.which == 10 || e.which ==  13) {
        // ... do stuff ...
        e.preventDefault();
    }
});

You should be doing this in both functions. I'm not sure why the first one doesn't refresh the page; I'm guessing you have a submit button in one form and not the other?


Q:

Blue Input Screen (Shell Script)

In Ubuntu Server 10.04
Sometimes when i'm installing some packages through apt-get, it prompts me with a blue dialog and asks for input/selection.. E.G: when installing mysql-server, it prompts me for a root password..
How can i accomplish this in my own shell script, so that same blue dialog will show up when i need to ask yes/no and password questions?

A:

Check tutorials for dialog here and here.