text:
Q: Process Workflow: Given key is not present in the dictionary in UiPath I am doing UiPath level-3 Assignment 1. I have made all the workflows using Ui Studio and I am stuck in the process workflow. While I run the WFs, it says

Process WF: Given dictionary is not present.

I checked all the values and arguments and they seem correct too.
Also when I run the Process WF separately, it gets stuck for each loop and say

object reference not set to an instance of an object.

Could someone help resolving these issues? Thanks in advance.

A: You are passing null value/trying to get value from dictionary using the key which doesn't exist. Please also remember that before using dictionary you have to create it.
It will be easier to help if you can provide status window logs at least.

A:
As you said - I checked all the values and arguments and they seem
  correct too.

So just check for spaces in your config file from where you are reading data and putting them in Dictionary.
Second Possibility
which seems to me is just check your arguments via which you are passing your configuration dictionary to your workflow. are you passing it from main workflow to your child workflows.
just double check your arguments.
Regards..!!
Aksh


text:
Q: Asana Workspace is_organization Value The Asana API documentation states that when querying all workspaces with https://app.asana.com/api/1.0/workspaces that it will return an is_organization value (set to true or false) depending on the kind of workspace the user has.
When I GET /workspaces I do not see this value come down with the workspace payload. Only the workspace id and name are available.
Will is_organization only appear if it's true and it's omitted entirely if its value is false?

A: You can specify the fields to return with the ?opt_fields option. For your request, this would be something like https://app.asana.com/api/1.0/workspaces?opt_fields=name,is_organization.
Note that the results may not be what you expect. I was surprised to see that even my Personal Projects workspace returned true for is_organization.

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS & Obj-C Strange formatted string to NSDate I have a date string like this: 2015-09-06T06:00:00
And I'm trying to convert it to NSDate with this function:
+(NSDate*)dateStringToNSDate:(NSString*)dateString{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-ddTHH:mm:ss"];
    return [dateFormatter dateFromString:dateString];
}

And it's a nil for me? Where am I doing the mistake? Thank you for help.

A: Your format is wrong. That's the problem.
Try this one. Should fix it
"yyyy-MM-dd'T'HH:mm:ss"


text:
Q: How to undo `Arg.Do(() => {})` in NSubstitute I've got this code:
sub.Foo(Arg.Do<int>(() => {}));

How do I undo this?
.ClearReceivedCalls() and .ClearReturnValues() seem to have no effect on removing this delegate

A: There isn't currently a way to remove the action, but you can queue it up in different ways that will allow you to stop it running.
The first option is to use an external action, then change that at a later point in time.
// Clear action manually
Action<string> action = x => SideEffect();
sub.Foo(Arg.Do<string>(x => action(x)));
// ...
action = x => { };

A variant of that approach can let you modify the action to automatically clear itself (alternatively we could use a guard clause to make sure it only runs the required amount of times):
// Self-clearing action (run once):
Action<string> action = x =>
{
    SideEffect();
    action = _ => { };
};
sub.Foo(Arg.Do<string>(x => action(x)));

Another option is to use the Callback builder. This is works with When..Do rather than Arg.Do, but does give you a bit of control over how different sequences of actions can be queued up (see the documentation for a more involved example):
// Callback builder:
// (See )
sub.When(x => x.Foo(Arg.Any<string>()))
   .Do(Callback.First(call => SideEffect()));


text:
Q: Rails generic controller and views I've been looking at Administrate source code and would like to know if it's a good practice or not the use of a generic controller and what implications it would have, like code complexity, performance degradation, etc.
Sometime ago, there was a gem inherited_resources that provide this feature, but since Rails 3.0 or 3.1 has been said we no longer need them.
So, since I have some very simple models (with only two or three fields) I could create a generic view and controller to manipulate them and save a lot of lines of "duplicated" code. Although I'm afraid, by avoiding repetition I could be creating another monster.
I've been looking for a Rails way to do this, but failed, so I would thanks some advice.
Note: I'm not looking to implement or use an admin dashboard, but use in my application instead

A: All Rails admin-panel implementations will make you hurt when you will try to make something more complex than stupid simple CRUD-application. I recomend you not to use such solutions. I had experiece in usage three different Rails's admin-panels and all of them had bad design and a lot of limitations. They are hard to mantain and extend their functionality.


text:
Q: Using static function for classes' helpers in C++ Is it still worth using static functions in C++ as a helpers?
Example:
in file.cpp
static void helperFunc() { do something }

// class implementation
// ...

// some public method, not static
void myClass::doSomething() { helperFunc(); }

That way I do not have to declare private method in class's declaration.
Or maybe it is better to use unnamed namespaces and write (in the same file as above)?
namespace {
    void helperFunc() { }
}

What is better?

A: Neither of your two examples is better than the other. It's a matter of style. The static keyword is more expressive. It outright spells out "do not export this name". Using an anonymous namespace is not that expressive. The fact that the name won't get exported is a side-effect, not a primary function.

A: It's better to declare a private (possibly static) method in the class.


text:
Q: Will Old revision google play services work after August 1 2014? What if i have already in my app with ADmob google play service lib(revision 15) do i need to upgrade to new revision(18) or it will be ok on August 1 2014(when google shut down 6.4.1 Ads SDK and lower) ? This upgrade does not cover old revision i hope ?

A: I will answer my own question. If already your app is showing ads using old play service sdk you can continue with that..or you can upgrade to new one(not required) !


text:
Q: Непонятные горизонтальные линии вокруг background (image) на мобильных Доброго времени суток,
Не могу разобраться, почему при просмотре сайта через планшет/телефон, появляются горизонтальные линии над и под фоновым изображением.

background:url('/images/cutheader.png') repeat-x top, #FAEBD7 url('/images/cutfooter.png') repeat-x bottom;

При этом на ПК в любом браузере такой проблемы нет.
Вот  сайт, чтобы эмулировать отображение через IOS:
Сайт
Вот сам сайт с проблемой:
Сайт
Полоски видны сразу под хедером и в футере.
Чтобы пример заработал, увеличьте масштаб до 200% ctrl+Колёсико мыши в хроме.

.head {
  background-color:red;
}
.body {
   padding: 15px 5px;
 background: url('http://geassnovels.ru/images/cutheader.png') repeat-x top, #FAEBD7 url('/images/cutfooter.png') repeat-x bottom;
 flex-grow: 1;
    -webkit-background-size: 11px 11px;
}

 Hello

A: Это эмулятор косячный, проверьте в инспекторе хрома.
На девайсе в порядке, в xcode эмуле тоже
]1
[]2
[]3

A: Это не глюк браузера, это неправильное павило.
.body {
  background: url('../images/defaultIMAGE.png') repeat-x top, #FAEBD7 url('../images/defaultIMAGE.png') repeat-x bottom;
}

@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
   .body {
       background: url('../images/retinaIMAGE-2x.png') repeat-x top, #FAEBD7 url('../images/retinaIMAGE-2x.png') repeat-x bottom;
       -webkit-background-size: 30px 15px;
          -moz-background-size: 30px 15px;
               background-size: 30px 15px;
    }
}

Либо по дефолту ставьте изображение большое например 60px на 30px а в бекграунд-сайз прописывайте 30px на 15px, правило для мобильных дивайсов
.body {
  background: url('../images/retinaIMAGE-2x.png') repeat-x top, #FAEBD7 url('../images/retinaIMAGE-2x.png') repeat-x bottom;
  background-size: 30px 15px;
}
@media
  only screen and (-webkit-min-device-pixel-ratio:2),
  only screen and (min--moz-device-pixel-ratio:2),
  only screen and (-o-min-device-pixel-ratio:2/1),
  only screen and (min-device-pixel-ratio:2),
  only screen and (min-resolution:192dpi),
  only screen and (min-resolution:2dppx){
    .body {
         background-size: 30px 15px;
    }
}

A: Было 2 проблемы:
1)margin-bottom: -1px; в ссылках (css)
2)кривой ресайз (решилось использование SVG)


text:
Q: How to get value from column in java I am writing a file from shell script and reading that file from java and prints % in jsp page..
Here's the file :
0K .......... .......... .......... .......... ..........  0%    6.93 MB/s
   50K .......... .......... .......... .......... ..........  0%    1.75 MB/s
  100K .......... .......... .......... .......... ..........  0%    3.78 MB/s
  150K .......... .......... .......... .......... ..........  1%    1.93 MB/s
  200K .......... .......... .......... .......... ..........  1%    3.66 MB/s
  250K .......... .......... .......... .......... ..........  2%    7.84 MB/s
  300K .......... .......... .......... .......... ..........  2%    3.65 MB/s
  350K .......... .......... .......... .......... ..........  3%    2.45 MB/s

Here's the code to get pertucular value from file :
while((line = file.readLine()) != null) {

                    int li = line.lastIndexOf("%");
                    if(li > 0)
                        progress = Integer.parseInt(line.substring(li - 3, li).trim());
                }

Now the file format has been changed to below format :
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0  164M    0     0    0     0      0      0 --:--:--  0:00:01 --:--:--     0
  0  164M    0  272k    0     0   117k      0  0:23:54  0:00:02  0:23:52  303k
  0  164M    0  624k    0     0   186k      0  0:15:04  0:00:03  0:15:01  322k
  0  164M    0  960k    0     0   221k      0  0:12:41  0:00:04  0:12:37  328k
  0  164M    0 1296k    0     0   242k      0  0:11:33  0:00:05  0:11:28  331k
  0  164M    0 1632k    0     0   258k      0  0:10:52  0:00:06  0:10:46  333k
  1  164M    1 1968k    0     0   267k      0  0:10:28  0:00:07  0:10:21  337k
  1  164M    1 2304k    0     0   276k      0  0:10:08  0:00:08  0:10:00  337k
  1  164M    1 2656k    0     0   283k      0  0:09:52  0:00:09  0:09:43  338k
  1  164M    1 2992k    0     0   289k      0  0:09:41  0:00:10  0:09:31  339k
  1  164M    1 3328k    0     0   293k      0  0:09:32  0:00:11  0:09:21  339k
  2  164M    2 3680k    0     0   297k      0  0:09:25  0:00:12  0:09:13  341k
  2  164M    2 4016k    0     0   300k      0  0:09:19  0:00:13  0:09:06  341k
  2  164M    2 4352k    0     0   303k      0  0:09:14  0:00:14  0:09:00  340k

