text:
Q: How to fetch row of max of date from a same month? I have table called XX_DATE with columns ID, start_date, end_date, start_reading, end_reading.

The last 2 rows in actual date should be fetched as single row using max end_date of same month as well as max end_reading of same month.

A: This isn't as simple as it looks. But let me start with a simple answer first.
To achieve your goal, create a query and group by the actual year/month of the end_date, then get the min(startdate) and max(end_date) and also apply the same rules for the reading columns.
select min(start_date)    as start_date
,      max(end_date)      as end_date
,      min(start_reading) as start_reading
,      min(end_reading)   as end_reading
from   XX_DATE
group by trunc( end_date, 'MM')

One issue is that the query won't take gaps in the period into account, meaning that if there is a gap in the period of the data, it will still be showed as one record and won't indicate that there is a gap. If this is okay, you're fine, otherwise this won't work.
Another issue is by doing this, you would loose the id column and you would have to think of creating a new sequence as the id column or create an aggregated id column like 6:7 so that you can always refer to the original id's.
ID as lowest id value
select min(id)            as id
,      min(start_date)    as start_date
,      max(end_date)      as end_date
,      min(start_reading) as start_reading
,      min(end_reading)   as end_reading
from   XX_DATE
group by trunc( end_date, 'MM')

ID as newly generated a id
select rownum as id,
       start_date,
       end_date,
       start_reading,
       end_reading
from (
  select min(start_date)    as start_date
  ,      max(end_date)      as end_date
  ,      min(start_reading) as start_reading
  ,      min(end_reading)   as end_reading
  from   XX_DATE
  group by trunc( end_date, 'MM')
)

ID as aggregated id column
select listagg(id, ':') WITHIN GROUP (order by id) as id_agg
,      min(start_date)    as start_date
,      max(end_date)      as end_date
,      min(start_reading) as start_reading
,      min(end_reading)   as end_reading
from   XX_DATE
group by trunc( end_date, 'MM')


text:
Q: Expectation of minimum discrete and continious random variable I have two random variables, one is $X$ which has $\mathbb{P}(X=2)=\mathbb{P}(X=4)=\mathbb{P}(X=6)=1/3$, and one, call it $Y$,  which is $unif(3,5)$ (continious) distributed. I want to compute $\mathbb{E}(min(X,Y))$, how do I do this?

A: Let $Z=\min(X,Y)$. Then, $$\mathbb{E}Z=\mathbb{E}(\mathbb{E}(Z|X))$$Now, $$\mathbb{E}(Z|X=k)=\mathbb{E}(\min (k,Y)|X=k),\ k=2,4,6$$ If $X\perp Y$, then $$\mathbb{E}(\min(k,Y)|X=k)=\mathbb{E}(\min(k,Y))=\int_{a}^k yf_{Y}dy+\int_{k}^b kf_Y(y) dy\\ \implies \mathbb{E}(\min(2,Y))=\int_{3}^5 2/2 dy=2$$ and similarl calculations for the others. So, $\mathbb{E}Z=\sum_{k}\mathbb{P}(X=k)\mathbb{E}(\min(Y,k))$

A: I'm guessing you're assuming that $X$ and $Y$ are independent. In which case, simply use the law of alternatives
$$E[min(X,Y)]=E[min(2,Y)|X=2]P[X=2]+E[min(4,Y)|X=4]P[X=4]+E[min(6,Y)|X=6]P[X=6]$$
$$=\frac{1}{3}(E[min(2,Y)]+E[min(4,Y)]+E[min(6,Y)])=\frac{1}{3}(E[2]+E[min(4,Y)]+E[Y])$$
Where I've used independence to get rid of the conditional expectations. All you have left is to compute what $E[min(4,Y)]$ is, again apply the law of alternatives using the events $\{Y\leq 4\}$ and $\{Y>4\}$.

A: $$\mathbb{E}\min\left(X,Y\right)=\sum_{n=1}^{3}\mathbb{E}\left(\min\left(X,Y\right)\mid X=2n\right)P\left(X=2n\right)=$$$$\frac{1}{3}\sum_{n=1}^{3}\mathbb{E}\left(\min\left(2n,Y\right)\mid X=2n\right)$$
Here $\min\left(2,Y\right)=2$ and $\min\left(6,Y\right)=Y$ so we
end up with:
$$\mathbb{E}\min\left(X,Y\right)=\frac{1}{3}\left[2+\mathbb{E}\left(\min\left(4,Y\right)\mid X=4\right)+\mathbb{E}\left(Y\mid X=6\right)\right]$$
If $X$ and $Y$ are independent then $$\mathbb{E}\left(Y\mid X=6\right)=\mathbb{E}Y$$
and $$\mathbb{E}\left(\min\left(4,Y\right)\mid X=4\right)=\mathbb{E}\min\left(4,Y\right)$$
The calculation of that I leave up to you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: longtblr caption format same as table environment I usually use a tblr oder tabularx within the table environment, but I have some long tables with (at least for me) not so easy formatting, which I place in a longtblr. If I place the longtblr within a table environment the page break is not working and the table is placed on a spot that doesn´t fit the content.
If I keep it the way I have it now, I need to adjust the formatting of my caption within tabularray (longtblr).
For table enviornment I use:
\usepackage[tableposition=top, font=small, labelfont=bf, belowskip=6pt, aboveskip=6pt]{caption}
\setlength{\abovecaptionskip}{6pt plus 3pt minus 2pt}
\setlength{\belowcaptionskip}{6pt plus 3pt minus 2pt}

For the tabularray I have so far:
\usepackage{tabularray}
\NewDocumentCommand \TblrAlignCenter { } { \centering }
\SetTblrStyle{caption-tag}{\bfseries}

The size and skip are still not the same and I don´t find how I can adjust it. Additionally, a multiline caption is not centered but aligned left. Would be great to get some insights.
For the size the following works (although I don´t know what each line does):
\ExplSyntaxOn
\prg_generate_conditional_variant:Nnn \tl_if_empty:n { e } { TF }
\let \IfTokenListEmpty = \tl_if_empty:eTF
\ExplSyntaxOff
\DefTblrTemplate{firsthead}{default}{%
  \addtocounter{table}{-1}%
  \IfTokenListEmpty{\InsertTblrText{entry}}{%
    \captionof{table}{\InsertTblrText{caption}}%
  }{%
    \captionof{table}[\InsertTblrText{entry}]{\InsertTblrText{caption}}%
  }%
}
\DefTblrTemplate{middlehead,lasthead}{default}{%
  \addtocounter{table}{-1}%
  \captionof{table}[]{\InsertTblrText{caption}(Continued)}%
}
\SetTblrTemplate{caption-lot}{empty}

Thx in advance!


text:
Q: Skip required validation and invoke the application I asked my question here but I think it lacks some obvious information. Hence I'm posting my question again.
I have a JSF form which has some required validation on h:inputText fields. When submitting the form I want to skip(or ignore) the required validation check and still invoke the application. I do want to do the form data validation and show the errors based on some condition.
Basically I want to skip the validations and invoke the application when the form is submitted using an ajax call and do the validation when the form is submitted via clicking a submit button.

A: Just put that condition straight in the required attribute.
<h:inputText ... required="#{someCondition}" />

It namely just accepts any EL expression like as many other attributes. Many starters think that you can only hardcode a "true" or "false" string in it. This is untrue.
For example, when you want to let it evaluate true only when the save button is actually pressed:
<h:inputText ... required="#{not empty param[save.clientId]}" />
...
<h:commandButton value="Cancel" ... />
<h:commandButton binding="#{save}" value="Save" ... />

(note: code is complete as-is, you do not need to bind it to a bean property)
This way the required attribute only evaluates true when the save button is pressed and it evaluates false for any other button or ajax event listener.


text:
Q: How to make a progress bar How would one go about making a progress bar in html/css/javascript. I don't really want to use Flash. Something along the lines of what can be found here: http://dustincurtis.com/about.html
All I really want is a 'progress bar' that changes to the values I give in PHP. What would be your though process? Are there any good tutorials on this?

A: Basically its this: You have three files: Your long running PHP script, a progress bar controlled by Javascript (@SapphireSun gives an option), and a progress script. The hard part is the Progress Script; your long script must be able to report its progress without direct communication to your progress script. This can be in the form of session id's mapped to progress meters, a database, or check of whats not finished.
The process is simple:

*

*Execute your script and zero out progress bar

*Using AJAX, query your progress script

*Progress script must somehow check on progress

*Change the progress bar to reflect the value

*Clean up when finished

A: I tried a simple progress bar. It is not clickable just displays the actual percentage. There's a good explication and code here: http://ruwix.com/simple-javascript-html-css-slider-progress-bar/

A: You can do it by controlling the width of a div via css. Something roughly along these lines:

That width value can be sent in from php if you so desire.

A: Here is my approach, i've tried to keep it slim:
HTML:

    50%

CSS:
.load{
    width: 50%;
    height: 12px;
    background: url( data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAALCAYAAAC+jufvAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwAAADsABataJCQAAABp0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuMTAw9HKhAAAAPklEQVQYV2M48Gvvf4ZDv/b9Z9j7Fcha827Df4alr1b9Z1j4YsV/BuML3v8ZTC/7/GcwuwokrG4DCceH/v8Bs2Ef1StO/o0AAAAASUVORK5CYII=);
    -moz-border-radius: 4px;
    border-radius: 4px;
}

.noload{
    width: 100px;
    background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAALCAYAAAC+jufvAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwAAADsABataJCQAAABp0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuMTAw9HKhAAAANUlEQVQYVy3EIQ4AQQgEwfn/zwghCMwGh8Tj+8yVKN0d2l00M6i70XsPmdmfu6OIQJmJqooPOu8mqi//WKcAAAAASUVORK5CYII=);
    -moz-border-radius: 4px;
    border-radius: 4px;
    border: 1px solid #999999;
    position: relative;
}

.loadtext {
    font-family: Consolas;
    font-size: 11px;
    color: #000000;
    position: absolute;
    bottom: -1px;
}

Fiddle: here

A: Infinitive progress bar using pure Javascript

Example http://fiddle.jshell.net/1kmum4du/

A: If you are using HTML5 its better to make use of <progress> tag which was newly introduced.

<progress value="22" max="100"></progress>

Or create a progress bar of your own.
Example written in sencha
if (!this.popup) {
            this.popup = new Ext.Panel({
            floating: true,
            modal: false,
            // centered:true,
            style:'background:black;opacity:0.6;margin-top:330px;',
            width: '100%',
            height: '20%',
            styleHtmlContent: true,
            html: '
Downloading Data

',

            });
}
this.popup.show('pop');

A: I used  this progress bar. For more information on this you can go through this link i.e customization, coding etc.

Hope this may be helpful to somenone.

A: http://jqueryui.com/demos/progressbar/
Check that out, it might be what you need.

A: You can use progressbar.js; Animated progress bar control and tiny chart (sparkline)
Demo and download link

HTML usage;

Javascript usage;
var progressBar;

window.onload = function(){

    progressBar = new ProgressBar("my-progressbar", {'width':'100%', 'height':'3px'});
    progressBar.setPercent(60);

}

A: var myPer = 35;
$("#progressbar")
    .progressbar({ value: myPer })
    .children('.ui-progressbar-value')
    .html(myPer.toPrecision(3) + '%')
    .css("display", "block");

