text:
Q: Erratic behaviour in ECC digital signature code I am trying to use SECP-256K1 (Bitcoin's ECC curve) to do a SHA256withECDSA signature on some data with the code posted below. The codes do not always work properly and can be rather erratic and unstable at times.
I would like help stabilizing the code below.
Code for generating ECC keypair on Signer's end:
AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec("secp256k1"));
ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
keyGen.initialize(ecParameterSpec);
KeyPair ecKeyPair = keyGen.generateKeyPair();
ECPublicKey deviceEcPub = (ECPublicKey) ecKeyPair.getPublic();
ECPrivateKey deviceEcPriv = (ECPrivateKey) ecKeyPair.getPrivate();

Convert the ECC public key into 04<Public X Axis><Public Y Axis> format as per Bitcoin specifications of public keys:
int cursor = 0;
byte[] devicePubKey = new byte[65];
devicePubKey[cursor] = (byte) 0x04;
cursor++;
System.arraycopy(deviceEcPub.getW().getAffineX().toByteArray(), 0, devicePubKey, cursor, 32);
cursor += 32;
System.arraycopy(deviceEcPub.getW().getAffineY().toByteArray(), 0, devicePubKey, cursor, 32);

Sign some data on the Signer's end:
Signature sig = Signature.getInstance("SHA256withECDSA");
sig.initSign(deviceEcPriv);
sig.update(data, 0, data.length);
byte[] signature = sig.sign();

Verifier's end receive the 04<Public X Axis><Public Y Axis> encoded public key and converts from a X,Y coordinates into an actual ECC Public Key for use:
byte[] x = new byte[32];
byte[] y = new byte[32];
// Skips the first byte containing the 0x04 byte and copies the rest
System.arraycopy(devicePubKey, 1, x, 0, 32);
System.arraycopy(devicePubKey, 33, y, 0, 32);

Verifier uses the X and Y coordinates and reconstructs the ECPublicKey:
AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec("secp256k1"));
ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)), ecParameterSpec);
ECPublicKey publicKey = (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(ecPublicKeySpec);

Executes the verification by the Verifier on the data and signature supplied:
Signature sig = Signature.getInstance("SHA256withECDSA");
sig.initVerify(publicKey);
sig.update(data, offset, length);
return sig.verify(signature);

The result of verification is sometimes True and sometimes False with seemingly random looking occurrences.
I would like advise on the above code to ensure that it doesn't have erratic behaviours.

A: Ok, I noticed that if the 1st byte starts with 0x00, the X or Y will be 33 bytes long and thus I am not properly copying X or Y bytes.
To mitigate the above where there can be 0x00 as the first byte for either or both X and Y, I would read the first byte of X and Y and if the first byte is 0x00, I will skip copying the first byte and read as much bytes until 32 bytes for each of X and Y are fully copied.
There are also cases where X and/or Y may fall short of 32 bytes (i.e. only 31 bytes long)
Another way is to measure the length. If the length is more than 32, skip bytes until last 32 bytes. If the length is less than 32, copy the bytes and put 0x00 bytes to the front of the byte array.
My re-implementation of extracting the public X and Y values are shown in the codes below.
int cursor = 0;
int copy = 0;

// Get X
byte[] X = deviceEcPub.getW().getAffineX().toByteArray();

// Evaluate length
if (X.length > 32) {
    copy = 1;
    System.arraycopy(X, copy, devicePubKey, cursor, 32);
} else if (X.length < 32) {
    System.arraycopy(X, copy, devicePubKey, cursor + (32 - X.length), X.length);
} else {
    System.arraycopy(X, copy, devicePubKey, cursor, 32);
}

// Increment cursor
cursor += 32;

// Reset copy offset status
copy = 0;

// Get Y
byte[] Y = deviceEcPub.getW().getAffineY().toByteArray();

// Evaluate length
if (Y.length > 32) {
    copy = 1;
    System.arraycopy(Y, copy, devicePubKey, cursor, 32);
} else if (Y.length < 32) {
    System.arraycopy(Y, copy, devicePubKey, cursor + (32 - Y.length), Y.length);
} else {
    System.arraycopy(Y, copy, devicePubKey, cursor, 32);
}

Result is the signature verification becomes stabilized.


text:
Q: trigger alarm using sms what does "the constructor intent(EAlarmReceiver, Class) is undefined" mean? is this the proper way of triggering an alarm using sms, also, how can i still start the alarm even in silent mode? thanks in advance
public class EAlarmReceiver extends BroadcastReceiver {

public static String sender;
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    Bundle bundle = intent.getExtras();
    Object[] pdusObj = (Object[]) bundle.get("pdus");
    SmsMessage[] messages = new SmsMessage[pdusObj.length];
    for (int i = 0; i<pdusObj.length; i++)
    {
            messages[i] = SmsMessage.createFromPdu ((byte[])
            pdusObj[i]);
            sender = messages[i].getOriginatingAddress();
    }

    for (SmsMessage msg : messages) {
        if (msg.getMessageBody().contains("alert")) {

            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.SECOND, 1);

            Intent i = new Intent(EAlarmReceiver.this, ReceiverInterface.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context,
                12345, i, PendingIntent.FLAG_CANCEL_CURRENT);
            AlarmManager am =
                (AlarmManager)context.getSystemService(Activity.ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                    pendingIntent);
        }//end if
    }//end for

}// end onreceive

A: Use context instead of EAlarmReceiver.this.
http://developer.android.com/reference/android/content/Intent.html#Intent(android.content.Context, java.lang.Class)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Grails functional test - DB setup/teardown, running as JUnit in Eclipse I am running Geb functional tests in my Grails app through Eclipse "Run As JUnit..."
This normally works great and allows me to keep my test server running with grails run-app, and I get fast test execution times.
However, it doesn't allow me to use GORM domain objects in my setup/teardown methods.  Those only work if I run with grails test-app, which requires a much longer cycle time.
Is there another way I can access the DB from my functional tests without GORM?  I would be perfectly OK accessing the DB directly through the groovy.Sql class, as long as I don't have to duplicate configuration.

A: The question you linked to in your comment actually does contain a solution in this answer - you should use Grails Remote Control plugin to change the state of your application under test from your functional tests. Some reasons why are outlined in this answer to another question.


text:
Q: EPPlus: Saving after setting ExcelDxfStyleConditionalFormatting I created a method for reformatting an Excel Workbook:
        string Formula = @"IF(LEN($A2)>0,1,0)";

        using (ExcelPackage excelFile = new ExcelPackage(destinationfile))
        {
            ExcelWorksheet worksheet = excelFile.Workbook.Worksheets[1];
            ExcelTable worktable = worksheet.Tables[0];
            string workrange = worksheet.Cells[worktable.Address.Start.Row + 1, worktable.Address.Start.Column, worktable.Address.End.Row, worktable.Address.End.Column].Address;

            ExcelAddress cellIsAddress = new ExcelAddress(workrange);
            var cfRule = worksheet.ConditionalFormatting.AddExpression(cellIsAddress);

            cfRule.Formula = Formula;

            //cfRule.Style.Fill.PatternType = ExcelFillStyle.Solid;
            //cfRule.Style.Fill.PatternColor.Color = Color.LightYellow;
            //cfRule.Style.Fill.BackgroundColor.Auto = true;
            //cfRule.Style.Font.Bold = true;
            //cfRule.Style.Fill.BackgroundColor.Color = Color.LightCyan;

            excelFile.Save();
        }

The problem is that, if I set any style to the rule (My goal was to set a yellow background, but I also tried with all the commented options), the Save() method crashes.
Any ideas?


text:
Q: produce standalone html for chunks of an Rmarkdown document I am searching for a way to produce a standalone HTML document from a chunk in Rmarkdown.
My example is this:
I have an Rmarkdown document for my analysis.
In one chunk of code, I produce interactive plotly plots that are quit long to load when I open the HTML.
I am looking for an option that would create another HTML document for this particular chunk and put a link to it in its place in the master HTML document.
I am sure I could manage to do something like that with a bit of tweaking with another script, but I would like to know if there is not a simpler option first.
Thanks

A: Yes, you can nest documents using knitr child documents. Put the chunk you want to isolate in its own Rmd (say, child.Rmd), then use this syntax to insert it in the master document:
```{r child='child.Rmd'}
```


text:
Q: Yii2 validation on controller action I am developing a Yii 2.0 application in which users can create orders then send the orders to review and after that it follows a number of stages in the workflow.
Everything is ok until yesterday that the customer ask for the possibility that before sending the orders to review the order are considered as draft. Which means I have to turn off validations on create and validate them when users clicks Send To Review button.  I know Yii 2.0 supports scenarios but maybe scenarios doesn't apply to this because the Send To Review button is shown in a readonly view.  This forces me to do validation inside the controller action because there is no send_to_review view.  How can this be done (I mean model validation inside controller action)?
Here is the controller action code
public function actionSendToReview($id)
{
    if (Yii::$app->user->can('Salesperson'))
    {
        $model = $this->findModel($id);
        if ($model->orden_stage_id == 1 && $model->sales_person_id == Yii::$app->user->identity->id)
        {
            $model->orden_stage_id = 2;
            $model->date_modified = date('Y-m-d h:m:s');
            $model->modified_by = Yii::$app->user->identity->username;

            //TODO: Validation logic if is not valid show validation errors
            //for example "For sending to review this values are required:
            //list of attributes in bullets"
            //A preferred way would be to auto redirect to update action but
            //showing the validation error and setting scenario to
            //"send_to_review".

            $model->save();
            $this::insertStageHistory($model->order_id, 2);
            return $this->redirect(['index']);
        }
        else
        {
            throw new ForbiddenHttpException();
        }
    }
    else
    {
        throw new ForbiddenHttpException();
    }
}

What I need to solve is the TODO.
Option 1: Showing validation errors in the same view and the user has to clic Update button change the requested values save and then try to Send To Review again.
Option 2: Redirecting automatically to update view already setting scenario and validation errors found in the controller.
Thanks,
Best Regards

