Several artifacts, how to force build order?

Question: I have a (standard non-maven, non-gradle, non-whatsoever) project in IntelliJ IDEA that consists of several modules.
One of those modules results in a jar that is used by one of the other modules.
I have two artifacts. The first one creates a war file. This one depends on the jar file built from the second artifact.
How can I order the build process of the two artifacts so that the second one creates the jar file and copies it to the lib folder of the first, before the first one builds, without the need to recreate both artifacts?
As soon as I select "Build/Build Artifacts/All Artifacts" it always tries to build the first one first.
EDIT: Maybe a better question: What is the recommended way to manually build several artifacts in order of their dependencies?
Answer:
How can I [configure IDEA] ... so that [it] ... creates the jar file and copies it to the lib folder of the first...

You can't really configure IDEA to do this directly. While you can configure Artifacts in the Project Structure dialog, there are no provisions for copying artifacts. IntelliJ IDEA is an IDE, not a build tool. While it can do a lot regarding complying and building, it has its limits.
One possible hackish way would be to go to the Artifact definition in the project structure. There, there are "Pre-processing" and "post-processing" tabs, They have the option to run an Ant target. So you could create a simple Ant target to do the copying. But in the end, I think the best answer to your question:

Maybe a better question: What is the recommended way to manually build several artifacts in order of their dependencies?

is to use a build tool such as Ant, Maven, or Gradle for building the project.


Problem generating dependencies in Makefile using -MM

Question: I am new to Makefiles and g++ and i am struck with a problem while generating dependencies of the project files using -MM flag. I'm posting the Makefile i am using for your consideration. Please take a look.
OUTPUT_ROOT := output/
SOURCE_ROOT := source/

TITLE_NAME := TestProj

SOURCES := \
 MyFile.cpp \
 stdAfx.cpp \
 Main.cpp \

OUT_DIR  := $(OUTPUT_ROOT)

OUT_O_DIR := $(OUT_DIR)

OBJS = $(SOURCES:%.cpp=$(OUT_O_DIR)%.o)
DEPS = $(OBJS:%.o=%.d)
DIRS = $(subst /,/,$(sort $(dir $(OBJS))))
SOURCE_TARGET = $(SOURCES:%.cpp=$(SOURCE_ROOT)%.cpp)
OUTPUT_TARGET = $(OUT_DIR)$(TITLE_NAME)

#---------------------------------------------------------------------
# executables
#---------------------------------------------------------------------
MD := mkdir -p
RM := rm
CC := g++

#---------------------------------------------------------------------
# rules
#---------------------------------------------------------------------
.PHONY: clean directories objects title

all: directories objects title

directories:
 @$(MD) $(DIRS)

clean:
 $(RM) -rf $(OUT_DIR)

$(OBJS): $(SOURCE_TARGET)
 @$(CC) -c $< -o $@

$(DEPS): $(SOURCE_TARGET)
 @$(CC) -c -MM $< > $(DEPS)

-include $(DEPS)

objects:$(OBJS) $(DEPS)

title: $(OBJS)
 @$(CC) $< -o $@

I tried several options and sooo many times. I googled for the solution but couldn't find any.
Is using "-MM" flag to generate dependencies the right option?? If not please suggest me the right way to generate the dependencies. I wanted to generated dependencies automatically because my project will have sooo many files. I thought it is the better option than to write down evey dependency manually.
These are the errors i am getting
g++: stdAfx.d: No such file or directory
g++: Main.d: No such file or directory
make: *** No rule to make target `stdAfx.d', needed by `objects'.  Stop.

Thanks in advance.
Comment: What is "DEPS = $(OBJS:%.o=%.d)" supposed to be doing? And why do you sometimes use ':=' and sometimes '='?
Comment: It is creating DEPS with the names of the objects in the object directory. I'm just testing with both '=' and ':=" options, but dont know the exact diff b/w them
Answer: It looks like you are trying to generate a dependency file (called *.d, by your makefile rules) for each .cpp file. This is not my understanding of how a dependencies file is used.
Use the -M option to generate a single dependencies file for your project and then include the dependencies file.
DEPS = $(OUR_DIR)/make.dep

$(DEPS): $(SOURCE_TARGET)
    @$(CC) -M $(SOURCE_TARGET) > $(DEPS)

include $(DEPS)

edit Your dependency file should also depend on your headers
$(DEPS): $(SOURCE_TARGET) $(HEADER_TARGET)
    @$(CC) -M $(SOURCE_TARGET) > $(DEPS)

where HEADER_TARGET is defined the same as SOURCE_TARGET. That way, when a header file is changed the dependency file is rebuilt.
Comment: Just want to point out that `-MM` excludes system headers ( more or less ) possibly making the build faster since there's allot less files to 1) check 2) process for building the depends list.  For example create foo.cpp with some stl includes and run `g++ -M foo.cpp` to see it spit out a list of close to 100 dependencies, none of which ever change, all of which make will have to check on each build.
Comment: Thank you mcdave, thats a very good trick. i think Generating a single file is better than generating a lot... Thank you again.
Comment: @Robert: Thanks for the tip -- I didn't know this and will update my makefiles to make them more efficient!
Comment: Thanks for posting this here. When using this technique I have the problem that my $(DEPS) target is even executed when I run 'make clean' - which is obviously not necessary and takes a long time. Do you know how to avoid that?
Comment: I'm not sure about this one - I think as soon as there is the `include $(DEPS)` line that the $(DEPS) target is run. It might be possible to add an if statement to remove the include statement when running `make clean`.
Answer: For a beginner, you are doing some exotic stuff. You should start simple and only use code in your Makefile that you 100% understand and trust. Even on a large project with hundreds of files you will not spend much time maintaining the Makefile.
Variables assigned with := are immediately expanded--all the $(VAR) values are substituted into the variable's value during assignment. Variables assigned with = are expanded when they are used, so they can do things like refer to variables that aren't defined yet.
The -MM flag for g++ will generate a Makefile dependency line, e.g. foo.o: foo.cc foo.hh, but I've never found it useful. I had a phony "dependency" target that generated a single dependency file. Your idea of making a bunch of *.d files with those one line dependencies might work, but you'll end up with a lot of those files.
The error you are getting is from g++, not from make. It's because you are using $(DEPS) as if it were a single file when it's the entire list of *.d files. What happens is this line:
@$(CC) -c -MM $< > $(DEPS)

gets expanded to:
g++ -c -MM MyFile.cpp > MyFile.d stdAfx.d Main.cpp

mcdave just posted the code I have used to generate a dependency file. You can either switch to the single dependency file style, or change your -MM command to this:
@$(CC) -MM $< > $@

You may also have to fix the -include statement because I don't think it supports a list of files to include.
Comment: Thank you Ken, i'm using single file now instead of soo many multiple files. Thank you telling the diff b/w '=' and ':=', that sure helps me alot.


Extending a dataframe, filling in missing time, and keeping the other column values with the corresponding time?

Question: More about my problem, I have a 2 column dataframe (one information based, and one time based) that is ~190k rows long. I am missing some dates, and would like to fill in the missing dates while keeping the information with the correct date, and the come back and resample the missing information using the interpolate refill sample.
What I've tried so far:
data_res = pd.period_range(min(data.time), max(data.time), freq = 'H')
...: data_res.reindex(data_res)

