Drupal 7 CKeditor always saves Array

Question: I am developing a custom module with some entities inside. I created a form to edit them and I would like to use CKEditor in one of the fields.
I can see and use the CKEditor, but when it's time to save, it always saves the value 'Array'. You can find the code I am using below:
<code>$form['description'] = array(
        '#type' => 'text_format',
        '#format' => 'full_html',
        '#title' => t('Content'),
        '#default_value' => $entity->content,
        '#weight' =>2,
        '#required' => FALSE,
    );
</code>
I'd say CKEditor changes the value before sending the form POST but I am not sure.
Any ideas?
Comment: This may help http://drupal.stackexchange.com/questions/33254/saving-a-field-of-type-text-format-as-a-system-setting-variable
Answer: Ok, that was easier than I thought. When using WYSIWYG editors you have to save the info differently.
For a normal textarea:
<code>$entity->content = $form_state['values']['description']
</code>
For a WYSIWYG:
<code>$entity->content = $form_state['values']['description']['value']
</code>

Drupal 7 CKeditor always saves Array


How to move an drag and drop item to a certain position, when located over canvas?

Question: I am working on a Tablet-environment with draggable objects.
The drag & drop works, it is even possible to drag several objects at once, when implemented.
References are :
Reference 1 & Reference 2
This is how the current version of my code looks like:

<!DOCTYPE html>

  <meta charset="utf-8">
    <meta
     name='viewport'
      content='width=50px, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,'
     />

  <title>Clean up</title>

<main1 id="main1">
    <div1 class="draggable" id="d1-0""></div1>
</main1>

The idea is, that the red box (div1) can be moved, dragged and dropped everywhere on the screen. But it needs to be moved to its very initial starting position, when it enters the yellow canvas. (The idea is to "clean up" and "move objects back to where they came from".)
Comment: You want the `red div` to snap into a specific location as soon as it enters the `yellow div` or when you release the mouse?
Comment: Thank you, Alex, for your quick response! When the red div enters the yellow div and the mouse is released.
Answer: You should use jQuery UI's draggable and touch punch for mobile friendliness
Let me know if this is close to what you're looking for and we can adjust as needed

$(document).ready(function() {
  $('#div1').draggable();
  $('#container').droppable({
    drop: function( event, ui ) {
       alert("You dropped the red on the yellow");
    }
  });
  $(document).on("click", "#animateBtn", function() {
    //Simple animate w/ just specifying the offsets
    //$('#div1').animate({top:"250px", left:"250px"});

    //Other animate options
    $('#div1').animate({
        top:"15px",
        left:"15px"
      }, {
        duration:555, //Animation time in pixels
        easing:"easeOutQuart"  //See https://api.jqueryui.com/easings/
      });
  });
});
#container {
  width: 200px;
  height: 200px;
  position: relative;
  background: yellow;
  top: 100px
}

body {
  position: relative;
}

#div1 {
  position: absolute;
  top: 0px;
  left: 100px;
  height: 72px;
  width: 72px;
  background: red;
  border: 0px solid #666;
  margin: 0;
  padding: 0;
}

#animateBtn {
  position:fixed;
  right:10px;
  bottom:10px;
  display:inline-block;
  padding:3px 5px;
  background-color:green;
  color:white;
  border-radius:6px
}
<!DOCTYPE html>

  <meta charset="utf-8">
    <meta
     name='viewport'
      content='width=50px, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,'
     />
  <title>Drag and Drop</title>

  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

Animate

