text:
Q: JavaEE CDI Injection - Cannot inject HttpServletRequest / Response I have a web application that reads a query parameter. It uses the parameter to get some data from an outside-app-source. The web application is a simple Servlet:
@WebServlet(name = "SomethingServlet", urlPatterns = {"/"}, loadOnStartup = 0)
public class SomethingServlet extends HttpServlet {

    @Inject
    InterfaceOfDesire objectOfDesire;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        objectOfDesire.doSomething();
    }
}

InterfaceOfDesire is an Interface which is (atm) implemented once. So there should be no ambiguities.
public interface InterfaceOfDesire {
    void doSomething();
}

public class ClassOfDesire implements InterfaceOfDesire {
    @Override
    public void doSomething() {
        // do something very cool
    }
}

And last, but not least there is a resolver which resolves the kind of implemented class (atm only 1)
public class SomethingResolver {
    @Inject
    private HttpServletRequest request;
    @Inject
    private HttpServletResponse response;

    @Inject
    public SomethingResolver(ServletContext servletContext) {
        // do something with the servlet context
    }

    @Produces
    public InterfaceOfDesire getInstance() {
        // do something with request and response
        // afterwards return object
        return new ClassOfDesire();
    }
}

Now I get the error
WELD-001408: Unsatisfied dependencies for type HttpServletResponse with qualifiers @Default

What am I doing wrong?

A: I would say the bean (SomethingResolver) needs to be somehow bound to the HTTP request or to its session. Only then it can get access to HttpServletRequest (or response).
Try annotating it with either @RequestScoped. @SessionScoped might work as well.
The reason behind this is that the way you have it now, the bean lifecycle is not bound to the request - it can be even longer than the request. CDI has no way of telling which servlet request should then be injected into it.


text:
Q: Query Performance: Aggregate before with derived tables or after when joining a lot of tables? I'm hoping the answer to this question isn't "depends".
I have to write a report that is a summary of class data.  Each class contains aggregated student data, such as grade, attendance, etc.  Some of this data, like grade is aggregate data of all graded assignments.
The query works, but I realize I have written an unmaintainable monster joining together about 15 tables.  If I rewrote the query using derived tables would I help or hurt performance?

A: As far as performance you could get improvements by adding indexes. Joins will be super fast.
As far as maintainability (and readability) derived tables could help. Also, you could create views in order to separate the logic.
Furthermore, you could consider creating tables with aggregate data and then just run a simple select * from summary

A: Actually ended up being a performance boost to use derived tables.  I realize I had a fairly poor question.  Let me give a small snippet...
Aggregate after JOINs.  Cost .937
DECLARE @0 INT = 141;

SELECT u.id, u.first_name, u.last_name,
    CAST(CAST(COUNT(haid.mastered_date) AS DECIMAL) / CAST(COUNT(sa.id) AS DECIMAL) * 100 AS DECIMAL(4, 1)) AS mastery_perc
FROM reporting_saved_reports r
JOIN reporting_saved_reports_sections sr ON sr.report_id = r.id
JOIN ums_ae_instructor_section_order_user isou ON isou.instructor_section_id = sr.section_id
JOIN ums_users u ON u.id = isou.user_id
JOIN reporting_states sa ON sa.tutor_id = r.Tutor_Id
    AND sa.business_type IN ('B', r.business_type)
    AND sa.haid = 'Y'
LEFT JOIN reporting_wrapup_haid haid ON haid.tutor_id = r.Tutor_Id
    AND haid.section_id = isou.instructor_section_id
    AND haid.user_id = isou.user_id
    AND haid.state_id = sa.id
    AND haid.mastered_date BETWEEN r.from_date AND r.to_date
WHERE r.id = @0
GROUP BY u.id, u.first_name, u.last_name
ORDER BY u.last_name, u.first_name
;

Aggregate before with derived table, then join.  Cost .546
DECLARE @0 INT = 141;

WITH wr AS (
    SELECT r.id AS report_id, r.Tutor_Id, r.from_date, r.to_date, r.business_type, sr.section_id, isou.user_id
    FROM reporting_saved_reports r
    JOIN reporting_saved_reports_sections sr ON sr.report_id = r.id
    JOIN ums_ae_instructor_section_order_user isou ON isou.instructor_section_id = sr.section_id
    WHERE r.id = @0
)
SELECT dual.user_id, dual.first_name, dual.last_name,
    CAST(CAST(haid.mastered_count AS DECIMAL) / CAST(dual.state_count AS DECIMAL) * 100 AS DECIMAL(4, 1)) AS mastery_perc
FROM (
    SELECT wr.user_id, u.first_name, u.last_name, COUNT(sa.id) AS state_count
    FROM ums_users u
    JOIN wr ON wr.user_id = u.id
    JOIN reporting_states sa ON sa.tutor_id = wr.Tutor_Id
        AND sa.business_type IN ('B', wr.business_type)
        AND sa.haid = 'Y'
    GROUP BY wr.user_id, u.first_name, u.last_name
) dual
LEFT JOIN (
    SELECT haid.user_id, COUNT(haid.mastered_date) AS mastered_count
    FROM reporting_wrapup_haid haid
    JOIN wr ON wr.Tutor_Id = haid.tutor_id
        AND wr.section_id = haid.section_id
        AND wr.user_id = haid.user_id
        AND haid.mastered_date <= wr.to_date
    GROUP BY haid.user_id
) haid ON haid.user_id = dual.user_id
ORDER BY dual.last_name, dual.first_name
;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can i iterate over a database to produce views from many tables at once? I have a PostGIS database with several tables with foreign key related to one table that holds the primary key. I have to apply certain select ..to each one of these tables, can I loop over the primary key table to get it done?
Can this be done without even use the primary-foreign key relation?
I can't find any information on iterating inside a database, any help would be much appreciated.

A: The most performant way to execute a query across multiple tables in Postgres is to use join statements. https://www.postgresql.org/docs/current/tutorial-join.html
Executing multiple queries, one for each table, and then, within your application logic, aggregating the results and then iterating over the aggregation to implement, for example, a SELECT or ORDER BY statement will always be less efficient than using a single query.
Setting indexes on the foreign keys of the tables you are joining will greatly improve the performance of the query. You can also improve query performance by scaling up the CPU and RAM over your server or by using something like Citus to horizontally scale your database across multiple servers.


text:
Q: Construction of the simply connected Lie group of a given Lie algebra Given a finite dimensional real Lie algebra $\mathfrak{g}$, I am trying to obtain a concrete realization of its simply connected Lie group $G$, with $\mathrm{Lie}(G) \cong \mathfrak{g}$.
Let us assume that $\mathfrak{g} = \mathfrak{g}_1 \oplus \mathfrak{g}_2$, where $\mathfrak{g}_1$ and $\mathfrak{g}_2$ are given by $\mathbb{R}^p$ and $\mathbb{R}^q$ respectively with certain commutator relations. I know in general how to obtain its simply connected Lie group $G$.

*

*By a corollary to Ado's Theorem one can conclude that
 $$\mathfrak{g} \cong \mathfrak{g}_0 \subseteq \mathfrak{gl}(n,\mathbb{R})$$

*One can find a connected Lie subgroup $G_0 \subseteq \mathrm{GL}(n,\mathbb{R})$ that has $\mathfrak{g}_0$ as its Lie algebra

*The universal covering group of $G_0$, denoted by $G$, gives $\mathrm{Lie}(G) \cong \mathrm{Lie}(G_0) \cong \mathfrak{g}_0 \cong \mathfrak{g}$.
I would appreciate if anyone could provide me with an example by using this method, especially since all points include rather abstract realization of the regarding spaces (item 1 needs the universal enveloping algebra of a given Lie algebra, in item 3 one has to construct the simply connected covering group).
How is this procedure achieved in practice? Does one guess the right simply connected Lie group or does one apply the described procedure. If yes, where can I see in detail how this method works, for a rather a simple example. Some sort of enlightenment would definitely help. Many thanks in advance

A: The Lie functor from Lie groups to Lie algebras can be inverted on the subcategory of simply connected Lie groups. The essential surjectivity of the functor is called the third fundamental theorem of Lie, namely, every Lie algebra of finite dimension over the real or complex numbers is isomorphic to the Lie algebra of a Lie group. There are at least two ways to prove this. We could use either Ado's theorem, or the Levi-Malcev decomposition $\mathfrak{g}=\mathfrak{s}\oplus \mathfrak{m}$, the semiidrect sum decomposition into a solvable ideal $\mathfrak{m}$ and a semisimple subalgebra $\mathfrak{s}$.
How are the steps 1.,2., 3. in practise ?
If the Lie algebra has trivial center, then the adjoint representation is faithful, and we do not need Ado's theorem anymore. This fact, and other refinements of Ado's proof help to find a faithful linear representation. If the Lie algebra is nilpotent, then the adjoint representation is never faithful, so that we have to do more. This is often not difficult, and well known, e.g., for the Heisenberg Lie algebras of dimension $2n+1$ etc.


text:
Q: UnicodeDecodeError when sending the result of a function in CherryPy Hı All,
I want to send a string variable to web app. Normally, I can send a string without any problem when I create it manually inside the 'switch' part of the code. But when I obtain that string from a function, I get an error. I mean, if counterstring='12.3' , there is no problem. But if counterstring=ReadCounter(), there is a problem.
Here is the actual part of code:
import cherrypy
import webbrowser
import os
import json
import sys

MEDIA_DIR = os.path.join(os.path.abspath("."), u"media")

class AjaxApp(object):
    @cherrypy.expose
    def index(self):
        return open(os.path.join(MEDIA_DIR, u'index.html'))

    @cherrypy.expose
    def switch(self):
        counterstring=ReadCounter()
        return counterstring

config = {'/media':
                {'tools.staticdir.on': True,
                 'tools.staticdir.dir': MEDIA_DIR,
                }
        }

def open_page():
    webbrowser.open("http://127.0.0.1:8080/")
    cherrypy.engine.subscribe('start', open_page)
    cherrypy.tree.mount(AjaxApp(), '/', config=config)
    cherrypy.engine.start()

and the error is :
    ERROR:cherrypy.error.55086800:[27/Jan/2015:02:47:09]  Traceback (most recent call last):
      File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 589, in run
        self.respond(pi)
      File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 690, in respond
        self.handle_error()
      File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 767, in handle_error
        self.error_response()
      File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 401, in set_response
        message=self._message)
      File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 407, in get_error_page
        return get_error_page(*args, **kwargs)
      File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 535, in get_error_page
        return result.encode('utf-8')
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 2271: ordinal not in range(128)

ERROR:cherrypy.error.42068624:[29/Jan/2015:09:14:46]  Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 589, in run
    self.respond(pi)
  File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 690, in respond
    self.handle_error()
  File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 767, in handle_error
    self.error_response()
  File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 402, in set_response
    message=self._message)
  File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 408, in get_error_page
    return get_error_page(*args, **kwargs)
  File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 536, in get_error_page
    return result.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 2294: ordinal not in range(128)