A: You can use $model ->validate()for validation in controller.
public function actionSendToReview($id)
{
    if (Yii::$app->user->can('Salesperson'))
    {
        $model = $this->findModel($id);
        if ($model->orden_stage_id == 1 && $model->sales_person_id == Yii::$app->user->identity->id)
        {
            $model->orden_stage_id = 2;
            $model->date_modified = date('Y-m-d h:m:s');
            $model->modified_by = Yii::$app->user->identity->username;

            //TODO: Validation logic if is not valid show validation errors
            //for example "For sending to review this values are required:
            //list of attributes in bullets"
            //A preferred way would be to auto redirect to update action but
            //showing the validation error and setting scenario to
            //"send_to_review".

            //optional
            $model->scenario=//put here the scenario for validation;

             //if everything is validated as per scenario
             if($model ->validate())
            {
               $model->save();
               $this::insertStageHistory($model->order_id, 2);
               return $this->redirect(['index']);
            }
            else
            {
                return $this->render('update', [
                 'model' => $model,
               ]);
            }

        }
        else
        {
            throw new ForbiddenHttpException();
        }
    }
    else
    {
        throw new ForbiddenHttpException();
    }
}

If you don't need validation in actionCreate().Create a scenario for not validating any field and apply there.


text:
Q: FIFO using vhdl I am writing a VHDL for fifo , but when i simulate   there is no output?i cantt view the output in behavioral simulation.its like There's no data in data_in for read to be writing to the output of fifo.In my code is   to write data into the FIFO first push the data onto the DataIn bus and then strobe the WriteEn input high for one clock cycle.
library IEEE;
        use IEEE.STD_LOGIC_1164.ALL;
        use IEEE.STD_LOGIC_UNSIGNED.ALL;
        use std.textio.all;
        use IEEE.NUMERIC_STD.ALL;

        entity fifo_mem is
        port (    clk : in std_logic;
                  reset : in std_logic;
                  enr : in std_logic;
                  enw : in std_logic;
                  data_in : in std_logic_vector (15 downto 0);     --input data
                  data_out : out std_logic_vector(15 downto 0);    --output data
                  fifo_empty : out std_logic;
                  fifo_full : out std_logic   );
        end fifo_mem;
         architecture Behavioral of fifo_mem is
        type fifo_type is array(0 to 10) of bit_vector (15 downto 0);
        signal memory : fifo_type :=(others => (others => '0'));
        signal readptr,writeptr : integer := 0;  --read and write pointers.
        signal empty,full : std_logic ;

     impure function InitRamFromFile (RamFileName : in string) return fifo_type is
        FILE RamFile : text is in RamFileName;
        variable RamFileLine : line;
        variable RAM : fifo_type;
        begin
        for I in 0 to 10  loop
        readline (RamFile, RamFileLine);
        read (RamFileLine, RAM(I));
        end loop;
        return RAM;
        end function;

     signal RAM : fifo_type :=InitRamFromFile("C:\Users\hp\Desktop\file\file1.txt");

begin
    fifo_empty <= empty;
    fifo_full <= full;

    process(Clk,reset)
    --this is the number of elements stored in fifo at a time.
    --this variable is used to decide whether the fifo is empty or full.
    variable num_elem : integer := 0;
    begin
    if(reset = '1') then
        data_out <= (others => '0');
        empty <= '0';
        full <= '0';
        readptr <= 0;
        writeptr <= 0;
        num_elem := 0;
    elsif(rising_edge(Clk)) then
        if(enr = '1' and empty = '0') then  --read
            data_out <=to_stdlogicvector(RAM(readptr));
            readptr <= readptr + 1;
            num_elem := num_elem-1;
        end if;
        if(enw ='1' and full = '0') then    --write
         RAM(writeptr)<= to_bitvector(data_in);
            writeptr <= writeptr +1;
            num_elem := num_elem+1;
        end if;

         if(readptr = 10) then      --resetting read pointer.
            readptr <= 0;
        end if;
        if(writeptr = 10) then        --resetting write pointer.
            writeptr <= 0;
        end if;
        --setting empty and full flags.
        if(num_elem = 0) then
            empty <= '1';
        else
            empty <= '0';
        end if;
        if(num_elem = 10) then
            full <= '1';
        else
            full <= '0';
        end if;
    end if;
    end process;

    end Behavioral;


text:
Q: How do you write "forces" in set theory, in Latex? I just learned forcing in my Set theory class. I am wondering how do we write "forces" denoted by a symbol that looks somewhat similar to, but different, o$\models$o.

A: I believe the symbol you're looking for is \Vdash available by loading the amssymb package.
Also, you want to put your whole math expression inside the $…$, not just the special symbol, so $o \Vdash o$.
Finally, when you're trying to find a symbol, the Detexify site (there's also an off-line tool) is handy for being able to draw a symbol and see what TeX commands will generate something similar.


text:
Q: graph - How to obtain the Minimum Weight Connected Subset? Here is an excise:

Consider the problem of finding a minimum weight connected subset T of edges from a weighted connected graph G. The weight of T is the sum of all the edge weights in T.Give an efficient algorithm to compute the minimum weight connected subset T.

Here are what I have got:

*

*I have to assume the weights are mixed by both positive and negative ones. Only the mix of both kinds of weights can make sense for this excise.

*I will sort the edges first, so the negative edges will come first.

*I will consider utilise Kruskal's algorithm, but should be with some modifications

*Because I welcome negative edges, I will try to add as many negative edges as possible.

*In addition, some positive edges may be added to just in case that not all negative edges are connected and they may need some positive edges as bridges.

Ok, above is my thinking. But when I try to get my hands dirty, I get stuck.
How can I always record the possible minimum weights set?
For example,
{0, 1} is with weight -20
{2, 3} is with weight -10
if {1, 3} has weight of 11, then of course I don't want {1, 3}
or if {1, 3} has weight of 9, then I want
With what kind of data structure I can always keep the minimum weight and the vertices for that weight?

It is worth to note that the subset this excise seeks for aim at edges.

Consider the problem of finding a minimum weight connected subset T of
  edges from a weighted connected graph G

This means that all vertices still need to be included.
Also it is more than a MST. Consider that if a vertex has two edges, one is -1, another is -2. In a normal MST algorithm, only edge of -2 will be taken. But in this excise, both -1 and -2 need to be taken to reduce the overall weight further.

A: I think your algorithm is mostly correct already, but with slight modifications it becomes trivial to implement.
First, every negative edge has to be included in order to minimize the resulting weight. Next, calculate the number of connected components c. If c=1, you're done. Otherwise you need extra c-1 positive edges.
Now, while you were adding negative edges, consider this already as a Kruskal's algorithm process. Every negative edges may unite a couple of trees in the Kruskal's forest. However, you add the negative edge even if its ends belong to the same tree in the Kruskal's forest — unlike the usual Kruskal's algorithm where you only add those edges that unite two different trees.
After this phase, you're left with a graph of c connected components (they may not be trees anymore). Now just continue the Kruskal's algorithm as usual. Process the positive edges in the increasing order, keeping track of the number of unions the you've made with positive edges. Once this number gets to c-1, you're done.
By the way, all the process of Kruskal's algorithm can be implemented easily if you represent the forest as disjoint-set data structure. It requires just a couple of lines of code to write, and after that it is trivial to keep track of the number of unions that were made.

Some pseudocode follows:
sort(edges);
c := n;
for edge in edges:
    if edge.weight < 0:
        if find(edge.firstEnd) != find(edge.secondEnd):
            --c;
        unite(edge.firstEnd, edge.secondEnd);
    else:
        if c == 1: break;
        if find(edge.firstEnd) != find(edge.secondEnd):
            unite(edge.firstEnd, edge.secondEnd);
            --c;

Here unite and find are the functions of disjoint-set data structure.


text:
Q: Constrain union T in different branches Is it possible to inspect what a generic unioned type is within the body of a method?
For example, I have
const stringIdentity = (original: string): string => {
    return original
}
const numIdentity = (original: number): number => {
    return original
}

const identity = <T = string | number>(original: T): T => {
    if (typeof original === 'string') {
        return stringIdentity(original) // <-- error on this line
    }
    if (typeof original === 'number') {
        return numIdentity(original)    // <-- error on this line
    }
}

Playground here.
In each of the branches I get an error*

Type 'string' is not assignable to type 'T'

As a human, I can see that T is a string in the top branch and that I should be able to return a string safely. Is there a way to convince the compiler of this?

*or "Type 'number'..."

A: The error is correct. You could for example call your function with T being string & {x: number}, it might make no sense but it is possible. Then the typeof condition will return true, but the result of stringIdentity will be of type string, but not T.
One solution would be to convert your identity functions so that they are generic, too. Another solution would be to just add a cast because anyone using string & {x: number} as T is not very probable.
But what I guess is really the case is that you simplified your real problem in order to make it into a StackOverflow question, but you simplified too much probably, and now it's not very clear what is your real setup. Are you really operating on strings and numbers or not?

A: You can achieve this as follows:
    const identity = <T = string | number>(original: T): typeof original => {
        if (typeof original === 'string') {
            return stringIdentity(original) as typeof original;
        }
        if (typeof original === 'number') {
            return numIdentity(original) as typeof original;
        }
    }

    const stringIdentity = (original: string): string => {
        return original
    }

    const numIdentity = (original: number): number => {
        return original
    }

Playground

Warning: Here in your identity function, what if I pass the object, neither string nor number. If you have marked the return type of identity function as T, so you have to handle all the possible types. Your identity function returning void on the given type of object.


text:
Q: MSI export in BizTalk has different files than expected In BizTalk admin console 2016 there is an option to export the MSI file. I tried to take the backup using this method but after installing the MSI I just compared a schema dll present in the MSI with the DLL in GAC and I see the difference in timestamp and the file also. As per my understanding the DLLin GAC will be part of the MSI export.
So I wanted to know from which path does export MSI functionality takes the backup of files?

A: The Export MSI uses copies of the DLLs stored in the BizTalk database, not the GAC.   If someone has followed bad practices and either GACed a DLL without importing it, or imported it with GACing, then the two will be different, which can cause all sorts of weird problems.
It also causes problems if you attempt to do a roll-back using an exported MSI as it then uses the DLL from the MSI to both import to the BizTalk Databases and the GAC, and if the GAC version was different, then you are not back to your original state.


text:
Q: Where are static structs stored in C#? From this question I understood that

*

*structs can be allocated on the stack or in registers and not on the heap

*if a struct is part of a reference type object on the heap, the struct will also be on the heap

But how about a struct that is not part of an object, but a static member of a class like so:
public class Program
{
    public static CustomStructType inst1;

    static void Main(string[] args)
    {
        //assigning an instance of value type to the field
        inst1 = new CustomStructType();
    }
}

public struct CustomStructType
{
    //body
}