Without changing much I just want to perform same operation (see code) to get the value of column 1 i.e : % value.
How to modify the above code or is there any method (like lastIndexOf) that will have the first's columns value???

A: Assuming the first column starts at 0 and takes 3 chars
 progress = Integer.parseInt(line.substring(0, 3).trim());

A: String line = "  101  164M    0  624k    0     0   186k      0  0:15:04  0:00:03  0:15:01  322k";
// replacing the whole string with percentage, if exists
String num = line.replaceAll("^\\s*([0-9]+).*", "$1");
// now, if the 'num' is really a number. for column header it will have the text
if(num.matches("[0-9]+")){
    // do whatever
    System.out.println("num >> "+num);
}

I have used regex here. First capturing the matched group, and then replaced by the capture ($1).


text:
Q: Execute bash function to run screen I'm using an aws ubuntu instance. I would like to create an alias/function to run some shortcuts, for example to activate a python virtual environnement in a screen.
I've made this function for example:
# Alias for jupyter notebook
function start_jupyter() {
    cd my_path/lab_workspace/  # 1. cd into my workspace
    source labworkspaceenv/bin/activate  # 2. activate my python virtualenv
    screen -S jupyter_lab  # 3. start screen
    echo 'You are in screen for jupyter lab'  # 4. print something
    jupyter lab  # 5. start jupyter lab
}

Problem is, when I run the function with start_jupyter, this seems to stop after 3. the screen is created but then nothing is printed and jupyterlab is not started.
What am I doing wrong?

A: The reason the function stopped is that you spawn an interactive screen session. You might want to do this instead:
screen -dmS jupyter_lab jupyter lab

This will create a detached screen session named jupyter_lab and execute the command there.
As per the screen --help info:
-dmS name     Start as daemon: Screen session in detached mode.

So, your function would be:
# Alias for jupyter notebook
function start_jupyter() {
    cd my_path/lab_workspace/  # 1. cd into my workspace
    source labworkspaceenv/bin/activate  # 2. activate my python virtualenv
    screen -dmS jupyter_lab jupyter lab  # 3. start screen
}


text:
Q: Why my UITextField data is lost when we come back from Second view controller to main view controller? I have three view controllers (first, second and third view controllers), first view controller and second view controller has 4 UITextField each one, after entering the data in text fields we can go from one VC to another along with data, finally we display data in third VC. The problem is when we come back from second to first the textfield is no more there. Not sure why this happens? How to solve this problem? Please help me resolve this issue.

A: when you push or present a new UIViewController you can send data with it but as soon as you reach the second UIViewController your first UIViewController releases the space from phone hence all your data in previous screen is lost.
and the only option you have is to send back the data you send while coming to second UIViewController and you can do it is by simply creating delegate class to send data.
create a header file lets say Sample.h and create this method inside it you can choose the datatype you want.
- (void)secVCDidDismisWithData:(NSDictionary *)data;

import header file in second UIViewController in .h file and put this line of code there
@property (nonatomic, assign)   id<Sample> delegate;

then you have to make custom pop button or dismiss button and put this code
[self.navigationController popViewControllerAnimated:YES];
if(_delegate && [_delegate respondsToSelector:@selector(secVCDidDismisWithData:)])
{
    [_delegate secVCDidDismisWithData:@{@"key1":@"value1",@"key2":@"value2"}];
}

then on the first UIViewController .m file import your second UIViewController which I am sure you already have done to present or push the screen then just below that add put this line
@interface FirstVC () <Sample>

and then create the object of second UIViewController and set delegate to self and the implement the delegate method you made like this
- (void)secVCDidDismisWithData:(NSDictionary *)data{
     NSLog(@"%@",data);}


text:
Q: Is ".then(function(a){ return a; })" a no-op for promises? I'm reading this tutorial about Bookshelf. Bookshelf uses Bluebird promises. There's quite a few examples that look something like this:
var getEvents = function(participantId) {
  return new models.Participant()
    .query({where: {id: participantId}})
    .fetch({withRelated: ['events'], require: true})
    .then(function(model) {
      return model;
    });
};

I'm still not comfortable with promises, but from what I've learned so far this seems odd. My question is, is the above function exactly the same as returning fetch() directly and leaving off the final then():
var getEvents = function(participantId) {
  return new models.Participant()
    .query({where: {id: participantId}})
    .fetch({withRelated: ['events'], require: true});
};

That is, it still does the same thing, returns the same promise, can be called in the same way, etc?
From what I understand, the parameter to the function passed to then gets the return value of the previous promise in the chain. So, it seems to me like .then(function (a) { return a; }) in general is just a no-op. Right?
If they aren't the same, what's the difference? What's going on and why did the author write it that way?

A: Bergi's answer is right, but just to demonstrate a case where it's not a no-op here is a contrived example where it's not a no-op:
o = {};
Promise.resolve(o).then(o => o.then = () => {}); // make thenable
Promise.resolve(o).then(console.log); // logs the object
Promise.resolve(o).then(x => x).then(console.log); // doesn't log the object

In general, don't do then(function(a) { return a; })

A:
It seems to me like .then(function (a) { return a; }) is just a no-op. Right?

Yes.1
It is useless and should be omitted.

What's going on and why did the author write it that way?

It's a blunder. Or the author didn't understand promises.

1: If they aren't the same, what's the difference?

As always, there are some edge cases. Really weird ones. That no-one should use (without extensive commenting):
a) it returns a new promise instance, a distinct object, to avoid sharing. However, .then() would as well.
b) a is tested again for its thenable-ness. If it suddenly became a promise since the fulfillment, it now will be awaited. This would be awful of course.


text:
Q: Can we predict the theorem we need when making a proof? Sometimes when I'm proving a mathematical problem, I might find out that i still need some hints(some important theorem, hypothesis,etc). Is there any possibility to know(to predict) what we need in the proof? Can the model theory solve this problem? Or something about Gödel's completeness theorem?

A: There's sort of two ends to this question, as I see it. First, the technical:
"What do I need to prove this?" is really asking "Of the axioms I have, which ones are necessary for the result I want?" Remember, if it's some important theorem you need or something else that isn't an axiom, you could in principle just prove it yourself and then use it, so you don't technically "need" it. The question of which axioms are necessary to prove a certain result is actually a major field of study, called reverse mathematics - you may want to look into it, it's very interesting! But no, we can't generally know which axioms are necessary for a result, and it's for exactly the reason you suggest - Godel's Incompleteness. The easy example is to consider the collection of axioms $PA + 1 = 0$ (that is, Peano arithmetic together with the false statement $1 = 0$) and say we wanted to prove $1 = 0$. This is a consequence of these axioms, but to know whether we need $1 = 0$ to do this proof we would need to know whether $PA$ is consistent. (This argument is a bit loose, but gives the right idea.)
Next, the practical: Of course, in practice, we do care whether an important theorem is necessary, because we can't really expect to prove them on our own. And no, there's no way to predict whether you'll need it - but as you do more and more proofs in a certain field, you start to get a feel for it. If you talk to mathematicians about a problem in their field, you'll probably hear them say something like "oh, yeah, that's just Fermat's Little Theorem" or "it's just a finite-injury construction, right?" They can predict the technique or the central theorem just because they know the field well enough to know what the "usual" tools are. And, while they aren't always right, they're usually okay at it.


text:
Q: How to real time display input value with jQuery? <input type="text" id="name" />

So that when user enter something inside "#name",will show it in "#display"

A: $('#name').keyup(function() {
    $('#display').text($(this).val());
});

A: You could simply set input value to the inner text or html of the #display element, on the keyup event:
$('#name').keyup(function () {
  $('#display').text($(this).val());
});

A: The previous answers are, of course, correct. I would only add that you may want to prefer to use the keydown event because the changes will appear sooner:
$('#name').keydown(function() {
    $('#display').text($(this).val());
});

A: A realtime fancy solution for jquery >= 1.9
$("#input-id").on("change keyup paste", function(){
    dosomething();
})

if you also want to detect "click" event, just:
$("#input-id").on("change keyup paste click", function(){
    dosomething();
})

if your jquery <=1.4, just use "live" instead of "on".

