Linear Algebra matrix $Ax=b$ true or false nullspace

Question: $Ax=b$
$m$ number of Rows
$n$ number of columns
true or false
A) If $n > m$, given any $b$ you can always solve $Ax=b$.
The answer: False. Counterexample: A is the zero matrix.

We have unknowns more than equations, so we can always solve $Ax=b$. Why the answer is false?
  And even if $A$ is the zero matrix we have the matrices x = zeros then $b$ zeros so there is always answer!!
  Can anyone explain why the answer is false? How can he proved false by $A$ is the zero matrix?

B) If $n < m$, the only solution of $Ax=0$ is $x=0.$
The answer: False. Counterexample: let $A$be the zero matrix.

I understand why it is false but I'm wondering, is there any special case makes this statement true?

Edit:
I made a matrix $A= 2$ rows $\times 1$ column contains $(1,0)$ and assume Ax=0 as the statement, then the only solution is when x=0 because we can't use row echelon form any more. is what I did correct to make the statement true?
Answer: For A), the statement is that given any $b \in \mathbb{R}^n$, there is a solution to the matrix equation $Ax = b$.  But if $A$ is the zero matrix, then there is only one $b$ for which there is a solution, namely $b=0$.  Since there are some $b$ for which $Ax = b$ cannot be solved, the original statement is false.
For B), the condition that the only solution to $Ax=0$ is $x=0$ means that there are no free variables in the reduced row echelon form of $A$.  Or said differently, when you apply Gauss-Jordan elimination, you must get $n$ pivots (or equivalently, $n$ non-zero rows).  Said still another way, the only solution to $Ax = 0$ is $x=0$ exactly when the rank of $A$ is equal to $n$.
Comment: Can you give an example of a matrix its rank equal to n? thank you so much
Comment: The $n \times n$ identity matrix has rank $n$.
Comment: I mean when n < m as the condition because nxn doesn't satisfy the condition. Can you give an example of a matrix its rank is equal to n and n < m ? Thank you very much for your answer it was really helpful. I will wait your example and thanks again in advance.
Comment: Sure, just add $m-n$ rows of zeroes to the $n \times n$ identity matrix.  This will be an $m \times n$ matrix with rank $n$.  Do you see why?  The most general example of an $m \times n$ matrix of rank $n$ is by using $n$ linearly independent column vectors in $\mathbb{R}^m$.
Comment: I'll tell you what I did
Comment: I'm sorry for bothering you but I just want to make sure that I understand. Please just tell me if it is correct what I did or not (read the Edit please). Thank you very much I really appreciate it.
Comment: You're correct that in your example, the only solution is $x = 0$.  But it is still in echelon form.  You should make sure you understand why the matrix $A = \begin{pmatrix} 1 \\ 0 \end{pmatrix}$ is in reduced row echelon form.
Comment: Yes I already made this matrix because it's in row echelon form. Thank you very much.
Answer: Let $f$ the canonical linear application associated to the matrix $A$ hence
$$f\colon \mathbb{R}^n\to \mathbb{R}^m$$
A) given any $b$ we can solve $f(x)=b$ if $f$ is surjective i.e. $\mathrm{rank}(f)=\mathrm{rank}(A)=m$
B) the only solution to $f(x)=0$ is $x=0$ if $f$ is injective i.e. $\ker(f)=\ker(A)=\{0\}$
so by the Rank-nullity theorem $\mathrm{rank}(f)=\mathrm{rank}(A)=n$
Comment: Maybe tell him what the canonical linear application is


IcCube - displaying row numbers in icCube Table

Question: In Google Table there is an option to show the row number. But in the other Tables this option is not available unfortunately. We don't use Google Table, since the IcCube Table is just rendering way faster with lots of data.
One workaround we learned about would be to create a calculated measure with a constant value for example : Row as 42 and then setup a custom renderer as following:
function(context) {
    return ""+context.getRowIndex()+"";
}

