Q: Correlation between two distance measures on bitstrings I have an infinite collection of $0/1$ random strings of length $n$ (i.e., say 010001110101), where each digit is an independent Bernoulli RV, with parameter $p_i$,  $i:1...n$.
Define the "trait value" of a string to be the number of "1"s. Define $X$ to be a RV representing the absolute difference between the trait values of a sample of two strings.
Define $Y$ to be a RV representing the "distance" between two sampled strings, where this distance is simply the number of mismatched digits (i.e., so 01101-00111=2), also known as the Hamming distance.
Given $n$ and $p_i$, $i:1...n$, what is the correlation of $X$ and $Y$? (or at least, their covariance)?

A: Well, I don't see any way to get easy expressions.  But for messy expressions, we have:
$$E[Y] =\sum_{i=1}^n 2p_i(1-p_i) $$
Now suppose two strings differ by $y\geq 1$ bits. Enumerate these $\{1, \ldots, y\}$.  For $k \in \{1, \ldots, y\}$ define $A_k=1$ if the first string has a 1 in the $k$th different bit, and $A_k=0$ else. Then $A_1, \ldots, A_y$ are i.i.d. Bernoulli with $Pr[A_k=1]=1/2$, and, given $Y=y$:
$$ X|_{Y=y} = \left|\sum_{k=1}^y A_k - \left(y - \sum_{k=1}^y A_k\right)\right| = \left|y-2\sum_{k=1}^y A_k\right| $$
So:
$$ E[X|Y=y] = \sum_{r=0}^y {y \choose r} (1/2)^y\left|y-2r\right|$$
Then:
$$ E[X] = 0 + \sum_{y=1}^n \underbrace{Pr[Y=y]}_{complicated}E[X|Y=y]$$
Also:
$$ E[XY] = E[YE[X|Y]] = 0 + \sum_{y=1}^{n} yPr[Y=y]E[X|Y=y] $$

Perhaps a more useful relationship is just the observation:
$$ X = |Y-2R| $$
where $R = 0$ if $Y=0$ and $R$ is a sum of $Y$ iid Bernoulli $(1/2,1/2)$ variables else.

If you define $W$ as the pure difference between the number of ones (so $W \in \{-n, \ldots, n\}$ and $X=|W|$) then the answer is easier:
$$ W = Y-2R $$
So $E[W]=E[Y]-2E[R]=0$ and,
\begin{align}
E[YW] &= E[Y^2] - 2E[YR]\\
&= E[Y^2] - 2\sum_{y=0}^n Pr[Y=y]yE[R|Y=y]\\
&=E[Y^2] - 2\sum_{y=0}^n Pr[Y=y]y^2/2 \\
&= E[Y^2] - E[Y^2]\\
&=0
\end{align}
So $W$ and $Y$ are uncorrelated.

Asymptotically for large $n$, write $X\equiv X_n$, $Y\equiv Y_n$, $R\equiv R_n$. Suppose there is a constant $\alpha \in (0,1)$ such that:
\begin{align}
\lim_{n\rightarrow\infty} \frac{1}{n}\sum_{i=1}^n 2p_i(1-p_i) = \alpha
\end{align}
Then with probability 1:
\begin{align}
&\lim_{n\rightarrow\infty} \frac{Y_n}{n} = \alpha\\
&\lim_{n\rightarrow\infty} \frac{R_n}{Y_n} = 1/2 \\
&\lim_{n\rightarrow\infty} \frac{X_n}{n} = 0
\end{align}
where the last can be derived by:
$$ \lim_{n\rightarrow\infty} \frac{X_n}{n} = \lim_{n\rightarrow\infty} \left|\frac{Y_n-2R_n}{n}\right|=\lim_{n\rightarrow\infty}\left|\frac{Y_n}{n} - \frac{2R_n}{Y_n}\frac{Y_n}{n}\right|=0$$


Q: wmic: error when setting remote desktop self-signed certificate I'm attempting to use the wmic approach of assigning a self-signed certificate for Remote Desktop use on a Windows Server 2012 VM as described here and here.
The CA for the RDP certificate has been installed under Local Machine > Trusted Root Certification Authorities and the RDP certificate itself has been installed under Local Machine > Remote Desktop.
When I attempt to issue the wmic command to use the imported RDP certificate, I receive the following error:
C:\Windows\system32> wmic /namespace:\\root\CIMV2\TerminalServices PATH Win32_TSGeneralSetting Set SSLCertificateSHA1Hash="3c7a7a78af9699b69182dff15329834113a518b3"
Updating property(s) of '\\SERVER\root\CIMV2\TerminalServices:Win32_TSGeneralSetting.TerminalName="RDP-Tcp"'
ERROR:
Description = Invalid parameter

...I also tried importing the RDP certificate under Local Machine > Personal, but the error message remains unchanged.

A: Stuck with the same issue for 3 hours, but found the root of the problem.
In my case the reason for "Invalid parameter" error was that I've mistakenly imported a certificate without a corresponding private key.
So make sure, that when you open your certificate in General tab you see in the last line a key symbol and the text "You have a private key that corresponds to this certificate."
Certificate with private key
It's quite easy to combine certificate and a key into pfx file. Have a look here https://www.ssl.com/how-to/create-a-pfx-p12-certificate-file-using-openssl/

A: Try placing the thumprint letters in caps instead of lower case. In Server 2012 R2, for some reason it doesn't take lower case characters in the thumbprint for the wmic command, so e.g. d8f87e2cff8fcc5789f53b5539fc12a0b5eecba8 should be D8F87E2CFF8FCC5789F53B5539FC12A0B5EECBA8.
Easiest way for me to get the thumbprint "as it should be", was to open powershell and get the thumbprint with the following command:
Get-Childitem Cert:\LocalMachine\My
It will display the thumbprints for the local machine certificates without spaces and letters in caps.
Anyway, check out this article, it's really good: https://ryanmangansitblog.com/2013/03/10/configuring-rds-2012-certificates-and-sso/

A: Trying to summarize the checklist, cause there are many ways this might happen.

*

*Ensure you are running your powershell/command prompt under Administrative Privileges as stated from this answer

*Make sure you import the certificate with private key. Check the answer from Dmitriy

*Ensure when you are trying to import the certificate, import to the Machine Account->Personal. Please refer to this blog.

*I have not yet faced this problem but someone might have, change the thumbprint to capital. Check the answer from Erick.

*If you are having the same issue as many other people like Ryan said, run the Powershell version of it.

*If you are using notepad to act as buffer when trying to remove space in thumbprint, make sure you have removed the ASCII symbol at the beginning of thumbprint. As stated from this support article by MS.

Hope this can solve your problem :D

A: On a previous answer related to this topic, one of the comments from someone claimed the wmic version of the command didn't work for them on a 2012 R2 machine, but the Powershell equivalent version did work.  You might try that.  Here's the equivalent Powershell command.
$path = (gwmi -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -Filter "TerminalName='RDP-tcp'").__path
swmi -Path $path -argument @{SSLCertificateSHA1Hash="THUMBPRINT"}

A: Found the command above was not working as anticipated. After typing out the commands manually it worked, not sure what happened but just in case here is what I used
$TSGS = Get-WmiObject -Class "Win32_TSGeneralSetting" -Namespace "root\cimv2\terminalservices"
Set-WmiInstance -Path $TSGS -Arguments @{SSLCertificateSHA1Hash="4adcffbcf35ba044d93108ae2e2c51fa3c3fc983"}

A: Make sure that the certificate you're using has Server Authentication (1.3.6.1.5.5.7.3.1) set for its enhanced key usage field, otherwise you will get that error.
Create self-signed terminal services certificate and install it

A: I also had this problem, which brought me here.  My solution was to double-check that your thumbprint (after you remove the spaces and special leading character) reflects exactly the certificate's thumbprint.  I was missing a trailing digit; once added back I received a "Property(s) update successful.  Good luck.

A: When copying a certificate, for some reason there is a hidden character at the beginning. make sure to copy the certificate without the hidden character when going into the certificate properties. If you look at the "invalid Parameter" response of the command and look up at the certificate you tried to put in, you would see a box character at the beginning.


Q: How to create Up and Down Methods using migrations? I am new to Code first, can you tell me how i can have all Up and Down methods for all tables in the database like below(given for one table)
public partial class abc: DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.UserTasks", "ServiceTechReason", c => c.Long());
        }

        public override void Down()
        {
            DropColumn("dbo.UserTasks", "ServiceTechReason");
        }
    }

i want all three types for a table viz .cs , .Designer.cs , .resx.
2) Can you explain the above example, i pick it from somewhere on internet i was searching for this but found nothing. is abc is my table name in database?
Provide me link if it is already answered.
EDIT
As mentioned by @scheien i already tried those commands they do not automatically override up and down methods for a table

A: Creating migrations is done by running the command Add-Migration AddedServiceTechReason.
This assumes that you have already enabled migrations using the Enable-Migrations command.
To apply the current migration to the database, you'd run the Update-Database. This command will apply all pending migrations.
The point of Code-First migrations is that you make the changes you want to your Entity(ies), and then add a new migration using the Add-Migration command. It will then create a class that inherits DbMigration, with the Up() and Down() methods filled with the changes you have made to your entity/entities.
As per @SteveGreenes comment: It does pick up all changes to your entities, so you don't need to run it once per table/entity.
If you want to customize the generated migration files, look under the section "Customizing Migrations" in the article listed.
All these commands are run in the package manager console.

View -> Other windows -> Package Manager Console.

Here's a great article from blogs.msdn.com that explains it in detail.


Q: What is the best way of reading/writing structured binary data in C# Like in C we could use structure pointers to read or write structured binary data like file headers etc, is there a similar way to do this in C#?

A: Using BinaryReader and BinaryWriter over a MemoryStream tends to be the best way in my opinion.
Parsing binary data:
byte[] buf = f                     // some data from somewhere
using (var ms = new MemoryStream(buf, false)) {   // Read-only
    var br = new BinaryReader(ms);

    UInt32 len = br.ReadUInt32();
    // ...
}

Generating binary data:
byte[] result;
using (var ms = new MemoryStream()) {   // Expandable
    var bw = new BinaryWriter(ms);

    UInt32 len = 0x1337;
    bw.Write(len);
    // ...

    result = ms.GetBuffer();   // Get the underlying byte array you've created.
}

They allow you to read and write all of the primitive types you'd need for most file headers, etc. such as (U)Int16, 32, 64, Single, Double, as well as byte, char and arrays of those.  There is direct support for strings, however only if

The string is prefixed with the length, encoded as an integer seven bits at a time.

This only seems useful to me if you wrote the string in this way from BinaryWriter in this way. It's easy enough however, say your string is prefixed by a DWord length, followed by that many ASCII characters:
int len = (int)br.ReadUInt32();
string s = Encoding.ASCII.GetString(br.ReadBytes(len));

