PowerShell form not displaying when screen is locked

Question: I'm using a PowerShell form to prompt users to close down Adobe Reader so it can be upgraded. It's executed via SCCM, so runs in the System context. It works if the user is logged on and the session is active, but if the screen is locked, the form does not display when I unlock the screen, although the script is running.
I originally used $Form.ShowDialog() to display it but saw some other posts that said it wasn't reliable, so I switched to [void][System.Windows.Forms.Application]::Run($Form) but it still doesn't work. Can anyone help me fix this please?
Below is the trimmed-down script with only the code relevant to rendering the form.
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
$Font = New-Object System.Drawing.Font('Segoe UI Light',14,[System.Drawing.FontStyle]::Regular)
$FontBold = New-Object System.Drawing.Font('Segoe UI',13,[System.Drawing.FontStyle]::Bold)

Function EndForm
{
    $Timer.Stop();
    $Timer.Dispose();
    $Label.Dispose();
    $CountdownLabel.Dispose();
    $ProgressBar.Dispose();
    $OKButton.Dispose();
    $Form.Close();
    $Form.Dispose();
}

$OnOKClick =
{
    $MsgBoxInput = [System.Windows.Forms.MessageBox]::Show("Are you sure you want to close and uninstall Adobe Reader now?","Confirm Adobe Reader Removal","YesNo","Warning")
    If ($MsgBoxInput -eq "Yes") {EndForm}
}

$Script:Countdown = 3600
$OKToolTip = "Click OK to close and uninstall Adobe Reader now"
$CountdownSubtitle = "Adobe Reader will close and uninstall in"

$Label = New-Object System.Windows.Forms.Label
$Label.AutoSize = $False
$Label.Height = 120
$Label.Width = 630
$Label.Font = $Font
$Label.BackColor = "White"
$Label.ForeColor = "#4D4C5C"
$Label.Location = New-Object System.Drawing.Size(52,180)
$Label.Text = "Your computer will soon be upgraded to newer versions of Windows 10 and Office 365. In order to succeed, the upgrade process requires that Adobe Reader be closed and uninstalled first. It will not be available for use again until after the upgrade has completed."

$CountdownLabel = New-Object System.Windows.Forms.Label
$CountdownLabel.AutoSize = $False
$CountdownLabel.Height = 40
$CountdownLabel.Width = 530
$CountdownLabel.Font = $Font
$CountdownLabel.BackColor = "White"
$CountdownLabel.ForeColor = "#4D4C5C"
$CountdownLabel.Location = New-Object System.Drawing.Size(120,380)

$ProgressBar = New-Object System.Windows.Forms.ProgressBar
$ProgressBar.Location = New-Object System.Drawing.Size(52,340)
$ProgressBar.Size = New-Object System.Drawing.Size(635,35)
$ProgressBar.Style = "Continuous"
$ProgressBar.Maximum = $Script:Countdown
$ProgressBar.Minimum = 0

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Name = "OK_Button"
$OKButton.Size = New-Object System.Drawing.Size(80,40)
$OKButton.Location = New-Object System.Drawing.Size(330,450)
$OKButton.UseVisualStyleBackColor = $True
$OKButton.Text = "OK"
$OKButton.DataBindings.DefaultDataSourceUpdateMode = 0
$OKButton.Add_Click($OnOKClick)

$ToolTip = New-Object System.Windows.Forms.ToolTip
$ToolTip.IsBalloon = $False
$ToolTip.InitialDelay = 100
$ToolTip.ReshowDelay = 200
$ToolTip.SetToolTip($OKButton,$OKToolTip)

$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Contoso LLC"
$Form.Font = $Font
$Form.Width = 770
$Form.Height = 580
$Form.MinimizeBox = $False
$Form.MaximizeBox = $False
$Form.ControlBox = $False
$Form.ShowIcon = $False
$Form.WindowState = "Normal"
$Form.FormBorderStyle = "Fixed3D"
$Form.ShowInTaskbar = $True
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $True
$Form.Controls.Add($ProgressBar)
$Form.Controls.Add($Label)
$Form.Controls.Add($CountdownLabel)
$Form.Controls.Add($OKButton)

$Timer = New-Object System.Windows.Forms.Timer
$Timer.Interval = 1000
$Timer.Add_Tick(
{
    If ($Script:Countdown -eq 0) {EndForm}

    $ProgressBar.Value  = $Script:Countdown
    $TimeRemain = New-Timespan -Seconds $Script:Countdown
    $HrsRemain = $TimeRemain.Hours
    $MinsRemain = $TimeRemain.Minutes
    $SecsRemain = $TimeRemain.Seconds

    If ($HrsRemain -ge 2) {$HrsText = "$HrsRemain hours"}
    If ($HrsRemain -eq 1) {$HrsText = "$HrsRemain hour"}
    If ($MinsRemain -ge 2) {$MinsText = "$MinsRemain minutes"}
    If ($MinsRemain -eq 1) {$MinsText = "$MinsRemain minute"}
    If ($SecsRemain -ge 2) {$SecsText = "$SecsRemain seconds"}
    If ($SecsRemain -eq 1) {$SecsText = "$SecsRemain second"}

    $CountdownLabel.Text  = "$CountdownSubtitle $HrsText $MinsText $SecsText"

    If ($HrsRemain -ge 1 -And $MinsRemain -eq 0) {$CountdownLabel.Text = "$CountdownSubtitle $HrsText $SecsText"}
    If ($HrsRemain -eq 0) {$CountdownLabel.Text = "$CountdownSubtitle $MinsText $SecsText"}
    If ($HrsRemain -eq 0 -And $MinsRemain -eq 0) {$CountdownLabel.Text = "$CountdownSubtitle $SecsText"}
    $Script:Countdown--
})

$Timer.Start()
[void][System.Windows.Forms.Application]::Run($Form)

Comment: Hi, I never said I wanted the form to display over the top of a lock screen. I'm happy for it to run in the background while the screen is locked. This is just in case the user is away from their desk when the form appears, and they happen to unlock their screen before the countdown ends. In that case, if they are using Adobe Reader, it will stop without warning, which while not the end of the world, could possibly generate helpdesk incidents which is not ideal. I'd rather not argue the logic of why I'm doing it this way, I'd prefer to focus on coming up with a solution. Thanks.
Comment: As for needing to be logged on as the user, that is not correct. This form displays perfectly when deployed via SCCM, which as I said runs in the System context (although there is an option to run it in the user's context - which I have not set).
Comment: OK, deleted the other comments with this clarification, but you are sending a GUI to a currently logged on user. So, it must be in the user's context to see it. PowerShell only runs/outputs to the user context that started it.
Comment: I actually think I may have figured a way 'around' it by considering a locked screen the same as a logged off user, and so just end Adobe Reader in that case. Using the logonui process as the determining factor. I'll test it and see if that helps. Sure, it's not ideal but it could work - at least Adobe Reader won't close before their eyes and they'll wonder what happened.
Comment: Good deal, and if the SCCM approach was a catch22, my next suggestion would have been using the logonui check via a scheduled task and fire the script to pop the UI when the user screen is unlocked. Yep, if they are just reading a PDF< no harm/no foul, but if they are editing on, well, you know. Well, if they are editing PDF's via Word, vs Adobe, still no harm, no foul.
Comment: Yep, thanks for your suggestions anyway. It was good to bounce some ideas off you :)
Comment: Roger that, good luck, take care...
Answer: I have decided to 'work around' this issue by detecting for the presence of the logonui process, which means the screen is locked. In that case, I will just close Adobe Reader anyway.


how to subtract Sub-Report group from main report group in Crystal Report