A: I know the following doesn't work currently because browsers do not support it yet, but maybe some day this will help:
At the time of this post attr() on other properties than content is just a Candidate Recommendation1. As soon as it is implemented, one could create a progress bar with just one element (like the HTML 5 <progress/>, but with better styling options and text inside)

and pure CSS
.bar {
    position: relative;
    width: 250px;
    height: 50px;
    text-align: center;
    line-height: 50px;
    background: #003458;
    color: white;
}

.bar:before {
    position: absolute;
    display: block;
    top: 0;
    left: 0;
    bottom: 0;
    width: attr(data-value %, 0); /* currently not supported */
    content: '';
    background: rgba(255, 255, 255, 0.3);
}

.bar:after {
    content: attr(data-value) "%";
}

Here is the currently not working demo.

1 Cannot imagine why this isn't implemented in any browser. First I'd think that if you have the functionality for content already, it should not be too hard to extend that (but of course I don't really know to be honest). Second: The above is just one good example showing how powerful this functionality could be. Hopefully they start to support it soon, or it won't even be part of the final specification.

A: You can create a progress-bar of any html element that you can set a gradient to. (Pretty cool!) In the sample below, the background of an HTML element is updated with a linear gradient with JavaScript:
myElement.style.background = "linear-gradient(to right, #57c2c1 " + percentage + "%, #4a4a52 " + percentage + "%)";

PS I have set both locations percentage the same to create a hard line. Play with the design, you can even add a border to get that classic progress-bar look :)

https://jsfiddle.net/uoL8j147/1/

A: Though one can build a progress bar using setInterval and animating its width
For best performance while animating a progress bar one has to take into account  compositor only properties and manage layer count.
Here is an example:

function update(e){
  var left = e.currentTarget.offsetLeft;
  var width = e.currentTarget.offsetWidth
  var position = Math.floor((e.pageX - left) / width * 100) + 1;
  var bar = e.currentTarget.querySelector(".progress-bar__bar");
  bar.style.transform = 'translateX(' + position + '%)';
}
body {
  padding: 2em;
}

.progress-bar {
  cursor: pointer;
  margin-bottom: 10px;
  user-select: none;
}

.progress-bar {
  background-color: #669900;
  border-radius: 4px;
  box-shadow: inset 0 0.5em 0.5em rgba(0, 0, 0, 0.05);
  height: 20px;
  margin: 10px;
  overflow: hidden;
  position: relative;
  transform: translateZ(0);
  width: 100%;
}

.progress-bar__bar {
  background-color: #ececec;
  box-shadow: inset 0 0.5em 0.5em rgba(0, 0, 0, 0.05);
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  transition: all 500ms ease-out;
}
Click on progress bar to update value

A: You could recreate the progress bar using CSS3 animations to give it a better look.
JSFiddle Demo
HTML

CSS/CSS3
.outer_div {
    width: 250px;
    height: 25px;
    background-color: #CCC;
}

.inner_div {
    width: 5px;
    height: 21px;
    position: relative; top: 2px; left: 5px;
    background-color: #81DB92;
    box-shadow: inset 0px 0px 20px #6CC47D;
    -webkit-animation-name: progressBar;
    -webkit-animation-duration: 3s;
    -webkit-animation-fill-mode: forwards;
}

#percent_count {
    font: normal 1em calibri;
    position: relative;
    left: 10px;
}

@-webkit-keyframes progressBar {
    from {
        width: 5px;
    }
    to {
        width: 200px;
    }
}

A: You could use ProgressBar.js. No dependencies, easy API and supports major browsers.
var line = new ProgressBar.Line('#container');
line.animate(1);

See more examples of usage in the demo page.

A: If you need to show and hide progress bar inside your php and java script, then follow this step.Its a complete solution, no need of any library etc.
           //Design Progress Bar

               //Progress Bar inside your Page

    // Button to show and Hide Progress Bar
<input class="submit" onClick="Show()" type="button" value="Show" />
<input class="submit" onClick="Hide()" type="button" value="Hide" />

            //Java Script Function to Handle Button Event

Image link: Download image from here

A: You can use setInterval to create a progress bar.

function animate() {
  var elem = document.getElementById("bar");
  var width = 1;
  var id = setInterval(frame, 10);
  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width++;
      elem.style.width = width + '%';
    }
  }
}
#progress-bar-wrapper {
  width: 100%;
  background-color: #ddd;
}

#bar {
  width: 1%;
  height: 30px;
  background-color: orange;
}

<button onclick="animate()">Click Me</button>

A: I was writing up an answer to a similar question that got deleted, so I'm posting it here in case it's of use to anyone.
The markup can be dropped in anywhere and takes up 50px of vertical real estate even when hidden. (To have it take up no vertical space and instead overlay the top 50px, we can just give the progressContainerDiv absolute positioning (inside any positioned element) and style the display property instead of the visible property.)
The general structure is based on code presented in this Geeks for Geeks article.

const
  progressContainerDiv = document.getElementById("progressContainerDiv");
  progressShownDiv = document.getElementById("progressShownDiv");
let
  progress = 0,
  percentageIncrease = 10;

function animateProgress(){
  progressContainerDiv.style.visibility = "visible";
  const repeater = setInterval(increaseRepeatedly, 100);
  function increaseRepeatedly(){
    if(progress >= 100){
      clearInterval(repeater);
      progressContainerDiv.style.visibility = "hidden";
      progressNumberSpan.innerHTML = "";
      progress = 1;
    }
    else{
      progress = Math.min(100, progress + percentageIncrease);
      progressShownDiv.style.width = progress + "%";
      progressNumberSpan.innerHTML = progress + "%";
    }
  }
}
#progressContainerDiv{
  visibility: hidden;
  height: 40px;
  margin: 5px;
}

#progressBackgroundDiv {
  width: 50%;
  margin-left: 24%;
  background-color: #ddd;
}

#progressShownDiv {
  width: 1%;
  height: 20px;
  background-color: #4CAF50;
}

#progressNumberSpan{
  margin: 0 auto;
}

<button type="button" onclick="animateProgress()">Go</button>

A:

10%


text:
Q: R sf::st_convex_hull() losing sf class on data with multiple groups I am trying to create a 95% minimum convex polygon using sf in R. My code works fine as long as I only group my data on 1 variable, but when I group on two variables, the output loses its sf class and becomes a grouped_df instead.
Here is a toy dataset as an example
library(dplyr)
set.seed(12)
toy <- tibble::tibble(
    ID = rep(c(1,2), each = 10),
    year = rep(c(1,2), 10),
    lat = runif(20, 1, 10),
    long = runif(20, 1, 10)
  ) %>%
    sf::st_as_sf(., coords = c("long", "lat"))
toy %>%
  group_by(ID) %>%
  summarize(.groups = "keep") %>%
  mutate(cent = sf::st_centroid(geometry)) %>%
  sf::st_cast(to = "POINT") %>%
  mutate(dist = sf::st_distance(geometry, cent, by_element = TRUE)) %>%
  filter(dist <= quantile(dist, .95)) %>%
  summarize()  %>%
  sf::st_convex_hull() %>%
  class()

This gives the output I want. But when I try to group by two variables, the result loses the sf class.
toy %>%
  group_by(ID, year) %>%
  summarize(.groups = "keep") %>%
  mutate(cent = sf::st_centroid(geometry)) %>%
  sf::st_cast(to = "POINT") %>%
  mutate(dist = sf::st_distance(geometry, cent, by_element = TRUE)) %>%
  filter(dist <= quantile(dist, .95)) %>%
  summarize()  %>%
  sf::st_convex_hull() %>%
  class

Is there something in my code keeping me from being able to group on two variables?

A: It's because the second summarize is regrouping on ID. You need a .groups = "keeps" there to pass the same grouping through and then convert back to an sf object. Alternatively you could create a grouping variable mutate(grp = paste0(ID, year)) and do group_by(grp) .
toy %>%
  group_by(ID, year) %>%
  summarize(.groups = "keep") %>%
  mutate(cent = sf::st_centroid(geometry)) %>%
  sf::st_cast(to = "POINT") %>%
  mutate(dist = sf::st_distance(geometry, cent, by_element = TRUE)) %>%
  filter(dist <= quantile(dist, .95)) %>%
  summarize(.groups = "keep")  %>%
  sf::st_convex_hull() %>%
  st_sf()


text:
Q: complex properties with moq I have something like:
UserControl view = _regionManager.Regions[Constants.FormDisplayerRegion].Views.FirstOrDefault() as UserControl;

I've mocked the region manager. Regions is a IRegionCollection, View is a IViewCollection.
What is the best way of dealing with this sort of thing.

*

*Do I need to create mocks for Regions  and Views?

*Or would I be better off skipping moq and creating my own stub?

A: With the very little information you've provided, it is hard to give a sensible response. From your description though, I'd say you just need to Setup your region manager mock so it returns a collection of views. The views collection can be faked.


text:
Q: UnboundLocalError: local variable 'lead_x' referenced before assignment def gameLoop():
    gameExit = False

    lead_x_change = display_width/2
    lead_y_change = display_width/2

    lead_x_change = 0
    lead_y_change = 0

    while not gameExit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    lead_x_change = -block_size
                    lead_y_change = 0
                elif event.key == pygame.K_RIGHT:
                     lead_x_change = block_size
                     lead_y_change = 0
                elif event.key == pygame.K_UP:
                    lead_y_change = -block_size
                    lead_x_change = 0
                elif event.key == pygame.K_DOWN:
                    lead_y_change = block_size
                    lead_x_change = 0

        if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0 :
           gameExit = True

The unboundlocalerror reads:

local variable 'lead_x' referenced before assignment.

Please help anyone who knows how to tackle this. Thanks in advance!


text:
Q: What is nim's equivalent of Python's `sys.executable`? Following is the content of foo.py
import sys
print(sys.executable)

When I execute this, I can get the full path of the the Python interpreter that called this script.
$ /mingw64/bin/python3.9.exe foo.py
/mingw64/bin/python3.9.exe

How to do this in nim (nimscript)?

A: If you want to do that in Nim (not NimScript), you can take compiler executable path using https://nim-lang.org/docs/os.html#getCurrentCompilerExe
import os

echo getCurrentCompilerExe()

A: Nim is compiled, so I assume you want to get the path of the application's own binary? If so, you can do that with:
import std/os

echo getAppFilename()

A: The question mentions NimScript, which has other uses in the Nim ecosystem, but can also be used to write executable scripts instead of using, e.g., Bash or Python. You can use the selfExe proc to get the path to the Nim executable which is running a NimScript script:
#!/usr/bin/env -S nim --hints:off
mode = ScriptMode.Silent

echo selfExe()

After saving the above as test.nims and using chmod +x to make the file executable, the script can be invoked to show the path to the current Nim executable:
$ ./test.nims
/home/.choosenim/toolchains/nim-1.4.8/bin/nim


text:
Q: VSS fails on creating snapshot - various VSS writers failed state, timed out I have several errors in my log. My environment is:

*

*Server 2008 R2 (virtual machines on Server Core stack).

*AppAssure Replay 4 as the backup solution.

*In the evening backup goes okay usually, snapshots get created fine.

*During the day and other times, it's a different story: Snapshots fail: numerous writers get into a failed state, a timeout.

*AppAssure's response at one point in time was to restart the Agent service. That solved the problem for a short time, but when I tried it today, that didn't work at all.

I've tried to look high and low for a way to just reset the writers - I thought they were controlled by the VSS Service/Microsoft Shadow Copy Provider, but apparently not. Should I have the Hyper-V Shadow Copy Provider running, over the Microsoft Shadow Copy Provider?
My errors, explicitly:

*

*Unable to take VSS snapshot and transfer data for 'C: ...'Error taking VSS Snapshot of volume(s): AsyncWait for DoSnapShotSet failed - Snapshot vetoed by provider.

*Event ID: 12289, VSS. 'Volume Shadow Copy Service error: unexpected DeviceIOControl (\?\Volume{guid} hr=9x80070057, The parameter is incorrect. Operation: Automatically choosing a different volume. Professing EndPrepareSnapshots
Context: Execution, System Provider

*Event ID: 22, volsnap:
The shadow copy storage volume specified for shadow copies on volume C: could not be added.

*A generic error when I try to view the 'Shadow Copies' tab on my C: drive.

*Running 'DiskShadow list writers status' gives me the status code 7, and what it means specifically: 'VSS_WS_FAILED_AT_PREPARE_BACKUP'.
I believe, obviously that all these errors are related. Most solutions I see say to stop the VSS and related services, unregister some modules, and register them again as a way of resetting the writers (for Server 2003). I disagree with this solution, there is no reason why I shouldn't be able to solve this without needing to reboot the box; especially in Server 2008.
Any and all help would be greatly appreciated, or at the very least letting me know that I'm perhaps overloading I/O, and to space out my snapshots (they are taken every hour on this server with errors: it's a file-server)


text:
Q: Real Analysis, Folland Problem 5.1.8 Normed Vector Spaces Background information:
Proposition 3.14 - If $\nu_1,\nu_2$ are complex measures on $(X,M)$, then $|\nu_1 + \nu_2|\leq |\nu_1| + |\nu_2|$
Theorem 5.1 - A normed vector space $X$ is complete if and only if every absolutely convergent series in $X$ converges.
Let $(X,M)$ be a measurable space, and let $M(X)$ be the space of complex measures on $(X,M)$. Then $\lVert \mu \rVert = |\mu|(X)$ is a norm on $M(X)$ that makes $M(X)$ into a Banach space. (Use Theorem 5.1.)
Attempted proof: For each $\nu\in M(X)$ there is a finite measure $\mu$ on $X$ and a function $f\in L^1(\mu)$ such that $d\nu = fd\mu$. Note that $\lVert \nu \rVert = |\nu|(X) = \int |f|d\nu$.
If $a\in\mathbb{C}$ then $\lVert a\nu\rVert = |a\nu|(X) = \int|af|d\nu = |a|\int |f|d\mu = |a||\nu|(X) = |a|\lVert \nu\rVert$. The triangle inequality follows from proposition 3.13. Therefore $\lVert \cdot \rVert$ is a norm on $M(X)$.
I fail to see how we use theorem 5.1 and show that the norm on $M(X)$ makes $M(X)$ into a Banach space. Any suggestions is greatly appreciated.

A: Suppose that $\{\mu_n\}$ is a sequence of measures such that $\sum_{n=1}^{\infty}||\mu_n||<\infty$, and define a new measure $\mu$ by
$$ \mu(E)=\sum_{n=1}^{\infty}\mu_n(E) $$
This sum converges absolutely, because
$$ \sum_{n=1}^{\infty}|\mu_n(E)|\leq \sum_{n=1}^{\infty}|\mu_n|(E)\leq \sum_{n=1}^{\infty}||\mu_n||<\infty $$
Moreover $\mu(\emptyset)=0$, and if $E=\cup_{j=1}^{\infty}E_j$ with the $E_j$ pairwise disjoint, then
$$ \mu(E)=\sum_{n=1}^{\infty}\mu_n(E)=\sum_{n=1}^{\infty}\sum_{j=1}^{\infty}\mu_n(E_j)=\sum_{j=1}^{\infty}\sum_{n=1}^{\infty}\mu_n(E_j)=\sum_{j=1}^{\infty}\mu(E_j)$$
by Fubini's theorem.
Therefore $\mu$ is a measure. Finally,
$$ ||\mu-\sum_{n=1}^N\mu_n||\leq \sum_{n>N}||\mu_n||$$
which tends to zero as $N\to\infty$. Therefore $\sum_n\mu_n$ converges to $\mu$, which proves that $M(X)$ is complete.


text:
Q: silverlight databinding not working from scriptable member We have exposed a silverlight page as a scriptable object. It has one scriptable member.
The page's datacontext is a viewmodel object, of typ TestViewModel with one property string Description. The TestViewModel implements INotifyPropertyChanged.
The page has a textbox bound to this Description property
When Description is set to some value from within method marked with the ScriptableMember attribute, the textbox does not change
I also have a button. When I set the Description property from the click event handler of the button, the textbox changes on my page, showing the correct value.
Any reason why databinding does not work from a scriptable member and if there is a way to make it work?

A: You have to make sure that "HtmlPage.RegisterScriptableObject(string scriptKey, object instance)" is set on the right place. Place it in the constructor of the xaml.cs of the page where the method with the ScriptableMember attribute is used.


text:
Q: Scipy.Minimize, how to share the same objects among objective function and constraints? The objective function is
def obj(w):
    a = f(w)
    return g(a)

The constraint function is
def cons(w):
    a = f(w)
    return a - 1

The function f(w) in both obj(w) and cons(w) is calculation heavy. How to calculate f(w) just once for every guess of w please?
Thanks.

A: In general you can access variables from given function outside of it, using this mechanism:
def f(a):
    out = a * a + 2
    f.inside = out
    return out
f.inside = None

print(f(1))
print(f.inside)

or using class.


text:
Q: CodeIgniter deleting with db doesnt work I am doing an ajax call..which doesnt output any mysql errors..Basically, I am trying to delete two records...
  public function task_delete($task_id)
     {
            $this->load->database();
            $this->db->delete('task_pages', array('id' => $task_id));
            $this->db->delete('tasks', array('id' => $task_id));

       }

This is the model..
And this is the controller..
class Ajax extends CI_Controller {

       public function delete()
      {
          $this->load->database();
          $this->load->model('tasks_model','task_delete');
          $result=$this->task_delete-> task_delete($this->input->post('myId'));
          echo $result;
      }

}

Where does my code fails?
UPDATE:
I get an error..the method deleteTask is being called on none object

A: Assuming your model is also called task_delete and the function you want to call is deleteTask, then you have given the function in your model the wrong name, it should be declared as this:
public function deleteTask($task_id)


text:
Q: Docker Swarm - Can't pull from private registry I'm running a service on a Swarm cluster, thanks to docker stack deploy --with-registry-auth and this compose file:
version: "3.1"
services:
  builder-consumer:
    image: us.gcr.io/my-gcloud-project/my/image:123
    stop_grace_period: 30m
    volumes:
      - [...]
    environment:
      - [...]
    deploy:
      mode: global
      placement:
        constraints:
          - node.role == worker
    secrets:
      - [...]
secrets:
  [...]

This works fine when I deploy, but when I add a worker node to the swarm later on, the new worker can't pull the image required to run the task. The system logs report this:

level=error msg="Not continuing with pull after error: denied:
  Permission denied for \123\" from request
  \"/v2/my-gcloud-project/my/image/manifests/123\". "
level=info msg="Translating \"denied: Permission denied for
  \\"123\\" from request
  \\"/v2/my-gcloud-project/my/image/manifests/123\\". \" to
  \"repository us.gcr.io/my-gcloud-project/my/image not found: does not
  exist or no pull access\""
level=error msg="pulling image failed" error="repository
  us.gcr.io/my-gcloud-project/my/image not found: does not exist or no
  pull access" module="node/agent/taskmanager" node.id=...
  service.id=... task.id=...
level=error msg="fatal task error" error="No such image:
  us.gcr.io/my-gcloud-project/my/image:123@sha256:..."
  module="node/agent/taskmanager" node.id=... service.id=... task.id=...

However, when I manually run docker pull on that machine, it works fine, since every machine in the cluster is authenticated to my private Google Registry, thanks to docker login.
Thus my questions are:

*

*Why can't the added worker pull from the private registry?

*What does --with-registry-auth do exactly?

Thanks a lot
Note: the nodes are running Ubuntu 16.04.2 LTS and the Docker version is:
Server:
 Version:      17.04.0-ce
 API version:  1.28 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   4845c56
 Built:        Mon Apr  3 18:07:42 2017
 OS/Arch:      linux/amd64
 Experimental: false

A: In my case I was not running the stack with "--with-registry-auth", so I shuted down the instances, and I started again the manager with that option, and now it works


text:
Q: How to add blog post and show post in Django web blog I am learning Django framework using djangogirls tutorial, reading this tutorial, I try to  make a blog. Now I want to add some blog post from forms .py file and show it in this blog but unable to do that, How can I do that in my blog ? please help with details.

A: This is rather a generic approach.I hope this helps.
A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget.
You can specify a widget as :
from django import forms

class CommentForm(forms.Form):
    name = forms.CharField()
    url = forms.URLField()
    comment = forms.CharField(widget=forms.Textarea)

Many widgets have optional extra arguments; they can be set when defining the widget on the field. In the following example, the years attribute is set for a SelectDateWidget:
from django import forms

BIRTH_YEAR_CHOICES = ('1980', '1981', '1982')
FAVORITE_COLORS_CHOICES = (
    ('blue', 'Blue'),
    ('green', 'Green'),
    ('black', 'Black'),
)

class SimpleForm(forms.Form):
    birth_year = forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES))
    favorite_colors = forms.MultipleChoiceField(required=False,
        widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES)


text:
Q: Javascript basic text only loading indicator I would like to use a basic, text only, loading indicator. So instead of using an image, I'd like to just show a text:
Loading ...

While some AJAX request is taking place. I would like this text to be changing like this:
Loading ...

Then:
Loading ..

Then:
Loading .

Then:
Loading ..

Then:
Loading ...

And so on. Any ideas? I can use jquery for this.

A: You could do something like this (adapt to your needs):
loading

jQuery
function animateIt() {

 var text = '...';
 jQuery({count:0}).animate({count:text.length}, {
     duration: 2000,
     step: function() {
         $(".dots").text( text.substring(0, Math.round(this.count)) );
     },
     complete: function() {
         animateIt();
     }
  });
}

animateIt();

Here's an example: http://jsfiddle.net/uZkzX/


text:
Q: I want to be able to have multiple widgets in a page, it isn't working though. I want to have containers like the image below. It only allows me text? This is the code below, please much appreciated if you can at least try. thank you |
I am trying to create an app where I can have multiple widgets in one page. I want to make apps kind of like the image below here:
That I Want Widgets To Look Like or Similar To It

This Is How My App Looks Like Blank

If you guys can help me figure out what I need to do that will be much appreciated beyond everything in existence. | Also, I have followed this tutorial. But, as you all can observe he only has a string of text as "Hello", "CART", "MENUE", "SETTING", "FAVORITES", Which are all text strings. I want to make widgets inside this pages, like the first image. Please I been trying to figure this out for the past 4 and a half weeks and  I cant get to see how to make it possible.
import 'package:curved_navigation_bar/curved_navigation_bar.dart';
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
final List<Widget> _options = [
  const _HomeScreenPage(),
  const _chatScreenPage(),
  const _locateScreenPage(),
  const _locationScreenPage(),
  const _profileScreenPage(),
];