Note that I do not have the BinaryReader and BinaryWriter objects wrapped in a using() block. This is because, although they are IDisposable, all their Dispose() does is call Dispose() on the underlying stream (in these examples, the MemoryStream).
Since all the BinaryReader/BinaryWriter are is a set of Read()/Write() wrappers around the underlying streams, I don't see why they're IDisposable anyway. It's just confusing when you try to do The Right Thing and call Dispose() on all your IDisposables, and suddenly your stream is disposed.

A: To read arbitrarily-structured data (a struct) from a binary file, you first need this:
public static T ToStructure<T>(byte[] data)
{
    unsafe
    {
        fixed (byte* p = &data[0])
        {
            return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));
        }
    };
}

You can then:
public static T Read<T>(BinaryReader reader) where T: new()
{
    T instance = new T();
    return ToStructure<T>(reader.ReadBytes(Marshal.SizeOf(instance)));
}

To write, convert the struct object to a byte array:
public static byte[] ToByteArray(object obj)
{
    int len = Marshal.SizeOf(obj);
    byte[] arr = new byte[len];
    IntPtr ptr = Marshal.AllocHGlobal(len);
    Marshal.StructureToPtr(obj, ptr, true);
    Marshal.Copy(ptr, arr, 0, len);
    Marshal.FreeHGlobal(ptr);
    return arr;
}

...and then just write the resulting byte array to a file using a BinaryWriter.

A: Here is an simple example showing how to read and write data in Binary format to and from a file.
using System;
using System.IO;
namespace myFileRead
{
    class Program
     {
       static void Main(string[] args)
       {
           // Let's create new data file.
           string myFileName = @"C:\Integers.dat";
            //check if already exists
            if (File.Exists(myFileName))
               {
                Console.WriteLine(myFileName + " already exists in the selected directory.");

                return;
            }

            FileStream fs = new FileStream(myFileName, FileMode.CreateNew);

            // Instantialte a Binary writer to write data

            BinaryWriter bw = new BinaryWriter(fs);

            // write some data with bw

            for (int i = 0; i < 100; i++)

            {
                    bw.Write((int)i);
            }

            bw.Close();
            fs.Close();

            // Instantiate a reader to read content from file
            fs = new FileStream(myFileName, FileMode.Open, FileAccess.Read);

            BinaryReader br = new BinaryReader(fs);

            // Read data from the file

            for (int i = 0; i < 100; i++)
            {
                //read data as Int32
                Console.WriteLine(br.ReadInt32());
            }
            //close the file
            br.Close();
            fs.Close();
       }

    }

}


Q: How do I skip methods using @AfterMethod in TestNG I have a set of tests as follows.
@Test
public void testX(){
}

@Test
public void testY(){
}

@Test
public void testZ(){
}

I have another test which I should run after each of the test is executed.
I hope I could do that with
@AfterMethod
public void testA(){
}

Now I need to skip testA for testX. Which means I don't need testA to run after testX. How do I do it? Also how to specify multiple test cases to skip in the above manner?

A: One way to do that would be to add to the same group every method you want testA to execute.
In the following example, testY and testZ are added to the "myGroup" group so the testA after method, which also belongs to this group, will only be executed for those tests.
@Test
public void testX(){
}

@Test(groups = { "myGroup" })
public void testY(){
}

@Test(groups = { "myGroup" })
public void testZ(){
}

@AfterMethod(groups = { "myGroup" })
public void testA(){
}


Q: How do i rescale feature classes of different scales for intersect analysis? before I intersect 2 feature classes of different scales (e.g. 1:200,000 soil map and 1:25,000 land use map), should I rescale them like how u would resample raster datasets to the same resolution before overlaying them together? If yes, how do I do so in ArcGIS? (I have ArcGIS10.1).

A: If the data is georeferenced, you do not need to rescale anything. However, you should be aware that your data sources have different spatial resolution and use a tolerance (20-50 m) to avoid sliver polygons due to this difference.


Q: how to get two item from a List<> in every get request in ASP.NET Core MVC How can I get two value per get request from a List<>, For example,
I have a Person List<> with six Person Ordered by ID in that List<> now in every get request using JQuery ajax() I want to get only two item from the list<>, first request will return Person with ID 1 & 2, second request will return Person with ID 3 & 4, and so forth.
I've tried
public IEnumerable<PersonViewModel> GetAllStudents()
    {
        IEnumerable<Person> dbPersons = _repo.getPersons().OrderBy(s => s.ID).Take(2);

        List<PersonViewModel> persons = new List<PersonViewModel>();
        foreach(var p in dbPersons)
        {
            persons.Add(MapDbPieToPersonViewModel(p));
        }

        return persons;
    }

But this only return first two item.

A: You should use Enumerable.Skip(Int32)
public IEnumerable<PersonViewModel> GetAllStudents(int page)
{
    const int PageSize = 2;
    IEnumerable<Person> dbPersons = _repo.getPersons().OrderBy(s => s.ID).Skip(page * PageSize).Take(PageSize);

    List<PersonViewModel> persons = new List<PersonViewModel>();
    foreach(var p in dbPersons)
    {
        persons.Add(MapDbPieToPersonViewModel(p));
    }

    return persons;
}


Q: Can a NSDictionary take in NSSet as key? I know you can use any object as key for NSDictionary but the problem is will it be able to retrieve the correct value? Support I have an entry where the key = {1,3,5} and value = { @"hello" }. Will I be able to retrieve from this dictionary entry by passing in the set {3,5,1}?
In order words, is the key matched based on the pointer or does it actually compare the contents of the set? (And if it is the former, how can I overcome this?)

A: The equality of keys is done using isEqual on the keys in question. Thus, the comparison of {1,3,5} and {3,5,1} (assuming that the numbers are represented by NSNUmber instances) will be YES.

A: Yep it seems to work nicely (not sure if there are any gotchas).
NSMutableDictionary * dict = [NSMutableDictionary dictionary];

NSSet * set;
set = [NSSet setWithObjects:@"a", @"b", @"c", @"d", nil];
[dict setObject:@"1" forKey:set];

set = [NSSet setWithObjects:@"b", @"c", @"d", @"e", nil];
[dict setObject:@"2" forKey:set];

id key;
NSEnumerator * enumerator = [dict keyEnumerator];
while ((key = [enumerator nextObject]))
    NSLog(@"%@ : %@", key, [dict objectForKey:key]);

set = [NSSet setWithObjects:@"c", @"b", @"e", @"d", nil];
NSString * value = [dict objectForKey:set];
NSLog(@"set: %@ : key: %@", set, value);

Outputs:
2009-12-08 15:42:17.885 x[4989] (d, e, b, c) : 2
2009-12-08 15:42:17.887 x[4989] (d, a, b, c) : 1
2009-12-08 15:42:17.887 x[4989] set: (d, e, b, c) : key: 2

A: Yes (since a set conforms to NSCopying and implements isEqual:), with one catch: Do not use a mutable set, or any other mutable object, as a key. You will mutate it, whereupon you will break your ability to look up its value in the dictionary.

A: Yes.
Try this in irb:
require 'osx/cocoa'
abc=OSX::NSSet.setWithArray([1,2,3])
cba=OSX::NSSet.setWithArray([3,2,1])
dict=OSX::NSMutableDictionary.dictionary
dict[abc] = 'hello'
puts dict[cba]

(it works, because isEqual: for NSSet is true when you'd expect it to be and NSDictionary bases its actions on that)


Q: How to return var parameter in Delphi ASM I'm far from having knowledge about ASM, so forgive me if this is a stupid question.
I have this function:
function SwapDWord(const AValue: DWORD): DWORD;
asm
  BSWAP EAX
end;

How would I convert it to a procedure in ASM:
procedure SwapDWordVar(var AValue: DWORD);
asm
  // ???
end;

I do not want to use AValue := SwapDWord(AValue); which I could. I want to do this in ASM.
I tried many silly things by looking at system.pas and tried to understand which register(s) to use. but nothing worked. It always return back the original AValue.

A: Possible variant:
procedure SwapDWordVar(var AValue: DWORD);
asm
  mov edx, [eax]
  bswap edx
  mov [eax], edx
end;

You might find useful Guido Gybels articles

A: Just try
procedure SwapDWordVar(var AValue: DWORD);
asm
  mov edx, dword ptr [AValue]
  bswap edx
  mov dword ptr [AValue], edx
end;

Note that this version will compile and work for both Win32 and Win64.
But note that it won't be faster than AValue := SWapDWord(AValue) since most of the time will be spent calling the function, not accessing the memory.


Q: How to run custom mysql script for Laravel app in test pipeline in CodeShip Basic? Relative newbie to PhpUnit and testing in general.  We do not use migrations in our project, but have a couple of scripts that I need to run in order to set up the database for testing.  How can I run mysql scripts from the project in the test pipeline?  I also need to create a new database with a specific name before running those scripts.
Thanks!

A: The commands that you use on your local machine are the same commands you can run in CodeShip Basic. CodeShip Basic is just a build machine with Ubuntu Bionic and it will run through the setup, test, and deploy commands as if you were entering each line into your CLI. :)
We also have some documentation about mysql: https://documentation.codeship.com/basic/databases/mysql/

A: OK, after some digging I found out how to do all this.  Below is the script I used for testing with a new mysql schema created with specific user from a sql script.  Hope this helps someone in the future.
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "CREATE USER 'myuser'@'%' IDENTIFIED BY 'testpassword';"
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "CREATE SCHEMA myschemaname;"
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'%' IDENTIFIED BY 'testpassword';"
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD myschemaname < ./app/Ship/Migrations/1of2-schema.sql
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD myschemaname < ./app/Ship/Migrations/2of2-seed.sql
php artisan passport:install
./vendor/bin/phpunit

$MYSQL_USER and $MYSQL_PASSWORD are replaced by Codeship - these are the env variables for the user and password for the mysql that exists in the build container.
the -e switch on the mysql call runs the script given and exits.  Had to do it this way since I couldn't interact with the mysql client.


Q: Installing CoreOS on a single machine How would I go about installing CoreOS on a single machine as the host OS?
I have read "Installing CoreOS to Disk" and ran the coreos-install script from Debian and CentOS live CDs, but both seem to miss the -p argument for the lsblk command which the script needs to load config files. Even after I updated util-linux, it is still not working.
Is using a live CD the right approach? PXE isn't an option in my situation.
Solution: In the end I used the latest Arch linux live cd, that worked fine.
$ wget https://raw.githubusercontent.com/coreos/init/master/bin/coreos-install
$ sudo bash coreos-install -d /dev/sda
$ mkdir rootfs
$ mount -t btrfs -o subvol=root /dev/sda9 rootfs #sda9 is the default root partition
$ mkdir -p rootfs/var/lib/coreos-install
$ wget http://bit.ly/abcd  #the location of your cloud config file
$ mv abcd rootfs/var/lib/coreos-install/user_data

A: It looks like -p (alternately --paths) was added in util-linux 2.24. Did you try a live system with that version?