Unfortunately if the table is exported, the constant value (i.e. 42) is displayed and not the row number.
Is there a useful way to get row numbers in the other tables in icCube?
Answer: One possibility is to use a calculated member to get the line numbers (it's not going to work with drilldowns).
Assuming you've two axis, the query would look like :
WITH
   FUNCTION _currentTuple(_t) as CASE _t.count
            WHEN 1 THEN _t.hierarchy.currentMember
            WHEN 2 THEN ( _t.Item(0).hierarchy.currentMember,_t.Item(1).hierarchy.currentMember)
            // you get the idea
            ELSE  Error( "_currentTuple- " + Str(_t.count)  )
           END
   MEMBER [Line Position] as Rank( _currentTuple( Axis(1)(0) )  ,   Axis(1) )
SELECT
 [Line Position] on 0,
 [Customers].[Geography].[Region].members * [Product].[Product].[Category] on 1
FROM [Sales]

Which make us think we should add a function to get the current axis members in an easier way.
_hope it helps


Finding expectation of waiting time

Question: Can someone explain this solution to me? The question was find E[W1 | X(t) = 2] where W1 is the time until the first event occurs and X(t) is a Poisson process. V1 represents the smallest of the uniform variables that are a part of this theorem. I understand the first line but I am unsure why they proceed to P(V1>s) and how they get (t-s/t)^2. I am also confused with how they calculate the expectation. Thanks for the help!
Answer: They are calculating $\renewcommand{\Pr}{\mathbb{P}} \Pr(V_1 > s)$ because $V_1$ is nonnegative and has the same distribution as the minimum of two i.i.d. random variables, so this quantity turns out to be convenient in two ways.
First, $\Pr(V_1 > s)$ can be easily employed to calculate the expected value of $V_1$. For any nonnegative random variable $X$, $\mathbb{E}(X) = \int_0^\infty \Pr(X > x) \,\mathrm{d}x$.
Now, since $X(t)$ is a Poisson process and we are conditioning on the fact that $X(t) = 2$, then the points of arrival are distributed as the order statistics of two uniform random variables on $[0,t]$. Thus, $V_1 = \mathrm{min}(U_1, U_2)$, equality here being in distribution, where $U_1$ and $U_2$ have a density that is $1/t$ on $[0,t]$ and 0 on $\mathbb{R} \setminus [0,t]$.
Hence,
$$
\Pr(V_1 > s) = \Pr(U_1 > s, U_2 > s) = \Pr(U_1 > s) \Pr(U_2 > s) = \big(\Pr(U_1 > s)\big)^2 \>.
$$
Finally,
$$
\Pr(U_1 > s) = \int_s^t \frac{1}{t} \mathrm{d}u = \frac{t - s}{t} \> .
$$
From here the rest is easy.

Finding expectation of waiting time


How do I find more resources?

Question: I have built some settlements but I need help. I can not find supplies that I need. I know that you can break stuff down and all that other good stuff. I'm specifically looking for copper and aluminum. Where and how can I find more of these?
Comment: What sort of supplies are you looking for?
Comment: Copper and aluminum.
Answer: You are able to mark specific resources in your Pip-Boy so that when you encounter Junk that will break down into those resources, they will be marked with a magnifying glass icon. (See here)

However, since you said you are looking specifically for Copper and Aluminum, here is a list of all the sources of each of them:
Copper:

Beaker Stand
Blue Table Lamp
Bone Cutter
Broken Lamp
Broken Light Bulb
Bunsen Burner
Condenser Power Module
Cooking Pot
Copper Bar
Fuse
Gilded Grasshopper
High-powered Magnet
Hot Plate
Light Bulb
Magnifying Glass
Power Relay Coil
Pre-war Lamp
Shadeless Lamp
Stew Pot
Telephone
Vacuum Tube
Yellow Table Lamp

As well as shipments of Copper.
Aluminum:

Alarm Clock
Aluminum Can
Aluminum Canister
Applicator
Cake Pan
Carlisle Typewriter
Cauterizer
Coolant Cap
Ear Examiner
Hubcap
Inactive Distress Pulser
Ring Stand
Sensor
Spanner
Surgical Tray
Sweeper
Toy Rocketship
Tray
Tri-tool
TV Dinner Tray
Tweezers
Wakemaster Alarm Clock

And of course, you can buy shipments of Aluminum.
Comment: Corvega Assembly Plant in particular has a bunch of hubcaps and coolant caps you can scrap for aluminum
Comment: Mahkra Fishpacking has a bunch of aluminum trays.
Comment: @Robert__garnet I'm not sure how far you are in the game, but once you get to a *certain Institution*, you'll have aluminum for days.
Comment: not far only level 24

How do I find more resources?


Abort execution of Proguard if a note or waning has been given

Question: Is it possible to let Proguard stop execution after raising a note or warning?
Sometimes Proguard tells me to fix some errors, but most of the time the building of the APK file just continues and I have to manually check if any notes or warnings have been given which might need to get fixed.
For instance the following note will be displayed but the APK file will continue to be build after Proguard is finished (real package name is replaced with ***):
Note: the configuration keeps the entry point 'nl.***.InputLayout { void setSelectedItemContainer(nl.***.ItemContainerObject); }', but not the descriptor class 'nl.***.ItemContainerObject'
Answer: By default, ProGuard will fail the build if any warnings are output during the build, unless you have the rule -ignorewarnings (or -dontwarn) specified in your configuration.
Notes are usually not critical and do not lead to a build failure.
Comment: So it's not possible to halt execution once a note has been raised?


Create an ASCII thermometer using MessageFormat

Question: I am using Java's MessageFormat class to create a string that takes several condition statements as parameters using the format method. With it I have created a thermometer using ASCII characters which takes in a random number as celsius and depending on that number, inserts asterisk characters into the string at specific locations depending on a condition, e.g. ((celsius >= 25) ? "*" : " "). In other words, the asterisks represent the temperature level in a thermometer depending on the temperature value.

At the moment I am using similar if statements in each of the 14 parameters which then determines if it should add an asterisk in said location temp >= location or an empty space temp <= location. I'm sure there is a much more efficient and cleaner way in doing this using another method, e.g. embedded for loop, regex, function, built-in method, etc.
Here's an example of the code (beware escape characters):
// random value between -35 and 40
double celsius = Math.round(Math.random() * (40 - 35) - 35);

// ASCII Thermometer
String meter = MessageFormat.format(
                "     ______________________"
                + "\r\n     |   ^F     _    ^C   |"
                + "\r\n     |  100  - |{0}| -  40  |"
                + "\r\n     |   90  - |{1}| -  30  |"
                + "\r\n     |   80  - |{2}| -  25  |"
                + "\r\n     |   70  - |{3}| -  20  |"
                + "\r\n     |   60  - |{4}| -  15  |"
                + "\r\n     |   50  - |{5}| -  10  |"
                + "\r\n     |   40  - |{6}| -   5  |"
                + "\r\n     |   30  - |{7}| -   0  |"
                + "\r\n     |   20  - |{8}| -  -5  |"
                + "\r\n     |   10  - |{9}| - -10  |"
                + "\r\n     |    0  - |{10}| - -20  |"
                + "\r\n     |  -10  - |{11}| - -25  |"
                + "\r\n     |  -20  - |{12}| - -30  |"
                + "\r\n     |  -30  - |{13}| - -35  |"
                + "\r\n     |         '***`       |"
                + "\r\n     |       (*****)      |"
                + "\r\n     |        `---'        |"
                + "\r\n     |____________________|"
                + "\r\n\r\n",
        ((celsius >= 35) ? "*" : " "),
        ((celsius >= 30) ? "*" : " "),
        ((celsius >= 25) ? "*" : " "),
        ((celsius >= 20) ? "*" : " "),
        ((celsius >= 15) ? "*" : " "),
        ((celsius >= 10) ? "*" : " "),
        ((celsius >= 5) ? "*" : " "),
        ((celsius >= 0) ? "*" : " "),
        ((celsius >= -5) ? "*" : " "),
        ((celsius >= -10) ? "*" : " "),
        ((celsius >= -15) ? "*" : " "),
        ((celsius >= -20) ? "*" : " "),
        ((celsius >= -25) ? "*" : " "),
        ((celsius >= -30) ? "*" : " "));

Answer: Do you want this?
public static void main(String[] args) {
    // random value between -35 and 40
    double celsius = Math.round(Math.random() * (40 - 35) - 35);

    final String s = "     ______________________"
            + "\r\n     |   ^F     _    ^C   |"
            + "\r\n     |  100  - |{0}| -  40  |"
            + "\r\n     |   90  - |{1}| -  30  |"
            + "\r\n     |   80  - |{2}| -  25  |"
            + "\r\n     |   70  - |{3}| -  20  |"
            + "\r\n     |   60  - |{4}| -  15  |"
            + "\r\n     |   50  - |{5}| -  10  |"
            + "\r\n     |   40  - |{6}| -   5  |"
            + "\r\n     |   30  - |{7}| -   0  |"
            + "\r\n     |   20  - |{8}| -  -5  |"
            + "\r\n     |   10  - |{9}| - -10  |"
            + "\r\n     |    0  - |{10}| - -20  |"
            + "\r\n     |  -10  - |{11}| - -25  |"
            + "\r\n     |  -20  - |{12}| - -30  |"
            + "\r\n     |  -30  - |{13}| - -35  |"
            + "\r\n     |         '***`       |"
            + "\r\n     |       (*****)      |"
            + "\r\n     |        `---'        |"
            + "\r\n     |____________________|";

    final int[] celsiusDegreeCompare = new int[]{
            35, 30, 25, 20, 15, 10, 5, 0, -5, -10, -20, -25, -30, -35
    };

    final String[] parameters = new String[14];

    IntStream.range(0, parameters.length).forEach(i -> {
        parameters[i] = (celsius >= celsiusDegreeCompare[i]) ? "*" : " ";
    });

    // ASCII Thermometer
    String meter = MessageFormat.format(s, parameters);

    System.out.println("celsius: " + celsius);
    System.out.println(meter);
}

Result:
celsius: -31.0
     ______________________
     |   ^F     _    ^C   |
     |  100  - | | -  40  |
     |   90  - | | -  30  |
     |   80  - | | -  25  |
     |   70  - | | -  20  |
     |   60  - | | -  15  |
     |   50  - | | -  10  |
     |   40  - | | -   5  |
     |   30  - | | -   0  |
     |   20  - | | -  -5  |
     |   10  - | | - -10  |
     |    0  - | | - -20  |
     |  -10  - | | - -25  |
     |  -20  - | | - -30  |
     |  -30  - |*| - -35  |
     |         ***`       |
     |       (*****)      |
     |        `---        |
     |____________________|

Answer: Since you are trying to draw an image rather than printing a String i would advice you to create a class that is responsible for that, namely AsciiImageThermometerPrinter. That class would be able to print() a certain state of temperature.
To build your String i suggest to use StringBuilder rather than MesssgeFormat.
As for creating your output i would use an line-based middle part that draws line-by-line your thermometer, a part for the header and one for the bottom-part.
what would be different?
You could simply provide thermometers with different ranges and units. you simply provide longer or shorter thermometers.
Your code would be testable and other developer would understand your code easier.
Your code would be more SOLID.
Comment: Sorry that answer was written from my mobile phone. Later, when im in the office i will provide some examples for the `StringBuilder` parts.


Rails Active Admin display belongs_to column

Question: How do I display a column from the relational belongs_to record? group.title is the column I want to display. Questions belongs to group.
column :group doesn't display anything
index do
selectable_column
id_column
column :question
column :group
actions

end
Answer: Try this:
column :group do |your_model|
  link_to your_model.group.title, admin_group_path(your_model.group)
end


How to enable Auto Sign-in after successfully Sign-up in Amplify AWS Cognito?

Question: I'm trying to do on-page passwordless authentication with only phone number, and I want to implement auto sign-in after sign-up automatically, any ideas?
I have enabled mfa for both login and signup, but amplify not signing the user after signup!
Answer: you are working with AWS Amplify and trying to implement on-page passwordless authentication with phone numbers in an Android Studio project, and you want users to be automatically signed in after signing up, even with MFA enabled. The automatic sign-in after sign-up might not be the default behavior, so you'll need to handle this logic in your code.
When a user signs up with their phone number, use the Amplify Auth category to initiate the sign-up process.
Amplify.Auth.signUp(
    phoneNumber, // The phone number provided by the user
    password,    // A temporary password (required for MFA)
    AuthSignUpOptions.builder().build(),
    result -> {
        // Sign-up successful, proceed to verification
        String confirmationCode = result.getNextStep().getCodeDeliveryDetails().getDestination();
        // Show a confirmation code entry UI to the user
    },
    error -> {
        // Handle sign-up error
    }
);

After sign-up, Amplify will send a confirmation code to the user's phone.
Once the user enters the confirmation code, you can use Amplify.Auth.confirmSignUp to confirm the user.
Amplify.Auth.confirmSignUp(
    phoneNumber,
    confirmationCode,
    result -> {
        // Confirmation successful, now sign in the user
        Amplify.Auth.signIn(
            phoneNumber,  // The phone number used for sign-up
            password,
            authResult -> {
                // User is signed in
            },
            authError -> {
                // Handle sign-in error
            }
        );
    },
    error -> {
        // Handle confirmation error
    }
);

Hopefully, it will help!!!


Where did the meteor fall?

Question: I have found a statue in Legend of Grimrock 2 that says it saw where the meteor fell.
Where did it fall?
Answer: Im not sure how much I can say without total spoilers. Are you familiar with the concept of triangulation?
Specifics follow:

There are two sets of eyes, one left, one right, you need to find both and figure out the exact point at which the two lines from the statues intersect.
Comment: And they're really far from one another.

Where did the meteor fall?


Google Chromium asks for keyring to unlock 14.04, but I don't want the password to be the same as my ubuntu login

Question: I don't want this prompt to use my default ubuntu login, I would like this to match the password I would use either on a chromebook, mac, or windows. In other words, similar behavior to the other operating systems.
How would I make it so that I typed in my chromebook login, for example?

Text of the prompt:
"Enter password for keyring 'Chromium' to unlock"
"An application wants access to the keyring 'Chromium', but it is locked"
Comment: The other questions did not ask to 'have a different' password than the login password. Please unmark the duplicate tag as I don't think it is appropriate here.
Answer: Specifically for  14.04
WARNING: Do not change your password to blank, as other answers have suggested. This could be dangerous.
1.) Run Password and Keyring or seahorse (if you dont have it installed, you can install it by running following command in teminal sudo apt install seahorse)
2.) File -> New (or Ctrl+N)

3.) Name a new 'Password Keyring' as "Chromium"

4.) Enter your 'Chromium' password.

End Result is different passwords for your login and your google chrome keyring, keeping them separate.
Comment: Two things: 1) it may be possible you are using 16.04, this Q/A applies only to 14.04 2.) The key should be named 'Chromium' to work, and nothing appears named 'Chromium Safe Storage'. This may be a question in it of itself, and less of a comment.
Comment: I should note that this functions the same as windows, but in windows it only asks for the password once and stores it for some reason.
Comment: I have created a new keyring, deleted the "Chromium Safe Storage" from the "default" keyring, locked it and restarted Chromium, but it still asks to unlock the "default" keyring.  How do I tell Chromium to use this new keyring I have created?
Comment: Ah, I hadn't realized the name has to be exactly "Chromium". I'll try again. I'm actually using Debian, not Ubuntu, but I'm guessing Chromium is the same for both?
Comment: Can you elaborate the solution for Ubuntu 16.04 ?
Comment: https://askubuntu.com/questions/867/how-can-i-stop-being-prompted-to-unlock-the-default-keyring-on-boot?noredirect=1&lq=1


Access token and user ID

Question: I'm currently trying to authenticate an angular 7 app with ADFS 2016 (using angular-oauth2-oidc). So far, it works pretty well. When I access the application, I'm redirected to ADFS login page where I enter my credentials and gets tokens.
Now, when the app calls the a web API, it send the access token in the request headers. The access token returned by ADFS looks like this:
{
  "aud": "microsoft:identityserver:xxx",
  "iss": "http://xxx/adfs/services/trust",
  "iat": 1554561406,
  "nbf": 1554561406,
  "exp": 1554565006,
  "apptype": "Public",
  "appid": "xxx",
  "authmethod": "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport",
  "auth_time": "2019-04-06T12:21:39.222Z",
  "ver": "1.0",
  "scp": "profile openid"
}

The issue is that the web API must know the ID of the user making the call (as there are some permissions defined at application level). I saw here that I can add claims to the access token, which I did. However, when reading articles on Internet, I read that apparently the access token is not supposed to be used to identify the user, so I don't know if it's correct to add a claim used by the web API to identify the user.
However, I read here that

The only user information the Access Token possesses is the user ID,
  located in the sub claim.