which was great, because it gave me the output and the correct times I needed.
(PeriodIndex(['1984-10-25 09:00', '1984-10-25 10:00', '1984-10-25 11:00',
          '1984-10-25 12:00', '1984-10-25 13:00', '1984-10-25 14:00',
          '1984-10-25 15:00', '1984-10-25 16:00', '1984-10-25 17:00',
          '1984-10-25 18:00',
          ...
          '2022-08-16 09:00', '2022-08-16 10:00', '2022-08-16 11:00',
          '2022-08-16 12:00', '2022-08-16 13:00', '2022-08-16 14:00',
          '2022-08-16 15:00', '2022-08-16 16:00', '2022-08-16 17:00',
          '2022-08-16 18:00'],
         dtype='period[H]', length=211460),

Then I used:
data1['time'] = pd.Series(data_res)

which had no issues. Finally I printed the table to double check and the output was:
189741 rows × 2 columns

Where instead of going from late 1980s  to 2022 like when I imported it, it now cuts off at 2006. I understand that the dataframe gets cut off when the row length of the time matches the information column. My problem seems to be twofold: insert the full time, and keep the information column values with the corresponding dates. I tried looking for similar problems, but everything I found was inserting a shorter column into a dataframe and filling the extra values with NA - which is similarish to what I need, but not helpful towards pointing me in the right direction. Does anyone have any ideas on how to fix this? I would also be happy to provide extra information if needed.
Answer: Try a merge of 2 dfs instead of pd.Series.
Time Series Range (using an 8 hr range for simplicity):
import pandas as pd
import numpy as np
s = pd.to_datetime("2022-08-01 00:00:00")
e = pd.to_datetime("2022-08-01 08:00:00")

data_res = pd.DataFrame(pd.period_range(s, e, freq = 'H'), columns = ['Time'])

DF with Data (Just sampling a few of the rows from the full dataset and adding random values as info)
actual_data = data_res.sample(n=6).sort_values(by=['Time'])
actual_data['info'] = np.random.random(size=len(actual_data))

    Time                info
0   2022-08-01 00:00    0.549414
2   2022-08-01 02:00    0.746876
3   2022-08-01 03:00    0.715491
5   2022-08-01 05:00    0.521234
6   2022-08-01 06:00    0.822393
7   2022-08-01 07:00    0.430862

You can then merge these 2 dfs on time and fill nulls from there - I'm filling with 0, but you can use whatever interpolation method is needed.
data_joined = pd.merge(data_res, actual_data, on=['Time'], how = 'left').fillna({'info': 0})

    Time                info
0   2022-08-01 00:00    0.549414
1   2022-08-01 01:00    0.000000
2   2022-08-01 02:00    0.746876
3   2022-08-01 03:00    0.715491
4   2022-08-01 04:00    0.000000
5   2022-08-01 05:00    0.521234
6   2022-08-01 06:00    0.822393
7   2022-08-01 07:00    0.430862
8   2022-08-01 08:00    0.000000

Comment: Absolutely wonderful. I had to use date_range instead, and I had to switch the data.time column to datetime format as well for it to work (type errors with period(H)) - but it is working now! I was wondering if I was missing something obvious, but thanks for the answer!


Is there a way to include multiple != operators?

Question: I'm trying to make a system that outputs invalid if a variable does not equal whole number or decimal number. The problem is, it outputs invalid when the variable is not equal to the first option instead of both options. Is there a fix for this?
I have tried making it an if statement as well as an else if statement instead of separating them with &&. It did not work.
if (user_input != "whole number") {
    std::cout << "\nInvalid";
    goto label1;
  }
  else if (user_input != "decimal number") {
    std::cout << "\nInvalid";
    goto label1;
  }

It outputs invalid is decimal number is inputted.
Comment: You need a compound conditional statement - join your two conditions in a single if statement with || which means or.
Comment: Generally it is poor practice to use goto statements as it makes code that can be very difficult to follow the logic of you have multiple gotos. Try writing your code without them
Answer: Your requirement is that the system should output invalid if the variable does not equal "whole number" or "decimal number".
We can translate this directly into code. To emphasize how I translated the requirement, I'm using and and or, but the code would be identical if you wrote things the more conventional way, using && for and and || for or.
if(user_input != "whole number" and user_input != "decimal number")
{
    std::cout << "\nInvalid";
    goto label1;
}

Alternatively, we could write:
if (not (user_input == "whole number" or user_input == "decimal number"))
{
    std::cout << "\nInvalid";
    goto label1;
}

Comment: I upvoted your answer because it is correct, but I think you may want to mention that the *usual* way to write `or` is `||` and the *usual* way to write `and` is `&&`. Nothing wrong with using the [alternative operator names](https://en.cppreference.com/w/c/language/operator_alternative) - it's just "uncommon".  Same goes for `not` which is commonly written as `!`.
Comment: Awesome! I'm glad I was able to help!
Answer: A readable way to do this, with real code:
bool invalid = ((typeid(var) != typeid(int)) && (typeid(var) != typeid(double)));
if(invalid)
    std::cout << "Invalid !" << std::endl;

Hope it helps.


Division of polynomials to find unknown coefficients

Question: The polynomial $-x^4 -x^3 + ax^2 -17x +b$, where $a$ and $b$ are constants, is denoted by $p(x)$. It is given that $x^2 + 4x + 1$ is a factor of $p(x)$.
(i) Find the values of $a$ and $b$.
(ii) With theses values of $a$ and $b$, show that the equation $p(x)=0$ has exactly two roots.
Comment: It looks like you just typed a homework problem in the box and want it solved for you. What have you tried so far and where are you stuck?
Comment: I've tried long division, then I've got remainder b-a-13=0 I've equated the constants terms = 0, I cant solve it,... :'(
Comment: Good,  please edit your question to include the work you've done (more detail than in the comment above)
Answer: by using the long division of $\frac{-x^4-x^3+ax^2-17x+b}{x^2+4x+1}$
$$\frac{-x^4-x^3+ax^2-17x+b}{x^2+4x+1}=(-x^2+3x+a-11)+\frac{(24-4a)x+b-a+11}{x^2+4x+1}$$
the reminder should be zero
$$(24-4a)x+b-a+11=0$$
$$24-4a=0$$
$$a=6$$
$$b-a+11=0$$
$$b-6+11=0$$
$$b=-5$$
$$-x^2+3x+a-11=-x^2+3x+6-11=-x^2+3x-5$$
or
$$x^2-3x+5$$
the roots of this equation are not real,but the $x^2+4x+1$ has two real roots
Comment: @rasr you are welcome
Comment: @LutzL Thanks, the result is ok but there were some mistakes in the typing numbers and signs.I have corrected them.


UnityEditor.SceneAsset class not accessible in build

Question: I am new to unity addressables and would like to load a scene with an AssetReference. To enforce AssetReferences being a scene, I created the following class in a utility assembly:
using System;
using UnityEngine;
using UnityEngine.AddressableAssets;

[Serializable]
public sealed class SceneReference : AssetReferenceT<SceneAsset>
{
    public SceneReference(string guid) : base(guid) { }
}

JetBrains Rider then said SceneAsset had to be referenced from assembly: UnityEditor.CoreModule. I used its suggestion, and Rider automatically set up the
assembly reference. Everything worked great, and indeed I could only drag scenes into a SceneReference field.
But everything broke down when I went to make a build. I get four errors:
1:Internal build system error. Backend exited with code 139.
2:Error building Player because scripts had compiler errors
3:Build completed with a result of 'Failed' in 11 seconds (11360 ms) UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&) (at /Users/bokken/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:189)
4:UnityEditor.BuildPlayerWindow+BuildMethodException: 2 errors at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x002ce] in /Users/bokken/buildslave/unity/build/Editor/Mono/BuildPlayerWindowBuildMethods.cs:193  at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in /Users/bokken/buildslave/unity/build/Editor/Mono/BuildPlayerWindowBuildMethods.cs:94  UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&) (at /Users/bokken/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:189)
I have tried to manually locate assembly UnityEditor.CoreModule and reference it in my utility assembly's assembly definition asset but couldn't find it. It still works great in the editor but won't compile for a build. If anyone has a solution or at least knows why this isn't working, I would be most appreciative.
Answer: SceneAsset indeed can not be in a build and only exists within the Unity Editor - for what reason ever.
It is a special case of an asset that only exists in editor since later on in a build the scenes are handled completely different as runtime Scene.
The entire UnityEditor namespace is completely stripped of in a build.

For serialization the best option is usually to serialize and store the asset path and later use that for loading the scene.

You can still make scenes Addressables though and load them via the usual more manual Addressables route e.g. using a "normal" generic
public AssetReference Scene;

See Addressables - Scene Loading.


Choosing a smooth diagonalizable approximation of a smooth map into $\text{Aut}(\mathbb R^{n}) = \textbf{GL}(\mathbb R^{n}) \subset M_{n}(\mathbb R)$

Question: Suppose we have a map $\mathbb R^n \to \text{Aut}(\mathbb R^{n}) = \textbf{GL}(\mathbb R^{n})$ with $A=(A_{ij}(x))$ and $A_{ij}$ all being smooth.
It is known that diagonalizable matrices with complex values are dense in set of $n\times n$ complex matrices, in particular matrices with real entries is dense in $M_n(\mathbb C)$ by the same proof if we allow diagonalization over $\mathbb C$. Thus for every $x\in \mathbb R^n$, we can choose a diagonalizable  matrix $B_\varepsilon(x)$ with $\|A(x)-B_\varepsilon(x)\|<\varepsilon$.
However, fixing a compact set $K\subseteq \mathbb R^n$, can we choose a map $x\mapsto B_\varepsilon(x)$ wih ${(B_\varepsilon)}_{ij}$ smooth such that $\|A(x)-B_\varepsilon(x)\|<\varepsilon$ holds for all $x \in K$?
Comment: @saolof Yeah, that's what I meant by allowing diagonalization over $\mathbb C$.
Comment: So A maps from R^n to GL(R^n) and both A and its coordinates in a chosen basis are smooth with respect to the standard topology? And A is fixed in the last part?
Comment: @saolof Yes, in the induced topology given by the inclusion $\textbf{GL}(\mathbb R^n) \hookrightarrow \mathbb R^{n^2}$.

And $x\mapsto A(x)$ is indeed a fixed map $\mathbb R^n\to\textbf{GL}(\mathbb R^n)$.
Comment: R is not algebraically closed though, so in general $B_{\epsilon}$ will be complex?
Comment: If the roots of a complex polynomial depend *smoothly* on the coefficients, I think this wouldn't be so hard to prove, but I don't know whether that's true.
Answer: Not an answer, but too long for a comment. Your statement "in particular matrices with real entries is dense in $M_n(\mathbb C)$ by the same proof if we allow diagonalization over $\mathbb C$." does not hold because of the trace
$$
tr:\  M_n(\mathbb C)\to \mathbb C
$$
which is invariant by conjugation and smooth.
Proof If $M\in M_n(\mathbb R)$ then $tr(PMP^{-1})=tr(M)\in \mathbb R$ which is closed in $\mathbb C$, then $V=tr^{-1}(\mathbb R)$ is closed, different from the whole $M_n(\mathbb C)$ (does not contain $iI_{n\times n}$ for instance) and closed by conjugation.
Hope it helps.


File types in Nautilus - how to distinguish between different file types?