A: Worked for me using Ubuntu Trusty livecd
~$ sudo wget https://raw.githubusercontent.com/coreos/init/master/bin/coreos-install
~$ sudo chmod +x coreos-install
~$ sudo ./coreos-install -d /dev/sda -C alpha -c ~/cloud-config.yaml

Though can you can mount the /dev/sda to do manual tweaking (rather than using/creating a cloud-config.yaml) via...
~$ mount -o subvol=root /dev/sda9 /mnt

.. like removing the root and core password, create systemd unit file for docker, etcd and fleet.


Q: replace 0 into dash in Fast Report Is it Possible to replace 0 value and turn it into dash in fast report?
like:
No.   turns to
1         1
2         2
0         -
3         3
0         -
0         -

A: Yes.
Use a built-in script engine.
Assuming you have a dataset DS and a field FIELD_NAME then instead of [DS."FIELD_NAME"] you should write [IIF(<DS."FIELD_NAME"> = 0, '-',  <DS."FIELD_NAME">)] as your frxMemoView text.


Q: databricks init script to mount dbfs on adls I am using a python notebook to mount dbfs on adls , now I want to add this to the init scrip so this can be done during the job cluster start
this is the python code I am using how to make this run as the init script please:
environment = "development"
scopeCredentials = "test-" + environment

# Secrets
# ADLS
app_id = dbutils.secrets.get(scope=scopeCredentials, key="app_id")
key = dbutils.secrets.get(scope=scopeCredentials, key="key")
adls_name = dbutils.secrets.get(scope=scopeCredentials, key="adls-name")

# Configs
# ADLS
adls_configs = {
  "dfs.adls.oauth2.access.token.provider.type": "ClientCredential",
  "dfs.adls.oauth2.client.id": app_id, #id is the AppId of the service principal
  "dfs.adls.oauth2.credential": key,
  "dfs.adls.oauth2.refresh.url": "url"
}

mount_point="mount_point"
if any(mount.mountPoint == mount_point  for mount in dbutils.fs.mounts()):
  print("Storage: " + mount_point + " already mounted")
else:
  try:
    dbutils.fs.mount(
      source = "source",
      mount_point = "mount_point",
      extra_configs = adls_configs)
    print("Storage: " + mount_point + " successfully mounted")
  except:
    print("Storage: " + mount_point + " not mounted")
    pass

any idea how to change this to make it as a bash init script ?

A: Mounting of the storage needs to be done once, or when you change credentials of the service principal.  Unmount & mount during the execution may lead to a problems when somebody else is using that mount from another cluster.
If you really want to access storage only from that cluster, then you need to configure that properties in the cluster's Spark Conf, and access data directly using abfss://...  URIs (see docs for details).  Mounting the storage just for time of execution of the cluster doesn't make sense from the security perspective, because during that time, anyone in workspace can access mounted data, as mount is global, not local to a cluster.


Q: Spring Reactive MVC vs @EnableAsync I'm a newbie to Spring Reactive Modules. What I got is basically, at its core it enable reactive programming and we can develop end to end reactive service.
But, suppose I just want to make my controller as Async, so that I can do work on multiple threads and send a reply like "Task Started" (not particularly this) and have my work going on and close the HTTP link.
I also got to know about @EnableAsync and @Async to make a method Async.
What if I just use @Async above my controller method that I want to make async. It worked but, is this a good practice? And can we use this in production codes?

A: I do not see any problem using @Asyncas this will release the request thread. But this is a simple approach and it has a lot of limitations. Note that if you want to deal with reactive streams, you do not have an API capable of that. For instance, if an @Async method calls another, the second will not be async.
The Webflux instead will bring the most complete API (in Java) to deal with things the reactive way. What you cannot do with only @Async. With Flux, for instance, you can process or access with multiple layers reactively and this you cannot reach the way you doing.
Nevertheless, it will bring a new universe for you, so if you just want to release the thread of the request, your approach is just fine, but if you need more you will have to deal with it in a more complex way.
Now, if you want to answer the HTTP request and then do the work asyncly, this is not what you want. I recommend that you have a JMS provider (like ActiveMQ), where your controller sends the message to be processed by a job and answers the request.
Hope it helps!


Q: Why search in .Net Dictionary is slower than in .Net List I tried to solve this task:
We have an array, eg. [1, 1, 2, 3, 5, 2, 7, 8, 1], find and output duplicates. For this array the result is
1, 2.
I wrote code to try "slow" and "fast" solutions.
"Slow" solution with inner loop and searching via list
   public uint[] InnerLoops(uint[] arr)
    {
        var timer = new Stopwatch();
        timer.Start();

        var result = new List<uint>();
        for (int i = 0; i < arr.Length; i++)
        {
            for (int j = i + 1; j < arr.Length; j++)
            {
                if (arr[i] == arr[j] && result.All(a => a != arr[j]))
                    result.Add(arr[j]);
            }
        }

        timer.Stop();

        Console.WriteLine($"Seconds: {timer.Elapsed}");

        return result.ToArray();
    }

I would estimate the solutions as O(n^2) and O(n) inside each inner loop. Sorry, I am not good at estimating complexity. Anyway, I thought, the following solution would be better
 public uint[] OneLoopDictionary(uint[] arr)
    {
        var timer = new Stopwatch();
        timer.Start();

        var dictionary = new Dictionary<uint, bool>();
        for (int i = 0; i < arr.Length; i++)
        {
            // Key - number, value - true if duplicates
            if (dictionary.ContainsKey(arr[i]))
            {
                dictionary[arr[i]] = true;
            }
            else
            {
                dictionary[arr[i]] = false;
            }
        }

        var result = new List<uint>();
        foreach (var item in dictionary)
        {
            if (item.Value)
                result.Add(item.Key);
        }

        timer.Stop();

        Console.WriteLine($"Seconds: {timer.Elapsed}");

        return result.ToArray();
    }

The complexity is O(2n) - one loop and loop via dictionary.
I was surprised that the fist solution with loop was faster that the second one. Could anyone explain me why?

A: Thanks to all! Espesially to who gave an advice to try with bigger array. I tryied with 100, 1000 and 100000 and I was surprised, that the dictionary was faster. Of course, previously, I tryied not just with array from my first post, bur with array of about 50 numbers, but the dictionary was slower.
With aaray of 100 or more numbers the dictuinary is much more faster. The result for 100000 items is:
list - 31 seconds,
dicionary - 0.008 seconds


Q: angularJs directive to format date I want to have a functionality in angular which help to enter date and show it in proper format and don't allow invalid values in it. also able to show server returned '20140314T00:00:00Z' json string for date.
Can anyone help me ?

A: Angular.js already have date filter {{20140314 | date}} //  Jan 1, 1970 9:35:40 AM
Angular Date Docs

A: This works for me,
   .directive('myDate', ['$timeout', '$filter', function ($timeout, $filter)
    {
        return {
            require: 'ngModel',

            link: function ($scope, $element, $attrs, $ctrl)
            {
                var dateFormat = 'mm/dd/yyyy';
                $ctrl.$parsers.push(function (viewValue)
                {
                    //convert string input into moment data model
                    var pDate = Date.parse(viewValue);
                    if (isNaN(pDate) === false) {
                        return new Date(pDate);
                    }
                    return undefined;

                });
                $ctrl.$formatters.push(function (modelValue)
                {
                    var pDate = Date.parse(modelValue);
                    if (isNaN(pDate) === false) {
                        return $filter('date')(new Date(pDate), dateFormat);
                    }
                    return undefined;
                });
                $element.on('blur', function ()
                {
                    var pDate = Date.parse($ctrl.$modelValue);
                    if (isNaN(pDate) === true) {
                        $ctrl.$setViewValue(null);
                        $ctrl.$render();
                    } else {
                        if ($element.val() !== $filter('date')(new Date(pDate), dateFormat)) {
                            $ctrl.$setViewValue($filter('date')(new Date(pDate), dateFormat));
                            $ctrl.$render();
                        }
                    }

                });
                $timeout(function ()
                {
                    $element.kendoDatePicker({

                        format: dateFormat
                    });

                });
            }
        };
    }])


Q: Circuit analysis homework - LTspice results are different from calculations Original question:

I have already tried calculating it, but after simulating the circuit in LTspice, the answer is different.
My working is shown below.
I've included a screenshot of the LTspice showing a Vout of about 118 mV whereas I calculated 1.163 V.
Where is my mistake, please?

(Original copy of working is at:  https://notability.com/n/1r9BP36Zt507ijpb2LnVdc
(Scroll down to page 12))

A: In case you need all others answers for verifying ... Maple sheet.

And this for the last question ...

A: Check your complex arithmetic:-

@100Hz
I get
Za = 4.7000e+03 + 6.2832e+01i
Zb = 2.2000e+03 - 3.3863e+04i
Zc = 1.0000e+03 - 1.5915e+05i
Zp = Za || Zb = 4.5887e+03 - 5.6789e+02i
Vo = 4 * Zp/(Zp + Zc) = 0.0182 + 0.1143i
|Vo| = 0.1157V


Q: How English say sentences about a coincident or accident In this question I asked about different usage of "that" and its possible corresponding with Persian sentences,
But still I don't know how English may say sentences like:

1) We were walking, that suddenly a car stopped in front of us...
2) I was reading a book that he entered the room.
3) I was cleaning it that it was broke
4) He was driving that he went to sleep and the car was crushed

They almost mean, as we were doing something, something happened.

A: Use 'when' to indicate that one event happens while another event is ongoing:

1) We were walking, when suddenly a car stopped in front of us...
2) I was reading a book when he entered the room.
3) I was cleaning it when it broke

(note that was broke would imply that 'it' was out of money).

A: In every one of your sentences, if you replace "that" with "then", they sound much more correct to my US English ears. As-is, they sound wrong.
For number 3, I would say

3) I was cleaning it, then it broke.


Q: Understanding continuity and Dense sets
Let $f$ and $g$ be continuous mappings of metric space X into metric space Y, and let E be dense in X. Prove $f(E)$ is dense in $f(X)$. If $g(p)=f(p)$ for all $p \in E$, prove $g(p)=f(p)$ for all $p\notin E$

My Attempt
For Rudin a set $E\subset X$ is dense if, for all points in X, that is a limit point of E or a point of E or both.
Take $f(x) \in f(X)\setminus f(E)$. Since $E$ is dense, there exists some sequence of $x_n$ such that $\{x_n\} \subset E$ and $x_n \to x$. By continuity, we see $f(x_n) \to f(x)$. Since $f(x_n) \in f(E)$, we have any point in $f(X)$ is a limit point of $f(E)$ or in $f(E)$.
I'm pretty sure the second part has been asked on MSE before, but I'd like to give my attempt to allow for critique.
Assume otherwise that $\exists p \notin E$ such that $g(p) \neq f(p)$. We can construct a sequence $p_n$ such that $\{p_n\} \subset E$ and $p_n \to p$. By continuity, we see $f(p_n) \to f(p)$ and $g(p_n) \to g(p)$. By assumption, $\lim_{n\to\infty} f(p_n) \neq \lim_{n\to\infty} g(p_n)$. However, $f(p_n) = g(p_n)$ for every $n$ which yields a contradiction.
Is my approach correct? Is there a more concise way of stating either part?