int _currentIndex = 0;
@override
Widget build(BuildContext context) {
 return Scaffold(
  appBar: AppBar(
    title: const Text(
      '               S|D',
      style: TextStyle(
        fontSize: 48,
        fontFamily: 'Subway',
      ),
    ),
    elevation: 0,
    backgroundColor: Colors.black,
    foregroundColor: Colors.cyan,
  ),
  body: Container(
    color: Colors.black87,
    child: Center(
        child: Text(
          _options[_currentIndex],
          style: const TextStyle(
              color: Colors.cyanAccent,
              fontWeight: FontWeight.bold,
              fontSize: 40),
        ),
        ),
  ),
  bottomNavigationBar: CurvedNavigationBar(
    buttonBackgroundColor: Colors.black54,
    backgroundColor: Colors.black87,
    color: Colors.black,
    items: const <Widget>[
      Icon(
        Icons.home,
        color: Colors.cyan,
      ),
      Icon(
        Icons.people_sharp,
        color: Colors.cyanAccent,
      ),
      Icon(
        Icons.my_location_sharp,
        color: Colors.cyanAccent,
      ),
      Icon(
        Icons.car_repair,
        color: Colors.cyanAccent,
      ),
      Icon(
        Icons.person_pin,
        color: Colors.cyan,
      ),
    ],
    onTap: (index) {
      setState(() {
        _currentIndex = index;
      });
    },
  ),
);
}
}

class _HomeScreenPage extends StatelessWidget {
const _HomeScreenPage({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
 return Column(
  children: [
    Expanded(
        flex: 7,
        child: Container(
          color: Colors.cyan,
        ))
  ],
);
}
}

class _chatScreenPage extends StatelessWidget {
const _chatScreenPage({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
  return Container();
}
}

class _locateScreenPage extends StatelessWidget {
const _locateScreenPage({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Container();
}
}

class _locationScreenPage extends StatelessWidget {
const _locationScreenPage({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Container();
}
}

class _profileScreenPage extends StatelessWidget {
const _profileScreenPage({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Container();
}
}

A: You can use the IndexedStack widget inside your homePage build method
replace
  body: Container(
color: Colors.black87,
child: Center(
    child: Text(
      _options[_currentIndex],
      style: const TextStyle(
          color: Colors.cyanAccent,
          fontWeight: FontWeight.bold,
          fontSize: 40),
    ),
    ),
),

to
   body: IndexedStack(
    children: _options,
    index: _currentIndex,
  ),


text: Q: ACL lost after save the file using gedit editor I have a file that have ACL info, added by setfacl -m u:user:rw file. If I use gedit(started by root) open this file, make some edit and then save the file, this file's ACL info will be lost, the vim does not have that problem, what going wrong?


text:
Q: Use another theme (postmark) with compodoc I would like to use the postmark theme with compodoc (https://compodoc.github.io/website/guides/themes.html).
However, it does not work!
I have already tried
npm run doc:buildandserve --theme Postmark

npm run compodoc --theme postmark

I get the error Provided source folder postmark was not found in the current directory
Do I have to download the theme? Where do I find it?

A: I may be late in answering this.  I just tried it today and it was working. Try the following command in Terminal of the project directory
compodoc -p src/tsconfig.app.json --theme postmark

And this will be the result

Method 2: If you are using script task in your package.json

command:

"compodoc": "npx compodoc -p src/tsconfig.app.json --theme postmark -n
  \"Project Name\""

Hope this help.


text:
Q: ASP.NET MVC 5 Active Directory Authentication Get User Group I have an application that authorizes against an active directory and this working perfectly. Now what I am trying to do is get the user that is login group name.
I have this method here:
[HttpPost]
        public ActionResult Login(LoginClass model, string ReturnUrl)
        {

            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(ReturnUrl) && ReturnUrl.Length > 1 && ReturnUrl.StartsWith("/")
                        && !ReturnUrl.StartsWith("//") && !ReturnUrl.StartsWith("/\\"))
                    {
                        return Redirect(ReturnUrl);
                    }
                    else
                    {
                        string[] test = Roles.GetRolesForUser();
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect");
                }
            }

            return RedirectToAction("Index", "Home");
        }

now this line: string[] test = Roles.GetRolesForUser(); returns empty. I put a breakpoint and found this message:
The Role Manager feature has not been enabled

I have also added this to my web.config:
<roleManager enabled="true" />

inside system.web inside configuration
What am I doing wrong, I know the groups exist and I just can't get them or how would get the users OU (organization unit)


text:
Q: I am not able to pause TTS(specifically Earcon) when an Earcon(part of TTS) is running I want to be able to pause it in between and resume it from the moment i paused it. What can i do to achieve it?
I am working on Android Studio using Java. I am able to pause TTS easily but its Earcon module is not pausing in the middle of speaking.
for (int i = 1; i <= ques; i++) {
    if (!gameRunning) break;
    // whistle.start();
    textToSpeech.playEarcon("[bark]", TextToSpeech.QUEUE_ADD, null);
    Log.d(TAG, "level3: bark started");
    //while (whistle.isPlaying()) ;
    while (textToSpeech.isSpeaking());
    Log.d(TAG, "level3: bark over");
}

I expect .playEarcon to pause when I want but instead it completes the whole loop and then it stops... i want it to stop in the loop itself and run the loop again for Earcon.


text:
Q: Change NSUrl to QLPreviewItem How can I convert NSUrl to QLPreviewItem? In the QLPreviewItem.h, it is written that the below category makes NSURL instances as suitable items for the Preview Controller:
@interface NSURL (QLPreviewConvenienceAdditions) <QLPreviewItem>

How can I use it if in my code I have:
- (id <QLPreviewItem>) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger) index
{
        NSString *path=[[NSBundle mainBundle] pathForResource:[filenamesArray objectAtIndex:index] ofType:nil];
        NSURL *url =  [NSURL fileURLWithPath:path];
        return //QLpreview item from URL;
}

A: You can just return the NSURL, it will work.
I've been using this:
if([downloadData writeToURL:self.fileUrl options:NSDataWritingAtomic error:&error])
(...)

And then I used the same URL as QLPreviewItem:
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    return self.fileUrl;
}

A: Or using Swift:
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
    let resumeUrl = Bundle.main.url(forResource: "resume", withExtension: "docx")!
    return resumeUrl as QLPreviewItem
}


text:
Q: -bash: ORACLE_HOME: command not found the following error raise when i login to oracle account on Company Oracle CentOS linux server :

-bash: ORACLE_HOME: command not found

# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

# User specific aliases and functions
ORACLE_BASE=/u01/app/oracle;export ORACLE_BASE;
ORACLE_HOME=$ORACLE_BASE/product/10.2.0/db_1;export ORACLE_HOME;
ORACLE_SID=CPS;export ORACLE_SID;
ORACLE_TERM=xterm;export ORACLE_TERM;
PATH=/usr/sbin:$PATH;export PATH;
PATH=$ORACLE_HOME/bin:$PATH;export PATH;

LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib;export LD_LIBRARY_PATH;
CLASSPATH=$ORACLE_HOME/JRE:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib;export CLASSPATH;

A: The exports are bad:
ORACLE_BASE=/u01/app/oracle;export ORACLE_BASE;

shoud be:
export ORACLE_BASE=/u01/app/oracle

and so on.

A: You probably want to change exports as @Florin Ghita wrote, source .bashrc:
. ~/.bashrc

and then check
echo $ORACLE_HOME

to see if the variable is set.

A: ORACLE_BASE=/u01/app/oracle;export $ORACLE_BASE;
ORACLE_HOME=$ORACLE_BASE/product/10.2.0/db_1;export $ORACLE_HOME;
ORACLE_SID=CPS;export $ORACLE_SID;
and so on .....
also check u opened a new shell before checking if the environment variables are set correctly ..


text:
Q: Django deleted migrations directory In my project directory while I was trying to update my code I have accidentally remove the migrations folder of my app, now that I have modified the models and when I use python manage.py makemigrations I get the following message:
Operations to perform:
    Apply all migrations: app_label
Running migrations:
   No migrations to apply.

I have already run this before migrating python manage.py makemigrations app_label

A: You could just reset your migrations to before your initial migrate and start over.  This doesn't delete data in the database, but rather resets the tracking of your migrations.  If all of your databases are already migrated to the same level, then you can start over in your migration tracking.
There is a StackOverflow question here that already addresses it:
How to reset migrations in Django 1.7?
In short,
./manage.py migrate --fake <app-name> zero

This resets the tracking to prior to your initial migration.
And then,
./manage.py makemigrations <app-name>
./manage.py migrate <app-name>

Which recreates the initial migration and applies it.
As always, if your data is important, make a backup first.

A: Just create new directory called migrations inside your app directory.
Then inside that folder create empty folder named __pycache__ and a empty file named __init__.py. Then just make the migrations and migrate


text:
Q: (iphone) basic memory management question I have used following 2 patterns to create a view.
@property (retain, nonatomic) SomeView* someView;

...

// First pattern
self.someView = [[SomeView alloc] initWithFrame frame];

// Second pattern
SomeView* aSomeView = [[SomeView alloc] initWithFrame];
self.someView = aSomeView;
[aSomeView release];

Now, looking back at this code, the first pattern's method should be changed to
self.someView = [[[SomeView alloc] initWithFrame frame] autorelease];

shouldn't it?
I feel dumb :(

A: Look at it like this:
[[SomeView alloc] initWithFrame: frame];

The above line creates an object and gives it a retain count of 1.
self.someView = [[SomeView alloc] initWithFrame: frame];

This line leaves it with a retain count of two, because the someView property is declared with retain:
@property (**retain**, nonatomic) SomeView* someView;

So, doing it this way leaves your someView property pointing to an object with retain count of 2. You can do it this way if you add an autorelease call to it:
self.someView = [[[SomeView alloc] initWithFrame: frame] autorelease];

Your second pattern is better, if you ask me. You create an object with a retain count of one. You assign it to a retaining property (now it has a retain count of 2) and then you release the original variable, leaving the object again with a retain count of 1. It's three lines where you might want only one, but it makes sense in the right context. Additionally, it's usually best to avoid using autorelease outside of an alloc or copy method since its usually an indication you don't fully understand memory management in Obj-C.
And as a commenter said in the comments to the question, don't feel dumb. None of this is intuitive at first. Nobody picks up a guitar and plays like Hendrix their first time.

A: Yes, you are right. autorelease means "release a bit later".

A: Yes, I think you should change that. With self.someView = you are calling the setter which increases the retain count.

A:
Now, looking back at this code, 1's method should be changed to self.someView = [[[SomeView alloc] initWithFrame frame] autorelease];
  shouldn't it?

correct
a)
SomeView * view = [[SomeView alloc] initWithFrame:frame];
self.someView = view;
[view release], view = nil;

b)
self.someView = [[[SomeView alloc] initWithFrame:frame] autorelease];

many people prefer b, simply because it is less to type.
i prefer an approach similar to a because:

*

*defects (such as over-releasing) are often exposed near the call site, rather than when the pool is destroyed (this often means you have to load up Instruments in Zombie mode to locate the callsite)

*it performs better and minimizes memory usage (in general, but not much in this specific case)

*you have more opportunity to check for invalid states and results

*you have a chance to init/configure the view/object for its usage before adding it to self, which is usually preferred