There will not be an instance of Program on the heap. So where will the struct be stored?
This question is a rephrased version of this deleted question. The user was deleted, so the question and answer went with it. I still found the idea interesting and the debugging result even more, so I chose to repeat it here.
About potential duplicates:

*

*this question creates an instance of a class. As mentioned, I understand that structs stored as part of objects are on the heap. My code does not create an instance of a class.

*this question leaves it open whether it's static or not, and the answer says "No, if you do that inside of Main, in general, it won't get allocated on the heap."

*this question has a great answer by Jon Skeet, which says that every new allocates space on the stack.

A: Perhaps you missed it: Eric Lippert has mentioned it in a side note:

[...] and static variables are stored on the heap.

That's written in the context of

The truth is that this is an implementation detail [...]
Here's how the Microsoft implementation does it:

But why are static variables stored on the heap?
Well, even the Main() method does not live forever. The Main() method could end and some other threads could still be running. What should happen in such a case to the struct? It needn't necessarily be on the heap, but I hope you see that it can't be on the stack and not in a register. The struct must be somewhere for other threads to still be able to access it. Heaps are a good choice.
Code example where Main() dies:
using System;
using System.Threading;

public class Program
{
    public static CustomStructType inst1;

    static void Main(string[] args)
    {
        new Thread(AccessStatic).Start();
        //assigning an instance of value type to the field
        inst1 = new CustomStructType();
        Console.WriteLine("Main is gone!");
    }

    static void AccessStatic()
    {
        Thread.Sleep(1000);
        Console.WriteLine(inst1);
        Console.ReadLine();
    }
}

public struct CustomStructType
{
    //body
}

Let's get back to your original code. When in doubt, you can always check with a debugger. This is a debug session of a Release build in .NET Framework 4.8 (4.8.4341.0).
I'm debugging with WinDbg Preview, which is a free debugger provided by Microsoft. It's not convenient to use, though. I learned about it from the book "Advanced .NET debugging" by Mario Hewardt.
I inserted a Console.ReadLine() for simplicity, so I don't need to step through everything and stop at the right time.
Load the .NET extension
ntdll!DbgBreakPoint:
77534d10 cc              int     3
0:006> .loadby sos clr

Search for an instance of Program (just to check whether the premise of the question is correct) indeed gives 0 objects:
0:007> !dumpheap -type Program
 Address       MT     Size

Statistics:
      MT    Count    TotalSize Class Name
Total 0 objects

Search for the class:
0:006> !name2ee *!Program
Module:      787b1000
Assembly:    mscorlib.dll
--------------------------------------
Module:      01724044
Assembly:    StructOnHeap.exe
Token:       02000002
MethodTable: 01724dcc
EEClass:     01721298            <--- we need this
Name:        Program

Get information about the class:
0:006> !dumpclass 01721298
Class Name:      Program
mdToken:         02000002
File:            C:\...\bin\Release\StructOnHeap.exe
Parent Class:    787b15c8
Module:          01724044
Method Table:    01724dcc
Vtable Slots:    4
Total Method Slots:  5
Class Attributes:    100001
Transparency:        Critical
NumInstanceFields:   0
NumStaticFields:     1
      MT    Field   Offset                 Type VT     Attr    Value Name
01724d88  4000001        4     CustomStructType  1   static 0431357c inst1
                                                            ^-- now this

Check where the garbage collected heaps are:
0:006> !eeheap -gc
Number of GC Heaps: 1
generation 0 starts at 0x03311018
generation 1 starts at 0x0331100c
generation 2 starts at 0x03311000
ephemeral segment allocation context: none
 segment     begin  allocated      size
03310000  03311000  03315ff4  0x4ff4(20468)
Large object heap starts at 0x04311000
 segment     begin  allocated      size
04310000  04311000  04315558  0x4558(17752)             <-- look here
Total Size:              Size: 0x954c (38220) bytes.
------------------------------
GC Heap Size:    Size: 0x954c (38220) bytes.

Yes, it's on the large object heap which starts at 0x04311000.
BTW: It was astonishing to me that such a small "object" (struct) will be allocated on the large object heap. Typically, the LOH will contain objects with 85000+ bytes only. But it makes sense, because the LOH is typically not garbage collected and you don't need to garbage collect static items.


text:
Q: How to fix UI deadlock on async WMI select/PerformanceCounter for getting remote machine LastBootUpTime I'm just creating Form aplication for controling remote workstations and servers on our company network and I have to create "Wait on restart of remote machine" function. This function is OK, but I need it to run asynchoniously and there is my problem...
The function check firstly online/offline status to determine restart and after that it is check new LastBootUpTime value of remote machine to be sure it was really restart and not only network problem.
When I run this check asynchroniously, ManagementObjectSearcher trigger deadlock, when using it's .Get() method. The same problem I have when I use PerformanceCounter instead.
There is 3 main objects for this:
1) Form class
2) Relation class (owned by Form)
3) RestartChecker class (owned by Relation)
When RestartChecker get info that restart was made, sends this info trough event to Relation. Relation use it's own event to sends it to Form and Form change icon on UI.
Here is my code (important parts) from RestartChecker:
This method is in Relation class and it's starts the RestartChecker. This Relation method is called from Form class.
    public void StartRestartMonitoring()
    {
        restartChecker = new RestartChecker(machine.Name, machine.OperatingSystem.lastBootUpTime.Value, wmiSuccess);

        //WasRestarted property calls event on value change to true. That event change icons on Form
        restartChecker.RestartWasMade += new Action(() => { WasRestarted = true; });

        restartChecker.Start();
    }

This method starts the check for restart function
Task checker;
CancellationTokenSource tokenSource;

    public void Start()
    {
        tokenSource = new CancellationTokenSource();
        CancellationToken token = tokenSource.Token;

        checker = CheckActionAsync(token);
        running = true;
    }

This is the more important part => Task method which should run asynchoniously
    private async Task CheckActionAsync(CancellationToken ct)
    {
        bool isOnline = await RemoteTask.PingAsync(target, PING_TIMEOUT_SECONDS);
        int onlineState = (isOnline) ? 0 : 1;

        try
        {
            lastKnownBootUpTime = (isOnline) ? (GetLastBootUpTime(target, useWMI) ?? lastKnownBootUpTime) : lastKnownBootUpTime;
        }
        catch (Exception ex)
        {
            //Logs to File
            EventNotifier.Log(ex,....);
        }

        //This part looks OK...
            while (onlineState < 2)
            {
                if (ct.IsCancellationRequested) { return; }

                bool actualOnlineState = await RemoteTask.PingAsync(target, PING_TIMEOUT_SECONDS);
                onlineState += (actualOnlineState == isOnline) ? 0 : 1;

                await Task.Delay(CHECK_INTERVAL);
            }

        while (!ct.IsCancellationRequested)
        {
            if (ct.IsCancellationRequested) { return; }

            //Here, until I get properly value for LastBootUpTime of remote machine, I'm still trying again and again (beacause first try is cannot be OK => machine is Online, but services for WMI is not ready yet, so there is exception on first try)
            while (newBootUpTime == null)
            {
                try
                {
                    newBootUpTime = GetLastBootUpTime(target, useWMI);
                }
                catch (Exception ex)
                {
                    //Some reactions to exception including logging to File
                }

                await Task.Delay(INTERVAL);
            }

            //This part looks ok too..
            newBootUpTime = newBootUpTime.Value.AddTicks(-newBootUpTime.Value.Ticks % TimeSpan.TicksPerSecond);
            lastKnownBootUpTime = lastKnownBootUpTime.Value.AddTicks(-lastKnownBootUpTime.Value.Ticks % TimeSpan.TicksPerSecond);

            if (newBootUpTime.Value > lastKnownBootUpTime.Value)
            {
                RestartWasMade?.Invoke();
                return;
            }

            await Task.Delay(CHECK_INTERVAL);
        }
    }

GetLastBoostUpTime method
    private static DateTime? GetLastBootUpTime(string target, bool useWMI)
    {
        DateTime? lastBootUpTime = null;

        if (useWMI)
        {
            //wmiBootUpTime is SelectQuery
            string dateInString = RemoteTask.SelectStringsFromWMI(wmiBootUpTime, new ManagementScope(string.Format("\\\\{0}\\root\\cimv2", target))).First()[wmiBootUpTime.SelectedProperties[0].ToString()];
            lastBootUpTime = (string.IsNullOrEmpty(dateInString)) ? null : (DateTime?)ManagementDateTimeConverter.ToDateTime(dateInString);
        }
        else
        {
            TimeSpan? osRunningTime = RemoteTask.GetUpTime(target);
            lastBootUpTime = (osRunningTime == null) ? null : (DateTime?)DateTime.Now.Subtract(osRunningTime.Value);
        }

        return lastBootUpTime;
    }

WMI method used for getting the data:
    public static List<Dictionary<string, string>> SelectStringsFromWMI(SelectQuery select, ManagementScope wmiScope)
    {
        List<Dictionary<string, string>> result = new List<Dictionary<string, string>>();
        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiScope, select))
        {
            //This line is deadlock-maker... Because remote machine  services is not ready yet, searcher.Get() is trying
            //until reach it's timeout (by default it is 30s) and that's my deadlock. For the time of running searcher.Get()
            //there is 30s deadlock. Where is the mistake I've made? I supposed that this can not confront my UI thread
            using (ManagementObjectCollection objectCollection = searcher.Get())
            {
                foreach (ManagementObject managementObject in objectCollection)
                {
                    result.Add(new Dictionary<string, string>());
                    foreach (PropertyData property in managementObject.Properties)
                    {
                        result.Last().Add(property.Name, property.Value?.ToString());
                    }
                }

                return result;
            }
        }
    }

PerformanceCounte method used for getting the data:
    public static TimeSpan? GetUpTime(string remoteMachine = null)
    {
        try
        {
            using (PerformanceCounter upTime = (string.IsNullOrWhiteSpace(remoteMachine))
                ? new PerformanceCounter("System", "System Up Time")
                : new PerformanceCounter("System", "System Up Time", null, remoteMachine))
            {
                upTime.NextValue();
                return TimeSpan.FromSeconds(upTime.NextValue());
            }
        }
        catch
        {
            return null;
        }
    }