Q: How can I solve my foreign key constraint error when I know I created the relationships right?

-- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema BrendasDMS
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `BrendasDMS` ;

-- -----------------------------------------------------
-- Schema BrendasDMS
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `BrendasDMS` DEFAULT CHARACTER SET utf8 ;
SHOW WARNINGS;
USE `BrendasDMS` ;

-- -----------------------------------------------------
-- Table `Customers`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Customers` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Customers` (
  `Customer_ID` INT NOT NULL AUTO_INCREMENT,
  ` FirstName` VARCHAR(45) NOT NULL,
  `LastName` VARCHAR(45) NOT NULL,
  `Email` VARCHAR(45) NOT NULL,
  `Phone` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`Customer_ID`),
  UNIQUE INDEX `CustomerID_UNIQUE` (`Customer_ID` ASC))
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Employees`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Employees` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Employees` (
  `Employee_ID` INT NOT NULL AUTO_INCREMENT,
  `FirstName` VARCHAR(45) NOT NULL,
  `LastName` VARCHAR(45) NOT NULL,
  `Address` VARCHAR(45) NOT NULL,
  `City` VARCHAR(45) NOT NULL,
  `State` VARCHAR(45) NOT NULL,
  `Zip` VARCHAR(45) NOT NULL,
  `County` VARCHAR(45) NOT NULL,
  `PhoneNumber` VARCHAR(45) NOT NULL,
  `BirthDate` DATE NOT NULL,
  `SSN` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`Employee_ID`),
  UNIQUE INDEX `FirstName_UNIQUE` (`FirstName` ASC))
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Shops`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Shops` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Shops` (
  `Shop_ID` INT NOT NULL AUTO_INCREMENT,
  `Address` VARCHAR(45) NOT NULL,
  `County` VARCHAR(45) NOT NULL,
  `Zip` VARCHAR(45) NOT NULL,
  `Phone Number` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`Shop_ID`),
  UNIQUE INDEX `ID_UNIQUE` (`Shop_ID` ASC))
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Sales`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Sales` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Sales` (
  `Sale_ID` INT NOT NULL AUTO_INCREMENT,
  `SaleDate` DATE NOT NULL,
  `Employee_ID` INT NOT NULL,
  `Customer_ID` INT NOT NULL,
  `Shop_ID` INT NOT NULL,
  `Quantity` INT NOT NULL,
  `Price` DECIMAL NOT NULL,
  `UnitOfMeasure` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`Sale_ID`, `Customer_ID`, `Employee_ID`, `Shop_ID`),
  INDEX `fk_Sale_Employee1_idx` (`Employee_ID` ASC),
  INDEX `fk_Sale_Customer1_idx` (`Customer_ID` ASC),
  INDEX `fk_Sale_Shops1_idx` (`Shop_ID` ASC),
  CONSTRAINT `fk_Sale_Employee1`
    FOREIGN KEY (`Employee_ID`)
    REFERENCES `Employees` (`Employee_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Sale_Customer1`
    FOREIGN KEY (`Customer_ID`)
    REFERENCES `Customers` (`Customer_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Sale_Shops1`
    FOREIGN KEY (`Shop_ID`)
    REFERENCES `Shops` (`Shop_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Products`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Products` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Products` (
  `Product_ID` INT NOT NULL AUTO_INCREMENT,
  `ProductName` VARCHAR(45) NOT NULL,
  `UnitOfMeasure` VARCHAR(45) NOT NULL,
  `Price` DECIMAL NOT NULL,
  `Quantity` INT NOT NULL,
  PRIMARY KEY (`Product_ID`),
  UNIQUE INDEX `RecipeID_UNIQUE` (`Product_ID` ASC))
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `SaleLineItems`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `SaleLineItems` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `SaleLineItems` (
  `Sale_ID` INT NOT NULL,
  `Quantity` INT NOT NULL,
  `Product_ID` INT NOT NULL,
  PRIMARY KEY (`Sale_ID`, `Product_ID`),
  INDEX `fk_Sale_has_Product_Sale1_idx` (`Sale_ID` ASC),
  INDEX `fk_SaleLineItem_Product1_idx` (`Product_ID` ASC),
  CONSTRAINT `fk_Sale_has_Product_Sale1`
    FOREIGN KEY (`Sale_ID`)
    REFERENCES `Sales` (`Sale_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_SaleLineItem_Product1`
    FOREIGN KEY (`Product_ID`)
    REFERENCES `Products` (`Product_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Vendors`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Vendors` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Vendors` (
  `Vendor_ID` INT NOT NULL AUTO_INCREMENT,
  `FirstName` VARCHAR(45) NOT NULL,
  `LastName` VARCHAR(45) NOT NULL,
  `VendorType` VARCHAR(45) NOT NULL,
  `Address` VARCHAR(45) NOT NULL,
  `Zip` VARCHAR(45) NOT NULL,
  `PhoneNumber` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`Vendor_ID`),
  UNIQUE INDEX `ID_UNIQUE` (`Vendor_ID` ASC))
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Orders`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Orders` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Orders` (
  `Order_ID` INT NOT NULL AUTO_INCREMENT,
  `Date` DATE NOT NULL,
  `Vendor_ID` INT NOT NULL,
  `Quantity` INT NOT NULL,
  `UnitOfMeasure` VARCHAR(45) NOT NULL,
  `Price` DECIMAL NOT NULL,
  PRIMARY KEY (`Order_ID`, `Vendor_ID`),
  UNIQUE INDEX `ID_UNIQUE` (`Order_ID` ASC),
  INDEX `fk_Orders_Vendor1_idx` (`Vendor_ID` ASC),
  CONSTRAINT `fk_Orders_Vendor1`
    FOREIGN KEY (`Vendor_ID`)
    REFERENCES `Vendors` (`Vendor_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `EmployeeShop`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `EmployeeShop` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `EmployeeShop` (
  `Shop_ID` INT NOT NULL,
  `Employee_ID` INT NOT NULL,
  PRIMARY KEY (`Shop_ID`, `Employee_ID`),
  INDEX `fk_Shop_has_Employee_Employee1_idx` (`Employee_ID` ASC),
  INDEX `fk_Shop_has_Employee_Shop1_idx` (`Shop_ID` ASC),
  CONSTRAINT `fk_Shop_has_Employee_Shop1`
    FOREIGN KEY (`Shop_ID`)
    REFERENCES `Shops` (`Shop_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Shop_has_Employee_Employee1`
    FOREIGN KEY (`Employee_ID`)
    REFERENCES `Employees` (`Employee_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Ingredients`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Ingredients` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Ingredients` (
  `Ingredient_ID` INT NOT NULL,
  `IngredientName` VARCHAR(45) NOT NULL,
  `UnitOfMeasure` VARCHAR(45) NOT NULL,
  `Quantity` INT NOT NULL,
  `Price` DECIMAL NOT NULL,
  PRIMARY KEY (`Ingredient_ID`))
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `OrderLineItems`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `OrderLineItems` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `OrderLineItems` (
  `Quantity` INT NOT NULL,
  `Order_ID` INT NOT NULL,
  `Ingredient_ID` INT NOT NULL,
  PRIMARY KEY (`Order_ID`, `Ingredient_ID`),
  INDEX `fk_OrderLineItems_Orders1_idx` (`Order_ID` ASC),
  INDEX `fk_OrderLineItems_Ingredients1_idx` (`Ingredient_ID` ASC),
  CONSTRAINT `fk_OrderLineItems_Orders1`
    FOREIGN KEY (`Order_ID`)
    REFERENCES `Orders` (`Order_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_OrderLineItems_Ingredients1`
    FOREIGN KEY (`Ingredient_ID`)
    REFERENCES `Ingredients` (`Ingredient_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = ndbcluster;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Recipes`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Recipes` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Recipes` (
  `Recipe_ID` INT NOT NULL,
  `Directions` VARCHAR(45) NOT NULL,
  `Product_ID` INT NOT NULL,
  PRIMARY KEY (`Recipe_ID`, `Product_ID`),
  UNIQUE INDEX `Recipe_ID_UNIQUE` (`Recipe_ID` ASC),
  INDEX `fk_Recipes_Products1_idx` (`Product_ID` ASC),
  CONSTRAINT `fk_Recipes_Products1`
    FOREIGN KEY (`Product_ID`)
    REFERENCES `Products` (`Product_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `RecipeIngredients`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `RecipeIngredients` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `RecipeIngredients` (
  `Quantity` INT NOT NULL,
  `Ingredient_ID` INT NOT NULL,
  `UnitOfMeasure` VARCHAR(45) NOT NULL,
  `Price` DECIMAL NOT NULL,
  `Recipe_ID` INT NOT NULL,
  PRIMARY KEY (`Ingredient_ID`, `Recipe_ID`),
  INDEX `fk_RecipeIngredients_Ingredients2_idx` (`Ingredient_ID` ASC),
  INDEX `fk_RecipeIngredients_Recipes1_idx` (`Recipe_ID` ASC),
  CONSTRAINT `fk_RecipeIngredients_Ingredients2`
    FOREIGN KEY (`Ingredient_ID`)
    REFERENCES `Ingredients` (`Ingredient_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_RecipeIngredients_Recipes1`
    FOREIGN KEY (`Recipe_ID`)
    REFERENCES `Recipes` (`Recipe_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SHOW WARNINGS;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

I have created a lot of tables and I am now trying to forward engineer my logical model into a physical database, but I am having trouble when it keeps saying "Can't add a foreign key constraint".
However, I know that the error is related to the Products referencing the Recipe_ID, but when I click on the relationship line from Recipes table to RecipeIngredients table, I see that the FK Recipe_ID IS REFERENCING the Recipe_ID primary key column in the Recipes table, not the Product table.

If that is the case, why is problem occurring? Any suggestions except recreating all of the tables again. Here is my picture model and picture of my problem.


Q: Swagger-play2 - hiding internal parameters I have configured swagger-play2 library version 1.7.1 (for play framework version 2.7) and have it up and running successfully. Our controller methods have an additional input: Http.Request request which is passed across the application for some logging and monitoring purposes. I need to hide this from the swagger specs, tried using @ApiParam(hidden = true) but it still shows up in specs. Is this flag not working as expected? how do I hide the input in this case? I'd like to know whether @ApiParam(hidden = true) has worked for anyone with swagger-play2 plugin, not with Spring.
Thanks.


Q: Flutter - AndroidManifest.xml corrupted after Flutter Upgrade I've just upgraded to Flutter 2 and upgraded an application along with it. I followed all the steps to upgrade the application, but now I can't seem to run the app because my AndroidManifest.xml file seems corrupted.
Here is the xml file (I've also added comments where the errors are appearing).
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.finances_management">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <application
        android:name="io.flutter.app.FlutterApplication" <-- Unresolved class 'FlutterApplication'
        android:label="finances_management"
        android:icon="@mipmap/ic_launcher"> <-- Cannot resolve symbol '@mipmap/ic_launcher'
        <activity
            android:name=".MainActivity" <-- Unresolved class 'MainActivity'
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme" <-- Cannot resolve symbol '@style/LaunchTheme'
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme" <-- Cannot resolve symbol '@style/NormalTheme'
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background" <-- Cannot resolve symbol '@drawable/launch_background'
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

I've seen elsewhere that people are just completely rebuilding their projects (as in completely generating a new project, stripping business logic from their Flutter 1.x app and copying it across to a Flutter 2.x app). Does anyone know what's happened to my XML file?

A: The best solution is to downgrade the Flutter . after that update AndroidManifest file


Q: Regarding GetProcAddress I have got MyDll.dll and its function defined as below
void pascal Myfunction(BOOL);

when I'm trying to use the function in another project i am unable get the address of the function with GetProcAddress(). Here is my code:
void callMyDll()
{
 HINSTANCE hDll;

 hDll=LoadLibrary(_T("MyDll.dll");

 if(hDll!=NULL)
 {
  cout<<"\n DLL Loaded \n";
 }
 else
  cout<<"\n DLL Not loaded\n"

 typedef void (__stdcall *MyFunction)(bool)

 Myfunction mf1 = (MyFunction) GetProcAddress(hDll, "MyFunction");

 if (mf1!=NULL)
  cout<<"\n Function Loaded Successfully \n";
 else
  cout<<"\n Function not loaded \n";

 FreeLibrary(hDll);
}

I'm getting output as:
DLL Loaded
Function not loaded

But when I'm trying with known DLLs like glut32.dll and its functions it is working fine.
I think it may be problem with its function like
void pascal MyFunction(BOOL);

Can anybody help me in this regard?

A: You need to use extern "C" to prevent name mangling and ensure the function is exported:
extern "C" __declspec(dllexport) void Myfunction(BOOL);

To view the exports from your DLL you can use dumpbin.exe utility that is shipped with Visual Studio:
dumpbin.exe /EXPORTS MyDll.dll

This will list the names of all exported symbols.
In addition to this do not have either of the following compiler switches specified:
Gz __stdcall calling convention: "Myfunction" would be exported as Myfunction@4
Gr __fastcall caling convention: "Myfunction" would be exported as @Myfunction@4

Note: I think last symbol is dependent on compiler version but is still not just "Myfunction".

A: The DLL export process is subject to name mangling and decoration. The long obsolete 16 bit pascal calling convention is equivalent to stdcall on 32 bit platforms.
First of all you should use extern "C" to specify C linkage and disable name mangling.
However, your function will still be subject to name decoration. If you export it with __declspec(dllexport) then it will in fact be exported with the name _Myfunction@4. If you wish to export it by its true name then you need to use a .def file.
However, the possibility still remains that you did not export the function from the DLL at all. Use Dependency Walker to check whether it was exported, and if so by what name.

A: Why are you using the pascal calling-convention? Perhaps that alters the names of symbols, and if so you might need to take that into account.

A: The symbol is going to be decorated, so it will never be called MyFunction, its more likely _MyFunction@4. you can quickly check this using something like dumpbin.
You can read up more on mangling here, if you want to avoid mangling, you need to use a def file to specify symbol names (or ordinals).


Q: i am dumping a piped data , but when i try to read using pickle.loads i get an error this code works fine thats piping out
    allWriteNodes=nuke.allNodes("Write")
    test = nuke.allNodes()
    for index,each in enumerate(test):
        wrtNodelst.insert(index,each.name())
        print index, each.name()
    sys.stdout.write(pickle.dumps(wrtNodelst))
    quit()
except RuntimeError:
  sys.stderr.write('could not find %s\n' % target_file)
  raise

but this line that is going to read in different file causes error:
print pickle.loads(process.stdout.read())

giving IndexError : list index out of range... any idea what might be causing it and out to read pickled stdout data ?
The Traceback  error
Traceback (most recent call last):
File "\RenderUI.py", line 384, in execApp
print pickle.loads(process.stdout.read())
File "D:\Python26\lib\pickle.py", line 1374, in loads
return Unpickler(file).load()
File "D:\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "D:\Python26\lib\pickle.py", line 1203, in load_setitems
mark = self.marker()
File "D:\Python26\lib\pickle.py", line 874, in marker
while stack[k] is not mark: k = k-1
IndexError: list index out of range

A: use
print pickle.load(process.stdout)

does this work?
read may not return the whole string.

A: This line:
   print index, each.name()

Causes issues, as it is sending debug output to stdout before the pickle is sent.


Q: Decimal/double to integer - round up (not just to nearest) How would you round up a decimal or float to an integer. For instance...
0.0 => 0
0.1 => 1
1.1 => 2
1.7 => 2
2.1 => 3

Etc.

A: Simple, use Math.Ceiling:
var wholeNumber = (int)Math.Ceiling(fractionalNumber);

A: Something like this?
int myInt = (int)Math.Ceiling(myDecimal);

A: Before saying it does not work, you have to check that ALL VALUES in the operation are double type.
Here is an example in C#:
 int speed= Convert.ToInt32(Math.Ceiling((double)distance/ (double)time));

A: Math.Ceiling not working for me, I use this code and this work :)
int MyRoundedNumber= (int) MyDecimalNumber;
                if (Convert.ToInt32(MyDecimalNumber.ToString().Split('.')[1]) != 0)
                    MyRoundedNumber++;

and if you want to round negative number to down for example round -1.1 to -2 use this
  int MyRoundedNumber= (int) MyDecimalNumber;
                    if (Convert.ToInt32(MyDecimalNumber.ToString().Split('.')[1]) != 0)
                        if(MyRoundedNumber>=0)
                           MyRoundedNumber++;
                        else
                           MyRoundedNumber--;

A: var d = 1.5m;
var i = (int)Math.Ceiling(d);
Console.Write(i);


Q: Node.js bindings for a Digital Asset Ledger Project I am working through Digital Asset Getting Started with Node.js bindings.
Running
npm install @da/daml-ledger

causes the following error message
npm ERR! code E401
npm ERR! 401 Unauthorized: @da/daml-ledger@latest

npm ERR! A complete log of this run can be found in:
npm ERR!     /...../.npm/_logs/2019-02-22T17_48_44_560Z-debug.log

here are the contents of that log file:
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/lib/nodejs/node-v10.15.1-linux-x64/bin/node',
1 verbose cli   '/usr/local/lib/nodejs/node-v10.15.1-linux-x64/bin/npm',
1 verbose cli   'install',
1 verbose cli   '@da/daml-ledger' ]
2 info using npm@6.4.1
3 info using node@v10.15.1
4 verbose npm-session 99e5e60df68735cb
5 silly install loadCurrentTree
6 silly install readLocalPackageData
7 http fetch GET 401 https://api.bintray.com/npm/digitalassetsdk/npm/@da%2fdaml-ledger 411ms
8 silly fetchPackageMetaData error for @da/daml-ledger@latest 401 Unauthorized: @da/daml-ledger@latest
9 timing stage:rollbackFailedOptional Completed in 4ms
10 timing stage:runTopLevelLifecycles Completed in 515ms
11 verbose stack Error: 401 Unauthorized: @da/daml-ledger@latest
11 verbose stack     at fetch.then.res (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/fetch.j
s:42:19)
11 verbose stack     at tryCatcher (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
11 verbose stack     at Promise._settlePromiseFromHandler (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/relea
se/promise.js:512:31)
11 verbose stack     at Promise._settlePromise (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/promise.
js:569:18)
11 verbose stack     at Promise._settlePromise0 (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/promise
.js:614:10)
11 verbose stack     at Promise._settlePromises (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/promise
.js:693:18)
11 verbose stack     at Async._drainQueue (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:133:
16)
11 verbose stack     at Async._drainQueues (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:143
:10)
11 verbose stack     at Immediate.Async.drainQueues [as _onImmediate] (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/blueb
ird/js/release/async.js:17:14)
11 verbose stack     at runCallback (timers.js:705:18)
11 verbose stack     at tryOnImmediate (timers.js:676:5)
11 verbose stack     at processImmediate (timers.js:658:5)
12 verbose cwd /home/vantage/DAnodeBindings
13 verbose Linux 4.15.0-45-generic
14 verbose argv "/usr/local/lib/nodejs/node-v10.15.1-linux-x64/bin/node" "/usr/local/lib/nodejs/node-v10.15.1-linux-x64/bin/npm" "install" "@da/daml-ledger"
15 verbose node v10.15.1
16 verbose npm  v6.4.1
17 error code E401
18 error 401 Unauthorized: @da/daml-ledger@latest
19 verbose exit [ 1, true ]

I followed the instructions in step 1 and step 2.  my .npmrc is updated with the response I received from entering
curl -umehul@digitalassetsdk:<API_KEY> https://api.bintray.com/npm/digitalassetsdk/npm/auth/scope/da

and I entered the command
npm config set @da:registry https://api.bintray.com/npm/digitalassetsdk/npm

What is causing the error?

A: From the comments it appears you missed a step of the setup, namely as the instructions tell you to paste the response of curl to ~/.npmrc.

The response should be pasted in the ~/.npmrc (in Windows %USERPROFILE%/.npmrc) file.

As an alternative, on Linux and MacOS you can just pipe the output of curl to ~/.npmrc as follows:
curl -u<USERNAME>:<API_KEY> https://api.bintray.com/npm/digitalassetsdk/npm/auth/scope/da >> ~/.npmrc

Using the >> operator will preserve the current content of ~/.npmrc and append the output of curl to the file (or create it if it's not there yet). If you want to overwrite the current ~/.npmrc file, just use the > operator instead.

A: The Bintary 'Set Me Up' Instructions (referenced in step 1.3 of https://docs.daml.com/app-dev/bindings-js/getting-started.html) say to run a curl command and the to run
npm config set @<SCOPE>:registry https://api.bintray.com/npm/digitalassetsdk/npm

When I skip the npm config step I have no problems.


Q: vue.js - Is there any way to render elements in two different divs using one v-for loop? The goal is to make the output look like this:

        tab 1
        tab 2

        tab 3

Currently I'm using this solution (using two v-for loops):
tabs.js (current)
export default {
    data() {
        return {
          tabs: {
              first: [{ name: 'tab1' }, { name: 'tab2' }],
              second: [{ name: 'tab3' }],
          }
        }
    }
    template: `

                {{ tab.name }}

                {{ tab.name }}

    `
}

I had an idea to do something like this but it performs more iterations than in the case with two loops:
tabs.js (idea)
export default {
    data() {
        return {
          tabs: {
              test: [
                  { name: 'tab1', category: 'first' },
                  { name: 'tab2', category: 'first' },
                  { name: 'tab3', category: 'second' }
              ]
          }
        }
    }
    template: `

                <template v-for="tab in tabs.test">
                    {{ tab.name }}
                </template>

    `
}

I read this topic but it contains slightly different solutions, which unfortunately didn't work in this case.

A: I did not see any harm in using two v-for (one for the object keys and another for the array elements) as far as it is all dynamic. You can give a try to this solution by using of Object.keys() :

new Vue({
  el: '#app',
  data: {
    tabs: {
      first: [{ name: 'tab1' }, { name: 'tab2' }],
      second: [{ name: 'tab3' }],
    }
  }
})

      {{ tab.name }}

A: There's no problem using more than one v-for loops. And there's no problem using nested v-for loops.
The problem I see with your current code is that it's not scalable. You're hard-coding the exact values of your tabs in <template />(e.g: first, second).
The main idea here is to loop through tabs and, inside each tab, to loop through each contents, without the <template> needing to know what the tab is or how many there are.
So that when you change your tabs to, say...
{
   tab1: [{ name: 'intro'}],
   tab2: [{ name: 'tab2-1' }, { name: 'tab2-2' }],
   tab3: [{ name: 'tab3' }]
}

template still works, without needing any change.

To achieve this type of flexibility, you need to use a nested v-for loop:

Demo:

new Vue({
  el: '#app',
  data: () => ({
    tabs: {
      tab1: [{
        name: 'intro'
      }],
      tab2: [{
        name: 'tab2-1'
      }, {
        name: 'tab2-2'
      }],
      tab3: [{
        name: 'tab3'
      }]
    }
  })
})
#tabs a { padding: 3px 7px }

      <a v-for="(link, key) in links"
         :key="key"
         :href="`#${link.name}`"
         v-text="link.name">

But I'd take it one step further and change the tabs to be an array:
data: () => ({
  tabs: [
    [{ name: 'intro'}],
    [{ name: 'tab1' }, { name: 'tab2' }],
    [{ name: 'tab3' }]
  ]
})

And use :id="'tab-' + name" on tab divs if you really need those unique ids. (Hint: you don't).
It makes more sense to me.

A: You could add a computed property being the .concat from both and loop for it
export default {
    data() {
        tabs: {
            first: [{ name: 'tab1' }, { name: 'tab2' }],
            second: [{ name: 'tab3' }],
        }
    },
    computed: {
       tabsCombined () {
          return this.tabs.first.concat(this.tabs.second)
       }
    },
    template: `

                <template v-for="tab in tabs.test">
                    {{ tab.name }}
                </template>

    `
}


Q: Changing Activity to Fragment with sqlite db I have recently tried to change a working sqlite populated listview activity into a fragment. I have made the changes needed but I continue to get errors that i dont understand. If any of you could help it would relieve serious frustration.
Here is my main activity
public class FoursFragment extends Fragment {

private DbHelper mHelper;
private SQLiteDatabase dataBase;

private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();

private ListView userList;
private AlertDialog.Builder build;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.display_activity, container, false);

    userList = (ListView) view.findViewById(R.id.List);

    mHelper = new DbHelper(getActivity());

    //add new record
    getView().findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            Intent i = new Intent(getActivity(),
                    AddActivity.class);
            i.putExtra("update", false);
            startActivity(i);

        }
    });

    //click to update data
    userList.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            Intent i = new Intent(getActivity(),
                    AddActivity.class);
            i.putExtra("Fname", user_fName.get(arg2));
            i.putExtra("Lname", user_lName.get(arg2));
            i.putExtra("ID", userId.get(arg2));
            i.putExtra("update", true);
            startActivity(i);

        }
    });

    //long click to delete data
    userList.setOnItemLongClickListener(new OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                final int arg2, long arg3) {

            build = new AlertDialog.Builder(getActivity());
            build.setTitle("Delete " + user_fName.get(arg2) + " "
                    + user_lName.get(arg2));
            build.setMessage("Do you want to delete ?");
            build.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {

                            Toast.makeText(
                                    getActivity(),
                                    user_fName.get(arg2) + " "
                                            + user_lName.get(arg2)
                                            + " is deleted.", 3000).show();

                            dataBase.delete(
                                    DbHelper.TABLE_NAME,
                                    DbHelper.KEY_ID + "="
                                            + userId.get(arg2), null);
                            displayData();
                            dialog.cancel();
                        }
                    });

            build.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alert = build.create();
            alert.show();

            return true;
        }
    });
    return view;
}