I tried many things about encoding/decoding. I added  encode/decode functions to strings in app
I have # -- coding: utf-8 --
at the top of my code.
Could you please tell about your suggestions to solve this out?
Thanks in advance.

A: It's not the problem of your code, as you can see the stack trace ends in get_error_page. It's CherryPy bug (or Python traceback.format_exc()'s bug as it produces quite a mess), I also met some ago. I've filed bug report, #1356, to CherryPy.
So if you can just avoid unicode exception messages. Other the workaround is to set custom error page handler:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cherrypy

def errorPage(**kwargs):
  temaplte = cherrypy._cperror._HTTPErrorTemplate
  return temaplte % kwargs

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8,
    # here's the workaround
    'error_page.default' : errorPage
  }
}

class App:

  @cherrypy.expose
  def index(self):
    return '''
      errorPageStr

      errorPageUnicode
    '''

  @cherrypy.expose
  def errorPageStr(self):
    raise RuntimeError('Şansal Birbaş')

  @cherrypy.expose
  def errorPageUnicode(self):
    raise RuntimeError(u'Şansal Birbaş')

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

EDIT: To make it easier to understand the answer. Your code, somewhere likely out of the snippet in question, raises an exception with unicode message. CherryPy tries to generate error page for your exception and fails because stack trace in such a case is messy. It doesn't matter whether exception message is UTF-8 bytes or unicode. The code above is just a distilled version.
You need to set custom error handler in your code so you can see your original exception.


text:
Q: Using variable for tag name in Ansible AWS modules ec2_snapshot module allows me to create snapshots of volumes and tag at the same time. This is straight forward while using fix names for tags. But how can I set tag name itself from a variable?
Example task:
- name: AWS EBS Disks Snapshot For Volumes
  ec2_snapshot:
    aws_access_key: "{{ aws_access_key_id }}"
    aws_secret_key: "{{ aws_secret_key_id }}"
    security_token: "{{ aws_security_token }}"
    volume_id: "{{ item.id }}"
    region:  "{{ aws_region }}"
    snapshot_tags:
      Name: "{{ timestamp.stdout }}"
      "{{ tagname_variable }}": "{{ tagvalue_variable }}"
      type: "{{ item.type }}"
    description: "{{ timestamp.stdout }}_snapshot"
  with_items:
    - "{{ volumeinputs }}"

The tagname_variable is literally created as a tag name, not the value of the variable.
How I can make this work?

A: You will need to dynamically create that part of you dictionary, for example, with a combine, as YAML dictionaries key are usually not templated by Ansible.
This can be done in a vars sections of the task itself:
- name: AWS EBS Disks Snapshot For Volumes
  ec2_snapshot:
    aws_access_key: "{{ aws_access_key_id }}"
    aws_secret_key: "{{ aws_secret_key_id }}"
    security_token: "{{ aws_security_token }}"
    volume_id: "{{ item.id }}"
    region:  "{{ aws_region }}"
    snapshot_tags: "{{ _snapshot_tags }}"
    description: "{{ timestamp.stdout }}_snapshot"
  loop: "{{ volumeinputs }}"
  vars:
    _snapshot_tags_static:
      Name: "{{ timestamp.stdout }}"
      type: "{{ item.type }}"
    _snapshot_tags: >-
      {{
        _snapshot_tags_static
        | combine({tagname_variable: tagvalue_variable})
      }}


text:
Q: Can someone explain to me why my HTML/CSS is not correct but very close ? The Odin Project Flexbox Layout 02

type herehtml, body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  margin: 0;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  height: 72px;
  display: flex;
  padding: 0 16px;
  background: darkmagenta;
  color: white;
  font-size: 32px;
  font-weight: 900;
  align-items: center
  ;
}

.footer {
  height: 72px;
  background: #eee;
  color: darkmagenta;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sidebar {
  width: 300px;
  list-style: none;
  padding: 16px;
  font-size: 24px;
  color:antiquewhite
  display: flex;
  background: royalblue;
  display: flex;
  height: 100vh;
  width: 400px
  flex-shrink: 0;
  padding: 16px;

}

.card {
  border: 1px solid #eee;
  box-shadow: 2px 4px 16px rgba(0,0,0,.06);
  border-radius: 4px;
  padding: 32px;
  margin: 16px;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  align-items: center;
  padding: 16px;
  gap: 16px;
  overflow: hidden;
  height: max-content;
  width:300px
}
.container {
  display: flex;
  gap: 16px;
  padding: 32px;
  display: flex;
  flex-wrap: wrap

width: fit-content;
  justify-content: center;
  align-content: center;

}
.big {
  display: flex;
  flex: 1
}

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

.card{
  height: 300px;
  width:auto;

}
.big {
  display: flex;
  flex-direction: row;
}

ul{
  list-style: none;
}

      MY AWESOME WEBSITE

⭐ - link one

♂ - link two

 - link three

 - link four

Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempora, eveniet? Dolorem dignissimos maiores non delectus possimus dolor nulla repudiandae vitae provident quae, obcaecati ipsam unde impedit corrupti veritatis minima porro?

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quasi quaerat qui iure ipsam maiores velit tempora, deleniti nesciunt fuga suscipit alias vero rem, corporis officia totam saepe excepturi odit ea.

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis illo ex quas, commodi eligendi aliquam ut, dolor, atque aliquid iure nulla. Laudantium optio accusantium quaerat fugiat, natus officia esse autem?

Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus nihil impedit eius amet adipisci dolorum vel nostrum sit excepturi corporis tenetur cum, dolore incidunt blanditiis. Unde earum minima laboriosam eos!

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis illo ex quas, commodi eligendi aliquam ut, dolor, atque aliquid iure nulla. Laudantium optio accusantium quaerat fugiat, natus officia esse autem?

Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus nihil impedit eius amet adipisci dolorum vel nostrum sit excepturi corporis tenetur cum, dolore incidunt blanditiis. Unde earum minima laboriosam eos!

      The Odin Project ❤

I got it to look very close but there are a lot of little things that look off. The sidebar text is too tight and my cards are too tall and not laid out properly.
I was instructed to use flex-wrap for the cards but that changes nothing, I struggled enough just to get the 'Holy Grail Layout' itself.
I've looked at the available solution and it is not described.

A: You left only Semicolon in css I have commented Where you left semicolon.
This is your solved code.

        MY AWESOME WEBSITE

⭐ - link one

♂ - link two

 - link three

 - link four

Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempora, eveniet? Dolorem dignissimos maiores non delectus possimus dolor nulla repudiandae vitae provident quae, obcaecati ipsam unde impedit corrupti veritatis minima porro?

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quasi quaerat qui iure ipsam maiores velit tempora, deleniti nesciunt fuga suscipit alias vero rem, corporis officia totam saepe excepturi odit ea.

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis illo ex quas, commodi eligendi aliquam ut, dolor, atque aliquid iure nulla. Laudantium optio accusantium quaerat fugiat, natus officia esse autem?

Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus nihil impedit eius amet adipisci dolorum vel nostrum sit excepturi corporis tenetur cum, dolore incidunt blanditiis. Unde earum minima laboriosam eos!

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis illo ex quas, commodi eligendi aliquam ut, dolor, atque aliquid iure nulla. Laudantium optio accusantium quaerat fugiat, natus officia esse autem?

Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus nihil impedit eius amet adipisci dolorum vel nostrum sit excepturi corporis tenetur cum, dolore incidunt blanditiis. Unde earum minima laboriosam eos!

        The Odin Project ❤


text:
Q: Multiple step registration process in a single activity with fragments I'am trying to create a multiple-step registration activity that handles several fragments. Each fragments is a step in the process and the final fragment should send the registration information collected in all fragments to a server and get a response. My problem is thinking how should I handle the information across fragments so that if the user goes back one step he will not loose the previously typed information. And also how should I handle these Fragment transactions. I was thinking in storing all the data in the activity and retrieve it each time the user goes back one step and then retrieve it in the final fragment to send the information but I don't think this is the best approach. Is there any way to do this cleanly?

A: Since fragments run on top of activities, I think the way to do this cleanly would be to have your fragments communicate back to the activity.
Basically the approach you are thinking about is correct.


text:
Q: How can I include a loess regression plot in a bland altman plot in RStudio? I've recently computed a Bland-Altman_Plot in RStudio using this code:
    fspiddet <- fscores(fitDetachment)
    fsskiddet <-fscores(fit.SKIDDETdisc)
    #new data.frame with fscores, average fscores and differences
    BAPlotDET <- data.frame(fsskiddet, subset(fspiddet,,1))
    BAPlotDET$avg <- rowMeans(BAPlotDET)
    BAPlotDET$diff <- BAPlotDET$F1 - BAPlotDET$G
    colnames(BAPlotDET) = c("fsskiddet", "fspiddet", "avg", "diff")

     #Bland-Altman-Plot
    bland.altman.plot(BAPlotDET$fsskiddet, BAPlotDET$fspiddet, graph.sys =
    "ggplot2",geom_count=TRUE)

     Then, I wanted to include a loess regression in there like this:

    loess50 <- loess(formula=diff ~ avg, data=BAPlotDET, span=.5, degree=0, model =
    TRUE)
    smooth50 <- predict(loess50)
    plot(BAPlotDET$avg, BAPlotDET$diff, pch=1, main='Loess Regression Models')
    lines(smooth50, x=BAPlotDET$avg, col='red')

which looks extremely weird... like this:
enter image description here
why does the loess regression look so bad? I've tried chaniging the smoothing parameter "span". The  more I smooth it, the more does the regression plot turn into an parallel graph to the x axis, at y = 0 which would predict a difference (y) of 0 for every x


text:
Q: How to connect to wireless network at boot automatically? Is there a package or a simple tutorial how to setup a normal 12.04 (not server) with wireless connection on by default?
Basically I'd like to be able to have my PC connected to the network before I login, so I can do ssh and run programs remotely even.
I've looked around but haven't spot any good tutorial yet. Could you point me to one?
Cheers!

A: This is how I've done it easily, click on the network indicator, then head down to "Edit connections", then go to the wireless tab and find your network and hit edit:

Then I check "Available to all users", which makes the connection systemwide. I always have enabled this to make the system connect to the wireless while it's booting, but should work fine for your needs.


text:
Q: ProgressBar causing constant onDraw calls for all the UI I have an activity which has a ProgressBar. This bar is used to show the elapsed time on the game level.
I'm updating this bar and a TextView with a CountdownTimer, called every 100ms. The problem is that every time I call setProgress, it seems to be causing an invalidate() that makes my whole UI to be redrawn. If I delete the line where the ProgressBar get updated everything works fine, even setText for the TextView that show the time left.
This is a problem for me because I also have a custom view which needs to be redrawn only when I need it, or at least a few times but not constantly because it'll affect performance.
This is a piece of my code:
private CountDownTimer timer;
private long ttime;
private long ctime;

private ProgressBar bar;
private TextView clock;

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    startTimer(500);
    ...
}

@Override
protected void onResume() {
    super.onResume();
    if(!checkFlags()){
        startTimer(500);
    }
}

@Override
protected void onPause() {
    super.onPause();
    if(!checkFlags()){
        timer.cancel();
    }
}