Question: Under file Type column in Nautilus, I get file categories like Image, Document, etc. I need to sort files according to file format. Is there a way make a distinction, based on file formats?
Comment: If you have the same question as someone else 1½ years ago, please try to contribute to that question e. g. by adding a bounty. Voted to close as a duplicate.
Comment: possible duplicate of [How can I stop Files from oversimplifying file types?](http://askubuntu.com/questions/291839/how-can-i-stop-files-from-oversimplifying-file-types)
Answer: How to select / distinguish filetypes in nautilus

In a nautilus window, choose icon view:

Press Ctrl+S (or choose Edit > Select Items Matching...), and type your searched properties:

The items that fulfill the requirements are selected:
Comment: @tagMacher was this the kind of answer you were looking for?
Comment: Actually what you suggested is the way I should have done; I could also have worked more efficiently than what I did, by opening up a Terminal window. The real issue is a successive dumbing down of Ubuntu that concerns me; I wanted to ask others if there is going to be a reversal in future versions, or is Ubuntu going the way of Microsoft Windows; David Foerster and others feel this is irrelevent and out of place so I will shut up here.


My code is not picking up the latest file in the folder

Question: Problem is simple. Not getting the latest file. And this problem only creeped up because of new year. It was working fine last year
Here is the relevant code:
 Dim yr As String
 Dim mo As String
 Dim destinationsfn As String
 Dim destinationtsfn
 Dim bdate As String
 Dim fdate As String
 Dim destinationfp As String
 Dim destinationfo As String
 Dim destinationShVar As Worksheet
 Dim destinationTorc As Workbook

 Dim sht As Worksheet

 yr = Format(Date, "yyyy")
 mo = Format(Date, "mm")

 If mo < 10 Then
 mo = Right(mo, 1)
 End If

 destinationfo = Dir("W:\Product Platforms\Macro\New destination Database\destination Master File\" & yr & "\" & mo & "*", vbDirectory)
 destinationfo = Trim(destinationfo)

 destinationfp = "W:\Product Platforms\Macro\New destination Database\destination Master File\" & yr & "\" & destinationfo & "\"

 destinationsfn = Dir(destinationfp & "*-*.xlsx")

Do While Len(destinationsfn) > 0
fdate = FileDateTime(destinationfp & destinationsfn)
    If fdate > bdate Then
        destinationtsfn = destinationsfn
        bdate = fdate
    End If
    destinationsfn = Dir
Loop

 On Error Resume Next
 Workbooks.Open (destinationfp & destinationtsfn)

Comment: Are the results from FileDateTime as you expect?  Try adding `Debug.print destinationsfn, fdate` inside the dir loop and check the output
Comment: `fdate` and `bdate` are both strings on this line `If fdate > bdate Then` (as that's what they're declared as). Shouldn't you convert them to dates prior to/during the comparison on the line? Does that make a difference? Conversion can be done with `cdate()`.
Comment: Have you tried debugging?  Is it finding the correct source folder?
Comment: Yeah, did the debugging and its only picking up the file of Jan 2nd and not Jan 4th
Comment: so its pikcking up 1-2.xlsx and not 1-4 xlsx
Comment: If you are in the US, a string `"12/31/2018"` will evaluate as being greater than a string `"01/01/2019"` I think -- due to alphabetical order (as the variables aren't dates).
Comment: Not sure why my debug print isn't working and i am in Canada, would that make a difference?
Comment: @Piccinin, if Excel shows you dates in `MM/DD/YYYY` format (due to your regional/local settings), then yes, it might do (as `FileDateTime` will return a Variant Date, which gets converted to a string according to these settings). Either way, I would consider declaring `bdate` and `fdate` as variants or dates, so that the `>` operator is comparing dates and not strings -- and so that your code is not sensitive to the user's locale settings.
Comment: Hey Chillin it worked, can you post this as answer so i mark it as correct answer?
Comment: @Piccinin, sure, have done so.
Answer: fdate and bdate are both declared as strings.
So, on this line:
If fdate > bdate Then
You aren't comparing dates with the > operator. You're comparing strings, which means alphabetical order is considered.
If you are in the US or any country that formats dates as "MM/DD/YYY..." and your locale settings in Excel reflect this, then the string "12/31/2018" will evaluate as being greater than a string "01/01/2019", due to alphabetical order. If they were dates, the opposite would be true.
Easiest fix might be just to declare both bdate and fdate as variant or date.


How to show current cart product's details on checkout page

Question: Hello guys,
Thanks in advance.
I am new to opencart and am currently developing a shopping cart in opencart and everything was going smoothly but I got stuck, help please
I want to access currently added cart items in checkout.tpl for generating an inquiry form, so I was editing controller/checkout.php and added these lines of code to access product details that are currently in the cart:
<code>    //Product detail for Enquiry
    $product_data = array();

    foreach ($this->cart->getProducts() as $product) {
        $option_data = array();

        foreach ($product['option'] as $option) {
            if ($option['type'] != 'file') {
                $value = $option['option_value'];
            } else {
                $value = $this->encryption->decrypt($option['option_value']);
            }

            $option_data[] = array(
                'product_option_id'       => $option['product_option_id'],
                'product_option_value_id' => $option['product_option_value_id'],
                'option_id'               => $option['option_id'],
                'option_value_id'         => $option['option_value_id'],
                'name'                    => $option['name'],
                'value'                   => $value,
                'type'                    => $option['type']
            );
        }

        $product_data[] = array(
            'product_id' => $product['product_id'],
            'name'       => $product['name'],
            'model'      => $product['model'],
            'option'     => $option_data,
            'download'   => $product['download'],
            'quantity'   => $product['quantity'],
            'subtract'   => $product['subtract'],
            'price'      => $product['price'],
            'total'      => $product['total'],
            'tax'        => $this->tax->getTax($product['price'], $product['tax_class_id']),
            'reward'     => $product['reward']
        );
    }

    $data['products'] = $product_data;
</code>
and then added a line in checout/checkout.tpl :
<code>    foreach ($products as $product)
    {
        echo 'yes am getting products details';
    }
</code>
but still getting error: Undefined variable: products ?
Am I doing it right? please correct me.
Answer: What you have done is almost correct, however you've used
<code>$data['products'] = $product_data;
</code>
where you should have put
<code>$this->data['products'] = $product_data;
</code>


Parse date with timezone

Question: I tried to parse this string :
"2018-08-21T10:12:06.872722+00:00"

but got java.text.ParseException.
I'm using this format :
"yyyy-MM-dd'T'HH:mm:ss.SSSz"

important: I tried to use: XXX, ZZZZZ, ZZZ, z for timezone, but not working
What is wrong? thanks.
covert date to new format:
formatDate("2018-08-21T10:12:06.872722+00:00");

public static String formatDate(String date) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
    SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd");

    Date d;
    try {
        d = sdf.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
        return "";
    }

    return output.format(d);
}

Comment: please show your code.
Comment: @VivekMishra, i tried solutions from your topic, it's not work
Comment: @Abhishek, i updated my question :)
Comment: @SWR i've given an answer. Hope you find it helpful.
Comment: As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with.
Answer: You can call this method.
void checkDateParsing()
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
            Date d = null;
            try {
                d = sdf.parse("2018-08-21T10:12:06.872722+00:00");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Log.e("date",d.toGMTString());
        }

Comment: It's working fine with your date.
Comment: ahh)) thanks for answer, i found mistake, that i use SSS instead of SSSSSS, xd, your answer is true, it's working fine now
Comment: Please vote if you find it correct.
Comment: While it may work on Android, on my Java 8 I get `java.text.ParseException: Unparseable date: "2018-08-21T10:12:06.872722+00:00"`. Using `XXX` instead of `Z` I get `21 Aug 2018 10:26:38 GMT`, which is 14 minutes 32 seconds off.
Answer: The SimpleDateFormat class you are using is now legacy, and should be supplemented by the java.time classes. Also it isn't thread-safe.
Therefore if you are using java 8 or above then use the below sample code::
public static void main(String[] args) {
        String date = "2018-08-21T10:12:06.872222+00:00";
        LocalDateTime parsedDate = LocalDateTime.parse(date, java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSz"));
        System.out.println(parsedDate.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}

If you are stuck with using SimpleDateFormat class then follow the answer by @Prateek.
Comment: No need to code your own format pattern strings since the involved formats are standard (ISO 8601). Just use `DateTimeFormatter.ISO_OFFSET_DATE_TIME` for parsing and `DateTimeFormatter.ISO_LOCAL_DATE` for formatting. You may even parse into an `OffsetDateTime` without mentioning any formatter at all.
Answer: In java 8 or above, you can achieve the same effect using one-line code as:
System.out.println(OffsetDateTime.parse("2018-08-21T10:12:06.872722+00:00",
            DateTimeFormatter.ISO_OFFSET_DATE_TIME).toLocalDate());

Output:
2018-08-21

Answer: public class test1 {
public static void main(String[] args) {
    System.out.println(formatDate("2018-08-21-10:12:06.872+0100"));

}

public static String formatDate(String date) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss.SSSZ");
    SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd");

Date d;
try {
    d = sdf.parse(date);
} catch (ParseException e) {
    e.printStackTrace();
    return "";
}
return output.format(d);

}

Parse date with timezone


Lenovo X1 Carbon is not charging battery even if plugged into AC

Question: I installed Ubuntu 13.04 on my X1 Carbon Touch laptop yesterday and everything worked fine, the battery charged as usual. Today I've noticed that the battery indicator shows me that I am working on battery power even if I plug power adapter into AC and LED on the left side of the laptop (near the power connector) is green.
I tried to use tpl tools as described somewhere on this site to set start and stop discharge thresholds but it does not help.
The only way to charge the battery is to shutdown laptop completely (not suspend) and wait for a couple hours. Which is not so great though. :)
Answer: Looks like the problems was in power adaptor I bought in some shady shop over the Internet. After switching back to original power supply problem dissolved.


Do natural structures generate above 128 blocks?

Question: We are running a Minecraft server (bukkit) with new version 1.2. The height limit was doubled in the release, but I can't find any natural structures that use the new space above 128 blocks. I found some jungle trees and mountains that are 122 blocks height, but nothing above 128.
Does the map generator generate natural structures higher than the old 128 block limit?
Edit:
A source for your answer would be nice. (The code of the part of the generator that limits the height, or a seed to proof structures above 128 blocks)
Comment: I forgot about that change. Maybe Notch will finally give us deeper oceans!
Answer: Dinnerbone has answered this question on reddit:

Will the terrain generator ever be updated to use the full 256 blocks of build height?
It's intentionally designed to only go as high as it does right now. Maybe in the future, or with different generators/options, but right now we're happy with the extra breathing room for players.
Answer: No, natural structures will not generate any differently as part of the height limit change. This change is thanks to the conversion to the new file format, Anvil, which supports layers 0-255 (as opposed to the Region file format, which only supports layers 0-127). The terrain generator works just like it used to, and blocks between layers 128-255 just default to air.
Comment: a source would be nice.
Comment: I'm willing to bet that if you added a source, the upvotes for Walter's comment would magically spawn some upvotes for your answer.
Answer: It doesn't generate terrain above 128 just like the old terrain generation everthing above there is just air, but if you want there's a mod that changes this, all it does is change a few numbers in the terrain generation code the rest stays the same, I'm pretty sure its called Dynamic Heights Mod (or something along those lines).


Xcode 6 integrate remotely

Question: We used XCode 5 Continues Integration in our company. There was a bot for our QA Team, I configured it to upload builds on TestFlight service. Testers, when they needed a build to test last changes in app, opened XCode bots web page, pressed "Integrate" button, integrate starts and on finish uploads a build to TF, testers got an email with the installation link.
Here is the link I found in web, it illustrates the old bots web page. There is a button to start integrate along the bot name:
http://matt.vlasach.com/wp-content/uploads/2013/10/Xcode-All-Bots.png
After upgrade to XCode 6 and last version of OS X Server  the manage bots web page doesn't have "Integrate" button, integrate is performing from XCode. I really don't want  QA team installs XCode to start integration.
The new bots web page without integrate button:
https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/xcode_guide-continuous_integration/art/bots_website_summary_2x.png
On WWDC 2014 "Continuous Integration with Xcode 6" video Apple guy uses Jeewes -  a Jabber robot that can start Integrate without XCode. As I understand should be a script that this robot calls.
The question is: How they setup launch integrate remotely, so the people without XCode can run bots.
Thank you.
Comment: Hi do you have any news about tis?
Answer: Apple has removed this feature. Not sure why. You can file an issue with them and hope they will look into it.
Your best bet is letting them remotely access a machine and kick it off from xcode there.
Answer: You'll want to check out this answer
Using script to fire Xcode bot
You can use the apple api to get JSON responses from os x server, so you can ask for all bots, get their IDs and names, show that remotely to a user who can tap on one, which then sends a POST to os x server to activate the bot.

Xcode 6 integrate remotely


Dynamically Adding Similar Objects

Question: I'm trying to push similar objects into an array and in each object I'm pushing some values, but the values updated are reflecting in all objects. I want to add only three values from the foo array into the 1st object and other 3 in foo of second object, but in both the objects, all six values are appearing.
<!DOCTYPE html>

{{(x)}}

Answer: Have a temporary array variable to hold the 3 values and push that value to foo array
var temp=[];
for(i=0;i<arr.length;i++){
    temp[i%3]=arr[i];
    if((i+1)%3==0){
        foo.push(temp);
        temp=[];
        k++;
    }
}

Dynamically Adding Similar Objects


Aging strategy in Forge of Empires

Question: In Forge of Empires I am in Early Middle Age and nervous about advancing. I have heard that some ages, like late/high middle age can be difficult to advance through and a player can get "stuck" in the age.
I have also heard that if you advance too far in age, it can be even worse because the advanced age can be very difficult and unrewarding to play and there is no way to go back.
So, I need sort of an aging strategy. What should be my approach and considerations for when to advance an age, and which age to advance to?
Answer: It is very important when you age up to do so with momentum. To do that you need to be prepared and choose your timing.
Preparations
There are few considerations that need to be considered before aging up to prevent being in an awkward position. These involve map progress, quest progress, building age, forge point storage, and the availability of goods.
Map progress
When aging up, it is important that your progress on the continent map is sufficient enough that you have boosted goods from that age, or that you can easily reach them. Progressing too far on the map can lead to problems, in that it can remove the ability to access recurring quests. Make sure you are observant of that.
Quest Progress
Prior to aging up, it is important to make sure that you are in a good place in your story line to take advantage of any "camping" options the next age may have. For example, in Late Middle Ages you can have access to two recurring quests at the same time if you take precaution with the story line.
Building Age
Special buildings (such as those from events or the antique dealer) do not automatically age up. Some don't need to, because the only added bonus is more gold. Others do need to, such as certain buildings giving attack power, or builds which provide goods. In order to accomplish this, you will need a boatload of one up kits or renovation kits; the more the merrier, and each age will progressively require more and more as well.
Forge Points
You will want to have enough forge points saved to move through the first 3 or so levels of the tech tree. This will require a decent amount of banked (inventory) forge point packets as well as timing your collections so that your bar has as many as possible. You may also end up buying some points with gold.
Available Goods
Aging up will require a decent amount of goods in order to purchase tech in the tech tree. Make sure you have enough goods on hand so that you don't accidentally get stuck needing some.
Timing
Once all of that is in place, make sure to plan on getting to your boosted goods and to your military of choice on day 1 of aging up if possible. With that plan in place, it is best to wait until right after both a season of Guild Battleground and Guild Expedition start. This will allow you to fight with advanced aged troops for 10 days in GBG and 64 encounters of GE.
All that is left is to start preparing, and to figure out which age is best for you. You may find that certain ages fit your fighting style better, or that more goods are available for trades, or that a neighborhood is easier to be in, or that your guild needs goods from that age.
Good Luck!
Answer: Yes, I know it's over a year old and you may already have all the answers you need, but, like me, others may be finding this later, and I'm writing for them, too :)
That first answer is an excellent overview of "how" but not "when" or "why".
But I'll start with the last part of your question first.
If you get stuck in a higher age you don't like, move on to the next, then the next, until you get to one you like again. If you can't find one, start a fresh world (or delete and start again on your current world), knowing that you're never going to advance beyond the age you've decided is yours.
More generally, the "Why" is much harder to answer. Some of the more experienced players in my guild(s) say they age up when they're near the top of their neighbourhood, or are bored with their current age. Yes, they'll prepare for the move by stockpiling goods and fp's for the tech tree, but having sufficient prep isn't the "reason why" they move when they do.
As for "When", the exact timing, there are different opinions as to whether it's better to age up before, during or after the next Event/GBG/GE season. Ask within your guild, you'll get lots of different answers and can then choose the approach that fits your style of play.
Finally here's a little insight into my own thinking when I am trying to decide when/why to move up an age:
I enjoy "camping" in an age. After 3 years and 6 worlds, I find I really like EMA. Battle quests (for events) are easy because you still have "small" players at the lower end of your neighbourhood, who are easy to beat. By Colonial, most of those have dropped out of the game.
None of my cities is higher than Industrial. On some worlds I've aged up because my guild required it. On one I aged up to Colonial because I dislike the appearance of the buildings in LMA. On another I got as far as Industrial because I wanted to see what it was like, and am nearly ready to move beyond that.  I've also decided that on one world I'll race ahead about 3 or 4 eras to something well advanced of my other worlds, just to see how it feels, but I don't know which of my six worlds I'll use for that experiment - probably the one that's already at Industrial. But I've been reluctant as I don't want to deal with 2-lane roads and "refined" goods once I hit whatever age it is that those kick in. I might get there, and find that I really love those features, and wonder why I've deprived myself of them for so long. Who knows? It's a game, the idea is to enjoy it.
Answer: My main goal in the game was to see all the ages so I could see the different technologies, buildings and mini-games (like the Oceanic Terminal).
I have played for over a year now and have made it to Oceanic Future. Here are my tips for aging:
(1) In general, if you want to maximize your progression in seeing content, you should age up as soon as your city has the stability to do so (see below for what I mean by stability).
(2) The main risk in aging up is that your military will be underpowered, so the two things you want to make sure of is to be able to immediately research all the key military technologies, and to have a high enough Attacker boost level.
(3) First things first, you should actively add new tiles to your city, so if there are bunch of tiles available by doing straightforward things, you should do that immediately and exploit those tiles before anything else. You should maximize all the tiles in the city. I aim at having buildings generating at least 1 FP per tile or 1% attacker boost per tile.
(4) Save up resources and FP so that when you age up you can get all the military unit types that you need. In general, each age has a preferred one or two military units (usually the heavy unit). You just use that one unit + ghosts when you fight. You can find the list of units elsewhere on the internet. For example, in Future, Arctic Future and Oceanic Future, Hover Tank is the key unit. In Contemporary, Anti-Aircraft Vehicle is the key unit, etc.
(5) You can tell if you have enough attack boost by how you are doing in GE. If you can complete all 64 encounters in GE comfortably, then you are strong enough to age up. If you are struggling to finish GE, then you should work on your Attacker boosts more. Note that it is more important to develop Attacker Defense than Attacker Attack. The reason for this is that attack boost power scales asymptotically, so that means it is very difficult to one-shot units, so you only need enough attack to two-shot units, since you will never get enough boost to one-shot units in most cases. However if you work on your Attacker Defense, you can easily get to a point where the enemy can only three-shot or four-shot you. This is why Attacker Defense is much more important than Attacker Attack.
(6) Never waste tiles on City defense. The value of the tiles for FP and Attacker bonus is much much more important than the trivial amount you might lose to plundering. Also, City defense will not really stop most plunderers. I easily plunder even the strongest people in my neighborhood, so all their defense is basically wasted tiles.
(7) Getting in good guilds will greatly help your progression.
Answer: I have some different opinions about the comment above.