@Override
public void onResume() {
    displayData();
    super.onResume();
}

/**
 * displays data from SQLite
 */
private void displayData() {
    dataBase = mHelper.getWritableDatabase();
    Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
            + DbHelper.TABLE_NAME, null);

    userId.clear();
    user_fName.clear();
    user_lName.clear();
    if (mCursor.moveToFirst()) {
        do {
            userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
            user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
            user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));

        } while (mCursor.moveToNext());
    }
    DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName);
    userList.setAdapter(disadpt);
    mCursor.close();
}

}
Here is adapter that is called.
public class DisplayAdapter extends BaseAdapter {

 private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;

public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
    this.mContext = c;

    this.id = id;
    this.firstName = fname;
    this.lastName = lname;
}

public int getCount() {
    // TODO Auto-generated method stub
    return id.size();
}

public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

public View getView(int pos, View child, ViewGroup parent) {
    Holder mHolder;
    LayoutInflater layoutInflater;
    if (child == null) {
        layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        child = layoutInflater.inflate(R.layout.listcell, null);
        mHolder = new Holder();
        mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
        mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
        mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
        child.setTag(mHolder);
    } else {
        mHolder = (Holder) child.getTag();
    }
    mHolder.txt_id.setText(id.get(pos));
    mHolder.txt_fName.setText(firstName.get(pos));
    mHolder.txt_lName.setText(lastName.get(pos));

    return child;
}