Asynchronious ping method
    public async static Task<bool> PingAsync(string target, int pingTimeOut)
    {
        bool result = false;
        Exception error = null;

        using (Ping pinger = new Ping())
        {
            try
            {
                PingReply replay = await pinger.SendPingAsync(target, pingTimeOut * 1000);
                result = (replay.Status == IPStatus.Success) ? true : false;
            }
            catch (Exception ex)
            {
                error = ex;
            }
        }

        if (error != null) { throw error; }

        return result;
    }

A: I don't see deadlock here, but I see you block async method with sync call
newBootUpTime = GetLastBootUpTime(target, useWMI);
you can should call this in separate thread asynchronously I think or make GetLastBootUpTime method async
newBootUpTime = await Task.Run(() => GetLastBootUpTime(target, useWMI));
You also should remove all other sync blocking calls from your async methods using way above..
Deadlock may cause only if you call
checker.Wait(); somewhere in thread in which you created Task checker (UI thread probably)
Are you doing this?
Also you can read about what is deadlock and how to avoid it here
https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html


text:
Q: if i change extends Activity to OrmLiteBaseActivity i get an java.lang.NoClassDefFoundError i begin to develop for android and use the "ormlite" ORM-mapper (SQLite).
The Mapper has a OrmLiteBaseActivity Class, this extends from Activity. If i change "MainActivity extends Activity" to "MainActivity extends OrmLiteBaseActivity" the code compiled without errors. On the first access (MainActivity.class.getSimpleName()) to this class, i get a java.lang.NoClassDefFoundError.
I dont understand what is the problem.
Thank you, for helping.

A: I'm not 100% sure what the problem is but I suspect that your ORMLite jars are not in the libs subdirectory under your Android project.  This was changed in recent versions of the Google Eclipse plugin.
See this question: Getting a java.lang.NoClassDefFoundError for every jar file


text:
Q: Theme Inspector "X-Ray" I looked around and sadly didn't find anything answering this, and I'm almost 100% sure that it doesn't exist but I figured I'd ask this active community.
I work in a Rails environment as a Front-End Engineer, but I still do a fair amount of WP work on the side. In our Rails project we use a nifty gem called xray-rails (demo can be found on github.com/brentd/xray-rails) and I was wondering if anyone used anything fun to help expose what template is calling something on a screen, this seems like it'd be very helpful in child themes.


text:
Q: If parent has class add class to other div I need to add a class to an img element (for an animation) if the parent of 'image-reveal-check' has an active class, how do I do this?
Clarification: The parent class does not always have 'active', that class is added when the element gets in the viewport.
HTML

jQuery
if ($(".image-reveal-check").parent().hasClass('active')) {
    $(".image-reveal-inner img").addClass('image-reveal-start');
}

A: Try this one it's working. You can check the output on Code Snippet.

$( document ).ready(function() {
console.log( "ready!" );
if ($(".image-reveal-inner").parent().hasClass('image-reveal-check')) {
 $(".image-reveal-inner img").addClass('image-reveal-start-add');
 console.log( "done!" );
}
});

        ASD

A: You can trigger the event explicitly when the active class added to the div.
Here I've added with a button click, in your case you can do when the element gets added in the viewport.

$("#addClassActive").click(function() {

//Here on button click the active class is added to div. For your case this needs to be called when the element added to the viewport
    $('.image-reveal-check').parent().addClass('active').trigger('classChange');
});

$('div:eq(0)').on('classChange', function() { //finding the root div and finding img and adding the desired class
     $(this).find("img").addClass("image-reveal-start")
});
.image-reveal-start
{
 border: solid 1px red;
 width: 50px;
 height: 50px;

}

            <button id="addClassActive">Add Class</button>

A: You could achieve that without the use of JS at all, just add a rule to your CSS code like :
div.active .image-reveal-inner img { }

The example below shows how the first image with a parent that has active class will be animated with the rule and not the second that has no active class on the parent div.

div.active .image-reveal-inner img {
  position: relative;
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s normal ease-out;
}

@-webkit-keyframes floatBubble {
  0% {
    right: 300px;
  }
  100% {
    right: 0px;
  }
}

@keyframes floatBubble {
  0% {
    right: 300px;
  }
  100% {
    right: 0px;
  }
}


text:
Q: ES6 class behaves differently in ExpressJS? Why does a class behave differently in ExpressJS? For an example:
With expressJS
lib/Polygon.js:
class Polygon {

    log (req, res) {
        var publicKey = req.params.publicKey;
        var query = req.query;
        console.log(this); // undefined

        var output = {
            publicKey :publicKey,
            query: query
        };
        res.send(output);
    }
}

export {Polygon as default}

app.js:
import express from 'express';
import Polygon from './lib/Polygon';

var polygon = new Polygon();
app.get('/input/:publicKey', polygon.log);

Without expressJS
lib/Polygon.js:
class Polygon {
   log(req, res) {
        console.log(this); // Polygon {}
    }
}

export { Polygon as default}

app.js:
import Polygon from 'Polygon';

var p = new Polygon();

p.log('world')

How can I get console.log(this); undefined to return Polygon {} in expressjs?

A: In the second code snippet the log function is called as a member of the p object and this is why this refers to the object. This is not the case in the first code snippet as you are passing the method to another function and the method is detached from the object. You can explicitly set the this value by using bind method:
app.get('/input/:publicKey', polygon.log.bind(polygon));

A: In the first case you are directly passing the function hence you wont get this as the polygon object
Use
app.get('/input/:publicKey', polygon.log.bind(polygon));

In the second case you are using
p.log('world')

here log function will be called and this would be the polygon.


text:
Q: Docker Swarm: Getting connection refuse while adding worker node I just started learning docker, I am facing below challenge, please let me know where I am doing wrong.
My use case: Set up docker swarm manager and add worker node to it.
Step1: To create docker manager, I used below command:
docker swarm init --advertise-addr <<ip_address>>

Step 2: Run below command, which gives you docker command to add worker.
docker swarm join-token worker

After running above command, I got output as:
docker swarm join --token SWMTKN-1-653srs28a6s48dqxnak9g9kic2cd1xyeowgnke53nf83710wfv-7u7u7u1vovahvn792814q2sts ip_address:2377

Step3: I logged-in to worker node and ran above docker swarm join command. But I am getting below error message.
Error response from daemon: rpc error: code = Unavailable desc = all SubConns are in TransientFailure, latest connection error: connection er
ror: desc = "transport: Error while dialing dial tcp ip_address:2377: connect: connection refused"

A: This could well be a firewall issue, make sure you have port 2377, 7946 & 4789 in open state between the hosts acting as manager or worker node -
From the docs -

Open protocols and ports between the hosts The following ports must be
  available.
TCP port 2377 for cluster management communications
  TCP and UDP port 7946 for communication among nodes
  UDP port 4789 for overlay network
  traffic


text:
Q: How to achieve Listview design on flutter I want to create a listview item design something like
Click here
and which I have tried so far is Click here
Here is my code
ListTile(
                leading: ConstrainedBox(
                    constraints: BoxConstraints(
                      minWidth: 44,
                      minHeight: 44,
                      maxWidth: 64,
                      maxHeight: 64,
                    ),
                    child: Image.network(catData[index]['icon'].toString(),
                      width: 150,
                      height: 150,
                      fit: BoxFit.cover,
                      headers: headersMap,
                    )
                    ),
                title: Padding(
                  padding: EdgeInsets.only(left: 10,bottom: 5, right: 10, top: 10),
                  child: Text(
                    getCategoryName(catData, index),
                    style: TextStyle(
                        fontWeight: FontWeight.w500,
                        fontSize: 20,
                        fontFamily: 'Mada-Medium',
                        letterSpacing: 0.25,
                    ),
                    maxLines: 3,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                subtitle: Padding(
                    padding: EdgeInsets.only(left: 10,bottom: 5, right: 10),
                    child: Text(
                      getText(catData[index]['catId'], subCatData),
                      style: TextStyle(
                          color: parseColor('##A2A2A2'),
                          letterSpacing: 0.25,
                          fontSize: 14,
                          fontFamily: 'Mada',
                          fontWeight: FontWeight.w500),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    )

                    ),
              )

The image portion is not setting properly on listTile title. Please help to create this design

A: Try this
class ListItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(10.0),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.all(Radius.circular(20.0))),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.0), bottomLeft: Radius.circular(20.0)),
            child: Image.asset(
              'assets/images/nilesh.jpg',
              fit: BoxFit.cover,
              height: 120,
              width: 100,
            ),
          ),
          SizedBox(width: 20),
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
//            mainAxisAlignment: MainAxisAlignment.spaceAround,
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              SizedBox(height: 20),
              Text(
                'Dummy Text',
                style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 30),
              Text(
                'Dummy Text',
                style: TextStyle(color: Colors.grey, fontWeight: FontWeight.normal),
              ),
            ],
          ))
        ],
      ),
    );
  }
}

OUTPUT


text:
Q: How do I plot the time-series for each time-point treatment of each patient? I want to plot a time-series for each patient, where the substring after the first underscore _ is the patient ID. I also want the time points in chronological order, meaning the substring prior to the first underscore _ must be plotted in ascending order.
import plotly.express as px
import numpy as np
import pandas as pd

# Treatment variables
hours = treatment_info.columns + "h"
patient_id = treatment_info.loc["Patient ID"]
time = treatment_info.loc["Time"]
time_cluster = treatment_info.loc['Time Cluster'].str.replace('Cluster ', 'TimeC') # TimeC = Time Cluster
patient_id_cluster = treatment_info.loc["Patient ID Cluster"].str.replace("Cluster ", "PIDC") # PIDC = Patient ID Cluster
survival = treatment_info.loc["Survivor/Non-Survivor"]

# Append all the treatment variables to assign new column names for the treatment columns, separated with "_"
treatment_col = hours + "_" +  patient_id + "_" + time + "_" + time_cluster + "_" + patient_id_cluster + "_" + survival

# Controls

pos_neg_ctl_df = df.loc[((df["mrna_assignment"].str.contains("pos_control")) | (df["mrna_assignment"].str.contains("neg_control"))),:]

probe_ctl_df = df.loc[((df["category"].str.contains("control->affx")) | (df["category"].str.contains("control->bgp->antigenomic"))),:]

Here, for each patient patient_id, I want to find the difference in hours of treatment. All the patients in one plot.
for patient_id in hsp_treatment_df.index.split('_')[1]:
  for hours in hsp_treatment_df.index.split('_')[0]:
    fig = px.line(df, x="patient_id", y="Gene Expression", title="Time-Series Treatment Analysis for Each Patient")
    fig.show()