text:
Q: Parsing relative links on a html page
I'm trying to parse a page to find all valid urls, but here is a problem. There are 3 types of links on a page: url (_http://site.com/dir/page.html), absolute uri (/dir/page.html) and relative uri (dir/page.html without starting slash). Probably i'm wrong about terminology, i'm not an html coder. But that's not the case in any way.
I need to find and collect all urls (i.e. _http://site.com/dir/subdir/page.html and so on). And here is the problem. If there is a page _http://site.com/dir/page.html with a link like link it's supposed to bring us to _http://site.com/dir/subdir/page.html. But if there is <base href="/"> in the head section of a page, same link leads to _http://site.com/subdir/page.html i.e. different from _http://site.com/dir/subdir/page.html.
The question is if there can be anything else in html code on a page that can influence target url.
Thanks in advance.

A: In HTML as such there is nothing else beside the href base You mentioned
What could become tricky and should be considered is that there might be linkage on page made by script execution, so things like window.location.href = something. This would be easy if the links are clearly stated, but they might be also computed by the script and then You could miss the link or mis-read it by using simple parsing.

A: Your problem is actually how url linking in html works, please read: http://www.webdevelopersnotes.com/design/relative_and_absolute_urls.php3 .  So say you're in /admin/ and you need /admin/login.aspx .  My relative URL is login.aspx, while my absolute is /admin/login.aspx make sense?
So basically what I'm saying is consider which directory your link is being served out of.  That will determine the type and content of the url link to use.
Other than that, as stated already, jscript and server side code can also do linking.


text:
Q: Sign In With Google + People API I'm trying to create a login button "Sign In With Google" and get additional information about the user (name, email + gender and date of birth) using the People API.
I have done this before with https://apis.google.com/js/api.js.
This library provides tools for authorization and requests, but Google stops support and offers to use a new option.
I followed this guide Load the client library + Display the Sign In With Google button.
In the end result (after decoding the JWT token) I get the name and email. To send a request to People API, I need an access_token. Where and how can i get it without server-side scripts?
Can someone tell me how to send a request to People API with JS in this case?

A: There's demo javascript code on the People API docs website:
https://developers.google.com/people/quickstart/js
It lists the account's contacts, but you can easily modify that to only get the user's details.

A: I have checked the documentation from the new Google Sign in Library and it seems that the access token is not included in the JWT token that is retrieved, it seems that this has been changed to handle the information gathered from the token response as documented here.


text:
Q: Is there a way for Google Cloud Python Authentication via the JSON keyfile itself and not the file path? So for Ruby, you can set the JSON content into the environmental variable of GOOGLE_CLOUD_KEYFILE_JSON. I am trying to find the documentation for Python, but all I can see is documentation loading the authentication for file path.

A: I found a way to do it, but I want to know if there is a better way. Using the google-auth library, I can do something like this:
import json

from google.cloud import bigquery
from google.oauth2 import service_account

"""
Securely get content of JSON file from protected memory because having
the credential file plainly on the filesystem is unsafe
"""

service_account_info = json.loads(json_file_content_string)
credentials = service_account.Credentials.from_service_account_info(service_account_info)
client = bigquery.Client(project='secret-proj', credentials=credentials)

More about the library here: https://google-auth.readthedocs.io/en/latest/reference/google.oauth2.service_account.html

A: You should be able to read the environment variables on Python using the following:
import os
print os.environ['GOOGLE_CLOUD_KEYFILE_JSON']

A: Nope, you need to set GOOGLE_APPLICATION_CREDENTIALS with a path to the JSON file instead.
See https://cloud.google.com/docs/authentication/getting-started for more details.


text:
Q: Javascript Rock, Paper, Scissors I followed the tutorial on Javascript on http://www.codecademy.com and one part was to create a rock, paper, scissors game. After I finished it I figured I would redesign it a bit to use on my own. So I did this:
<!DOCTYPE html>

Choose between rock, paper or scissors:

        <input id="userChoice">
        <button onClick="Run()">Choose</button>

But it doesn't work, I get undefined for compare, computerChoice, userChoice and that there isn't anything that becomes stored in value.
What's wrong?

A: You need to put all of the content of the script in a function, try this. It is trying to use the variables before they are set by the logic at the beginning since the logic at the beginning is never called:)
    function run(){

    var userChoice = document.getElementById("userChoice").value;

    if (userChoice != "rock" && userChoice != "paper" && userChoice != "scissors"){
        alert("Your choice was not rock, paper or scissors");
        userChoice = prompt("Do you choose rock, paper or scissors?");
    }
    var computerChoice = Math.random();
    if (computerChoice < 0.34) {
        computerChoice = "rock";
    } else if(computerChoice <= 0.67) {
        computerChoice = "paper";
    } else {
        computerChoice = "scissors";
    }

    var compare = function(choice1, choice2) {
        if (choice1 == choice2) {
            return "The result is a tie!";
        } else if (choice1 == "rock") {
            if (choice2 == "scissors") {
                return "Rock wins";
            } else {
                return "Paper wins";
            }
        } else if (choice1 == "paper") {
            if (choice2 == "rock") {
                return "Paper wins";
            } else {
                return "Scissors wins";
            }
        } else if (choice1 == "scissors") {
            if (choice2 == "paper") {
                return "Scissors win";
            } else {
                return "Rock wins";
            }
        }
    }
        document.getElementById("pcc").innerHTML = "Computer: " + computerChoice;
        document.getElementById("result").innerHTML = compare(userChoice, computerChoice);
    }

A: You should remove the  tags and correctly close your second paragraph tag like so:


text:
Q: Reschedule Task after Completion in Java I want to develop an app with Java that will fetch some files in the Internet every 24h after it has finished. It will start every time on startup and will be on Window's task bar.
Steps:

*

*Start the GUI (windows startup);

*Automatic trigger to perform task;

*Do the job;

*Print task results on the GUI;

*After the task is completed, schedule the task for 24h from now;

And the steps 3-5 would be repeated every time the app has performed its task.
I'm facing a lot of problems with the usage of Timer and TimerTask.
I was thinking about an architecture similar to this:
Main Runner Class (Just initialization of GUI and jobs);
GUI handler Class;
Job Performer Class;
How can should I proceed to schedule the Job Performer Class to perform again after it has completed its goal?


text: Q: How can i add common interceptor class which will be called even before calling Rest Controller in the existing spring boot microservices project? I need to create a common interceptor class in the existing spring boot microservice project that will check & generate the tracing id or UUID (if one isn't present) which will propagate through out the execution path for tracing purpose. Now, how do i ensure that each service/api call will call this common interceptor class first & check the UUID then fwd the request to the controller so that tracing can be achieved. Also, where should i implement this. I mean, common interceptor should get called after the api gateway or where? i Please help me.


text:
Q: I want to set a background color behind my progress bar that won't grin all the time I have an animated progress bar, the normal one in example 1.  But the one I want will be like in example 2, but the one in the back will play non-stop.
example 1

example 2

.progress {
    display: flex;
    height: 1rem;
    overflow: hidden;
    line-height: 0;
    font-size: .5625rem;
    background-color: #e4e7ea;
    border-radius: 4px;
}

.progress-bar {
    display: flex;
    flex-direction: column;
    justify-content: center;
    overflow: hidden;
    color: #fff;
    text-align: center;
    white-space: nowrap;
    background-color: #348fe2;
    transition: width .6s ease;
}

I tried putting a background, but I'm having problems with the animation.

A: The default css for the animation is:
.progress-bar-striped {
    background-image: linear-gradient(45deg,rgba(255,255,255,.15)
    25%,transparent 25%,transparent 50%,rgba(255,255,255,.15)
    50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);
}

You can mess with that to change the animation itself.
Or / and you can just change the background color:
.bg-indigo {
    background-color: black;
}

In both cases you have to overwrite the exsisting css.


text:
Q: How do I remove the glow on plank dock when an app is focused on? I want to remove this glow on plank anybody know how?

I opened the dock.theme file and the only way i could make it disappear was to make TopPadding=-12 which will just basically make my whole dock transparent.


text:
Q: Check if stdin has bytes pending (for escape sequences) In plain C, how can check if standard input has bytes pending without blocking?
The reason for this is handling escape sequences which are multi-byte.
For example, if I use getchar() and the user presses Ctrl-Up Arrow, then 3 bytes are immediately placed in standard input: 1B 4F 41, however getchar() only reads ONE of those bytes. I need to read all three before continuing on. Different escape sequences are of different length, so the logic is that if the first character is an escape character then I read ALL characters currently in the buffer and then process that as an escape unit. But I can't do that with getchar() because it will block when it reaches the end of the buffer. I need to know how many characters are in the buffer.

A: There's no such provision in standard C; you need to use OS-specific calls to either do non-blocking reads or, as I think is more appropriate here, to read bytes from the input immediately rather than wait for a newline. For the latter, see
setvbuf not able to make stdin unbuffered
Note:

the logic is that if the first character is an escape character then I read ALL characters currently in the buffer and then process that as an escape unit

That really isn't the way to do it, and will fail if keys are pressed rapidly or are autorepeated, or, say,  you're reading from a key log file. Each byte determines how many more bytes of escape sequence there are; you should read conditionally based on what you have already seen.


text:
Q: Injectivity of rank function Let $R$ be well founded and set like on $A$. I want to show that $R^{*}$ is a total order iff $rank_{A,R}(y)=\sup\{rank(x)+1|$ $xRy$ $\wedge{x\in{A}}\}$ is injective. Here $R^{*}$ is the transitive closure of $R$ in $A$.
I proved the forward direction. For the backward direction I looked at $X= \{a\in{A}|\exists{y}\in{A}(y\neq{a}$ $\wedge$ $\neg{yR^{*}a}$ $\wedge$ $\neg{aR^{*}y})\}$. If $X$ is empty then we are done. So suppose not. Since $R^{*}$ is also well founded it has a $R^{*}$ minimal element, say $a$. Now fix $b$ s.t. $a\neq{b}$, $\neg{bR^{*}a}$, $\neg{aR^{*}b}$.
Since $a\neq{b}$, we have that $rank(a)\neq{rank(b)}$. Now we know that $rank(a)$, ${rank(b)}$ are ordinals. I showed that $rank(a)>{rank(b)}$ leads to a contradiction. However I can't figure out how to show that $rank(a)<{rank(b)}$ also leads to contradiction.
Any ideas on how I can get a contradiction?

A: Here's a similar, but slightly more direct approach. Instead of assuming towards contradiction, assume the contrapositive. Suppose that $R^*$ is not a linear order. Let $a,b$ two elements incomparable by $R^*$, such that:

*

*$\alpha=\operatorname{rank}(a)$ is the least rank of an element that has an incomparable element in $A$, such that the minimal element of $\{\operatorname{rank}(x)\mid x\text{ and }a\text{ incomparable}\}$ is the minimal possible.

*$\beta=\operatorname{rank}(b)$ is the least rank of an element incomparable with $a$.

Now if $\alpha>\beta$ then this is a contradiction to the choice of $a$. If $\alpha<\beta$, then for every $b'$ such that $b'\mathrel{R^*}b$ we have that $a$ and $b'$ are comparable. Pick any such $b'$ of rank $\geq\alpha$, then $a\mathrel{R^*}b'$ and therefore $a\mathrel{R^*}b$. This is a contradiction to the choice of $b$.
Therefore $\alpha=\beta$. $\qquad\square$


text:
Q: Windows 7 Home Premium missing administrator account A computer that doesn't get used much needed updates the other day but it seems to be missing an admin account. I tried to activate it through cmd but since the one account on there is a standard user, it does not have the privileges to execute the commands to do this. I've also tried starting the pc in safe mode with cmd and it pulls up a standard user cmd every time. Any ideas?

A: Run the cmd as administrator by searching cmd then right clicking it and then "run as administrator". Then you can execute net user administrator /active:yes


text:
Q: Get folders from a class library
I have a Startup.cs file where I need to access resources files from "Resources" folder in a different class library.
I tried specifying path to dll and get all files from dll. I'm not sure how to get folder "Resources" from dll.
This is what I tried:
 string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Localization)}.dll", Path.GetFileName("Resoures"));
 string[] files = Directory.GetFileSystemEntries(path);