But by default, ADFS does not provide a "sub" token. Is it correct if I add a "sub" claim by myself that contains the email address of the user or do I have to proceed in a different way?
Answer: Yes, access token is not supposed to be used to identify the user. But if you can get a user identifier into the access token and it's all you need to know about a user, then it's probably the easiest way. But it's implementation-specific for your auth server.
The standard way is to ask for the profile scope (which you did) and get information from the userinfo endpoint (see OpenID Connect RFC). If you use this way, you may want to cache the response, so you don't need to make this HTTP call on every client request.
If your backend API is used just by the Angular application and is not supposed to be called by third parties, you could also consider using the backend as the OAuth2 client which receives an authorization code and exchanges it for an ID token. Then, it can save the user's identity (read from the ID token) in a session and issue a cookie identifying the session. So there would be no need for the frontend to send a token on each request. This would make the backend stateful, but it might be easier to implement.
Comment: Is it a security risk to include the user email in the access token ?
Comment: I don't see a reason why it could be a security risk, especially if ADFS supports it. I don't consider user email being a sensitive information and access tokens should not get to distrusted parties, so I would not mind having it there.
Comment: Just to note that ADFS only returns "sub" on the "userinfo" endpoint.

Access token and user ID


Toilet bubbles and gurgles after capping vent stack

Question: We had a bad wax ring on the toilet so we replaced that, then we decided to replace the toilet with a newer model. Now the toilet doesn't flush right--sometimes we have to flush it a couples of times for things to go down.
We thought it might be a clog so we had a plumber company clean the lines out there was nothing blocking it. They suggested that the vent stack might be clogged so we flushed it out with water and capped the vent pipe. However, the toilet is still acting up with bubbling and gurgling sounds and we can't figure out whats going on. Any suggestions?
Comment: Sanity check: What do you mean by "cap the vent pipe"? presumably something which still lets air through so it serves its purpose, right?
Answer: The bubbling and gurgling sounds from the toilet(s) is an indication of poor venting or a plugging issue. Also, you should not have to "flush it a couples off times for things to go down" unless there is a special circumstance (like too much paper... or something).
Call a reputable licensed plumber and have your entire system assessed, including camera inspection. Then pay appropriately to have the root cause addressed.


Increasing request size cause any issue?

Question: I have my request size to nearly to 2Mb.Will this cause any other issues?
<code><httpRuntime maxRequestLength="2048576" />
</code>
I am using many datasets and dictionaries saved in my view state.So I had to increase my request size.
Comment: The issue is that you are using many datasets and dictionaries saved in view state. (not the maxRequestLength itself) For each request user will send 2mb of data....it is a huge amount and your website will be very slow and unresponsive.
Answer: The MaxRequestLength property specifies the limit for the buffering threshold of the input stream. So one of the drawback I can think is that this limit can be used to prevent denial of service attacks that are caused by users who post large files to the server.
I would recommend only setting those larger values for the page that needs them rather than the site as a whole; both can be set programmatically for the page.
Comment: Thank you @Mohit for the reply.I will increase the size programmatically for the corresponding page.The issue is unexpected page load occurs when large data comes.It clears all View state values.Since I'm using many panels in the page as Wizard.When doing any operation it redirects to initial panel (Like initial page load)>I am fed up with this issue.Kindly give a solution, please.
Comment: Hey @Akhil you can add another question with more details of the issue you were facing. Since that would be easier to understand the scenario well.
Comment: I have added a question yesterday, but don't know what's wrong with it.Nobody gave a reply correctly.Since I'm new in C#  I am not sure my question is correct or not.Thank you @Mohit.Here
Comment: Here is the question : [link](https://stackoverflow.com/questions/41262346/will-the-increased-view-state-size-cause-unexpected-errors).


How to pass the image value in one xaml page to another xaml page in windows phone 7?

Question: My Requirement is,
in first xaml page place all the images .if whenever click on particular image that image can be displayed in another xaml page .How To pass The image value from one xaml page to another xaml page for  windows phone 7 app developement  using silverlight.
Answer: There's a good screencast on different ways of navigating between pages (and passing values) from DimeCasts.net at http://www.dimecasts.net/Casts/CastDetails/174
As an example of one way of doing this (and assuming the images were in a ListBox) would be to add the following to the SelectionChanged event.
private void OnSelectedImageChanged(object sender, SelectionChangedEventArgs e)
{
  NavigationService.Navigate(new Uri(string.Format("/image/{0}", HttpUtility.UrlEncode(((sender as ListBox).SelectedItem as PhotoViewModel).uri)), UriKind.Relative));
}

The above assumes an appropriately mapped route like:

and that the original listbox was bound to the uri property of a PhotoViewModel object.
Hopefully, watching the screencast should make any of the above clearer.


How to store response values into an array and read it in response body of another request using index values

Question: I want to store the IDs of each set in an array and later I want to read each value in the array using index values in JMeter. Can someone please help me how can I achieve this?
response of the 1st request is in the below format:
{
    "success": true,
    "vulns":     [
                {
            "TYPE": "vuln",
            "ID": "82003",
            "FQDN": "",
            "PORT": "",
            "Table": "67696056"
        },
                {
            "TYPE": "vuln",
            "ID": "90067",
            "FQDN": "",
            "PORT": "",
            "Table": "67696057"
        },
                {
            "TYPE": "vuln",
            "ID": "70000",
            "FQDN": "",
            "PORT": "",
            "Table": "67696058"
        },
                {
            "TYPE": "vuln",
            "ID": "70032",
            "FQDN": "",
            "PORT": "",
            "Table": "67696059"
        },
                {
            "TYPE": "vuln",
            "ID": "90042",
            "FQDN": "",
            "PORT": "",
            "Table": "67696060"
        }
    ]
}

I need to pass the IDs of the above request in the 2nd request's body as below:
Request Body:
{"data":[{"id":"ID1"},{"id":"ID2"}]}

where ID1 and ID2 are read from an array that stores all the IDs from the 1st request's response
Answer:
Add JSR223 PostProcessor as a child of the request which returns the above JSON

Put the following code into "Script" area:
def ids = new groovy.json.JsonSlurper().parse(prev.getResponseData()).vulns.ID.collect { id -> ['id': id] }

def payload = ["data": ids]

vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString())

It will extract all the ID elements values and transform them according to your needs

In the next request refer the generated JSON as ${payload} JMeter Variable

More information:

Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It


Why is the Grass Fields rated as an easier starting zone than the Rocky Desert?

Question: I've run a couple games of Satisfactory so far, starting out on the two easiest starting zones, and I have to say I don't understand why Grass Fields is rated as the easiest, introductory-level zone.  In almost every way, it seems to be inferior to Rocky Desert:

Poor-quality ore deposits vs. pure-grade ore at the starting zone
More difficult access to caterium, oil, and (arguably) coal
Water nearby is both less plentiful and harder to find
Rocky Desert has thermal geysers on a plateau directly overlooking the starting zone, for when you finally unlock the ability to make use of them.  For Grass Fields, the nearest geysers are waaaaaay out in the Blue Crater, near the horribly inconvenient oil field.

The only real advantage I've seen to a Grass Fields start is its abundant biomass, but biomass really stops being relevant almost entirely as soon as you get coal, and it's not scarce enough in Rocky Desert that it was ever a problem for me, so it kind of feels like Rocky Desert is easily the better "introductory level" starting zone.  But are there any factors I'm overlooking?  Is there any good reason to justify the ratings as they are?
Comment: There may be in-game reasons why the Rocky Desert might be in some ways more difficult, or there may not be. The list just means that asker did their homework (as recommended, e.g. see https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/), and there may be more subtle reasons.  Even if the answer may be 'no, there are no gameplay reasons for this, it's a bug/oversight' does note mean the question should be closed.
Comment: I would imagine all sorts of factors come in to play here - Rocky Desert has better quality deposits but Grass Fields has far more of them, there are also fewer hazards like spore flowers and alpha creatures in Grass Fields. Visual aesthetic is probably also a factor. But all that said, your question is essentially "why did the developers do this?", which is off-topic.
Comment: @JonK Less hazards?  I'm not sure about that.  Grass Fields has armadillo-pigs everywhere, while Rocky Desert mainly has those stinging firefly things.  The bugs are a nuisance; the pigs are an actual threat to your safety, especially before you get Blade Runners.
Answer: Satisfactory has a pretty specific game balance design: there are not supposed to be "beter" and "worse" starting zones in general, there are zones "better for beginners", "better for intermediate players", "better for advanced players".
The "beginner" areas provide environment conductive for safe start - open flat areas allowing for much easier combat or avoiding enemies, easy open space for building, plenty of biofuel, safely accessible iron, limestone, copper (not necessarily in copious amounts but only with moderate danger involved), plenty of paleberries. On the other hand, mid-game resources like coal,oil,water will be limited and more distant or inconveniently located.
The "good for experts" areas are more punishing early on - better nodes but defended better too, harder terrain, sometimes scarcity of biofuel, worse or more scarce healing plants, but mid-game resources closer, more accessible (late-game ones: bauxite, uranium, nitrogen are poorly accessible regardless of starting point).
Then comes Coffee Stain's perceived difficulty of the enemies: hog < spitter < flying crabs < alpha fauna and stingers. This may not be completely reflecting reality: the game is still being balanced; but also it may not reflect individual players' proficiencies: someone who killed a score of flying crabs already will have much easier time with another clutch, than with their first fluffy-tailed hog. The enemies all require different tactics and different masteries.
Regardless, from what you write one can judge you're an advanced player and it's very obvious how mid-game shortcomings of Grass Fields outweigh the early benefits.


Is there a standard wiring scheme for AC/heater thermostats?

Question: I have a project idea where I would really like to be able to make my own thermostat to control my home's AC and heater. I have just two questions

Is there any standard wiring/color code?
Are any of the wires supplying a high voltage or current? (ie, possibly dangerous)