A: code.
$(document).ready(function(){

<!DOCTYPE html>

<input type="text" id="name" />


text:
Q: How do I view data during debugging? I always get the remark "Expanding the Results View will enumerate the IEnumerable" while debugging and trying to view what's in my local array.
I am using Visual Studio 2013 for Web and coding in C#.
How do I view my data?

A: Enumerable's in C# are subject to deferred execution, and so if you have an Enumerable object which has only been assigned to but not yet used then you will encounter the "Expanding results view" message when debugging.
Here is a simple example of this to help illustrate
string[] myArr = { "one", "two", "" };
var query = myArr.Where(x => !String.IsNullOrEmpty(x));
foreach(var q in query)
{
    Console.WriteLine(q);
}

In this example, setting a breakpoint on the foreach and inspecting the value of query in the debugger will give you the message you are referring to - this is because the execution of the .Where has been deferred until the collection is actually enumerated.
Luckily for us that will happen in the next line, since the foreach will iterate over the collection causing the .Where to execute.
However you may find there will be situations where the collection isn't enumerated until much later - I believe this to be one of the benefits of deferred execution, as it allows for perceived performance at runtime (especially over a large collection).
A brief example could be that a user may access a page in your application which amongst other things has a rarely used drop down list containing a large collection of objects. Rather than have the drop down list slow down the loading of that page by enumerating the large collection of objects, it is instead better to defer that enumeration until after the page has loaded and the user decides to use drop down list to view the collection (which they may never do!).
However, you can force the execution to occur immediately rather than waiting for the array to be enumerated in which you simply call .ToArray() or .ToList() on the query like so
var query = myArr.Where(x => !String.IsNullOrEmpty(x)).ToArray();

Now when you are debugging you will see the contents of query populated before it is used in the foreach.


text:
Q: Let $a_n$ bounded and $b_n=\frac{a_1+a_2+...+a_n}{n}$ prove $\limsup (b_n)\le \limsup (a_n) $
Let $a_n$ bounded and $b_n=\frac{a_1+a_2+...+a_n}{n}$ prove $\limsup (b_n)\le \limsup (a_n) $

I tried to prove it like this:
Let $x_m=\sup{\{a_n : n>m}\}$ so $a_n\le x_N$ for all $n > N$.
let $n > M > N$ then:
$b_n = \frac{1}{n}\sum _{j=1}^N\:a_j+\frac{1}{n}\sum \:_{j=N+1}^n\:a_j$
$\le\frac{1}{n}\sum _{j=1}^N\:a_j+\frac{1}{n}\sum \:_{j=N+1}^n\:x_N$
$\le\frac{1}{M}\sum _{j=1}^N\:a_j+\frac{n-N}{n}x_N$
$<\frac{1}{M}\sum _{j=1}^N\:a_j+x_N$
so we get $\sup_{n>M}b_n \le \frac{1}{M}\sum _{j=1}^N\:a_j+x_N$
now let $M \to \infty   $ conclude that : $\limsup b_n \le 0 + a_N$
and  $N \to \infty   $ yields : $\limsup b_n \le \limsup (a_n)$
Is my proof correct , if not how to prove it ?
thanks


text:
Q: flatten list of ranges to single result range set I am trying to "flatten" a list of ranges in a defined order (alphabetically by name in the examples provided) to a single merged result. Newer Ranges  overwrite values of older ranges. Conceptually it looks like this, with "e" being the newest range:
0   1   2   3   4   5   6   7

|-------------a-------------|
        |---b---|
    |---c---|
                |---d---|
            |---e---|

|-a-|---c---|---e---|-d-|-a-|  <-- expected result

To prevent further confusion: The expected result here is indeed correct. The values 0 - 7 are just the ranges' values, not a progression in time. I use integers for simplicity here, but the values might not be discrete but continuous.
Note that b is completely overshadowed and not relevant anymore.
the data may be modeled like this in SQL:
create table ranges (
    name varchar(1),
    range_start integer,
    range_end integer
);

insert into ranges (name, range_start, range_end) values ('a', 0, 7);
insert into ranges (name, range_start, range_end) values ('b', 2, 4);
insert into ranges (name, range_start, range_end) values ('c', 1, 3);
insert into ranges (name, range_start, range_end) values ('d', 4, 6);
insert into ranges (name, range_start, range_end) values ('e', 3, 5);
-- assume alphabetical order by name

It would be perfect if there was a way to directly query the result in SQL, e.g. like this:
select *magic* from ranges;
-- result:
+------+-------------+-----------+
| a    |           0 |         1 |
| c    |           1 |         3 |
| e    |           3 |         5 |
| d    |           5 |         6 |
| a    |           6 |         7 |
+------+-------------+-----------+

But I suspect that is not realistically feasible, therefore I need to at least filter out all ranges that are overshadowed by newer ones, as is the case for b in the example above. Otherwise the query would need to transfer more and more irrelevant data as the database grows and new ranges overshadow older ones. For the example above, such a query could return all entries except for b, e.g.:
select *magic* from ranges;
-- result:
+------+-------------+-----------+
| a    |           0 |         7 |
| c    |           1 |         3 |
| d    |           4 |         6 |
| e    |           3 |         5 |
+------+-------------+-----------+

I was unable to construct such a filter in SQL. The only thing I managed to do is query all data and then calculate the result in code, for example in Java using the Google Guava library:
final RangeMap<Integer, String> rangeMap = TreeRangeMap.create();
rangeMap.put(Range.closedOpen(0, 7), "a");
rangeMap.put(Range.closedOpen(2, 4), "b");
rangeMap.put(Range.closedOpen(1, 3), "c");
rangeMap.put(Range.closedOpen(4, 6), "d");
rangeMap.put(Range.closedOpen(3, 5), "e");
System.out.println(rangeMap);
// result: [[0..1)=a, [1..3)=c, [3..5)=e, [5..6)=d, [6..7)=a]

Or by hand in python:
import re
from collections import namedtuple
from typing import Optional, List

Range = namedtuple("Range", ["name", "start", "end"])

def overlap(lhs: Range, rhs: Range) -> Optional[Range]:
    if lhs.end <= rhs.start or rhs.end <= lhs.start:
        return None
    return Range(None, min(lhs.start, rhs.start), max(lhs.end, rhs.end))

def range_from_str(str_repr: str) -> Range:
    name = re.search(r"[a-z]+", str_repr).group(0)
    start = str_repr.index("|") // 4
    end = str_repr.rindex("|") // 4
    return Range(name, start, end)

if __name__ == '__main__':
    ranges: List[Range] = [
        #               0   1   2   3   4   5   6   7
        range_from_str("|-------------a-------------|"),
        range_from_str("        |---b---|            "),
        range_from_str("    |---c---|                "),
        range_from_str("                |---d---|    "),
        range_from_str("            |---e---|        "),
        # result:       |-a-|---c---|---e---|-d-|-a-|
    ]

    result: List[Range] = []
    for range in ranges:
        for i, res in enumerate(result[:]):
            o = overlap(range, res)
            if o:
                result.append(Range(res.name, o.start, range.start))
                result.append(Range(res.name, range.end, o.end))
                result[i] = Range(res.name, 0, 0)
        result.append(range)
    result = sorted(filter(lambda r: r.start < r.end, result), key=lambda r: r.start)
    print(result)
    # result: [Range(name='a', start=0, end=1), Range(name='c', start=1, end=3), Range(name='e', start=3, end=5), Range(name='d', start=5, end=6), Range(name='a', start=6, end=7)]

A: The following simple query returns all smallest intervals with top name:
with
 all_points(x) as (
   select range_start from ranges
   union
   select range_end from ranges
 )
,all_ranges(range_start, range_end) as (
   select *
   from (select
           x as range_start,
           lead(x) over(order by x) as range_end
         from all_points)
   where range_end is not null
)
select *
from all_ranges ar
     cross apply (
     select max(name) as range_name
     from ranges r
     where r.range_end   >= ar.range_end
       and r.range_start <= ar.range_start
     )
order by 1,2;

Results:
RANGE_START  RANGE_END RANGE_NAME
----------- ---------- ----------
          0          1 a
          1          2 c
          2          3 c
          3          4 e
          4          5 e
          5          6 d
          6          7 a

So we need to merge connected intervals with the same names:
Final query without new oracle-specific features
with
 all_points(x) as (
   select range_start from ranges
   union
   select range_end from ranges
 )
,all_ranges(range_start, range_end) as (
   select *
   from (select
           x as range_start,
           lead(x) over(order by x) as range_end
         from all_points)
   where range_end is not null
)
select
   grp,range_name,min(range_start) as range_start,max(range_end) as range_end
from (
   select
      sum(start_grp_flag) over(order by range_start) grp
     ,range_start,range_end,range_name
   from (
      select
        range_start,range_end,range_name,
        case when range_name = lag(range_name)over(order by range_start) then 0 else 1 end start_grp_flag
      from all_ranges ar
           cross apply (
           select max(name) as range_name
           from ranges r
           where r.range_end   >= ar.range_end
             and r.range_start <= ar.range_start
           )
   )
)
group by grp,range_name
order by 1;

Results:
       GRP RANGE_NAME RANGE_START  RANGE_END
---------- ---------- ----------- ----------
         1 a                    0          1
         2 c                    1          3
         3 e                    3          5
         4 d                    5          6
         5 a                    6          7

Or using actual oracle specific features:
with
 all_ranges(range_start, range_end) as (
   select * from (
      select
        x as range_start,
        lead(x) over(order by x) as range_end
      from (
         select distinct x
         from ranges
         unpivot (x for r in (range_start,range_end))
      ))
   where range_end is not null
 )
select  *
from all_ranges ar
     cross apply (
     select max(name) as range_name
     from ranges r
     where r.range_end   >= ar.range_end
       and r.range_start <= ar.range_start
     )
match_recognize(
   order by range_start
   measures
      first(range_start) as r_start,
      last(range_end) as r_end,
      last(range_name) as r_name
   pattern(STRT A*)
   define
     A as prev(range_name)=range_name and prev(range_end) = range_start
);

A: Here is a hierarchical query that would give you the desired output:
WITH ranges(NAME, range_start, range_end) AS
  (SELECT 'a', 0, 7 FROM dual UNION ALL
   SELECT 'b', 2, 4 FROM dual UNION ALL
   SELECT 'c', 1, 3 FROM dual UNION ALL
   SELECT 'd', 4, 6 FROM dual UNION ALL
   SELECT 'e', 3, 5 FROM dual UNION ALL
   SELECT 'f', -3, -2 FROM dual UNION ALL
   SELECT 'g', 8, 20 FROM dual UNION ALL
   SELECT 'h', 12, 14 FROM dual)
, rm (NAME, range_start, range_end) AS
  (SELECT r.*
     FROM (SELECT r.NAME
                       , r.range_start
                       , NVL(r2.range_start, r.range_end) range_end
                    FROM ranges r
                    OUTER apply (SELECT *
                                   FROM ranges
                                  WHERE range_start BETWEEN r.range_start AND r.range_end
                                    AND NAME > r.NAME
                                 ORDER BY range_start, NAME DESC
                                 FETCH FIRST 1 ROWS ONLY) r2
                    ORDER BY r.range_start, r.NAME desc
                    FETCH FIRST 1 ROWS ONLY) r
  UNION ALL
   SELECT r2.NAME
        , r2.range_start
        , r2.range_end
     FROM rm
    CROSS apply (SELECT r.NAME
                      , GREATEST(rm.range_end, r.range_start) range_start
                      , NVL(r2.range_start, r.range_end) range_end
                   FROM ranges r
                   OUTER apply (SELECT *
                                  FROM ranges
                                 WHERE range_start BETWEEN GREATEST(rm.range_end, r.range_start) AND r.range_end
                                   AND NAME > r.NAME
                                ORDER BY range_start, NAME DESC
                                FETCH FIRST 1 ROWS ONLY) r2
                  WHERE r.range_end > rm.range_end
                    AND NOT EXISTS (SELECT 1 FROM ranges r3
                                     WHERE r3.range_end > rm.range_end
                                       AND (GREATEST(rm.range_end, r3.range_start) < GREATEST(rm.range_end, r.range_start)
                                        OR (GREATEST(rm.range_end, r3.range_start) = GREATEST(rm.range_end, r.range_start)
                                        AND r3.NAME > r.NAME)))
                  FETCH FIRST 1 ROWS ONLY) r2)
CYCLE NAME, range_start, range_end SET cycle TO 1 DEFAULT 0
 SELECT * FROM rm

First you get the first entry ordered by range_start desc, name which will give you the most resent entry with the lowest name.
Then you search for a range with higher name that intersect with this range. If there is one the range_start of this interval will be the range_end of you final interval.
With this start you search more or less the next entry with the same condition.

A: There is also another less effective but easier and shorter approach: to generate all points and just aggregate them.
For example this simple query will generate all intermediate points:
select x,max(name)
from ranges,
     xmltable('xs:integer($A) to xs:integer($B)'
       passing range_start as a
              ,range_end as b
       columns x int path '.'
     )
group by x

Results:
         X M
---------- -
         0 a
         1 c
         2 c
         3 e
         4 e
         5 e
         6 d
         7 a

Then we can merge them:
select *
from (
   select x,max(name) name
   from ranges,
        xmltable('xs:integer($A) to xs:integer($B)-1'
          passing range_start as a
                 ,range_end as b
          columns x int path '.'
        )
   group by x
   order by 1
)
match_recognize(
   order by x
   measures
      first(x) as r_start,
      last(x)+1 as r_end,
      last(name) as r_name
   pattern(STRT A*)
   define
     A as prev(name)=name and prev(x)+1 = x
);

Results:
   R_START      R_END R
---------- ---------- -
         0          1 a
         1          3 c
         3          5 e
         5          6 d
         6          7 a

A: I don't understand your results -- as I've explained in the comments.  The "b" should be present, because it is most recent at time 2.
That said, the idea is to unpivot the times and figure out the most recent name at each time -- both beginnings and ends.  Then, combine these using gaps-and-islands ideas.  This is what the query looks like:
with r as (
      select name, range_start as t
      from ranges
      union all
      select null, range_end as t
      from ranges
     ),
     r2 as (
      select r.*,
             (select r2.name
              from ranges r2
              where r2.range_start <= r.t and
                    r2.range_end >= r.t
              order by r2.range_start desc
              fetch first 1 row only
             ) as imputed_name
      from (select distinct t
            from r
           ) r
     )
select imputed_name, t,
       lead(t) over (order by t)
from (select r2.*,
             lag(imputed_name) over ( order by t) as prev_imputed_name
      from r2
     ) r2
where prev_imputed_name is null or prev_imputed_name <> imputed_name;

Here is a db<>fiddle.
Basically the same code should run in Postgres as well.


text:
Q: Modal that displays conditionally with async pipe wont display twice Hey I have a modal I am using which is basically listening to an subject observable and the global http interceptor is pushing an error onto it
so this works great for the first error:
<modal
  modalwidth="50"
  open="true"
  label="Oh no!"
  *ngIf="errorMessage$ | async as errorMessage"
>

if on the same page though you cause another error this modal does not appear again, so you get the first error - modal appears, you close it - cause another error and the modal never appears.
http interceptor calls handleError->
private errorMessageSubject = new Subject<CustomError>();
  public errorMessage$ = this.errorMessageSubject.asObservable();

  handleError(error: HttpErrorResponse): void {
    this.errorMessageSubject.next({

then on the root of the Angular app in the app.component.ts
 this.errorMessage$ = this.errorService.errorMessage$;

I believe what I need to reset the observable somehow

A: After closing modal emit void:
this.errorMessageSubject.next(void 0);


text:
Q: Universal PAN id in zigbee Is there any Universal PAN id in zigbee which can receive packets from different PAN id senders?(For sending packets to all PANid we can use oxFFFF)

A: ZigBee document 075297r04 is the "Proposal for Inter-PAN Exchange of Data in ZigBee".  You'll need to be a member of the ZigBee Alliance to access that though.
Inter-PAN is mentioned in a few specs, but I have not seen it in use yet.  You'll want to check with your hardware/stack provider to see how they support it.

A: You could also use "groups". Controling at the and all devices that joined this group.


text:
Q: FlatMapGroupsWithStateFunction with lazy iterator as return value When using Apache Spark with stateful processing, it can group rows with same key using flatMapGroupsWithState function
Dataset<Row> ds = spark.sql("SELECT ... FROM parquetTable")
                             .groupByKey(..., Encoders.STRING()
                             .flatMapGroupsWithState(new FlatMapFunctionEager(),
                                     OutputMode.Append(),
                                     Encoders.kryo(Session.class),
                                     RowEncoder.apply(PARQUET_SCHEMA),
                                     GroupStateTimeout.ProcessingTimeTimeout());

Generally, examples or tutorials show a FlatMapGroupsWithStateFunction with a List<Row> created first and iterator to it is returned:
private class FlatMapFunctionEager implements FlatMapGroupsWithStateFunction<String, Row, Session, Row> {
    @Override
    public Iterator<Row> call(String key, Iterator<Row> values, GroupState<Session> state) throws Exception {
        Session session = null;
        if (state.exists()) {
            session = state.get();
        } else {
            session = createSession();
            state.update(session);
        }

        // here a list is created and populated with results
        List<Row> result = new LinkedList<>();
        while (values.hasNext()) {
            Row row = values.next();
            result.add(process(row, session));
        }

        // here iterator of the list is returned
        return result.iterator();
    }

    private Row process(Row row, Session session) {
        // do processing and return generated row
    }
}

However, this sometimes causes memory problems since Spark can group a lot of Rows for processing.
Is it safe to return a lazy iterator that stores Iterator and GroupState provided by the caller?
Or can Iterator and GroupState change after the call and therefore not safe to use them lazily?
Sample code:
public class FlatMapFunctionLazy implements FlatMapGroupsWithStateFunction<String, Row, Session, Row> {
    @Override
    public Iterator<Row> call(String key, Iterator<Row> values, GroupState<Session> state) throws Exception {
        // here we pass the state and values iterator
        return new LazyIterator(state, values);
    }
}

public class LazyIterator implements Iterator<Row> {
    private final GroupState<Session> state;
    private final Iterator<Row> values;

    public LazyIterator(GroupState<Session> state, Iterator<Row> values) {
        this.state = state;
        this.values = values;
    }

    @Override
    public boolean hasNext() {
        return values.hasNext();
    }

    @Override
    public Row next() {
        // here we use the provided iterator when our iterators next is called
        Row row = values.next();
        return process(row);
    }

    private Row process(Row row) {
        Session session = null;
        // here we query and update the state (GroupState)
        if (state.exists()) {
            session = state.get();
        } else {
            session = createSession();
            state.update(session);
        }

        return process(row, session);
    }

    private Row process(Row row, Session session) {
        // do processing and return generated row
    }
}

Is this kind of usage safe or will be the behaviour undefined?
I tried lazy iterator with some sample input and got correct results however I could not be sure for its correctness since sometimes multi-threaded programs may produce correct results even though some race conditions exist and also documentation is not clear about this area.


text:
Q: Move avi files to a different drive after being created using batch file Due to little C:/ drive space, I have spent hours looking and trying code that will manage the following with my X-Plane 11 avi files process and move.

*

*Xplane11 is creating *.avi files to my C:/ drive. Each *.avi file is approximately 2 GB in size.

*Xplane11 will continue creating *.avi files as long as it continues to record flight.

I need a batch file which will do the following:

*

*Check for *.avi files on C:/ and their status.

*Wait to complete creation before moving them from C:/ drive to D:/. Then. move them.

*Continue this process until simulator recording has finished and no more *.avi files are being created.

I have tried numerous variations of code similar to this:
@echo off

:loop
if not exist "C:\X-Plane 11\Output\*.avi" goto :end

if exist ("C:\X-Plane 11\Output\*.avi") do (

If %Errorlevel% gtr 0 (
echo Avi file still being created please wait!
) else (
echo Avi created and is now being moved!
goto :copy
)
)
:copy
start /w "" move "C:\X-Plane 11\Output\*.avi" "D:\X-Plane 11\Output\New Captures
loop

:end
echo Avi does not exist!
exit

The problem I find is that it won't wait until the *.avi finishes before moving and preferred without any console key presses as I am not always sitting at simulator when files being created.

A: I have managed a partial batch solution to my question having looked through previous stackoverflow solutions and help from its coders (thx Mofi). It will check for an existing .avi and move it to another directory when it has completed being created and repeat the process until no more .avi files exist at source location. I am now looking to change its name when moved as any new .avi files overwrite the previous.
Here is my new code so far....
@echo off

:loop

if not exist "C:\X-Plane 11\Output\*.avi" (
echo No more Avi files to move!
echo Will now Exit!
pause
goto :exit
)
) else (
if "!errorlevel!" GTR "0" (
echo
) else (
echo Please Wait.....
for %%F in (C:\X-Plane 11\Output\*.avi) do (
move "C:\X-Plane 11\Output\*.avi" "D:\X-Plane 11\Output\"
)

PING localhost -n 10 >NUL
goto :loop
)
)
)
)
:exit
exit


text: Q: How to set via JS the value of an empty contenteditable text input field in React (as those used for posts and messages in Facebook and Whatsapp)? This is an example of an empty input field from Whatsapp in the DOM. Whenever the contents of the P node is changed and the Input event is trigerred (on the DIV), the contents of P is reset to BR.


text:
Q: Need Uri for Activeperl installation in docker For my use case, I need to create a windows container of Activeperl application. I found a GitHub link which explains the process for a Strawberry Perl.
Code snippet from the link
RUN \
    if(!(Test-Path -Path 'C:\Temp')) \
    { \
        New-Item \
            -Path 'C:\Temp' \
            -ItemType Directory \
            -Verbose | Out-Null ; \
    } ; \
    \
    Invoke-WebRequest \
        -Uri "http://strawberryperl.com/download/$ENV:PERL_VERSION/strawberry-perl-$ENV:PERL_VERSION-64bit.zip" \
        -OutFile "C:\\Temp\\strawberry-perl-$ENV:PERL_VERSION-64bit.zip" \
        -UseBasicParsing \
        -Verbose ; \
    \
    Expand-Archive \
        -Path "C:\\Temp\\strawberry-perl-$ENV:PERL_VERSION-64bit.zip" \
        -DestinationPath 'C:\Program Files\Perl' \
        -Verbose ; \
    \
    Set-ItemProperty \
        -Path 'HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment' \
        -Name 'Path' \
        -Value $($ENV:Path + ';C:\Program Files\Perl\perl\bin;C:\Program Files\Perl\perl\site\bin;C:\Program Files\Perl\c\bin') \
        -Verbose ;

Strawberryperl Uri - http://strawberryperl.com/download/$ENV:PERL_VERSION/strawberry-perl-$ENV:PERL_VERSION-64bit.zip
For me, I want an equivalent Uri for downloading Activeperl instead of Strawberryperl. I am even ok with a Windows Container Image with activeperl installed already. I just couldn't find any of them.

A: Since ActivePerl doesn't provide an option for downloading a zipped version of Perl.
This is how I was able to transfer an active Perl to a Windows container
In my host windows machine, I have downloaded the Active Perl from https://activeperl.software.informer.com/download/
The downloaded file is ActivePerl-5.28.1.0000-MSWin32-x64-e90bcbf1.msi
I have installed this at the location C:\Perl64\
Copied this Perl64 folder into a new folder called Perl_root, so that this can be copied into the container via Dockerfile. Create a file called Dockerfile in the same location as Perl_root.
Filesystem_Root
C:\
 |__ docker_trial
     |___ Perl_root
     |___ Dockerfile

Dockerfile:
#pulled a windows container from docker hub
FROM mcr.microsoft.com/windows/servercore:1607-amd64

ADD Perl_root .

Open a command prompt and navigate to the folder where dockerfile is present.
>docker build --tag dockertrail:1.0 .
>docker run -it --name tag1 dockertrail:1.0

Once the terminal inside the docker container opens up, open a PowerShell and create the update the environment variable Path as below
Powershell>[Environment]::SetEnvironmentVariable("Path",$env:Path+"C:\Perl64\site\bin;C:\Perl64\bin","Machine")

exit from the PowerShell and container. Now restart the container tag1, for the environment variable to work.
start the container tag1 again, once it starts, open up a PowerShell and run the command $env:Path  you must be able to see the perl path being added to environment variables.
Now check the functioning of Perl using the command perl -v
This should print the perl verion.


text:
Q: Detect if a command is piped or not Is there a way to detect if a command in go is piped or not?
Example:
cat test.txt | mygocommand #Piped, this is how it should be used
mygocommand # Not piped, this should be blocked

I'm reading from the Stdin reader := bufio.NewReader(os.Stdin).

A: Use os.Stdin.Stat().
package main

import (
  "fmt"
  "os"
)

func main() {
    fi, _ := os.Stdin.Stat()

    if (fi.Mode() & os.ModeCharDevice) == 0 {
        fmt.Println("data is from pipe")
    } else {
        fmt.Println("data is from terminal")
    }
}

(Adapted from this tutorial)

A: same can be done with performing a similar bitwise operation with ModeNamedPipe
package main

import (
        "fmt"
        "os"
)

func main() {
        fi, err := os.Stdin.Stat()
        if err != nil {
                panic(err)
        }

        if (fi.Mode() & os.ModeNamedPipe) != 0 {
                fmt.Println("data is from pipe")
        } else {
                fmt.Println("data is from terminal")
        }
}


text:
Q: Asm ClassReader accept I am using Asm to visit the java byte code to get the method infomation.It seems that accept method of  class ClassReader is called in a asynchronized manner.So it is impossible to obtain method infomation immediately.What can I do ?

A: Actually,  the accept method is called from your own code and you shoult pass your ClassVisitor implementation. Then methods of that visitor will be called and when call toaccept completes all information about class is passed trough that visitor. You can record it in some visitor's member fields or process imediately. If you need in-memory model of your class, you can use ClassNode as such visitor.


text:
Q: SpringXD-issue in mysql as source .FAILED TO VALIDATE A NEWLY ESTABLISHED CONNECTION I am creating a spring xd stream like below :
stream create foo --definition "jdbc --url=jdbc:mysql://localhost:3306/test --driverClassName=com.mysql.jdbc.Driver --query='select * from employee' |hdfs --inputType=text/plain --rollover=200" --deploy

I am able to get the data in hdfs..ButI am getting error in the logs like below..Any reason for this kind of error..
The output is here:
-rw-r--r--   3 root hdfs        216 2015-10-15 08:45 /xd/foo/foo-34.txt
-rw-r--r--   3 root hdfs        216 2015-10-15 08:45 /xd/foo/foo-35.txt
-rw-r--r--   3 root hdfs        216 2015-10-15 08:45 /xd/foo/foo-36.txt
-rw-r--r--   3 root hdfs          0 2015-10-15 08:45 /xd/foo/foo-37.txt.tmp

But the error is this in the log file
        at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:204)
        ... 21 more

2015-10-15 08:42:04,839 1.1.2.RELEASE ERROR task-scheduler-9 handler.LoggingHandler - org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: Failed to validate a newly established connection.
        at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:245)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:457)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
        at com.sun.proxy.$Proxy182.call(Unknown Source)
        at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller$1.run(AbstractPollingEndpoint.java:298)
        at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:52)
        at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
        at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:49)
        at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:292)
        at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
        at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLException: Failed to validate a newly established connection.
        at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:802)
        at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:617)
        at org.apache.tomcat.jdbc.pool.ConnectionPool.getConnection(ConnectionPool.java:186)
        at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:127)
        at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:204)
        ... 21 more