Expected:
string[] files = Directory.GetFileSystemEntries(path);

files should have the names of files from folder "Resources"
Actual:
An error occurred while starting the application.
DirectoryNotFoundException: Could not find a part of the path
  'D:\home\site\wwwroot\DataAccess.Repositories.Localization.dll\Resoures'.

A: You can get all the embedded resources using below code.
Please note that folders are not retained when you compile the project.
When you Mark a resource as embedded resource, that resource can be accessed
 string[] resourceNames = this.GetType().Assembly.GetManifestResourceNames();
 foreach(string resourceName in resourceNames)
{
      Console.WriteLine(resourceName);
}


text:
Q: Speeding up Sql query I have a Postgresql table with about 50 million entries. Now i want to find two id's, by looking for the first time and the last time a timestamp appears, to give me a range of entries.
Finding the "first" id  takes about 100 milliseconds.
But finding the second id takes about 3 minutes.
Query for finding the first id
SELECT id
FROM transactions
WHERE "hashBlock" =
    (SELECT hash
    FROM blocks
    WHERE n_time > 1262300400
    ORDER BY id ASC
    LIMTI 1)
ORDER BY id ASC
LIMTI 1

Query for finding the second id
Select id
FROM transactions
WHERE "hashBlock" =
    (SELECT hash
    FROM blocks
    WHERE n_time < 1306879200
    ORDER BY id DESC
    LIMTI 1)
ORDER BY id DESC
LIMTI 1

I guess the longer runtime result in the query going from the first id until it find an id which satisfies the query and the second one starting at the last id.
Is there any way to speed up the second query?

A: I would create the following indexes, if you don't have them already:
create index ix1 on transactions ("hashBlock", id);

create index ix2 on blocks (n_time, id, hash);


text:
Q: How can i select text from browser screen with help of mouse events in selenium? I am trying to select text which is already present on the browser.
I want to select that particular text and perform right click operation on it.
However, the page on the browser has disabled right click.
How can I select text in such situation?

A: Using a normal web browser without Selenium the only workaround that I can think about is to disable javascript to stop the script that prevents you from right clicking. So it should also work with a browser controlled by Selenium Webdriver.
I don't know if it will be OK for you because your website may be relying on javascript for  essential features.
However if you don't need Javascript for your Selenium test you can try the following when you launch your driver :
FirefoxProfile p = new FirefoxProfile();
p.setPreference("javascript.enabled", false);
driver = new FirefoxDriver(p);

I assume that you already know how to perform a right click because your question was only about dealing with the problem preventing you from doing this right click. But if not, you can also refer to this answer :
Select an Option from the Right-Click Menu in Selenium Webdriver - Java
Edit:
I'm sorry I really thought you could use Selenium actions to select the text you want but after some tests I didn't manage to perform a click and drag to select a text. The only thing that works for me in Chrome or Firefox is the following. It looks for a <p>which contains some text and then perform a double click to select a word.
driver.get("http://en.wikipedia.org/wiki/Java_(programming_language)");
WebElement text = driver.findElement(By.xpath("//p[contains(text(),'Java is')]"));
Actions select = new Actions(driver);
select.doubleClick(text).build().perform();

However it only highlighs one word in the html element that contains your text, so it's not really convenient.
I've also tried to do Ctrl+F and type the text so that the web browser automatically select it but the browser doesn't do anything when executing :
Actions search = new Actions(driver);
search .sendKeys(Keys.chord(Keys.CONTROL,"+f")).sendKeys("Java is").build().perform();

It seems that Selenium can only send keys events to the html elements and not to the browser (in the case of ctrl+F).
I don't really see a solution for now, let's see if someone else can find a workaround. It's an interesting issue, it would also be useful for me to select a text the way you described

A: Move to middle of the element
Actions builder = new Actions(webDriverObject);
builder.moveToElement(element).build().perform();

Move to starting of element, click and hold, move to end
Integer width = element.getSize().getWidth();
Actions newBuilder = new Actions(webDriverObject);
newBuilder.moveByOffset(width/2,0).clickAndHold.moveByOffset(width,0).release().build().perform();


text:
Q: PDO insert into dynamic field I have this function in my class
public function insertnewRec($name,$lastname,$category){
  try{
     $cmd = $this->connection->prepare('INSERT into user (fname,lname,$category) values(?,?,?)');
     $cmd->execute(array($name,$lastname,$category));
    }
  catch(){}
}

I want to insert to a field base on the value of my category,example if the value of category is = left then the pdo statement should like this,
 insert into user(fname,lname,left) values etc.....

but it's not working.I get error sql syntax
$cmd = $this->connection->prepare('INSERT into user (fname,lname,$category) values(?,?,?)');

Thank you in advance.

A:
"example if the value of category is = left then the pdo statement should like this"

That's because left is a MySQL reserved word:

*

*http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Therefore, you will need to wrap $category in backticks:
INSERT into user (fname,lname,`$category`)

As is the word right, should you decide to also use that word.

*

*Consult the link above for a full list.

A: You should create an new pdo object
// Replace `$category` with a parameter `:category`
  $cmd = $this->connection->prepare('INSERT into user (fname,lname,:category) values(?,?,?)');

// bind $category and pass it into the execute() call inside an array
   $cmd ->execute(array('category'=>$category));


text:
Q: Css - size one floated column to same height as another Reading through some of the answers to similar questions, I'm still not clear on whether this is possible.
Consider the situation of 2 floated columns inside a clearfix-ed container. Column1's contents can grow and determine the height of the container. Column2's contents are always guaranteed to be less then Column1 but its height should stretch to fill the container.
How on earth to get Column2 to stretch?
Here's the jsbin (With Column2 not stretching)
Things I do not want to do

*

*Use javascript

*Position absolute

*Use table html

I can figure out something with these techniques, but consider this an academic excercise. I'm trying to figure out whether css provides a "correct" solution that I can just commit to memory and be done with it.  My suspicion is that the answer might be in one of the following techniques which I do not yet fully understand.

*

*Using the table css display types

*That whole flexbox thing coming out soon

*Whatever it is that twitter bootstrap does

A: Like you suspect, table CSS will work so long as you don't need to support oldIE:
section {
  width: 50%;
  display: table-cell;
  box-sizing: border-box;
  border: solid grey 1px;
}

Flexbox could also be made to work, but beware the significant differences between what's currently implemented in browsers and what the current draft says.
I've not used Twitter bootstrap in anger so I'm not in a position to comment on it.


text:
Q: Open a PHP page with window.location in Javascript is not working How do I open a php page from javascript function ?

*

*window.location = "http://www.google.com";

*window.location.href = "http://www.google.com";

*location.href = "http://www.google.com";
None of them is working.
Even put in php.ini
allow_url_fopen = on

What is wrong at my approach?

A: If you have this javascript embedded within <script> tags it should work:
<script type="text/javascript">
  window.location = "http://www.google.com";
</script>

However, you cannot cause a PHP script to be included within a page you are writing with thsi javascript function: It will only redirect the browser to google or whatever other page you have set in window.location. You can include a PHP script from within a PHP page using the PHP include() or require() functions:
<?php
  include('file.php');
?>

A: window.location = "http://www.google.com";

Should work..
I think your javascript code contain some error so it is not working.

A: So php.ini's line allow_url_fopen has nothing to do with this. It is to allow or not a url to be given to the fopen function of PHP.
Here what you want to do is to redirect a user to another page using window.location = '/page.php'.
Unless by open you meant getting loading inside the actual page, in this case have a look at the mdn documentation about XHR. And you should be using jQuery's load function.

A: window.location.href = "http://www.google.com";

That will only redirect the user to Google.
But you can't load a page in a JS variable, every browser have a "cross-domain" restriction (unless the page is on the same domain as you JS file & your visitor).


text:
Q: After push to remote, the default uwsgi changed the location I have a Django project with the local repo, In my local git repo, I installed the uwsgi in my project venv/lib/python3.5/site-packages, and I push my local repo to remote repo use:
(venv) james_pro:myProject ldl$ git push remote_repo
ldl@101.120.32.16's password:
Counting objects: 10279, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (8966/8966), done.
Writing objects: 100% (10279/10279), 18.43 MiB | 886.00 KiB/s, done.
Total 10279 (delta 2774), reused 0 (delta 0)
To 103.200.32.76:/home/ldl/repo/Qiyun02
   551388c..ef0a95f  master -> master

in my local repo I show the uwsgi:
(venv) james_pro: $ pip3 show uwsgi
Name: uWSGI
Version: 2.0.17
Summary: The uWSGI server
Home-page: https://uwsgi-docs.readthedocs.io/en/latest/
Author: Unbit
Author-email: info@unbit.it
License: GPL2
Location: /Users/lll/Desktop/myProject/Project/myProject/venv/lib/python3.5/site-packages
Requires:
Required-by:

You see its under my project's venv.
But in my remote repo, if I show the uwsgi, it will shows the
(venv) [root@www myProject]# pip3 show uwsgi
Name: uWSGI
Version: 2.0.17
Summary: The uWSGI server
Home-page: https://uwsgi-docs.readthedocs.io/en/latest/
Author: Unbit
Author-email: info@unbit.it
License: GPL2
Location: /usr/local/Python3/lib/python3.5/site-packages
Requires:
Required-by:

this location is /usr/local/Python3/lib/python3.5/site-packages, not the venv path.
How can I solve this issue? because I want to use uwsgi to connect the django.


text:
Q: Semantic and Unsemantic markup with re-useable CSS class names I just want to ask a question as to whether my current method of creating class names is a terrible idea. Let me explain a little.
I am a web designer / application developer who loves PHP and can quickly create fully functioning, advanced PHP web applications that are responsive and look great. I like to create an inital template and then design my App in the browser; as and when a new page / html structure is written to the page in PHP.
How I make my pages look GREAT!
To generate PERFECT vertical rythym I user drewish vertical rythym claculator which generators perfect spacing between paragraphs and headings. I then create the following classes:
.noTop {
    margin-top:0px;
}

.lgTop {
    margin-top: ( WHATEVER MY
 margin top is )
}

.mdTop {
    margin-top: ( WHATEVER MY
 margin top is )
}

etc...

I now have EVERY class I need to sculpt a perfect vertical rythym website simply by spitting out HTML and adding classes to elements that look out of place. This really does work for me and ensures that EVERYTHING will always match up whilst only using a few class names. Also when another developer with an un-tranied design eye works on the project, I can rest assure that he will create spacing.
My question is, is this REALLY a terrible way of doing things for Vertical Rythym? An example case would be below:

This is a heading

This is a perfectly sized & spaced sub line

Example Text

<img class="mdTop"  //Image that site perfectly under paragraph.

Thank you all in advanced. This method works for me but I know it isn't the best. Using this I can very quickly create prototypes. Is there a BIG reason why I shouldn't do this?


text:
Q: Deconding base64 API response throws a FormatException An API I'm working on returns the following Base64, UTF8 Data.