Not sure if this is the best place to ask, but I figured I'd give it a shot
Answer: The standard colors can be found at various sites on the web.  Here is the important part from that site (I did the best I could to cleanup the formatting since I don't think we have support for tables here):

Older systems and base signals on newer ones
Code    Color   Signal  Description
C       Black   24 Vac  Common  From one side of the 24Vac transformer (Think of this as 24Vac neutral
R/V     Red     24 Vac  Power to be switched    From other side of the 24Vac transformer (Think of this as 24Vac L1)
Rh/4    Red     24 Vac  Heat call switch power  Same as R, but dedicated to the Heat call switch
Rc      Red     24 Vac  Cooling call switch power   Same as R, but dedicated to the cooling call switch
G       Green   Fan     Fan switch on thermostat - is connected to R when Fan /Auto switch is in the fan position
W       White   Heating call    Is connected to R or Rh when themostat calls for heat. (Might be jumpered to Y on a heat pump. On others might be second stage heating
Y       Yellow  Cooling call    Is connected to R or Rc when themostat calls for cooling. Also Cooling or 1st stage heating on a heat pump. Most often connected to G when Fan switch is set to auto.

New signals - for heat pumps and staged systems
Code    Color   Signal          Description
Y2      Blue/Or 2nd Cooling
W2      Varies  2nd Heating     First stage Auxiliary heating on a heat Pump
E       Varies  Emg heat        Disable the heat pump and turn on first stage Aux heating
O       Varies  Reversing valve Energize to cool (Changes from heat to cool on heat pumps)
B       Varies                  Sometimes common side of transformer. Needed on some electronic thermostats or if you have indicator lamps OR   Reversing valve (energize to heat) above. York and Trane sometimes use (B) as common.   Might be heating changeover or on older stuff common of transformer.
X       Varies                  Might be common but sometimes emergency heat relay
X2      Varies                  Second stage heating or indicator lights on some thermostats    Might be emergency heat relay
T       Varies                  Outdoor anticipator reset   Used on GE/Trane/American Standard and some Carrier Products.
L       Varies  Service Light
Comment: Note, I'd suggest using the link, I only copied the important parts in case the link moves in the future.
Comment: So does that mean you can just use a relay to connect the green and red pins to tun on the fan?
Answer: I think it is typically:

Black - 24Vac (Common -C)
Red -   24Vac (Hot -R)
Green - Fan (G)
White - Heating (Wx)
Yellow - Cooling(Yx)

But I'd definitely try and find a wiring diagram for your AC/Heating unit.
Comment: ... So the +24V black wire would be the one to avoid while it's live. It'll give you a nice jolt, though nothing like a 120V15A mains wire.
Comment: @KeithS: the red wire is that one that will get you.
Comment: Oops, sorry, yes, red. I read the list and saw black == +24V, dunno what happened there. I probably need to go home for the day


App crash after long time is in background

Question: hi app crashes when it is in background .so what is good way to handle
i am doing
  @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState == null) {
            finish();
        }
    }

is this good ?as onRestoreInstanceState will call only after system restart my app right ?
Comment: `onRestoreInstanceState` would not normally (and maybe not ever) be called with a `null` argument.  And it may be called when your activity is recreated after a configuration change.
Comment: Were you able out the root cause of the Crash? @bob
Answer: No, this is an atrocious approach. You should investigate the cause of your crash and correctly handle restoring the state of your application.
The best way to debug this is to enable the developer setting on your phone, under "Developer settings", called "Don't keep activities". This will help you investigate the cause of your crashes by reproducing the behavior of Android restarting your activities from a saved instance state.
Answer: It is very simple bro:
You have two options:
1) Use UnCaught exception handler inside your code so when crush happened you could save the reason for that crush.
OR
2) Just put your app into background until it crush and than use command line with adb: insert that line - "adb logcat > newTextFileName.txt"
Than go to that file and search for the word "FATAL" in the end of the file
There you can see the class and the line number that caused your problem.


is there any way to hide a  input field but still making it usable?

Question: what my issue is: is that I'm trying to make a simple website as a hobby project but for this i need to have a input field, so I used the one that  has but that was ugly. so a friend of mine made a SVG. now I'm trying to hide the  input field underneath the input field in the SVG
Comment: You could style it to be hidden, you could use an ``, etc.  What did you try and what didn't work?
Comment: Form elements can be styled in all sorts of ways using CSS. I would suggest learning how to do that first.
Comment: i tried using `````` but then the input field would no longer work
Comment: You could try to set the fields opacity to 0 `` but it would probably be easier to take a swing at styling your input fields to look like the svg and then if your having troubles coming back here for advice on that.
Answer: You could just add style = "display: none;" or style = "visibility: collapse;" which would make the input no longer visible to the user. The form will still grab the information from it and pass it to your back end. You can still use JavaScript on it as well as normal. As some comments pointed out, you can also use <input type="hidden"> as another option.
display: none; has the page just not show the element at all, as if it were never on the page.
visibility: collapse; has the page render the page and then hide the field, keeping the formatting the same (i.e. if it were a cell in a table it would help set the width of a column and the width would be the same if it is or is not shown).
I recommend looking into both of these options more, as I find them both really useful! Here are links to learn more about
Display and Visibility
At the end of the day, there are many different ways you can accomplish what you are wanting to do, just a matter of deciding what works best for you here.


Wrapper with height 100% displaing scrollbar

Question: How to remove scrollbar and display footer in bottom of page?
HTML:

    wrapper

    footer

CSS:
* {
    padding: 0;
    margin: 0;
}
html, body {
    height: 100%;
    width: 100%;
}
.wrapper {
    height: 100%;
}

http://jsfiddle.net/eoe26o83/
Thanks in advance.
Comment: This might be helpful: http://ryanfait.com/sticky-footer/
Comment: @CaseyFalk, if I add `overflow: hidden;` to body then footer will be hidden. Padding and margin already setted.
Answer: The problem above is that you have height of wrapper at 100%, leaving "no room" on that page for the footer. It necessarily is placed after 100% of the page is used, thus forcing a scroll.
Instead, you can change the position of the footer to be fixed, and always be on the bottom of the page.
footer{
    position:fixed;
    bottom:0;
}

http://jsfiddle.net/eoe26o83/4/
Comment: This isn't a good idea....the footer should stay in the flow of the document in case the content is taller than the Viewport.
Answer: Use calc() in your CSS. The only caveat is you need to know the height of your footer.
http://jsfiddle.net/michaelburtonray/eoe26o83/9/
HTML

wrapper

wrapper

wrapper

wrapper

wrapper

wrapper

wrapper

wrapper

wrapper

wrapper

wrapper

wrapper

    footer

CSS
* {
    padding: 0;
    margin: 0;
}
html, body {
    height: 100%;
    width: 100%;
}
.wrapper {
    min-height: calc(100% - 100px);
}
footer {
    background: red;
    height: 100px;
}


How to inherit a static property with a unique value for each subclass?

Question: I have a series of objects, lets call them buildings, that each share certain properties that are static for that building, but different for each building, such as price.  I assumed that the best way to implement this was to create an abstract superclass with the shared price attribute and set the values in each subclass, but I cannot figure out how to get this to work.  Here is an example of something I have tried:
using System;
public abstract class Buildings
{
   internal static int price;
   internal static int turnsToMake;
}

using System;
public class Walls : Buildings
{
    public Walls()
    {
        price = 200;
        turnsToMake = 5;
    }
}

This works fine for construction, but if I want to check the price before creating it (to check if the player has enough money) then it just returns a null value.  I'm sure that it is is a super simple fix, but I can't figure it out.  Any help?
Comment: May I ask why you care so much about creating the object? It's just an object. Nothing wrong with creating a building object, verify if the player can afford it, if not, leave the building for the GC.
Comment: Since we are talking about subclassing here, can you show us how you create instances of `Buildings` (or of a derived class) depending on `price` and `turnsToMake`? Do you have some kind of factory class or method?
Comment: Sadly C# doesn't support class properties/methods, so it's not possible to write code like this.
Comment: @CodesInChaos: Static properties *are* class properties, so C# supports these. What it doesn't support are *virtual* class properties. And that concept perhaps doesn't make much sense anyway, since static members are resolved at compile-time, while `virtual` methods are all about making polymorphism work, at run-time.
Comment: @stakx Class methods in the way delphi used them receive the type they're called on as first argument. They can be virtual, but even if they're not, receiving the class can be useful. Virtual class methods/properties would be a great solution to the OP's problem.
Comment: @CodesInChaos: Interesting! I'll have to take a look at Delphi's class  properties/methods then. Thx for the pointer.
Answer: There is a "patchy" yet simple solution that's worth to consider. If you define your base class as a Generic class, and in deriving classes set T as the class itself, It will work.
This happens because .NET statically defines a new type for each new  definition.
For example:
class Base<T>
{
    public static int Counter { get; set; }

    public Base()
    {
    }
}

class DerivedA : Base<DerivedA>
{
    public DerivedA()
    {
    }
}

class DerivedB : Base<DerivedB>
{
    public DerivedB()
    {
    }
}

class Program
{
    static void Main(string[] args)
    {

        DerivedA.Counter = 4;
        DerivedB.Counter = 7;

        Console.WriteLine(DerivedA.Counter.ToString()); // Prints 4
        Console.WriteLine(DerivedB.Counter.ToString()); // Prints 7

        Console.ReadLine();
    }
}

Comment: I really like this solution for some reason
Comment: Very, very nice solution to a tricky problem. Well explained too. Much appreciated. Hats off to you, sir.
Comment: This is great when you call the property on the derived class, but what if you need to have a shared static method on the base class that uses the static property value from the derived class?
Answer: Don't use static.  Static says that all instances of Building have the same value.  A derived class will not inherit its own copy of the statics; but would always modify the base class statics.  In your design there would only be one value for price and turnsToMake.
This should work for you:
public abstract class Buildings
{
  internal int price;
  internal int turnsToMake;
}

However, most people don't like using fields these days and prefer properties.
public abstract class Buildings
{
  internal int Price { get; set; }
  internal int TurnsToMake { get; set; }
}

Comment: That's excatly what I would do. +1
Comment: If I understood the OP correctly, there is still the problem that you'd have to instantiate `Buildings` before you can read the values of these properties. The only solution is to extract the property values into a separate "metadata" object that is associated with a specific class; something like `KeyValuePair>`.
Comment: @stakx You are correct that that is still my issue.  Is there not some simpler way to do this?
Comment: @Garrett: I dare say no. To inspect an object before it is created is impossible. Therefore my suggestion to inspect a diffeent object than the one you're (perhaps) going to create. You could look into custom attributes (`[Cost(Price=10,TurnsToMake=2)] class X`), or into the metadata suggestions made above and in my answer.
Answer:
I want to check the price before creating it […]

I suppose that's how you got to static fields; however, static and virtual behaviour cannot be combined. That is, you would have to re-declare your static fields for each subclass. Otherwise, all your subclasses share the exact same fields and overwrite each others' values.
Another solution would be to use the Lazy<T, TMetadata> type from the .NET (4 or higher) framework class library:
public class Cost
{
    public int Price { get; set; }
    public int TurnsToMake { get; set; }
}

var lazyBuildings = new Lazy<Buildings, Cost>(
        valueFactory: () => new Walls(),
        metadata: new Cost { Price = 200, TurnsToMake = 5 });