A: I've encountered this issue as well at times. I opened a JIRA issue to look into this: https://jira.spring.io/browse/XD-3620
In the meantime you can work around this by specifying "--testOnBorrow=false" when creating the job or the stream.


text:
Q: Uniform distribution presentations seem incomplete I'm studying the book "A practical guide to quantitative finance interviews." This is how it presents the discrete uniform distribution:

I've seen several other sources present it the same way (http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Discreteuniform.pdf, )
This presentation relies on $\Delta x= 1$. If $\Delta x = 1$, then the number of possible values for $x$ is $b-a+1$, i.e., the difference between the max and min plus 1. But what if $\Delta x \neq 1$, then the number of points is no longer the difference between the max and min plus 1. Wouldn't a better presentation make $P(x)$ and $Var(x)$ a function of $a, b, n$, where n is the number is possible $x$ values? Is there a particular reason why this is not done?
For example, in this case, say $\Delta x = 0.5$, so $x = a, a+0.5, a+1, \cdots, b$, then $P(x) \neq \frac{1}{b-a+1}$, but instead, $P(x) = \frac{1}{2b-2a+1}$

A: You are right - there is no particular reason to make this convention.
In general we can derive the expectation and variance (and higher order moments) by using centering and scaling arguments from the uniform distribution on $\{0, \ldots, n\}$. I present this below.
As becomes clear - the calculations do not simplify that well, and likely if the sources you are reading only use the case of unit steps, then presenting the result in this context allows for much simpler formulae.