Question: Sub Report formula
whileprintingrecords;
shared numbervar exp_credit:= Sum ({Exp_credit.amount}, {Exp_credit.date}, "monthly"

Sub Report value
04/2014    1500
05/2014    2000
06/2014    1500
07/2014    1000
08/2014    3000
09/2014    4000
10/2014    3500
11/2014    2800
12/2014    2600
01/2015    2800
02/2015    2800
03/2015    2600

Main Report formula
whileprintingrecords;
shared numbervar exp_debit:= Sum ({Exp_debit.amount}, {Exp_debit.date}, "monthly"

Main Report value
04/2014    3500
05/2014    3500
06/2014    3000
07/2014    4000
08/2014    3900
09/2014    3900
10/2014    4000
11/2014    5000
12/2014    2800
01/2015    3500
02/2015    3700
03/2015    3700

Net formula
whileprintingrecords;
shared numbervar exp_credit;
shared numbervar exp_debit;
shared numbervar net:= (exp_debit-exp_credit);

I am getting net formula value
04/2014    900
05/2014    900
06/2014    400
07/2014   1400
08/2014   1300
09/2014   1300
10/2014   1400
11/2014   2400
12/2014    200
01/2015    900
02/2015   1100
03/2015   1100

I think sub report last value 2600 is deducted for each month and I need each month value separately please help me.
Comment: Where did you place sub report and where did you place main report? In which section?
Comment: Sub report formula @exp_credit is placed in sub report's group header#1 section,  and sub report is placed on main report in report header section. All values are correctly calculated. Sub report last value 2600 is deducted for each month and I need each month value separately. Please help me asap. Thanks in advance
Comment: Please answer my question, waiting your reply please.....
Comment: Your implementation is very confusing....it's better to use arrays...have you tried using those....let me know...again in main report where did you place the main report values
Comment: Why are you using sub report....i dont see any use...from  how many tables are you getting debit and credit values
Comment: Nearly 30 to 40 tables. If apply direct formula I can't get correct result. please suggest if you have any idea.
Comment: In main report I placed main report value in group header#1 and it nearly 30 to 40 tables. If apply direct formula I can't get correct result. please suggest if you have any idea.
Comment: All the stuff you are doing in sub report...do in main report and check the values.....if you can post the report screen shot and tables screen shot will help
Comment: I am unable to use in single report and need sub report then let me know
Comment: I can't attach my screen shots, how do it.
Comment: There is option to attach the image use that....if that is not available then you can post the link that takes to image
Answer: You can try below approach:
Create 2 sub reports for debit and credit and place one by one in header. Store all values of debit in array and all values of credit in array and pass both to main report.
Use below code to store values in array.
Shared StringVar array store;

store:=store+ (Date&"-"&ToText(Value));
//append date and value to retrieve correctly in main report
1

Create same formula in both sub reports with different shared variable
In main report
Shared Stringvar Store //assume debit value
Shared stringvar store1 //assume credit

//now split and convert to number and subtract the values

Tonumber( Split(Store[1],"-")[2]) - Tonumber(Split(Store1[1],"-")[2] )
Take care you subtract similar dates
This will give you difference of first value..in the same way change the numbers in store and store 1 braces to get values for other values
Comment: Siva, thanks for your timely support. If I use this formula am getting error message "the result of a formula cannot be an array". How to solve it. Sorry for this delay reply.
Comment: There are two formulas which formula are you talking about...also i checked there shouldnt be that error appearing
Comment: original formula is --> Shared StringVar array store;
store:=store+ (Date&"-"&ToText(Value));     my applied formula is  --->  Shared StringVar array store;
store:=store+ (GroupName ({Exp_debit.date}, "monthly")&"-"&ToText(Sum ({Exp_debit.amount}, {Exp_debit.date}, "monthly"))); please let me if I have any mistakes
Comment: Have you added 1 after semicolon...add it also editing the solution a bit
Comment: I applied main report formula as ---> Shared Stringvar Store
Shared stringvar store1

Tonumber( Split(Store,[1]"-")[2]) - Tonumber(Split(Store1[1],"-")[2] ) but got error message " The remaining text does not appear to be part of the formula.
Comment: Yes you are right, if i corrected it  --->error message [The ) is missing"] with selection on "-" . How to solve it.
Comment: Edited answer check and let me know
Comment: I got error message while run report it is placed on detail section --> [A subscript must be between 1 and the size of the array] with selection on ( Split(Store[1],"-")[1] ).
Comment: In each value are date and value concatinated or there is only one value
Comment: Post the format of your values in array...how those look like
Comment: Please find below my output format 04/2014    2000
05/2014    1500
06/2014    1500
07/2014      300
08/2014      900
09/2014     -100
10/2014      500
11/2014    2200
12/2014      200
01/2015      700
02/2015      900
03/2015    1100
Comment: - should be between every value that is 04/2014-2000 should be one value in the array like wise all values and in both the sub reports where did you place the concatination formula
Comment: Now it works thank you so much, there is no word to explain my expression, you save my job really you are genius. You are doing great job thank you for your valuable support and I need all 12 or more values should print based on input dates. How is it possible to print all data line by line.
Comment: You can create 12 formulas or you can use line break in single formula and display 12 values...line break can be achieved by `chrW(13)`
Comment: Can you please guide how to use line break in formula.
Comment: Dear Siva, Can you please guide how to use line break in formula. If i do get error message only. waiting your answer please...
Comment: Sure let me know if you get a error message...will post resolution
Comment: My output formula is -->  Shared Stringvar array Store;
Shared stringvar array store1;
Tonumber( Split(Store[1],"-")[2]) - Tonumber(Split(Store1[1],"-")[2] )+
chrw(13)+
Tonumber( Split(Store[2],"-")[3]) - Tonumber(Split(Store1[2],"-")[3] ) if I save it (A number, currency amount, date, time, or date-time is required here with selection on chrw(13).
Comment: I have done it while run report error message--> A subscript must be between 1 and the size of the array.
Comment: Its a generic error....without seeing exact code it is difficult to tell but will tell you how to debug the issue
Comment: Count all the rows in array. Now array starts from 1 now take care in you code in array subscript your value should never exceed the count of array...for eg if total elements in array is 10 then if you subscript is 11 this will throw error
Comment: First formula--> Shared StringVar array store;
store:=store+ (GroupName ({Exp_debit.date}, "monthly")&"-"&ToText(Sum ({Exp_debit.amount}, {Exp_debit.date}, "monthly"))); 1
Second formula--> Shared StringVar array store1;
store1:=store1+ (GroupName ({Exp_credit.date}, "monthly")&"-"&ToText(Sum ({Exp_credit.amount}, {Exp_credit.date}, "monthly"))); 1 output formula --> Shared Stringvar array Store;
Shared stringvar array store1;
Tonumber( Split(Store[1],"-")[2]) - Tonumber(Split(Store1[1],"-")[2])
&chrw(13)&
Tonumber( Split(Store[2],"-")[3]) - Tonumber(Split(Store1[2],"-")[3])
Comment: Tonumber( Split(Store[2],"-")[3]) - Tonumber(Split(Store1[2],"-")[3] this is wrong
Comment: Tonumber( Split(Store[2],"-")[2]) - Tonumber(Split(Store1[2],"-")[2]....this is correct.....store sub script will increase not other
Comment: If i use formula ---> Shared Stringvar array Store;
Shared stringvar array store1;
Tonumber( Split(Store[1],"-")[2]) - Tonumber(Split(Store1[1],"-")[2])
&chrw(13)&
Tonumber( Split(Store[2],"-")[2]) - Tonumber(Split(Store1[2],"-")[2])
&chrw(13)&
Tonumber( Split(Store[3],"-")[3]) - Tonumber(Split(Store1[3],"-")[3])
am getting same error while run the report -->  A subscript must be between 1 and the size of the array
Comment: Dont blindly follow try to understand logic..Tonumber( Split(Store[3],"-")[2]) - Tonumber(Split(Store1[3],"-")[2]...in the same wayTonumber( Split(Store[4],"-")[2]) - Tonumber(Split(Store1[4],"-")[2]
Comment: sorry bro.... now I corrected it. But I get first value of 04/2014 2000 only not getting other line items.
Comment: Yes, values in array is printing horizontally, not printing line by line.
Comment: Hi Siva, thanks for your support it works good.  Please give solution for following, 1) Is it possible to make chart based on the above formula because chart option is disabled for this formula. 2) How to increase more than 12 values of array, please...
Comment: We didnt define any size for the array so array will accomodate any number of values for chart start a new question....comments have become very lenghty..


Find linearization

Question: Consider
$$
u_t=u_{xx}+\cos u-1+\mu
$$
and insert the traveling wave ansatz $u(x,t)=u(z), z=x-ct$. This gives
$$
-cu_z=u_{zz}+\cos u-1+\mu
$$
or, equivalently, the system
\begin{align}\tag{1}
&u_z=v\\
&v_z=-cv-\cos u+1-\mu.
\end{align}
What is the linearization of this system in $u=u_0$?
I think one makes the ansatz $u=u_0+w$ and gets
\begin{align}
&u_z=w_z=v\\
&v_z=-cv-\cos(u_0+w)+1-\mu
\end{align}
Now, how to linearize the term $\cos(u_0+w)$?
Answer: You have $\cos(u_0+w)=\cos(u_0) \cos(w)-\sin(u_0) \sin(w)$ so:
$$\cos(u_0+w) = \cos(u_0) - \sin(u_0) w +O(|w|^2)$$
(Or even simpler $\cos$ is $C^1$ and $(\cos(u_0))'=-\sin(u_0)$).
Comment: The equilibria of the system (1) are $(0,u_0)$ with $\cos(u_0)=1-\mu$. Am I right that the linearization in the equilibria $(0,u_0)$ is given by $$\frac{d}{dz}\begin{pmatrix}w\\v\end{pmatrix}=\begin{pmatrix}0 & 1\\\sin(u_0) & -c\end{pmatrix}\begin{pmatrix}w\\v\end{pmatrix}$$?
Comment: It seems correct to me.

Find linearization


C++ - Checking all member variables for condition

Question: Simplified example of my situation:
I have a class with 3 member variables, all integers, e.g.
class Foo
{
   public:
      int A;
      int B;
      int C;
};

I want to have a function that returns a Boolean true if all of the member variables are 0 and false otherwise.
Easy enough, could be accomplished with this member function:
bool all_zero()
{
   return (A == 0 && B == 0 && C == 0);
}

I can do this if necessary.
However, this is not ideal in my situation because:

I am not the only person who manages this software.
Occasionally, new member variables are added to this class (e.g. int D).
This is a very large C++ project, and we often don't add new member variables to the class directly by manually modifying the code - instead, we have custom tools that automatically modify the code for us. Therefore, it is pretty rare that we make manual modification to this class.
Additionally, since this project is so large, the all_zero function above could easily be overlooked (i.e. someone could forget, or be completely unaware to add && D == 0 to the function if a new member variable is added).

All that said... here is my question:
Is there any way to modify this all_zero function such that it always checks all member variables (of int type), without needing to tell the function to explicitly check each one? By the way, I am also OK if this functionality is accomplished outside of the class (rather than inside the class with a member function).
I am hoping that I don't have to resort to this, but worst case scenario for me here is that I can stick with this original all_zero idea above and just proceduralize the adding of a new member variable to this class, basically telling anyone who adds a member variable to the class must also manually modify this all_zero function.
Comment: If you use an automatic tool to generate the class, why can't it generate the function as well? Seems like a self imposed hardship
Comment: Guessing where @Bathsheba is going, can't you make an array instead of having distinct variables? Because then you could easily use e.g. [`std::all_of`](http://en.cppreference.com/w/cpp/algorithm/all_any_none_of) or other [standard algorithm functions](http://en.cppreference.com/w/cpp/algorithm).
Comment: Are all the member variables `int` types?
Comment: The only thing that comes to my mind is that it would be possible if the members were in the form of an array.
Comment: @StoryTeller I cannot modify the tool because it was provided to us by a vendor, and they did not provide us with the source code.
Comment: You can see here: https://stackoverflow.com/questions/6386404/find-the-list-of-member-variables-of-a-class-and-their-types which explains it's not possible
Comment: So? Check to see if the tool can be configured, or ask the vendor for an enhancement. It's not unheard of.
Comment: @Bathsheba No. The classes are very large, and contain many types.
Comment: [magic_get](https://github.com/apolukhin/magic_get) might help as viewing your struct as `tuple`. Then it is normal meta prog.
Comment: "This is a very large C++ project, and we often don't add new member variables to the class directly by manually modifying the code - instead, we have custom tools that automatically modify the code for us. Therefore, it is pretty rare that we make manual modification to this class." Can you modify the custom tool to generate the function automatically as well?
Comment: @AlessandroTeruzzi No, I don't have the source code to modify the tool. The contractor who provided us with the tool, the contract has expired so we'd have to pay them to modify it, which is not worth doing solely to solve this problem.
Answer: bool all_zero() const
{
   Foo f{}, g{};
   g = *this;
   return ::memcmp(&f, &g, sizeof(f));
}

is one way, assuming your class is trivially copyable. The {} will zero-initialise the members including any padding bits, and the compiler generated assignment operator will copy the members for comparison.
Quite possibly we will soon get a compiler-generated == which would probably be better. See https://isocpp.org/blog/2016/02/a-bit-of-background-for-the-default-comparison-proposal-bjarne-stroustrup.
Finally, if the comparison method needs to be outside the class, then consider
bool all_zero(const Foo& f)
{
    Foo g{}, h{};
    h = f;
    return ::memcmp(&g, &h, sizeof(f));
}

Comment: I'm trying to think if padding at the end is likely or not. If there's padding, its content is unspecified. It may end up giving false negatives.
Comment: I hate to be *that guy*, but it's backwards. [C++ accounts for padding](https://timsong-cpp.github.io/cppwp/n4659/dcl.init#6.2). While [C... not so much](http://port70.net/~nsz/c/c11/n1570.html#note310).
Comment: @StoryTeller: Dunnit.
Comment: @ImaginaryHuman072889: Dunnit. Also got round the padding issue.
Comment: @StoryTeller: You're the expert here. I'm wondering if the padding has to be initialised with a default constructor in the same way as it is with `{}`.
Comment: I'm checking, at the moment. I don't remember if zero-initialization applies to padding too
Comment: @StoryTeller: I have a *feeling* (and my feelings normally mean I'm wrong) that it the behaviour is better defined in C than C++.
Comment: But again, this hinges on `this` being value->zero initialized. It's a neat way to leverage C++, but I'd add a cautionary note.
Comment: @Bathsheba Thanks, not sure if this will work or not. I will test and let you know.
Comment: @ImaginaryHuman072889: If std::is_trivially_copyable is true for your type, and you do all the initialisations as I advise, it will work.
Comment: @Bathsheba Also, is it possible to have this functionality *outside* of the class? This would actually be ideal in this situation, because then I wouldn't have to interfere at all with the tool that automatically generates this class.
Comment: @ImaginaryHuman072889: So long as you ensure that all objects are zero-intiialised then that would be fine. The issue is that you need to initialise the padding bits for true portability.
Comment: @Bathsheba Thanks, can you please edit you post to show what the code would look like outside of the class?
Comment: @StoryTeller: Got round the padding issue. I believe my solution is now truly portable, if a little *wild*, if you get my meaning. Thanks for your help.
Comment: @Bathsheba Any reason you avoided `static const Foo g{};
    return f == g;` as your impl?
Comment: @UKMonkey: Are you from the future? We don't have a compiler generated `==` yet.
Comment: @Bathsheba sorry - good point; I'd missed that the auto-generated code didn't include an `==` for some reason.  But thanks - I'll work with C++21 anyway if you don't mind :)
Comment: I don't think this really solve the OP problem, two of his requirements: "Is there any way to modify this all_zero function such that it always checks all member variables (of int type)?" At the questions are all int types he replied: " No. The classes are very large, and contain many types." So, there is no guarantee for memcmp to work reliably even if the class is trivially copyable. For example: struct A { int a; char b; } b can be any value and it should not have any effect in the result of all_zero() function
Comment: @AlessandroTeruzzi huh? Why wouldn't the value of `b` affect `memcmp`? It most certainly does.
Comment: Unless I am misunderstanding the OP, it wants to compare only the int data members. So, for example A f; f.a = 0; f.b = 'B'; and A g; g.a = 0; g.b='C' they should both return true to all_zero(). I don't see how memcmp can fit the bill
Comment: @AlessandroTeruzzi that's not what I got from the question. "I want to have a function that returns a Boolean true if **all of the member variables** are 0 and false otherwise."  The `int` variables are just an example.
Comment: @bolov your interpretation might be the correct one, I guess all_zero is not are really good name for that kind of function then
Comment: @AlessandroTeruzzi The question clarifies at the bottom that I want to check only all members *of int type*. I assumed this wasn't an issue because Bathsheba specifically asked if there were other types other than `int` before posting this answer.
Comment: I find that relying on value-initialization to initialize the padding bits is quite obscure. Combining `memcmp` with `memset`, on the other hand, is something almost any C/C++ programmer should understand. You might also want to add the obligatory warning regarding floating-point shenanigans, i.e. [negative zero](https://en.wikipedia.org/wiki/Negative_zero). Note that `-0.0 == 0.0`, i.e. this is not an orthogonal issue.
Comment: @bolov it seems that the OP wants to disregard any data member that is not an int in the function. So, memcmp cannot be used here


How can i take a thread dump exactly when many outofmemory error occur?

Question: I had run a jvm process, one day it encountered the outofmemory exception. In the log I have found many outofmemory errors::

-bash-3.00# grep OutOfMemoryError AdminServer.log00399
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap space
####<2013-6-28 05:09:27 pm CST> <Error> <Server> <kfmsapp2> <AdminServer> <DynamicListenThread[Default[3]]> <<WLS Kernel>> <> <>

<1372410567863>

It also generated a heapdump file, I found it was a big object from a thread after analysing by using mat, I just know it's a hibernate common object org.hibernate.engine.PersistenceContext, but I don't know where it come from.
I want to write a small program, and it will generate a threaddump file automatically when the outofmemory error occured.
My question is: what time of the program executing is best to take a thread dump exactly? Is it on the first outofmemory error appear in the log file?
Answer: I'd probably try to use an UncaughtExceptionHandler:
public static void main(String[] args) {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
            // print it ...
        }
    });

            // ... continuing
}

For printing, see here or here.


Does a Skylight need to be installed with the dedicated flashing system

Question: I'm looking at this product

for a garden office roof but I could not find the corresponding flashing kit for the roof material I was planning to use, which is this:

The closest type of flashing I could find was this

but I'm not sure if it would be suitable for the chosen roofing material?
Comment: I just searched for a kit and it looks like the one you have picture is by Velux, and it illustrates it on the same roof you plan to use. Perhaps that is the way to go.
Comment: Is the roofing already installed and the skylight not installed yet? Or vice versa?
Comment: It has not been built yet.
Comment: You will need to look to the roof supplier for that material, IF they offer it.
Comment: @Jack I have concluded the same. I looked for Fakro flashings for my planned roof and they just don't exist. I'm going to go with Velux and change the roof style to the one in the picture (with the flashing).
Answer: I just searched for a kit and it looks like the one you have picture is by Velux, and it illustrates it on the same roof you plan to use. Perhaps that is the way to go.
It may tell you this in the instructions for the flashing install, but on the piece below the skylight, I would flatten out the standing ribs just a bit to help ease the membrane over the top of the lower piece. That way no sharp corner could pierce the membrane.


c# fixed arrays - which structure is fastest to read from?

Question: I have some large arrays of 2D data elements. A and B aren't equally sized dimensions.
A) is between 5 and 20
B) is between 1000 and 100000
The initialization time is no problem as its only going to be lookup tables for realtime application, so performance on indexing elements from knowing value A and B is crucial. The data stored is currently a single byte-value.
I was thinking around these solutions:
byte[A][B] datalist1a;

or
byte[B][A] datalist2a;

or
byte[A,B] datalist1b;

or
byte[B,A] datalist2b;

or perhaps loosing the multidimension as I know the fixed size and just multiply the to values before looking it up.
byte[A*Bmax + B] datalist3;

or
byte[B*Amax + A] datalist4;

What I need is to know, what datatype/array structure to use for most efficient lookup in C# when I have this setup.
Edit 1
the first two solutions were supposed to be multidimensional, not multi arrays.
Edit 2
All data in the smallest dimension is read at each lookup, but the large one is only used for indexing once at a time.
So its something like - Grab all A's from sample B.
Comment: There is no single correct answer to this question in its current form. As @George mentions, it depends on how you access the array. Are you doing random access? sequential? If sequential, in which direction (ie. A-dimension or B-dimension) primarily? The best way to handle this is to write different versions of the code and profile it, and that's in fact the correct answer to any such "what is fastest" type questions anyway.
Comment: Probably depends how you're stepping through the array when looking up values.
Comment: Have you also considered a two dimensional array: `byte[A,B]`? (The form `byte[A][B]` is an array of arrays.)
Comment: The first three rules of performance optimizations: Measure, measure, measure. Set up some kind of test environment that matches the production environment, and test them.
Comment: @Richard Using multidimensional arrays in C# has a significant impact on its performance, they are implemented differently:http://www.codeproject.com/KB/dotnet/arrays.aspx
Comment: @Richard According to Jeffrey Richter's book, CLR via C#, 3rd edition, page 398 (for those who have the book), 2+-dimensional arrays are actually slower in many cases than jagged (`x[...][...]`) arrays, because the compiler can in many cases optimize the usage of single-dimension arrays much better than 2d-arrays. So again, don't fall into the trap of assumptions, always measure measure measure.
Comment: @Richard I didn't imply that you did :) just information I had :) For all we know, 2d-array is faster *in this case*
Comment: I was hoping someone knew this already from testing what kinda array lookup C# compiled into. It was merly an architectual question from my point of view, as most CPUs will handle this quickly anyway. But doing this millions of times each day might in the end save some CPU cycles.
Comment: @Richard - ups!... my fault, thats what I meant. Going to edit the question. Thanks!
Comment: @Lasse V. Karlsen: I dont hope you call me lazy, but can you recommend a structure from my last edit, without messure?
Comment: Lets say I use the [][] syntax, should the large dimension (B) be the first or the last?
Comment: As I said before, *we* can't give you that answer because it depends on *your* program and how *it* accesses the array. You *really* need to measure this if you care this deep about your program performance. If you really want my advice, it would be to just leave it for now, come back to it if you feel it's a bottleneck later. One thing about measuring for performance is that in 9 out of 10 cases (in my experience), bottlenecks crop up where I least expect it, so even if you manage to optimize this code, it is likely that this won't be your primary bottleneck.
Comment: Sorry for being so ignorant, but back in old days, there was a significant difference between how I index memory from C/C++ like when pulling data from a VGA-memory on PC. I thought the same rules applied on C#. I use the large B for index/lookup and pull ALL data from A each time.
Comment: @Lasse: Note I *didn't* recommend them. It seems odd that they were not referenced.
Comment: There probably is a difference, but the question is - is it big enough to worry about? If you have another performance problem in your program which overshadows this one by an order of magnitude, you should fix that one first. And @Lasse V. Karlsen is right - the fastest approach will depend on the manner you access your array elements. So, please, profile first. Otherwise any answer we give here will be most likely wrong.
Comment: okay, I will stop here. we dont have the performance problem yet. its all on drawing board so far, so we just try to avoid structural stupidty from the beginning and this one spawned a discussion.
Comment: I have tried (lower is better): one-D=498; two-D=958; jagged=526; unsafe=512. I was wrong about the jagged, because it seems that making an explicit multiplication is better. However, once again the unsafe way does not worth the value.
Answer: I'd bet on the jagged arrays, unless the Amax or Bmax are a power of 2.
I'd say so, because a jagged array needs two indexed accesses, thus very fast. The other forms implies a multiplication, either implicit or explicit. Unless that multiplication is a simple shift, I think could be a bit heavier than a couple of indexed accesses.
EDIT: Here is the small program used for the test:
class Program
{
    private static int A = 10;
    private static int B = 100;

    private static byte[] _linear;
    private static byte[,] _square;
    private static byte[][] _jagged;

    unsafe static void Main(string[] args)
    {
        //init arrays
        _linear = new byte[A * B];
        _square = new byte[A, B];
        _jagged = new byte[A][];
        for (int i = 0; i < A; i++)
            _jagged[i] = new byte[B];

        //set-up the params
        var sw = new Stopwatch();
        byte b;
        const int N = 100000;

        //one-dim array (buffer)
        sw.Restart();
        for (int i = 0; i < N; i++)
        {
            for (int r = 0; r < A; r++)
            {
                for (int c = 0; c < B; c++)
                {
                    b = _linear[r * B + c];
                }
            }
        }
        sw.Stop();
        Console.WriteLine("linear={0}", sw.ElapsedMilliseconds);

        //two-dim array
        sw.Restart();
        for (int i = 0; i < N; i++)
        {
            for (int r = 0; r < A; r++)
            {
                for (int c = 0; c < B; c++)
                {
                    b = _square[r, c];
                }
            }
        }
        sw.Stop();
        Console.WriteLine("square={0}", sw.ElapsedMilliseconds);

        //jagged array
        sw.Restart();
        for (int i = 0; i < N; i++)
        {
            for (int r = 0; r < A; r++)
            {
                for (int c = 0; c < B; c++)
                {
                    b = _jagged[r][c];
                }
            }
        }
        sw.Stop();
        Console.WriteLine("jagged={0}", sw.ElapsedMilliseconds);

        //one-dim array within unsafe access (and context)
        sw.Restart();
        for (int i = 0; i < N; i++)
        {
            for (int r = 0; r < A; r++)
            {
                fixed (byte* offset = &_linear[r * B])
                {
                    for (int c = 0; c < B; c++)
                    {
                        b = *(byte*)(offset + c);
                    }
                }
            }
        }
        sw.Stop();
        Console.WriteLine("unsafe={0}", sw.ElapsedMilliseconds);

        Console.Write("Press any key...");
        Console.ReadKey();
        Console.WriteLine();
    }
}

Comment: @BerggreenDK remember to cache the current line in the first loop to reduce indexer operations, if iterating in order. E.g. `for(...) { var line = arr[i]; for (...) { var elem = line[j]; } }`
Comment: Although Jagged arrays are good for maintainable data structures it isn't as simple as an indexer operation - remember the CLR has to do null checking, bounds checking, etc. This adds a significant amount of overhead to each indexer you do. Algebraic arrays would be faster because of this (but less maintainable).
Comment: FYI, I've added the source of the program used for the test.
Comment: @MarioVernari: Oh no, it's not the code you posted which is wrong. I was referring to your comment (no.5 from the top) "Anyway, it does not matter which array is the first: it's an access that costs in equal manner." which is obviously wrong, because it does matter which array is first :)
Comment: Amax or Bmax is just the length of the two dimensions, and they will not be the power of 2 very often (only if we are lucky from time to time). So okay, jagged it is.
Comment: which one would you put first then? does it matter? large before small or oppersite? we need ALL data from the small in each look up. Consider this: we might have 100 of these tables and using the same lookup index inside them all (lets say lookup=2345), then we pull 20 values from byte[lookup=2345][20:values] or byte[20:values][lookup=2345] ???
Comment: I consider the question as informative, because I usually prefer to sacrifice the performance than the readiness/form.
Anyway, it does not matter which array is the first: it's an access that costs in equal manner. I also agree with Jonathan (and others) about the fuzziness of the jagged arrays (better: array in general).
Comment: @Mario Vernari: thanks for your testresults. Whats the "unsafe" from your results?
Comment: AWESOME WORK !!! great!!! I'll bet this will save a LOT of people some time next time they need to make a choice! Much appriciated!
Comment: entered my own values for the test and got these: linear:81531, square:156547, jagged:87160 and unsafe:81014 ... so the loss from using jagged is rather minimal and a great option if you dont want to write ugly code. Using the unsafe is not what we are looking for, so the fastest would be linear.
Comment: @MarioVernari: Reread the question. In this scenario, the array is a lookup table which maps a lot of keys to a chunk of values and the chunk is always read whole. So unless all the data fits into a single memory page, it _does_ make a difference which way around you access the data. Here's a gist to illustrate: https://gist.github.com/diab0l/042e47d1902a897263ec
Comment: @M.Stramm I agree, but what's the point? In any case of huge blocks of data you can have the paging problem. I mean the question was about the "generic" approach, so I can't rely on any optimization.
Comment: @MarioVernari: The point was that if you layout your data sequentially, you may still run into the paging problem. If you spread it across pages, you will force the problem to manifest itself. And that applies "generically". It is not an optimization you rely on, it's more of a mistake you shouldn't make.
Comment: @M.Stramm:Again, I don't see any difference between my snippet and your considerations on the gist, expect for the optimization. Of course, here's not because the comparison wouldn't be reliable. Where is my mistake?
Answer:
Multidimensional ([,]) arrays are nearly always the slowest, unless under a heavy random access scenario. In theory they shouldn't be, but it's one of the CLR oddities.
Jagged arrays ([][]) are nearly always faster than multidimensional arrays; even under random access scenarios. These have a memory overhead.
Singledimensional ([]) and algebraic arrays ([y * stride + x]) are the fastest for random access in safe code.
Unsafe code is, normally, fastest in all cases (provided you don't pin it repeatedly).
Comment: You skip bounds checking; which is the slowest part of arrays.
Comment: That's right, but the unsafe way requires the array to be pinned with the "fixed" statement, which is slow. Also, well, it depends on how you want to have access to the array: bitmap access (so fixed once), or random access (fixed every time).
Comment: "Unsafe code is, obviously, the fastest in all cases". I don't think so. Try yourself, and you'll be surprised (C# speaking).
Comment: @Mario - Fixed doesn't actually pin the memory, it uses a clever trick to avoid it.  In spite of the documentation.  No bounds checking either, it is fast and dangerous with perf like C arrays.
Answer: The only useful answer to "which X is faster" (for all X) is: you have to do performance tests that reflect your requirements.
And remember to consider, in general*:

Maintenance of the program. If this is not a quick one off, a slightly slower but maintainable program is a better option in most cases.
Micro benchmarks can be deceptive. For instance a tight loop just reading from a collection might be optimised away in ways not possible when real work is being done.

Additionally consider that you need to look at the complete program to decide where to optimise. Speeding up a loop by 1% might be useful for that loop, but if it is only 1% of the complete runtime then it is not making much differences.

* But all rules have exceptions.
Comment: This is good general advice, but doesn't answer the question which is quite specific about optimizing performance of accesses to 2-dimensional chunks of data in C#, which has quite a specific answer.
Answer: On most modern computers, arithmetic operations are far, far faster than memory lookups.
If you fetch a memory address that isn't in a cache or where the out of order execution pulls from the wrong place you are looking at 10-100 clocks, a pipelined multiply is 1 clock.
The other issue is cache locality.
byte[BAmax + A] datalist4;  seems like the best bet if you are accessing with A's varying sequentially.
When datalist4[bAmax + a] is accessed, the computer will usually start pulling in datalist4[bAmax + a+ 64/sizeof(dataListType)], ... +128 ... etc, or if it detects a reverse iteration, datalist4[bAmax + a - 64/sizeof(dataListType)]
Hope that helps!
Answer: May be best way for u will be use HashMap
Dictionary?
Comment: too complex a datastructure, considering our need of simple bytearrays and an index.


Reinstall Ubuntu on other disk with Windows dual boot

Question: I am new to Linux and I have just installed a dual boot with Ubuntu 20.04 and Windows.
Unfortunately Ubuntu was installed on the hard disk and not on my SSD.
Can I just boot with the Live-USB and remove the Ubuntu partitions with Gparted?
Next, I would simply install Ubuntu on the SSD.
Do I still need to repair the Windows boot loader (which you would have to do if Ubuntu were removed)?
Are there other things I should consider?
Comment: Does this answer your question? [Removing an Ubuntu installation](https://askubuntu.com/questions/277838/removing-an-ubuntu-installation) and [How do I install Ubuntu alongside a pre-installed Windows with UEFI?](https://askubuntu.com/q/221835/)
Comment: You can use GParted to copy the Ubuntu partition from the HDD and paste it on free space of the SSD, **Use Windows Disk Manager** to create the free space on the SSD, not GParted. You will need to edit grub.cfg and fstab with the new Ubuntu's partition UUID. and depending on the location of the bootloader reinstall GRUB.
Answer: I had the same issue, first, if you can boot into both OS's then you are good and at this point, you just want to have Ubuntu on the drive you originally wanted, right? Do you have the unwanted Ubuntu on its own partition that is safe to delete? If so, that is what I did and I installed Ubuntu on a its own partition completely separate from anything windows and when I wanted to remove it, I booted into the BIOS so I could boot into Windows directly from the boot options and then just deleted the ubuntu partitions, BUT THIS WILL REMOVE GRUB BOOTLOADER, so you will need to install Ubuntu right after or if you want to use Windows you will need to switch what to boot from in the BIOS so Windows will work when you boot the computer. If it is easier for you, GParted is better, but make sure to only delete the Linux partitions so make sure to double-check what you are about to delete by the file system type as Windows will never use ext as its file system type. Then I would install Ubuntu right after so you can get grub back, have ubuntu on the drive you want and be able to easily boot into either OS when turning on the computer. Please post if you have any questions before you start as I would rather you have a clear picture of what to do vs you losing data you needed by accident. On a personal note, I love GParted and use it often so you can use Windows to modify the partitions or GParted, but GParted is a better tool. Just make sure to be 100000% sure the drive you are about to delete, wipe, or nuke is what you want gone forever.


Count how many times while loop was used

Question: so i build a simple while loop to check how many blows needed to cool down the tea. One blow reduces the tea temperature by 10C. The problem is that I have no idea how to go forward with this. I know its something simple but just started python. Thanks
tea = 100 #temperature of tea to start with
while tea >= 70:
    print (str(tea) + " C")
    tea = tea - 10
print (" It's ready now ... ")

Comment: Why not start a counter at 0 before the loop and increment it by 1 for each "blow"?
Answer: tea = 100 #temperature of tea to start with
count = 0
while tea >= 70:
   print (str(tea) + " C")
   tea = tea - 10
   count += 1
print (" It's ready now ... ")

Answer: One way to do this would be to have a variable outside the loop, and increment it in each iteration. So:
tea = 100
count = 0
while tea >= 70:
    print(str(tea) + " C")
    tea -= 10   # shorthand for tea = tea-10
    count += 1
print("It's ready now")
print("It took {} blows to cool down".format(count))

Comment: oh thanks, i tried to use the count function but I displayed in wrong way. Thank you so much
Comment: and what is the meaning of {} in the last print ? does it mean it will display whatever is in the .format(count) ?
Comment: yes, you're right! In this case count was the argument, it'll format inside {} whatever you pass to the format() method
Comment: ohh I get it . Thanks again :)
Answer: Why do you need a loop?
def steps(current, target, step):
    return int(math.floor((current - target) / float(step)) + 1)

print("It took {} steps!".format(steps(100, 70, 10)))

Comment: @user3077730 Great :) Welcome!


Uncaught TypeError: this.state.imgData.map is not a function

Question: Here id my Data file for image
imageData = [
        {
            id: 1,
            imgName: "Apple",
            imgFile: "apple.jpg",
            imgQuestion: "Which fruit is this",
            imgAnswer: "This is an Apple"
        },
        {
            id: 2,
            imgName: "Orange",
            imgFile: "orange.jpg",
            imgQuestion: "What is the color of Orange",
            imgAnswer: "The color of orange os orange"
        },
        {
            id: 3,
            imgName: "Mango",
            imgFile: "mango.jpg",
            imgQuestion: "Do you like Mangoes",
            imgAnswer: "Yes I like Mangoes"
        }
    ]

I don't know why my code is showing error message in browser console:

Uncaught TypeError: this.state.imgData.map is not a function

import React, { Component } from 'react';

import Jokes from './../components/Jokes';
import Data from './../data';

export default class Index extends Component {

    constructor() {
        super()
        this.state = {
            imgData: Data
        }
    }

    render() {
        const imgDataItem = this.state.imgData.map(item => {
            <Jokes  data={{key: this.item.id}}
                    data={{
                        img: this.item.imgName,
                        imgFileName: this.item.imgFile,
                        question: this.item.imgQuestion,
                        answer: this.item.imgAnswer
                    }}
            />
        })

        return (
            {imgDataItem}
        )
    }
}

I am new to react and please get me the solution where I am getting wrong
Comment: map can only be applied to array... imgData is not an array
Comment: please show what is in `'./../data'`
Comment: i have send the `./../data` file.. please solve my problem..
Comment: What are you exporting? Do console.log(Data) in constructer to see if you are getting whats you expect i.e. an array
Comment: ok ill try to do so.
Answer: Try destructuring with assignment by default value for imgData
 render() {
    const {imgData = []} = this.state;
    const imgDataItem = imgData.map(item => {
        <Jokes  data={{key: this.item.id}}
                data={{
                    img: this.item.imgName,
                    imgFileName: this.item.imgFile,
                    question: this.item.imgQuestion,
                    answer: this.item.imgAnswer
                }}
        />
    })

    return (
        {imgDataItem}
    )
}


Mysql - update + insert json

Question: I got a table that has a JSON field. The default value for the field is "NULL" - now I'd like to update a single field of the JSON data.
   | ----------------- |
   | [int]  |   [JSON] |
   |  xy    |   ipdata |
   | ----------------- |

So the field could be something like this:
{ ip: "22.214.171.124", "data": "test", "name": "Peterson", "full_name": "Hanson Peterson" }

So I'd like to update the IP.
update table set ipdata = JSON_SET(ipdata, "$.ip", "newIp") where xy = 2;

But what happens if the field is NULL? The query above does not seems to "create" a new JSON with just the field IP. It just does nothing.

How can I tell mySql to insert the {"ip": "newIp"} if the field is empty and otherwise just update the ip json key?
Answer: You can use Case .. When to handle Null. When the field is null, you can instead create Json_object() and set it:
UPDATE table
SET ipdata = CASE WHEN ipdata IS NULL THEN JSON_OBJECT("ip", "newIp")
                  ELSE JSON_SET(ipdata, "$.ip", "newIp")
             END
WHERE xy = "xy";

Mysql - update + insert json


Can the Gauss-Bonnet theorem be proven from Stokes's theorem?

Question: In a comment to this question, John Ma claims that the Gauss-Bonnet theorem can be proven from Stokes's theorem, but does not explain how.
For two dimensions, Stokes's theorem says that for any smooth 2-manifold (i.e. surface) $S$ and one-form $\omega$ defined on $S$,
$$\oint_{\partial S} \omega = \iint_S d\omega.$$
I could vaguely imagine coming up with some kind of one-form $\omega$ that depends on the metric, such that (a) along the boundary curve $\omega$ maps the boundary tangent vector to the geodesic curvature and (b) in the surface interior $\ast d\omega$ equals the Gaussian curvature. (In more concrete vector-field language, this corresponds to a vector field $\vec{\omega}$ defined over the surface such that (a) on the boundary curve $\vec{\omega} \cdot d\vec{l}$ equals the curve's geodesic curvature and (b) in the surface interior $(\vec{\nabla} \times \vec{\omega}) \cdot d\vec{S}$ equals the Gaussian curvature.) This would reproduce part of the Gauss-Bonnet formula, but how could you possibly get out the Euler characteristic term?
Comment: The proof given by Chern in "A simple intrinsic proof of the Gauss-Bonnet formula for closed Riemannian manifolds" is based on Stokes' theorem.
Comment: For the 2-dimensional G-B theorem, you can see (most of) the argument on p. 105 of [my differential geometry text](https://math.franklin.uga.edu/sites/default/files/inline-files/ShifrinDiffGeo.pdf). The local-to-global argument to get to $\chi(M)$ is the standard triangulation argument. If you recognize $\chi$ as the sum of the indices of a vector field, you can turn the proof into a direct argument, taking out little balls $B$ around each zero and seeing that $\int_{\partial B} \bar\omega_{12}$ gives the index of the vector field.
Answer: See Differential Forms and Applications (by Manfredo P. Do Carmo ) chapter 6 section 1. The proof of Gauss-Bonnet's Theorem presented by Do Carmo in his text is essentially the same as given by S.S. Chern and use the Stokes' theorem. The original proof of S.S. Chern is found here.
Comment: Could you gist it for me? I don't have access to the book or the paper.
Comment: @tparker I only have access to the Portuguese version of the Do Carmo book I bought recently.
Comment: For paper see the link. https://scholar.google.com.br/scholar?hl=pt-BR&as_sdt=0%2C5&q=A+Simple+Intrinsic+Proof+of+the+Gauss-Bonnet+Formula+for+Closed+Riemannian+Manifolds&btnG=
Comment: I'm afraid this proof is too advanced for me to understand :(


How to get datetime data in database?

Question: I'm trying to get date from SQL Server to C#. I couldn't do that.
I can't get the date. I just need the date information like MM/DD/YY, not like 06/26/2009 00:00:00:000, I don't need the time information.
When I try this command text in SQL Server, it works.
When I try this code, at the
date = drr["Tarih"].toString();

part, I get an error

System.IndexOutOfRangeException

Code:
SqlConnection con;
SqlCommand cmd;
string date;

public string getDate(int noo, int idd)
{
        int no = noo;
        int id = idd;

        con = new SqlConnection(@"Data Source=AHMET\SQLEXPRESS; Initial Catalog=yoklama; Integrated Security=True");

        cmd = new SqlCommand();

        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "Select Max(Tarih) from Yoklama where Ogrenci_NO = '" + no + "' and Ders_ID = '" + id + "' ";

        try
        {
            con.Open();

            SqlDataReader drr = cmd.ExecuteReader();

            while(dr.Read()) {
                date = drr["Tarih"].ToString();
            }
        }
        catch (SqlException)
        {
            // error here
        }
        finally
        {
            con.Close();
        }

        return date;
}

Comment: [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection
Comment: This is messed up.   There return type is int.   Does tarih = dr["Tarih"]; even work?  I don't see where you even open the connection.  Fix the formatting.
Comment: that was my bad, i tried a lot of things, i forget to fix it
Comment: Then fix the question.  And fix the formatting.  Answer is only as good as the question.  This is likely to get shut down if you don't fix the question.
Comment: @Paparazzi i fixed the question
Answer:
System.IndexOutOfRangeException

This assumes that there is a column named Tarih:
drr["Tarih"]

But there isn't.  Look closely at the query:
Select Max(Tarih) from Yoklama ...

The query uses that column, but doesn't actually produce that column.  It produces a calculated column which is going to have some default name.
You can specify a name for that column in the query:
Select Max(Tarih) AS Tarih from Yoklama ...

or perhaps just select the first (and basically only) column in the results:
drr[0]

Comment: it doesn't work, i don't know why.. there is no date data
Comment: @Ahmet: In what way does it fail?  What does the actual SQL query return?  What is in `dr["Tarih"]`?  Does `dr` contain any rows at all?  "It doesn't work" isn't really a description of a problem.
Comment: i fixed the question
Comment: Thank you sir ! it works now. i wanna kiss your hand, in Turkey if you respect to someone, you kiss him hand :) i was trying to fix this for 2-3 hours. This is my first time i used max() , that is why i couldn't fix it
Comment: @Ahmet: Glad I could help!  (And hand-kissing isn't entirely necessary on Stack Overflow.  We're happy just to be of service here.)

How to get datetime data in database?


Getting CWNetwork data rates

Question: I'm trying to get the data rates (in Mbps) for a CWNetwork object using CoreWLAN but I'm not able to figure out how to do this.
I've searched through all the API documentation and even the private methods for the CWNetwork and CWChannel objects.
What's the correct way of getting this information?
Answer: class CWInterface has transmitRate property. This property returns the current transmit rate (Mbps) for the interface.
CWInterface *wifiInterface = [CWInterface interface];
NSLog("Transmit Rate - %.f Mbps", wifiInterface.transmitRate);

Output - 145 Mbps

Getting CWNetwork data rates


What is this staff skin?

Question: In the Mad King's Labyrinth, what staff skin does this NPC have equipped?
Answer: The staff is called The Crossing.
Comment: And it makes the nougats actually worth collecting. Why nougats don't give a mini, I have no idea.
Comment: @Koviko I'm on a never ending quest to get an Aetherized hammer skin for 400g from the TP, so I've been selling my nougats when I hit 250. Think u can get 1 gold for em.

What is this staff skin?


MD5 hash for ubuntu .iso (14.04 through 18.10)

Question: I cant find the MD5 hash for ubuntu-14.04.1-desktop-amd64.iso on this website.
Am I looking in the right place?
Comment: Possible duplicate of [Where to find the checksums of Ubuntu ISO images?](https://askubuntu.com/questions/9417/where-to-find-the-checksums-of-ubuntu-iso-images)
Comment: There's no reason to keep a copy of MD5SUMS on this site, or a link to each release's MD5SUMS.  [Eliah Kagan's answer](https://askubuntu.com/a/339857/158442) very clearly explains how to look up the hashes.
Answer: No. they are not the same.
The Md5sums for 14.04 releases are as follows:
 dccff28314d9ae4ed262cfc6f35e5153 *ubuntu-14.04-desktop-amd64.iso
 c4d4d037d7d0a05e8f526d18aa25fb5e *ubuntu-14.04-desktop-i386.iso
 01545fa976c8367b4f0d59169ac4866c *ubuntu-14.04-server-amd64.iso
 08d25bf879e353686a974b7b14ae7d81 *ubuntu-14.04-server-i386.iso
 119cb63b48c9a18f31f417f09655efbd *ubuntu-14.04.1-desktop-amd64.iso
 a4fc15313ef2a516bfbf83ce44281535 *ubuntu-14.04.1-desktop-i386.iso
 ca2531b8cd79ea5b778ede3a524779b9 *ubuntu-14.04.1-server-amd64.iso
 3aa14ca13d52df070870d39306f4a4eb *ubuntu-14.04.1-server-i386.iso

The md5sums for 14.10 are as follows:
08494b448aa5b1de963731c21344f803 *ubuntu-14.10-desktop-amd64.iso
4a3c4b8421af51c29c84fb6f4b3fe109 *ubuntu-14.10-desktop-i386.iso
91bd1cfba65417bfa04567e4f64b5c55 *ubuntu-14.10-server-amd64.iso
1c920941d2544c0e097deb79cf3ebfbd *ubuntu-14.10-server-i386.iso

The right place to look is one of the sources below (If you are detecting a pattern here, you're right in that the link is http://releases.ubuntu.com/version.number/MD5SUMS. where version number is yy.mm of the release in question. You can also find md5sums for the following at the aforementioned link.
Edubuntu
Kubuntu
Lubuntu
Mythbuntu
Ubuntu GNOME
UbuntuKylin
Ubuntu MATE
UbuntuStudio
Xubuntu

Sources:

14.04
14.10
15.04
15.10
16.04
16.10
17.04
17.10
18.04
18.10

The md5sums for recent Ubuntu versions including Lubuntu Kubuntu Xubuntu, etc. can be found here and previous and point releases and their md5sums can also been found on this page. Drill down through version into release (or source) to find the sum (hash) for your version.
You can check the hash (md5sum) with the command md5sum ubuntu-version-desktop-variant.iso on a Linux system (Changing the name of the ISO file to match the one you have).
You can check the ISO under Windows using the built-in command certUtil (included in Windows 7 or newer), or you can use either the MD5 & SHA Checksum Utility available here or the Microsoft File Checksum Integrity Verifier available here.
Comment: @ElderGeek The link is for 14.04, not for 14.04.1. I found the [Lubuntu hashes](http://cdimage.ubuntu.com/lubuntu/releases/14.04.1/release/MD5SUMS) with the help of Google. I also found two relevant bug reports, one [for Ubuntu](https://bugs.launchpad.net/ubuntu/+source/ubuntu-docs/+bug/1349715) and one [for Lubuntu](https://bugs.launchpad.net/ubuntu/+source/ubuntu-docs/+bug/1356023).
Comment: Is there a safe source? That one is fine, but I would like to access that kind of information using https
Comment: Do you know where we can find MD5 sums for other distros such as Lubuntu?
Comment: @PaddyLandau Thank you. I incorporated the information into my answer


Get credential in nodejs google sheet v4

Question: I'm following this tutorial https://developers.google.com/sheets/api/quickstart/nodejs and I'm able to read and update my sheet.
I'd like to get the credential in order to pass more parameters to my function.
authorize(JSON.parse(content), listMajors);

How can I pass 1 more parameter to listMajor?
Or How can I get auth to pass my own function like listMajors?
function listMajors(auth) {

Answer: In your case, in order to add one more parameter to the arguments in listMajors, how about using call and/or apply?
Using call:
authorize(JSON.parse(content), (auth) => listMajors.call(this, auth, "additionalParameter"));  // or listMajors.call(null, auth, "additionalParameter")

Using apply:
authorize(JSON.parse(content), (auth) => listMajors.apply(this, [auth, "additionalParameter"]));  // or listMajors.apply(null, [auth, "additionalParameter"])

Note:

In above modification, the arguments can be used like function listMajors(auth, parameter){}.

References:

call()
apply()

Added:
I add 2 other methods.
1. Using function:
authorize(JSON.parse(content), (auth) => listMajors(auth, "additionalParameter"));

In this case, the arguments can be used like function listMajors(auth, parameter){}.
2. Using bind:
authorize(JSON.parse(content), listMajors.bind(this, "additionalParameter"));  // or listMajors.bind(null, "additionalParameter")

In this case, the arguments can be used like function listMajors(parameter, auth){}.
Reference:

bind()


Can you 3 star a base without destroying a tesla that isn't triggered?

Question: Is it required to destroy all Tesla towers to 3 star a base? What about those that don't get triggered?
For example, if I were to "hide a tesla" where it isn't likely to get triggered by an attacker will that help me in any way from getting 3-starred?
Answer: Yes it is necessary to destroy all teslas.
According to the wiki

The only exception to this rule is that Hidden Teslas will reveal themselves once a base has incurred at least 51% damage, as they must be destroyed (along with all other buildings) in order to achieve 3 stars.
Comment: @Ben_Craig. So the answer is "No it is not possible". For you to get a third star you need to reach 100% base destruction, that means passing through the 51% where the teslas will be revealed therefore making it necessary to destroy them to get to 100% and therefore a three star.
Comment: Unless you meant "yes it is necessary to destroy all teslas" :)
Comment: @pnizzle updated for clarity
Answer: I tried the hiding the hidden tesla strategy, it pops up automatically after your base is destroyed by a certain amount. the only good thing about doing this is that the attacker might not have enough time to get to the hidden tesla
Comment: That is exactly what the accepted answer says. This answer doesn't really add anything useful.
Comment: @JohnFx perhaps he was saying that hidden tesla can be tucked away to corners like builder huts, so that it pops up in middle and thereby wasting time. Might work in Th7 bases as they have less buildings. +1


Javascript unique random number generator is not generating unique numbers

Question: I'm trying a new random number generator that is supposed to generate numbers without duplicates, but when I try to apply it to my page it produces many duplicates. At least 60% of the time there was a dupe, one time a triplicate, and two sets of duplicates.
I'm trying the answer from Generate unique random numbers between 1 and 100 , and it seems to work as is even when I limit it to 20 numbers. Ran it 40 times with zero duplicate numbers. It's when I try to put it in my existing function that it falls apart. Any idea what I'm missing here? This is a continuation of my previous question Fill table with random images
/* The part of what each image url has in common
   ⍟ var base = 'images/Image_'
   */
var base = 'images/Image_';
var suff = '.jpg';

function randomCellBG(base) {

  // Reference the

  var T = document.getElementById('mainTable');

  /* Collect all .cell into a NodeList and convert
  || it into an array
  */
  var cellArray = Array.from(T.querySelectorAll('.cell'));

  // map() the array; run a function on each loop...
  cellArray.map(function(cel, idx) {

    // Get a random number 1 - 9
    var arr = []
    while (arr.length < 9) {
      var ran = Math.ceil(Math.random() * 40)
      if (arr.indexOf(ran) > -1) continue;
      arr[arr.length] = ran;
    }

    /* Concatenate base and random number to form
    || a string of a url of an image
    ⍟ result: "images/Image_08.jpg"
    */
    var img = base + ran.toString() + suff;

    /* Assign that url as the value to the
    || backgroundImage property of the .cell
    || in current iteration
    */
    cel.innerHTML = "";

  });

}

Comment: You're generating a new set of 5 unique random numbers for each item in `cellArray`. There could be overlap between those sets. Side note: avoid using `.map` if what you actually want to do is `.forEach`. They serve different purposes.
Comment: Sorry, forgot to change the code back after testing how it performed with a constrained set of numbers. I want to choose 9 from a set of 40.
Comment: you should generate the random numbers before `cellArray.map`, not inside it
Answer: if I understand it correctly, then you need: 1. change map to forEach 2. you need to move the array where you save already generated numbers out of the forEach function 3. change the number generator loop
/* The part of what each image url has in common
⍟ var base = 'images/Image_'
*/
var base = 'images/Image_';
var suff = '.jpg';

function randomCellBG(base) {

  // Reference the

  var T = document.getElementById('mainTable');

  /* Collect all .cell into a NodeList and convert
  || it into an array
  */
  var cellArray = Array.from(T.querySelectorAll('.cell'));

  // initialize the array
  var arr = []
  // map() the array; run a function on each loop...
  cellArray.forEach(function (cel, idx) {

    // generate numbers 1-40 and check if they were already generated
    do {
      var ran = Math.ceil(Math.random() * 40)
    } while (arr.indexOf(ran) > -1);
    //save the newly generated unique number
    arr[arr.length] = ran;

    /* Concatenate base and random number to form
    || a string of a url of an image
    ⍟ result: "images/Image_08.jpg"
    */
    var img = base + ran.toString() + suff;

    /* Assign that url as the value to the
    || backgroundImage property of the .cell
    || in current iteration
    */
    cel.innerHTML = "";
  });
}

Answer: Why don't you shuffle the array and then take the first n items which you need for the table?
You can use a shuffle algorithm and then simply slice the elements you need for your image table.
Shuffle means that there will be no duplicates derived from using a random function.
Something along these lines:

function shuffleArray(array) {
    array.forEach(function(e, i) {
        exch(array, i, Math.floor(Math.random() * (i + 1)));
    });
    function exch(array, i, j) {
        const temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8];
shuffleArray(array);
console.log(array.slice(0, 3));

array = ["a", "b", "c", "d", "e", "f"];
shuffleArray(array);
console.log(array.slice(0, 3));
Answer: It looks like what you need to do is generate your random numbers, and then apply them to each cell:
function generateNumbers(count, upperBound) {
    if (count > upperBound) { throw new Error('count cannot be more than upper bound'); }

    var arr = []

    while (arr.length < count) {
      var ran = Math.ceil(Math.random() * upperBound)
      if (arr.indexOf(ran) > -1) continue;
      arr[arr.length] = ran;
    }

    return arr;
}

function randomCellBG(base) {

  // Reference the

  var T = document.getElementById('mainTable');

  /* Collect all .cell into a NodeList and convert
  || it into an array
  */
  var cellArray = Array.from(T.querySelectorAll('.cell'));

  var nums = generateNumbers(cellArray.length, 40);

  // map() the array; run a function on each loop...
  cellArray.forEach(function(cel, idx) {
    /* Concatenate base and random number to form
    || a string of a url of an image
    ⍟ result: "images/Image_08.jpg"
    */
    var img = base + nums[idx] + suff;

    /* Assign that url as the value to the
    || backgroundImage property of the .cell
    || in current iteration
    */
    cel.innerHTML = "";

  });

}


Why does dirt appear after we turn off water either to the house or under the sink?

Question: I had to call the plumber to come out a few times recently to work on my kitchen faucet or bathroom faucet.  Each time, he either turned off the water under the sink or turned off the water to the house.  The funny thing is each time he turned the water back on, it seemed like there was sediment that came out and was caught in my kitchen sprayer or in the bathroom faucet aerator.
This is confusing to me since we didn't dig the pipe up to introduce dirt into the water system or anything.  All that was done was turn the valve underneath the sink a half turn to shut off water or allow water.  Can someone explain to me what's happening and why sediment gets disturbed when I turn the underneath valve?
Comment: @crip659 "a disturbance in the force"?  Wasn't expecting a metaphysical explanation :)
Comment: Most water pipes after some time will not look as nice and clean as when they were new.  Some will look quite icky inside.  Turning the water off and on again causes a disturbance in the force(pipe) and can loosen some stuff.
Comment: A guess:  the empty pipes let the built-up sediment dry out, which weakens the bond between the sediment and the pipes.  In support of this baseless guess, it does seem like leaving the supply off longer creates more gunk that takes longer to clear out.  More time, more drying.
Answer: Fine silt and dissolved minerals coming out of solution settle on the inside of pipes. When the system is de-pressurized and re-pressurized it's normal for that material to be disturbed and come out the faucets. Just flush them out until the water runs clear again, and remove and clean the aerator screens if it's big enough to get caught.
You could take a planned approach and start by flushing the hose bibs until clear, to get most of it from the supply side out of the house, then flush the interior fixtures.
A previous house had only plastic and copper piping, but iron in the water. Any time the system was shut down and turned back on, rust would pour out the faucets for a while.
Comment: Agree, and the other possible source of crud is the shutoff valve itself. If the sediment is black and oily, it could be the washer in the valve disintegrating. If so, the valve is on its way to failure and will need replacement (preferably with a quarter turn model so this doesn't happen in the future).
Comment: It counts as shaking the pipes and moving the valve, both of which will shake some accumulation loose. Expected and mostly harmless.
Comment: I see no need to add my own answer, but wanted the OP to know that I've see old galvanized steel supply lines reduced from 2" down to 1/4" with mineral content. Here's an example. https://innovativeplumbingpros.com/why-does-calcium-build-up-occur-in-your-plumbing-pipes-and-how-to-deal-with-it/
Comment: So going underneath the sink and turning a 1/2 turn constitutes as de-pressurizing/re-pressurizing the system?
Answer: This is definitely particular to your location, house age, and water service but sediment in your water supply isn't abnormal.  If you haven't ever done this, unscrew an aerator from one of your fixtures (kitchen or bathroom) and look at what has collected there.
In my experience, I have found little rocks, coarse sand, iron fragments, etc.  My home is almost 85 years old.  It's not reasonable to think that this was there the whole time and just made their way to the faucet.  When I've fixed leaky faucets, usually the problem is tiny rocks that have damaged the seats and/or gaskets on valves.  Anecdotally, this tends to happen after the water is cut off in the general area for repairs.  E.g., a 'boil water' alert from the water company.
Recently, I had an issue where water would just dribble from a faucet.  After checking the supply lines, I started unscrewing the aerator.  I had made a mistake: the faucet valve was open.  I heard a loud pop and the aerator shot off, bounced off the sink, and luckily, I was not maimed.  It turns out that the aerator was completely clogged with sediment.  I replaced the aerator and no problems since.
The upshot here is that your water supply likely goes through a lot of places that you might be surprised about. Don't assume it is all good.  At the same time, don't forget how amazing it is to be able to turn a faucet and have water delivered.
Answer: I've seen the water look dirty and black-ish for a few seconds, many times after using a multi-turn shut off valve that has an old washer.
The washer itself starts to break down, when you use the valve and squish it closed it washes the "black stuff" (from fine powder even up to little bits of washer) out the faucet when it's turned back on.  Eventually the washer will be so bad it won't shutt off the water too, and I wouldn't really want to drink water that has breaking down washer residue in it anyway.
Here's an image of a multi-turn shutoff valve with the bonnet nut and stem removed, showing the washer at the end:

And another image with all the parts labeled:

And another picture showing a different type of shutoff valve (globe I believe) that also uses a washer:

The washers are fairly easy to replace too (there's usually a stem valve washer / bonnet packing in there also, or a string type packing on the older valves), if the valve will come apart and isn't corroded solid. If so, I would highly recommend just changing the washers and internal parts instead of putting on a whole new valve (wrestling off an old damaged compression nut and cleaning the pipe is NOT worth it when a new washer takes about a minute).
For example, BrassCraft sells a Multi Turn Stop Stem Repair Kit
BCSR01 for their multi-turn shutoff valves, although the kit is about 70% the price of a whole new valve. Or the washers alone are available from a few places, try a web search for BrassCraft Valve Bibb Washer for Stop Valve


Google's protocol buffers in Golang

Question: Does Go support Google's protocol buffers
(Protocol buffers are a language-neutral, platform-neutral extensible mechanism for serializing structured data.)
Answer: Simple search with Google (irony?) reveals protobuf

Google's protocol buffers in Golang


How do I set value in an independent child component in VueJs?

Question: I have an inline edit component that works without any dependencies with other components, In one situation, I wish to trigger the edit view of the component from a parent component.
The component uses one variable called editing that toggles the edit view
// my-parent-component template

    <editable v-for="item in items" v-model="item" type="text">
    </editable>

// my-editing-component template

<input v-model="value" @keydown.enter="done"/>

The editable component is
export default {
    name : 'editable',
    props: ['value','type']
    data : function(){
        return {
            editing: false;
        }
    }
    methods : {
        edit(){
            this.editing = true;
        },
        done(){
            this.editing = false;
        }
    }

}

Now the challenge is I have a global listener for enter key and I maintain index of "active" item in the parent component.
When the user hits enter, I want to trigger edit of the active "item".
I can pass it as
<editable v-for="(item,index) in items" v-model="item" :editing="index == active" ></editable>

But that prop "editing" will not be in other places where I use the editable component
Is it ok to set property from the parent like this: this.$refs.editable.editing = true
From the documentation I understand that Its not possible to send a event to the child component.
What is the best way to do this?
Comment: Hi Masade, you have considered using central state management with Vuex for example?
Comment: Yeah, I am already using vuex to manage state for rest of application, however i wish this component "editable" is to be used in other applications. So using store may not be right.
Answer: Usually you should pass props to child components in order to control their states. But if you want a hacky access to children state, there are several workarounds:

use ref pointers on children (though it requires actual ref placed),
access component's children with this.$children.

this.$children requires some additional logic probably, where you decide which index of the array you need to access. It depends on your application.
Usage example:

new Vue({
  el: '#app',
  methods: {
    toggleChild: function() {
      this.$refs['editMe'].editable = !this.$refs['editMe'].editable;
      // different approach without 'ref':
      // this.$children[0].editable = !this.$children[0].editable;
    }
  },
  components: {
    'child' : {
      template: `<p>{{ editable }}</p>`,
      data: function() {
       return {
          editable: false
        }
      }
    }
  }
});

  <child ref="editMe"></child>
  <button @click="toggleChild">Toggle editable inside child</button>


Resolving dependencies for migration AEM 6.0 to 6.2

Question: Hi I have trying to start the bundle in 6.2 as part of migration from 6.0.
I have included UBER jar and still bundle is not started.

com.day.cq.replication,version=[5.5,6)-- this is the error.
Answer: Following is available in AEM 6.2 and that's what your POM should reflect -
For CQ Replication
<code><groupId>com.adobe.granite</groupId>
<artifactId>com.adobe.granite.replication.core</artifactId>
<version>6.0.14</version>
</code>
Comment: if I add that version, The below is showing up while compiling
Failed to execute goal on project company-bundle: Could not resolve dependencies for project com.x:company-bundle:bundle:0.0.5-SNAPSHOT: Could not find artifact com.adobe.granite:com.adobe.granite.replication.core:jar:6.0.14 in adobe-public-releases (https://repo.adobe.com/nexus/content/groups/public/) -> [Help 1]
Comment: Add scope as provided in dependency
Comment: Download the jar from crx and upload it to your local nexus


Firebase function not returning data

Question: I'm trying to get data from my Firebase function, but it keeps returning a null response. It looks like I need to return a promise and return my data in that promise, but I can't seem to get it to work even though I think I'm doing that. I'm not the most familiar with Node.JS, so I might be returning the wrong things in the promise.
Here's my function code:
exports.tasksLists = functions.region('us-east1').https.onCall((data) => {
  const userDoc = db.collection('users').doc(data.text);
  return userDoc.get().then((doc) => {
    if (!doc.exists) {
      return "";
    } else {
      return doc.data().tasksKey;
    }
  }).then((tasksCreds) => {
    const oauth2Client = new google.auth.OAuth2(
      '444701140384-srcttdrg28geg598h65dkekad47u9a48.apps.googleusercontent.com',
      'wNL4ZrBGYOnXUMvEcE7Z_Smo',
      'https://collag-oauth-u5b2i5chyq-ue.a.run.app/classroomcallback'
    );
    oauth2Client.setCredentials({
      refresh_token: tasksCreds.refresh_token,
      access_token: tasksCreds.token
    });
    const service = google.tasks({ version: 'v1', auth: oauth2Client });
    return service.tasklists.list({}, (err, res) => {
      if (err) {
        functions.logger.error(new Error(err));
        return JSON.stringify(err);
      }
      const lists = res.data.items;
      if (lists) {
        functions.logger.info(lists);
        return lists;
      } else {
        functions.logger.info('no lists');
        return "No lists";
      }
    });
  })
    .catch((e) => {
      functions.logger.error(new Error(e));
      return JSON.stringify(e);
    });;

});

I've also tried putting the OAuth and API request in the first .then() under else but that didn't work either.
Here's my frontend code to call the function and handle the data:
let tasksLists = fireApp.functions('us-east1').httpsCallable('tasksLists');
          tasksLists({ text: currentUser.uid }).then(function (result) {
            if (!result.data) {
              console.log('no data');
            }
            let lists = result.data;
            console.log(lists);
          });

The console.log(lists) just outputs null.
Answer: The problem is that you're not returning a promise. You can use the Promise constructor, passing in the resolve/reject parameters and call any of those when your want to return the asynchronous result. Change your cloud function like so:
exports.tasksLists = functions.region('us-east1').https.onCall((data) => {
  const userDoc = db.collection('users').doc(data.text);
  return new Promise((resolve, reject) => {
    userDoc.get().then((doc) => {
    if (!doc.exists) {
      return "";
    } else {
      return doc.data().tasksKey;
    }
  }).then((tasksCreds) => {
    const oauth2Client = new google.auth.OAuth2(
      '444701140384-srcttdrg28geg598h65dkekad47u9a48.apps.googleusercontent.com',
      'wNL4ZrBGYOnXUMvEcE7Z_Smo',
      'https://collag-oauth-u5b2i5chyq-ue.a.run.app/classroomcallback'
    );
    oauth2Client.setCredentials({
      refresh_token: tasksCreds.refresh_token,
      access_token: tasksCreds.token
    });
    const service = google.tasks({ version: 'v1', auth: oauth2Client });
    service.tasklists.list({}, (err, res) => {
      if (err) {
        functions.logger.error(new Error(err));
        // return JSON.stringify(err);
        reject(err);
      }
      const lists = res.data.items;
      if (lists) {
        functions.logger.info(lists);
        resolve(lists);
        // return lists;
      } else {
        functions.logger.info('no lists');
        resolve("No lists")
        // return "No lists";
      }
    });
  })
    .catch((e) => {
      functions.logger.error(new Error(e));
      reject(e);
      // return JSON.stringify(e);
    });
  })
});

Comment: That worked, thank you! I thought I was already returning a promise with `userDoc.get()` but I guess not.

Firebase function not returning data


Using regex to match variables in a string

Question: I would like to match, using regex with groups, in java these scenarios but I am not very good with regex and don't understand how to match repeating things like these:
Text: local var1, var2, var3 = 100
I want to match to get all the lua variable names so my matches would be 'var1' and 'var2' and 'var3'
Text: self.var1, self.var2 = 200
Same as above but using self instead of local- I'd like matches of 'var1' and 'var2'
And lastly
Text: var1, var2, var3 = 300
I imagine I may be able to use the first regex for this, right? I'd like the matches to work for 1 or more matches so these all would work:
var1 = 10
var1, var2 = 10
self.v = 1
self.v1, self.v2 = 20
local v1,v2 = 10
local v1 = 30
I do not need all this in one big regex, 2 or 3 different patterns would work. (Hope this type of question is appropriate since I don't really have any code to show...)
Thanks in advance!
Answer: I think something like this should work
<code>String input = "...Your input...";
List<String> matches = new ArrayList<>();

Matcher m = Pattern.compile("(\\w+)\\s*(?=[,=])").matcher(input);
while(m.find()) {
    matches.add(m.group(1));
}
</code>
Comment: thanks, works well with a little tweaking for my purpose!


Textarea change is not detected on onkeyup event?

Question: Textarea change needs to be detected onkeyup event when page is loading. Textarea resizing is working fine but textarea is not detected onkeyup event when page is loaded.I tried following code.

Comment: Can we have a _working demo_ with HTML ? Where have you placed your `
Answer: try by running your code in  window.onload
window.onload=function(){
    jQuery.each(jQuery('textarea[data-autoresize]'), function() {
      var offset = this.offsetHeight - this.clientHeight;
      var resizeTextarea = function(el) {
        jQuery(el).css('height', 'auto').css('height', el.scrollHeight + offset);
      };
      jQuery(this).on('keyup input', function() {
        resizeTextarea(this);
      });
      jQuery(this).trigger('keyup');
    });

    //trigger when modal showing
    $('.modal').on('shown.bs.modal', function () {
        jQuery('textarea[data-autoresize]').trigger('keyup');
    })

}

fiddle here
Comment: in Add Clause popup ?
Comment: ok in this case you need to trigger on modal showing for example.

$('.modal').on('shown.bs.modal', function () {
  jQuery('textarea[data-autoresize]').trigger('keyup');
})
Comment: can you show me example ? i don't think so this should be happen
Comment: jQuery(this).on('keyup input', function() {
        resizeTextarea(this);
      }).trigger('keyup'); you can also try
Comment: how to setTime out for trigger keyup events in your code?
Comment: setTimeout(function(){
jQuery('textarea[data-autoresize]').trigger('keyup');

 }, 3000);
Comment: i added in code but it is not working can show on jsfiddle
Comment: I added your code in my program but it not working , $("#orderModal").modal("show");
  $('.modal').on('shown.bs.modal', function () {
     setTimeout(function(){ jQuery('textarea[data-autoresize]').trigger('keyup'); }, 3000);
    });
Comment: wighout model it working , my problem is , when i click on button model is coming , in this model have textarea , this textarea not trigger keyup event ,
Comment: time-delay is working, but in your code i change 3000 to 100 then textarea is jembling or jenking or blinking , i don't want show that effect
Comment: why don't you add some kind of transition on resize ? jenking issue is not because of my code
Comment: when button click model is coming same time textarea trigger without any delay, how can i do?
Comment: hire me than i will help you :D well see full documentation here http://getbootstrap.com/javascript/#modals-options
Answer: You shall execute jquery once the doc has finished loading.
Wrap it like this:

Comment: Please post your html


$\dfrac{y\mathrm{e}^{yx}}{x}dy+e^{xy}dx=0$ finding integrating factor?

Question: $\dfrac{y\mathrm{e}^{yx}}{x}dy+e^{xy}dx=0$ Find the integrating factor
ı have tried using $\frac{N_x-M_Y}{xM-yN} = R$ but could't get anything
Comment: it is fixed now
Answer: $$\dfrac{y\mathrm{e}^{yx}}{x}dy+e^{xy}dx=0$$
$$e^{xy}({y}dy+xdx)=0$$
$${y}dy+xdx=0$$
Integrate:
$$y^2+x^2=C$$

$$\dfrac{y\mathrm{e}^{yx}}{x}dy+e^{xy}dx=0$$
You can multiply by $\mu (x,y)=xe^{-xy}$ then the DE becomes exact.
$$ydy+xdx=0$$
Is exact.
Comment: I see  @ArmanTuran but note that $xdx+ydy=0$ is exact
Comment: https://imgur.com/biifMWX here is the question
Comment: Then multiply by $e^{-xy}x$ the DE then it's exact @ArmanTuran


Do AFCI and GFCI protect against cheap equipment and bad wiring?

Question: Generally I only buy electrical fixtures (lights, fans, etc.) from a reputable seller out of concern for fire risks, but if AFCI breakers and GFCI receptacles are installed, would that eliminate any potential for fires / dangerous issues if there was either a faulty fixture or wiring in the house?
Comment: Eliminate no, but should reduce the chances by a very large amount.  Should be close to zero chance if everything is to code and the breakers/receptacles are working as they should.
Comment: @MonkeyZeus  Sorry about that, guess I got up on the wrong side of the bed this morning. But using 50 cent outlets is also egregious .
Comment: @monkeyzeus, they do not have the same quality hardware so yes they do wear out faster, new they don't have the same withdrawal force after just a few cycles (some jobs I have to measure the withdrawal force). That with the ones that only have backstabs should be outlawed in my opinion. Although backstabs may have put my son through college so I should like them. Despise backstabs yes because of the close calls to full blown fires. Not only arcing at a stab but look at the plug face for soot from arcing, most likely a cheep one even if it has screws in my experience.
Comment: I confidently buy a 10-pack of outlets for $5 and use them without worry. Is that cheap? Yes. Is the company reputable? Also yes. Are the faulty? Only time can tell. You should revise your question to remove money from the equation. Yes AFCI and GFCI exist to protect people from various electrical failures regardless of perceived quality of of your fixtures/devices. However, don't cheap out on the AFCI/GFCI protection itself.
Comment: @GeorgeAnderson I never thought I could be insulted over the Internet but accusing me of using backstabs is a particularly heinous transgression...
Comment: I've remodeled a couple of rentals I had and the outlets were the cheepies. After about 10 years, they were so weak that a plug would hardly stay in, def. an arc fault/fire hazard.  I replaced them all with spec grade.  Yeah, they are much harder to push in a plug, but a much more secure/solid connection.
Comment: Because UL isn't in the business of grading quality, they grade **safety**.  It's obvious that an unsafe unit is not quality, but other than that, UL is silent on usefulness, durability or reliability. Caveat Emptor.
Comment: @MonkeyZeus So you are willing to spend $40-$50 on AFCI/GFCI breakers to protect fifty cent outlets? ...probably back stabs, which are awful. Step it up and get some spec grade outlets that will last for more than a few years.  I wish SE would allow DV'ing comments.
Comment: @GeorgeAnderson Hah, no sweat. My comment was supposed to be cheeky. What is a "spec grade" outlet anyways? If the Home Depot 10-pack is UL Listed then what's the issue? Is spec grade immune to faults? I'm not saying that a $50 breaker is an excuse to use bad products. At the end of the day, the breaker is a good idea regardless of how much you spent on downstream equipment.
Comment: I do agree with George on the cheeep contractors grade receptacles. I do spend more when I spec the job actually +5x on receptacles and that is part of why people seek me out years later. Those receptacles are UL listed but so are backstabs and I have repaired quite a few burned up receptacles in my career. A recipe for a fire, .50 cent receptacle with a 18 gauge extension cord to a milk house heater , 3 full blown fires I have repaired.
Comment: @EdBeal Why are they sub-par exactly? Do they wear out faster or are they mechanically unsafe? Do you simply despise the existence of backstabs? Like I said, I **DO NOT** ever use backstabs.
Comment: @george Anderson I am surprised you got 10 out of homeowners grade that is a long time, spec / commercial grade are expected to last 20 years in commercial use but my rep said 50 to 100 years is more likely and hospital grade have totally different standards from insertion force to withdrawal force and tougher plastic if jerked out hospital grade is the best , commercial the middle and homeowners cheapest the plastics are similar to the grade also so a broken plastic face is common on homeowners grade compared to rarely seeing a broken hospital grade (not the cover plate the receptacle face).
Comment: @EdBeal  Not sure of the exact timeline.  I didn't own the rental all that long before I remodeled it. I assumed since it was about 10 years old when I bought it that the outlets were of the same vintage.  Shoot:   50 year old outlets were better than the cheap stuff nowadays.
Comment: @MonkeyZeus 50 cent outlets are fine for outlets in code-required areas that nobody ever uses.  If it's an outlet that you'll plug something into maybe once every few years, fine a 50 cent outlet will do the job.  But if it's in regular use and things are going in and out of it with any frequency then those cheap outlets fall apart pretty quickly and you end up with plugs that will fall out of the receptacle with little more than gravity or a wiggle.  Plug a vacuum or hairdryer in something that sloppy and the contact resistance is higher, the outlet gets hotter, etc.
Answer: Do AFCI and GFCI protect against cheap equipment?
Not really. A GFCI will limit a shock and an AFCI will limit arcing.
There are many other things that can happen with non listed equipment. I specifically look for a UL listing or TUV true verification that the devices are safe to use. Some JUNK  may not arc or have ground faults but overheat and start a fire.
So NO even the combination AFCI + GFCI devices can not protect for these cases where no arcing or ground faults happen. Poorly chosen components that over heat and start fires can still happen.
What's worse is some devices cause nuisance tripping, no faults, new replacement more tripping the owner removes the AFCI and the device ends up causing a small fire (usually contained in the junction box).
Comment: +1 Indeed, not really. To the OP: UL + AFCI/GFCI are added layers of protection for different failure modes (wiring, fitting, install, wear & tear, wet conditions), not substitutes.
Comment: Ed:  I wish I could give you a 100 points for that answer!  And the advice monkeyzuse it not good. It's just not that much more expensive to invest in quality materials.   ++++++++++
Answer: If the cheap equipment is so cheap, that you experience a live-neutral shock, you will die, and neither the GFCI/AFCI will trip, because killing you became the load. You'll be long dead before the lowest rated breakers will trip from shocking you.
AFCI/GFCI do not cover all possible source of danger. It covers some of it and can make things safer, but electricity will still kill you. Don't do stupid things and think AFCI/GFCI can compensate for garbage electronics.
Answer: At the very least, you need to comply with NEC 110.2 (it's on the first page) which says you must use approved equipment.   In practice that means listed by an NRTL such as UL, CSA, ETL, BSI, TUV and the like, this being independent lab testing to positively confirm the appliance complies with the relevant UL White Book standards so it won't kill you.  And then, continued surveillance of factory output to assure the factory doesn't bait-and-switch.
*It sounds like what you're saying is, "Is it OK to use the cheap Cheese junk I see on AliExpress, Amazon, eBay, Banggood, DealExtreme and wish.com" the vast majority of which are not listed.
Right off the top of my head, here's a fatal blunder:  As you know, any random plastic will burn like a freak and produce toxic smoke; very commonly in house fires, the toxic smoke overcomes you - it doesn't need to kill you clinically dead, just incapacitate you and the smoke/fire does the rest. They must be made out of the right plastics (expensive) to NOT do that. The right plastics cost money.
That's an immediate example of something AFCI and GFCI won't protect against.
That cheapo stuff online is all about cutting every possible corner on costs, so they dispense with both proper materials and independent lab testing.  Since most consumers expect an NRTL mark to be there, they just stick a CE, CCC, FCC or RoHS mark on there, none of which are NRTLs but you don't know that. They either don't relate to device safety, or are voluntary self-certifications that are unenforced outside certain jurisdictions, so no consequence for faking them.