private void startTimer(long delay){
    timer = new CountDownTimer(ctime,100){
        public void onTick(long millisUntilFinished){
            ctime = millisUntilFinished;
            clock.setText(formatTime(millisUntilFinished));
            bar.setProgress((int) (1000 - ((ctime * 1000)/ttime)));
        }

        public void onFinish(){
            clock.setText("00:00");
            gameOver(false);
        }
    };

    if(delay > 0){
        Handler handler = new Handler();
        handler.postDelayed(new Runnable(){
            public void run(){
                timer.start();
            }
        },delay);
    }else{
        timer.start();
    }
}

How could I prevent the ProgressBar to cause this onDraw calls for every element of the UI?

A: According to 'sources/android-18/android/widget/ProgressBar.java' in Android SDK the call of setProgress() will result in the call of invalidate().
private synchronized void doRefreshProgress(int id, int progress, boolean fromUser,
        boolean callBackToApp) {
    float scale = mMax > 0 ? (float) progress / (float) mMax : 0;
    final Drawable d = mCurrentDrawable;
    if (d != null) {
        Drawable progressDrawable = null;

        if (d instanceof LayerDrawable) {
            progressDrawable = ((LayerDrawable) d).findDrawableByLayerId(id);
            if (progressDrawable != null && canResolveLayoutDirection()) {
                progressDrawable.setLayoutDirection(getLayoutDirection());
            }
        }

        final int level = (int) (scale * MAX_LEVEL);
        (progressDrawable != null ? progressDrawable : d).setLevel(level);
    } else {
>>>     invalidate();
    }

    if (callBackToApp && id == R.id.progress) {
        onProgressRefresh(scale, fromUser);
    }
}

Try to use setProgressDrawable(). It seems that invalidate() is not called in that case.


text:
Q: SSLError: sslv3 alert handshake failure I'm making the following call to branch.io
import requests
req = requests.get('https://bnc.lt/m/H3XKyKB3Tq', verify=False)

It works fine in my local machine but fails in the server.
SSLError: [Errno 1] _ssl.c:504: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure

Openssl versions:
local: OpenSSL 0.9.8zg 14 July 2015
server: OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008
Python:
local: 2.7.10
server: 2.7.6
Branch io server connection:
Chrome verified that DigiCert SHA2 Secure Server CA issued this website's certificate. The server did not supply any Certificate Transparency information.
I tried urllib2, but the result was same. Any help?

A: Jyo de Lys has identified the problem. The problem is described here and the solution is here. I did the following to get this working:

*

*easy_install pyOpenSSL

*easy_install ndg-httpsclient

*easy_install pyasn1

If you're getting this error while using urllib2, you'll need to upgrade to python 2.7.9 or later too.


text:
Q: Filter by nested subdocument value with mongoose How can I filter by a nested subdocument value ?
I need to filter the playlist by the owner id.
var playlistSchema = new Schema();
playlistSchema.add({
    name: String,
    owner: {
        id: String,
        email: String,
        name: String
    }
});

A: You can use sort() method for filter by ascending order and descending order.
Ascending order use follow method.
playlist.find().sort('owner.id': 1);

Descending order use follow method.
playlist.find().sort('owner.id': -1);

A: Assume a collection sales has the following documents:
{
   _id: 0,
   items: [
     { item_id: 43, quantity: 2, price: 10 },
     { item_id: 2, quantity: 1, price: 240 }
   ]
}
{
   _id: 1,
   items: [
     { item_id: 23, quantity: 3, price: 110 },
     { item_id: 103, quantity: 4, price: 5 },
     { item_id: 38, quantity: 1, price: 300 }
   ]
}
{
    _id: 2,
    items: [
       { item_id: 4, quantity: 1, price: 23 }
    ]
}

The following example filters the items array to only include documents that have a price greater than or equal to 100:
db.sales.aggregate([
   {
      $project: {
         items: {
            $filter: {
               input: "$items",
               as: "item",
               cond: { $gte: [ "$$item.price", 100 ] }
            }
         }
      }
   }
])


text:
Q: javascript memory leaks and profilling? I am novice to javascript development. I built a huge javascript application. Testing the application I used chrome dev tools and I dont know about profiling. I took a heap snapshot and I got 32mb on snapshot.
what is it(32mb) and How to know memory leaks in javascript?
How to use profiling to measure my application?

A: You can just press F12, you will get profiles option there. If you want to check the time required to complete the button click operation, just select Collect Javascript CPU Profiles and say start. Then click on required button and then stop. You will get the detailed analysis of the click there. You can later check where you can reduce the total time taken for the operation. i.e., optimize it. You can also use developer tool in IE for the same purpose.  For optimization you can avoid unnecessary looping, store elements in variable and then use those which are required frequently in your code. etc. You can also view the errors at the right bottom corner in chrome if any and can resolve those for optimization.  Profiles will give you the time taken by the parent function and the other functions which are called inside the parent function individually which helps to optimize each function independently. When you start and stop the profiler for any operation like click of button, you will get the total time in seconds or milliseconds for that operation in Chrome profiles. If time is more that user acceptance time for that operation, you can modify/optimize your javascript code. If any operation is taking more than user acceptance time, that means your site is not having good performance and it needs optimization. The user acceptance time totally depends on the type of operation

A: DevTools is able to show you the objects that look like a leak.
The simplest and useful technique described here
With help of it people form gmail team managed to fix the leaks in gmail page.


text:
Q: Android: SimpleDateFormat ParseException in Arabic I am parsing the date string but getting the parse exception in Arabic mode but works fine when the language in the app is set to English.
ParseException
06-15 19:16:07.607: W/System.err(27340): java.text.ParseException: Unparseable date: "6-15-2014" (at offset 2)
06-15 19:16:07.617: W/System.err(27340):    at java.text.DateFormat.parse(DateFormat.java:626)

But this is parsing fine in English.
Code
SimpleDateFormat format = new SimpleDateFormat(formatString);
        Date date = null;
        try {
            date = new SimpleDateFormat("MM-dd-yyyy").parse(detail.getContactBDate());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Can anyone please point out that what is missing? or in other languages what I can do to prevent these types of strings?
Thanks in advance

A: I am able to resolve the issue by setting the Locale.English as the default locale for date parsing after reading the Stackoverflow thread "Unparseable date" using SimpleDateFormatter with API code example.
Thanks,

A: Are you sure "detail.getContactBDate()" would return the exact string '6-15-2014'?
I believe ,it has no relationship with your language setting. Because Java can handle internationalization very well.
Print out the string and recheck your argument.


text:
Q: mysql alphabetical order applied to a string Is it a way in mysql to alphabetically ordering a string ?
I am looking for a function who does that :
select alphabeticallyorder('cba')

will return me
'abc'

A: A query like this should return the values that you need. I know it's not a nice query, and you also need a numbers table, filled with numbers:
SELECT col, GROUP_CONCAT(SUBSTRING(col, n, 1)
                         ORDER BY SUBSTRING(col, n, 1)
                         SEPARATOR '') AS ordered_col
FROM
  tablename INNER JOIN numbers
  ON LENGTH(tablename.col)>=numbers.n
GROUP BY
  id, col

Also it will work only if LENGTH(col)=CHAR_LENGTH(col). Please see fiddle here.

A: Please see the REVERSE function.
http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_reverse
mysql> SELECT REVERSE('abc');
    -> 'cba'


text:
Q: Is there anyway to store key, value, value into map After reading through most of the maps questions, I eventually got an idea from this link: How to unique my data that are stored in an object which are stored in a vector?
I have a task of storing X, Y, Z coordinates from the user input. To prevent the user from entering duplicated data, I have decided to use map containers as they do not allow duplicated data.
I tested the code out.
I am using X as the key and Y as the value
I am able to store X and Y via this:
map<int, int> mapp2d;
mapp2d.insert(pair<int, int>(X, Y));

And to access them via this:
map<int, int>::iterator p = mapp2d.begin();
map<int, int>::iterator e = mapp2d.end();
while ( p != mapp2d.end())
{
    cout << "X: " << p->first << " Y: " << p->second << endl;
    p++;
}

Is it possible to do it for X, Y, Z ? Like this:
map<int, int, int> mapp3d
mapp3d.insert(pair<int, int, int>(X, Y, Z))

I tested out the code but i got this errors:
error: wrong number of template arguments (3, should be 2)
error: provided for 'template<class _T1, class _T2> struct std::pair

Yes, i do know it is illegal for me to do that, but there're no tutorials on how should i do so, and i kind of ran out of ideas, and how can i access them ?
Appreciate you guys for taking a look, thanks in advance.

A: You should store the coordinates together instead of using one coordinate as key:
struct Point
{
    int x, y, z;

    Point(int x, int y, int z) : x(x), y(y), z(z) {}
};

Then just implement a custom comparator:
struct PointComparator
{
    bool operator()(const Point& a, const Point& b)
    {
        if (a.x < b.x) return true;
        if (a.x == b.x && a.y < b.y) return true;
        if (a.x == b.x && a.y == b.y && a.z < b.z) return true;
        return false;
    }
};

And finally, use a set instead of a map (because in your case, values and keys are the same):
#include <set>
std::set<Point, PointComparator> points;

Sets are (just like maps) ordered, by default from low to high values. You need to specify a custom comparator here because the default one that is used if you just do std::set<Point> is std::less. This comparator can compare numbers etc, but has no clue how to compare objects of type Point. The set could therefore not order its elements properly and also not figure out if two elements are identical (which is what you are after). If you do std::set<Point, PointComparator>, you create a set that uses the logic in PointComparator to compare its elements.
This example will print "1" and "2":
points.insert(Point(1, 2, 3));
points.insert(Point(1, 2, 3));
points.insert(Point(2, 3, 4));

std::set<Point, PointComparator>::iterator it = points.begin();
while (it != points.end()) {
    std::cout << "x = " << it->x << std::endl;
    it++;
}

A: Have you considered using a tuple? They can be used for holding more than 2 elements
http://www.cplusplus.com/reference/tuple/tuple/
I guess another possibility if you really have your heart set on using a map is doing something like the below link where your map's values are :
Using find on map<pair, int>

A: I'm not a C++ expert, but I think you should use a set rather than a map, and use a tuple for the values. Sets are normally used for holding unique values (although I'm speaking from Java and Python knowledge rather than C++). Look at set and unordered_set; apparently unordered_set is faster, but set is sorted. Neither of them keep track of the order you put things in, and neither does map, so if you need that then you'll need to find a different solution. And I think tuples can store arbitrary numbers of elements.

A: It's often useful to distinguish between how you store data and how you access it.
For example, you can store the points in a vector, but place a 'uniqueness index' upon them by using, say, a std::set. Here's some standalone code demonstrating the idea:
#include <functional>
#include <iostream>
#include <memory>
#include <set>
#include <vector>

class Point {
 public:
  Point(int x, int y, int z) : m_x(x), m_y(y), m_z(z) {}

  int x() const { return m_x; }
  int y() const { return m_y; }
  int z() const { return m_z; }

 private:
  int m_x;
  int m_y;
  int m_z;
};