Do not research all military technologies, nor any other technologies too fast after aging up. If you need units of next era ASAP, just wait for a GBG opening day (Thursday morning) to age up and fight enemies of lower ages to earn as many units as you can.

In some ages you can have higher era units, researching technologies before having a main quest asking you to do so will make you miss some most advantages (like having Hover Tanks in CE or PME).
See this tutorial for more informations:
https://forum.us.forgeofempires.com/index.php?threads/higher-age-units-guide-v1-22.37109/

No, it's always more important to have more attack bonus for attacker than defense one, especially after having Arctic Orangery. You dont need to one shot directly, but you shall at least have 7 damage points each shot. Why? Because with Arctic Orangery, having more than 7 base damage means one-shot-kill each critical strike. (7 X 1.5 > 10).

In the late game, all space-age units have the skill "keen eye", allowing an extra chance of critical strike with double damage. In the beginning of each round, the player always move first before AI enemy for the same type of units, having higher attack bonus means you can one shot kill enemy before they even have chance to attack you (let alone they have to waste one more shot to transform your rogue first), defense bonus wont make a lot of change in this case.
The only exception is when you are in an age where the heavy unit has the skill "reactuve armor"(CE, AF, OF etc), without critical strick you cannot deal more than 4 damage (3 for AF heavy unit) no matter your attack bonus, only in this case your defense bonus matters since you cannot fast kill the enemies before getting attacked.

If you play PvP, city defense bonus now matters a bit, especially when you have higher-era units as defense, or when you are in some ages like SAM where your units are much more powerful that those in previous age. Yes, you can never truly stop your neighbour of the same age, but you can at least "discourage" a lot of lower age attackers in PvP from attacking you, which will make you loose your PvP points more slowly. Most players are not hardcore fighters like me to be ready to crush anyone of higher era, some of them will just click "refresh" to seek an easier opponent after seeing your defense bonus .

As my own example, here is a video of how I repelled a TE attacker with 600% bonus (auto fight) when I was in CE. Even I have only a little defense bonus, but with AF and OF units and around 150 city defense, it's still possible to win an auto combat. So do not rush the conclusion that "city defense is useless", having kind of 150-200 city defense bonus does not take bunch of space (some are included in event buildings), but in some specific cases it will make alot of difference.

For the topic, my own suggestion is, besides enough attacker boost and FP/goods production, it's better to learn abit the age you want to move in, the combat mecanism, how to get higher era units if possible, etc. Especially after AF the gameplay is changed and you wont be allowed to rush several ages in a time. So dont get surprised by your new age and end up hating it, that's the most important thing.

Aging strategy in Forge of Empires


User with multiple roles, access always denied