public class Holder {
    TextView txt_id;
    TextView txt_fName;
    TextView txt_lName;
}

}
And here is the DBhelper.
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public DbHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT)";
    db.execSQL(CREATE_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}

}
The error i receive is as follows
03-20 13:15:50.108: E/AndroidRuntime(795): FATAL EXCEPTION: main
03-20 13:15:50.108: E/AndroidRuntime(795): java.lang.NullPointerException
03-20 13:15:50.108: E/AndroidRuntime(795):  atapp.norman.tennis.FoursFragment.onCreateView(FoursFragment.java:52)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:795)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:998)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.BackStackRecord.run(BackStackRecord.java:622)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1330)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.FragmentManagerImpl$1.run(FragmentManager.java:417)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.os.Handler.handleCallback(Handler.java:605)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.os.Looper.loop(Looper.java:137)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.ActivityThread.main(ActivityThread.java:4340)
03-20 13:15:50.108: E/AndroidRuntime(795):  at java.lang.reflect.Method.invokeNative(Native Method)
03-20 13:15:50.108: E/AndroidRuntime(795):  at java.lang.reflect.Method.invoke(Method.java:511)
03-20 13:15:50.108: E/AndroidRuntime(795):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-20 13:15:50.108: E/AndroidRuntime(795):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-20 13:15:50.108: E/AndroidRuntime(795):  at dalvik.system.NativeStart.main(Native Method)

I really don't mind if it is something stupid but really cant figure out what is going on! Thankyou!

A: Replace
//add new record
getView().findViewById(...

with
//add new record
view.findViewById(...

getView() in onCreateView() is too early - you haven't yet returned the view to the framework for getView() to return.


Q: Rollback not happening for ForEach container in SSIS I have the following use case:
I am trying to move the files in one folder to another folder. If any file is corrupt then whole process should be rolled back and no files should be moved.
For achieving this I am making use of one data flow task and one file system task. Data flow task would check for the integrity of the file and file system task would then move the file. These two tasks are in foreach container.
The transaction property of foreach is set to required and for the two tasks inside it, i am keeping it as supported.
Issue: There are 6 files in one folder which are to be moved. The file # 4 is corrupt. I want the whole task to rollback when system detects the corrupt file. However, this is not happening and files uptil file no 3 get moved.
Screen shot attached.


Q: Check type a variable I'm making a call to os/Create function and want to make sure in one of my test cases that the response is indeed of type *os.File.
Below is my code snippet. Though I made a lot of iterations but the motivation for these lines was this post.
//somevar -- gets *os.File from a function
var varType *os.File
tpe := reflect.TypeOf(varType).Elem()
fmt.Println(reflect.TypeOf(somevar).Implements(tpe)) // I expect a true or false

When I run this code I get a panic:
panic: reflect: non-interface type passed to Type.Implements [recovered]
    panic: reflect: non-interface type passed to Type.Implements

Please suggest what wrong I'm doing. All I want to check for is - some variable is of type *os.File - yes or no.

A: I think you may just be looking for
var varType *os.File
tpe := reflect.TypeOf(varType).Elem()
fmt.Println(tpe == reflect.TypeOf(somevar).Elem())


Q: python django ORM error/bug?: ...Cannot resolve keyword 'id' into field. Choices are: id,  i found the answer! this happened if i named a script exactly like the app name!
this is a corrected (simplified) version of the post.
i'm trying to run this standalone script (or even located in the app directory):
#!/usr/local/bin/python -W ignore
# coding: utf-8

import sys, os
sys.path.append('/usr/home/code')
os.environ['DJANGO_SETTINGS_MODULE'] = 'tuppy.settings'
from tuppy.tup.models import *

some_dict={}
print UserProfile.objects.filter(id=1)
print 'lallala'
print some_dict['unexisting_key']

and get the following error. mind that the script first prints the correct request result to UserProfile, and only facing another error prints incorrect error description:
# ./tup.py
[<UserProfile: 115>]
lallala
Traceback (most recent call last):
  File "./tup.py", line 10, in <module>
    p = UserProfile.objects.filter(id=1)
  File "/usr/local/lib/python2.6/site-packages/django/db/models/manager.py", line 141, in filter
    return self.get_query_set().filter(*args, **kwargs)
  File "/usr/local/lib/python2.6/site-packages/django/db/models/query.py", line 556, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/usr/local/lib/python2.6/site-packages/django/db/models/query.py", line 574, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/usr/local/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1152, in add_q
    can_reuse=used_aliases)
  File "/usr/local/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1045, in add_filter
    negate=negate, process_extras=process_extras)
  File "/usr/local/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1215, in setup_joins
    "Choices are: %s" % (name, ", ".join(names)))
django.core.exceptions.FieldError: Cannot resolve keyword 'id' into field. Choices are: credit_limit, id, insured_order_limit, mob_tel, resale_limit, sec_tel, status, user, voice_psw

#

A: I had the same issue on trying to get the first group from auth_group (Django v. 1.3.5)
Group.objects.get(name='First Group')
gave the same FeildError.
Stangerly this worked:
try:
    Group.objects.get(name="Active Rater")    #crazily not working
except django.core.exceptions.FieldError as e:
    group = Group.objects.get(name="Active Rater")    #crazily works

I have not yet dug into the django code to figure out why.


Q: visual c++ 2005 dll project and prerequisites needs to be installed on target machine i wrote a simple dll and i included below header files:
#include <windows.h>
#include <sddl.h>
#include <winsock.h>
#include <stdio.h>
#include <stdlib.h>
#include <mprapi.h>
#include <raserror.h>
#include <mprerror.h>
#include <strsafe.h>