bool operator<(const Point & a, const Point & b) {
  return (a.x() < b.x()
          || (a.x() == b.x()
              && (a.y() < b.y()
                  || (a.y() == b.y()
                      && a.z() < b.z()))));
}

class Points {
 public:
  Points() {}

  bool add(Point p) {
    if (m_uniqueIndex.count(p) == 0) {
      m_points.emplace_back(new Point(p));
      m_uniqueIndex.emplace(*m_points.back());
      return true;
    }
    return false;
  }

 private:
  std::set<std::reference_wrapper<Point>> m_uniqueIndex;
  std::vector<std::unique_ptr<Point>> m_points;
};

const char * s(bool b) {
  return b ? "true" : "false";
}

int main(int argc, char * argv[]) {
  Point a(1, 2, 3);
  Point b(2, 1, 0);
  Point c(-1, 0, 1);
  Point a2(1, 2, 3);

  Points points;

  std::cout << "Adding a: " << s(points.add(a)) << std::endl;
  std::cout << "Adding b: " << s(points.add(b)) << std::endl;
  std::cout << "Adding c: " << s(points.add(c)) << std::endl;
  std::cout << "Adding a2: " << s(points.add(a2)) << std::endl;
}

In my experience, when using spatial data, you always end up wanting to ask questions like: what are this coodinates neighbours? How many things are within some distance of this coordinate, etc. So I'd also recommend that you do some reading-up on k-d trees (for points) and r trees (for shapes).


text:
Q: Zend Fetch on large table 10,000 + rows, ~100 columns I have an sql view which returns over 10,000 records with about 120 columns (ridiculous, I know).
The view data is gathered from the database in PHP using a Zend_Db_Table_Abstract object. We have a report controller which does a fetchAll (which obviously creates a massive array) and stores the array in a view object. Next we have a view script which iterates over the array and echoes a json formatted array.
This is slowwww. Like over 1 minute to render this report, what can I do to speed this up?
Bare in mind I am very new to this project and have no knowledge of Zend and little of PHP. Also I can't give away to much due to data protection etc.
If you could ask what you need to help you gather the picture that would be great. But basically this is what the script does:
Report controller:
Setup some basic json report data (for data tables)
$this->view->report_data = fetchALL($oSelect);

View script:
Output the basic json stuff, then:
"report_data": [
<?php
    for($i = 0; $i < count($this->report_data); $i++){
        echo "[";
        foreach($this->columns as $k=>$col){
            echo '"'. $this->escape($this->report_data[$i][$col]) .'"';
            if($k < count($this->columns) -1 ){
                echo ',';
            }
        }
        echo "]";
        if($i < count($this->report_data) -1){
            echo ",";
        }
        echo"\n";
    }
?> ]

So after doing some research I gathered that I could use fetch() instead of fetchAll() so to get 1 row at a time, to avoid the massive array. However I tried to use the fetch() and got this error:
Call to undefined method Zend_Db_Table_Abstract::fetch()
So now I'm bummed.
My idea was to get each row and output each row Json formatted, however I don't really know how I would do this in the report controller/ view scenario. Would I have to just get rid of the view script and just use the controller to output the data?
Anyway why does fetch() not work, I can't actually see it in the docs either, well there is some array function _fetch()
Any help would be appreciated, any if you need more info just ask.
Thanks

A: See the docs for fetch().
The following is not very elegant, but could help you:
Model:
...
function getResults()
{
    return $db->query('SELECT * FROM bugs');
}
...

Controller:
...
$this->view->report_data = $model->getResults();
...

View:
...
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
    echo Zend_Json::encode($row);
}
...

I haven't tested the code, but you should get the idea.

A: You have to improvise use of framework here to gain that extra bit of performance
In controller
$this->view->result = mysql_query($sql);

In view
while ($row = mysql_fetch_assoc($this->result)) {
 echo json_encode($row);
}

Note to setup mysql procedure interface read
http://php.net/manual/en/function.mysql-fetch-assoc.php

A: As you have realised from the error message Zend_Db_Table_Abstract does not have a fetch() method. It does, however, have a fetchRow() method that has this signature:-
/**
 * Fetches one row in an object of type Zend_Db_Table_Row_Abstract,
 * or returns null if no row matches the specified criteria.
 *
 * @param string|array|Zend_Db_Table_Select $where  OPTIONAL An SQL WHERE clause or Zend_Db_Table_Select object.
 * @param string|array                      $order  OPTIONAL An SQL ORDER clause.
 * @param int                               $offset OPTIONAL An SQL OFFSET value.
 * @return Zend_Db_Table_Row_Abstract|null The row results per the
 *     Zend_Db_Adapter fetch mode, or null if no row found.
 */
public function fetchRow($where = null, $order = null, $offset = null)

So replacing fetch() with fetchRow() and looping while !null === fetchRow() should work for you.
It is always worth delving into the code of Zend Framework to see what is on offer.
Zend Paginator may also be an option for you as it just fetches the records required to render the page.


text:
Q: DAO Data bind Refresh() call - Run-time error 3061, 3075 I use a DAO Data component to data bind control elements on a form. The query I create dynamically in a recordset which I bind to the Data component. This works pretty well. However, when I run Data.Refresh and the SQL Where statement contains references to the same table via different aliasses then an error shown.
Note: the sql queries below run fine in the MS Access query designer
Global gDB As DataBase

Set Data1.Recordset = GetData(select, from, where, order)
Data1.Refresh

Public Function GetData(select As String, from As String, where As String, order As String) As Recordset
  Dim sql As String
  sql = "SELECT " & select & " FROM " & from & " WHERE " & where & " ORDER BY " & order
  Set GetData = gDB.OpenRecordset(sql, dbOpenDynaset)
End Function

The following will work:
SELECT
  WIZ_APPL.*,
  TRANS_PRI.Text AS LocalizedText
FROM
  TRANSLATIONS AS TRANS_PRI,
  WIZ
WHERE
  TRANS_PRI.Tag="prog" & WIZ_APPL.Id AND
  TRANS_PRI.LanguageId=1 AND
  WIZ_APPL.Enabled <> 0
ORDER BY
  WIZ_APPL.Id;

Until I try this:
SELECT
  WIZ_APPL.*,
  TRANS_PRI.Text AS LocalizedText,
  TRANS_ALT.Text As AlternativeText
FROM
  TRANSLATIONS AS TRANS_PRI,
  TRANSLATIONS AS TRANS_ALT,
  WIZ_APPL
WHERE
  TRANS_PRI.tag="prog" & WIZ_APPL.Id AND
  TRANS_ALT.tag="prog" & WIZ_APPL.Id AND
  TRANS_PRI.LanguageId=1 AND
  TRANS_ALT.LanguageId=2 AND
  WIZ_APPL.Enabled <> 0
ORDER BY
  WIZ_APPL.Id;

I get a Run-time error '3061':
    Too few parameters. Expected 1.
With a slightly different query, which includes an INNER JOIN on another table I get a Run-time error '3075':
    Syntax error (missing operator) in query expression 'TRANS_PRI.tag = "prog'.
SELECT
  WIZ_APPL.*,
  TRANS_PRI.Text AS LocalizedText,
  TRANS_ALT.Text As AlternativeText
FROM
  TRANSLATIONS AS TRANS_PRI,
  TRANSLATIONS AS TRANS_ALT,
  WIZ_APPL
INNER JOIN
  WIZ_COUNTRY_APPL ON WIZ_APPL.Id = WIZ_COUNTRY_APPL.APPL
WHERE
  TRANS_PRI.tag="prog" & WIZ_APPL.Id AND
  TRANS_ALT.tag="prog" & WIZ_APPL.Id AND
  TRANS_PRI.LanguageId=1 AND
  TRANS_ALT.LanguageId=2 AND
  WIZ_COUNTRY_APPL.Country=1
ORDER BY
  WIZ_APPL.Id;

The bizar thing is that the created recordset is fine and I can print the data. Also, the controls on the form are binding and showing data. However, as soon as I call Data1.Refresh I get the run-time error. Also, refresh() probably destroys the recordset (which is probably normal behaviour).
Set Data1.Recordset = GetData(select, from, where, order)
Do While Not Data1.Recordset.EOF
  Debug.Print Data1.Recordset!LocalizedText
  Debug.Print Data1.Recordset!AlternativeText
  Data1.Recordset.MoveNext
Loop
Data1.Refresh

UPDATE: If I assign the SQL query as String to Data1.RecordSource then the refresh works fine. However, when I assign the SQL query to a recordset then recordset.Name contains only a part of the SQL query. After a Refresh() call Data1.RecordSource is the same as Data1.RecordSet.Name. If the Data component tries to build a query from the shortened Recordset name then it obviously would not work.
Is this a known VB6 DAO Recordset issue?

A: I am not entirely sure about this but I think this is a DAO recordset and Data component bug.
It looks like the recordset uses the SQL query to create its name property however, it cuts the query short. The data component seems to use this cut query to refresh its internal recordset.
Bug 1: the recordset name property cuts the query short
Bug 2: the data component probably uses the recordset name property to retrieve the SQL query from the recordset or, it uses another property/function which also cuts the query short
Workaround or perhaps the correct method of usage; don't assign the SQL query to the internal recordset, rather use the Data component recordsource property


text:
Q: Loading a json file into Power Query I am trying to load a JSON file I pulled from data.gov into Power Query for manipulation, but I can't figure out how to get Power Query to convert the JSON file to a tabular format.
Is there a way to convert JSON to a table in Power Query without writing a custom query?

A: JSON data often appears as Records within Lists within Records (and other variations).  You can usually use the PQ UI to expand those objects without writing code.
Here's a sample JSON endpoint: http://api.nobelprize.org/v1/laureate.json
After running the PQ "From Web", the next step is to click the Record Tools / Convert / Into Table button in the PQ ribbon.
This returns a single row, with the second column (Value) containing a List.  Click the expand button next to "Value" to expand the List.
This returns multiple rows, with each second column (Value) now containing a Record.  Expand the record to get the columns of data in a tabular format.
Note there is more depth to this particular JSON layout - see the Value.prizes column at the far right. Your exact steps may vary, depending on your JSON input and your output requirements.
Here's the full code to get to a table - each step was generated by clicking on the UI.
let
    Source = Json.Document(Web.Contents("http://api.nobelprize.org/v1/laureate.json")),
    #"Converted to Table" = Record.ToTable(Source),
    #"Expanded Value" = Table.ExpandListColumn(#"Converted to Table", "Value"),
    #"Expanded Value1" = Table.ExpandRecordColumn(#"Expanded Value", "Value",
        {"id", "firstname", "surname", "born", "died", "bornCountry", "bornCountryCode",
         "bornCity", "diedCountry", "diedCountryCode", "diedCity", "gender", "prizes"},
        {"id", "firstname", "surname", "born", "died", "bornCountry", "bornCountryCode",
         "bornCity", "diedCountry", "diedCountryCode", "diedCity", "gender", "prizes"})
in
    #"Expanded Value1"