Question: Users may have multiple roles, e.g. ROLE_USER, ROLE_SUBSCRIBTION_FOO, ROLE_SUBSCRIBTION_BAR.
Based on their role I define an access control list:
    - { path: ^/admin/helpdesk/foo, roles: ROLE_SUBSCRIPTION_FOO }
    - { path: ^/admin/helpdesk/index, roles: ROLE_ADMIN }

The role hierarchy
role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUBSCRIBTION_FOO: ROLE_ADMIN
        ROLE_SUPER_ADMIN: ROLE_ADMIN

The problem now is, when user has the role ROLE_SUBSCRIBTION_FOO and accesses  /admin/helpdesk/foo access is denied. The user has both ROLE_ADMIN and ROLE_SUBSCRIBTION_FOO. However when I have
- { path: ^/admin/helpdesk/foo, roles: ROLE_ADMIN }

it works but I need it to be
- { path: ^/admin/helpdesk/foo, roles: ROLE_SUBSCRIPTION_FOO }

which does not work, howeve the user does have the role? This is kinda weired. Any ideas where the problem is?
Comment: Are you sure the user you are testing has the `ROLE_ADMIN` and not `ROLE_SUPER_ADMIN`? Because with your actual setup a user with `ROLE_SUPER_ADMIN` does not have `ROLE_SUBSCRIBTION`.
Comment: Nope, user with roles a:2:{i:0;s:10:"ROLE_ADMIN";i:1;s:21:"ROLE_SUBSCRIBTION_FOO";} is the user I am testing
Comment: Well, it seems right... Have you checked if the user has these roles in the session as well? not in the db only?
Comment: Checked array(3) { [0]=> string(10) "ROLE_ADMIN" [1]=> string(21) "ROLE_SUBSCRIBTION_FOO" [3]=> string(9) "ROLE_USER" }
Comment: Awww it works now. I deleted dev cache and it seems to work
Answer: It looks like a typo to me. You defined ROLE_SUBSCRIBTION_FOO in your hierarchy (with a B) but you're wanting to restrict the path with ROLE_SUBSCRIPTION_FOO (with a P).
Answer: Looking at the setup everything seems right.
I want to change user roles dynamically from admin area of my application. So e.g. I give the FOO role to user BOB and expect the changes to take effect immediately.
But this does not work. The currently open session of user BOB is not refreshed. He has to reauthenticate himself. After reauthentication (logout and login again) symfonys security system will compare the role correctly with the given access list.
So I expected the user session to be updated automatically, but this is not possible with the default security system of symfony. I think it needs to be extended with database based session management. This way you could refresh the user session.


How can i put text in disabled  with selenium chrome driver and c#?

Question: Hellow, i have  element on web page, that is disabled. Here it is: disabled element
<input id="uploadPdfFileName" type="text" class="form-control" placeholder="Test" title="Test" disabled="disabled">

i tried put some text in it with selenium sendKeys() method, but i got this:
OpenQA.Selenium.InvalidElementStateException : invalid element state: Element is not currently interactable and may not be manipulated

How can i put text in this element with selenium chrome driver and c#? Maybe i must try some other ways?
Answer: Try maybe to set the text before and then disable it with selenium.
Answer: I change "disabled" attribute to false with ExecuteScript() selenium method, before putting text in input with sendKeys(). It woks.


Gridview popout window to edit when clicked on a column

Question: I have a gridview. I need to include a hyperlink to one of the columns so when the user clicks the link a popout should come with option to Edit and save. After the save the gridview should automatically get refreshed.
Following is my Gridview Code:
 <asp:GridView ID="EmployeeGridView" runat="server" AutoGenerateColumns="False"
               DataKeyNames="Emp_id" onrowcancelingedit="EmployeeGridView_RowCancelingEdit"
               onrowediting="EmployeeGridView_RowEditing" onrowdeleting="EmployeeGridView_RowDeleting"
               onrowupdating="EmployeeGridView_RowUpdating" Width="395px"
               CellPadding="4" ForeColor="#333333" GridLines="None"
               onrowdatabound="EmployeeGridView_RowDataBound" AllowPaging="True"
               onpageindexchanging="EmployeeGridView_PageIndexChanging1" PageSize="5">
               <AlternatingRowStyle BackColor="White" />
    <Columns>
    <asp:TemplateField HeaderText = "Action">
                   <ItemTemplate>
                        <asp:CheckBox ID = "chkDelete" runat = "server" AutoPostBack="True"
                            oncheckedchanged="chkDelete_CheckedChanged" />

                    </ItemTemplate>
            </asp:TemplateField>

    <asp:TemplateField HeaderText="Sr.No">
                   <ItemTemplate>
                       <asp:Label ID = "lblID" runat = "server" Text = '<%#Container.DataItemIndex+1 %>'></asp:Label>
                   </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Name">
                   <ItemTemplate>
                        <asp:Label ID = "lblEmpName" runat = "server" Text = '<%# Eval("Emp_name") %>'></asp:Label>
                    </ItemTemplate>

                                    <EditItemTemplate>
                                         <asp:TextBox ID="txtempname" runat="server" Text='<%#Eval("Emp_name") %>'></asp:TextBox>
                                    </EditItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField HeaderText="Experience">
                   <ItemTemplate>
                        <asp:Label ID = "lblEmpExp" runat = "server" Text = '<%# Eval("Emp_exp") %>'></asp:Label>
                   </ItemTemplate>

                                  <EditItemTemplate>
                                           <asp:TextBox ID="txtempexp" runat="server" Text='<%#Eval("Emp_exp") %>'></asp:TextBox>
                                  </EditItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField HeaderText="Address">
                    <ItemTemplate>
                        <asp:Label ID = "lblEmpAddress" runat = "server" Text = '<%# Eval("Emp_address") %>'></asp:Label>
                    </ItemTemplate>

                                <EditItemTemplate>
                                            <asp:TextBox ID="txtempaddress" runat="server" Text='<%#Eval("Emp_address") %>'></asp:TextBox>
                                </EditItemTemplate>
    </asp:TemplateField>
                <asp:CommandField ShowEditButton="true" ButtonType ="Button"
            HeaderText="Edit" ControlStyle-BackColor= "#15524A" >
<ControlStyle BackColor="#15524A"></ControlStyle>
        </asp:CommandField>
                <asp:CommandField ShowDeleteButton="true" ButtonType="Button" HeaderText="Delete" />
    </Columns>

        <EditRowStyle BackColor="#7C6F57" />
        <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#E3EAEB" />
        <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F8FAFA" />
        <SortedAscendingHeaderStyle BackColor="#246B61" />
        <SortedDescendingCellStyle BackColor="#D4DFE1" />
        <SortedDescendingHeaderStyle BackColor="#15524A" />
    </asp:GridView>

The code behind is :
public partial class _Default : System.Web.UI.Page

{
    SqlConnection connstr = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            protected void EmployeeGridView_Sorting(object sender, GridViewSortEventArgs e)
    {
        Session["sortBy"] = e.SortExpression;
        FillGrid();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Session["sortBy"] = null;
        if (!Page.IsPostBack)
        {
            FillGrid();
            BindGrid();
        }

    }
    public void FillGrid()
    {
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("GetEmployeeInfo", con);
        SqlDataReader dr = cmd.ExecuteReader();//it reads froword only data from database
        DataTable dt = new DataTable();//object of data table that uses to conatin whole data
        dt.Load(dr);//Sql Data reader data load in data table it is DataTable Method.
        EmployeeGridView.DataSource = dt;
        EmployeeGridView.DataBind();

    }
    private void BindGrid()
    {
        string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select Id, Name from tblFiles";
                cmd.Connection = con;
                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();
                con.Close();
            }
        }
    }
    protected void EmployeeGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        EmployeeGridView.EditIndex = -1;
        FillGrid();

    }
    protected void EmployeeGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        EmployeeGridView.EditIndex = e.NewEditIndex;
        FillGrid();

    }

    protected void EmployeeGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int empid = Convert.ToInt32(EmployeeGridView.DataKeys[e.RowIndex].Value.ToString());//Get Each Row unique value from DataKeyNames
        string name = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempname")).Text;//get TextBox Value in EditItemTemplet that row is clicked
        string experience = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempexp")).Text;
        string address = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempaddress")).Text;
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("EmployeeUpdate", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@emp_id ", empid);
        cmd.Parameters.AddWithValue("@emp_name ", name);
        cmd.Parameters.AddWithValue("@emp_exp ", experience);
        cmd.Parameters.AddWithValue("@emp_address ", address);
        cmd.ExecuteNonQuery();//Sql Command Class method return effected rows use for insert,update, delete
        EmployeeGridView.EditIndex = -1;// no row in edit mode
        FillGrid();
    }
    protected void EmployeeGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int empid = Convert.ToInt32(EmployeeGridView.DataKeys[e.RowIndex].Value.ToString());
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@emp_id ", empid);
        cmd.ExecuteNonQuery();
        FillGrid();

    }

    protected void EmployeeGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        EmployeeGridView.PageIndex = e.NewPageIndex;
        FillGrid();
    }

    protected void buttonDelete_Click(object sender, EventArgs e)

    {
        foreach (GridViewRow row in EmployeeGridView.Rows)
        {
            var chk = row.FindControl("chkDelete") as CheckBox;
            if (chk.Checked)
            {
                var lblID = row.FindControl("lblID") as Label;
                Response.Write(lblID.Text + "
");

                SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand comm = new SqlCommand("Delete  from tbl_employee where Emp_id=@emp_id", conn);
                // comm.CommandType = CommandType.StoredProcedure;
                conn.Open();
                comm.Parameters.AddWithValue("@emp_id", int.Parse(lblID.Text));

                comm.ExecuteNonQuery();
                conn.Close();
            }
       }
        FillGrid();
    }
    protected void buttonUpdate_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in EmployeeGridView.Rows)
        {

            var chk = row.FindControl("chkDelete") as CheckBox;
            if (chk.Checked)
            {

                SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

                var lblID = row.FindControl("lblID") as Label;
                var lblEmpName = row.FindControl("lblEmpName") as Label;
                var lblEmpExp = row.FindControl("lblEmpExp") as Label;
                var lblEmpAddress = row.FindControl("lblEmpAddress") as Label;
                //Response.Write(lblFirstName.Text + "
");
                SqlCommand comm = new SqlCommand("EmployeeUpdate", conn);
                comm.CommandType = CommandType.StoredProcedure;
                comm.Parameters.AddWithValue("@emp_id", int.Parse(lblID.Text));
                comm.Parameters.AddWithValue("@emp_name", EmpName.Text);
                comm.Parameters.AddWithValue("@emp_exp", EmpExp.Text);
                comm.Parameters.AddWithValue("@Emp_address", EmpAddress.Text);

                conn.Open();
                comm.ExecuteNonQuery();
                conn.Close();
                EmpName.Visible = false;
                EmpExp.Visible = false;
                EmpAddress.Visible = false;
            }

        }
        FillGrid();
    }
}