Traceback:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-93-1a74154283c4> in <module>()
      2 ## Get the patient ID from each column
      3
----> 4 for patient_id in hsp_treatment_df.index.split('_')[1]:
      5   for hours in hsp_treatment_df.index.split('_')[0]:
      6     fig = px.line(df, x="patient_id", y="Gene Expression", title="Time-Series Treatment Analysis for Each Patient")

AttributeError: 'Index' object has no attribute 'split'

Dataframe as dictionary:
hsp_treatment_df[1:3].to_dict()
{'0h_P1_T1_TimeC1_PIDC4_Non-Survivor': {'DNAJC14': '8.44', 'DNAJC30': '7.34'},
 '0h_P2_T1_TimeC2_PIDC2_Survivor': {'DNAJC14': '8.34', 'DNAJC30': '7.42'},
 '0h_P3_T1_TimeC1_PIDC1_Survivor': {'DNAJC14': '8.67', 'DNAJC30': '7.15'},
 '0h_P4_T1_TimeC1_PIDC1_Survivor': {'DNAJC14': '8.63', 'DNAJC30': '7.46'},
 '0h_P5_T1_TimeC4_PIDC3_Survivor': {'DNAJC14': '8.32', 'DNAJC30': '7.29'},
 '12h_P1_T4_TimeC2_PIDC4_Non-Survivor': {'DNAJC14': '8.64', 'DNAJC30': '7.2'},
 '12h_P2_T4_TimeC3_PIDC2_Survivor': {'DNAJC14': '8.38', 'DNAJC30': '7.32'},
 '12h_P3_T4_TimeC2_PIDC1_Survivor': {'DNAJC14': '8.57', 'DNAJC30': '7.32'},
 '12h_P4_T4_TimeC2_PIDC2_Survivor': {'DNAJC14': '8.25', 'DNAJC30': '6.98'},
 '12h_P5_T4_TimeC2_PIDC3_Survivor': {'DNAJC14': '8.25', 'DNAJC30': '7.38'},
 '24h_P1_T5_TimeC4_PIDC4_Non-Survivor': {'DNAJC14': '8.43', 'DNAJC30': '7.41'},
 '24h_P2_T5_TimeC3_PIDC2_Survivor': {'DNAJC14': '8.54', 'DNAJC30': '7.26'},
 '24h_P3_T5_TimeC3_PIDC1_Survivor': {'DNAJC14': '8.42', 'DNAJC30': '7.25'},
 '24h_P4_T5_TimeC3_PIDC2_Survivor': {'DNAJC14': '8.6', 'DNAJC30': '6.93'},
 '24h_P5_T5_TimeC3_PIDC3_Survivor': {'DNAJC14': '8.14', 'DNAJC30': '7.52'},
 '48h_P1_T6_TimeC3_PIDC1_Non-Survivor': {'DNAJC14': '8.27', 'DNAJC30': '7.46'},
 '48h_P2_T6_TimeC3_PIDC3_Survivor': {'DNAJC14': '8.23', 'DNAJC30': '7.45'},
 '48h_P3_T6_TimeC3_PIDC1_Survivor': {'DNAJC14': '8.65', 'DNAJC30': '6.77'},
 '48h_P4_T6_TimeC3_PIDC2_Survivor': {'DNAJC14': '8.7', 'DNAJC30': '7.28'},
 '48h_P5_T6_TimeC3_PIDC3_Survivor': {'DNAJC14': '8.21', 'DNAJC30': '7.56'},
 '4h_P1_T2_TimeC1_PIDC4_Non-Survivor': {'DNAJC14': '8.69', 'DNAJC30': '7.53'},
 '4h_P2_T2_TimeC2_PIDC1_Survivor': {'DNAJC14': '8.47', 'DNAJC30': '7.41'},
 '4h_P3_T2_TimeC2_PIDC1_Survivor': {'DNAJC14': '8.38', 'DNAJC30': '7.29'},
 '4h_P5_T2_TimeC2_PIDC3_Survivor': {'DNAJC14': '8.1', 'DNAJC30': '7.47'},
 '8h_P1_T3_TimeC4_PIDC4_Non-Survivor': {'DNAJC14': '8.58', 'DNAJC30': '7.29'},
 '8h_P2_T3_TimeC2_PIDC2_Survivor': {'DNAJC14': '8.13', 'DNAJC30': '7.58'},
 '8h_P3_T3_TimeC4_PIDC1_Survivor': {'DNAJC14': '8.44', 'DNAJC30': '7.38'},
 '8h_P4_T3_TimeC4_PIDC1_Survivor': {'DNAJC14': '8.53', 'DNAJC30': '7.32'},
 '8h_P5_T3_TimeC4_PIDC3_Survivor': {'DNAJC14': '8.41', 'DNAJC30': '7.28'}}


text:
Q: Echoing a command, then running it - fails on piped commands? I have an environment setup script where I want to alert the user as to what commands I'm executing (i.e. what is being installed). Using set -x makes the output too cluttered, so I have a function successfully that's called on commands that are important:
#!/bin/bash
trap "exit 1" TERM
export TOP_PID=$$

real_exit() {
  echo -e "Goodbye :'("
  kill -s TERM $TOP_PID
}

successfully() {
  echo -e "$*"
  $* || (echo -e "\nFailed. Check output and then retry, please." 1>&2 && real_exit)
}

For example, I can call successfully brew update in my script, and if it fails, the user knows what command it fails on and the script stops.
However, my script is failing when I try to install Ruby/RVM:
successfully "curl -L https://get.rvm.io | bash -s stable --ruby"

The curl command works fine when I call it from the command line, yet it fails when the script calls it with the error:
curl -L https://get.rvm.io | bash -s stable --ruby
curl: option --ruby: is unknown
curl: try 'curl --help' or 'curl --manual' for more information

A: You would need to use eval, but it's not recommended.
successfully() {
    echo -e "$1"
    eval "$1" || (echo -e "\nFailed. Check output and then retry, please." 1>&2 && real_exit)
}

Also send SIGHUP instead of SIGTERM:
  kill -s SIGHUP "$TOP_PID"