text:
Q: Reverse ssh tunnel for p2p downloads I am looking to implement a solution where I use a remote bittorrent client on the cloud server and then download the files to local system over http. This is expected to improve my bandwidth and overcome blacklisting my ip(suppose if I am behind proxy). My solution would be exactly like seedr.cc . One another improvement I want to provide is that the files/directories to be downloaded in parts locally(client application) simultaneously. This can also be done very easily if my solution is a client server application. Now, the real question, suppose if I want to not download the files/directories on the server at all, but on clients directly without mounting remote disk(client's disk). Here, remember the server is used for just the network, no storage is used at all. Do you know of any thing that can help?

A: well , "rsync" in the title is a bit misleading and you're running into several problems here: the remote has to be reachable .. so having an "active tunnel" back to your clients will be a heavy task
for the incoming part: you could use lftp for torrents https://lftp.yar.ru/torrent.html and separate this per user , also helping you with quotas etc. , suggestion: use it in a screen or byobu session
for the download part:

*

*maybe use a ramdisk ( mkdir /tmp/ramtamtam;mount -t tmpfs /dev/null /tmp/ramtamtam/ -o size=64M  ) and let the client access this

*use archivemount https://github.com/bramp/archivemount and send this to the client

*use external providers like mega with rclone and let the clients access this

*a neat optoin would is letting the clients access a torrent on your server through torrent itself with a custom magnet link , and add this to the running lftp session , since the download is at 100%  for this you could use https://webtorrent.io/

*downloading over http can also be achieved with lftp's mirror command

A: Let me first describe your topology to be clear.
You build a server and some clients, the clients can download files using p2p. And you want a client can download file both from sever and other clients to accelerate the speed.
Firstly, the bt download can improve your speed but the limitation comes from your ISP. If you only buy a 100Mb bandwidth, you can not get a higher speed than it.
Secondly, if this topology can help you, then you can build such a systems.

*

*NAT traversal is needed, it's the basic a p2p communication. You may need natpmp, upnp or ICE. Since you have a server, maybe ICE is better.

*LSD and DHT will help you find other clients.

*peer wire communiction protocol is needed to connect to other peers and download files.
There is a open source project named libtorrent may help you. It builds the whole system, you can use it or build your own by learning it.
As for downloading both form server and clients, there need to have a peer manager design, that is relatively hard, and I cannot make it short, you need to do many examples and optimization by yourself.

A: Bittorrent clients generally require random access to the data they are transferring since they download and upload at the same time and have to serve random requests from remote peers.
This means if you use a network filesystem then the performance of a bittorrent client will be constrained by both the upload and download bandwidth and latency of the host providing the storage. This is likely going to cripple the performance that a cloud instance could otherwise achieve.
Instead you could use a cloud instance (server henceforth) with ephemeral storage as accelerator. This can be achieved by letting both the server and your local client implement bittorrent but give preferential bandwidth treatment from the server to the client. This way the server will be downloading the data from other peers and at the same time transfer it to the client. The server can keep seeding a torrent from its temporary storage until it's rebooted.


text:
Q: Missing HttpOnly cookies in Selenium/Docker container, when calling IIS website Unsure if this is Selenium, chromedriver, Docker or IIS-specific. I am using Docker for Windows (beta, with Hyper-V) on my PC. On the same PC, I am using IIS to serve a website.
When using the selenium/standalone-chrome-debug:2.53.0 image to run a test on that website, the Chrome instance in the container does not receive any HttpOnly-cookies (I have used VNC to check). It does get normal cookies though. This means the CSRF token is gone, and trying to POST a form fails.
Works fine if I visit the website on my PC. Both my PC and the container has the domain for the website in their HOSTS-file.
Normal traffic (HTTP GET) works fine from the container, the only difference (thus far) is that it does not get HttpOnly-cookies.
Edit: When I opened up for navigating to external sites I do receive HttpOnly-cookies. So this is probably not related to Selenium or the chromedriver.
It might be related to use of VPN on my host PC, which I need for the local IIS website.

A: This turned out not to be a problem with Docker/Selenium/chromedriver/VPN.
We had a request filter that added the Secure-flag to cookies that are sent with the response, but only to requests that comes from remote machines. The Docker container is in this case seen as a remote machine.
When testing on my local IIS I am doing this over HTTP, which means that secure (HTTPS) cookies are not sent.


text:
Q: How to access vuex store with factory function pattern I inherited an app which is bootstrapped in a way that is rather perplexing to me (unlike like the docs or anything I have seen), my task is to create a global loader instead of implementing on each page separately.
I thought this would be simple where I could just manage the state in the store and have a shared "Header" component respond to changes in the "loading" property in the store. Boy was I wrong, it seems as though the way the app is setup with factories I don't have access to the store inside my interceptor.
The code is a bit advanced for me and I would be very appreciative if anyone can explain either how to restructure the code or alternatively how to access the store inside the interceptor.
My main.js looke like this:
import 'babel-polyfill' // IE support
import cssVars from 'css-vars-ponyfill'; // css variables support for IE
import 'innersvg-polyfill'; // svg support for IE
// until here, all polyfills

import "vue-material-design-icons/styles.css";

import VueI18n from 'vue-i18n'
import {localizationFactory} from "./localization";
import {apiFactory, apiPluginFactory} from './api/api';
import {storeFactory} from "./store/store";
import {configServiceFactory} from "./services/configService";

import {Services, Security, Utils} from 'em-common-vue';

import Vue from 'vue'
import './plugins/vuetify'
import App from './App.vue'
import router from './router'
import {filtersFactory} from './filters/index';

const appsService = new Services.appsService(process.env);
const loginDetails = {
    loginHost: appsService.getLoginStorage()
};
console.log("top of main.js before factory functions", this)
Security.ServiceFactory(loginDetails).then($security => {
    console.log("inside secutiy service factor 'then'", this)
    Vue.config.productionTip = false;

    Vue.use(Utils.EventBusPlugin);
    Vue.use($security);

    var vInstance = new Vue();
    const $api = apiFactory(vInstance, $security);

    configServiceFactory($security, $api).then($config => {
        Vue.use($config);
        Vue.use( apiPluginFactory($api) );

        // for now
        const store = storeFactory($api, null);

        Vue.use(VueI18n);

        filtersFactory($config.$service);

        localizationFactory($config.$service).then(messages => {

            const i18n = new VueI18n({
                locale: 'en', // set locale
                messages, // set locale messages
            });

            new Vue({
                router,
                store,
                i18n,
                render: h => h(App),

                computed: {

                    title: {
                        set(val) {
                            document.querySelector('title').innerText = val;
                        },
                        get(val) {
                            return document.querySelector('title').innerText;
                        }
                    }
                },

                mounted() {
                    cssVars({
                        silent: false, // default,
                        watch: true,
                        onWarning() {
                            console.log("onWarning",arguments); // 1
                        },
                        onError() {
                            console.log("onError", arguments); // 1
                        }
                    });

                    if (!document.querySelector('title')) {
                        let title = document.createElement('title');
                        document.head.append(title);
                    }

                    this.title = this.$config.get().title;
                }
            }).$mount('#app')
        });
    });

}).catch(err => {
    console.error(err);

    if (err.loginUrl) {
        const nextUrl = appsService.getLogin(window.location.href);
        window.location.href = nextUrl;
    } else { // for now
        alert(err);
    }
});

The apiFactory which is where the interceptor resides looks like this:
import axios from 'axios';

import {UsersApi} from "./usersApi";
import {PartnersApi} from "./partnersApi";
import {TrialsApi} from "./trialsApi";

export function apiFactory(vue, $security) {
    console.log("inside api factory")
    console.log(this)
    const $http = axios.create({
        baseURL: process.env.VUE_APP_API_URL
    });

    $http.interceptors.request.use(function (config) {
        console.log("inside interceptor ", this)
        // this.$store.commit('toggleLoader')
        const token = $security.loginFrame.getToken();

        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }

        return config;

    }, function (error) {
        vue.$eventBus.$emit('toastMessageHandler', {message: error.message, type: 'error'});
        return Promise.reject(error);
    });

    $http.interceptors.response.use(function (response) {

        return response;

    }, function (error) {
        if (error.response && error.response.status === 401) {

            vue.$eventBus.$emit('authErr', error);
        } else if (error.response && error.response.status === 403) {
            alert('You are not authorized to access this application. If you believe you are seeing this message in error, please contact support@emergingmed.com.');
        }

        else if (error.response && error.response.status !== 409){
            vue.$eventBus.$emit('toastMessageHandler', {message: error.message, type: 'error'});
        }
        else if (error.response && error.response.status === 500){
            vue.$eventBus.$emit('toastMessageHandler', {message: 'There was a problem with this operation - please contact support@emergingmed.com.', type: 'error'});
        }

        return Promise.reject({error});
    })

    const $api = {
        users: new UsersApi($http),
        partners: new PartnersApi($http),
        trials: new TrialsApi($http)
    };

    return $api;
}

// register $api as vue plugin
export function apiPluginFactory($api) {
    return {
        install(vue) {
            vue.prototype.$api = $api;
        },
    };
}

When I try to run this code this.$store.commit('toggleLoader') (commented out in the actual code) I get an error that store is undefined. In general this structure does not seem to me idiomatic to vue (or maybe even JS) but I am not sure how I would restructure it.
1)How might I access my store in the interceptor code?
2)How might the app be restructured?


text:
Q: Passing object to JQuery function as options Not posting the whole function here, but the basic premise is that I'm trying to create a plug-in with options. I'd like not to have to rewrite the entire structure of the function, and I've been Googling for two hours now without any luck.
This is what it looks like now:
function slider($rotator_container, settings) {

    var settings = {
        auto_rotate : false,
        auto_rotate_speed : 1000,
        transition_support : true //Disable this to use JQuery animations only
    }
};

And I'm calling the variables with the following:
slider("main-slider", {auto_rotate:true, auto_rotate_speed:5000});

This works if I take the object's deceleration and defaults outside of my function, but the problem is that I call it multiple times on a page so it needs to not be global. How do I go about this? Would I need to rewrite the entire function?

A: In order to have default options you should extend the option using $.extend
(function($){
    jQuery.fn.extend({

        // Plugin Name
        slider: function(options) {

            // Defaults options are set here
            // Every default goes within the { } brackets as seen below
            // A comma separates the different values
            var defaults = {
                auto_rotate : false,
                            auto_rotate_speed : 1000,
                             transition_support : true

            };
            var options = $.extend(defaults, options);

return this.each(function() {

});
}

    });
})(jQuery);

Then you can call as
$("div").slider(auto_rotate : true});

IN your case you can extend object as follows
function slider($rotator_container, settings) {

    var defaultsettings = {
        auto_rotate : false,
        auto_rotate_speed : 1000,
        transition_support : true //Disable this to use JQuery animations only
    };
  $.extend( defaultsettings, settings );
)


text:
Q: How to make an event happen after a javascript alert in c# I have this line of code:
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('You need to be logged in in order to proceed to checkout. You will now be transfered to the Login page.')", true);

And I want to be transfered to the a page using Response.Redirect() after I click on "OK" in the alert pop-up message. How can I do it?
Thank you for your answers.