For the column Name I need to make a hyperlink and when clicked the popout should come to edit and view data
Comment: Please visit following link:-http://www.aspdotnet-suresh.com/2011/03/how-to-show-modalpopup-to-edit-gridview.html
Answer: Not sure I fully understand what do you need but you can check out how modal popup works in MS AJAX toolkit and try to emulate sample code that comes with the download.


Meteor js client side connect directly to mongodb

Question: Using meteor js on the client side and from this condition: if (Meteor.isClient), is it possible to connect to a mongodb collection directly?
If so, how can I do that?
Answer: Well, that's what Meteor is all about! See the documentation. Simple example:
<code>if(Meteor.isClient) {
  Documents = new Meteor.Collection('documents');
  var document = Documents.findOne({title: 'Example'});
}
</code>


Why is NodeJS inaccurate with big-number additions?

Question: I performed the same addition in PHP and NodeJS. PHP calculated correctly upto 1 billion iterations, but NodeJS calculated correctly only up to 100 million iterations.
This is the PHP code:
<?php
$start_time = time();
$j = 0;
for ($i = 0; $i <= 1000000000; $i++) {
    $j += $i;
}
$end_time = time();
echo "Time Taken: " . ($end_time - $start_time);
echo "\n";
echo "i: " . $i;
echo "\n";
echo "j: " . $j;
echo "\n";
?>

Which returned the following output:
Time Taken: 15
i: 1000000001
j: 500000000500000000

This is the NodeJS code:
var epoch = require('epoch.js');
var start_time = epoch().format('ss');
var i;
var j = 0;
for (i = 0; i <= 1000000000; i++) {
    j += i;
}
var end_time = epoch().format('ss');
var time_taken = end_time - start_time;
console.log("Time Taken: " + time_taken + " \ni: " + i + "\nj: " + j);

Which returned the following output:
Time Taken: 1
i: 1000000001
j: 500000000067109000

Why is the j variable wrong in NodeJS?
Edit:
As pointed out by @SalmanA (and confirmed by me) I would further like to ask why the max integer limit stays same for Javascript on different processors, but changes for PHP?
Comment: http://www.javascripter.net/faq/accuracy.htm this article describes why js is inaccurate and also how you go around.
Comment: PHP floating point numbers are subject to same limitations as those for JavaScript number. Why PHP produces 500000000500000000 is beyond me... I get different result.
Comment: With your PHP code I get `500000000067109000` by setting [`precision`](http://php.net/manual/en/ini.core.php#ini.precision) to 17.
Comment: That is actually another interesting question: It seems Javascript conforms to a fixed limit whereas for PHP the limit changes with hardware. Thanks for pointing it out @SalmanA
Comment: @Turab PHP _typically_ uses the same floating point number format that JavaScript uses (IEEE 754) so both have same characteristics and same problems. If your PHP script displays 500000000500000000 then something is peculiar about your PHP setup.
Comment: @SalmanA I checked this same piece of code on two very different machines with very different PHP setups, yet returning the same output.

Details of the machines are:

Machine 1: Intel Core i5-6440HQ CPU @ 2.60GHz - 8GB DDR4 RAM - PHP 7.1 ---

Machine 2: Intel Xeon E3-1246V3 - 4GB DDR3 - PHP 5.6
Comment: In JavaScript all numbers are _defined_ to be 64-bit IEEE-754 doubles.  In PHP, they're not - it's architecture dependent.
Answer: Since you changed the intent of question I felt like reopening it.
In JavaScript, there are no integers or floats, just Number, represented using IEEE 754-2008 64-bit (double-precision) format. One of the characteristics of this format is that all "integers" between −9007199254740991 and 9007199254740991 can be represented accurately. Numbers outside this range are approximated. Simple example:
> 9007199254740993
< 9007199254740992

Your Node.js code produces a value that is larger than Number.MAX_SAFE_INTEGER which is why the result is approximate instead of accurate.

In PHP, you have integers and floats. However:

The size of integer datatype is not the same across all platforms

PHP x64 uses 8-byte integers* (-9223372036854775808 ... 9223372036854775807)
PHP x86 uses 4-byte integers (-2147483648 ... 2147483647)
PHP seems to use IEEE 754-2008 64-bit floats, same as JavaScript

PHP changes the datatype of variable from integer to float in case of overflow

Your sample program, when run on PHP x64 ends up with $j = int(500000000500000000) which is less than the value of PHP_INT_MAX so conversion to float (and loss of accuracy) does not happen.
The same code, when run on PHP x86 converts the variable to a float value once it becomes greater than PHP_INT_MAX and therefore you will end up with $j = float(5.0000000006710899E+17)**.

* Not on Windows though
** you need to set precision to the maximum value
Answer: javascript Number.MAX_SAFE_INTEGER is 9007199254740991


What's the difference between cards, panels, and tiles?

Question: It seems as if with some of the modern front-end development frameworks there is a blur between the different types of 'container' elements. Whether this is an attempt to abstract the design from implementation or if this is due to there not being any standardization of terminologies I am not sure, but it leads to the fact that in some design frameworks I see the term panels being used but not cards (e.g. Bootstrap 3) while in others the term cards exists but not panels (e.g. Iconic), and perhaps both exist in others?
From a design perspective, it seems that both cards and panels are just containers, and since there's nothing that defines how big a card can get and how small a panel can be, I am wondering whether there's really any difference. From an implementation perspective, it seems that cards should be used for smaller size design elements and are preferred on mobile specific applications, whereas panels are used for a wider range of design elements and are preferred on desktop specific applications.
Is there any evidence/reference/examples that will help to illustrate or highlight the (lack of) differences? For some reason I think cards and tiles are more closely related to each other, and that panels seem to be in a slightly different class/family?
If we take the argument that there are no differences, then it is hard to understand why people associate 'tiles' with Microsoft 'Metro' style home pages, while on Google and Android apps it is 'cards' and for Java and Gnome applications it is 'panels'. Perhaps there are some contextual or implementation differences?
UPDATE: with the release of Bootstrap 4, it seems like cards are basically equivalent to panels (since one component has replaced the other), but with this comes the cost of having to maintain a more flexible container that will make it difficult to implement consistently. According to Bootstrap:

A flexible and extensible content container. It includes options for
  headers and footers, a wide variety of content, contextual background
  colors, and powerful display options.

FURTHER UPDATE: It seems as if Bootstrap 5 and Material.io have adopted the card UI component in the new world of responsive and mobile first/multi-device ecosystem design systems while "tiles" have a very specific meaning in the Microsoft Fluent Design System:

A tile is an app's representation on the Start menu. Every app has a tile. When you create a new Universal Windows Platform (UWP) app project in Microsoft Visual Studio, it includes a default tile that displays your app's name and logo

Panels don't seem to be part of the vocabulary anymore, as least in terms of a UI component, but in the Microsoft and Java world it still represents an abstract concept of organisation layouts of UI components.
Comment: Mostly dimensions. Cards are taller than they are wide, panels are just general content panes, and tiles are generally more square-like.
Comment: While there are likely subtle stylistic or semantic/usage differences, I kind of chalk it up to marketing & companies trying not to get sued by each other. You see the same thing in iOS vs Android where Apple & Google have invented different proprietary vocabulary for 100% identical concepts and functionality...
Answer: The container zoo
The terms card, panel, tile, and others are often used interchangeably, so their definitions not precise and can change from company to company or ecosystem to ecosystem. But, there is a loose vernacular definition for the different containers.
Why does it matter?
Because in practice, naming things is important.  Here is an example of why container names are important (click image to expand):

Now, imagine that some of these container names were swapped.  For example, if card were swapped with panel or toolbar were swapped with tile.  That would lead to some pretty confusing UX discussions.
This thought exercise shows us that although the container terms are all loosely interchangeable, there is a loose convention around what they mean.
It also illustrates why it's important to have different terms for containers (imagine how hard it would be to work with this layout if all of the containers were named 'panel').

Vernacular definitions
Here's a rough definition of vernacular use for the terms.  The illustration above is a decent reference for examples of each container:

Window

Common ecosystem: MS Windows, Mac OS, Ubuntu, and other operating systems
Typically refers to the largest visual container for an application view, and is typically defined by the operating system.

Frame

Common ecosystems: all digital UI's
Typically refers to an outside element or border object which contains a single body of content.
e.g. in HTML, panels are often wrapped inside a frame object which allows the frame to be styled independently from the panel contents.

Panel

Common ecosystems: all digital UI's
Typically refers to a container within a window which contains multiple related elements. For example, a panel might contain a form, a set of information, a data table, etc.
Panels are often used to section window contents to ease visual organization.

Card

Common ecosystems: web, Google Material Design, mobile and table applications
Typically refers to a rectangular container that contains multiple related elements that can appear several times on a page.  For example, news articles, search results, and restaurant listings are all items that may contain multiple elements (image, title, description) and are well suited to card layouts.
Cards are a convenient way to chunk and organize content in grid-layout, to facilitate the presentation of complex/hierarchical information.
Cards (unlike tiles) can and frequently do contain multiple interactive elements.  For example, in the illustration above you have approve/deny buttons, and the user might be able to click on the card title to load more details.
Cards are often manipulable as containers....often users can dismiss, drag, swipe, or rearrange cards.

Tile

Common ecosystems: Microsoft Metro interface
Tiles typically represent small, single-purpose containers.  Tiles may present a single piece of information (e.g. an icon for an application) or a small cluster of related information (e.g. weather temperature and humidity), but rarely present extensive information.
Tiles are often distinguished by their single use....in Microsoft Windows 8+ tiles are clickable and send the user to a single application, view or web page.

Again, these terms are only loosely defined and usage may vary from organization to organization.
But it's still useful to have a loose/informal definition for the reasons outlined above:  distinguishing containers by name is very helpful in practice for UX professionals.
Comment: Great answer -- would love a Bootstrap 4 side note as people seem to be collapsing cards & panels
Answer: There probably isn't objective answer to this question. As you said, if Microsoft, Google or Oracle doesn't seem to agree, how could we?
My view is mostly based on Google Material design on cards and Microsoft Metro tiles. To me a card is close to what Google calls cards. Metro tiles and tiles in general are more homogenous items that may have some actions associated with them. Google uses image gallery as an example for tile usage.
Appearance
Google Material design cards always have constant width within a collection.

Cards have a constant width and variable height. The maximum height is limited to the height of the available space on a platform, but it can temporarily expand (for example, to display a comment field).

In Google Material design cards always have rounded corners while tiles always have square corners.
Microsoft Metro tiles can be of variable size within a collection.

The user can change your tile's size at any time, there is no programmatic way to know which size is currently being used, and only notifications that match its current size are displayed.

Tile and toast visual assets (Windows Runtime apps)
Content
Microsoft Metro tiles:

This topic discusses the concepts and terminology surrounding app tiles, which are the Start screen tiles that represent and launch your app. An app tile is more than a big icon; it has the ability to display a continuously changing set of content that can be used to keep the user aware of events associated with that app (such as new social networking posts, new news headlines, or stock quotes) when the app is not running.

Google Material Design cards:

A card is a piece of paper with unique related data that serves as an entry point to more detailed information.
[...]
Cards are a convenient means of displaying content composed of different elements. They're also well-suited for showcasing elements whose size or supported actions vary, like photos with captions of variable length.

So Metro tiles are bit more restricted when it comes to content. They display only the application logo and possibly some notifications sent by the application. Google cards can support multiple types of content, dynamic or static.
So in a way Google cards are like panels in Java. From Java api docs for panel:

Panel is the simplest container class. A panel provides space in which an application can attach any other component, including other panels.

But unlike panel in Java, Google cards or Metro tiles can't contain other cards or tiles in them.
Actions
Metro tiles have one action, start the application, while Google cards can support multiple supplemental actions in addition to card's primary action:

The primary action in a card is typically the card itself.
Supplemental actions can vary from card to card in a collection, depending on the content type and expected outcome; for example, playing a movie versus opening a book.

Metro applications can have secondary tiles that launch the same application but with distinct content or from distinct state:

A secondary tile allows a user to launch directly from the Start screen to a specific location or subexperience in an app. The app decides which content to offer as a pinning option, but the user chooses whether the secondary tile will be created or deleted.

On panels
I have always thought of panels to be clearly different to cards/tiles. To me panels are containers too but never to be used as a collection in a way cards/tiles are used.
Panels are used as callouts that can contain actions, mainly CTA's. Panels contain much more information than cards/tiles and are almost always bigger in size than cards/tiles. Here is an example panel from Foundation framework, this is what I think when panels are mentioned. These panels can be used to create cards/tiles, though.
Comment: I would be shocked if Microsoft, Google and Oracle agreed on specific design issues :D I think the only thing that they agree on is the UX is important (since Oracle is also rolling out their version of a UX design process)...
Answer: 1. Cards - 2. Tiles - 3. Panels
The short answer is there really is no difference between these terms. Any of these can be any size and I've used the terms interchangeably on various projects.
We should adapt to use whatever terminology the rest of the team is comfortable with because very little can be gained from spending cycles trying to make a distinction between them.
Card layouts are very good at chunking data into bite sized pieces and work nicely in a responsive design.  I prefer the term cards because most people carry around cards in their wallet while tiles and panels are a little less common.
Comment: I do agree that there might not be any actual difference between the terms, although if you go to a Microsoft 'Metro' style home page people will see 'tiles' rather than cards or panels, whereas on an Android or Google web app people might see 'cards', so it stands to reason that there might be some contextual or implementation differences.
Answer: According to Google's Material Specification...Tiles have square corners, no more than 2 actions, cannot be rearranged or dismissed. Cards have rounded corners (like playing cards), have multiple actions, can be rearranged or dismissed
Answer: I'm documenting apps that use what might be termed tiles, cards or panels. From a programming standpoint, maybe the differences are acceptably vague. From a documentation standpoint, I need descriptive handles for reference that make logical sense.
My read on most of the comments I've seen is that the differences don't matter too much. I would suggest that, from a taxonomical perspective in documentation, the differences are critical.
With this in mind:
1) Tile - single-purpose, static image used as a pointer to other content
2) Card - multi-purpose, multi-element container displaying a subset of live data that may contain links to other content or functions
3) Panel - complex document that may, in certain contexts, be the equivalent of a Word doc, and in other contexts, be the equivalent of an ordered layout of a row of data or query results
Maybe there are existing UI terms in database design that I'm unaware of at present. However, forms and query results don't fit in the model I'm laying out here.
Comment: +1 it is always nice to get a fresh perspective on an old question. Thanks for your contribution to UXSE, hope to see some more of your answers :)