if (lazyBuildings.Metadata.Price < …)
{
    var buildings = lazyBuildings.Value;
}

That is, the metadata (.Metadata) now resides outside of the actual types (Buildings, Walls) and can be used to decide whether you actually want to build an instance ( .Value) of it.
(Thanks to polymorphism, you can have a whole collection of such "lazy factories" and find a building type to instantiate based on the metadata of each factory.)
Comment: Could you please provide a full example? Thanks!
Answer: Building on Uri Abramson's answer above:
If you need to access the static property from within the Base class, use reflection to get the value from T. Also, you can enforce that Base must be inherited using T of the derived type.
e.g.
class Base<T> where T : Base <T> {
        static int GetPropertyValueFromDerivedClass<PropertyType>(BindingFlags Flags = BindingFlags.Public | BindingFlags.Static, [CallerMemberName] string PropertyName = "")
        {
            return typeof(T).GetProperty(PropertyName, Flags)?.GetValue(null);
        }

        static int Counter{ get => GetPropertyValueFromDerivedClass(); }
}

        static int DoubleCounter{ return Counter*2; } //returns 8 for DerivedA and 14 for DerivedB
}

If you have a better way to do this, please post.
Answer: Not as easy for the inheritor, but workable...

public abstract class BaseType
{
    public abstract contentType Data { get; set; }
}

public class InheritedType : BaseType
{
    protected static contentType _inheritedTypeContent;
    public override contentType Data { get => _inheritedTypeContent; set => _inheritedTypeContent = value; }
}


mutable.Buffer does not work with Scalding JobTest for Type Safe API

Question: I have almost finished my Scalding project which uses the Type Safe API instead of the Fields API.  The last issue that remains for me in overall project set up is the integration tests of the entire Scalding job itself (I have finished unit tests for Type Safe External Operations pattern yay!).  This means to run the complete job and test the output of the various sinks of my job.
However, something very peculiar is happening.  In my
typedSink { scala.collection.mutable.Buffer[] => Unit }

It seems that my program does not see the buffer or do anything with the buffer so the integration test always passes even when it should not.  Below is both the job itself and the test to help illuminate what is going on:
object MyJob {
  val inputArgPath = "input"
  val validOutputArgPath = "validOutput"
  val invalidOutputArgPath = "invalidOutput"
}

class MyJob(args: Args) extends Job(args) {

  import OperationWrappers._

  implicit lazy val uId: Some[UniqueID] = Some(UniqueID.getIDFor(flowDef))

  val inputPath: String = args(MyJob.inputArgPath)
  val validOutputPath: String = args(MyJob.validOutputArgPath)
  val invalidOutputPath: String = args(MyJob.invalidOutputArgPath)

  val eventInput: TypedPipe[(LongWritable, Text)] = this.mode match {
    case m: HadoopMode => TypedPipe.from(WritableSequenceFile[LongWritable, Text](inputPath))
    case _ => TypedPipe.from(TypedTsv[(LongWritable, Text)](inputPath))
  }

  def returnOutputPipe(outputString: String): FixedPathSource with TypedSink[(LongWritable, Text)] with TypedSource[(LongWritable, Text)] = {
    val eventOutput: FixedPathSource with TypedSink[(LongWritable, Text)] with TypedSource[(LongWritable, Text)] = this.mode match {
      case m: HadoopMode => WritableSequenceFile[LongWritable, Text](outputString)
      case _ => TypedTsv[(LongWritable, Text)](outputString)
    }
    eventOutput
  }

  val validatedEvents: TypedPipe[(LongWritable, Either[Text, Event])] = eventInput.convertJsonToEither.forceToDisk

  validatedEvents.removeInvalidTuples.removeEitherWrapper.write(returnOutputPipe(invalidOutputPath))
  validatedEvents.keepValidTuples.removeEitherWrapper.write(returnOutputPipe(validOutputPath))

  override protected def handleStats(statsData: CascadingStats) = {
    //This is code to handle counters.
  }
}

Below is the integration test:
class MyJobTest extends FlatSpec with Matchers {
  private val LOG = LoggerFactory.getLogger(classOf[MyJobTest])

  val validEvents: List[(LongWritable, Text)] = scala.io.Source.fromInputStream(getClass.getResourceAsStream("/validEvents.txt")).getLines().toList.map(s => {
    val eventText = new Text
    val typedFields = s.split(Constants.TAB)
    eventText.set(typedFields(1))
    (new LongWritable(typedFields(0).toLong), eventText)
  })

  "Integrate-Test: My Job" should "run test" in {

    LOG.info("Before Job Test starts.")
    JobTest(classOf[MyJob].getName)
      .arg(MyJob.inputArgPath, "input")
      .arg(MyJob.invalidOutputArgPath, "invalidOutput")
      .arg(MyJob.validOutputArgPath, "validOutput")
      .source(TypedTsv[(LongWritable, Text)]("input"), validEvents)
      .typedSink[(LongWritable, Text)](TypedTsv[(LongWritable, Text)]("invalidOutput")) {
      (buffer: mutable.Buffer[(LongWritable, Text)]) => {
        LOG.info("This is inside the buffer1.")
        buffer.size should equal(1000000)
      }
    }
      .typedSink[(LongWritable, Text)](TypedTsv[(LongWritable, Text)]("validOutput")) {
      (buffer: mutable.Buffer[(LongWritable, Text)]) => {
        LOG.info("This is inside the buffer2.")
        buffer.size should equal(1000000000)
      }
    }
      .run
      .finish
  }
}

And finally, the output:
[INFO] --- maven-surefire-plugin:2.7:test (default-test) @ MyJob ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- scalatest-maven-plugin:1.0:test (test) @ MyJob ---
Discovery starting.
16/01/28 10:06:42 INFO jobs.MyJobTest: Before Job Test starts.
16/01/28 10:06:42 INFO property.AppProps: using app.id: A98C9B84C79348F8A7784D8247410C13
16/01/28 10:06:42 INFO util.Version: Concurrent, Inc - Cascading 2.6.1
16/01/28 10:06:42 INFO flow.Flow: [com.myCompany.myProject.c...] starting
16/01/28 10:06:42 INFO flow.Flow: [com.myCompany.myProject.c...]  source: MemoryTap["NullScheme"]["0.2996348736498404"]
16/01/28 10:06:42 INFO flow.Flow: [com.myCompany.myProject.c...]  sink: MemoryTap["NullScheme"]["0.8393418014297485"]
16/01/28 10:06:42 INFO flow.Flow: [com.myCompany.myProject.c...]  sink: MemoryTap["NullScheme"]["0.20643450953780684"]
16/01/28 10:06:42 INFO flow.Flow: [com.myCompany.myProject.c...]  parallel execution is enabled: true
16/01/28 10:06:42 INFO flow.Flow: [com.myCompany.myProject.c...]  starting jobs: 1
16/01/28 10:06:42 INFO flow.Flow: [com.myCompany.myProject.c...]  allocating threads: 1
16/01/28 10:06:42 INFO flow.FlowStep: [com.myCompany.myProject.c...] starting step: local
16/01/28 10:06:42 INFO util.Version: HV000001: Hibernate Validator 5.0.3.Final
Dumping custom counters:
rawEvent    6
validEvent  6
16/01/28 10:06:42 INFO jobs.MyJob: RawEvents: 6
16/01/28 10:06:42 INFO jobs.MyJob: ValidEvents: 6
16/01/28 10:06:42 INFO jobs.MyJob: InvalidEvents: 0
16/01/28 10:06:42 INFO jobs.MyJob: Job has valid counters and is exiting successfully.

As you can see, the Logger logs the "Before Job Test Starts" but nothing happens inside of the typedSink parts.  This is frustrating because my code looks like all of the other code I see for this but it does not work.  It should fail the test but everything runs successfully.  Additionally, the Logger inside of the typedSink never outputs.  Lastly, if you look at the output, you see that it handled counters correctly so it is running the job to completion.  I have spent many hours trying new things but nothing seems to work.  Hopefully the community will be able to help me.  Thanks!
Comment: Try removing the `mode` check for the sake of an experiment and see if it helps. I don't remember how it is, but would not be surprised if `JobTest` runs in Hadoop mode.
Comment: Ok, then I don't know :) Time to fire up a debugger?
Comment: Can you post what you have found out as an answer? I would be interested in seeing it.
Comment: My team has been using the Fields API with the Scalding book and they have had no trouble with the mode check.  However, I will try this right now.  Thanks for your suggestion!
Comment: I tried your suggestion and I received this exception:

Cause: com.twitter.scalding.ModeException: Cascading local mode not supported for: com.twitter.scalding.WritableSequenceFileWrappedArray(input)

which suggests that JobTest uses Cascading local mode.
Comment: I had a conversation with some of the Scalding devs in the Scalding Gitter room.  I have to rethink how I test and some of my initial assumptions of the job.
Comment: I have posted my answer Dima.
Answer: So, while I don't have a great answer to this post, I have what worked for me.  Basically my problem was that I was using ScalaTest to run my Scalding jobs from this link: Using the ScalaTest Maven plugin.  This worked fine for my unit tests on operations but this caused weirdness when using ScalaTest with JobTest.  After talked to the Scalding devs and finally acknowledging my team's own success with JUnitRunner, I decided to go with that.  I changed my POM to support JUnitRunner and added @RunWith(classOf[JUnitRunner]) annotations to my tests.  Everything worked and behaved like I wanted them too.


How to indicate a text field does not contain content?

Question: In the wireframe below, the three containers could contain text.  The user can add text to empty containers and edit existing text. Note that this form is not just for entering text, but often the user will be just reading the text previously inputted by her or one of her co-workers.
Two questions:
1) How do I communicate to the user that a container (i.e. Section 2) does not contain any content? i.e. it blank because no content has been added, and not because there has been some display error.
2) Should  the Call to Action for an empty container be "edit" or "add"?

download bmml source – Wireframes created with Balsamiq Mockups
Comment: Some interesting thoughts on how to design for empty spaces here: http://tympanus.net/codrops/2013/01/09/designing-for-the-empty-states/
Comment: Do you need to be more explicit than just showing an empty field?
Comment: @KenMohnkern  Not if it is obvious.  Would it be if all three were initially empty?  One would just see a label with edit button and a box.
Answer: Provide context
No matter what you do, it's no good idea to leave empty elements just like that, trusting that users will understand the affordance. Even if they do (and any test will show you form elements are rarely understood by default by 100% of people), you will create another set of questions for the user: why are these elements empty? Did they forget something? Do they expect ME to do anything?
The good news is there are hundreds or probably thousands of resources to deal with this very common problem, including theory, examples and research. You can get some insight on what to do with an empty field depending on a wide variety of situations, quite probably yours will be included:

Designing For The Empty States
Google Material Design Guidelines: Empty states
UI Design for Empty States, Zero Data, and Onboarding
Empty States Patterns
pattrns: Empty States

Conclusion
You'll see there are many ways to approach your issue depending on your specific needs, but you'll see there's always something in common: you NEVER leave anything to user's imagination if you can avoid it. In short: if an element that might or might not be empty is empty, then explain to the user why, and what to do (assuming there's an expected action)
Comment: Great list of resources.  I didn't know there was so much written on the topic.
Comment: By the way, I was very torn about not selecting this answer as it is great.
Answer: For the first question : How do you make it obvious to the user that a text area is blank in the series of text areas ? I would do something like this, a faded tool tip/label inside the text area that is on display by default for an 'empty' state. This is popular in forms. As you type, key in, that messages goes away. When made empty again, its displayed. You can change the text to what fits your requirement. Kind of like a watermark.

You can see same approach for search field in StackOverflow page above.

Second question was do you use Add or Edit for empty text areas ? I would say why do you even need a link to say that? You can use inline edit, so on click inside the text area, those text areas can be made editable. If you really require a link to clearly say Edit or Add, then I think for a blank field Add makes more sense. For me an Edit is more in the case of making changes to existing content.
Comment: In HTML spec, that is called 'placeholder' http://www.w3schools.com/tags/att_input_placeholder.asp
Comment: Often the user will just want to read the previously inputted the text and will not be editing or adding text, and as such, I feel some stronger action such as clicking an edit button should be used to put it into "edit" mode.  The placeholder idea when empty makes sense, and can be improved by giving instructions.  Thanks!
Answer: A blank text box (what you have now) is sufficient.
In most contexts, it will be clear that a blank, labelled text box is empty.  Users will understand that text can be entered here (particularly when there is an edit link, which further reinforces that they can enter something there).
Comment: If all were initially empty, what makes then think it is a text box, and not just some strange rectangle?
Comment: @user1032531 If *everything* can be empty that is slightly different than one field that can be empty.  You might need to communicate somehow that editing the information is possible (however, you are already doing this to some extent with the links that say "add" and "edit").  Ultimately this depends on the context...if you edit your question with more specifics about the application, that would help.
Answer: You should use a <textarea> for the field and a  element for your Section 1, Section 2 and Section 3.
You can now link the  to the <textarea> using the for attribute in the  element, which must point to the id of the text area. For example:
Section 1
<textarea id="name" rows="4" cols="50"></textarea>

This will really help you support accessibility for blind users who might be using an audio screen reader. Also, if you do this, when you click the label the text area will now automatically take keyboard focus.
From a user experience point of view, if it looks like a field a user will treat it like a field, so there is no need to add anything, as long as the field shows that it has focus, i.e. when you click it or use the tab keyboard key to navigate to it.
Answer: You could distinct 2 different states solving for:

reading
editing

For reading, use header and text. If empty, use placeholder explaining that there's no content yet
Editing could be triggered for each section separately or all together. Then it changes from text to textarea.
Comment: Yea, I think maybe a placeholder should be used.   Midas's recommended http://ux.stackexchange.com/questions/93609/indicating-empty-text-field seems to show some examples.


Form with list below - List shows blank entry

Question: I have a controller:
class UsersController < ApplicationController

 def departments
    @users_departments = current_user.departments
    @new_department = current_user.department.new
 end

My view looks similar like this:
 <%= form_for @new_department, :url => {:action => "departments"} do |f| %>
.
<% end %>

<% @users_departments.each do |dept| %>
  <%= dept.name %>
  <%= dept.employees %>
<% end %>

@users_departments.each... shows me an empty department. Why? And how to solve that?
Answer: Ok I found out that the magic thing is called lazy and eager loading.
What I made was changing this:
@users_departments = current_user.departments

to
@users_departments = current_user.departments.find(:all)

Rails seems to be loading the results in the view if it was called. With "find" in place the db get hit and @users_departments fetches "really" the entries. Not in view, like before.
Answer: First of all - try to use REST
form_for doc
something like that:
<%= form_for @post do |f| %>

will generate link to create action in your UserController
And about @users_departments.each - maybe in your DB current_user.departments.count - return 0
I mean maybe there is no such record in your database.
Comment: Hi Demitriy, I do not really understand. When I create records for my departments (with user_id set) though the current_user, the empty entry is still there. If I remove the form from the view and ALSO THE `@new_department = current_user.department.new` from the controller, the empty entry is gone.


D3 .js Select All pass variable

Question: I want to select all the elements which are having a specifiv value for the bound-by attribute
so on clicl of will be executing the below piece of code
and storing the value in a variable and then applying a transition effect
var bindingProp = d3.select(this).attr("bound-by");
var test = d3.selectAll(bindingProp);
test.transition().duration(1500).delay(000).attr("x", 35);

but the above code is not working any suggestions?
or is their a way in which i can use selectAll to select the elements having bound-by attribute or is it that select all accepts only classNames
the problem is that the bound-by is not static it will be determined on what element the user has clicked so i want to pass a variable to it that and that variable will contain my bound-by value which user has clicked
Answer: Try this way.
var boundByVal = d3.select(this).attr("bound-by");
var el = d3.selectAll("[bound-by="+boundByVal+"]")
   .transition()
   .duration(1500)
   .delay(000)
   .attr("x", 35);

d3.select("[bound-by=boundByVal]") code will return element having bound-by attribute value set as boundByVal

var circle = d3.select("circle[bound-by=name]");
console.log(circle.node());

<svg width="200" height="200">
  <circle r="15" cx="25" cy="50" bound-by="name"></circle>
  </svg>
Comment: I the problem is that the boundByVal is not staic it will be determined on what element the user has clicked so i want to pass a varible to it that variable will contain my boundByVal which user has clicked so how can i pass a variable in  d3.select("[bound-by=boundByVal]")??

D3 .js Select All pass variable


gnome-tweak-tool doesn't start due to "ImportError: No module named gi" error

Question: I am using Ubuntu 11.10 with Gnome Shell and have a problem with gnome-tweak-tool. When I click on it, it does nothing and when I try to open with terminal it gives this error:
Traceback (most recent call last):
File "/usr/bin/gnome-tweak-tool", line 22, in <module>
import gi
ImportError: No module named gi

I googled a bit, found some solutions (reinstalled some python-gobject packages), but still didn't help./
Answer: Little workaround found here:
sudo nano /usr/bin/gnome-tweak-tool

Change #!/usr/bin/env python to #!/usr/bin/python
Comment: Should have known to do this already, had the same problem with diffuse.  Not sure why installed "binaries" seem to be so deferential towards using the current env Python.
Answer: My file is named 'gnome-tweaks' BTW, and it was already #!/usr/bin/python
I solved my crisis by realizing that I've recently installed python3 along side
python2 and set it to default. [[  python -> python3  ]]
I changed my line to
#!/usr/bin/python2
Now it works
Comment: This is what worked for me.
Answer: I got this error after messing with pyenv. I changed system python to one from pyenv so system could not find modules installed for system python. pyenv global system fixed the error.
Comment: same for me in 2023


Insecure Object Reference in java web application

Question: I am creating a web application in java. It deals with several business Objects being modeled in the application. Each object has table associated with it in database. I want to show the details of particular object, say for eg. Student to User. For that I am making ajax request to server and passing UserId as input parameter. The psuedocode looks something like given below :
<code>1) Get StudentId from request.
2) Fetch Student details from db for given studentId
3) Send the student data as response to the user
</code>
What I want is, StudentId must not be used and instead of that a random number or anything else can be used, that can be mapped to student id at server side and consequently student details are fetched and send to client. I want this so that even if studentId is doctored/modified by user, as part of query string, user doesn't get any other student data and thus, error message is show to it.
Comment: Why not validate that the current user is allowed to access the given student instead?
Comment: Maybe useful: http://stackoverflow.com/questions/35817200/accessing-url-with-params-in-spring-security
Comment: Use Spring Security ACL
Answer: Without some form of authentication, an attacker would be able to simply try different values for StudentId until they find one that works. By repeating this, they would be able to enumerate the different StudentIds and retrieve all the student data. A user should only be able to access the records they have access to. I would strongly recommend implementing a solid authentication method.
However, if you cannot implement an authentication mechanism, you can try to make the enumeration process more difficult. One way to do this would be to randomly assign StudentIds (To avoid the German Tank Problem), and make them as long as is practical. Something like a long, random string would make an excellent ID. Note that the more users you have, the less effective this will be at "safeguarding" your data. In addition, this method does not actually secure your data,  it merely makes it (theoretically) more difficult for an attacker to retrieve all of it. If they guess the right ID, they can still get data they shouldn't.
In addition, since you are using Java, you can use PreparedStatements and parameter binding to avoid SQL injection attacks.
Comment: Note that [GUIDs are unique, not random](https://blogs.msdn.microsoft.com/oldnewthing/20120523-00/?p=7553/). The same goes for UUIDs - the specification doesn't actually state they have to be generated from a cryptographically secure pseudo random number generator.
Answer: one shot solution is use owasp esapi access reference map, you will love it :)
https://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/esapi/AccessReferenceMap.html


Counter Strike: Global Offensive Lags

Question: I'm playing CS:GO for a while now and on some days I'm really bad.
It was noticeable that on these days even my teammates from the same city I live in were lagging and "flying" from one point to another without a fluent movement.
My Ping is about 15ms and I've got an average of 250FPS (according to the steam fps viewer overlay).
Do you have any idea if it depends on my CS:GO settings, G Data Internet Security or something else?
The game runs on a SSD with an Intel i5, a Radeon HD7870 and I've got a stable 50K down and 10K up internet connection.
Thank you!
Johannes
Comment: 15ms ping with 250FPS sounds like you're fine.  Unless you're stuttering, it's not you.
Comment: But they've got the same ping as me, better computers and don't have these lags with other players
Answer: That sounds like you have heavy packet loss somewhere between your home NAT router and the server you are playing on.
As a first step, you could enter net_status in the CS:GO console. This will give an output like the following:
] net_status
Net status for host 192.168.2.23:
- Config: Multiplayer, listen, 1 connections
- Ports: cl0 27005, sv1 27015, htv2 27020, htv13 0, 4 total.
- Latency: avg out 0.04s, in 0.01s
- Loss:    avg out 0.0, in 0.0     <====================== This line show packet loss
- Packets: net total out  65.0/s, in 64.5/s
           per client out 65.0/s, in 64.5/s