H4sIAAAAAAAEAIXS3WvCMBAA8H8l5MmB9Wtf2idtJ86HDrHKNsYeYntrgzUpl2RQpf/7UsExsXZvCcf97ri7A0XQBsUT04y6BzoGRIlAXUrbFDIQkZx+g9D8GBR4+tChjY8NZgvOtGZfEnc2n6Za58rtdk3EOwnoQhqEKqMjRcYFVGb1ldT9sByPf7l+xcWgIuR7LkXVwKDXH5G1PyfByiOvErOY+Cnb5TasUp4rskBQNh1isilIABiBBRwPxJ60Aik0CRm3YTIRAhx/8nJDy/Z51duGqkvJ4tqyrXeJW/tEcGbe8hK9a0DXuGGiXvVTEElsHP+5ptH7OnPQO5p+EWWS+CiVqpMvrIcr1vkEj4OXRmg7Q+LxLZxsk1+Ijw3decEbCU1u7b8N1iDDBmSFLNr+fwMrrpTUpOUB2mtzZtOa7Ywaylxf+YQnGTgBQ80TUZBwPbfyZ1mWP1eCbD1AAwAA

I wrote the following test to convert it to a UTF8 Json string.
void main() {
  const data = "H4sIAAAAAAAEAIXS3WvCMBAA8H8l5MmB9Wtf2idtJ86HDrHKNsYeYntrgzUpl2RQpf/7UsExsXZvCcf97ri7A0XQBsUT04y6BzoGRIlAXUrbFDIQkZx+g9D8GBR4+tChjY8NZgvOtGZfEnc2n6Za58rtdk3EOwnoQhqEKqMjRcYFVGb1ldT9sByPf7l+xcWgIuR7LkXVwKDXH5G1PyfByiOvErOY+Cnb5TasUp4rskBQNh1isilIABiBBRwPxJ60Aik0CRm3YTIRAhx/8nJDy/Z51duGqkvJ4tqyrXeJW/tEcGbe8hK9a0DXuGGiXvVTEElsHP+5ptH7OnPQO5p+EWWS+CiVqpMvrIcr1vkEj4OXRmg7Q+LxLZxsk1+Ijw3decEbCU1u7b8N1iDDBmSFLNr+fwMrrpTUpOUB2mtzZtOa7Ywaylxf+YQnGTgBQ80TUZBwPbfyZ1mWP1eCbD1AAwAA";

  test('Base64 decoder', () {
    final bytes = base64.decode(data);

    String jsonString;
    try {
      jsonString = utf8.decode(bytes);
    } catch (e) {
      // ignore: avoid_print
      print(e);
    }

    // ignore: avoid_print
    print("$jsonString\n");

    final decoded = json.decode(jsonString);
    // ignore: avoid_print
    print("$decoded\n");
    expect(decoded, !null);
  });
}

The bytes that get decoded from the base64 string look good to me, but when I try to utf8.decode() the bytes. I get a FormatException, or, if I add allowMalformed = true, a non-sense string.
How can I decode the Json string correctly?

A: Your BASE64 input is a GZip compressed JSON String. The following program will work:
import 'dart:convert';
import 'dart:io';

void main() {
  const data = "H4sIAAAAAAAEAIXS3WvCMBAA8H8l5MmB9Wtf2idtJ86HDrHKNsYeYntrgzUpl2RQpf/7UsExsXZvCcf97ri7A0XQBsUT04y6BzoGRIlAXUrbFDIQkZx+g9D8GBR4+tChjY8NZgvOtGZfEnc2n6Za58rtdk3EOwnoQhqEKqMjRcYFVGb1ldT9sByPf7l+xcWgIuR7LkXVwKDXH5G1PyfByiOvErOY+Cnb5TasUp4rskBQNh1isilIABiBBRwPxJ60Aik0CRm3YTIRAhx/8nJDy/Z51duGqkvJ4tqyrXeJW/tEcGbe8hK9a0DXuGGiXvVTEElsHP+5ptH7OnPQO5p+EWWS+CiVqpMvrIcr1vkEj4OXRmg7Q+LxLZxsk1+Ijw3decEbCU1u7b8N1iDDBmSFLNr+fwMrrpTUpOUB2mtzZtOa7Ywaylxf+YQnGTgBQ80TUZBwPbfyZ1mWP1eCbD1AAwAA";

  final bytes = base64.decode(data);

  String jsonString;
  try {
    jsonString = utf8.decode(GZipCodec().decode(bytes));
  } catch (e) {
    // ignore: avoid_print
    print(e);
  }

  // ignore: avoid_print
  print("$jsonString\n");

  final dynamic decoded = json.decode(jsonString);
  // ignore: avoid_print
  print("$decoded\n");
}

Returns:
{"returnData":{"@errore":"","elencoEventi":{"@nrEventi":"8","@urlPiattaforma":"https://uci.getyourevent.online","evento":[{"@idEventi":"1","@descrizione":"2019 UCI MTB World Championships Presented by Mercedes-Benz (Mont Sainte Anne-CAN)"},{"@idEventi":"3","@descrizione":"2019 UCI Road World Championships (Yorkshire-GBR)"},{"@idEventi":"4","@descrizione":"2019 UCI Urban World Championships (Chengdu-CHN)"},{"@idEventi":"5","@descrizione":"2020 UCI Cyclo Cross World Championships"},{"@idEventi":"6","@descrizione":"2020 Mercedes-Benz UCI Mountain Bike World Cup"},{"@idEventi":"7","@descrizione":"2020 UCI BMX Supercross World Cup"},{"@idEventi":"8","@descrizione":"2020 UCI Track World Championships Presented by Tissot (Berlin-GER)"},{"@idEventi":"9","@descrizione":"2020 UCI Road World Championships (Aigle-Martigny SUI)"}]}}}