Use @JsonIgnore only for prodcution, but in tests it should be there

Question: I have in Kotlin a (data) class like this.
While running the application with active Spring profile live I want to return only name.
But running the application with active Spring profile test, I want version to be shown, so I can test if I got the right version.
data class MyClass(

 val name: String

 @JsonIgnore
 val version: Number

)

Is it possible somehow?
Comment: I don't think it's possible, you can use @JsonProperty and use a different json key to set the version. But your use case is not clear, provide some context why you need it.
Comment: https://uzxmx.github.io/add-or-remove-java-annotation-at-runtime.html etc; it's intrinsically non-trivial if the annotation itself doesn't support some form of run-time introspection. IIRC Jackson *does* provide some form of this via `JacksonAnnotationIntrospector` (or at least did) but it may require modifying the object mapper code.
Comment: @RDK - use-case is: when I return the `MyClass` via REST I don't want the `version` to be shown.  But I need to verify, that it's the right version in my test. (longer story... that's the short version.)
Answer: You can use different Jackson JSON Views for test and prod env.
data class MyClass(
 @JsonView(Views.Prod.class,Views.Test.class)
 val name: String

 @JsonView(Views.Test.class)
 val version: Number

)

And you have to manually take care of serialization/deserialization by passing the view based on environment.
MyClass class = mapper
      .readerWithView(Views.<Required-view>.class)
      .forType(MyClass.class)
      .readValue(json);
String result = mapper
      .writerWithView(Views.<Required-view>.class)
      .writeValueAsString(class);

Answer: You could use @JsonInclude(Include.NON_NULL) to only include it in the response if it's non-null. Then you could just create the object without a version number when you are running in production:
data class MyClass(
    val name: String,

    @JsonInclude(Include.NON_NULL)
    val version: Number? = null
)

// At creation:
val myClass = if (prod) MyClass(name) else MyClass(name, version)

Comment: (Leading to the possible issue that it's not that `version` isn't *used*, just that it's not visible when serializing.)


Water dripping inside furnace

Question: We've got a Carrier Infinity, 2 stage, high efficiency furnace.
I noticed water on the floor just underneath the furnace, and can hear a metallic dripping sound. When I opened it up, I do see water dripping at the very back of the bottom of the furnace.
Is this something I can fix myself? Or do I need to call HVAC repair? And if so, what is (most likely) wrong and how much will it cost me?
I checked, its not the condensate tube that leads to the pump (which has given us issues in the past)
Comment: If "it's not *the* condensate" (one of the 3 lines, or the stupid little drain box thing itself), then you've a problem. "Water on the Floor - If moisture has buildup on the floor at the foundation of your furnace, then the most probable cause is a **cracked heat exchanger**. While leaking water is common in high-efficiency furnaces due to the condensation process, it's rare in standard-efficiency ones." https://andersonair.com/8-symptoms-of-a-cracked-heat-exchanger/ - There's a *working* CO detector in the house, right?
Comment: Do you have a humidifier installed there at the furnace?
Answer: Most likely causes are leak in the condensate or you have high humidity in the room and your house air is condensing on a cold portion causing the drips.  Both should be fixable with some level of DIY skills.

Water dripping inside furnace


Find PDF of $Y=-2\ln X$ given that $X$ is uniform on $(0,1)$

Question: Let $X$ have a uniform distribution with p.d.f. $f(x) = 1$, $x$ is in $(0, 1)$, zero elsewhere.
Find the p.d.f. of $Y = -2 \ln X$.
I don't think this is a very difficult question, I just don't really understand what it is asking or where to start. Any help would be very much appreciated. Thank you!
Update: I did
$$F(y)= P(Y \le y) = P(-2\ln x \le y) = P(\ln x \ge -y/2) = P(x \ge e^{-y/2}).$$
Then $ x=e^{-y/2}$ and $dx/dy =-1/2e^{-y/2}$
Is this all I need to do? Also, I'm not 100% sure why I am using inequalities here- can someone give me a quick explanation?
Comment: You could start with finding the CDF of $Y$. Its derivative is the PDF of $Y$. If you get stuck on that then edit your question to add your efforts.
Comment: Note that $P(x\ge\lambda)=1-\lambda$
Comment: Please I need help wit this. It is known that a particular coin is twice as likely to turn up tails as heads. If the coin is tossed independently, what Is the probability that the 3rd head occurs on the 5th toss?
Answer: you are asked to find the probability distribution of the random variable $Y$ that is related to the random variable $X$ by the relation $Y=-2\ln X$, being $X$ uniform in the interval $[0,1]$. You can solve it considering a change of variable applied to the cumulative function $F(x)$:
$$F(x)=\int_0^x f(x)dx = \int_\infty^y f(y)\Big|\frac{dx}{dy}\Big|^{-1}dy$$
so that
$$f(y) = f(x)\Big|\frac{dx}{dy}\Big|_y$$
and in your situation $x=\exp(-y/2)$, so $\Big|\frac{dx}{dy}\Big|_y = \frac{1}{2}\exp(-y/2)$, so $$f(y)= \frac{1}{2}\exp(-y/2)$$
If you try to integrate $f(y)$ between $\infty$ and $0$ you can verify that it gives you $1$.
Comment: Negative density? On y<0?
Comment: sorry, I forgot the absolute value around the derivative
Comment: at this page https://en.wikipedia.org/wiki/Integration_by_substitution you can find exactly application to probability of change of variables in integration
Comment: Thank you! Is my thought process in the edit correct? And where would the absolute value come in if my solution is valid?
Comment: Sorry, why are you able to use absolute values here? And how did you choose 0 and inf as the range for f(y). Thank you!!
Comment: Integration limits came directly from the input range once you apply on it the coordinate transformation.  You know that y=-2lnx so taking the limit for x going to 0 you have y going to infinity and taking the limit for x going to 1 you have y going to 0.
Answer: Let $f(x)=1_{(0,1)}(x)=F_{X}'(x)$. Note that
$$F_{Y}(y)=P(X\geq e^{-y/2})=1-P(X\leq e^{-y/2})=1-F_{X}(e^{-y/2}).$$
Then the density is
\begin{align}
F_{Y}'(y)&=(1-F_{X}(e^{-y/2}))'\\
&=-F_{X}'(e^{-y/2})\frac{\mathrm{d} }{\mathrm{d} y}(e^{-y/2})\\
&=-1_{(0,1)}(e^{-y/2})\cdot \left ( -\frac{1}{2}e^{-y/2} \right )\\
&=1_{(0,\infty)}(y)\frac{1}{2}e^{-y/2}.
\end{align}
Comment: $$(\ln(X^{-2})\leq y)=(X\geq e^{-y/2})\ne(X\leq e^{2y})$$
Comment: No. See previous comment.
Comment: Have you tried verifying that your answer is in fact a density? (area under the curve equals $1$)?
Answer: $ P(-2logX\le x)=P(logX\ge -x/2)=P(X\ge e^{\frac{-x}{2}})=\int_{e^{\frac{-x}{2}}}^1dt=1-e^{\frac{-x}{2}}$
$F_X(x)=1-e^{\frac{-x}{2}}$
hence $f_X(x)=\frac{1}{2}e^{\frac{-x}{2}}$
which is the pdf of exponential with parameter $\frac{1}{2}$
Answer: It was such a long time ago I did this, but this seems to work too. At least in my computer simulations. Maybe it is just a coincidence it works for this particular function, if that is the case, please show me why.
$Y = -2 \ln(X)$ means that if a sample of X is x, then the corresponding sample of Y is $y = -2\ln(x)$
$y = \ln(x^{-2})$ and then $e^y = x^{-2}$ and $e^{-y/2} = x$. We see that since x is between 0 and 1, y will be between 0 and infinity. Now we just need to normalize, i.e. find $k$ so that $\int_0^\infty ke^{-y/2} dy = 1$ and that is an easy exercise in calculus.
Comment: Is this saying that if $X=g(Y)$ (probably with $g$ monotonous and) with $X$ is uniform on $(0,1)$ then a multiple of $g$ is the PDF of $Y$? **Not so**. Rather, in this setting, assuming that $g$ is strictly decreasing,$$P(Y\leqslant y)=P(X\geqslant g(y))=1-g(y)$$ hence $$f_Y(y)=-g'(y)$$
Comment: Always slightly surprising to see that, roughly two years later, no correction occurred...
Comment: No @Did it was 3 years ago, since 2018-2015 = 3 . I was busy doing other things. I still don't understand your question in comment. Even if I was sure it was wrong I would rather edit with a remark than delete.
Comment: 0. My comment was posted roughly 2 years ago, not 3 years ago (the point of your (wrong) remark being?). 1. What prevented you from asking for explanations, if you needed some, if really you found something unclear in my comment, instead of letting the thing sleep? 2. What exactly is unclear in my comment? Please be specific.
Comment: I don't understand anything about how you interpreted my answer.
Comment: If you are at your most constructive with this pair of comments, indeed nothing to be done here (but you could skip the "interpret" part, there is nothing to interpret here, only a blatantly false post).
Comment: Ah now I remember, interpolating from your last post. I realized it would not be worth my time to try to respond.
Comment: Trying to be insulting, I can see. Not worth more time.
Comment: I meant more like I can't understand your comment and I thought it was unlikely that an explanation would make me more able to understand it. So asking for a clarification would likely waste both of our times.


Installation failing on Latitude D620

Question: I'm trying to install 14.04.3 on a Dell Latitude D620 and am failing.
The procedure I used was to download the file ubuntu-14.04.3-desktop-i386.iso to both my Thinkpad running Debian 8 and, alternatively, to the target Dell, which is running Windows 7. I attempted to make bootable USB drive on the Debian box by running as root the command `dd if=/path/to/ubuntu-14.04.3-desktop-i386.iso of=/dev/sdb'.
This did create a bootable drive that started the Ubuntu installer on the Dell.  There was an Ubuntu splash screen and the color-changing dots, after which the installation failed in two different ways.  The first way was that the screen showed a black-and-white, elongated checker-board pattern and drive activity seemed to cease.  No questions were ever asked by the install program.
Thinking that the ISO was specific to the Thinkpad, I downloaded the same file on the Dell and wrote it to the pendrive using the site and EXE program Universal USB Installer.  This failed in a screen that was poorly rendered in the top half with text "Username", "Password", and "Remember me" and static on the bottom half.
I've searched for any forum posts with the keywords "latitude d620" and "failed install" and all I find are a few posts about wifi driver issues.  There seems to be very little failure of the Ubuntu distribution to install, so I'm asking for help.
Thanks.
Answer: The solution was to simply give the install-from-USB-key more time--a lot of time.  When I left for Mardi Gras the funky display was present.  When I returned several hours later, the laptop was running from the USB key with an Ubuntu desktop displayed, including a link icon titled "Install Ubuntu".  Thanks for the help!

Installation failing on Latitude D620


When we configure log shipping do we have to open a firewall from the destination server to the source server too?

Question: When we configure log shipping do we have to open a firewall from the destination server to the source server too?
Answer: It depends on whether or not the two instances of SQL Server taking part in the log shipped configuration are:

On the same server (Then No)
Behind different firewalls within the same domain/network (Then Yes)
Answer: Log shipping contains four separate job by Sql server Agent.
1.Getting back up in primary server
2.Shipping logs to secondary server
3.Restoring logs in secondary server
4.Monitoring the log shipping process (Optional)
in steps 2 and 3, you need have a shared folder in network if your primary and secondary servers are separate and for this you should give access to secondary server to copy all files from primary server.and The important thing is "databases in a log shipping configuration must use the full recovery model or bulk-logged recovery model".
You must be a sysadmin on each server instance to enable log shipping. The backup and restore directories in your log shipping configuration must follow these requirements.
For the backup job, read/write permissions to the backup directory are required on the following:
The SQL Server service account on the primary server instance.
The proxy account of the backup job. By default, this is the SQL Server Agent account on the primary server instance.
For the copy job, read permissions to the backup directory and write permissions to the copy directory are required by the proxy account of the copy job. By default, this is the SQL Server Agent account on the secondary server instance.
For the restore job, read/write permission to the copy directory are required by the following:
The SQL Server service account on the secondary server instance.
The proxy account of the restore job. By default, this is the SQL Server Agent account on the secondary server instance.


Joining 8 wires into one

Question: I have the cables from 9 bulbs joined into one using a screw terminal temporarily.
What is the best thing to use to do this in a way that's waterproof and suitable for outdoor use. Whatever i use needs to be small and black, and fit on the back of a branch. I know the bulbs are over rated for the dimmer, i guess you can go over the max rating somewhat without that much of a risk of fire.

and this is the decroded piece of crap i am working on in its entirity...
Comment: You are at risk of fire, the dimmer needs to be overrated for the bulbs, not the other way around. You should also check for clearance requirements of the light sockets to be sure they aren't overheating inside the bottles, and the amperage limit of the lamp cord that you're using to be sure that it can run all 8 bulbs after that junction.
Comment: Best way to do this is to wire it in serial.
Comment: Or at least wire some of it in serial, like in pairs, this would half the size of the bus junction.
Answer: You should be looking for something like an IP65 weatherproof junction box.
The designs vary from country to country (as do regulations of course) so it's hard to be more specific.

Ideally you want a bus type connector that has separate connection points for each wire. A single screw-terminal probably can't securely hold so many wires.

Example WAGO 8-way push fit connector and 5-way lever-clamp connector (400V 32A max)

Joining 8 wires into one


Object reference not set to an instance of an object

Question: I am seeing following exception.

System.NullReferenceException: Object reference not set to an instance of an object.
     at System.Web.Util.StringUtil.memcpyimpl(Byte* src, Byte* dest, Int32 len)
     at System.Web.Util.StringUtil.UnsafeStringCopy(String src, Int32 srcIndex, Char[] dest, Int32 destIndex, Int32 len)
     at System.Web.HttpWriter.Write(String s)
     at System.Web.HttpResponse.Write(String s)

I already have following checks on the context to which I am responding.
return !(context == null || context.Response == null ||
    context.Response.OutputStream == null ||
    !context.Response.OutputStream.CanWrite);

Can anyone hint on what could be causing this?
Answer: Are you sure that's where the error is? Looks like the exception started from the Write method of HttpResponse.
Answer: I had this error while working with asynchronous handlers and modules. My problem was that I would use ThreadPool.QueueUserWorkItem from within the HttpHandler's EndProcessRequest method and within the work item callback I would try to use the HttpContext. The trouble is once EndProcessRequest returns back to the caller (but the work item callback has not yet been invoked), the HttpContext object instance is no longer "mine" and ASP.NET has assumed control and is tearing it down. See http://odetocode.com/articles/112.aspx for more info.
Answer: Why even bother with all of those checks?  Why not just write out to the output stream and be done with it?
Also, where in the ASP.NET processing pipeline is this call being made?
Comment: // grab a local copy of the text writer
   TextWriter writer = context.Response.Output;

   // write out the message map
   writer.Write("output data...");
Comment: @unknown (google): I mean, where in the processing pipeline.  Is this an HTTP handler?  An application event handler?
Answer: I think your error is elsewhere, but I'd suggest writing this expression a little more directly without the negatives:
return context != null && context.Response != null &&
    context.Response.OutputStream != null &&
    context.Response.OutputStream.CanWrite;

Answer: This might be happening if you are trying to actually write a null object to the buffer IE:
context.Response.OutputStream.Write(null, 0, 0);

Also You could represent it as...
return (context != null && context.Response != null &&
    context.Response.OutputStream != null &&
    context.Response.OutputStream.CanWrite);