If $X \sim \text{Unif}(0, \ldots, n)$ then the transformed variable
$$Y = a + \frac{b-a}{n} X$$
will be uniform on $\{a, a + \frac1n\, \ldots, b - \frac1n, b\}$.
One can show that
$$\mathbf E X = \frac{n}{2}, \qquad \text{Var}(X) =  \frac{(n+1)^2 - 1}{12},$$
(both follow from the formulae for $\sum_{k=0}^n k$ and $\sum_{k=0}^n k^2$).
And subsequently centering/scaling of expectations and variances give:
$$ \mathbf E[Y] = a + \frac{b-a}{n} \mathbf E[X] = \frac{b + a}{2},$$
and
$$
\begin{align*}
\text{Var}(Y) & = \left(\frac{b-a}{n}\right)^2 \text{Var}(X) \\
& = \left(b-a\right)^2\frac{(n+1)^2 - 1}{12n^2}
\end{align*}$$
In the case of unit steps, $n = b-a$, and the above simplifies to the original formula you gave.


text:
Q: Technotrend CT2 4650 not working in fresh install I have a Technotrend CT2 4650. It worked perfectly on a Ubuntu 16.04.02, which was a upgrade from the previous LTS line as far as I remember. The USB module was dvb_usb_dvbsky.
Then my SSD crashed, and I reinstalled 16.04.02 the other day. It's not discovered anymore. It's shown in lsusb of course, but the module does not seem to initialize it:
Bus 001 Device 003: ID 0b48:3015 TechnoTrend AG

When I modprobe dvb_usb_dvbsky, this appears in dmesg:
[  175.468458] usbcore: registered new interface driver dvb_usb_dvbsky

I have tested the module on a PC running OpenSuSE, and the following turned up in dmesg:
[220841.422482] usb 1-2: new high-speed USB device number 9 using xhci_hcd
[220841.563158] usb 1-2: New USB device found, idVendor=0b48, idProduct=3015
[220841.563161] usb 1-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[220841.563162] usb 1-2: Product: TechnoTrend USB2.0
[220841.563163] usb 1-2: Manufacturer: CityCom GmbH
[220841.563164] usb 1-2: SerialNumber: 20151107
[220843.006483] usb 1-2: dvb_usb_v2: found a 'TechnoTrend TT-connect CT2-4650 CI v1.1' in warm state
[220843.006543] usb 1-2: dvb_usb_v2: will pass the complete MPEG2 transport stream to the software demuxer
[220843.006557] DVB: registering new adapter (TechnoTrend TT-connect CT2-4650 CI v1.1)
[220843.007850] usb 1-2: dvb_usb_v2: MAC address: bc:ea:2b:65:04:ab
[220843.020459] i2c i2c-8: Added multiplexed i2c bus 9
[220843.020462] si2168 8-0064: Silicon Labs Si2168-B40 successfully identified
[220843.020463] si2168 8-0064: firmware version: B 4.0.2
[220843.023511] si2157 9-0060: Silicon Labs Si2147/2148/2157/2158 successfully attached
[220843.030075] sp2 8-0040: CIMaX SP2 successfully attached
[220843.030085] usb 1-2: DVB: registering adapter 0 frontend 0 (Silicon Labs Si2168)...
[220843.058431] Registered IR keymap rc-tt-1500
[220843.058529] input: TechnoTrend TT-connect CT2-4650 CI v1.1 as /devices/pci0000:00/0000:00:14.0/usb1/1-2/rc/rc0/input25
[220843.058616] rc rc0: TechnoTrend TT-connect CT2-4650 CI v1.1 as /devices/pci0000:00/0000:00:14.0/usb1/1-2/rc/rc0
[220843.058619] usb 1-2: dvb_usb_v2: schedule remote query interval to 300 msecs
[220843.058621] usb 1-2: dvb_usb_v2: 'TechnoTrend TT-connect CT2-4650 CI v1.1' successfully initialized and connected
[220843.058647] usbcore: registered new interface driver dvb_usb_dvbsky
[220849.365260] dvb_ca adapter 0: DVB CAM detected and initialised successfully