text:
Q: Erro ao colocar Virtualbox como serviço Criei um serviço no windows pra para poder configurar minha VM no modo Headless, com o comando:
sc.exe create DailyLubuntu binpath= "\"C:\Program Files\Oracle\VirtualBox\VBoxHeadless.exe\"  startvm Daily LUbuntu - Lucas" DisplayName= \"Daily Lubuntu VM" start= "auto"

O serviço foi criado com êxito, porem quando vou inicializar o serviço com o comando:
> net start DailyLubuntu

, aparece este erro:

Erro de sistema 2. O sistema não pode encontrar o arquivo especificado. Para obter mais ajuda, digite NET HELPMSG 2186.

A: Existe um projeto chamado VBoxVmService que faz esse serviço por você. Basta instalar, alterar o arquivo VBoxVmService.ini dentro de C:\vms e reiniciar o serviço.


text:
Q: File.exists() return false using javaservice.exe I have the following Java code to check if exists the remote directory: "\\server_web\\Covers"
File CoversPathFile = new File(Options.CoversPath);
if (!CoversPathFile.getAbsoluteFile().exists()) throw new Exception();

It works well when the execution is through command line or a .Bat file,
But if I use the JavaService.exe to wrap the java class in a Windows service, the File.exists() method returns false;
The problem doesn't occurs if a Local Path is used.
It's JavaService.exe bug?
JavaService.exe version: 2.0.10.0
Platform: Windows 2008
Java versión: 8.0_40

A: You have to specify a current work directory. Because you are using relativ path names. Starting from a batch makes the start path to the current working path. Therefore you can use the -current option to provide a path:

-current current_dir (optional) - A directory to use as the current working directory for the service. If this parameter is specified, all
  relative paths in the service will be relative to relative to the
  specified directory.

See also here:
http://javaservice.ow2.org/docs/devdocs/devcmds.html

Update:
If you are accessing a remote resource, the user assigned to the service does not have the privileges to access that resource.
To  change the permission, you have to assign a specific user to your service. As default a service runs on the local service user account. Change this to an proper user.
Open the service and change the user on the register "logon".
Or use the option -user from javaservice.exe:

-user user_name (optional) - Specify the Windows domain username to be used when running the service (also requires that the password
  parameter is specified). Local user accounts are specified as
  .\user_name whereas domain accounts may be specified as either
  domain\user_name or user_name@domain (the latter form has been
  required on some systems to avoid reports of 'I/O Operation in
  progress' errors).

I strongly suggest to read the above link.


text:
Q: $.getJSON Callback Help - Not a Function My context is as follows:
I have a variable 'qq' - I want to assign data to this variable from an API call, and once the data has been assigned, I then use this data in a paint/binding process.
The API call and assigning to var 'qq' works fine - but I cant seem to get my callback to work - I keep getting an error: callback() is not a function
This is what my code currently looks like:

var qq = [];

// binding function - to be run after data loader has completed
function sayIamDone() {
    alert('I Am Done');
    // do data bindings with qq
}

// load data from api into var qq

function dataLoader(inp,callback) {
    let url = 'http://localhost:65232/api/layercolor/' + inp;
    console.log(url);
    $.getJSON(url,function(result) {
        qq = eval('({' + result + '})');
        //console.log(qq);
        callback();
    });

}

// call data loader
dataLoader('Prov', sayIamDone());

From the above I get the following error in my chrome console:
Uncaught TypeError: callback is not a function
I have tried the following - which seems to work:

dataLoader('Prov', function () { alert('I Am Done');});

but it is not ideal in my context, as I want to call dataLoader('Prov',XXX()) where XXX() could be a number of different functions using the newly loaded values in qq
Any suggestions as to where I am missing the boat please?

A: change:
dataLoader('Prov', sayIamDone());

to
dataLoader('Prov', sayIamDone);

because:
sayIamDone is function ,sayIamDone() is the result of function.Normally, sayIamDone() is undefined or return value in the sayIamDone;
want to use arguments?you can do this:
dataLoader('Prov', callFunc(n));

function callFunc(arg) {
    return function() {
        sayIamDone(arg);
    };
}

or more arguments?you can do this by spread
dataLoader('Prov', callFunc(n));

function callFunc(...arg) {
    return function() {
        sayIamDone.apply(null, arg);
    };
}

A: By running dataLoader('Prov', sayIamDone()); you are passing to dataLoader the result of sayIamDone function. You have to pass it without parenthesis in order to pass the function itself.
dataLoader('Prov', sayIamDone);


text:
Q: Angular updating matTableDatasource with interval brings scroll to the top of page I have a mat-table which needs to be updated about the changes. I set an interval and inside the interval I call a method which is like
updateMatTable(offset: number, size: number): void {

        offset = offset * size;

        /* GET DATA FROM REST SERVICE */

            this.dataSource = new MatTableDataSource(this.newTableData.dataRows);

        });

    }

it seems like equating dataSource to the newTableData brings the scroll position to top of the page only when we are at a scroll position where we can see under the mat-table (near bottom of page ) and that the table needs scrolling down
Is this a bug about the library or am I missing something about mat-tables.
Thank you for the answers

A: Ok,I added a change detector under the codes and it is not behaving strange somehow. I would like to have an explanation tho.
    updateMatTable(offset: number, size: number): void {

            offset = offset * size;

            /* GET DATA FROM REST SERVICE */

                this.dataSource = new MatTableDataSource(this.newTableData.dataRows);

                this.changeDetectorRef.detectChanges();

            });

        }

A: In my case scrolling page to the top was caused by stickyEnd directive added to one of the column of mat-table.

A: I've now encountered this bug/quirk of mat-table with sticky columns on a scrolling page. Another workaround (besides removing sticky columns) is to set a static height on the mat-table element such as height: 600px; I've tried setting height to a % or vh but the bug persists.


text:
Q: Set colors in Matplotlib.pie by label name I have created a large matrix of pie plots using a function that runs through a datafrane. I am only plotting in the pie charts two variables. When one of the variables is not present in the specific data, matplotlib automatically switches the colors. See sample picture below.
How would I make sure the colors stay consistent based on values? Would I manipulate the colors argument in my function?
my def code that I run the data through
#function to make matrix
def pie(v, l, color=None):
    plt.pie(v, labels=l.values, colors = ????, autopct='%0.f')

#function being called for data - l='coverage'
g = sns.FacetGrid(market_covered_sum, col="mkt_mcap_decile", row="market",
                  margin_titles=True)
g.map(pie, "MKT_Cap_mn", "coverage").set_axis_labels(" ", " ")

I want to keep the colors consistent, and change them to a color code once I can keep consistent.


text:
Q: XQuery: Fill array the FLWOR way I have an array and I want to fill it with strings taken from specific XML nodes, like in this pseudocode example:
let $array := array {}

for $child in $collection
where contains(data($child), "Hey")
do $array := array:append($array, data($child))

How would correct code look like to perform such an operation?
So if I have this XML
<root>
    <child>Hey</child>
    <child>Ho</child>
    <child>Hey Ho</child>
</root>

I expect the array to be
array ["Hey", "Hey Ho"]

A: XQuery is a functional language. As such, variables cannot be reassigned once they have been declared.
The following code should do the trick:
array {
  for $child in $collection
  where contains(data($child/node1), "Hey")
  return $child/node2
}

Please note that the native XQuery data type for values is a sequence. Depending on your use case, maybe you don't need arrays at all.


text:
Q: Why is the expected value of variance different than the expected value of Maximum Likelihood variance? The expected value of variance is:

The expected value of the maximum likelihood of variance is:
$E\left[\frac{1}{N}\sum_{n=1}^{N}(X-\mu_{ml})^{2})\right] = \frac{N-1}{N}\sigma ^{2} $
Why does inserting the maximum likelihood of the mean, change the result of the expectation? Or is the term that makes the difference:

I have the entire mathematical proof in front of me, but I can't seem to intuitively understand why they would be different. Why is the expectation of maximum likelihood, different than the expectation of the data? Am I mixing up the expectation of a set of data and the expectation of multiple samples of data?

A: If you have data $X_1, X_2, \dots, X_n$ randomly sampled from $\mathsf{Norm}(\mu, \sigma),$ with $\mu$ known and $\sigma$ unknown, then
$V = \frac{1}{n}\sum_{i=1}^n (X_i - \mu)^2$ has $E(V) = \sigma^2,$ with
$\frac{nV}{\sigma} \sim \mathsf{Chisq}(\nu = n).$ The proof follows directly
from the definition of $\mathsf{Chisq}(\nu = n)$ as the distribution of the
sum of $n$ independent standard normal random variables.
However if $\mu$ is also unknown, then
$S^2 = \frac{1}{n-1}\sum_{i=1}^n (X_i - \bar X)^2,$ where $\mu$ is estimated
by $\bar X = \frac{1}{n} X_i,$ is the usual unbiased estimator of $\sigma^2,$
with $E(S^2) = \sigma^2$ and $\frac{(n-1)S^2}{\sigma^2} \sim
\mathsf{Chisq}(\nu = n-1).$ Informally, people may say that one degree of
freedom is 'lost' in the estimatiion of $\mu.$ However, a formal proof
requires moment generating functions or a transformation of an $n$-variate
normal distribution.
In the latter case ($\mu$ unknown), some statisticians have argued that it is better to use
$Q = \frac{n-1}{n}S^2$ $= \frac{1}{n}\sum_{i=1}^n (X_i - \bar X)^2$ because, for normal data,
it has a smaller mean squared error than $S^2.$ It is true that $\mathrm{MSE}(Q) < \mathrm{MSE}(S^2),$
but it is not obvious that minimizing MSE is a suitable criterion for choosing the best
estimator. [And if minimizing MSE is to be the criterion, then
$Q^\prime=\frac{n-1}{n+1}S^2$ has even smaller MSE, and both variants are biased.]
Simulations and some graphs:
set.seed(626)
m = 10^5;  n = 5
x = rnorm(m*n, 100, 15)
DTA = matrix(x, nrow=m)
v = rowSums((DTA-100)^2)/n
s.2 = apply(DTA, 1, var)
par(mfrow=c(1,2))
 hdr="CHISQ(5)"
 hist(n*v/15^2, prob=T, br=40, col="skyblue2", main=hdr)
  curve(dchisq(x,5), add=T, lwd=2)
 hdr="CHISQ(4), not CHISQ(5)"
 hist((n-1)*s.2/15^2, prob=T, br=40, col="skyblue2", main=hdr)
  curve(dchisq(x,4), add=T, lwd=2)
  curve(dchisq(x,5), add=T, col="red", lty="dashed", lwd=2)
par(mfrow=c(1,1))

mean((s.2 - 15)^2)
[1] 69444.44       # aprx. MSE S^2
q = (n-1)*s.2/n
mean((q - 15)^2)
[1] 43445.15       # aprx. MSE Q
q1 =(n-1)*s.2/(n+1)
mean((q1 - 15)^2)
[1] 29488.79       # even smaller MSE