Comment: Thank you very much, Tom Gerken! Yes, that is really good, thank you! The next issue would then be to add a function to move the red div to certain coordinates on the screen - does it make sense to do this with animate?
Comment: I assume a  function to move the red div to certain coordinates on the screen has to be added - Which means, that the initial coordinates of the red div are required (could they be extracted from the #div1 in css?) and that there needs to be a function to move the red div to the respective coordinates. I found several tutorials on how to move an object relatively to the current position (e.g [https://www.w3schools.com/howto/howto_js_animate.asp]), which is not really, what I was searching for.
Comment: No prob Melanie, yeah use jQuery's animate function, specifying the top and left offsets (often you'll need to add half the width/ height of the object if you are trying to center it somewhere)  I added an example to my answer
Comment: I tried to include something like this into the code of the function, but I seem to have made a mistake, as the div is not draggable anymore:  $(document).ready(function() {
  $('#div1').draggable();
  $('#container').droppable({
    drop: function( 100, 0 ) {
       var d = document.getElementById('div1');
  d.style.position = "absolute";
  d.style.left = 100 +'px';
  d.style.top = 0 +'px';
    }
  });
});
Comment: Wow, that is really great! Thank you very much @Tom Gerken! I will try to merge the animation with the drop function (to replace the alert with the animation)!
Comment: Ok, I tried to do this, but I did not manage to make it work. I tried this:     $(document).ready(function() {
      $('#div1').draggable();
      $('#container').droppable({
        drop: function() {
        $('#div1').animate({
            top:"15px",
            left:"15px"
          }, {
            duration:555,
            easing:"easeOutQuart"
          }
        }
      });
Comment: Found a bracket-mistake, now it works! Will post the code below! :) Thank you so much!!! :D
Answer:

<!DOCTYPE html>

  <meta charset="utf-8">
    <meta
     name='viewport'
      content='width=50px, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,'
     />
  <title>Drag and Drop</title>

  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

  <title>Clean up</title>

Answer: I didn't see a mention of jQuery but w3schools has a working example that goes without. Could you some touchup though:
/**
 * Make object draggable
 * @param {Element} element
 */
const addDraggable = (element)=> {
    let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;

  const dragMouseDown = e => {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    [pos3, pos4] = [e.clientX, e.clientY];
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  };

  const elementDrag = e => {
        console.log(e.clientX, e.clientY);
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    [pos1, pos2] = [pos3 - e.clientX, pos4 - e.clientY];
    [pos3, pos4] = [e.clientX, e.clientY];
    // set the element's new position:
    [element.style.top, element.style.left] =
            [(element.offsetTop - pos2) + "px", (element.offsetLeft - pos1) + "px"];
  };

  const closeDragElement = _ => {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  };

  element.onmousedown = dragMouseDown;
}

document.addEventListener("DOMContentLoaded", event=> {
  _('#logo-top').addEventListener('click', event=> {
    event.stopPropagation();
    _('#logo-top').classList.toggle('active');
    _('nav').forEach( n=> n.classList.toggle('collapsed') );
    _('main').classList.toggle('extended');
  });

    addDraggable( _('#help-text') );
    _( '#help' ).addEventListener( 'click', ()=>{ _('#help-text').classList.toggle('active')} );
    _( '#help-text-close' ).addEventListener( 'click', ()=>{_('#help-text').classList.toggle('active')}  );

});

Another way would be to use the Drag Operations


How can I delete a file in a cron job?

Question: A custom module is creating a file in public:// folder, that should reside there only temporary. How can I delete this temporary file in a cron job?
Answer: Write a function in a custom module:
/**
* Implements hook_cron().
*/
mymodule_cron() {
  // Get the file id somehow, make this more generic, perhaps use file_scan_directory()?
  $uri = 'public://temporary/myfile.pdf';
  $files = \Drupal::entityTypeManager()
    ->getStorage('file')
    ->loadByProperties(['uri' => $uri]);
  if (count($files)) {
    foreach ($files as $item) {
      file_delete($item->id());
    }
  }
}

Answer: Also in drupal, we can delete a file on a cron job via setting the file status=0.
After 6 hours the cron job will delete the files whose status is zero.
     $filename = "myfile.pdf";
     $tmp_file = file_save_data('', 'public://' . $filename);
     $tmp_file->status = 0; // will automatically delete
     $tmp_file->save();

How can I delete a file in a cron job?


How can I bulk update the language for all content?

Question: I have a site that has been duplicated from an english site and has been translated into Italian.
I installed Italian as a language and have set it as default. However, all of the nodes created in the cloned site are still set to "english".
How can I bulk update the language for all content, either programmatically or directly with SQL?
Answer: Load the nodes entities and set its langcode column
For example:
<code>$w_node = entity_load('node', $nid);
$w_node->set('langcode', $data_langcode);
$w_node->save();
</code>
To do it in bulk, i guesing that you should create a new action to be available in the defaults bluk operations for the admin/content view


Enums in Generic constraints

Question: I built a extension method for Enums (Enumerations) - , name it, say GetEnumSecondName
static string GetEnumSecondName(this Enum myEnumInstance)    {...}

Now, I have a generic method, that should take a Enumeration and return all the second names for that type.
List<string> GetSecondNames<T : ?T:Enum ? >()
{
  // ...

  foreach T member in GetAllMembers<T>()
    // should work only for Enum instances
    resultList.Add(member.GetEnumSecondName());

  // ...
}

Is there a workaround to do it?
Edit:
As I understood (thanks to Jon Skeet), C# does not support thins kind of constraint. If there are any VB.NET expert to confirm that "ordinary" VB.NET does not support it either. Thanks.
Comment: possible duplicate of [Interesting "params of ref" feature, any workarounds?](http://stackoverflow.com/questions/1776020/interesting-params-of-ref-feature-any-workarounds)
Answer: Yes, there's a workaround. You may not like it though. You have to rewrite the IL to express the constraint you want - because the CLR allows it, but C# doesn't. (The compiler respects the constraint; it just doesn't let you express it in C# code.)
I have a project called Unconstrained Melody which does exactly this, introduced in a blog post.
It's regrettable that you can't express this, and maybe it'll be fixed in a future version of the language. For now, IL rewriting is all there is as far as I know.
EDIT: I've just tried the constraint you'd want in VB:
Foo(Of T As { System.Enum, Structure }) (...)

And the compiler complains with:
error BC32061: 'Enum' cannot be used as a type constraint.

So no, you can't do it in VB either. Oddly enough, the web page about that error doesn't mention the restriction...
EDIT: To anyone wanting to play with Unconstrained Melody, there are a few steps required to get it working:

You need to make sure you have an appropriate SDK directory as referred to by ConstraintChanger\Program.cs. In particular, check in \Program Files\Microsoft SDKs\Windows to see what version you've got - and change Program.cs appropriately
Critically, you need a directory called "Rewritten" at the top level (i.e. alongside lib)
If you're using VS2010 you'll need to go through the project upgrade at the start

Once all of that is correct, you should just be able to hit Ctrl-Shift-B and get a working build. Do not remove and replace the project references - the test assembly needs to refer to the rewritten one, not the project it's created from.
I'll attempt to address some of these issues tonight - and possibly even create a Nuget package...
Comment: @serhio: If you work in VB, why did your write your question in C#? Way to waste people's time... I don't know whether VB allows it. Read the VB spec to check.
Comment: VB doesn't afaik, but F# supports it.
Comment: @Jon Skeet: I wrote it in C#, because I write all my examples in C#. The answer from people came faster if I Write in C# if I write it in Vb.NET. And I didn't specify the C# tag...
Comment: @serhio: But how is that good if the answers aren't then useful? You should *at least* have mentioned that you were really interested in VB.
Comment: @Jon: Almost any of questions here are not language specific. I didn't know *a priori* that this constraint could be language specific...
Comment: @serhio: No, *lots* of the questions here are language specific. It's bad enough to not mention the language you're interested in - it's downright rude to give code in one language when you're only interested in a different one.
Comment: @Jon: I understood. In my practice I have not almost any question of that kind. But I will pay attention to this in the future.
Comment: @Jon: actually I find it great that he took time and wrote the example in C#. I agree with him that there's a lot of more answers for code written in C# than VB.net (although I haven't checked any statistics). I don't think that he answered your comments in a rude way, it's rather you that answer him with an attitude.
Comment: @jgauffin: Because I object to my time being wasted. If someone asks me a question, I expect *that question* to be what they want an answer to - so it annoys me when I put in effort answering exactly that question, only to find out that they *really* wanted something else. Serhio knew to start with that he wanted an answer in VB - I didn't. Suppose this *was* allowed in VB - I could have tried that quickly instead, and not written any of the stuff about C#. All the C# bits would be irrelevant, and therefore a waste of my time. (Continued)
Comment: *As it happens* in this case the restrictions are the same, but there's no reason to suppose they would be, or that the answer would be the same. There are plenty of topics where this would apply - lambda expressions, anonymous types, iterator blocks, dynamic typing etc. I view it as disrespectful of potential answerers' time (not just me - anyone else answering the question too) to have relevant information and not bother including it in the question.
Comment: the google project unconstrained don't work on my machine: The type 'UnconstrainedMelody.Test.BitFlags' cannot be used as type parameter 'T' in the generic type or method 'UnconstrainedMelody.Flags.IsFlags()'. There is no boxing conversion from 'UnconstrainedMelody.Test.BitFlags' to 'UnconstrainedMelody.IEnumConstraint'. In ...UnconstrainedMelody\UnconstrainedMelody.Test\FlagsTest.cs 11 27 UnconstrainedMelody.Test
Comment: @serhio: I suspect you're trying to do something against the un-rewritten IL... or you haven't fixed the code to use the correct rewriter location. Have you just opened the project and tried to build it as-is?
Comment: @Jon: I tried first, but no success I saw a icon (!) on the unconstrainedMelody reference, so I removed it and replaced with the project (unconstrainedMelody) reference. Didn't help. I tried to build just the "UM" project, but "The command "...UnconstrainedMelody\\ConstraintChanger\bin\Debug\ConstraintChanger"" exited with code 1." I converted the solution in VS 2010...
Comment: @Jon skeet: All I'm saying is that his intentions was good. You of all should know that it's not easy to write a good question with all relevant details. At least I have written several answers which answered something else than the OP really wanted due to incorrect or missing details. But that's not a reason to give an attitude, is it? After all, we do answer questions because we want to, not because we are forced to.
Comment: @serhio: Ah. No, you absolutely should *not* have removed that reference. It's deliberately set to the rewritten code, which needs to be built first. You need to adjust ConstraintChanger to refer to the relevant ilasm binary, IIRC.
Comment: @jgauffin: Every possible relevant detail can be hard to work out. Which language you're interested in *isn't* hard to work out or state. And I answer questions because I want to help people - which makes it frustrating when the person I'm *trying to help* wastes my time. That time could be spent helping someone who *doesn't* write a question in one language but then ask for an answer in a different one. Would you feel any differently if you'd spent an hour on a long answer which turned out to be entirely useless to the person you were answering?
Comment: without removing the reference, 65 errors, firrst one:
Error 1 The name 'Enums' does not exist in the current context C:\Documents and Settings\me\Desktop\test\UnconstrainedMelody-0.0.0.2-src\UnconstrainedMelody\UnconstrainedMelody.Test\EnumsTest.cs 13 32 UnconstrainedMelody.Test
Comment: ok, thank you. Don't spend your time with me man, if you don't want! I don't force you to answer me!
Comment: @serhio: Yes, you first need to build the constraint changer, then run it successfully on the non-test assembly (which is part of the build). I suspect that *just* fixing the local of ilasm.exe in ConstraintChanger and then doing Rebuild Solution would have sorted it out...
Comment: @serhio: I have no objection to spending time helping people. I have an objection to people not taking the time when they ask for help to thinking what might be relevant, and presenting that information accordingly. I'll try building Unconstrained Melody from scratch on my own laptop and update this answer with instructions...
Comment: I built successfully the ConstraintCharger, but I don't understand the "then run it successfully on the non-test assembly" (how to "run" the *ConstraintChanger* "on the" *UnconstrainedMelody*)
Comment: @serhio: it should run automatically in the build. It sounds like you saw it fail to run properly earlier on.
Comment: @serhio: I've edited the answer with the steps you need to get it working. Hope that helps.

Enums in Generic constraints


How to check authenticity of iOS device

Question: I have an app-server process that needs to check if the device making a request is an actual iOS device.  I used to do this by taking advantage of push notifications.  The user first authorizes push.  Each time the user makes a specific type of request, I push a code to that device with which the app uses to make a second "authenticated" request to the app server.  That additional channel of going through APNS would, in a sense, prove the authenticity of the requester's device.  This makes it difficult for a person to spoof the request because they would not be able to receive the push notification with the needed code.
Recently though Apple started enforcing the rule that apps cannot require the user to accept push notifications in order to use the app, even though we do not use push notifications for alerts.
Is there any comparable way for my app server to check with Apple that a request is coming from my app on an actual iOS device?  Or is this an unrealistic expectation to be able to determine this.
Comment: There is none, but you can use HTTPS to difficult (in most cases prevent) sniffing. You can also make you server generate an identifier/token for each device that doesn't have one, and make that device store it locally, or preferably on its keychain. Then the device informs the token via HTTPS and your server is able to to identify the device. I believe this should solve your concern. Does it help?
Comment: Is your real goal to ensure a request coming to your server is really coming from your app?
Answer: I could not find the article now, but some guys managed to register raspberry pi as a iOS device and receive push notifications via wifi... that I believe would be concrete proof that not even your first "2 way authentication" is really safe...
Now, directly answering, NO, there's no way for your app server to check if the request did come from a iOS device because all info in a TCP/UDP package is 100% "spoofable"...
Comment: Which is why I posted my comment below the question. Most likely, checking for an iOS device is the wrong approach. The approach should be to authenticate that the request is coming from a specific app and there are proper solutions to that.

How to check authenticity of iOS device


C# - Windows Mobile - Pairing with Zebra RW 420

Question: Update: This may not be "Pairing". This may just need to have a service started and bound to a port. However, this code is not storing it either. I need the device to be stored even after the application is closed.
I am building a program specifically suited for Zebra RW 420's on a Windows Mobile 6 Handheld device. The application needs to allow a mobile device to pair with the printer on COM1. I believe I am very close to getting it, but I can't get the pair request to work.
I am able to communicate with the printer and even print by directly connecting and printing, but I can't get the mobile device to actually pair with it. I've tried a variation of pins to include null, "1", "0000", and "1234". No matter what, the method always returns false. Any suggestions or ideas why this might be failing? I can pair the device just find in the WM6 Bluetooth menu, but not in my application.
It might be important to note that the little light bulb icon on the printer comes on when the program says it is attempting to pair, but after about 5 to 10 seconds, it fails.
BluetoothSecurity.PairRequest(device, "1"))

Additional Information:
I've successfully paired with my Android phone using this code.
I then logged in and set a PIN on the Zebra printer. However, this code still fails to pair with the printer even when I know the pin is correct / set in the printer.

From https://km.zebra.com/kb/index?page=answeropen&type=open&searchid=1336682809706&answerid=16777216&iqaction=5&url=https%3A%2F%2Fkm.zebra.com%2Fkb%2Findex%3Fpage%3Dcontent%26id%3DSO8031%26actp%3Dsearch%26viewlocale%3Den_US&highlightinfo=6292341,26,43#
Zebra Bluetooth enabled mobile printers are 'slave' devices only. The printers will pair with any 'master' device that tries to make a valid connection. Since only a master device can initiate a connection, the printer does not store pairing data, that function is always done on the master device. The printer can only be connected to one master device at a time, but any number of master devices that have stored pairing information for the printer would be able to initiate a connection to the printer without having to rediscover it.
I'm guessing that this means the InTheHand.Net BluetoothSecurity.PairRequest might not work for this type of pairing?

In the Bluetooth section of the WM handheld, under the "Devices" tab, I can add the device. I need to essentially do that. I need to register the device in that list and then set it to use COM 1 in the "COM Ports" section. The application I am using doesn't actually print. It's sole purpose is to prepare the printer for other applications.
Answer: The quote from Zebra make it sounds as pairing is actually not required at all.  Are you printing from your app?  If so just connect to the SPP service and send the text.
BluetoothAddress addr = ...
Guid serviceClass;
serviceClass = BluetoothService.SerialPort;
var ep = new BluetoothEndPoint(addr, serviceClass);
var cli = new BluetoothClient();
cli.Connect(ep);
Stream peerStream = cli.GetStream();
peerStream.Write ...

(From General Bluetooth Data Connections)
Comment: In the Bluetooth section of the WM handheld, under the "Devices" tab, I can add the device. I need to essentially do that. I need to register the device in that list and then set it to use COM 1 in the "COM Ports" section. The application I am using doesn't actually print. It's sole purpose is to prepare the printer for other applications.
Answer: The Zebra Mobile Printer needed to be properly configured before pairing with this method will work. Here is what I did:

First, I ran the following commands on the printer:

.
! U1 setvar "bluetooth.authentication" "setpin"

! U1 getvar "bluetooth.authentication"

! U1 getvar "bluetooth.enable"

! U1 getvar "bluetooth.discoverable"

! U1 setvar "bluetooth.bluetooth_pin" "0000"

! U1 getvar "bluetooth.bluetooth_pin"

Then, the application with this code ran successfully.

.
int pair_req = 0;
try
{
    if (BluetoothSecurity.SetPin(device, "0000")) {
        while (status == false && pair_req < 3)
        {
            ++pair_req;
            status_box.Text = status_box.Text + '\n' + "Attempt " + pair_req.ToString();
            status_box.Update();

            if (BluetoothSecurity.PairRequest(device, "0000"))
            {
                status = true;
                client.Refresh();
                status_box.Text = "Paired Successfully.";
                status_box.Update();
                Thread.Sleep(5000);
            }
            else
            {
                status = false;

            }

        }
    }
}
catch (ArgumentNullException e)
{
    status_box.Text = "Pair failed.";
    status_box.Update();
    Thread.Sleep(5000);
}

status_box.Update();
Thread.Sleep(400);


How to interpret eigenvectors in PCA analysis?

Question: I'm trying to apply the output from PCA analysis I've run on some yield curve history and am getting a bit confused. I have followed the steps below,

From a history of the yield curve ($m \times n$ where $m$ are the days and $n$ are the tenor points) I derive the daily returns
Calculate a covariance matrix from the daily returns
Calculate the eigenvectors and eigenvalues that correspond to the covariance matrix. The first two eigenvectors (principal components) are,
Tenor      PC2          PC1
1Y         -0.15028     0.05154
2Y         -0.32138     0.13310
3Y         -0.41856     0.20852
5Y         -0.41465     0.26116
7Y         -0.33315     0.29555
10Y        -0.19980     0.31919
15Y        -0.04874     0.33416
20Y         0.08760     0.34173

PC1 explains 85% of the variance and PC2 explains 11%, so these two components are enough for the purposes of my analysis.
What I would like to do is measure the amount the yield curve moves if I assume the 5Y point moves by exactly one unit with every point moving in the same direction (the move exactly described by PC1).
To do this I calculate a shift to the yield curve using the following expansion,
$ \textbf{PC1} = \Bigg[ \textbf{SD} \cdot \bigg[ \textbf{P} \cdot \big[ \textbf{Sc} \cdot \textbf{SD} \cdot \textbf{P} \big] ^ {-1} \bigg] \Bigg] \cdot \big[1\big]$
where,

$\textbf{SD}$ is the standard deviation matrix of size $n \times n$ where $n$ is the number of tenors, the diagonal value is the square root of the diagonal of the covariance matrix and zeros everywhere
$\textbf{P}$ is the first Principal Component vector, which is simply the eigenvalues of the covariance matrix of the daily returns of size $n \times 1$
$\textbf{Sc}$ is a scalar vector that represents a unit shift at the 5Y point, so is a $n \times 1$ vector with 0 at each element apart from 1 at the corresponding 5Y tenor

The output of the above expansion does indeed lead to an $n \times 1$ vector that has a shift for every tenor and exactly 1 at the 5Y point, so the result does appear to be correct.
This is the output,
0.071660453
0.336473214
0.707324248
1
1.204548309
1.340536029
1.429582409
1.489268877

However, some other references suggest that I can use the eigenvectors as weights directly. If I do that and scale the results of the PC1 vector so that the 5Y element is exactly 1, I get this result,
0.197343561
0.509633359
0.798451041
1
1.131677872
1.222203892
1.279510769
1.308506297

So my question simply is - which result is correct? Is it the first one or the second, which is simply a linear scaling of the eigenvector?
Thank you in advance.
Comment: Welcome to CV. I've a few questions to clarify what you are doing. what is SD? The standard deviation of a matrix I am familiar with is a scalar (see http://www.allexamshelps.com/calculating-matrix-mean-variance-and-standard-deviation/) . Do you mean the covariance matrix with element by element square root? Or maybe the eigenvalues? You allude to references, could you provide some?
Comment: Hi Rene, I've edited my question about. In specific answer to your questions SD is square root of the diagonal of the covariance matrix. I've also linked to a reference.
Answer: Try squaring your transformed PC1 (eqn 1) and compare it to the directly weighted loading (option 2) - you will see that it is the square of the direct weighting.
For your purposes there is no need to manipulate the eigenvectors themselves, what you should adjust is the scores applied to each PC (which is method 2).If you manipulate the eigenvectors themselves, you are directly manipulating the underlying reality of your covariance structure. Eigenvectors are unit vectors, so they have an overall weight of 1 - if you mess with that you just make life complicated for yourself in correcting for when to square and when to square root, as you would need to work out with solution 1.
If you manipulate the scores, you are simply observing what happens as you manipulate observations, which sounds more like what you want.
The PCA equation it is very simple.
$ Data = Scores * PCs$
If you adjust the scores there is no squaring involved - the effect of scaling changes are inherently handled by the nature of linear algebra multiplication.
Comment: Hi Rene, thanks but I don't follow your explanation. What do you refer to by "transformed PC1", "scores" and "weighted loading"? Can you please clarify.
Comment: OK, have included reference to your 1st and second options. If you scale the eigenvectors then you are introducing a weight to them.


gráfico de resíduos half-normal plots no ggplot2

Question: Estou tentando realizar o gráfico apresentado abaixo referente aos resíduos no half-normal plot em ggplot2.

No entanto, estou enfrentando um erro intitulado Erro: data must be a data frame, or other object coercible by fortify(), not an S3 object with class hnp.
Os dados podem ser vistos abaixo.
Stones <- c(rep("Stone1",1), rep("Stone2",1), rep("Stone3",1))
treat <- c(rep("T6",9), rep("T7",9), rep("T8",9),
           rep("T10",9), rep("T11",9),
           rep("T12",9),rep("T14",9),rep("T15",9),
           rep("T16",9))
Samples <- c(rep("SampleI",3), rep("SampleF",3), rep("SampleR",3))
Count <- c(3,3,1,1,2,2,0,0,0,1,2,3,0,0,1,0,0,0,2,0,2,2,0,0,0,0,0,6,
           1,0,2,2,2,0,0,0,4,4,1,3,2,5,0,0,0,3,4,4,5,1,2,0,0,0,
           4,4,6,1,2,1,0,0,0,4,6,4,2,3,1,0,0,0,3,2,2,1,0,5,0,1,0)
Total <- c(rep("6", 81))
dados <- data.frame(treat, Stones, Samples, Count, Total);dados
dados$treat = as.factor(dados$treat)
dados$Samples = as.factor(dados$Samples)
dados$Total = as.numeric(dados$Total)
dados$Prop = dados$Count/dados$Total
dados16 = dados[dados$treat=="T16",];dados16`

O ajuste do modelo está apresentado a seguir.
resp16 <-cbind(dados16$Count,dados16$Total - dados16$Count); resp16
m16 <- glm(resp16 ~ Samples,
           data = dados16,
           family = quasibinomial)

Graph16=hnp(m16, xlab = 'Percentil da N(0,1)', ylab = 'Resíduos',
    main = 'Gráfico Normal de Probabilidades')

O erro está aqui.
ggplot(data = Graph16)
Erro: `data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class hnp

Answer: Segundo a secção Value de help("hnp), o objeto Graph16 é uma lista de classe "hnp". Estes objetos têm membros x, lower, upper, median e residuals, que são os vetores representados no gráfico.  Primeiro tem que se criar um data.frame com esses vetores e depois traçar o gráfico.
library(ggplot2)

G16 <- with(Graph16, data.frame(x, lower, upper, median, residuals))
G16

ggplot(data = G16, aes(x)) +
  geom_point(aes(y = residuals)) +
  geom_line(aes(y = lower)) +
  geom_line(aes(y = upper)) +
  geom_line(aes(y = median), linetype = "dashed")

Comment: Obrigado Rui Barradas!!


Where is the Java TextArea paint method implemented?

Question: I am looking for the paint method implementation for a Java TextArea component (java.awt.TextArea).
I have read through the source code for the class as well as its super class (java.awt.TextComponent), but have not found a public void paint(Graphics g) method implementation, which I think means the class would be using the default Component#paint(Graphics) implementation, which doesn't make sense. Am I missing something here? How is a TextArea component painted?
Comment: Since you've got the source code, why not have a look at the `Component#paint(Graphics)` method to see exactly how a `JTextArea` can be painted without defining its own `paint` method?
Comment: @Shakedown I did look at the [java.awt.Component](http://www.java2s.com/Open-Source/Java-Document/6.0-JDK-Core/AWT/java/awt/Component.java.htm) source and the `paint` method is empty.
Comment: Whoops, I'm sorry, I meant `JComponent`, not `Component`.
Answer: TextArea is an AWT component, not a Swing component. It's thus what's called a heavyweight component, which means it's in fact implemented by a native component of the underlying platform/OS (i.e. a Windows/Gnome/Motif component, depending on the OS), called the peer of the component. The painting is thus done by the platform's native widget, and not by the component.
Comment: Ahh, so that's what the peer it references is. That makes sense. `JTextArea` and `JTextComponent` also do not contain a `paint` method. Are they also painted by the platform as well?
Comment: No. These are lightweight components. Read http://java.sun.com/products/jfc/tsc/articles/painting/index.html for explanations.
Comment: IUUC, painting is delegated, e.g. [`javax.swing.plaf.TextUI`](http://download.oracle.com/javase/6/docs/api/javax/swing/plaf/TextUI.html) for `JTextComponent`.
Answer: AWT Components is dinosauruses from last milenium, and only by back-compactible are there and still exists, please/better would be to change that to the Todays JComponents, all starts with "J" here is list of JComponents with tutorials, but for Swing's JComponents is there paintComponent(Graphics g) instead of paint(Graphics g)
method paint is still there but for deepest painting in XxxXxxUI, for example MetalButtonUI, but not for painting Image/Lines/Text ... and just try to avoid a similar examples from year 2000 and another very old examples, that's really wrong implemntation for Custom Painting in Java6's Swing,
here is your required tutorial and Java6 API
on this Forum are plenty threads about Painting Something in JComponents
EDIT: if you want to paint something then look for JLabel (is transparent by defalut), that best JComponent for  2D Graphics, examples for that here, and with paintComponent() method only
Comment: I understand `AWT Components` are outdated by the newer `Swing Components`. I'd be just as content being able to see `JTextArea`'s `paint` method (which is just as elusive). I'm looking to write my own `TextArea` class for use on the Amazon Kindle's Java 1.4.2 based KDK, as the KDK's implementation is somewhat broken. I want to use the Java API's implementation for a reference.


How to round mean values when imputing missing questionnaire items

Question: When there are missing items (answers) in a questionnaire it is sometimes usual to impute them with the mean of the valid items. For example here are 3 items/question which can have a four values from 1 to including 4.

[2, 3, missing] would result in [2, 3, 2.5]
[4, 3, missing] would result in [2, 3, 3.5]

Because the floating point is not a valid/possible answer, rounding may be needed to give the item one of the allowed values.
Is scientific rounding the correct choice here? Please correct me if I am wrong but possible synonyms are symmetric rounding, mathematics rounding, round half down or bankers rounding.
In that case and if I am interpreting the rounding rule correct:

[2, 3, missing] would result in [2, 3, 2]
[4, 3, missing] would result in [2, 3, 3]

This question does not take technical problems (e.g. representation of floating point numbers) into account. This is about the best theoretical choice and not how to implement it.
More thoughts
Assume the case of a questionnaire where I have 3 to 5 items with possible values between 1 and 4. The calculation of mean() will often result in a *.5 number. Using scientific rounding will round them all down. I would hypothesize that more then the half of the rounding will go down which causes an unbalance.
Because of that I would argue that rounding to the nearest even value would result in a better balance between up and down rounding.
What does the more experience researches thing about that?
EDIT: This question is not about the right imputation method. The questionnaire author said I have to use this method not other. The question is about the rounding method only.
Comment: I need to see  your basis for supporting this type of imputation.  Some sort of comparability across items seems to be needed.  Multiple imputation may also be needed, not using a simple rule.
Comment: Need more to go on before judging the validity of the method.
Comment: What are the particular questions?  Are the interchangeable?  What are specific reasons to trust such a simple imputation?
Comment: The manual of the questionnaire say so that this "simple rule" can be used: If 2/3 of the items of a subscale have valid values the missings one's can imputated by the mean of the valid values. No more information's about that in the manual; which is in German because this is the German and further developed version of the Kings Health Questionnaire (KHQ). The original KHQ manual (1995) say nothing about imputation. https://doi.org/10.1055/s-2005-872957
Comment: I do not understand what do you need. I am not a statistican.
Answer: Here is a balanced algorithm: On the $i^{th}$ questionnaire, if there are $k_i$ valid responses which sum to $s_i$, then:

round $s_i/k_i$ up if $(i\! \mod k_i) < (s_i\! \mod k_i)$
round $s_i/k_i$ down if $(i\! \mod k_i) \ge (s_i\! \mod k_i)$

In the long run of this algorithm, averages like 2.5 get rounded up half the time and down half the time, while averages like 2.7 get rounded up 70% of the time and rounded down 30% of the time.
Answer: Imputing the average of the other questionnaire items has some shortcomings.
Example: Suppose that you have 21 items that take binary values, 10 of them have a value of one, 10 of them have a value of zero, and one is missing.

If you impute the average you get a value of 0.5. But this is not a feasible data point.
The issue is that there is uncertainty. In addition to the mean you also need to account for the variability of the imputed value.

One way to address is to use multiple imputation. The idea behind this method is to create multiple draws around the average of the items, by having a model to predict the missing values based on the responses in the other items. This is attractive computationally because it is an approach designed to fit the data at hand. There are many statistical packages that allow you to run standard analyses like regression using multiple imputation (e.g. look at "mi" commands in Stata).
This approach circumvents the need to choose an arbitrary "rounding" rule, because you directly account for the variability in the observed data points.
Answer: For which reason can't you use fractions in imputation? Based on that you will have to decide on an alternative.
For instance, it might be that the variable is categorical and you can't use numbers in the regression model. In that case, you could impute the categories (you could impute each category once with a weight depending on the frequency that the category occurs).
Answer: It's commonly done to impute based on the mean of the other items, but that's more because it's simple, easy to do and has some vague logic to it ("Well, if they are all high or low, maybe the missing one would be, too, right?"). However, that does not mean it is a good (never mind the best) option.
Let's imagine you have this data for one person:

Week 0, Question 1: Score 9 out of 10
Week 0, Question 2: Score 8 out of 10
Week 0, Question 3: Score 2 out of 10
Week 4, Question 1: Score 8 out of 10
Week 4, Question 2: Score 9 out of 10
Week 4, Question 3: Score 1 out of 10
Week 8, Question 1: Score 10 out of 10
Week 8, Question 2: Score 9 out of 10
Week 8, Question 3: missing

Would your first thought be to impute question 3 at week at as 9.5?
A more obvious approach is to e.g. do multiple imputation based on a joint latent normal model for ordinal data, which is an approach that is much more capable to reflect how different questions tend to be correlated. If there are multiple assessments for the same person filling in the questionnaire, one can then even try to capture within person correlations. This kind of approach then has the ability to come up with a more sensible answer to our example above.


How can I remove the wrapper around the input when using Inference Schema

Question: When using Inference Schema to autogenerate the swagger doc for my AzureML endpoint (as detailed here and here), I see that it creates a wrapper around my input_sample. Is there a way to
not wrap the input inside this "data" wrapper?
Here is what my score.py looks like:
<code>input_sample = {
                "id": 123,
                "language": "en"
                "items": [{
                    "item": 1,
                    "desc": "desc"
                }]
            }
output_sample = [{'prediction': 'true', 'predictionConfidence': 0.8279970776764844}]

@input_schema('data', StandardPythonParameterType(input_sample))
@output_schema(StandardPythonParameterType(output_sample))
def run(data):
"""
    {
        data: { --> DON'T WANT this "data" wrapper
                "id": 123,
                "language": "en"
                "items": [{
                    "item": 1,
                    "desc": "desc"
                }]
            }
    }
    """
    try:
        id = data['id']
        ...

</code>
Comment: do you want to customise the swagger json file associated to the API of the deployed model.?
Answer: InferenceSchema used with Azure Machine Learning deployments, then the code for this package was recently published at https://github.com/Azure/InferenceSchema under an MIT license. So you could possibly use that to create a version specific to your needs.


What are the advantages of c# over, say, delphi/realbasic for windows applications

Question: Has anyone ever written an application bigger than its .NET luggage?
People used to criticize VB6 for its 2 MB runtime but it rarely dwarfed the app it accompanied.
Today despite having Vista on my machine I had to download 35 MB of the 3.5 framework and reboot to then try out an app half that size.
When you factor in the decreased source code security I wonder why anyone would anyone develop a windows application in .NET rather than in a language that allowed for the building of native executables.
What is superior about .NET that outshadows these drawbacks when it comes to writing applications to run on Windows?
Comment: if you are talking specifically about Windows apps in Win32 is hard to come up with a good argument for using C# over Delphi, for that *specific environment* Delphi is the best thing ever
Comment: @ShuggyCoUk: OK. You've finally lost it. Obviously Delphi couldn't have been there when .NET first came out, because Delphi isn't made by MS. Your argument is the same as "The Prius will never sell, because it wasn't around when the Model T first came out". News flash: Recent can be as goodr.
Comment: @ShuggyCoUk - being better later is exactly what Microsoft have been doing all these years. Doesn't seem to have hurt them so far.
Comment: I didn't expect it to be there *immediately* when it came out, but .Net came out in 2000/2001! even waiting till the 2.0 features were in place (a reasonable thing) would mean 2004!
Comment: It is worth pointing out that for my usage (at work) neither of your negatives have any significance to my usage whatsoever.
I knew a few LOB programmers who really loved delphi, but where was prism when .net first came out... Being better *later* is not going to cut it
Comment: Does your work involve developing windows applications using C#?
Comment: Yes, both client and server. and in f# and C++/CLI (there's a little VBA for excel integration too but I try to forget that :)
Comment: Yep. As "goodr". [Note to self: Proof better before posting.]  And my condolences for the "VBA" - I deal with it, too. (Legacy stuff written in Access/VBA for statistical info.)
Answer: PEOPLE: Please note that this was written in February, 2009, and what is said was appropriate at that time - yelling at me in late 2012 (3+ years later) is meaningless. :-)
Delphi has some considerable advantages for Win32. Not that .NET apps are inherently bad, but try:

running a .NET app (any version) on Win95/ME, where .NET doesn't exist (AFAIK)
distributing any small ( < 1.5 MB) .NET app (yes, floppy drives still exist)
providing any .NET app on a system that has no Internet access (yes, they exist)
distributing your .NET apps in countries without widespread high bandwidth
keep people from seeing your source code without spending a ton of dough (Reflection, anyone?)

Garbage collection in .NET might be really nice, but anyone who knows anything about programming can also handle manual allocation/deallocation of memory easily with Delphi, and GC is available with reference-counted interfaces. Isn't one of the things that brought all of the non-programmers to proliferation the pseudo-GC of VB? IMO, GC is one of the things that makes .NET dangerous, in the same way VB was dangerous - it makes things too easy and allows people who really have no clue what they're doing to write software that ends up making a mess. (And, before I get flamed to death here, it's great for the people who do know what they're doing as well, and so was VB; I'm just not so sure that the advantage to the skilled outweights the hazards to us from the unskilled. )
Delphi Prism (AKA Rem Objects Oxygene, formerly Chrome) provides the GC version of Delphi that those who need it are looking for, along with ASP.NET and WPF/Silverlight/CE, with the readability (and lack of curly braces) of Delphi. For those (like me) for which Unicode support isn't a major factor, Delphi 2007 provides ASP.NET and VCL.NET, as well as native Win32 support. And, at a place like where I work, when workstations are only upgraded (at a minimum) every three years, and where we just got rid of the last Win95 machine because it wasn't a priority to upgrade, the .NET framework is an issue. (Especially with company proxy requirements only allowing Internet access to a handful of people, limiting bandwidth and download capabilities, and proper non-admin accounts with no USB devices allowed, all still running across a Netware network - no such thing as Windows Update, and never a virus so far because nothing gets in.)
I work some in .NET languages (C#, Delphi Prism), but the bread and butter both full-time and on the side, comes from Win32 and Delphi.
Comment: If you think that useful programming tools should be denied to me (and by inference you) because idiots will misuse them then I can't say I share your view. Don't employ idiots, if this is a problem for you work someplace else.
Comment: I'll take Delphi over C# every day of the week. I don't understand the love of GC. It's not that hard. If you create an object, free it when you are done. It really is that easy.
Comment: You're both misunderstanding what I said.  GC itself isn't dangerous; it's the ease that GC offers to idiots to enable them to produce software that is worrysome. Like I said, think about all of the VB apps that were written - there was a lot more garbage than gold. :-)
Comment: I don't understand how GC makes it easier to write bad code. If someone is writing bad code in .NET, throwing them into an unmanaged environment will surely be a trainwreck.
Comment: @Ken White: Ouch, claiming the moral high ground from a GC perspective is kinda uninformed. On average the percentage of bad programs out there have nothing to do with GC - the percentage of excellent program has. There is just more time to be spent on features instead of manual GC. ;)
Comment: Number of bad programs will not be reduced (if not increased) if you remove GC. Also some of the mistakes(yes, even good programmers do mistakes) of allocating and dealocating memory can be handled simply by using GC.
Comment: That's what makes it dangerous. Just like VB, there's the possibility of proliferation of crappy, badly written, junky applications because of the ease of GC. If the people who wrote those apps had to work to do so, that wouldn't be as easy to do.
Comment: @JeremyThompson: You did notice that this was written three years ago, right? There was a time when people said "Windows? Who needs all that graphical stuff when DOS gives you all you need?", and when people said "Who needs that fancy auto-mo-beel stuff when a horse takes you where you need to go?" - times change. What was applicable then isn't necessarily applicable now, especially with regards to technology. Thanks for the "still a good answer", though. :-)
Comment:  -- Manual allocation/deallocation leads to code pollution especially because error code paths become very unwieldy.
Comment: @JeroenWiertPluimers: Thanks. The edit was added because someone just decided to downvote this answer, despite it's date and the recent comments about things having changed since then. :-) Apparently the downvoter can't read (or didn't bother to do so) posting dates. ;-) Bill Gates is lucky he wasn't on SO when he made his now famous `640K is more than enough` remark.
Comment: .NET 2.0 (base version) runs on Win 98/ME, although .NET 2.0 SP1 and higher are not.
It is simple to package the .NET runtime along with the app on a CD for systems without Internet access.
I disagree that GC makes .NET dangerous for unskilled developers.  Most of the time it just works.
Comment: @ShuggyCoUK: Trust me - I've fired plenty of idiots over the years.  This has nothing to do with employing them or working with them; it has to do with the trashy apps they release into the public that I have to clean up after. My mother and siblings aren't computer-literate.
Comment: Everyone of those 5 points aren't that bad:

1. Who runs windows 95 and Me these days? the dinosaurs that still use mainframes.
2. Floppy drives may still exist, but it would be easy to get around the <1.5MB limit - use a network card - 3. no internet access required.
4. Same exists for distributing any apps without widespread high bandwidth (not .Net specific).
5. You can obfuscate .Net code, but it doesn't matter I've had one of my unmanaged code apps hacked using tools like IDA Pro. Just my 2 cents - still a good answer.
Comment: You're definitely in the minority.
Comment: You're probably right. It's not GC so much as .NET in general. It's like VB that way; while I know some VB developers that I respect and that write good code, they're vastly outnumbered by the people who shouldn't be allowed anywhere near an IDE. :-)
Comment: @Tobias: You obviously didn't read the comment just before yours, when I admitted it wasn't GC's fault.  The percentage of bad programmers has to do with the simplicity of .NET itself (like VB before it); GC is just a part of it. And no, I'm not "uninformed". Defensive, maybe, after VB.
Comment: @anothersilverlight: You should read comments before yours first.  GC isn't the problem; it's just another enabler. Yes, it avoids allocation errors; .NET (and VB before) make it too easy for idiots to pretend they're programmers. That's all I'm sayin'. :-)
Comment: Man, yes, there's a lot of disvantages on .NET framework, like all other tecnologies has its owns, but, make things easy like GC does, doesn't make the programmer a stupid one. That's my only one disagree point of your tought.
Comment: @Gedean: I never said GC made programmers stupid. Read the other comments above yours, where I specifically address this (pay particular attention to my reply to Tobias about 5 above yours).
Comment: You get what you pay for. Expecting to run free or 99 cent apps without either a lot of computer knowledge or introducing problems into your system is stupid. That's like comparing going to the junk yard for a cheap car part and installing it yourself or paying the money for a mechanic.
Comment: I still have Win98SE boxes; they're in storage right now because I had to move;
Comment: @pkumar0 when I look at the average GC based (.NET/Java) app quality, it suffers from the same things as Delphi: code pollution. So many things that are hung on for too long so the GC (.NET/Java) or the Ownership/Reference counting mechanisms (Delphi) cannot do their job.
Comment: +1 for the edit and the original article. I do both managed and unmanaged projects and both have their place.
Comment: @KenWhite Not to stray off topic, but that Bill Gates quote unfortunately remains an unconfirmed myth: http://www.computerworld.com/s/article/9101699/The_640K_quote_won_t_go_away_but_did_Gates_really_say_it_
Comment: @b1naryatr0phy: Not sure if you noticed, but this thread is from 4+ years ago, so I'm not sure it matters much. If you read the comments in order, I wasn't really attributing the comment to him anyway; it was more about getting punished for things said a long time ago without taking note of the fact that technology (and feelings about them) change over the years. IOW, the state of .NET in early 2009 was not what it is today, and what I wrote then about it probably doesn't apply now, any more than the (mal)attributed quote would.
Comment: @KenWhite What does the age of the thread have to do with an alleged quote that is now decades old?! You didn't just state the quote itself, instead you said "Bill Gates...made his now famous quote..." And yes I have read the comments in order (which you have said about a dozen times previously) which is why I can tell you have an obsession with arguing with people, even when it is meaningless.
Comment: @b1naryatr0phy: Yeah, whatever. I'm not the one being pedantic about a meaningless and jokingly-made quote citation in an antique comment. :-)
Comment: @KenWhite I'm a programmer, of course I'm precise =P Aren't you?
Comment: Even from the perspect of 2009, the only valid point you made is this - keep people from seeing your source code without spending a ton of dough, but Delphi has been easy to reverse as well.  Just .NET code is easier to reverse back to near original code due to MSIL (the amount of data stored about the code itself).
Comment: @Samuel: No, the other four points were valid at the time as well. I remember very well, as I was there. But thanks for the downvote on a topic you clearly know nothing about 6 years after it was made despite a disclaimer that it was outdated.
Answer: Okay, I doubt this will persuade you as you don't want to be persuaded, but here's my view of the advantages of .NET over older technologies. I'm not going to claim that every advantage applies to every language you mentioned in the question, or that .NET is perfect, but:

A managed environment catches common errors earlier and gives new opportunities:

Strong typing avoids treating one type as another improperly
Garbage collection largely removes memory management concerns (not totally, I'll readily admit)
"Segmentation fault" usually translates to "NullReferenceException" - but in a much easier to debug manner!
No chance of buffer overruns (aside from the potential for CLR bugs, of course) - that immediately removes a big security concern
A declarative security model and a well-designed runtime allows code to be run under a variety of trust levels
JITting allows the CLR to take advantage of running on a 64 bit machine with no recompilation necessary (other than for some interop situations)
Future processor developments can also be targeted by the JITter, giving improvements with no work on the part of the developer (including no need to rebuild or distribute multiple versions).
Reflection allows for all kinds of things which are either impossible or hard in unmanaged environments

A modern object-oriented framework:

Generics with execution time knowledge (as opposed to type erasure in Java)
Reasonable threading support, with a new set of primitives (Parallel Extensions) coming in .NET 4.0
Internationalisation and Unicode support from the very start - just one string type to consider, for one thing :)
Windows Presentation Framework provides a modern GUI framework, allowing for declarative design, good layout and animation support etc
Good support for interoperating with native libraries (P/Invoke is so much nicer than JNI, for example)
Exceptions are much more informative (and easier to deal with) than error codes
LINQ (in .NET 3.5) provides a lovely way of working with data in-process, as well giving various options for working with databases, web services, LDAP etc.
Delegates allow a somewhat-functional style of coding from VB and C#; this is better in C# 3.0 and VB9 due to lambda expressions.
LINQ to XML is the nicest XML library I've used
Using Silverlight as an RIA framework allows you to share a lot of code between your lightweight client and other access methods
A mostly-good versioning story, including binding redirection, runtime preference etc

One framework targeted by multiple languages:

Simpler to share components than with (say) COM
Language choice can be driven by task and team experience. This will be particularly significant as of .NET 4.0: where a functional language is more appropriate, use F#; where a dynamic language is more appropriate, use IronRuby or IronPython; interoperate easily between all languages
Frankly, I just think C# is a much cleaner language than VB or C++. (I don't know Delphi and I've heard good things about it though - and hey, you can target .NET with Delphi now anyway.)

The upshot of most of this - and the soundbite, I guess - is that .NET allows faster development of more robust applications.
To address the two specific issues you mentioned in the question:

If your customer is running Vista, they already have .NET 3.0. If they're running XP SP2 or SP3, they probably have at least .NET 2.0. Yes, you have to download a newer version of the framework if you want to use it, but I view that as a pretty small issue. I don't think it makes any sense to compare the size of your application with the size of the framework. Do you compare the size of your application with the size of the operating system, or the size of your IDE?
I don't view decompilation as nearly such a problem as most people. You really need to think about what you're afraid of:

If you're afraid of people copying your actual code, it's usually a lot easier to code from scratch if you're aware of the basic design. Bear in mind that a decompiler won't give local variable names (assuming you don't distribute your PDB) or comments. If your original source code is only as easy to understand as the decompiled version, you have bigger problems than piracy.
If you're afraid of people bypassing your licensing and pirating your code, you should bear in mind how much effort has gone into stopping people from pirating native applications - and how ineffective it's been.
A lot of the use of .NET is on the server or for internal applications - in neither of these cases is decompilation an issue.
I've written more on this topic in this article about decompilation and obfuscation.
Comment: I quite like the futures/async concept backed into Delphi Prism. That the product is only available on a commercial basis means I am unlikely to try it.
Comment: ++ rather better written than mine too, guess if I get two more votes I get to get a disciplined badge.
Comment: @Shuggy: Heck no! Please don't delete yours - it gives way more of the "pros *and* cons" than my answer. I'm sure there's plenty of non-duplication there as well.
Comment: @Jon: Nice post. I'd debate a couple of points, but there's no room in the comments for anything worthwhile. :-) FYI, though, Delphi has a pretty nice OOP framework (not as extensive, I admit), and as of D2009 supports generics and anonymous methods. It's fully Unicode aware, as well.
Comment: Yes, I guessed that Delphi would be the hardest of those to argue, especially as it can target .NET. Unfortunately I know almost nothing about Delphi beyond it being another work of Anders, and it having a sort of "static polymorphism". (I know what the concept is roughly, but not its name.)
Comment: @Jon: I'm not sure what you mean by "static polymorphism"; Delphi supports polymorphism, inheritance, and encapsulation the same way any other OOP language does. And yes, it was Anders brainchild, but the current development team is pretty good too, IMO.
Comment: @ShuggyCoUk: Prism is new to CodeGear. They're reportedly working on new versions of the Turbo product line; while I haven't heard anything about Prism or Delphi for PHP inclusion, I wouldn't be surprised to see them there - everything else Delphi or C++ Builder related is part of it.
Comment: @Ken: I mean polymorphism of type methods (static methods in C#). You can't override static methods in C#, but I believe there's some rough equivalent in Delphi which allows it. Again, I wish I had the right terminology :(
Comment: Delphi has "class references" which, among other things, permit static virtual members. Most useful is the use for virtual constructors.
Comment: @Henk: Yup, that's the one I meant :)
Answer: To name a few:

Automatic memory management, garbage collection
Type safety
Bounds checking
Access to thousands of classes that you will not have to create
Comment: +1 "thousands of classes that you will not have to create"
Comment: @Mason Wheeler: Check out the number of Delphi questions here on SO about object ownership, interfaces and ref-counting, or how to properly use try finally, and you will see that manual memory management has for many programmers at least as many problems as GC has in your opinion.
Comment: -1 Type safety. Delphi has had that for decades (TP 1)
-1 Bounds checking. TP
2 left. GC - questionable. Classes? Delphi has a lot of them too, although I'm not sure they're quite as many as "thousands" (have you actually counted them in Delphi and .NET?)
Comment: CONTINUED: A single dangling pointer to deallocated memory kills your
type safety: if a value of a different type gets allocated at the same
location, you have a type violation
Comment: Darin, you're almost right.  A "dangling pointer" certainly isn't type-safe; however, if you're an idiot who leaves a pointer dangling, you shouldn't be programming. And to use the Win32 API (which will be around a long time yet), you need pointers, even in C#.
Comment: Epic fail here.  The author specifically tagged this as a comparison with Delphi.  It has type safety, bounds checking, and a very comprehensive runtime.  Everything but garbage collection, which IMO causes more problems than it fixes.  But if you really need it, you can get it too.
Comment: Ken, any language that has dynamic memory allocation that it expects to be reclaimable (no infinite memory) and doesn't have a GC isn't
type-safe.
Answer: OK first up, No one language/platform is ever going to be universally superior.

Specialization will always provide a better use case in certain areas but general purpose languages will be applicable to more domains.
Multi-paradigm languages will suffer from complex boundary cases between paradigms e.g.

Type inference in any functional language that also allows OOP when presented with sub classes
The grammar of C++ is astonishingly complex, This has a direct effect on the abilities of its tool chain.
The complexities of co/contra variance coupled with generics in c# is very hard to understand.

Older languages will have existing code bases that work, this is both positive (experience, well tested, extensive supporting literature) but also a negative (the resulting inertia against change, multiple different ways to do things leading to confusion for new entrants).
The selection/use of both languages and platforms is, as are most things, a balancing of the pros and cons.
In the following lists Delphi has some of the same pros and cons, but differs on many too.
Potential Negatives of .Net (if they are not an issue to you they aren't negatives)

Yes, you need the runtime deployed (and installed), and it's big.
If you wanted a language with multiple inheritance you're not going to get it
The BCL collections library has some serious flaws
Not widely supported outside the MS universe (mono is great but it lags the official implementation significantly)
Potential patent/copyright encumbrance
Jitted (ignoring ngen) start up time is always going to be slower and more memory will be needed.

There are more but these are the highlights.
Potential Positives (again if they don't matter to you)

A universal GC, no reference counting that prevents certain data structures being usable, I know of no widely used Functional language without GC, I can't think of significant language of the last 10 years without at least optional GC. If you believe this is not a big deal you would appear to be in a minority.
A large BCL (some parts not so good as others but it's very broad)
Vast numbers of languages (and a surprising number of paradigms) can be used and interact with each other (I use c#, f#, C++/CLI within one wider application using each where it makes most sense but able to easily use aspects of one from another).
Full featured introspection combined with declarative programming support. A wide variety of frameworks become much simpler and easy to use in this manner.
Jitted - alterations in underlying CPU architecture can be largely transparent, sophisticated runtime optimizations not available to pre-compiled languages are possible (java is doing rather better on this currently)
memory access safety
Fusion dll loading and the GAC for system dlls

Likewise specifically for c#
Con:

Syntax based on C underpinnings
(pre 4.0) late binding solely via inheritance
More verbose than some imperative languages
poor handling of complex embedded literals (regexes/xml/multi line strings)
variable capture within closures can be confusing
nested generators are both cumbersome and perform appallingly

Pro:

Syntax based on C underpinnings
Much functional support through lambdas
Expressions allowing compile time validation of non code areas such as Linq to SQL
Strongly typed but with some Type inference to make this easier
if you really need to unsafe is there for you
interaction with existing C++ ABI code via P/Invoke is both simple and clear.
multicast event model built in.
light weight runtime code generation

The C underpinnings really is a pro and con. It is understandable by a vast number of programmers (compared to pascal based style) but has a certain amount of cruft (switch statements being a clear example).
Strong/Weak/Static/Dynamic type systems are a polarising debate but it is certainly not contentious to say that, where the type system is more constraining it should strive to not require excessive verbosity as a result, c# is certainly better than many in that regard.
For many internal Line of Business applications a vast number of the .Net platform Cons are absolutely immaterial (controlled deployment being a common and well solved problem within corporations).
As such using .Net (and this does largely mean c#, sorry VB.Net guys) is a pretty obvious choice for new development within a windows architecture.
Answer: The "simplicity" of developing complex(and simple) applications using it. A lot of basic stuff is already coded for you in the framework and you can just use it. And downloading 35mb file today is much easier than 2mb file 8-6 years ago.
Comment: Compared to any .NET language, Delphi is simpler to develop in.
Comment: It's very simple to develop in delphi and probably realbasic too.
Some people say too simple (see vb6)!
Comment: It's simple to develop simple stuff in Visual Basic.
Comment: It is simple do develop simple stuff in vb6. But try consuming web services, doing remote communications between processes, writing web applications or web services in it and then compare it to .Net
Comment: Well seeing as how vb6 hasn't been updated in 11 years is that so surprising? Might be a different story in delphi though
Comment: Let me add that downloading the runtime is only required once and is typically available through the windows update service. I could see tha argument if every .NET app had to download a separate copy of the framework, but that is not the case.
Comment: Unless you started with Delphi (or some other non-C language), it isn't simpler than Java/C#... language wise
Comment: @JohnFX: Unless: a) you write a .NET app that uses .NET 305, and the user has .NET 2.0, and your app updates to .NET 3.0; b) you have more than one computer, and c) your PC is behind a corporate-mandated proxy that precludes Windows Update. What then?
Comment: @Ken Obviously that is a problem, if you view it as insurmountable for your app then it's a deal breaker fine. But plenty of cases don't fall into the category. Choice right? Nothing is globally superior, nor will it ever be.
Comment: And I didn't say it was. Read my post below; .NET has it's place. My point is that so does Delphi and straight Win32 programming.
Comment: I didn't read any of the reasonable answers here as suggesting they weren't
Comment: I guess I was responding to the non-reasonable ones then.
Comment: I rather liked the Anders++ argument ;)
Comment: So did I. :-) There were some good arguments on both sides here. It's been fun - a great discussion w/o any flaming at all. I'm kinda liking it here.
Comment: It's a shame they don't provide a way to take something to a forum for discussion. I appreciate it's not the core purpose, I just miss it
Comment: Yeah, I agree. 300 characters isn't quite enough sometimes to cover something someone has said (see my comment to Jon Skeet's post below).
Answer: There are a lot of reasons. I don't know much about RealBasic, but as far as Delphi goes:

Less widespread than .NET, smaller development community. Many of the Delphi resources on the net are ancient and outdated.
Until Delphi 2009, Delphi didn't have full unicode support.
I don't know about Delphi 2009, but 2007 didn't have very good garbage collection. It had some sort of clunky reference counting that required some intervention on behalf of the developer. .NET has a much more advanced GC that does virtually everything for you.
.NET has a larger standard library and more up-to-date 3rd party libraries.
.NET languages like C# are arguably better, and certainly easier to understand for those new to the language.
Comment: Delphi is an example of excellence in backwards compatability. In fact, CodeGear demonstrated recently how their demo app that shipped with Delphi 1 would still compile as-is with Delphi 2009. Delphi v1 came out over 14 years ago! The community is smaller than .NET, but very active.
Comment: Delphi less widespread but enough to be viable. Has unicode support.
Has a debate on merits of GC, maybe yet provide on an optional basis. 4th point I can't say.
IMO Object pascal reads like english as to c# hieroglyphics.
Has native executables and a passion to preserve backward compatibility.
Comment: Can't all that delphi.net stuff be ported back to win 32. Wasn't that whole idea originally anyway?
Comment: @Henk: Reference counting isn't only strings, but; interfaces too. "Backward compatibility" works for all Win versions (pre D2009/.NET) prior to Delphi 2009 and Unicode.

I'm sensing a personal dislike (rather than objective/professional) to Delphi. Care to explain, or do you just want bias to show?
Comment: kjack, when I said easier to understand, I meant for people who already have experience programming. A lot of people migrate to C# from Java or C-like languages, where C# will be a lot more familiar than Delphi. It also doesn't help that a lot of tutorials for learning Delphi are  way out of date.
Comment: @Henk: I've studied it. I just don't agree that the "more to offer" is the be-all-and-end-all that some people think it is - there's still plenty of room for Win32 w/o .NET, and plenty of reasons for using non-.NET languages. Delphi is one of the better ones. :-)
Comment: Ken: and dynamic arrays. Personally I'd use C# directly if I would go ASP.NET, but for desktop apps I still prefer Delphi (non .NET).
Answer: There's a lot of supposed advantages cited by .NET developers here that shouldn't be in that comparison, simply because Delphi has them as well:

Type safety
Bounds checking
Access to thousands of classes (components) that you will not have to create

There are however some things in .NET that Delphi doesn't have out-of-the box, and only some of those can be added by libraries and own code. To name a few:

Support for multiple languages working on top of the same runtime - allowing to choose the matching language for the problem (e.g. functional programming using F#)
Dynamic source code generation and compilation - this is something so alien to Delphi programmers that they probably don't even see how it could be useful [1]
Multicast events
Better multi-threading support (for example BackgroundWorker class, asynchronous delegates)
Seamless support for both 32 and 64 bit processes
Weak references

[1] If you don't know but are interested, check out the home page of Marc Clifton, especially the articles about declarative programming.
Edit: I'd like to respond to the comment by Mason Wheeler:

Re dynamic code: I know that there are solutions to have Pascal scripting embedded in the application. There is however a distinct difference between making parts of your internal object hierarchy available to the scripting engine, and having the same compiler that is used for your code available at runtime as well. There are always differences between the Delphi compiler and the compiler of the scripting engine. Anyway, what you get with .NET goes far beyond anything that is available for Delphi. And anyway, it's not the point whether one would be able to code similar infrastructure for Delphi, the point is that with .NET it's already there for you, when you need it.
Re Multicast events: Exactly, there's ways to code it, but it's not part of Delphi / the VCL out-of-the-box. That's what I was saying above.
Re weak references: You are sadly mistaken. Try to use interfaces in a non-trivial way, creating circular references on the way. Then you have to start to use typecasts and wish for weak references.
Comment: Dynamic code: I'm aware of at least 2 powerful, mature Object Pascal scripting engines just off the top of my head.  Multicast events: http://blogs.codegear.com/abauer/2008/08/15/38865 Weak references: Who cares? Those only matter if you're using GC.
Comment: @Mason: You're right. There are more than two, although I don't sell mine anymore. We had one of the early ones (TCFEvaluator, in the Clipper Functions for Delphi library) back in the days of Delphi 2. You could even reference properties of the form it was on if you wanted.) And way pre-.NET. :-)
Comment: @Ken: Do you really not see how different this is from using the very same tools used for developing, at runtime? Using the power of reflection that goes way beyond a few published properties?
Comment: Re: your edit, specifically part 3: First off, interface reference counting is a form of GC. Second, interfaces were created for COM--for your EXE to talk to external code. They don't make sense for anything else, unless you're using them specifically for the reference counting. (continued)
Comment: There are various GC tricks that depend on this. None of them require circular interface references that I'm aware of. And if you've got circular *external* references, then either you or the person who created the code you're interfacing with is doing something very, very wrong.
Comment: Your idea that interfaces make no sense except for COM or a poor way of doing GC is so wrong it's not even funny. Discussing this just makes no sense if you are starting on such a wrong premise. If you are able to question your assumptions then have a look at for example the Delphi OTAPI.
Comment: If you want support for dynamic, you better dump .net and go straight to smalltalk. There you have the advantages of dynamic, without the straightjacket. Better object persistence (Gemstone), better web framework (Seaside)
Comment: @Stephan: Sure, there are more interesting dev environments still. But that was not what I was writing about, I just wanted (as a long time Delphi developer) hint at that there are indeed things .NET does better than Delphi.
Comment: Umm... that's exactly what the Open Tools API is: Delphi's EXE talking to external code through interfaces. If it doesn't specifically use COM servers, the basic idea is still the same, and that's what I meant when I wrote that: Interfaces only make sense for external code.
Comment: Of course Mason. Maybe you would read http://dn.codegear.com/article/20384: [cjazdzewski on interfaces] "It allows us to more cleanly separate functionality in the IDE as well as support add-ins through the OpenTools API." But what would the Delphi developers know about it, compared to you...
Answer: Well, the .NET Framework is shared for all .NET applications, so you have it only once on your machine and 35MB are nothing today (compare it to the size of your Vista installation). For your second .NET application you don't have to download it again.
Comment: Well I didn't download vista and the framework will soon have changed again.
Comment: Some people download Vista ;-)
Comment: Actually I just did windows update yesterday (honest) so how come today I need to download .net?
Comment: You can do that with Delphi's runtime package support, too. I have some apps that are < 250KB because of runtime packages, and they're pretty complex and functional apps.
Answer: For Windows app, .NET (using C# or whatever) gives you more direct access to the latest and greatest Windows features.  It's also very well supported by Microsoft, has a huge community and lots of books written about it.
REALbasic (now Xojo) is for cross-platform apps.  Using it just on Windows can sometimes be useful, but that would not be its strength (which is that it's amazingly easy to use).
I don't know much about Delphi.
Comment: it's "strength"  :-)
Comment: Grammar and spelling Nazis need to learn capitalization of proper nouns like "Nazi". :-)

Seriously, people: get a life.
Comment: "", ""
Comment: Even then, the use of a closing tag without an opening tag is questionable. Really, shouldn't it be an empty tag?
Comment: "its strenth"  :)
Answer: From what I can see RealBASIC doesn't have much (if anything) in the way of Object Relational tools and probably wouldn't be as good a choice for n-tier, database-centric applications.


How to get latest version of Microsoft.TeamFoundation.DistributedTask.Task.Deployment.dll?

Question: Where can I download the latest version of Microsoft.TeamFoundation.DistributedTask.Task.Deployment.dll for a release on Azure DevOps?
Comment: Hi, what's your issue progress? Does the decompiled script could solve your puzzle? Feel free to leave comment if you still need help or still had issue.
Answer: Microsoft-hosted agents are regularly updated to make sure the latest and applicable images of the softwares are applied to the agents.
If you want to use the latest version of softwares to run the related pipeline tasks on DevOps,you can install the latest softwares on the agents which you used .
If the agent you used is privated agent, you need to manually install or upgrade all the softwares you request on the agent machine.By downloading the latest package from Internet or using the related commands to install/upgrade the softwares.
You can refer to this  case for details.
Comment: Hi, that's actually my question. Thanks for taking a look. I've posted a comment on the answer there with a little bit more detail.
Comment: Hi,Mike our engineers need more information to investigate further in the dc forum,you can continue it.
Answer: For other SO users could get clearly know more details about this issue when they are checking to this ticket, I add the following ticket which relevant with this ticket:
SO forum: Register-Environment Failing
DC forum: Where to download latest versions of deployment utilities for azure pipeline tasks?

When you using the task(such as AzureFileCopy V1.*) which need/import the Microsoft.TeamFoundation.DistributedTask.Task.Deployment.dll file, no matter whether the agent you used is hosted agent or private agent, its version are always be the latest version to the task, because these dll files are all exists depend with task.

According to the content you shared in the DC forum ticket:

I suspect that there's a newer version of these with a newer version
  of Register-Environment, because with my version of this PowerShell
  module, the following line fails claiming that I'm missing parameters,
  specifically a "taskContext."

the error you are facing caused by the configuration of the Microsoft.TeamFoundation.DistributedTask.Task.Deployment.dll file. We did not defined the parameter taskContext in it.
To check and verify it, you can execute the PowerShellOnTargetMachines v2.* task in your private agent, then find the dll file in the path of ~\_work\_tasks\PowerShellOnTargetMachines_3b5693d4-5777-4fee-862a-bd2b7a374c68\2.0.7\DeploymentUtilities. And also, you can see its version is 18.104.22.168.
Then you can use decompile tool, here what I am using is Reflector, to decompile this dll file.

You can see that in the script block of RegisterEnvironmentCmdlet, there does not have parameter taskContext defined in it.
When you use PowerShellOnTargetMachines v2.* task, the parameter for Register-Environment supported only include EnvironmentName, EnvironmentSpecification, UserName, Password, WinRmProtocol, TestCertificate, ResourceFilter, ProjectName, TagsList.
For the parameter taskContext, it is the one which only used in v1.*(See v1.* source code) and does not supported in v2.*. In v1.*, taskContext used for Get-VssConnection cmdlet which dose not used any more in v2.*. That's why you facing the error message in PowerShellOnTargetMachines v2.* task.


How does the rise in popularity of fantasy sports affect league ticket sales?

Question: I've seen some guesswork on the web around the economic impact fantasy sports has had on tv viewership and general product sales.  However, I can't find any hard research on what the effect on ticket sales has been in the past 15 years or so since fantasy sports has boomed into the tens of millions of participants.
Given fantasy football and fantasy baseball are the most popular, I'd be most interested to see if those sports have had a measurable increase in attendance that can be reasonably tied to the rise in fantasy sports popularity.
Comment: I have a feeling it would be very hard to divorce this factor from the availability of HD broadcasts of the games. Although my impression is that attendance has grown/stayed level even with the rise of these factors, but I don't have numbers in front of me to prove it.
Comment: Yeah, it's tough data to come across.  The FSTA does some reports on this, but I find there data to be pretty suspect (they claim fantasy sports is a $2-4 billion business for instance).
Answer: This is definitely different for every sport, so I think it is hard to make a general statement. So, I will attempt to answer the question from the point-of-view of fantasy football and the NFL.
There is evidence to show that it actually hurts ticket sales. In 2012, the NFL will require that teams show fantasy statistics at all stadiums. The belief is that fans are staying home to keep track of their fantasy football teams instead of buying tickets and attending games. Since ticket sales have been on the decline* for the past 5 years or so and subscriptions to services like NFL Red Zone and NFL Ticket are on the increase, it would stand to reason that the increase in popularity does not necessarily mean an increase in ticket sales. While this may be good for the NFL, it is not good for the individual clubs.
It is worth noting that this impacts the NFL harder than other sports due to the fact that at least 50% of their games are played at 1:00PM ET on Sundays. So, if you are attending a game, you are likely missing out on the majority of other games going on that week. The impact may not be nearly as severe with fantasy baseball or fantasy basketball.
*: warning- article is dated 2010, but the 2011 data was skewed due to the lockout and the 2012 data is not yet available
Comment: My worry is that this ignores other factors that may drive down ticket sales, such as higher ticket prices, a worse economy that makes it harder for the average family to purchase tickets, or the larger availability of games through cable and satellite (which may cost the same for an entire season as the tickets for a single game). Separating out the variables for the decline in ticket sales would be incredibly difficult. Fantasy football may have some impact, but the combination of factors probably has a much stronger relationship to the decline of ticket sales.
Comment: This makes a lot of sense.  While I generally agree with Mark Cuban's post (http://blogmaverick.com/2011/12/24/the-fan-experience-at-sporting-events-we-dont-need-no-stinking-smartphones/) it makes sense that it could drive people away from attending games if not available.
Comment: @SocioMatt Yeah, that's true. I didn't mean to say that fantasy football was responsible for ALL of the decline in ticket sales, but just that there is evidence to suggest that it actually hurts ticket sales more than it helps them.
Comment: @MarcusSwope I get that you weren't suggesting it accounted for all of the decline. It makes sense that it might be a contributing factor, I just don't know that it is clear that there is any impact by fantasy football. But I think you make some great points in the answer.


Exchange Server 2003 - the response from the remote server was 550 5.7.1 - alexparen fixedclix

Question: In our organization we have been receiving spam email from email marketing companies namely alexparen fixedclix, so we blocked those domains on our exchange server (2003).
This resulted in being unable to receive ANY emails from google, aol, and other external services.
the failure notification shows:
Your message has been blocked.
response from remote server
550 5.7.1 xxx.xxx.xxx.xxx ip has been blocked by alexparen.com
Disabling the block on our exchange lets the messages deliver normally.
We are very alarmed by this since it seems that somehow our emails get intercepted by that server?
Or somehow our exchange acts as being part of alexparen or fixedclix (both use same ip 22.214.171.124)
Might we be infected and acting as a bot for those marketers..?
Any information anyone might have or similar experiences are welcome
Answer: Based on my knowledge, Exchange Server 2003 extended support ends on April 8, 2014, you'd better upgrade exchange 2003 for more support.
Comment: yeah I know that, I wouldnt be asking here though right? I'd be asking MS for support
Comment: You'd better open a ticket for MS support:)


url_launche behaves differently in local vs firebase hosting

Question: I have created a simple Flutter Web App and deployed in to Firebase hosting.
I use url_launcher: ^6.0.17
I created a list of links that can be clicked to open in a new window:
<code>dynamic _launchURL() async {
  final parsedUrl = Uri(
    path: url,
    scheme: 'https',
  );
  if (await canLaunchUrl(parsedUrl)) {
    await launchUrl(
      parsedUrl,
      // mode: LaunchMode.externalApplication,
      webOnlyWindowName: "_blank",
    );
  } else {
    throw 'Could not launch $url';
    //  TODO: open window to copy url
  }
}

</code>
It works perfectly fine in test chrome/edge but also in emulator and my phone plugged to pc (when debugging from AndroidStudio)
When I deployed to Firebase hosting it behaves in a different way - it appends url I am providing after last slash of my mian page and thus it fails.
e.g.
when I am on https://.web.app
and click a link I see in browser that it attempts to open
https://my app name.app/ target link in a new browser tab
As I am new to firebase I am not even sure how to troubleshoot it - e.g. get app logs etc.
Any help will be appreciated
I tried:
googling + stack overflow + playing with url_launcher params + tested on multiple browsers
Answer: Ok - the problem was linked to url_launcher extension. I ended using deprecated API methodes - e.g. 'launch' instead of 'launchUrl' and it worked
Comment: Can you tell which version you are using. I am using 6.1.7 and the deprecated method of `launch` still not opening links


Field permissions per content type?

Question: I have a video field that should be visible only to authenticated users on one content type (bundle), but unrestricted on another content type.
What's a clean way to hide this field on one content type only, for anonymous users?
Notes:

I have the module field permissions installed, but it doesn't support per bundle field permissions.
I'm using Display Suite, so I'd rather not use a custom template unless that's the cleanest way to handle this one field.
I could create a new view mode that hides this field and and use HOOK_entity_view_mode_alter to switch to that view mode for anonymous users, but there are quite a lot fields to display so having 2 big view modes that are 95% the same seems kind of silly.

Edit: This is the code I used based on @wolverine's answer below:
<code>function HOOK_utility_field_access($op, $field, $entity_type, $entity, $account) {

  //Check video field only when attached to 'lesson'.
  if ($field['field_name'] == 'field_video' && $entity_type == 'node' && $op == 'view' && $entity->type == 'lesson') {

    //Grant access only if user is logged in.
    if ($account->uid > 0) {
      return TRUE;
    }
    return FALSE;
  }
}
</code>
Answer: Since you want to do it for few fields, I would suggest to do it using custom code rather than any module.
You can implement hook_field_access($op, $field, $entity_type, $entity, $account) and check for the "field name, content type, user, operation" and then  deny or allow access.

Field permissions per content type?


::active + CSS não está funcionando

Question:

div.duvidas2 > div > div::active +
div.duvidas2 > div > article {
  display: block;
}
div.duvidas2 > div > article {
  display: none;
}

      Titulo 1
      +

Artigo 1.

      Titulo 2
      +

Artigo 2.

Meu objetivo é clicar na div.duvidas2 > div e abrir o article
Mas apenas o article da div.duvidas2 > div que estiver ativa deve estar com display:block
Onde estou errando?
Answer: Cara está tudo errado...
Active não tem dois dois-pontos, não é assim ::active, é assim :active
Não adianta colocar :active em uma div, pq :active não é uma propriedade desse tipo de elemento, :active é para usar em links e alguns elementos de form, mas não em uma div
A regra tb está equivocada...
div.duvidas2 > div > div::active +
div.duvidas2 > div > article

Primeiro que vc está usando o + que pegaria uma div com a classe div.duvidas2 que vem depois da primeira div com div.duvidas2, só que vc só tem uma div.duvidas2 então a regra já não bate...
É nessas coisas ai que vc está errando
Agora pelo que entendi do que vc quer, uma opção seria usando uma tag  e a pseudo classe :focus, assim quando vc clicar no  vai fazer o focus e mostrar o
 com uma regra CSS tipo a:focus + article {display:block}

div.duvidas2 > div > a + article {
    display: none;
}
div.duvidas2 > div > a:focus + article {
    display: block;
}

      Titulo 1
      +

Artigo 1.

      Titulo 2
      +

Artigo 2.

Comment: Sobre os :: é regra do CSS3. : apenas era no CSS2. Mas no caso hugocsl, tem como, ao clicar no mesmo link, fechar ele também? Tipo: abriu, clica de novo e fechou. Isso com CSS? Ou no caso só dá com JS? Mas entendi sua explicação. Mas, o link mostra um exemplo com input type text https://jsfiddle.net/zsderorm/1/
Comment: @CarlosRocha não jovem, não existe `::active` em lugar nenhum, aqui vc pode conferir uma documentação confiável e vai ver que não tem menção a `::active`, os `::` são para pseudo-elementos, não para pseudo-classe veja https://developer.mozilla.org/pt-BR/docs/Web/CSS/Pseudo-classes esse exemplo do link que vc postou usa `:focus` como o exemplo que eu deixei ai na resposta. Do jeito que vc quer da pra fazer tb, mas a técnica é outra, é usando checkbox e label. Ou então vc pode fazer como nessa questão https://pt.stackoverflow.com/questions/360001/como-customizar-a-seta-padr%c3%a3o-da-tag-details
Comment: entendi! Nesse caso, fazer com JavaScript ou JQuery vai ficar melhor! Mas muito obrigado. Vou aceitar a resposta pois foi compatível totalmente com a pergunta!
Comment: @CarlosRocha haha pois vc perguntou onde estava errando né rss. Mas para resolver existem várias tecnicas, algumas sim com JS/jQuery, mas tb dá pra fazer com html/css, procure por "Collapse component" no Google que vc vai achar algumas coisas. Essa outra questão tb pode te interessar tem umas dicas lá https://pt.stackoverflow.com/questions/182123/como-fazer-collapse-e-expand-de-um-texto-usando-apenas-html5

::active + CSS não está funcionando


How should I check the assumption of linearity of the log-odds in a logistic regression and for multicollinearity when my predictors are all binary?

Question: From what I've read, logistic regression assumes

$y_i\sim \text{Bernoulli}(p)$
$y_i \perp y_j$, for $i\ne j$ and  $i,j \in \lbrace 1,..., n\rbrace$
log-odds is linear in $X$, i.e. $\text{logit}(p)=X\beta$
no multicollinearity among predictors
$n$ is large enough

However, I'm confused about assumptions 3 and 4 in the context where all my predictors are binary.
What plot or test should I run to assess if the linearity assumption is satisfied?
For multicollinearity, I know the way we define correlation matters. For instance, if your using ordinal data, Spearman correlation is appropriate. For nominal, polychoric correlation is appropriate. So, when doing a multicollinearity test, is it still reasonable to usual tests like VIF, condition numbers, and pair-wise correlation to evaluate multicollinearity? If not, what tools are appropriate? Would a pair-wise correlation with tetrachoric be appropriate? In the numerical case, I thought this was flawed because not all multicollinearity occurs just between pairs but can be groups of several predictors correlated with each other. Hence, VIF and condition numbers are used. Wouldn't this issue be present in binary data? If so, what is the binary equivalent of VIF and condition numbers?
Answer: Assumption 2 states that the observations are independent from each other. This would be violated if individuals shared an unmeasured quality based on their location, for example. It is commonly violated when students are nested with school, cities within states, patients within hospitals, etc. There are a few ways to control for dependence, which include using mixed models or generalized estimating equations.
Assumption 3 just means that you have the model form correct. This is an unverifiable assumption. It may be possible to see whether there are some egregiously wrong predictions, which would indicate that your functional form is incorrect, and you can use other methods to prune a larger model (e.g., lasso), but the assumption of linearity just means that the logistic regression model you specified correctly represents the relationship between the predictors and the outcome.
Multicollinearity is automatically satisfied when you use automated software to fit logistic regression. It is not a statement about how correlated covariates are with each other; its a statement about the rank of the design matrix. Logistic regression is valid with variables that are correlated at .99 (however you measure that), but unless your sample size is massive, there will be extreme imprecision in the estimates and the design matrix may not be invertible. This is a computational problem, though, not related to the assumptions of logistic regression. With binary variables, this amounts to not including both levels of the binary predictor and an intercept in the model. You wouldn't do this anyway, so you don't need to worry about it. Including perfectly redundant variables is another way to violate this assumption, but most software will figure that out and remove the offending variables for you.
You don't need to think about how you are measuring the association between predictors to figure out if this assumption has been met. The VIF measures how much additional uncertainty is caused by having correlated predictors, but this has nothing to do with the assumptions of logistic regression. It's better to have independent predictors to maximize the precision of the coefficient estimates, but estimates are still consistent even if the predictors are highly correlated (however you measure that).