As far as I can remember, this is more or less what turned up on the previous Ubuntu install as well - I particularly remember seeing the initialization of the CAM...
I have tried insmodding the required modules manually, with no result.
This is what appears in dmesg when I plug the USB cable to the device, with relevant modules loaded:
[ 3285.678512] usb 1-1.1: new high-speed USB device number 6 using ehci-pci
[ 3285.776059] usb 1-1.1: New USB device found, idVendor=0b48, idProduct=3015
[ 3285.776065] usb 1-1.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 3285.776070] usb 1-1.1: Product: TechnoTrend USB2.0
[ 3285.776073] usb 1-1.1: Manufacturer: CityCom GmbH
[ 3285.776076] usb 1-1.1: SerialNumber: 20151107

Compared to OpenSuSE (and previous Ubuntu install) it's not much.
Any pointers are welcome.

A: Upgrading to 4.8 fixed things. Turned out that the 4.4.0 kernel is too old.


text:
Q: CIFS Fileshare 'randomly' cycling through different combinations of attributes Would appreciate any assistance here, I have a file share (WD EX4100 NAS) on my docker host (Ubuntu 18.08.4 LTS - Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-123-generic x86_64)) that has been working until recently, now my files appear to be cycling through random patterns of attributes causing other issues with read / modify access for other systems, etc... due to the immutable flag.
Notice the timestamps

[15:17:38] administrator@ubuntu-container_host:/media/plexarex/share$ lsattr
s-S-i-dAc-jI------ ./test.txt
s-S-i-dAc-jI------ ./test2.txt
[15:17:41] administrator@ubuntu-container_host:/media/plexarex/share$ lsattr
----iad-c-jI------ ./test.txt
----iad-c-jI------ ./test2.txt
[15:17:42] administrator@ubuntu-container_host:/media/plexarex/share$ lsattr
----iad---jI------ ./test.txt
----iad---jI------ ./test2.txt
[15:17:43] administrator@ubuntu-container_host:/media/plexarex/share$ lsattr
s-S-i-d-c-jI------ ./test.txt
s-S-i-d-c-jI------ ./test2.txt
[15:17:43] administrator@ubuntu-container_host:/media/plexarex/share$ lsattr
su----d-c-jI------ ./test.txt
su----d-c-jI------ ./test2.txt
[15:17:44] administrator@ubuntu-container_host:/media/plexarex/share$ lsattr
s---i---c-jI------ ./test.txt
s---i---c-jI------ ./test2.txt

/etc/fstab entry
//192.168.1.30/plexarex /media/plexarex cifs rw,noacl,nouser_xattr,credentials=/home/fileshare_svc/.smbcredentials,iocharset=utf8,uid=fileshare_svc,gid=fileshare_svc 0 0

Troubleshooting steps / Things I've tried:

*

*Disabled all containers

*Attempted to overwrite with chattr

*Recreated share

*Unmapped share from all other locations

*Changed /etc/fstab (added noacl, nouser_xattr)

Looking for ideas here, I don't know what else to try, I've never ran into this before and am unsure on where to go / what to try next.


text:
Q: Jest test expecting specific error to be thrown I have a Jest test that is expecting a specific error to be thrown on a function, however even when the error is throw it is not detecting it.
async function resolve(hostname) {
   return dns.resolve(hostname)
      .then(ip => (`address: ${ip}`))
      .catch(err => {
         throw new DnsError
      })
}

test('Resolving records', () => {
   expect(() => { dns.resolve('http://fsdfsvsdv') }).toThrowError(DnsError)
})

I'm a little stuck on why this test isn't passing, when I run it I can see in the console that the specific error is in fact being throw but for some reason Jest is not picking that up.. Am I doing something wrong? Any help would be appreciated.


text:
Q: Changing An Elements Content I would like to change the content of a element with a button click and then have it return back to its original message. How Would i do this preferable with toggle class if possible.
<doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Day Practice</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"> </script>

</head>
<body>
<h1> HotDogs</h1>
<input type=button id=button value=button>
<script>
$("#button").click(function(){
$("h1").html("Change to this");
});

</script>

This changes the header with a button, but I don't know how to revert it when I click on the button again. Maybe Toggle Class, I don't know.

A: this should solve:
$( "#button" ).toggle(function() {
  $("h1").html("Change here");
}, function() {
  $("h1").html("Revert back here");
});

A: Set a flag to toggle and check, and store the old text whenever you change it. An example:
var flag = false;
var old_text = "";

$("#button").click(function () {
    if (flag) {
        $("h1").html(old_text);
    } else {
        old_text = $("h1").html();
        $("h1").html("Change to this");
    }
    flag = !flag;
});

A: You can try this:
var alternate_text = "Change to this";
$("#button").click(function(){
    var temp = $("h1").html()
    $("h1").html(alternate_text);
    alternate_text = temp; // Switch the two instances of text.
});

A: Since you prefered to do this with toggleClass(), here you go:
$(document).ready(function(){

    var oldContent;

    $("#button").click(function(){
        if($(".newCont")[0]){
            $("h1").html(oldContent);
        } else {
            oldContent = $("h1").html();
            $("h1").html("New text here");
        }

        $("h1").toggleClass("newCont");
    });
});


text:
Q: ncurses novice - starting out with GNU C A simpler life
I am returning to C to help reinvigorate my programming lobe. The last time I learned to program I was at college working with Turbo C on MSDOS.  Simple ASCII animations became an obsession once I found Borland's friendly <conio.h> one include away.  A lot of fun was had with the gotoxy and textcolor functions and it wasn't long before I was writing games like snake and pong.  It was a very rewarding way to learn a language, and each game pushed me further as I got more ambitious.
ncurses
I'd like start with similar game type projects.  Today though, I'm on a mac with a dusty linux machine in the corner. I could launch my beloved Turbo C in dosbox (an ubiquitous enough platform) but I want to learn C such that I can develop something that compiles naturally on any BSD or unix platform. I've been told that ncurses is the way forward but the GNU site has largely gone over my head. Back in the day I had my friendly textmode function and I was aprint expression away from pong.  ncurses seems a lot more powerful.
whoosh
There must be many people who've been in this situation. I'm looking for a relevant tutorial or resource that will help me grapple with what ncurses is and how to work with it.  Any tips or similar stories would be of great interest too!

A: Yup, ncurses is the library you're looking for.  As an example, here's the (n)curses equivalent of gotoxy:

NAME
move, wmove - move curses window cursor
SYNOPSIS
   #include <curses.h>

   int move(int y, int x);
   int wmove(WINDOW *win, int y, int x);

DESCRIPTION
These  routines  move the cursor associated with the window to
  line y and column x.  This routine does not move the physical cursor
  of the terminal until refresh is called.  The position specified is
  relative to the upper left-hand corner of the window, which is (0,0).

Addendum:
In your comment you ask about curses windows - I don't think I can really improve upon what the ncurses man page says on this, so I'll just quote it:

The  ncurses  library permits
  manipulation of data structures,
  called windows, which can be thought
  of as two-dimensional arrays of
  characters representing all or part of
  a CRT screen.  A default window called
  stdscr, which is the size of the
  terminal screen,  is supplied.  Others
  may be created with newwin.
Note  that  curses  does not handle
  overlapping windows, that's done by
  the panel(3CURSES) library.  This
  means that you can either use stdscr
  or divide the screen into tiled
  windows and not using stdscr at all.
  Mixing the two will result in
  unpredictable,  and undesired,
  effects.
Windows  are referred to by variables
  declared as WINDOW *.  These data
  structures are manipulated with
  routines described here and elsewhere
  in the ncurses manual pages.  Among
  those, the most basic routines are
  move and addch.  More general
  versions  of  these routines are
  included with names beginning with w,
  allowing the user to specify a window.
  The routines not beginning with w
  affect stdscr.
After using routines to manipulate a
  window, refresh is called, telling
  curses to make the user's CRT screen
  look like stdscr.  The characters  in
  a  window are actually of type chtype,
  (character and attribute data) so that
  other information about the character
  may also be stored with each
  character.

So, in summary, you can safely ignore the whole window thing and just use the stdscr window.

A: Well, on UNIX-like systems such as BSD and Linux you definitely want to use ncurses as the terminal emulators make your life really miserable if you don't.
You should probably write yourself a simple wrapper, containing the functionality you need and implement it differently for different OSes. On Windows there are a few console functions you can use so that part won't be too hard.

A: Here's a little program to get you started.
#include <curses.h>

int main(void) {
  int ch;

  /* The whole program needs error-checking */
  initscr();
  noecho();
  cbreak();
  printw("Hit Ctrl+C to exit ...\n\n");
  for (;;) {
    ch = getch();
    printw("Value of char: %d (%02x)\n", ch, ch);
  }
  endwin();
  return 0;
}

Remember to tell the linker to add the libcurses library.
gcc ... -lcurses

A: There is a library providing Turbo C like console IO to Linux: TurboC
Also related: CONIO for DevC++


text:
Q: How do I create collision for all four sides of a wall in Flash CC? Here is my code:
/* Move with Keyboard Arrows
Allows the specified symbol instance to be moved with the keyboard arrows.

Instructions:
1. To increase or decrease the amount of movement, replace the number 5 below with the number of pixels you want the symbol instance to move with each key press.
Note the number 5 appears four times in the code below.
*/

stage.focus=stage;

var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;

obj01_mc.addEventListener(Event.ENTER_FRAME, moveDirection01);
stage.addEventListener(KeyboardEvent.KEY_DOWN, setPressed01);
stage.addEventListener(KeyboardEvent.KEY_UP, unsetPressed01);

function moveDirection01(event:Event)
{
    if (upPressed)
    {
        obj01_mc.y -= 5;
    }
    if (downPressed)
    {
        obj01_mc.y += 5;
    }
    if (leftPressed)
    {
        obj01_mc.x -= 5;
    }
    if (rightPressed)
    {
        obj01_mc.x += 5;
    }
}

function setPressed01(event:KeyboardEvent):void
{
    switch (event.keyCode)
    {
        case Keyboard.UP:
        {
            upPressed = true;
            break;
        }
        case Keyboard.DOWN:
        {
            downPressed = true;
            break;
        }
        case Keyboard.LEFT:
        {
            leftPressed = true;
            break;
        }
        case Keyboard.RIGHT:
        {
            rightPressed = true;
            break;
        }
    }
}