so my dll works fine in my computer but in another computer not working. i installed vcredist_x86 on target machine but nothing changed. i also used setup deploy wizard and nothing happend. but when i installed visual studio 2005 on target machine my dll works perfectly.
so here is the question, how can i retrieve which prerequisites needs to be installed on target machine?
also i must mention that i compiled my code as c code "Compile as C Code (/TC)".
sorry for my poor english and thanks for your helps in advance.


Q: Busybox: Find all files on partition that have been modified since power-on I am trying to come up with a Busybox-compatible script (or one-liner) that lists every file inside a specified partition that has been modified since the last power-on. This should include files that were written during boot, where possible. It should not include files that are mounted separately to the specified partition e.g if I ask it to search the root partition / then it should automatically exclude /dev because it is a separate devtmpfs.

A: This command did the trick:
find / -xdev -type f -mmin -`cat /proc/uptime | cut -f1 -d" " | awk '{printf("%d", $1 / 60)}'`

A: find / -xdev -type f -newer /proc/1 ought to deliver same results, and a little simpler/shorter.


Q: How to ensure that gid in /etc/passwd also exist in /etc/group Background: The Unclassified RHEL 6 Security Technical Implementation Guide (STIG), a DoD guide, specifies in (STID-ID) RHEL-06-000294 that all user primary GIDs appearing in /etc/passwd must exist in /etc/group.
Instead of running the recommended 'pwck -rq' command and piping to a log then forcing the admin to manually remediate, it makes more sense to programmatically check if the users GID exists and, if not, simply set it to something which does exist such as "users" or "nobody"
I've been beating my head against this and can't quite get it.  I've failed at sed, awk, and some piping of grep into sed or awk.  The problem seems to be when I attempt to nest commands.  I learned the hard way that awk won't nest in one-liners (or possibly at all).
The pseudo-code for a more traditional loop looks something like:
# do while not EOF /etc/passwd
#   GIDREF = get 4th entry, sepparator ":" from line
#   USERNAMEFOUND = get first entry, separator ":" from line
#   grep ":$GIDREF:" /etc/group
#   if not found then
#      set GID for USERNAMEFOUND to "users"
#   fi
# end-do.

This seems like it should be quite simple but I'm apparently missing something.
Thanks for the help.
-Kirk

A: List all GIDs from /etc/passwd that don't exist in /etc/group:
comm -23 <(awk -F: '{print $4}' /etc/passwd | sort -u) \
         <(awk -F: '{print $3}' /etc/group  | sort -u)

Fix them:
nogroup=$(awk -F: '($1=="nobody") {print $3}' /etc/group)
for gid in $(
 comm -23 <(awk -F: '{print $4}' /etc/passwd | sort -u) \
          <(awk -F: '{print $3}' /etc/group  | sort -u)); do
  awk -v gid="$gid" -F: '($4==gid) {print $1}' /etc/passwd |
   xargs -n 1 usermod -g "$nogroup"
done

A: I'm thinking along these lines:
if ! grep "^$(groups $USERNAME | cut -d\  -f 1):" /etc/group > /dev/null; then
  usermod -g users $USERNAME
fi

Where
groups $USERNAME | cut -d\  -f 1

gives the primary group of $USERNAME by splitting the output of groups $USERNAME at the first space (before the :) and
grep ^foo: /etc/group

checks if group foo exists.
EDIT: Fix in the code: quoting and splitting at space instead of colon to allow the appended colon in the grep pattern (otherwise, grep ^foo would have also said that group foo existed if there was a group foobar).


Q: vim: multiple substitutions like sed Simply question,with sed is possible to do a multiple substitution
sed -e s/uno/due/ -e s/uno/due/

Is possible something similar with VIM internal substitution?
:'<,'>s/445/53/a/444/53/g

and
:'<,'>s/445/53/e/444/53/g

Doesn't work

A: Try this:
:'<,'>s/445/53/e | s/444/53/e
This works by concatenating Ex commands using the pipe (|) symbol and using the e substitution flag (see: :help :s_flags) to avoid raising an error when the pattern cannot be found.


Q: Access object in Typescript/Javascript class ResistorColor {
  private colors: string[]

  public colorValues = {
    black: 0,
    brown: 1,
    red: 2,
    orange: 3,
    yellow: 4,
    green: 5,
    blue: 6,
    violet: 7,
    grey: 8,
    white: 9
  }

  constructor(colors: string[]) {

    if( colors.length > 2)
    {
      for( key in this.colorValues)
      {
        if (this.colorValues[key].indexOf(colors[0]) !== -1)
        {
          return key;
        }
      }
    }

    this.colors = colors

  }
}

Idea is to find whether the color that has been input by the user is present in the object colorValues or not.
I referred to this: Find a value in a JavaScript object
I am getting the error of cannot find name key. I am using a Typescript, online editor.
Please explain to me what am I doing wrong here.

A: Look at @Owl 's answer, it fixes the other problems in your code too.
In your loop the variable key is not defined. You'd have to write it like this:
for (const key in this.colorValues) {
  ...
}