{returnData: {@errore: , elencoEventi: {@nrEventi: 8, @urlPiattaforma: https://uci.getyourevent.online, evento: [{@idEventi: 1, @descrizione: 2019 UCI MTB World Championships Presented by Mercedes-Benz (Mont Sainte Anne-CAN)}, {@idEventi: 3, @descrizione: 2019 UCI Road World Championships (Yorkshire-GBR)}, {@idEventi: 4, @descrizione: 2019 UCI Urban World Championships (Chengdu-CHN)}, {@idEventi: 5, @descrizione: 2020 UCI Cyclo Cross World Championships}, {@idEventi: 6, @descrizione: 2020 Mercedes-Benz UCI Mountain Bike World Cup}, {@idEventi: 7, @descrizione: 2020 UCI BMX Supercross World Cup}, {@idEventi: 8, @descrizione: 2020 UCI Track World Championships Presented by Tissot (Berlin-GER)}, {@idEventi: 9, @descrizione: 2020 UCI Road World Championships (Aigle-Martigny SUI)}]}}}


text:
Q: What will be the total work done by friction on the system (man+boat)?
As I am seeing this,  the man and boat will have different displacement from ground frame,  so there should be a net work done by friction .  The books says,  total work done by friction is zero when friction is static and internal to system. Please explain..

A:
As I am seeing this, the man and boat will have different displacement
  from ground frame, so there should be a net work done by friction

Viewed from the ground frame (frame of the observer in picture) and considering the man alone as the system, the static friction force between the man and the boat does work on the man causing a horizontal displacement the man toward the observer. Per Newton's third law, the man exerts and equal and opposite external force on the boat that does work on the boat causing a horizontal displacement of the boat away from the observer.

The books says, total work done by friction is zero when friction is
  static and internal to system. Please explain..

When the man and the boat are considered to be a system, the static friction force is internal to the system. Given there is no friction between the boat and water (and assuming no air friction as well) then there are is no net external force acting on the system and therefore no net work is done on the system by the internal static friction force. To put it another way, there is no displacement of the center of mass of the man/boat system due to the static friction force.

Can you mathematically show friction work adding up to zero.

Keep in mind we need to differentiate between friction work that is done on the man and the boat individually in the reference frame of the observer vs the friction work that is done on the system of the man + boat in the reference frame of the observer.
In the first case we apply Newton's second law to the boat and man individually and calculate the work done on each by the friction force.
In the second case we need to apply Newton's second law to the combination of the boat and man. The acceleration of the boat/man system is the acceleration of the center of mass of the boat/man system. Since the boat and man will each accelerate with an acceleration inversely proportional their masses, the acceleration of the center of mass of the boat and man will be
$$a_{cm}=\frac{Ma_{M}+ma_{m}}{M+m}$$
Per Newton's third law, the friction force exerted on the man by the boat is equal and opposite to the friction force exerted by the man on the boat, or
$$Ma_{M}=-ma_{m}$$
Consequently, $a_{cm}=0$. Therefore there is no displacement of the center of mass of the boat/man system. The internal static friction force does no net work on the boat/man system.
Now, in response to your discussions with @Adrian Howard:

So am I correct to say that, in ground frame, the kinetic energy is
  due to internal friction forces. I am just trying to apply work energy theorem..

The net (static friction) force on the man equals its change in kinetic energy in the observers reference frame and equals the change in kinetic energy of the boat in the observers reference frame.

Also I read that, work done by non-conservative forces changes
  mechanical energy of system. So what I am thinking is that friction
  being internal nonconservative force, added kinetic energy to this
  system(in ground frame). Point me where I am wrong, or is it a correct
  explanation.

Static friction does add kinetic energy to the boat and man individually, but it does not add kinetic energy to the center of mass of the boat/man system, since there is no change in velocity of the center of mass of the system. For the boat/man system the total change in kinetic energy, at the macroscopic level, is the sum of the changes in its internal kinetic energy (man plus boat individually) and external kinetic energy (kinetic energy of the center of mass of boat/man system). The change in kinetic energy of the center of mass is zero.
In your example of the system of charges, the increase in kinetic energy of the charges accelerating towards each other involves an equal decrease in electrical potential energy. Total mechanical energy is conserved because the electrical force are conservative. For the boat/man system there is an increase in internal kinetic energy of the system with no change in potential energy. Mechanical energy is not conserved because friction forces are non-conservative. The increase in kinetic energy comes from the internal energy of the man (chemical energy).
But for both the boat/man system and system of charges there is no change in kinetic energy of the center of mass of either system, because there is no net external force acting on either system.
Hope this helps.


text:
Q: Extract rectangular text boxes from an image I have image of application form in that i want to extract only name, DOB, signature and tick text boxes which are surrounded by text boxes, but i am getting the result along with others unexpected results.
Input image:

Expected result:

My result:

i have tried the below code
import numpy as np
from PIL import Image
import tensorflow as tf
import os
import pytesseract
import sys
import re

#from pdf2image import convert_from_path #need proppeler windows distrubution
import cv2
#from pdf2image.exceptions import PDFInfoNotInstalledError,PDFPageCountError,PDFSyntaxError

pdftoppm_path = r"C:\Program Files (x86)\Poppler\poppler-0.68.0\bin\pdftoppm.exe"

#path to tesseract instalattion
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'

def sort_contours(cnts, method="left-to-right"):
    # initialize the reverse flag and sort index
    reverse = False
    i = 0

    # handle if we need to sort in reverse
    if method == "right-to-left" or method == "bottom-to-top":
        reverse = True

    # handle if we are sorting against the y-coordinate rather than
    # the x-coordinate of the bounding box
    if method == "top-to-bottom" or method == "bottom-to-top":
        i = 1

    # construct the list of bounding boxes and sort them from top to
    # bottom
    boundingBoxes = [cv2.boundingRect(c) for c in cnts]
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
                                        key=lambda b: b[1][i], reverse=reverse))

    # return the list of sorted contours and bounding boxes
    return (cnts, boundingBoxes)

def box_extraction(img_for_box_extraction_path, cropped_dir_path):

    img1 = cv2.imread(img_for_box_extraction_path, 0)  # Read the image
    img = cv2.resize(img1, (800, 800))
    (thresh, img_bin) = cv2.threshold(img, 120, 255,
                                      cv2.THRESH_BINARY | cv2.THRESH_OTSU)  # Thresholding the image
    img_bin = 255-img_bin  # Invert the image

    ##cv2.imshow("Image_bin.jpg",img_bin)

    # Defining a kernel length
    kernel_length = np.array(img).shape[1]//150

    # A verticle kernel of (1 X kernel_length), which will detect all the verticle lines from the image.
    verticle_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, kernel_length))
    # A horizontal kernel of (kernel_length X 1), which will help to detect all the horizontal line from the image.
    hori_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_length, 1))
    # A kernel of (3 X 3) ones.
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))

    # Morphological operation to detect verticle lines from an image
    img_temp1 = cv2.erode(img_bin, verticle_kernel, iterations=3)
    verticle_lines_img = cv2.dilate(img_temp1, verticle_kernel, iterations=3)
    #cv2.imwrite("verticle_lines.jpg",verticle_lines_img)

    # Morphological operation to detect horizontal lines from an image
    img_temp2 = cv2.erode(img_bin, hori_kernel, iterations=3)
    horizontal_lines_img = cv2.dilate(img_temp2, hori_kernel, iterations=3)
    #cv2.imwrite("horizontal_lines.jpg",horizontal_lines_img)

    # Weighting parameters,a=0.4 and b=0.8. this will decide the quantity of an image to be added to make a new image.
    alpha = 0.8
    beta = 5.0 - alpha
    # This function helps to add two image with specific weight parameter to get a third image as summation of two image.
    img_final_bin = cv2.addWeighted(verticle_lines_img, alpha, horizontal_lines_img, beta, 0.0)
    img_final_bin = cv2.erode(~img_final_bin, kernel, iterations=2)
    (thresh, img_final_bin) = cv2.threshold(img_final_bin, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

    # For Debugging
    # Enable this line to see verticle and horizontal lines in the image which is used to find boxes
    ##cv2.imshow("img_final_bin.jpg",img_final_bin)
    # Find contours for image, which will detect all the boxes
    contours, hierarchy = cv2.findContours(
        img_final_bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # Sort all the contours by top to bottom.
    (contours, boundingBoxes) = sort_contours(contours)#, method="top-to-bottom")

    idx = 0
    for c in contours:
        # Returns the location and width,height for every contour
        x, y, w, h = cv2.boundingRect(c)
        #print(x,y,w,h)

        # If the box height is less than 80, widht is <400, then only save it as a box in "cropped/" folder.
        if (w < 400 and h < 80): # and h < 6*w:
            idx += 1
            new_img = img[y:y+h+10, x:x+w+10]
            contours1, hierarchy1 = cv2.findContours(img_final_bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            # Sort all the contours by top to bottom.
            (contours1, boundingBoxes) = sort_contours(contours1, method="top-to-bottom")
            # get the thresholded crop
            retval, thresh_crop = cv2.threshold(new_img, thresh=200, maxval=255, type=cv2.THRESH_BINARY)
            cv2.imwrite(cropped_dir_path+str(idx) + '.png', thresh_crop)

    # For Debugging
    # Enable this line to see all contours.
    # cv2.drawContours(img, contours, -1, (0, 0, 255), 3)
    # cv2.imwrite("./Temp/img_contour.jpg", img)

box_extraction("X:\PDF2IMG\TEST.jpeg", "X:\PDF2IMG\cropped")

#cv2.waitKey(0)
#cv2.destroyAllWindows()

How can i get the expected result only?
I have image of application form in that i want to extract only name, DOB, signature and tick textboxes which are surrounded by text boxes, but i am getting the result along with others unexpected results.

A: To extract the desired regions, we can use the property of a rectangular box in that they can be isolated using contour approximation and contour area. Here's an approach:

*

*Convert image to grayscale, blur, and threshold

*Perform morphological operations to smooth image and remove noise

*Find contours

*

*Filter using contour approximation and contour area

*Extract and save ROI using Numpy slicing

Here are the detected rectangular text boxes highlighted in green

Since we have the bounding boxes, we simply extract the ROIs

import cv2

image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur,0,255,cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)[1]

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
cnts = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

ROI_number = 0
for c in cnts:
    area = cv2.contourArea(c)
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    x,y,w,h = cv2.boundingRect(approx)
    if len(approx) == 4 and (area > 1000) and (area < 80000):
        ROI = image[y:y+h, x:x+w]
        cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
        ROI_number += 1

cv2.imshow('thresh', thresh)
cv2.imshow('opening', opening)
cv2.waitKey()


text:
Q: PHP Encode message length as 2 byte hex for XML socket post I am dealing with an XML socket server which I receive and send XML requests from/to.
The server requires a 2 byte hex prefix to the string that indicates the length of the message; the message I receive when connecting to the XML socket is as follows:
XML String received
<?xml version="1.0" encoding="UTF-8"?>
<Iso8583PostXml>
<MsgType>0800</MsgType>
<Fields>
<Field_007>xxx</Field_007>
<Field_011>xxx</Field_011>
<Field_012>xxx</Field_012>
<Field_013>xxx</Field_013>
<Field_070>001</Field_070>
</Fields>
</Iso8583PostXml>

String converted to HEX
01013c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d38223f3e0d0a3c49736f38353833506f7374586d6c3e3c4d7367547970653e303830303c2f4d7367547970653e3c4669656c64733e3c4669656c645f3030373e303831323136323235373c2f4669656c645f3030373e3c4669656c645f3031313e3139323235373c2f4669656c645f3031313e3c4669656c645f3031323e3139323235373c2f4669656c645f3031323e3c4669656c645f3031333e303831323c2f4669656c645f3031333e3c4669656c645f3037303e3030313c2f4669656c645f3037303e3c2f4669656c64733e3c2f49736f38353833506f7374586d6c3e

You can see starts with "0101" when I convert it to hex, which is the length of the XML message sent.  To decode this message in to XML, I convert it to a hex string and then chop off the first 4 characters, it then works in simplexml_load_string - if I dont remove that "0101" the XML doesn't parse - even though if I echo out the string received it looks like normal xml with nothing prepending it.
The response I send back is an XML string:
<?xml version="1.0" encoding="UTF-8"?>
<Iso8583PostXml>
<MsgType>0810</MsgType>
<Fields>
<Field_007>xxx</Field_007>
<Field_011>xxx</Field_011>
<Field_012>xxx</Field_012>
<Field_013>xxx</Field_013>
<Field_070>001</Field_070>
<Field_039>00</Field_039>
</Fields>
</Iso8583PostXml>

This has a length of 322, what I need to do is prefix this length as a 2 byte hex value to the string and send the message back, the same as the message I received.
Does anyone know how I can set that 322 hex header to the string?
[UPDATE]
I've tried doing the following:
$hex_string = bin2hex($length.$xml);
$send_xml = pack('H*', $hex_string);
echo "Sending acknowledgement...\n";
$result = socket_write($socket, $send_xml, $length);
echo $send_xml;

The $send_xml is outputting the length as a string in front of the XML
322<?xml version="1.0" encoding="UTF-8"?>
<Iso8583PostXml>
<MsgType>0810</MsgType>
<Fields>
<Field_007>0813063726</Field_007>
<Field_011>093726</Field_011>
<Field_012>093726</Field_012>
<Field_013>0813</Field_013>
<Field_070>001</Field_070>
<Field_039>00</Field_039>
</Fields>
</Iso8583PostXml>

Which is not working.. I somehow need to write that 322 in to a 2 byte prefix for the xml string

A: Try below code its working great for me
function sendSocketRequest($XmlString, $Socket_Request) {
    if (!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        die("Couldn't create socket: [$errorcode] $errormsg \n");
    }

    if (!socket_connect($sock, $Socket_Request['HostName'], $Socket_Request['Port'])) {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        die("Could not connect: [$errorcode] $errormsg \n");
    }

    $status = socket_write($sock, pack_int32be(strlen($XmlString)), 4);
    $status = socket_write($sock, $XmlString, strlen($XmlString));
    $response = socket_read($sock, $this->_socketReadLength);

    socket_close($sock);
    return substr($response, 2);
}

function pack_int32be($i) {
    if ($i < -2147483648 || $i > 2147483647) {
        die("Out of bounds");
    }
    return pack('C4', ($i >> 24) & 0xFF, ($i >> 16) & 0xFF, ($i >> 8) & 0xFF, ($i >> 0) & 0xFF
    );
}
$socketResponse = sendSocketRequest($yourXMLString, array('HostName'=>'<HostName>','Port'=>'<Port>');

A: Check php function pack (http://php.net/manual/en/function.pack.php) with formats h or H depens on your Endianness of your XML socket server.
But it should give you a push into the right direction


text:
Q: Why does my Async custom validator in Angular app works with typed input but not with pasted input? I have created a custom validator that checks whether an email already exists in MySQL database. It works in that when a user types in an email that already exists in a database, an appropriate warning message will appear and not allow the admin to insert an existing user.
However, after testing it a few times, it looks like this validation can be easily broken by simply copying the email address from the database and pasting it in the form field. It is worth to note that when pasting in the email the first time round, it doesnt validate the email but when I then delete it and paste it in the second time, it then recognises it.  I have shown the process in the attached photos below:

Please also see my code:
My custom validator:
import { Directive } from '@angular/core';
import { AsyncValidator, AbstractControl, ValidationErrors, NG_ASYNC_VALIDATORS, AsyncValidatorFn } from '@angular/forms';
import { Observable } from 'rxjs';
import { PatientsService } from './patients.service';
import { map } from 'rxjs/operators';

export function uniqueUsernameValidator(patientService: PatientsService): AsyncValidatorFn {
    return (c: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
        return patientService.checkUserEmail(c.value).pipe(
            map(users => {
                return users && users.length > 0 ? { 'uniqueUsername': true } : null;
            })
        );
    };
}

@Directive({
    selector: '[uniqueUsername]',
    providers: [{ provide: NG_ASYNC_VALIDATORS, useExisting: UniqueUsernameValidatorDirective, multi: true }]
})
export class UniqueUsernameValidatorDirective implements AsyncValidator {

    constructor(private patientService: PatientsService) { }

    validate(c: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
        return uniqueUsernameValidator(this.patientService)(c);
    }

}

component I am using it in:
email: [
        null,
        [Validators.required,Validators.maxLength(30),Validators.email],
        [this.usernameService.usernameValidator()]
      ]

Referenced in my html

    Email
    <input type="email" formControlName="email" name="email" class="form-control" id="inputEmail4"placeholder="Email">

        Please enter maximum 30 characters.

        Please enter an email address.

        Please insert a valid email address.

        Email already exists

Could someone please advise ? I am trying for it to also validate clipboard events (copy and paste) the first time round.

A: try this :

onPasteEmail(): void {
  addForm.updateValueAndValidity();
}
<input (paste)="onPasteEmail()">

paste event will be trigger when you copy&paste your email the first time, then updateValueAndValidity() function from reactive form will trigger your validation

A: Use ReactiveForms instead, there's no reason to make it more complex than needed.
Hardcoded fixes for the 'onPaste' is sort of ridiculous to rely on.