function unsetPressed01(event:KeyboardEvent):void
{
    switch (event.keyCode)
    {
        case Keyboard.UP:
        {
            upPressed = false;
            break;
        }
        case Keyboard.DOWN:
        {
            downPressed = false;
            break;
        }
        case Keyboard.LEFT:
        {
            leftPressed = false;
            break;
        }
        case Keyboard.RIGHT:
        {
            rightPressed = false;
            break;
        }
    }
}
//Wall Collision
stage.addEventListener(Event.ENTER_FRAME,handleCollision);

function handleCollision( e:Event ):void{

    if(obj01_mc.hitTestObject(wall01_mc))
       {
           obj01_mc.x+=5;
       }
    if(obj01_mc.hitTestObject(wall02_mc))
       {
           obj01_mc.x-=5;
           obj01_mc.y-=5;
           obj01_mc.width/10;
           obj01_mc.y+=10;
       }
    if(obj01_mc.hitTestObject(wall29_mc))
       {
           obj01_mc.x-=5;
       }
    if(obj01_mc.hitTestObject(wall13_mc))
       {
           obj01_mc.y+=5;
       }
    if(obj01_mc.hitTestObject(wall16_mc))
       {
           obj01_mc.y-=5;
       }
}

I'm having issues with wall02_mc, the other walls I have so far are only the borders and work fine for me. How do I make it so that obj_01 collides with all four sides of the wall, rather than half the sides it passes through?

A: first of all I think you have to know the position of the object before the displacement when you test your collision to be able to place the object at the good position close the wall.
After that I think it's better to handle all your game logic in the same function and not to have 2 ENTER_FRAME events handlers.
Here is my suggestion:
stage.focus=stage;

var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;

stage.addEventListener(KeyboardEvent.KEY_DOWN, setPressed01);
stage.addEventListener(KeyboardEvent.KEY_UP, unsetPressed01);

stage.addEventListener(Event.ENTER_FRAME,gameLoop);

function setPressed01( event:KeyboardEvent ):void
{
    switch (event.keyCode)
    {
        case Keyboard.UP:       upPressed = true;       break;
        case Keyboard.DOWN:     downPressed = true;     break;
        case Keyboard.LEFT:     leftPressed = true;     break;
        case Keyboard.RIGHT:    rightPressed = true;    break;

    }
}

function unsetPressed01( event:KeyboardEvent ):void
{
    switch (event.keyCode)
    {
        case Keyboard.UP:       upPressed = false;      break;
        case Keyboard.DOWN:     downPressed = false;    break;
        case Keyboard.LEFT:     leftPressed = false;    break;
        case Keyboard.RIGHT:    rightPressed = false;   break;
    }
}

/** the main game loop **/
function gameLoop( event:Event ):void
{
    // get the object position
    var x:int = obj01_mc.x;
    var y:int = obj01_mc.y;

    // calculate your move
    if( upPressed )     y -= 5;
    if( downPressed )   y += 5;
    if( leftPressed )   x -= 5;
    if( rightPressed )  x += 5;

    // do the collition test and the placement of your object
    placeObject( obj01_mc, wall01_mc, x, y );
    placeObject( obj01_mc, wall02_mc, x, y );
    placeObject( obj01_mc, wall29_mc, x, y );
    placeObject( obj01_mc, wall13_mc, x, y );
    placeObject( obj01_mc, wall16_mc, x, y );
}

/** place the object after the collision test **/
function placeObject( object:DisplayObject, collisionObject:DisplayObject, targetX:int, targetY:int ):void
{
    // pass through horizontally
    if( targetX > collisionObject.x-object.width && targetX < collisionObject.x+collisionObject.width )
    {
        // case pass trough by the left, return to the left border
        if( object.x < targetX )    object.x = collisionObject.x-object.width;
        // case pass trough by the right, return to the right border
        if( object.x > targetX )    object.x = collisionObject.x+collisionObject.width;
    }
    // no horizontal collision
    else
    {
        object.x = targetX;
    }

    // pass through vertically
    if( targetY > collisionObject.y-object.height && targetY < collisionObject.y+collisionObject.height )
    {
        // case pass trough by the up, return to the up border
        if( object.y < targetY )    object.y = collisionObject.y-object.height;
        // case pass trough by the bottom, return to the bottom border
        if( object.y > targetY )    object.y = collisionObject.y+collisionObject.height;
    }
    // no vertical collision
    else
    {
        object.y = targetY;
    }
}

Note: in this example your functions handleCollision and moveDirection01 have been replaced by gameLoop function. So just the gameLoop function react to the ENTER_FRAME Event.
I hope this could help you :)


text:
Q: SAPUI5: Getting argument as undefined, passed while routing from one view to another I am passing arguments from Master to Detail view while routing, but getting it as undefined.
Code from MasterController.js
onPressItemDetail: function(evt) {
    var object = evt.getSource().
    getBindingContext().
    getModel().
    getProperty(evt.getSource().getBindingContext().getPath());

    var context = {
        object: object,
        bindingContext: evt.getSource().getBindingContext()
    };
    var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
    oRouter.navTo("fourth", context);
}

Code from DetailController.js
onInit: function() {
    var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
    oRouter.attachRouteMatched(function(oEvent) {
        if (oEvent.getParameter("name") !== "fourth") {
            return;
        }
        var object = oEvent.getParameter("arguments").object;
        var bindingContext = oEvent.getParameter("arguments").bindingContext;

    }, this);
}

Routing configuration from Component.js
"routing": {
    "config": {
        "routerClass": "sap.m.routing.Router",
        "viewType": "XML",
        "viewPath": "umicoreMP.view",
        "controlId": "app",
        "controlAggregation": "pages"
    },
    "routes": [{
        "pattern": "",
        "name": "first",
        "target": "first"
    }, {
        "pattern": "secondview",
        "name": "second",
        "target": "second"
    }, {
        "pattern": "thirdview",
        "name": "third",
        "target": "third"

    }, {
        "pattern": "changeitem",
        "name": "fourth",
        "target": "fourth"
    }],
    "targets": {
        "first": {
            "viewName": "FirstView"
        },
        "second": {
            "viewName": "SecondView"
        },
        "third": {
            "viewName": "ThirdView"
        },
        "fourth": {
            "viewName": "ChangeItem"
        }
    }
}

A: Route pattern must contain the desired parameter in the following format:
{
  "pattern": "changeitem/{object}",
  "name": "fourth",
  "target": "fourth"
}

oRouter.navTo() contains the desired route and an object which contains the parameters of the route:
oRouter.navTo("fourth", {object: property});