You could use a safe variation like this as well:
successfully() {
    local __A=() __I
    for (( __I = 1; __I <= $#; ++__I )); do
        if [[ "${!__I}" == '|' ]]; then
            __A+=('|')
        else
            __A+=("\"\$$__I\"")
        fi
    done
    echo "$@"
    eval "${__A[@]}" || (echo -e "\nFailed. Check output and then retry, please." 1>&2 && real_exit)
}

Example:
successfully curl -L https://get.rvm.io \| bash -s stable --ruby  ## You just have to quote pipe.


text:
Q: Decrypt files recovered from encrypted external hard drive I am trying to recover the data from one of the external hard drives of my company. I ended up using DiskDrill to extract all the files into a new, non-encrypted hard drive. Unfortunately I made the mistake of erasing the original hard drive before properly checking the exported data... :/
If I look at the recovered data, all the file structures and file sizes seem correct. But if I try to open any file I get a system error saying:

"The document "File.rtf" could not be opened."

I used cat to check the content of the file, and from the outcome it looks to me like it's still encrypted:

|?!?z?n;?AԒ??Ћ???f??Y?-?bA?-??ۚw?5?vc?D???yr????l?&yg?????U#
  ????F?????l??
  ??ٔ=??S?????#t????v:??#?˰wDZ$??y>?n??y??C?j??,???WI?L?[?a??CC?
  P?U?>K?l?Ե???????OH?[Ẉ[Y?'^k?*?mDћ)?,0?Ի;
  ??^?\dW?|?`??=?c6&-~?\?YT+3w?4d?'?F@???D???G(?$??>??+?҃?6?t????p?M?wC[?:?$d1?{?Ϊ?.???~KW?r??Q?6??
  o@???u???
  ?B|?[[??>/%???$??[;?z?h?!???O??dn??;?"?GZ?v?{W?B???[???P?d?!????d??Q?@?mG??/?|?x?_???H%)?v?Z??$?]????F??>?"????!U?rFl???
  ?GB2?W0Iy??]??|x??]X??aN[??????WJ??????l B??噡g?ہ'I???^}Yk>??Ǘ

The command:
file -  /Users/Cortana/Desktop/File.rtf

Returns:

application/octet-stream; charset=binary

The original disk was encrypted using FileVault. I do know the original password.
Is there any command I can run in terminal (or anything else really) that I can do to recover my data. I'm not an expert at unix so please explain it to me like I'm 5.
Thank you,
Danny

A: Unfortunately, you cannot recover the data.
From Apple's Support document:  Use FileVault to encrypt the startup disk on your Mac

If you lose both your account password and your FileVault recovery
  key, you won't be able to log in to your Mac or access the data on
  your startup disk.


text:
Q: Mongodb $lookup query using PHP driver not working
I want to get data from two collections where there is a common field
  between this two collections.I am giving both queries for Mongo and
  PHP. My PHP version is PHP 5.6.31-1~ubuntu14.04.1+deb.sury.org+1 (cli)
  My mongo db query for between two collections:

db.dental_refset.aggregate(
[
    {   $lookup:
        {
            from:"v20170731",
            localField:"referencedComponentId",
            foreignField:"conceptId",
            as:"joinedData"
        }
    }

])

I am ding this in php and my code is below:
error_reporting(1);
require 'driver/vendor/autoload.php';
$client = new MongoDB\Client("mongodb://192.168.2.95:27017");
$collection = $client->selectDatabase('en-edition')->selectCollection("dental_refset");
$ops = array(
    array(
        "$lookup" => array(
            "from" => "v20170731",
            "localField" => "referencedComponentId",
            "foreignField" => "conceptId",
            "as" => "user_docs"
        )
    )
);
$results = $collection->aggregate($ops);
print_r($collection);

But error occurs. Error has given below:
Uncaught MongoDB\Driver\Exception\RuntimeException: Invalid filter: empty
  key in
  /var/www/html/mednxtMod/mednxt/driver/vendor/mongodb/mongodb/src/Operation/Aggregate.php:223\nStack
  trace:\n#0
  /var/www/html/mednxtMod/mednxt/driver/vendor/mongodb/mongodb/src/Operation/Aggregate.php(223):
  MongoDB\Driver\Server->executeCommand('en-edition',
  Object(MongoDB\Driver\Command),
  Object(MongoDB\Driver\ReadPreference))\n#1
  /var/www/html/mednxtMod/mednxt/driver/vendor/mongodb/mongodb/src/Collection.php(215):
  MongoDB\Operation\Aggregate->execute(Object(MongoDB\Driver\Server))\n#2
  /var/www/html/mednxtMod/mednxt/error.php(19):
  MongoDB\Collection->aggregate(Array)\n#3 {main}\n  thrown in
  /var/www/html/mednxtMod/mednxt/driver/vendor/mongodb/mongodb/src/Operation/Aggregate.php
  on line 223Uncaught

A: Use single quote for '$lookup' or escape it "\$lookup", or PHP will treat it as a variable, which is undefined/empty

A: This is working with use of toArray();
error_reporting(1);
    $collection = $this->mongo->your_db->admin;
    $ops = array(

        array(
            '$lookup' => array(
                "from" => "users",
                "localField" => "id",
                "foreignField" => "user_id",
                "as" => "inventory_docs"
            )
        )

    );
    $results = $collection->aggregate($ops)->toArray();
    echo "<pre>";    print_r($results);exit;


text:
Q: How to remove elements from map if it reaches a memory size limit? I have implemented a LRU cache using ConcurrentLinkedHashMap. In the same map, I am purging events if my map reaches a particular limit as shown below.
I have a MAX_SIZE variable which is equivalent to 3.7 GB and as soon as my map reaches that limit, I am purging events from my map.
Below is my code:
import java.util.concurrent.ConcurrentMap;
import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
import com.googlecode.concurrentlinkedhashmap.EvictionListener;

// does this really equal to 3.7 GB? can anyone explain this?
public static final int MAX_SIZE = 20000000; //equates to ~3.7GB with assumption that each event is 200 bytes AVG

public static EvictionListener<String, DataObject> listener = new EvictionListener<String, DataObject>() {
    public void onEviction(String key, DataObject value) {
        deleteEvents();
    }
};
public static final ConcurrentMap<String, DataObject> holder = new ConcurrentLinkedHashMap.Builder<String, DataObject>()
            .maximumWeightedCapacity(MAX_SIZE).listener(listener).build();

private static void deleteEvents() {
    int capacity = MAX_SIZE - (MAX_SIZE * (20 / 100));
    if (holder.size() >= capacity) {
        int numEventsToEvict = (MAX_SIZE * 20) / 100;
        int counter = 0;
        Iterator<String> iter = holder.keySet().iterator();
        while (iter.hasNext() && counter < numEventsToEvict) {
            String address = iter.next();
            holder.remove(address);
            System.out.println("Purging Elements: " +address);
            counter++;
        }
    }
}

// this method is called every 30 seconds from a single background thread
// to send data to our queue
public void submit() {
    if (holder.isEmpty()) {
        return;
    }

    // some other code here

    int sizeOfMsg = 0;
    Iterator<String> iter = holder.keySet().iterator();
    int allowedBytes = MAX_ALLOWED_SIZE - ALLOWED_BUFFER;

    while (iter.hasNext() && sizeOfMsg < allowedBytes) {
        String key = iter.next();
        DataObject temp = holder.get(key);

        // some code here

        holder.remove(key);

        // some code here to send data to queue
    }
}

// this holder map is used in below method to add the events into it.
// below method is being called from some other place.
public void addToHolderRequest(String key, DataObject stream) {
    holder.put(key, stream);
}

Below is the maven dependency I am using for this:
<dependency>
    <groupId>com.googlecode.concurrentlinkedhashmap</groupId>
    <artifactId>concurrentlinkedhashmap-lru</artifactId>
    <version>1.4</version>
</dependency>

I am not sure whether this is the right way to do this? Does this MAX_SIZE really equates to 3.7 GB if events are of 200 bytes in average? Is there any better way to do this? I also have a background thread which call deleteEvents() method every 30 second and same background thread also calls submit method to extract data from holder map and send to queue.
So idea is, add events to holder map in addToHolderRequest method and then from the background every 30 second call submit method which will send data to our queue by iterating this map and then after submit method is finished, call deleteEvents() method from same background thread which will purge elements. I am running this code in production and it looks like it is not purging events properly and my holder map size keeps growing. I have a min/max heap memory set as 6GB.

A: *

*In lieu of estimating the size of objects in the JVM and referencing them using strong references you can use soft references which are "most often used to implement memory-sensitive caches" (SoftReference). e.g. CacheBuilder.softValues() from google/guava: Google Core Libraries for Java 6+: "Softly-referenced objects will be garbage-collected in a globally least-recently-used manner, in response to memory demand." However, I'd recommend first familiarizing yourself with CachesExplained · google/guava Wiki (specifically the Reference-based Eviction section).

*As a tweak to using soft references you can also try a "victim caching approach" as described here which uses a "normal cache that evicts to [a] soft cache, and recovers entries on a miss if possible".

*If you are certain you want to actually estimate the size of objects then take a look at Ehcache and its Sizing Storage Tiers. It has Built-In Sizing Computation and Enforcement for memory-limited caches.


text:
Q: git diff and git difftool do nothing and give no output I am trying to get git diff to work on Windows 7 64 bit. When I run the following commands from a windows command prompt:
C:\temp\mygrit>git diff

or
C:\temp\mygrit>git difftool

I get no output and no external program launches. Here is my .gitconfig file:
[diff]
    tool = bc3
[difftool]
    prompt = false
[difftool "bc3"]
    cmd = \"c:/program files (x86)/beyond compare 3/bcomp.exe\" \"$LOCAL\" \"$REMOTE\"

I get the same results if I remove all these lines from .gitconfig.
Any idea what's going on?

A: OK, simple answer. The default behaviour for git diff is to show the all files which have been modified but not staged. If you have no modified files then there is no output.
git difftool uses the output of git diff so if there's no output from the previous command git difftool will do nothing as well.
Solution: Change some files but don't stage them, re run the commands. If there are problems with your config file they will show up then.


text:
Q: how to check and show error if same data exists as array in firestore The code which i write  for storing data stores data in firestore as an array .
Problem is
1)if same user enter same name twice it overwrites them
2)if mulpile users enter same name it stores in firestore.
So I want to show error if same name is enter either by same user or multiple users.
How to do this query.please help
for more understanding . let a user with phone number 6458935467 enters name as "beautiful" so second time he enters the same name in the edittext there is no change in firestore . but let another user with phone number 7638956478 enters name as "beautiful" but this time firestore add this name even though previous user already enter this name..
so I want to make user sure that there is no duplicate entries made by them.
I want to check if same name is there in firestore by any of the user and show error before they proceed
below is the method I use to store and update the names in arrays in firestore
mainActivity
    private void storeNewUserData() {

                //to get user phone number
                SharedPreferences preferences = getSharedPreferences(mypreferences, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                String a = (preferences.getString("phoneNo", ""));

                TextInputLayout ig_name;
                ig_name = findViewById(R.id.ig_name);

                String name = Objects.requireNonNull(ig_name.getEditText()).getText().toString().trim();
                final Map<String, Object> addUserToArrayMap = new HashMap<>();
                addUserToArrayMap.put("Name", FieldValue.arrayUnion(name));

                //updating name of existing array field
                firebaseFirestore
                        .collection("Note")
                        .document(a)
                        .update(addUserToArrayMap)
                        .addOnCompleteListener((Task<Void> task) -> {
                            if (task.isSuccessful()) {

                                Toast.makeText(getApplicationContext(), "successfully entered", Toast.LENGTH_SHORT).show();
                                intent = new Intent(getApplicationContext(), secondActivity.class);
                                startActivity(intent);
                                finish();

                            }
                        })
                        .addOnFailureListener(error -> {

                           //adding name in firestore as array field if no field exists
                            firebaseFirestore
                                    .collection("Note")
                                    .document(a)
                                    .set(addUserToArrayMap)
                                    .addOnSuccessListener(aVoid -> {

                                        Toast.makeText(getApplicationContext(), "successfully entered", Toast.LENGTH_SHORT).show();
                                        intent = new Intent(getApplicationContext(), secondActivity.class);
                                        startActivity(intent);
                                        finish();

                                    })
                                    .addOnFailureListener(e2 ->
                                            Log.w(TAG, "Error writing document", e2));
                            editor.apply();
                        });
            }


text:
Q: Printing out random images form an array I have created an array which contains 2 images, I want to show these images randomly (so one shows then when the page is refreshed a different show, etc) I have re-used code i used a long time ago and it doesn't seem to be working could someone help me with where i am going wrong please.
<?php
$images = array(
            '',
            ''
        );

    shuffle($images); // Randomize images array;
    ?>

<?php echo "

I believe it is how i am trying to echo ut the Image but everything i try i keep getting this error message
Parse error: syntax error, unexpected ';' in /home/domain/public_html/app/design/frontend/base/default/template/checkout/success.phtml on line 42
Line 42 is where the echo is
Thank you in advance

A: Here's a way that you can not only make it random, but you can make it dynamic so it automatically adjusts if you choose to add more images to the array.
$i = mt_rand(0, count($images));

src=$images[$i]

Note that doing it this way you do not need to shuffle the array. Also, you just need the img url's in the array, not the rest of the html.

A: First off your array values contain html markup so the value you are echoing  would be all of that html markup inside of the img tag. Second you are using single quotes around your $images array which whould tell php to print out $images[] instead of the value of the array. Third when you are echoing the array you are not giving an index value. The following code should work assuming you are wanting to leave the html markup inside the array:
<?php echo $images[0];?>

A: <?php
$images = array(
            '',
            ''
        );

    shuffle($images); // Randomize images array;
    ?>

<?php
 echo $images[0];
?>

Try this one.

A: <?php
$images = array(
            '',
            ''
        );

    ?>

<?php
echo $images[shuffle($images)];
?>

Single quotes force the string to be evaluated as a string and variable values will not be used.  Use single quotes around special characters then you won't have to escape them.


text:
Q: Script runs great in VSCode, but hangs in Powershell ISE and command prompt I have a script that is on the complex side. It registers an objectevent and has a bunch of embedded C# code.
It works great in the VSCode debugger
But in both the Powershell ISE and a powershell command prompt, it hangs part way through running the action in the objectevent.
From some other threads with a similar smell, I have confirmed that all three powershell run time environments (VSCode debugger, Powershell cmd prompt and Powershell ISE) all are running in STA mode:
    PS C:\Users\sam> [System.Threading.Thread]::CurrentThread.GetApartmentState()

STA

All three enviroments report the following version information:
PS C:\Users\sam> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.22000.282
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.22000.282
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

What is the delta in these environments that I should chase?


text:
Q: show items in a list like email how do I display a list of items on the screen, like how email is displayed on the screen?

What is this controller called?

A: It is a UITableView. Check the Table View Programming Guide and Table View Suite code sample by apple.


text:
Q: ListBox style in WPF - MouseLeave and UnSelect fadeout I'm styling a listbox to have some effects like MouseLeave and UnSelect fadeout.
It works when no item selected. But once some items are selected one by one, effects not working for them anymore! even if they're not selected.
Ideal behavior is when, items behave constantly in response to events and property changes.
I want to have List Box items that respond to MouseOver and MouseLeave events when they're not selected, and respond to Unselect property change.
Resourse Dictionary:
<ResourceDictionary>
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Color x:Key="DisabledControlLightColor-LS1">#FFE8EDF9</Color>
    <Color x:Key="SelectedBackgroundColor-LS1">#FFC5CBF9</Color>
    <Color x:Key="MouseOverBackgroundColor-LS1">#FFE5E9F7</Color>
    <Color x:Key="SelectedUnfocusedColor-LS1">#FFDDDDDD</Color>
    <Color x:Key="UnSelectedBackgroundColor-LS1">#00C5CBF9</Color>
    <Color x:Key="ControlLightColor-LS1">White</Color>
    <Color x:Key="ControlMediumColor-LS1">#FF7381F9</Color>
    <Color x:Key="BorderMediumColor-LS1">#FF888888</Color>
    <Color x:Key="DisabledBorderLightColor-LS1">#FFAAAAAA</Color>
    <SolidColorBrush x:Key="ListBorder" Color="#828790"/>
<Style x:Key="LS1-MS" TargetType="ListBox">
        <Setter Property="ItemContainerStyle" Value="{DynamicResource LSItem-LS1}"/>
        <Setter Property="SnapsToDevicePixels" Value="true" />
        <Setter Property="OverridesDefaultStyle" Value="true" />
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" />
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
        <Setter Property="ScrollViewer.CanContentScroll" Value="true" />
        <Setter Property="MinWidth" Value="120" />
        <Setter Property="MinHeight" Value="95" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBox">
                    <Border Name="Border" BorderThickness="1" CornerRadius="2">
                        <Border.Background>
                            <SolidColorBrush Color="{StaticResource ControlLightColor-LS1}" />
                        </Border.Background>
                        <Border.BorderBrush>
                            <SolidColorBrush Color="{StaticResource BorderMediumColor-LS1}" />
                        </Border.BorderBrush>
                        <ScrollViewer Margin="0" Focusable="false">
                            <StackPanel Margin="2" IsItemsHost="True" />
                        </ScrollViewer>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter TargetName="Border" Property="Background">
                                <Setter.Value>
                                    <SolidColorBrush Color="{StaticResource DisabledControlLightColor-LS1}" />
                                </Setter.Value>
                            </Setter>
                            <Setter TargetName="Border" Property="BorderBrush">
                                <Setter.Value>
                                    <SolidColorBrush Color="{DynamicResource DisabledBorderLightColor-LS1}" />
                                </Setter.Value>

                            </Setter>
                        </Trigger>
                        <Trigger Property="IsGrouping" Value="true">
                            <Setter Property="ScrollViewer.CanContentScroll" Value="false" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style x:Key="LSItem-LS1" TargetType="ListBoxItem">
        <Setter Property="SnapsToDevicePixels"
          Value="true" />
        <Setter Property="OverridesDefaultStyle"
          Value="true" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <ControlTemplate.Resources>
                        <Storyboard x:Key="MouseEnterBC">
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0" Value="{StaticResource MouseOverBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0" Value="{StaticResource UnSelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                        <Storyboard x:Key="MouseLeaveFadeOut">
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="{StaticResource UnSelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="{StaticResource UnSelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                        <Storyboard x:Key="SelectBC">
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0" Value="{StaticResource SelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0" Value="{StaticResource UnSelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                        <Storyboard x:Key="unSelectBcFadeOut">
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="{StaticResource UnSelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="{StaticResource UnSelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                    </ControlTemplate.Resources>
                    <Border x:Name="Border" Padding="1" SnapsToDevicePixels="true" BorderThickness="1">
                        <Border.Background>
                            <SolidColorBrush Color="{DynamicResource UnSelectedBackgroundColor-LS1}"/>
                        </Border.Background>
                        <Border.BorderBrush>
                            <SolidColorBrush Color="{DynamicResource UnSelectedBackgroundColor-LS1}"/>
                        </Border.BorderBrush>

                        <ContentPresenter />
                    </Border>

                    <ControlTemplate.Triggers>

                        <Trigger Property="IsMouseOver" Value="True">
                            <Trigger.ExitActions>
                                <BeginStoryboard x:Name="MouseLeaveFadeOut_BeginStoryboard3" Storyboard="{StaticResource MouseLeaveFadeOut}"/>
                            </Trigger.ExitActions>
                            <Trigger.EnterActions>
                                <BeginStoryboard x:Name="MouseLeaveFadeOut_BeginStoryboard" Storyboard="{StaticResource MouseEnterBC}"/>
                            </Trigger.EnterActions>
                        </Trigger>

                        <EventTrigger RoutedEvent="Selector.Selected">
                            <BeginStoryboard x:Name="SelectBC_BeginStoryboard2" Storyboard="{StaticResource SelectBC}"/>
                        </EventTrigger>

                        <EventTrigger RoutedEvent="Selector.Unselected">
                            <BeginStoryboard x:Name="MouseLeaveFadeOut_BeginStoryboard1" Storyboard="{StaticResource MouseLeaveFadeOut}"/>
                            <StopStoryboard BeginStoryboardName="SelectBC_BeginStoryboard2"/>
                        </EventTrigger>

                    </ControlTemplate.Triggers>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

MainWindow.Xaml
<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <ListBox Style="{DynamicResource LS1-MS}" Margin="42,10,72,10">
        <ListBoxItem FlowDirection="RightToLeft" Content="Test List Box Items"/>
        <ListBoxItem Content="Test List Box Items"/>
        <ListBoxItem FlowDirection="RightToLeft" Content="Test List Box Items"/>
        <ListBoxItem FlowDirection="RightToLeft" Content="Test List Box Items"/>
        <ListBoxItem FlowDirection="RightToLeft" Content="Test List Box Items"/>
        <ListBoxItem FlowDirection="RightToLeft" Content="Test List Box Items"/>
        <ListBoxItem Content="Test List Box Items"/>
        <ListBoxItem Content="Test List Box Items"/>
        <ListBoxItem Content="Test List Box Items"/>
    </ListBox>

</Grid>

A: You are never stopping the storyboards, so eventually they are all running.I have added file FillBehavior="Stop" in storyboard.You can set the FillBehavior of the Storyboards to Stop so that the Storyboard will stop setting the value after it completes.
    <Style x:Key="LSItem-LS1" TargetType="ListBoxItem">
        <Setter Property="SnapsToDevicePixels" Value="true" />
        <Setter Property="OverridesDefaultStyle" Value="true" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <ControlTemplate.Resources>
                        <Storyboard x:Key="MouseEnterBC">
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0" Value="{StaticResource MouseOverBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0" Value="{StaticResource UnSelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                        <Storyboard x:Key="MouseLeaveFadeOut" FillBehavior="Stop">
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="{StaticResource UnSelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="{StaticResource UnSelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                        <Storyboard x:Key="SelectBC">
                            <ColorAnimationUsingKeyFrames  Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0" Value="{StaticResource SelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0" Value="{StaticResource UnSelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                        <Storyboard x:Key="unSelectBcFadeOut" FillBehavior="Stop">
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="{StaticResource UnSelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
                                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="{StaticResource UnSelectedBackgroundColor-LS1}"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                    </ControlTemplate.Resources>
                    <Border x:Name="Border" Padding="1" SnapsToDevicePixels="true" BorderThickness="1">
                        <Border.Background>
                            <SolidColorBrush Color="{DynamicResource UnSelectedBackgroundColor-LS1}"/>
                        </Border.Background>
                        <Border.BorderBrush>
                            <SolidColorBrush Color="{DynamicResource UnSelectedBackgroundColor-LS1}"/>
                        </Border.BorderBrush>

                        <ContentPresenter />
                    </Border>
                    <ControlTemplate.Triggers>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsMouseOver" Value="True" />
                                <Condition Property="IsSelected" Value="False" />
                            </MultiTrigger.Conditions>
                            <MultiTrigger.EnterActions>
                                <BeginStoryboard x:Name="MouseLeaveFadeOut_BeginStoryboard" Storyboard="{StaticResource MouseEnterBC}"/>
                            </MultiTrigger.EnterActions>
                            <MultiTrigger.ExitActions>
                                <BeginStoryboard x:Name="MouseLeaveFadeOut_BeginStoryboard3" Storyboard="{StaticResource MouseLeaveFadeOut}"/>
                            </MultiTrigger.ExitActions>
                        </MultiTrigger>
                        <Trigger Property="IsSelected" Value="True">
                            <Trigger.EnterActions>
                                <BeginStoryboard  x:Name="SelectBC_BeginStoryboard2" Storyboard="{StaticResource SelectBC}"/>
                            </Trigger.EnterActions>
                            <Trigger.ExitActions>
                                <BeginStoryboard Storyboard="{StaticResource MouseLeaveFadeOut}"></BeginStoryboard>
                            </Trigger.ExitActions>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>


text:
Q: How to Update the table if data is not even consistent in Teradata I have data like "00000973456, 973456, 00006589234, 6589234 etc.." kind of values in X col (len:11), in my table, while I am trying to update table data using these values : 00000973456 & 00006589234 and it is working fine.
But how to Update using values without zero's in front (973456, 6589234) though the length of these values are different.
Can anyone help me with the code to update using both type of values.
Click here for Image example


text:
Q: AspectJ pointcut to match methods annotated with @Test I am building a module that listens to TestNG tests and performs certain actions just before a test method starts its execution, for every test method.
I just want to know when a test(method) starts its execution, name of the method and optionally name of the test class.
I was successfully able to write pointcuts for invoker calls of testNG. It worked.
@Pointcut("execution(* org.testng.internal.IInvoker.invokeTestMethods(..))")

Instead, I was wondering as every test method is annotated with @org.testng.annotations.Test, how can I write pointcut to catch execution joinPoint of every test method annotated with @org.testng.annotations.Test?
Here is how my test looks like
@BeforeClass
    public void setup() {
       //setup logic
    }
    @BeforeMethod
    private void configure() {
        //config logic
    }

    @Test
    public void testLoad() {
    //test
    }

    @Test
    public void testForm() {
    //test
    }

I tried a few pointcuts, they turned out to be invalid ones.
Note: I am using load time weaving.

A: Try this
"execution(* *(..)) && @annotation(org.testng.annotations.Test)"


text:
Q: Getting a number from interest equation Here is the question for my homework:
A mother wants to invest $\$7000.00$ for her son's future education. She invests a portion of the money in a bank certificate of deposit (CD account) which earns $4\%$ and the remainder in a savings bond that earns $7\%$. If the total interest earned after one year is $\$420.00$, how much money was invested in the CD account?
Now, here is my steps:
Amount invested in the savings bond can be represented as $7000 - x$
The interest earned in one year on the CD account is $0.04x$
So, the interest earned on the savings bond in one year can be represented as: $0.07(7000-x)$
The total interested earned after one year is $\$420.00$
The equation is now $0.04x+0.07(7000-x) = 420.00$
Now to SIMPLFY it.
I have this so far
$n - 420 = 0.03x$
How do I get the number $n$?

A: I'm not sure what n is supposed to represent but instead of it you should still have that 7000*.07. Now you are left with just a number on the left and you can proceed to solve for x. $$.07(7000)-420.00 = 0.03x$$


text:
Q: Upload de arquivo automático Preciso fazer com que ao atualizar a pagina, o meu elemento <input type="file"> já venha carregado com os arquivos que serão salvos no banco, lembrando que os arquivos terão o mesmo nome.

A: Você quer que o formulário seja auto-submetido? Se for isto:
<form id="formulario" method="post" enctype="multipart/form-data">
    <input type="file" onchange="formulario.sumbit()" name="arquivos[]" multiple/>
</form>

A mágica está no onchange="formulario.submit()". Ele executa a função quando o valor do input for alterado.
O atributo name com [] no final servem para facilidade na hora de tratar os dados no backend.
O atributo multiple serve para dizer ao navegador aceitar vários arquivos.

A: O campo input type=file não pode ser carregado novamente com os arquivos que estão no banco, você deve exibir os arquivos de outra forma. o campo do tipo file não é como um campo do tipo text que você pode adicionar o texto em um value para exibir ao usuário.
Por exemplo: Você carregou uma imagem no input file, enviou para o banco. No seu banco vc salvou o caminho da imagem que foi feito upload no servidor. Na hora de editar essa imagem vc não carrega os dados dela no seu input file, vc exibe ela em um  o campo input file fica em branco.

A: Formulários com eventos e uploads (simples ou múltiplos) são um problema do ponto de vista de usabilidade.
Devido a restrições de segurança, você não pode definir o nome do arquivo a ser enviado programaticamente. Então, se for necessário atualizar o form sem Ajax, o arquivo será enviado ou "perdido".
Então, o que geralmente eu faço é desvincular o envio de anexos do restante do formulário:

*

*O primeiro passo é fazer o upload automático quando o usuário seleciona um arquivo. O arquivo é gravado num local temporário e vinculado à sessão do usuário com algum identificador relacionado ao formulário atual.

*Após o envio, eu atualizo o formulário mostrando um item com o nome do arquivo e uma opção para removê-lo. O(s) arquivo(s) já enviados devem ser listados através dos itens salvos como descrito no item anterior.

*Quando o formulário for efetivamente submetido eu verifico se há um ou mais arquivos "temporários", incluindo suas informações em alguma tabela do modelo e movendo os arquivos para o diretório definitivo.

O diretório com arquivos temporários deve ser limpo de tempos em tempos, excluindo os arquivos de sessões abandonadas. Pode-se utilizar algum critério relacionado à data do arquivo para isso, por exemplo, excluindo arquivos mais antigos que 1 dia.


text:
Q: Delete entire row if one or more cells are blank in any column I am trying to iterate through rows and delete a row if there is a blank cell in the row, on a button click, regardless of what column it is in.
I have 151 rows and Columns A to L.
When I run the code all my rows disappear.
Sub Button3_Click()
Dim lRow As Long
Dim iCntr As Long
Dim col As Integer
col = 1
lRow = 151
For iCntr = lRow To 1 Step -1
    If Trim(Cells(iCntr, col)) = "" Then
        Rows(iCntr).Delete
    End If
    col = col + 1
Next

End Sub

A: You need to loop across a fixed set of columns too - at the moment you appear to be just examining just one one cell per row - the col = col + 1 means you examine a diagonal stripe of cells, different column on each row.
Anyway it's better to collect all deletion rows and delete at the end of the process, so that you're not altering the space you're examining.
Sub Button3_Click()
Dim irx As Long
Dim ARow As Range
Dim ACell As Range
Dim DelSet As Range

Set DelSet = Nothing
For irx = 1 To 151
    Set ARow = Range(Cells(irx, 1), Cells(irx, 12))
    For Each ACell In ARow
        If Trim(ACell.Value) = "" Then
            If DelSet Is Nothing Then
                Set DelSet = ACell.EntireRow
            Else
                Set DelSet = Union(DelSet, ACell.EntireRow)
            End If
            Exit For
        End If
    Next ACell
Next irx

If Not DelSet Is Nothing Then
    DelSet.Delete
End If

End Sub

To see what this is doing, without actually deleting anything, you could change the DelSet.Delete into DelSet.Select and it will show you what the allocated region for deletion is.
I recognize from your comment that this use of Range object variables might be new to you, but definitely worth learning.

A: Delete Rows Containing At Least One Blank Cell

*

*If any of the cells in a row of the 'given' range (rg) is blank (empty, ="", ' etc.), then the row range (rrg) will be combined (using Union) into the Delete Range (drg). Finally, the entire rows of the Delete Range will be deleted.

*Your use of Trim may indicate that you also want to delete rows containing spaces. This is not covered by this solution (a cell is not blank if it contains a space).

A Quick Fix
Option Explicit

Sub Button3_Click()

    Const Cols As String = "A:L"
    Const First As Long = 1
    Const Last As Long = 151

    Dim rg As Range: Set rg = Columns(Cols).Rows(First & ":" & Last)

    Dim drg As Range
    Dim rrg As Range

    For Each rrg In rg.Rows
        If Application.CountBlank(rrg) > 0 Then
            If drg Is Nothing Then
                Set drg = rrg
            Else
                Set drg = Union(drg, rrg)
            End If
        End If
    Next rrg

    If Not drg Is Nothing Then
        drg.EntireRow.Delete
    End If

End Sub

Your Idea Fixed
Sub Button3_Click()

    Const fRow As Long = 1
    Const lRow As Long = 151
    Const fCol As Long = 1 ' ("A")
    Const lCol As Long = 12 ' ("L")

    Dim r As Long, c As Long

    For r = lRow To fRow Step -1
        For c = fCol To lCol
            If Trim(Cells(r, c).Value) = "" Then
                Rows(r).Delete
                Exit For ' found and deleted: don't loop the columns any more
            End If
        Next c
    Next r

End Sub

A: you need to select the row using the sintaxis:
E.g.
Rows(nrow:nrow).select -->  Rows(4:4).select
But you are counting in countdown, I guess you will need to count how many rows you have deleted. to select the right row.
Good luck
Sub Button3_Click()
    Dim lRow As Long
    Dim iCntr As Long
    Dim col As Integer
    col = 1
    lRow = 151
    For iCntr = lRow To 1 Step -1
        For col = 1 To 12 '12 is L
            If Trim(Cells(iCntr, col)) = "" Then
                Rows(iCntr & ":" & iCntr).Select
                Selection.Delete Shift:=xlUp
                Exit For ' if found 1 blank, get out afeter delete
                'After delet check wich cell you need to be stan on
            End If
        Next col
    Next
End Sub


text:
Q: Field not accessible within runAs() method in Test class I am checking for field accessibility of an User u whose Profile is p in apex Test class.To this profile field level security is set to Hidden for the field team_name__c.When I run as this user using runAs() method, and check the field accessibility as below, it returns false.
System.runAs(u){
system.debug('Accessible---> '+Schema.SObjectType.MyCustomObject__c.fields.team_Name__c.isAccessible());
//prints false
}

But according to the doc

The system method runAs enables you to write test methods that change
  the user context to an existing user or a new user so that the user's
  record sharing is enforced. The runAs method doesn't enforce user
  permissions or field-level permissions, only record sharing.

Which means field should have been accessible to the User within runAs() method as it doesn't enforce field level permissions.Please correct me if my understanding is wrong.

A: Apex will not enforce CRUD and FLS no matter what you do -- but you can test for CRUD and FLS using the method you documented in your code sample.
You must write your own handling code to 'gracefully degrade' your app should the running user not have the appropriate (read, create, update, delete) on the object or field within the object.
I'm sure you've read these docs a dozen times, but I'm posting it here for completeness of the answer:
https://developer.salesforce.com/page/Testing_CRUD_and_FLS_Enforcement
https://developer.salesforce.com/page/Enforcing_CRUD_and_FLS

developers should consider having graceful degradation within their
  applications if appropriate for their design.


text:
Q: Error handling - Unstructured Can someone please advise why the first transaction fails and the second succeeds, I've been stuck on this for a while now
GO
DECLARE @errnum AS int;
BEGIN TRAN;
SET IDENTITY_INSERT Production.Products ON;
INSERT INTO Production.Products(productid, productname, supplierid,
categoryid, unitprice, discontinued)
VALUES(1, N'Test1: Ok categoryid', 1, 1, 18.00, 0);
SET @errnum = @@ERROR;
IF @errnum <> 0

BEGIN
IF @@TRANCOUNT > 0 ROLLBACK TRAN;
PRINT 'Insert #1 into Production.Products failed with error ' +
CAST(@errnum AS VARCHAR);
END;
INSERT INTO Production.Products(productid, productname, supplierid,
categoryid,unitprice, discontinued)
VALUES(101, N'Test2: Bad categoryid', 1, 1, 18.00, 0);
SET @errnum = @@ERROR;
IF @errnum <> 0
BEGIN
IF @@TRANCOUNT > 0 ROLLBACK TRAN;
PRINT 'Insert #2 into Production.Products failed with error ' +
CAST(@errnum AS VARCHAR);
END;
SET IDENTITY_INSERT Production.Products OFF;