It seems that MSE is very heavily influenced by the right tail. Too heavily?
par(mfrow=c(1,3))
 hist(s.2, prob=T, xlim=c(0,max(s.2)), col="skyblue2")
  abline(v=15^2, col="red")
 hist(q, prob=T, xlim=c(0,max(s.2)), col="skyblue2")
  abline(v=15^2, col="red")
 hist(q1, prob=T, xlim=c(0,max(s.2)), col="skyblue2")
  abline(v=15^2, col="red")
par(mfrow=c(1,1))


text:
Q: MongoDB MapReduce - Reducing BSONElement I am trying to apply a map reduce function in a document like this:
{
"_id": 2,
"timestamp_day": "1/20/2005 12:00:00 AM",
"variableID": "GUID",
"subscriptionID": "1",
"unit": "kWh",
"timezone": "UTC",
"sum": 0,
"numberOfRecords": 96,
"values": {
    "1": 0.06232154558520836,
    "2": 0.06232154558520836,
    "3": 0.06232154558520836,
    "4": 0.06232154558520836,
    "5": 0.06232154558520836,
    "6": 0.06232154558520836,
    "7": 0.06232154558520836,
    "8": 0.06232154558520836,
    "9": 0.06232154558520836,
    ...
   }
}

I have documents for each day I'm keeping information, and each value represents a reading. My objective is to apply a mapReduce function in this document so I can retrieve metrics like avg per day, avg per day per id, and so on. The thing is that I don't know how to do that since the values key contains a BSONElement.
So far my map function is as follows:
var mapFunction = function() {
   emit(this.subscriptionID, this.values);
}

And by what I understood with this, it will be sent to reduce function all the values stored in values, but again, since it is a BSON element how can I make those calculations? A foreach going through each one? Performance is important..
Thanks in advance.

A: So I got a few days ago and I'll leave it here if anyone needs this.
var mapFunction = function() {
  for (var key in this.values) {
    emit(this.subscriptionID, this.values[key]);
  }
}

In this particular case this function will send to the reduce function all the values mapped to one subscriptionID as an array. For the values in the question, the map will send something like this:
[0.06232154558520836, 0.06232154558520836, 0.06232154558520836, ...]

Hope it helps someone.


text:
Q: An easy solution in R? Binding several numbered data frames I have 408 "Spatial Points" Data Frames, each numbered as follows:
Points1, Points2,..., Points408.
What I want is to loop through all of them, adding them to a list. I would then like to row bind them to create one huge Spatial Points file.
When I type "Points1" into R, this is printed:
              x         y
  [1,] 40.38285 -11.54500
  [2,] 38.41897 -13.55959
  [3,] 38.51536 -12.42431
  [4,] 38.82389 -12.95476
  [5,] 39.88932 -12.77925
  [6,] 39.86099 -13.32380
  [7,] 38.47942 -14.10968
  [8,] 39.85796 -11.84176
  [9,] 38.16891 -13.70572
 [10,] 39.89386 -12.21040
 [11,] 38.32758 -14.03576
 [12,] 39.97627 -11.97127
 [13,] 38.50884 -14.07678
 [14,] 39.06521 -12.19818
 [15,] 39.40532 -13.68988

Please note that each Points data frame has the same number of points.
What I want is one huge file that has 15*408=6120 Spatial Points.
Thanks so much!


text:
Q: Confuse in how to post data for edit row in jqgrid This is the first time I'm using jqgrid.
I have confused in how to post all value from modal's edit row(pencil icon).
I'm so familiar with dataTable but not in this plugin. I need some server side script for this edit process. So, I can learn from it.
Could you give some tutorials or sample to send this data?
thanks in advance.

jQuery("#list").jqGrid({
                         url:'dounfinish.php',
                         datatype: 'json',
                         mtype: 'POST',
                         colNames:['id','Date', 'Line','Shift','Model','Serial','DIC','Def_class','Symptom','Cause','Symgrup','Modgrup'],
                         colModel :[......],
                         pager: jQuery('#pager'),
                         rowNum:10,
                         rowList:[10,20,30],
                         sortname: 'Problem_date',
                         sortorder: "desc",
                         editurl: "process1.php",
                                                viewrecords: true,
                                                imgpath: 'themes/basic/images',
                                                caption: 'OQC DEFECT DATA'
                                                });
                        jQuery("#list").jqGrid('navGrid','#pager',{edit:true,add:false,del:false});

how to send data to this:
........
case 'edit':
         edit(postVar('id'),postVar('DIC'),postVar('Def_class'),postVar('Symptom'),postVar('Cause'));
                break;
           });
function edit($id,$DIC,$Def_class,$Symptom,$Cause){
        $defID = mysql_real_escape_string($id);
        $DIC = mysql_real_escape_string($DIC);
        $Defclass = mysql_real_escape_string($Def_class);
        $Symp = mysql_real_escape_string($Symptom);
        $Cause = mysql_real_escape_string($Cause);
        $DIC=strtoupper($DIC);
        $Defclass=strtoupper($Defclass);

        $sql = "UPDATE oqc_defect SET DIC = '".$DIC."', Def_class = '".$Defclass."', ";
        $sql.= "Symptom = '".$Symp."', Cause = '".$Cause."' ";
        $sql.= "WHERE def_id = ".$defID;

echo $sql;
$result=mysql_query($sql) or die(_ERROR26.": ".mysql_error());
//echo $result;
mysql_close($dbc);
}

A: just add loadonce : true all can work normally.


text:
Q: Calculate running total using unbounded preceding I am working on writing a query which will give the number of hours left on starting day and it should gradually decrease towards end day and reach zero.
I tried using unbounded preceding function. It helped but not completely.
SELECT project_id,
       sprint_id,
       est_task_per_sprint,
       start_date,end_date,
         nvl(sum(est_task_per_sprint) over (
           order by end_date rows between unbounded preceding and 1 preceding

       ),0) tot
FROM   project_sprint where project_id=1;

The sum(est_task_per_sprint)=1134 is the total hours.
Output I got:
Proj  Sprint  Hours  startdate  enddate    hoursremaining
   1       1    262  01-JAN-19  31-JAN-19               0
   1      11    263  01-FEB-19  28-FEB-19             262
   1      21    266  01-MAR-19  31-MAR-19             525
   1      31    262  01-APR-19  30-APR-19             791
   1      41    261  01-MAY-19  31-MAY-19            1053

Expected:
Proj  Sprint  Hours  startdate  enddate    hoursremaining
   1       1    262  01-JAN-19  31-JAN-19            1053
   1      11    263  01-FEB-19  28-FEB-19             791
   1      21    266  01-MAR-19  31-MAR-19             525
   1      31    262  01-APR-19  30-APR-19             262
   1      41    261  01-MAY-19  31-MAY-19               0

A: You can calculate the remaining hours by subtracting the the sum of the hours up to - and including - the current row (not 1 preceding) from the total of all hours for the project.
I've added partitioning by project ID so this will work without the ID filter too, and as the window now matches the default (rows between unbounded preceding and current row) I've left that clause out. This example includes the total and completed hours to make it clearer - they aren't needed in your real query.
SELECT project_id,
       sprint_id,
       est_task_per_sprint as hours,
       start_date,
       end_date,
       sum(est_task_per_sprint) over (partition by project_id) as total,
       coalesce(sum(est_task_per_sprint)
                  over (partition by project_id order by end_date), 0) as completed,
       sum(est_task_per_sprint) over (partition by project_id)
         - coalesce(sum(est_task_per_sprint)
                      over (partition by project_id order by end_date), 0) as remaining
FROM   project_sprint
--WHERE  project_id=1
ORDER BY project_id, start_date;

PROJECT_ID  SPRINT_ID      HOURS START_DATE END_DATE        TOTAL  COMPLETED  REMAINING
---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
         1          1        262 2019-01-01 2019-01-31       1314        262       1052
         1         11        263 2019-02-01 2019-02-28       1314        525        789
         1         21        266 2019-03-01 2019-03-31       1314        791        523
         1         31        262 2019-04-01 2019-04-30       1314       1053        261
         1         41        261 2019-05-01 2019-05-31       1314       1314          0

which is the same as summing later rows, this time using a window clause of rows between 1 following and unbounded following:
SELECT project_id,
       sprint_id,
       est_task_per_sprint as hours,
       start_date,
       end_date,
       coalesce(sum(est_task_per_sprint)
                over (partition by project_id order by end_date
                      rows between 1 following and unbounded following), 0) as remaining
FROM   project_sprint
--WHERE  project_id=1
ORDER BY project_id, start_date;

PROJECT_ID  SPRINT_ID      HOURS START_DATE END_DATE    REMAINING
---------- ---------- ---------- ---------- ---------- ----------
         1          1        262 2019-01-01 2019-01-31       1052
         1         11        263 2019-02-01 2019-02-28        789
         1         21        266 2019-03-01 2019-03-31        523
         1         31        262 2019-04-01 2019-04-30        261
         1         41        261 2019-05-01 2019-05-31          0

db<>fiddle
Notice that the numbers don't exactly match your expected result, but that's because I believe that your expectation wasn't quite right, and was based on the numbers your query produced - just reversing those doesn't make sense though.


text:
Q: Read node value in array using XDocument class I have below xml.How can I get FileTypeId,EngName,JpnName in an array if I have FolderName. For eample if I have Test2, I want to get 2, EngName2, JpnName2 in an array of string using XDocument class.
<Row>
    <FolderName>Test1</FolderName>
    <FileTypeId>1</FileTypeId>
    <EngName>EngName1</EngName>
    <JpnName>JpnName1</JpnName>
  </Row>
  <Row>
    <FolderName>Test2</FolderName>
    <FileTypeId>2</FileTypeId>
    <EngName>EngName2</EngName>
    <JpnName>JpnName2</JpnName>
  </Row>
  <Row>
    <FolderName>Test3</FolderName>
    <FileTypeId>3</FileTypeId>
    <EngName>EngName3</EngName>
    <JpnName>JpnName3</JpnName>
  </Row>

A: you need main root,
var doc = XDocument.Load("data.xml");

<Rows>
  <Row>
    <FolderName>Test1</FolderName>
    <FileTypeId>1</FileTypeId>
    <EngName>EngName1</EngName>
    <JpnName>JpnName1</JpnName>
  </Row>
  <Row>
    <FolderName>Test2</FolderName>
    <FileTypeId>2</FileTypeId>
    <EngName>EngName2</EngName>
    <JpnName>JpnName2</JpnName>
  </Row>
  <Row>
    <FolderName>Test3</FolderName>
    <FileTypeId>3</FileTypeId>
    <EngName>EngName3</EngName>
    <JpnName>JpnName3</JpnName>
  </Row>
</Rows>

A: Try with LINQ:
XDocument xdoc = XDocument.Load("input.xml");

string yourCondition = "Test2";
var query = from elem in xdoc.Root.Elements("Row")
            where elem.Element("FolderName").Value == yourCondition
            select new
            {
                FileTypeId = elem.Element("FileTypeId").Value,
                EngName = elem.Element("EngName").Value,
                JpnName = elem.Element("JpnName").Value
            };