- Data:    net total out  8.9, in 10.3 kB/s
           per client out 8.9, in 10.3 kB/s

This shows the packet loss of incoming and outgoing packets (I don't know the units, maybe percent). If it says anything other than 0.0, that's a reason to be suspicious. Something on the route between you and the server throws away packets. You should probably contact your internet service provider about the problem, unless you are willing to investigate further.

If you want to investigate furhter, you'll need the server's IP address. Enter status in the CS:GO-console and look for the line udp/ip:
] status
hostname:  xxxxxxx
version : 184.108.40.206/13509 6171 secure
udp/ip  : 10.11.12.13:27015          <============== The part before the : is the IP
os      :  Linux
type    :  community dedicated
map     : de_dust2
players : 1 humans, 3 bots (12/0 max) (not hibernating)

Once you got that, you can test packet loss using the ping command1. This will tell you if the problem just exists inside CS:GO or if it really is a network problem. Just open a terminal (enter "cmd" in the start menu and press Enter) and enter the following (with the correct IP, obviously):
ping -t ip.of.the.server

Your PC then sends requests to that server and measure the time until it answers. Pressing Ctrl+Break will show you statistics like this:
Ping statistics for ip.of.the.server
    Packets: Sent = 467, Received = 467, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 20ms, Maximum = 23ms, Average = 21ms

Pressing Ctrl+C will terminate the ping program and show the same statistics.
If it says anything but 0% loss, you've got a problem.

If you know something about how network protocols work and/or are willing to invest some time learning, you can try to find the cause of the issue yourself. Here's a good tutorial about debugging packet loss, which you can use as a starting point. (archive link)

1. Disclaimer: Obviously this only measures loss of ICMP packets, not UDP or TCP, but normally these should correlate.
Comment: This is a good answer, though I'd include an explanation on how to fix the packet loss, if it can be rectified/helped.
Comment: @ʰᵈˑ You're right, of course, but debugging packet loss is really hard, if not impossible, for the average home user, because it requires some expert knowledge on internet protocols. That's why I suggested contacting the ISP.
Comment: In case you are interested: You would need to find the route the packets are taking using `tracert` (which might or might not work due to the configuration of remote routers which you don't control), find out which of those routers drops packets (again, this might fail due to router config), and contact the operator of said router (I wouldn't even know how to find that out). Here's a writeup of the general process, though not a tutorial: http://serverfault.com/questions/207375/how-do-you-diagnose-packet-loss
Comment: @ʰᵈˑ I think it's better now. :)
Comment: I tried "ping -n 100 google.com" and I lost 2 packages (directly after boot of my PC, maybe firewall was initialised?) the first time, 0 packages the second and again 2 the third time... I also used tracert and no * were visible so I think my connection is very stable.

I don't know how to get the IP adress of the CS:GO MM-servers but maybe I can use net_graph to see package loss..

Is it possible that these settings influence my performance:  _rate cl_cmdrate cl_updaterate cl_interp_ratio cl_interp fps_max_?
Comment: @Johannes when you join a server I think it shows you the IP in console, it'll say something like `connecting to 22.214.171.124`
Comment: Ok I will try tomorrow. I added an two way exception for CS:GO in my G Data Firewall and despite a higher ping (different server i guess) it worked pretty fine. Maybe it depends on the server (infrastructure) or there is one hop that results in an error more often
Comment: @Johannes Your PC should *never* lose packages, even when you just booted it. To find out the IP, try entering `status` in the CS:GO-Console when connected to a server. Then use that IP in the `ping` and `tracert` commands. Alternatively you can also type `net_status` in the CS:GO-console, which will tell you (among other things) the packet loss for the current game session.
Comment: @Fritz I tried that with net_graph 1 and it says Loss: 0%.. My Router (fritz.box) says that the connection is stable for more than 8 days and there are only 17 erros occured since this day. I have to try ping and tracert with the server adress soon
Comment: @Johannes Did you try that while you had those lag problems, or just now? Because you said, it's only some days. Another possibility would be that some packets are not lost, but severely delayed (by about a second, as you describe "flying"). However, I can't really imagine how that might happen, short of routing every 10th packet through China or something (Note: I consider this *highly* unlikely). And if that were the case, it would probably be easier to just switch to another ISP than trying to figure out what the problem is. :(
Comment: @Fritz I tried it just yesterday but there weren't any problems. I moved to another city two month ago and with my old provider (vodafone germany) it was even worse. I had this problem there nearly every day despite a ping of about 45ms. Now I live in a bigger city with 1&1 as my ISP (uses Deutsche Telekom infrastructure) and my Ping is better and the problem occurs not that often but it's still there. I will try a ping with my notebook too this afternoon and if there is package loss too, it has something todo with my ISP, if not, with my PC for gaming I guess...
Comment: @Johannes That approach sounds good. Did you use `ping -t`? Leave that to run for a while and press Ctrl+Break (Pause on a German keyboard) to get better statistics with more packets instead of just 4.
Comment: @Fritz I used `ping -n 20 domain.com` which does nearly the same but only 100 times. I'm right?
Comment: @Johannes Yes, that's good too, but it sends only 20 packets before stopping. You likely want to send more than 100 packets to get a meaningful packet loss percentage value. So either something like `ping -n 200` or `ping -t`.
Comment: @Fritz Sorry, this was an example, I tried n = 150 yesterday. I also pinged heise.de with this method and there was no package loss at all. Only with google.com I loose always 2 packages
Comment: I called 1&1 and they said that maybe something is wrong in the telephone switch (hosted by Deutsche Telekom). But I figured out that this package loss only occurs in the internet "prime time" between ~ 5PM and 11PM. I also tried some pings with my notebook too and it showed the same package loss.
I think I have to wait..

Counter Strike: Global Offensive Lags


I need x on x axis y on y axis and fx and fy in plot area in R

Question: I need this type of figure:

I need x on x axis, y on y axis and fx and fy in ploy area. Could you please help me in R i.e. both curves intersect to each other. My code is
   gx <- expand.grid(x=seq(1,5,length=50))
   fx <- function(x) { exp(-x) }
   gx$fx <- apply(gx,1,fx)
   plot(gx, type="l",col="red")

   gy <- expand.grid(y=seq(1,5,length=50))
   fy <- function(y) { y*exp(-y) }
   gy$fy <- apply(gy, 1, fy)
   par(new=TRUE)
   plot(gy, type="l", col="green")

Comment: If you're asking about x,y-labels, then please say that. It would help if you posted the image of the current plot and explain what you expected to see differently. "fx, fy in plot area"? Do you want to see text showing the numerical value of fx, fy placed at the corresponding points in the lot area?
Comment: Change your last line to `lines(gy, col="green")`. This will add it to the previous plot.
Comment: Than you for your response Andrew Gustar. I need x,  fx according to x axis and y, fy according to y axis in a single plot.
Comment: Please check your function for `f(x)`. It's definitely not giving you the calculation as what you require.
Answer: Not 100% sure I understand what this question means, but if you are looking to label your axes you can use the xlab and ylab graphical parameters:
ie:
plot(gx, type="l",col="red", xlab="label for x axis", ylab="label for y axis")

Answer: Use of legend and lines functions along with plot would give the following figure.
plot(gx,type="l",col="red", xlab ="x", ylab="y")
lines(gy,col="green")
legend("topright", inset=.05, cex = 1, c("f(x)","f(y)"), horiz=TRUE, lty=c(1,1), lwd=c(2,2), col=c("red","green"), text.font=3)

Answer: Here's the plot with base:
plot(gx, type="n", xlab="", ylab="")
for(i in 1:2) lines(get(c("gx", "gy")[i]), col=c("red", "green")[i])
title(xlab="x", ylab="y")

I personally prefer to do a little bit more data-manipulation to combine both data (gx and gy) into a single data.frame in long-form using "dplyr" and "tidyr" packages :
dat <- data.frame(gx, gy)
dat <- dat %>%
      gather(xvar, x, x,y) %>%
      gather(yvar, y, fx, fy)
head(dat)

#   xvar        x yvar         y
# 1    x 1.000000   fx 0.3678794
# 2    x 1.081633   fx 0.3390415
# 3    x 1.163265   fx 0.3124642
# 4    x 1.244898   fx 0.2879703
# 5    x 1.326531   fx 0.2653964
# 6    x 1.408163   fx 0.2445921

This will make it easy to visualise with ggplot:
ggplot(dat, aes(x,y, col=yvar)) + geom_line()

Answer: It doesn't seem anyone so far has answered about putting f(x) and f(y) in the plot area. You can do this with text(), though it's not the most elegant solution because you have to manually give the coordinates of where to place the text.
The data you gave:
gx <- expand.grid(x=seq(1,5,length=50))
fx <- function(x) { exp(-x) }
gx$fx <- apply(gx,1,fx)

gy <- expand.grid(y=seq(1,5,length=50))
fy <- function(y) { y*exp(-y) }
gy$fy <- apply(gy, 1, fy)

Creating the plot:
plot(gx,type="l",col="red", xlab ="x", ylab="y")
lines(gy,col="green")
text(x=c(3,2),y=c(0.18,0.1), labels=c("f(y)","f(x)"))

Gives this:

I hope this helps! The part that is confusing about your question is when you say that you need the lines to intersect. That's an issue with your data and/or the functions you are applying, and not one we can answer without some clarity.


Merge one subject observations to all others

Question: I'm attempting to remove a subject from the data set and then subsequently merge them in with the others so that their values at each time point can be compared to everyone else.
This is what the data looks like:
subject <- rep(1:5, each = 20)
seconds <- rep(1:20, times = 20)
variable <- rnorm(n = subject, mean = 20, sd = 10)
d <- data.frame(subject, seconds, variable)

Then, I am removing subject four from the data and trying to merge them back to compare them to each of the other subjects:
four <- subset(d, subject == 4)
d2 <- subset(d, subject != 4)

I've tried this but the problem is that it repeats each of the seconds 4 times for each merge:
merge(d2, four, by = "seconds")

Is there a way to get an exact merge of each individual relative to subject 4?
Answer: The problem in your code comes from the fact that only subjects 4 have values that satisfy seconds == 4. See:
subject <- rep(1:5, each = 20)
seconds <- rep(1:20, each = 20)
d <- data.frame(subject, seconds)
with(d, table(subject, seconds))
       seconds
subject  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
      1 20  0  0  0  0 20  0  0  0  0 20  0  0  0  0 20  0  0  0  0
      2  0 20  0  0  0  0 20  0  0  0  0 20  0  0  0  0 20  0  0  0
      3  0  0 20  0  0  0  0 20  0  0  0  0 20  0  0  0  0 20  0  0
      4  0  0  0 20  0  0  0  0 20  0  0  0  0 20  0  0  0  0 20  0
      5  0  0  0  0 20  0  0  0  0 20  0  0  0  0 20  0  0  0  0 20

Since you are merging on seconds, and for all entries in four, seconds equals four, the output of merge is correct, i.e. you would expect an empty table.
If you change the ordering, the problem will not occur.
subject <- rep(1:20, each = 5)
seconds <- rep(1:20, each = 20)
d <- data.frame(subject, seconds)

four <- subset(d, subject == 4)
d2 <- subset(d, subject != 4)

newdf <- merge(d2, four, by = "seconds")
head(newdf)
  seconds subject.x subject.y
1       1         1         4
2       1         1         4
3       1         1         4
4       1         1         4
5       1         1         4
6       1         1         4

Where you see that now we can find subjects in x and in y, i.e. the left and right dataframe handed over to merge.

A comment: what you are after sounds more like reshaping your data, but you still need to figure out what to do with your duplicates. To give you an idea:
library(reshape2)
d$ind <- factor(d$subject==4, labels = c("four", "not four"))
out <- dcast(d, seconds ~ ind, fun.aggregate = function(x) x[1], value.var = "variable")
head(out)
  seconds      four  not four
1       1 20.836195 16.539739
2       2 15.923540 11.534704
3       3  1.250495 12.992153
4       4 25.127817 31.510210
5       5  8.990819  8.030607
6       6 21.783900 38.300430

This will take the first value whenever there is a duplicate.
Comment: Thank you. I actually see that I had an error in my example data (in the seconds column, as you pointed out). I've edited the original post to correct for that. The issue I am having is the repeating of each of the seconds 4 times when doing the merge..
Comment: What would you expect? There are multiple entries in your data. If you don't want to have them, you can drop duplicates.
Comment: Okay, I can certainly drop duplicates but with such a large data set I am working with, I wasn't sure if there was a way to make the code more streamlined and get exactly what I was asking for.
Comment: I am sure there is, but the data that you are showing here is just repeating itself quite frequently, so it necessarily contains duplicates. Can you show us an example of your real data?
Comment: @user3585829 I have added a small code snippet that might be what you are looking for.
Comment: Thanks. The original data looks similar to this. What I'm trying to get is a data frame that basically has the comparison for subject one to four at each second/time point and then subject two to four at each second/time point, etc. If that makes sense.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/183324/discussion-between-coffeinjunky-and-user3585829).


Java HashSet Optimization

Question: How is the HashSet class in Java implemented so that it runs efficiently?

On an assignment, I was asked to implemented a data structure similar to a HashSet from scratch.
The basic concept was to use an array of LinkedList, resizing when the load factor -- L = N / S, where L is the load factor, N the total number of elements, and S the size of the array -- exceeded some constant.
In the function to resize, I tried to solely use functions within the LinkedList class that were of O(1) when recomputing the hashcode of each element and reinserting into the HashSet.
In the hashcode function itself, I simply referred to using the hashcode for the String class, modulo'd with the array size to prevent an 'index out of bounds' exception.
With this implementation, I am still not able to achieve half the performance as achieved by the HashSet class provided by Java.
I am leaning to believe that it is hashcode within the class that makes it so efficient: one that would evenly distribute the input, whether it was ordered or not, such that the size of array needed would be S = N / C -- where S is the size of the array, N the number of elements, and C be some small integer constant such that searching through a LinkedList would be O(C).
If so, or if not, how does the hashcode or HashSet work?
Comment: You can see for yourself (`HashMap` is used internally by `HashSet`) http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/HashMap.java?av=f
Comment: Also for a school assignment, your implementation should not reasonably be expected to perform as well as the `java.util` implementation.
Answer: This algorithm is called seperatechaining,There is [book]which is studied and you can find here it's details. When you resize the array, don't try to move the entries from one list to temporary and then back to that list. You can simple let list refer to the temporary list.
Comment: Hm, so are you saying I should not be popping out the LinkedList and rehashing its elements?
Comment: There are many possible options, Suppose you have an array of $10$ elements and each array entry has one linkedlist. Depending on the type of keys you are using once again suppose that your first $1000$ entries fall into only 5 buckets which means that you have $5$ linkedList of 200 elements and some later time you 6th element and you need to increase size.
Comment: At this point you are computing 200 hashfunctions for each of the linked list and in total $1000$  which will take a lot of time. You can only compute new function of the one element from each list and add this element in a new linkedlist , since the head of this linked is an element of previous ,you can let tail point to the previous linkedlist because all those values will hash to same bucket as this element because they were previously in same bucket.

Java HashSet Optimization


Python: Determining odd and even numbers

Question: Having trouble with a part of a homework assignment. I'm not sure how to do what it's asking. The object of the assignment is to determine if a number is odd or even and then print one of the two statements. I know how if / else statements work, I just don't know how to figure out if a number is odd or even! (I know, I'm terrible). Any help would be appreciated. Here's an example of what I'm doing:
user_num = 13
if #your solution goes here:
    print('Even')