Although I wouldn't use a for-in loop, since objects have their own prototype properties, which you would also receive in a for-in loop. A better solution would be this:
for (const key of Object.keys(this.colorValues) {
  ...
}

But since you don't need the keys and just use them to retreive the values in the colorValues object, you could also use this:
for (const color of Object.values(this.colorValues) {
  ...
}

A: The cannot find name key error is answered by @MrCodingB
A nicer way to write this:
class ResistorColor {
  private colors: string[]

  public colorValues = {
    black: 0,
    brown: 1,
    red: 2,
    orange: 3,
    yellow: 4,
    green: 5,
    blue: 6,
    violet: 7,
    grey: 8,
    white: 9
  }

  constructor(colors: string[]) {

    const colorValues = Object.keys(this.colorValues);
    // colorValues is ["black", "brown", "red", ...]

    const isValid = colors.every(c => colorValues.includes(c));
    // `every` is used to tests whether all elements in the array pass the test implemented by the provided function,
    // in this case, we check whether each value exists in `colorValues`

    if (isValid) {
      this.colors = colors
    } else {
      throw new Error("Invalid Color(s)");
    }
  }
}

const resistorColor = new ResistorColor(["black", "brown"]); // correct
console.log("resistorColor has correct color");

const resistorColor2 = new ResistorColor(["black", "brown", "gold"]); // throws error
console.log("resistorColor2 has correct color");

Typescript playground

It's also possible to print out the incorrect colors value by using .filter()
class ResistorColor {
  private colors: string[]

  public colorValues = {
    black: 0,
    brown: 1,
    red: 2,
    orange: 3,
    yellow: 4,
    green: 5,
    blue: 6,
    violet: 7,
    grey: 8,
    white: 9
  }

  constructor(colors: string[]) {

    const colorValues = Object.keys(this.colorValues);
    const invalidColors = colors.filter(c => !colorValues.includes(c));

    if (invalidColors.length === 0) {
      this.colors = colors
    } else {
      throw new Error(`Invalid Color -> ${invalidColors.join(", ")}`);
    }
  }
}

const resistorColor = new ResistorColor(["black", "brown"]); // correct
console.log("resistorColor has correct color");

const resistorColor2 = new ResistorColor(["black", "brown", "gold", "foo"]); // throws error "Invalid Color -> gold, foo"

Typescript playground

A: Some of the errors that you are trying to prevent at run-time can be avoided at compile-time with stricter types.  You can create a type that only allows specific string literal color names and you can also enforce a minimum length on the colors array using tuple types.
It looks like this.colorValues might just be an enum?
enum COLOR_VALUES {
    black = 0,
    brown = 1,
    red = 2,
    orange = 3,
    yellow = 4,
    green = 5,
    blue = 6,
    violet = 7,
    grey = 8,
    white = 9
}

type ColorNames = keyof typeof COLOR_VALUES;

class ResistorColor {

    // can have two or more colors
    constructor(private colors: [ColorNames, ColorNames, ...ColorNames[]]) {
    }
}

Now you can only call the constructor with valid arguments.
const a = new ResistorColor(["black", "blue"]); // ok
const b = new ResistorColor(["black", "blue", "red"]); // ok
const c = new ResistorColor(["black"]); // error: Source has 1 element(s) but target requires 2.
const d = new ResistorColor(["white", "cyan"]); // error: Type '"cyan"' is not assignable to type

Typescript Playground Link
If this.colorValues is an instance variable I would create the initial value outside of the class so that we can use typeof.
const initialValues = {
    black: 0,
    brown: 1,
    red: 2,
    orange: 3,
    yellow: 4,
    green: 5,
    blue: 6,
    violet: 7,
    grey: 8,
    white: 9
  }

type ColorNames = keyof typeof initialValues;

class ResistorColor {

    public colorValues = initialValues;

    // can have two or more colors
    constructor(private colors: [ColorNames, ColorNames, ...ColorNames[]]) {
    }
}

Typescript Playground Link


Q: iOS Keychain data after renewing distribution certificate My distribution certificate is about to expire & I am planning to submit a new update of app to AppStore. My question is what happens to my app's keychain data after updating the distribution certificate ?
I have read this questionwhich describes that
On iPhone, Keychain rights depend on the provisioning profile used to sign your application. Be sure to consistently use the same provisioning profile across different versions of your application.

But as I am not updating my provisioning profiles but distribution certificate , can anybody tell me what happens after updating distribution certificate ?
Any kind of information will be very helpful. Thanks in advance

A: Apple removed this sentence from the docs, because it's not true. Team ID and keychain-access-groups are the most important things that should match.
Check the github link below a code example of two apps reading and writing the same keychain item:
https://github.com/evgenyneu/keychain-swift/issues/103#issuecomment-491986324


Q: space of schwartz, problem my question is:
Let $f\in S(\mathbb{R})$, with $f(0)=0$, then there exists $g\in S(\mathbb{R})$ such that:
$$ f(x)=xg(x)\;\text{ for all }\;x\in \mathbb{R}.$$
I need to prove this.

A: There is a convenient way to define $g$ which is

$$
g(x)=\int_0^1f'(tx)dt\qquad \forall x\in \mathbb{R}
$$

This handles $x\neq 0$ and $x=0$ simultaneously. Then it only remains to differentiate under the integral, etc...

A: Note that on $\Bbb R\setminus \{0\}$ the function $f(x)/x$ is $\mathcal C^\infty$ and it still satisfies the decreasing properties on infinity. The only thing to prove is that in zero our function $g(x)=f(x)/x$ is still $\mathcal C^\infty$.
First of all, obviously $g(0)=f'(0)$ by L'Hôpital's rule. Then again, you need to show that $$\frac{d^n}{dx^n}(f(x)/x)$$is continuous at zero. Leibnitz rule will give us
$$\frac{d^n}{dx^n}(f(x)/x) = \sum_{k=0}^n (-1)^{n-k}(n-k)!\binom{n}{k}\frac{f^{(k)}(x)}{x^{n-k+1}}$$
$$=(-1)^{n}\frac{n!}{x^{n+1}}\sum_{k=0}^n \frac{f^{(k)}(x)(-x)^{k}}{k!}.$$
The sum - easy to recognise - is a Taylor developement of $f(0)$ in the point $x$, hence we can replace it by $f(0) - (-1)^{n+1}\frac{f^{(n+1)}(x)(-x)^{n+1}}{(n+1)!}+\mathcal O(x^{n+2}) $, which results in
the following:
$$\frac{d^n}{dx^n}(f(x)/x)= \frac{n!}{x^{n+1}} \left(  \frac{f^{(n+1)}(x)(-x)^{n+1}}{(n+1)!}+\mathcal O(x^{n+2})\right).$$ It's evident that the limit $x\to 0$ exist and is equal to $\frac{ f^{(n+1)}(0)}{n+1}$, which concludes the proof.


Q: loosing pointers on vector of struct instances, with pointers in the struct Not sure if the title is right or not, but here it goes:
If I have for example the following structure:
struct strA{
    int x;

    strA(int x);
}

strA::strA(int x){
    this->x = x;
}

And another structure that uses a pointer to the previous one:
#include strA

struct strB{
    int y;
    strA *var_strA;

    strB(int y);
    ~strB(){
        delete var_strA;
    }
};

strB::strB(int y){
    this->y = y;
    var_strA = new strA(123);
}

Then if I do from the main aplication a vector of strB items:
std::vector<strB> vectB;

main(){
    strB *itemB = new strB(456);
    vectB.push_back(*itemB);
    delete itemB;

    //more code
}

If I try to access the var_strA on the item in the vector, is empty. And also, I get an error when by deleting the item on the vector, since the destructor tries to delete var_strA again.
Comming from Java... I'm really getting lost with the damn pointers.
thanks in advance

A: You need a copy constructor and a copy assignment operator on that pointer-holding type, i.e. follow the rule of three. Here's a great resource here on SO: What is The Rule of Three?


Q: performSelector unable to run while UITableView is dragged? I have a UITableViewController with its default UITableView. I begin slowly dragging the table with my finger to scroll, i.e. not flicking it with my finger. Every time the table moves on-screen the scrollViewDidScroll method of the controller is called; when some conditions I've specified are met, one of these calls to scrollViewDidScroll uses performSelector:withObject:afterDelay to schedule some action at a later time.
However, I'm finding that the action will not execute until I release my finger. For example, if I set the afterDelay parameter to 2 seconds, but hold my finger for 5 seconds, when I release my finger and the action executes it's 3 seconds too late. Is there any way to allow the action (which is to update the UI and so must run in the main thread) to execute while the finger is still against the screen?
Thanks!

A: This is because when a UIScrollView (UITableView's superclass) is scrolling, it changes its runloop in order to prioritize the scrollView over whatever the application was doing. This is happening to make sure scrolling is as smooth as it can be.
try using this version of delayed method:
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes;

for the modes, I'd suggest starting with an array that contains the following:
[[NSRunloop currentRunLoop] currentMode],
NSDefaultRunLoopMode


Q: Differentiation of $x$ to the power of $y$ with respect to $x$ As the title suggests, I need to differentiate $x$ to the power of $y$ with respect to $x$. Not sure how to start. Do I need to take natural log on both sides?
That is: $\dfrac{d}{dx}x^y=?$

A: We need $$\frac{d(x^y)}{dx}$$
One of the ways could be:
Let $f(x)=x^y\implies \ln f(x)=y \cdot \ln x$
Using Chain Rule for the Left hand side,
$$\frac{\ln f(x)}{dx}=\frac{\ln f(x)}{d f(x)}\frac{d f(x)}{dx}=\frac{f'(x)}{f(x)}$$
and  Product Rule of Differentiation  for the Right,
$$\frac{d(y \cdot \ln x)}{dx}=y\cdot \frac{d(\ln x)}{dx}+\ln x\cdot \frac{dy}{dx}=\ln x\cdot \frac{dy}{dx}+\frac 1x\cdot y$$
$$\implies \frac{f'(x)}{f(x)}=\ln x\cdot \frac{dy}{dx}+\frac yx$$
$$\implies f'(x)=f(x)\left(\ln x\cdot \frac{dy}{dx}+\frac yx\right)=x^y\left(\ln x\cdot \frac{dy}{dx}+\frac yx\right)$$

A: As $x^y=(e^{\ln x})^y=e^{y\ln x}$
$$\frac{d(x^y)}{dx}=\frac{d(e^{y\ln x})}{dx}$$
$$=\frac{d(e^{y\ln x})}{d(y\ln x)}\cdot \frac{ d(y\ln x)}{dx}$$ (applying Chain Rule)
$$=e^{y\ln x}\left(y\cdot \frac{d(\ln x)}{dx}+\ln x\cdot\frac{dy}{dx}\right)$$
$$=x^y\left(y\cdot\frac1x+\ln x\cdot\frac{dy}{dx}\right)$$


Q: Java get each digit from 2 strings and calculate it The task is asking me to insert 2 strings of a very huge number and sum them from right to left like the way we studied in primary school like:
23 + 28 =
(2 + 2 + <1> (this is the left 1 >>> keep reading ))(3 + 8 (give the left <1> from 11 sum with the two front numbers)) =
 51.
The algorithm is ok but when I try to do like (just default that the 2 number has the same length so I get lenA and not greater than 10 to make easier):
 int len = a.length();
 String result="";
 for(int i = len; i>0 ; i--) { //<- We only need it to loop how many times
      result = Integer.valueOf( a.charAt(len-1) ) + Integer.valueOf( b.charAt(len-1) ) + "" + result;//<<<because we sum them from right to left
      lenA--; lenB--;
 }

and that (<<<) line always give me the error.
This is just one of a many ways I tried if it's wrong and you have a solution, please just guide me, sometimes i think too much and forgot a lot of small details :))
So the question here is how can i change it from a digit of String to Integer, calculate it and print out String again. But after I read the .charAt() info it said: "Returns the char value at the specified index." so the question maybe confuse between the first question and Convert from a digit from String use charAt -> become Char then convert Char to Integer to calculate and finally convert back to String so that I can + with String result.
I tried a lot of way but still can't solve it.

A: int lena = a.length();
int lenb = b.length();
int inta[] = new int[lena];
int intb[] = new int[lenb];
int result[];
int carry = 0, maxLen = 0, tempResult;

if(lena >lenb)
   maxLen = lena + 1;
else
   maxLen = lenb + 1;

result = new int[maxLen];

for(int i = lena - 1; i>=0 ; i--) {
   inta[i] = Integer.valueOf( a.charAt(i) );
}

for(int i = lenb - 1; i>0 ; i--) {
   intb[i] = Integer.valueOf( b.charAt(i) );
}

for(int i = maxLen - 1; i >= 0; i--) {
   result[i] = 0;
}

for(int i = 1; i < maxLen - 1; i++) {
   tempResult = 0;
   if(lena > i)
       tempResult += inta[lena - i];
   if(lenb > i)
       tempResult += intb[lenb - i];
   result[maxSize - i] += tempResult % 10;
   result[maxSize - i - 1] = tempResult / 10;
}

String res = "";
for(int i = 0; i < maxLen; i++) {
   res += result[i];
}

System.out.println(res);

I think that would do what you want and will avoid most simple mistakes (couldn't try it, no acces to an IDE).
I actually separate the two string into their inside number and then add them into the result tab.
Then I put the result tab into a string that I print.


Q: Deserialize ISO 8601 date time string to C# DateTime I'm trying to use:
JsonConvert.DeserializeObject<DateTime>( "2009-02-15T00:00:00Z", new IsoDateTimeConverter() )

But it gives me a FormatException: Input string was not in a correct format.
What am I doing wrong?

A: If you're parsing a single value, the simplest approach is probably to just use DateTime.ParseExact:
DateTime value = DateTime.ParseExact(text, "o", null);

The "o" pattern is the round-trip pattern, which is designed to be ISO-8601:

The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values.

I haven't specified a format provider, as it doesn't matter:

The pattern for this specifier reflects a defined standard (ISO 8601). Therefore, it is always the same regardless of the culture used or the format provider supplied.

If you need Json.NET to handle this transparently while deserializing other values, it may be a trickier proposition - others may know more.
Additionally, just as a plug, you may wish to consider using my Noda Time project, which supports ISO-8601 and integrates with JSON.NET - albeit not in a pre-packaged way just yet.


Q: Results of a survival analysis change when converting the data to counting process format Consider the following simple example:
library( survival )
data( veteran )

 coef( coxph(Surv(time, status) ~ trt + prior + karno,
           data = veteran) )
         trt        prior        karno
 0.180197194 -0.005550919 -0.033771018

Note that we have neither time-dependent covariates, nor time-varying coefficients, so the results should be the same if we change to counting process format, no matter where we cut the times.
That's true if we cut at event times:
veteran2 <- survSplit( Surv(time, status) ~ trt + prior + karno,
                       data = veteran, cut = unique(
                              veteran$time ) )

 coef( coxph(Surv(tstart,time, status) ~ trt + prior + karno,
                  data = veteran2 ) )
         trt        prior        karno
 0.180197194 -0.005550919 -0.033771018

But quite interestingly not true, if we cut at every day:
veteran3 <- survSplit( Surv(time, status) ~ trt + prior + karno,
                       data = veteran, cut = 1:max(veteran$time) )

 coef( coxph(Surv(tstart,time, status) ~ trt + prior + karno,
                  data = veteran3 ) )
         trt        prior        karno
 0.180197215 -0.005550913 -0.033771016

The difference is not large, but definitely more than just a rounding error, or something like that.
What's going on? How can the results get wrong, especially by including more cutpoints?


Q: jquery ajax return value and done function I found this little example on jquery documentation page. I always tried returning value from ajax function and I was always told that there is some problem of sync and async thing and I can't return value out of $.ajax function without making it async.
$.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $(this).addClass("done");
});

In the example above, on what this done function is applied(whats being used as $(this) in example).
one more thing, as the ajax function can't set global variables, can't the be set in this done too? cant I return value out of done function either?

A:
what this done function is applied

$.ajax returns a jqXHR object (see first section after the configuration parameter description) wich implements the promise interface and allows you to add callbacks and get notified of changes of the Ajax call.

whats being used as $(this) in example

Inside the callbacks for $.ajax, this refers to the object context refers to in the configuration or the jqXHR instance if context was not set. In this case it refers to document.body:

context: This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).

This and more is all explained in the documentation: http://api.jquery.com/jQuery.ajax/

as the ajax function can't set global variables

That is not correct, any function can set global variables. The problem with asynchronous functions is that you are likely accessing the variable before it was set.

can't the be set in this done too

See above

cant I return value out of done function either

You can return a value (as in putting a return statement inside the callback), but you cannot return it to your code, since jQuery is calling the callback internally and just ignoring the return value.