if (query.Count() > 0)
{
    var result = query.First();

    // You can access the fields through this:
    string engName = result.EngName;
    string fileTypeId = result.FileTypeId;
    string jpnName = result.JpnName;
}

And as "snn brn" pointed out, you need a Root element in your xml.


text:
Q: RestSharp Deserialize a List in a List i have some trouble getting this to work:
my xml looks like:
<root>
    <item>
        <id></id>
        <name></name>
        <CollectionProp>
            <item>
                <id></id>
                <name></name>
            </item>
        </CollectionProp>
    </item>
</root>

my class looks like:
public class Item
{
    public int id { get; set; }
    public string name { get; set; }
    public List<CollectionProp> CollectionProp { get; set; }
}

and another one:
public class CollectionProp
{
    public int id { get; set; }
    public string name { get; set; }
}

i also tried to wrap another class around CollectionProp
CollectionPropCollection : List<CollectionProp>

Also tried: CollectionPropCollection class with / or with a property "item" of type CollectionProp.
here's my execute statement:
var result = client.Execute<List<Item>>(request);

EDIT Aug 19:
ok, my post may not clearly pointed out my problem.
so now i think i broke down the problem to the following:
the XmlDeserializer has a problem to distinguish between the item under  and the item under
so the response has 2 items under  and each has 3 items under , my deserialized result has 8 objects. the first with values, the next 3 with properties set to null, the 4th with values and so on....
any idea how i can solve this in a way like : item under  needs to be parsed into objectA, item under , which is a child of item under root, needs to be parsed into objectB ?

A: If the xml file is a serialized Item you can do this:
XmlSerializer serializer = new XmlSerializer(typeof(Item)); //or if you have a item variable item.GetType()
FileStream stream = new FileStream(pathToFile, FileMode.Open, FileAccess.ReadWrite);
Item item = (Item) serializer.Deserialize(stream);
stream.Close();

UPDATE
When it's a list of Items you just replace typeof(Item) with typeof(List<Item>) and you cast it to a List<Item>


text:
Q: get all user's contact list (including phone number) from google login in javascript I am trying to get the contact number of all the user's contacts through google sign in. I am getting contact name, email and other details but not the contact number. I am specifically trying contacts API v3.
this official link
gives a way to get contact details (including phone number) but I am not really sure how to do that in javascript. I googled around and found that people are using contacts API v2 and v1 to get this information. But even there I couldn't find any suitable example. My current implementation using google api (gapi) gives me contacts in this format

displayName: "Jamie Lannister"
  etag: ""XXXXXXXX-YYYYYYYYYYYYYYYYYY/Wl9XXXXXXXXXXXXXZ9-cJsx-wUY""
  id: "107108760XXXXXXXXXXXX"
  image: Object
  url: "https://lh4.googleusercontent.com/-9Iyxxxxxxx/xxxxxxxxxxxxxxx/xxxxxxxxxxk/xxxxxx-xxx/photo.jpg?sz=50"
  proto: Object
  kind: "plus#person"
  objectType: "person"
  url: "https://plus.google.com/107108760XXXXXXXXXXXX

I got this from this link and this link.
My question is it really possible to get a user's google+ or google contacts with phone numbers? If yes please answer here. Is there any other way to do this?
Oh by the way, this question is not eligible for bounty yet. Correct answer gets +50 bounty in next 2 days.

A: I used the following javascript function (httpGet) to get the google contacts with name and number. The url i passed in the "theUrl" param is : "https://www.google.com/m8/feeds/contacts/user.email@gmail.com/full?access_token="+authToken+'&max-results=9999'"
function httpGet(theUrl)
    {
        $.ajax({
            type: "GET",
            url: theUrl,
            dataType: "jsonp",
            success: function (xml) {
                $(xml).find('entry').each(function(){
                    var name = '';
                    var number = '';
                    $(this).find("gd\\:phoneNumber").each(function(){
                        number = $(this).text();
                    });
                    $(this).find("title").each(function(){
                        name = $(this).text();
                    });

                    if(number!=null && number.length>0)
                    {
                        number = number.replace(/[^0-9]/g,'');
                        userContacts.push(name+'-'+number);
                    }
                });

            },
        });
    }

Explanation:
by default google returns a particular number of contacts, to get all the contacts pass a really big number in max-results parameter (hence the 9999).
authToken is what you get after you authorize the user.
email address: after getting authtoken you an query for email address as well. here is how i did it:
function getEmail(){
        gapi.client.load('oauth2', 'v2', function() {
            var request = gapi.client.oauth2.userinfo.get();
            request.execute(getEmailCallback);
        });
    }

function getEmailCallback(obj){
        email = '';
        if (obj['email']) {
            email = obj['email'];
            //here you get the email address of the user who just signed in
        }
    }

the gapi here is google's api javascript object. add this script and you are good to go
script type="text/javascript" src="http://www.google.com/jsapi"/ (add jQuery script too)

Without the ajax call in httpGet(), you will receive a cross domain compliance error. What you receive after httpGet of the mentioned url is an xml file, the whole success lot inside the httpGet() method is for parsing that xml, you will also receive a bunch of other info, if required parse those too (I only needed contact number and name). if you want a google account with contacts just log in to google contacts and add some test phone numbers there.
Needless to say you will also need client Id, secret, API key etc for this. Please go to the link provided below for details. the user contacts var in httpGet() contains all the user contacts separated by hyphen. The regex pattern in httpGet() is to pick only numbers from contact number or else you might get something like this (123) 456 7890.
more details straight from google


text:
Q: Windows RDP vs. Various Versions of NX Can anyone weigh in on the speed, responsiveness, reliability and flexibility of the following two options:

*

*Using RDP to remotely access a Windows machine from a Windows machine

*Using NX to remotely access a Linux machine from a Linux machine (or a Windows machine if not much different)
The application I would run on either guest is the same.  If the approaches perform about as well as each other, I'd prefer the second for security reasons pertaining to Linux.  However if NX is going to be significantly slower, I may reluctantly go with RDP and Windows for the time being.
Please mention the variety or varieties of NX you have experience with (FreeNX, NeatX, x2go, etc.)  Thanks!

A: The short answer is that it really depends on what the application does, NX can be quite efficient with applications that draw using X11 primitives, much less so for graphical/video.
As for the different NX varieties: FreeNX is unmaintained, so is NeatX, and you forgot winswitch.
When it comes to performance, which implementation you choose makes no difference since they all rely on the same NX libraries for remoting the display (assuming they do not misconfigure the link parameters), the only thing they change is the way they manage the sessions (the UI) and the client-server protocol used for the GUI app (which has no impact on performance).
It is now at least as efficient as RDP and NX so you may also want to give xpra a go.


text:
Q: Open PDFs in Adobe instead of in Google Chrome Lately when I download a PDF in Chrome and click the downloaded file in the bar at the bottom, it opens in chrome. I would like it to open in adobe as default, since I download mostly files  with comments or stuff Chrome doesn't support anyway. I have seen this, but it makes chrome download all files and open them in Adobe.
So what I want is: if I click a random PDF, it should open in the chrome browser, if I click a downloaded file from the bar at the bottom or from chrome://downloads it should open the file in Adobe. (Just as it used to be two weeks ago). Is that still possible?

A: In Chrome, type chrome://plugins/
Find the Chrome PDF Viewer and click Disable
From your browser, click a PDF file; it should show at the bottom as a downloaded file.
Click the arrow next to the downloaded file, and choose Always open files of this type
(You may need to manually click Open on any recent files you want to view, otherwise...)
The next time you click a PDF file, it should open however your computer is configured to open PDF files. If that method is via Adobe Reader or Adobe Acrobat (standard, pro), then that should meet the need you expressed in your question.

A: 1- Go to chrome://settings.

2- Click on "Privacy" --> "Content Settings".

3- At the bottom, click on:
"PDF Documents" --> "Open PDF files in the default PDF viewer application".

This should solve the problem!

PS:
1- Instead of 1 & 2, you can navigate to: chrome://settings/content
2- You can click on the file name's small (upside) arrow in the "Downloads bar" at the bottom, and, click on "Always open with system viewer". However, this works only for this downloaded file, not other downloads (it should be a bug though)!
3- After doing the above three steps, when you click on a file in the download bar, it first opens another tab and closes it quickly (another bug, which is a little annoying)! But then opens the file in your PDF viewer anyway.
4- Previously you could control this from chrome://plugins which is now removed from Chrome (57 and later versions). So you just ignore what you found on the web about chrome://plugins.

A: FYI for others: if you're okay with the Chrome PDF viewer, but want only downloaded PDFs to open in your external PDF viewer (Adobe Acrobat, Foxit Reader, etc.), you don't need to disable the Chrome PDF Viewer.
Always open PDFs using your system's viewer
Simply click the arrow next to a PDF download and select the option to use the system viewer.

Turn off auto-open of PDFs in the system viewer

UPDATE 6/7/2017
As of Chrome version 59, the option below doesn't exist in Settings. I'll leave these instructions, because if they ever add it back it'll probably be in the same place.

*

*Click on the Chrome Menu icon

*Click on

*Scroll down and click

*Scroll down to Downloads. If you have enabled any file types to open using the system viewer, you'll see a button to Clear auto-opening settings. Clicking this will reset the settings for all file types.

More info
Relevant SuperUser discussion here: How to automatically open "saved" pdfs in system viewer on chrome?

A: You should try this:

*

*Open Chrome.

*Type chrome://plugins/ in the address bar, hit enter.

*Browse the list for Adobe PDF viewer or Adobe reader (and chrome pdf viewer)

*Disable both (although disabling adobe reader would work alone.)

Hope this helps.

A: Slightly simpler way with latest Chrome browser:

*

*Navigate to: chrome://settings/content/pdfDocuments

*Then set that to on.

A: This is what worked for me.

*

*Click on the three vertical menu dots in the right hand corner of the Chrome bar and choose SETTINGS.

*Under settings, click on EXTENSIONS.

*A new tab opens and displays the software which uses file extensions for document management.  Click on the DETAILS tab which appears in the Adobe box.  The page titled at the top, "Adobe Acrobat: PDF edit, convert, sign tools", appears.

*Click on EXTENSION OPTIONS which appears toward the bottom of that page.

*A new tab opens titled, "Adobe Acrobat Preferences".  Turn on the "OPEN PDFS IN ACROBAT" option by clicking the gray/blue toggle bottom to its right.  It is the first option.  Click SAVE PREFERENCES at the bottom of the page.

*You may want to clear history and cache in Chrome and in your computer.  For Chrome: Right hand three vertical dot menu-->Settings-->Privacy and security-->Clear browsing data-->Under Advanced, for ALL TIME, check Browsing history, Download history, Cookies and other site data, and Cached images and files.  Click CLEAR DATA.

*Close Chrome, turn the computer off, and restart the computer.  Check your PDF files.  They should now display as PDFs and open in Acrobat.
I am using Google Chrome v. 109.0.5414.120 and Adobe Acrobat Pro DC v. 2015.006.30527.
Nothing else worked for me.  Going through the EXTENSIONS OPTIONS did.
Hope this helps,
Mark J. Miller