else:
    print('Odd')

Comment: Then perhaps you should ask yourself: "*When is a number odd? What are the condition(s) that should be met?*"
Comment: so would it be like if the number is not divisible by 2? forgive me but I was always crap at math which is why I keep asking so many questions here, lol. Could I use modulus and divide by 2 because anything odd will always have a remainder?
Comment: `if user_num % 2 == 0`
Comment: Exactly. So what should your program do? Calculate the modulus of a division by two. And if it is not zero, then...
Comment: You must check if the number "user_num" is odd or even. To do this, read about these concepts (https://en.wikipedia.org/wiki/Parity_(mathematics))
Comment: Thanks Willem I was able to figure it out without you having to do everything for me which feels better. Haha
Answer: A number is called even if it is divisible by 2, i.e, the remainder should be 0. Using the modulo operator in Python you can get your answer.
So your code should go like this:
user_num=13
if(user_num%2==0)
    print('Even')
else
    print('Odd')

Answer: Any EVEN number divided by two is a whole number.
How would you go about determining this?
Is it easier to find if the number is a whole number or if dividing gives a remainder.
Say 5 divided by 2. This would be 2 with a remainder of 1.
Or with your number, 13 divided by 2 is 6 remainder 1.
Finding if something has a remainder of 1 is easier than checking if the answer leaves a whole number. How do you check if something has a whole number?
Think of discrete math here. When doing divisor operations. There is a specific term I am alluding to.
Comment: Thank you! Between you and Willem above I was able to write the formula correctly using %


How do I get the storyline missions to start?

Question: According to the guide at ModLink:

 The storyline starts at about April 14th 2010 when the top Uplink Agent (deceased) sends you an email. In this mail will be a link to ARC Central Mainframe, along with his user name and password. In order to enter the storyline, you must connect to ARC Central Mainframe, and try to hack the system using the Codes that the Agent sent you. The codes wont work, but the act of trying alerts ARC to your presence. Before you do this, make sure you have at least 4Gq of memory space left, or you wont get the file that ARC send you when they contact you. A week or two later, ARC will send you an email offering you a job. Accept this and the storyline begins.

When I got the first message, I initially disregarded it.  I left it sitting in my Inbox, and went to take care of the other missions I had queued first.  After I finally got to following up on the message, I logged into the system of interest only to find that it had security systems that were currently beyond my abilities to hack.  So, I left and continued on completing missions until finally I stumbled across a bank account with over 1 million credits.
After acquiring the finances, and buffing my Gateway to the max, I went to follow up on the e-mail.  After the initial failure with the known account credentials, I went through the standard process of hacking the Admin account.  I logged in to the system, expecting to find something interesting on the file server, and found nothing.  I backed out and cleaned up my tracks, and then went in search of a guide.
That's when I found ModLink.  After reading the guide, I hit the fast-forward button to wait for my next message.  However, months have now gone by and I still have nothing.
Is there something I missed, or is my game broken?
Answer: First, do missions first because you need heavy software. Fast forward until you see a news that uplink top agent is dead from apparent suicide. After a few days, you will receive an email. It says to stand up against arc. Poke Arc central database for a long time and an email will come. reply the message from arc. I think it's named "an offer you can't refuse".
You will receive a mission and a email with Revelation attached. Arunmor's email will arrive shortly (you must fast forward time). Now choose your side.
Answer: Tried to do the arc mission didn't get email for two months after poking around so i decided to let then catch me doing it but since I got caught I got a messenger from uplink and got disavowed for trying to hack into arc
Comment: Just to be clear - you experienced the same problem as the asker, but were able to find a solution?
Comment: No he's saying that he tried letting them catch him in the act to trigger the next story action but that failed. He just died.


async layout switch with left shift and right shift Ubuntu 20.04

Question: I'm transitioning from Windows to Ubuntu and would like to replicate the same functionality I had on my Windows machine using a special layout switcher called Keyla. This switcher allows me to enable the en layout by pressing the Left Shift key, and subsequent Left Shift key presses do not alter the layout. On the other hand, pressing the Right Shift key activates the es layout and also ignores repeated key presses, providing me with certainty about the current layout in use. For instance, I can press the Left Shift key once and be confident that I am typing in the en layout.
I've attempted various suggestions provided by ChatGPT, but none of them have proven successful. The closest solution I found was using xcape with a bash script, but it appears to be impossible to execute a bash script in this context. Furthermore, when I use the command setxkbmap -layout to change the layout, the system's layout indicator remains unchanged. Additionally, I cannot switch layouts using the default switcher (Super + Space) and can only do so by using the setxkbmap command with a different layout.
I'm uncertain whether this is the correct approach, so I'm wondering if anyone else has already configured such settings or knows precisely how to achieve this.
Answer: Ok. Finally I wrote a little service that implements such layout switch scheme. https://github.com/dreamscatchers/layout-switcher


Can completely remove black paint from Bowser?

Question: I see many videos about Black Bowser's battle from Paper Mario: Color Splash. But, after black paint removed from Bowser's head, the black paint takes control of him again and the second phase started.
However, can completely remove black paint from Bowser? If yes, how and what happens after it?
Answer: You can't remove the black paint in the first phase, the black paint can't be lower than half of bowser.