Passing the bindingcontext as a parameter is not recommended (and in this case, not possible) because it's an object and it's not safe to pass object like this in URL.
If you want to access the data which belongs to the property passed to the Detail view, you can fetch it from the model.
Assuming that your model is assigned to the component, each view has access to that. Here you can bind the proper entry of the model to the view in several ways, for example:
oRouter.attachRouteMatched(function (oEvent) {
  if (oEvent.getParameter("name") !== "fourth") {
    return;
  }
  var object = oEvent.getParameter("arguments").object;
  this.getView().bindElement({path: object, model: "nameOfTheModel"});
}

The exact value of the path depends on the model (JSONModel or ODataModel). Model name should be defined in component.js.
With this bindElement function call you can assign the specific row of the model to the view, so controls in the view can access properties of the selected data entry with relative binding:
<Text text="{propertyInModel}" />


text:
Q: Error Installing Linuux-image-5.15.0-46-generic I am not familiar with computer programming terminology.
I was installing Ubuntu in Oracles Virtual Box and towards the end of the installation I get this error:

Error Installing Linux-image-5.15.0-46-generic
Installed linux-image-5.15.0-46-generic package post-installation script subprocess returned error exit status 1

I click "ok' then:

Error while installing packages
An error occurred while installing packages:
E:Sub-process/usr/bin/dpkg returned an error code (1)
The following packages are in a broken state:
This may be due to using an old installer image, ort it may be due to a bug in some of the packagees listed above. More details may be found in /var/log/syslog. The installer will try to continue anyway, but may fail at a later point, and will not be able to install or remove other packages (possibly including itself) from the installed system. You should first look for newer versions of your installer image, or failing that report the problem to your distributor.

It say installation complete. So I clicked "Restart Now". This is what I get.

/dev/sda3: clean, 214055/622592 files, 2361554/2489344 blocks
[ 8.307596] mtd device must be supplied (device name is empty)
[ 9.045373] [drm:vmw_host_printf [vmwgfx]] ERROR Failed to send host log me message.

I deleted the virtual folder, downloaded fresh virtual box and ubuntu, re-tried installing.
Pls. help.
Thank you.

A: JRey, I had the same issue, after many reinstallations of Ubuntu on my VM I tried to allocate more Memory to the VM (20GB) and my installation was successful


text:
Q: h:message show Messages in different positions i have a problem in h:message, it shows the requiredMessage in a different position of the validatorMessage, and i want it to show them in the same position!!
here is my code :
<h:form>
    <h:panelGrid columns="3" width="800" border="0">
        <p:outputLabel value="login *" />
        <p:inputText id="login" value="#{acteurAuth.login}" label="Login"
                     required="true" requiredMessage="Login est obligatoire"
                     validatorMessage="5-->6">
            <f:ajax event="blur"  render="loginMsg" />
            <f:validateLength minimum="5" maximum="6"/>
        </p:inputText>
        <h:message id="loginMsg" for="login"/>`

        <p:outputLabel value="mot de passe  *" />
        <p:password id="pwd" value="#{acteurAuth.password}" label="mot de passe"
                    required="true" requiredMessage="Mot de passe est obligatoire" >
            <f:ajax event="blur"  render="pwdMsg" />
        </p:password>
        <h:message id="pwdMsg" for="pwd"/>

        <p:commandButton value="Valider"
                         action="#{acteurAuth.authentification()}" />
    </h:panelGrid>
</h:form>


text:
Q: DOMPDF only showing image watermark on the last page I'm trying to display an image watermark using DomPdf, but it only appears on the last page. I've looked on some sites, but I haven't found anything related.
That's my code:
<?php
    require_once 'dompdf/autoload.inc.php';

    //referenciar o DomPDF com namespace
    use Dompdf\Dompdf;
    //Referenciar o NameSpace Options
    use Dompdf\Options;

    //Definir Options para habilitar PHP incorporado.
    $options = new Options();
    $options->set('isPhpEnabled', 'true');

    //Criando a Instancia
    $dompdf = new Dompdf($options);

    // Carrega seu HTML
    $dompdf->loadhtml("
https://www.TutorialsWebsite.com

Welcome to Tutorials Website

Tutorialswebsite is a leading online education portal that helps technologies, software, business and creative skills readers to learn new skills at their own place from the comforts of their drawing rooms. Individual, corporate and academic members have access to learn anything on tutorialswebsite.com likes video tutorials, blogs content etc.

From 5 years, we worked our way to adding new fresh articles on topics ranging from programming languages that helps students, leaders, IT and design professionals, project managers or anyone who is working with software development, creatives and business skills.

Mission

Our mission is to deliver easy and best online resources on programming and web development to encourage our readers acquire as many skills as they would like to. We offer the useful and best tutorials for web professionals-developers, programmers, freelancer free of cost. We don't force our readers to sign up with us or submit their details.

About Author

Pradeep Maurya is the Professional Web Developer and Founder of  "Tutorialswebsite". He lives in Delhi and loves to be a self dependent person. As an author, he is trying his best to improve this platform day by day.
You can contact him @facebookWebsite: https://www.pradeepmaurya.in

'");

    $dompdf->setPaper('A4', 'portrait');

    //Renderizar o html
    $dompdf->render();

    //Instanciar o Canvas
    $canvas = $dompdf->getCanvas();

    //Recuperar Altura e Largura da página
    $width = $canvas->get_width();
    $height = $canvas->get_height();

    //Especifica a Imagem de Marca D'Água
    $imageURL = 'img/forper.png';
    $imgHeight = 511;
    $imgWidth = 250;

    //Define a Opacidade da Imagem
    $canvas->set_opacity(.3);

    //Especifica as posições horizontal e vertical
    $x = (($width - $imgWidth) / 2);
    $y = (($height - $imgHeight) / 2);

    //Adiciona a Imagem ao PDF
    $canvas->image($imageURL, $x, $y, $imgWidth, $imgHeight);

    //Exibibir a página
    $dompdf->stream(
        "$nip.pdf",
        array(
            'Attachment' => false //Para realizar o download somente alterar para true
        )
    );
?>

I changed the HTML because the old one was too big.
If there is only one page, the watermark will appear correctly, but if there are two or more pages, the image will only appear on the last one.
I've tried to add the code below to add the watermark in the first page, but the image is in front of the text.
// Dirty fix for images and lines
    $canvas->page_script('
        $image = \'img/image.png\';
        // $pdf is the variable containing a reference to the canvas object provided by dompdf
        $pdf->image($image, ' . $x . ', ' . $y . ', ' . $imgWidth . ', ' . $imgHeight . ');
    ');

A: You have to use page_script function (like you did) but you need to edit the canvas inside too.
To avoid formatting error and keeping a good syntax for maintaining, I suggest adding a new file with the canvas code only.
canvasScript.php
$canvas = $dompdf->getCanvas();

$width = $canvas->get_width();
$height = $canvas->get_height();

$imageURL = 'img/forper.png';
$imgHeight = 511;
$imgWidth = 250;

$canvas->set_opacity(.3);

$x = (($width - $imgWidth) / 2);
$y = (($height - $imgHeight) / 2);

$canvas->image($imageURL, $x, $y, $imgWidth, $imgHeight);

Your code
// [...]
// Renderize HTML
$dompdf->render();

// Add watermark to all pages
$canvasScript = file_get_contents('/canvasScript.php');
$canvas->page_script($canvasScript);

$dompdf->stream("your_pdf.pdf");

dompdf has no documentation and lack this kind of use, I recommend using mpdf/mpdf next time.


text:
Q: can i swich from experienced C++ developer to a java application developer? HI
I am a B.E(CS) fresher.I am searching for a job in IT.There are openings for few C++
developers than java developers.Once i get 1-2 years of experience as C++ developer,can
i switch to a java application developer(for survival).

A: If your smart you can switch to anything. Really.
Specifically regarding programming languages, a language is like a tool used for a particular problem. See yourself as a carpenter rather than a 'hammer operator' or 'saw operator'.
See similar questions:
Learning multiple languages

A: Sure you can.  Just don't underestimate the effort to learn the language well - you will be benefitted by the syntax looking familiar, and flabbergasted at the size of the runtime library.
If you go for this, write a lot of code.

A: Possible, but the environments/frameworks for each mean they are more different than the cosmetic syntax similarities might suggest. Don't assume they're basically interchangeable.

A: From an employers point of you I'd say previous 1-2 years experience will not count for much if anything. Friends of mine who have tried this in the past have had to drop a lot in salary and almost start in junior positions again. With only 1-2 years of experience that might not make a big difference in your case.


text:
Q: Which style options are available for polylines in Leaflet? I added a polyline layer as GeoJSON within Leaflet and want to style it.
The following options to set the style I could find (and which work) are:

*

*color

*weight

*opacity

What are other available options, is it possible to add a border around the line?

A: The available options for styling L.Polylines are clearly documented in the Leaflet API reference. Please note that styling options are common with circles, polygons and any other paths, and so appear as "Options inherited from L.Path".

Is it possible to add a border around the line?

No, it's not possible.
Depending on your needs, you might want to either buffer the line, or to display the line twice, displaying the heavier stroke underneath to serve as a "casing" of sorts.

A: This seems to be a highly ranked result on search engines so I thought I would stop in and update + add to it.
The Leaflet documentation seems to have been updated since the original answer was provided (v1.03 vs v1.40 at the time of this posting), but even then the documentation on polylines hasn't ever identified any style options outside of the 3 used in the example (that the OP mentions). That makes finding the rest of the options somewhat time consuming. Those options are actually inherited from Path and that's where you'll find the documentation on them. I've attached an image of the options available and tested as many of them as I could to see if they work (2nd column), but only in so far as my current project can make use of them.

NOTE the last item, 'className'. This will allow you to set a CSS class name and use CSS (or SASS) to style your Polyline instead of hard coding it. It should also be noted that CSS rules seem to override the Leaflet style options you configure in your code. Unfortunately, that still doesn't get you borders, ie. border: 1px solid red; doesn't work. This is due to the fact that these aren't HTML elements, but rather SVG.
SVG doesn't recognize the concept of a "border" aka a line around an object. A Polyline is already a "line". SVG does recognize the concept of fill and stroke, however, which can be used to achieve a border-like effect. If you draw a polygon around the polyline and set the stroke to your desired border style and the fill color to your desired line color you'll get a "border". You can read more on that approach here: https://stackoverflow.com/questions/36132689/how-to-convert-polyline-with-weight-to-polygon-in-leaflet
And in text those Path options are:

*

*stroke

*color

*weight

*opacity

*lineCap

*lineJoin

*dashArray

*dashOffset

*fill

*fillColor

*fillOpacity

*fillRule

*bubblingMouseEvents

*renderer

*className

A:
it possible to add a border around the line?
Yes, without drawing draw the line twice  :

• The following works only with Mozilla Firefox
in your CSS file add:
path.stroke-polyline {
    filter: drop-shadow(1px 1px 0 #fff) drop-shadow(-1px -1px 0 #FFF) drop-shadow(1px -1px 0 #FFF) drop-shadow(-1px 1px 0 #fff);
}

• then add the class stroke-polyline to the polyline

A: As mentionned above, you can draw the line twice to get a line border:
var style = {
color: "#008000",
weight: 5,
opacity: 0.6
 },
stroke = {
color: "#fff",
weight: 7,
opacity: 0.4
};
polyline_2 = new L.Polyline(polylinePoints, stroke);
polyline_2.addTo(active_track);
polyline = new L.Polyline(polylinePoints, style);
polyline.addTo(active_track);


text:
Q: Oracle job scheduler not working i create a job in oracle which will run in every minute but the problem is job is create successfully but not run on time
execute PACKAGE_BATCH.USP_TERMIANTE_SUSPENSION;
BEGIN
    DBMS_SCHEDULER.CREATE_JOB (
            job_name => '"LTR"."TERMINATE_SUSPENSION_JOB"',
            job_type => 'STORED_PROCEDURE',
            job_action => 'LTR.PACKAGE_BATCH.USP_TERMINATE_SUSPENSION',
            number_of_arguments => 0,
            start_date => sysdate,
            repeat_interval => 'FREQ=MINUTELY;BYMINUTE=1',
            end_date => NULL,
            enabled => TRUE,
            auto_drop => TRUE,
            comments => 'Terminate Suspension When End Date is equal to Current Date');

            DBMS_SCHEDULER.set_attribute
            ( name => '"LTR"."TERMINATE_SUSPENSION_JOB"',
            attribute => 'job_action',
            value => 'LTR.PACKAGE_BATCH.USP_TERMINATE_SUSPENSION');

            DBMS_SCHEDULER.SET_ATTRIBUTE(
             name => '"LTR"."TERMINATE_SUSPENSION_JOB"',
             attribute => 'logging_level', value => DBMS_SCHEDULER.LOGGING_RUNS);

    DBMS_SCHEDULER.enable(
             name => '"LTR"."TERMINATE_SUSPENSION_JOB"');
END;

A: FREQ=MINUTELY;BYMINUTE=1

This will make the job run at every "1"st minute. So 12:01, 1:01, 2:01 etc.
If you need to make it run every minute - FREQ=MINUTELY is sufficient or you can add BYSECOND=0 if you want to ensure it runs at exactly 12:01:00, 12:02:00, 12:03:00 etc.

A: To keep it simple, see these examples:

*

*Every minute
Repeat interval using calendaring syntax.
'freq=minutely;'

Repeat interval using dates and timestamps.
'sysdate + 1/24/60'
'systimestamp + 1/24/60'

'sysdate + interval ''1'' minute'
'systimestamp + interval ''1'' minute'

*

*Every minute, on the minute
Repeat interval using calendaring syntax.
'freq=minutely; bysecond=0;'
Repeat interval using dates and timestamps.
'trunc(sysdate, ''MI'') + 1/24/60'
'trunc(systimestamp, ''MI'') + 1/24/60'

'trunc(sysdate, ''MI'') + interval ''1'' minute'
'trunc(systimestamp, ''MI'') + interval ''1'' minute'

More example here http://oracle-base.com/articles/10g/scheduler-10g.php#every_minute