Smooth 60fps frame rate independent motion in AS3

Question: I'm having trouble achieving frame rate independent motion in AS3 at 60fps. Every frame I measure the time since the previous frame, add it to an accumulator, and if the accumulator is greater than my target time, which is 16.666ms (60fps), a frame is simulated.
The problem is that the AS3 getTimer() only returns a time in milliseconds.
The delta times I get are often 16ms for the first frame, 16ms for the second, then 18ms for the third, and this pattern repeats. This averages out to 16.666. But in the first frame it is lower than the target time (16 < 16.666), so no frame is simulated. In the second frame the accumulator is higher than the target time, but slightly less than double it, so one frame is simulated. For the third frame 18ms pushes the accumulator over double the target time, so two frames are simulated.
So I'm getting this very jerky motion where no frames are rendered, then one, then two, then none, then one, then two, and this continues.
How would I get around this?
Comment: I suggest reading this article: http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/
Comment: Why are you using Timer and not Event.ENTER_FRAME ?
Answer: Wow... I thought I was only one who found that out.
Yes, the timer class in AS3 is not accurate.  It will only trigger every ~16ms which causes MAJOR issues at times.

If want to see 2048 actions in 1000ms: FlashText Markup Language

(To test this, you'll need a method which takes 1ms to execute - just for even stats)
Notice the difference:

CORRECT: 1000ms | timer=0 == 1000 actions
AS3: 1000ms | timer=0 == 62.5 actions

I was able to write a class that works like this:

CORRECT: 1000ms | timer=0 == 1000 actions
RESHAPE TIMER: 1000ms | timer=0 == 1024 actions

NOTE:

it DOES NOT fire an action every ms
it DOES catch up to actions between the 16ms interval
an ACTION (the way I use it) is a method call, each method call can have its own body

The methodology I used to create this was catch-up... basically the first timer event will fire at 16ms... we know we have a full 16ms worth of code time to fire our own actions before the timer class fires again - thats where you inject sub-actions...
The highest I was able to produce was 2048 actions in 1000ms... more than 2 actions per ms.
Now... back to your problem
There is NO WAY to trigger a 0ms timer event.  Based on my solution, if you want to by-pass the first 16ms of lag before the timer fires... you can dispatch an event which will fire within 2ms depending on the current system processes.
Possible Solution
If you take my approach for throwing your own actions within the 16ms, then you can build your own timer class.  Use events for times under 16ms, when fired... fire 15 more - lol.  Basically, you can create your own deltas between the 16ms.


How to use Recurring Dates with Views properly?

Question: I am trying to use recurring dates for one of my content types (Event) to limit the amount of Event records.
I would like to have one Event record created for all dates of that Event.
For example if an Event occurs every week for a year I have 1 record instead of 52.
Still I would like to see 52 separate lines in the related View because I would like to be able to sort/filter the View to see current week's Events only.
How to set up a Events View for that data so that each view line shows one date only ?
I would like a View to return a list like this...
 - Event A  12-10-2011
 - Event B  12-11-2011
 - Event A  12-12-2011
 - Event B  12-13-2011
 - Event A  12-14-2011
 - Event B  12-15-2011

(Event A and B are recurring every second day )
...instead of a list like this:
 - Event A
    - 12-10-2011
    - 12-12-2011
    - 12-14-2011
 - Event B
    - 12-11-2011
    - 12-13-2011
    - 12-15-2011
 - Event A
    - 12-10-2011
    - 12-12-2011
    - 12-14-2011
 - Event B
    - 12-11-2011
    - 12-13-2011
    - 12-15-2011
 - Event A
    - 12-10-2011
    - 12-12-2011
    - 12-14-2011
 - Event B
    - 12-11-2011
    - 12-13-2011
    - 12-15-2011

Comment: Please note I know how to do it without recurring dates but I specifically need to limit the amount of data to be stored in and especially entered into the database. That is why I would prefer to use recurring dates or another simillar solution.
Answer: Eventually I found how to set this up an easy way:

Go to your View
Go to Displays --> <your display name,  for example Page> --> Edit
Select Format : Table
Add a date field:
Select a Content: <your date field name>
You will see Configure field: Content: <your date field name>
Go to "Multiple field settings"
Uncheck "Display all values in the same row"

If checked, multiple values for this field will be shown in the same
  row. If not checked, each value in this field will create a new row.
  If using group by, please make sure to group by "Entity ID" for this
  setting to have any effect.
Answer: You can also use "unformatted list" and filter your dates with "greater than or equal" now to show current and upcoming events.
Answer: If you use Display Suite for displaying the events (Show: Display Suite) you can do something like this in a custom module. Remember to change 'mymodule' and 'field_date' to correspond your module and date field names.
/**
 * Implements hook_ds_views_row_render_entity_alter()
 */
function mymodule_ds_views_row_render_entity_alter(&$content, &$context) {
  //Display only the current date value from repeating dates
  $date_field_name = 'field_date';
  if (isset($content[$date_field_name]) && count($content[$date_field_name]['#items']) > 1) {
    // Modify the view, or the content render array in the context of a view.
    for ($i = 0; $i < count($content[$date_field_name]['#items']); ++$i) {
      if($content[$date_field_name]['#items'][$i]['value'] != $context['row']->field_data_field_date_field_date_value) {
        unset($content[$date_field_name][$i]);
      }
    }
  }
}

If you are just using fields as your Show option you can probably do something similar with View's hooks.


LINQ - checking for null values then appending statement back to query

Question: Am using Linq-to-SQL and have wrote the following query but I need to be able to check that the variable "UserRole.RoleID" is not null.
var MemberQuery = from SystemUser in SecurityFilter.FilteredMembers(SecurityInfo, Context, DetailLevelEnum.NameOnly)
                      join Member in Context.webpages_Memberships on SystemUser.ID equals Member.UserId
                      join UserRole in Context.webpages_UsersInRoles on Member.UserId equals UserRole.UserId
                      where Member.IsConfirmed || IncludeUnconfirmed && Filter.SelectedMemberRoles.Contains(UserRole.RoleId) // This will sometimes be null
                      select SystemUser;

I have thought through a number of approaches such as wrapping the query in an if / else statement or creating an anonymous type. Am not sure what the best approach would but I am trying to do something like this:
var MemberQuery = from SystemUser in SecurityFilter.FilteredMembers(SecurityInfo, Context, DetailLevelEnum.NameOnly)
                              join Member in Context.webpages_Memberships on SystemUser.ID equals Member.UserId
                              where Member.IsConfirmed || IncludeUnconfirmed
                              select SystemUser;

if (Filter.SelectedMemberRoles != null)
{
    MemberQuery = MemberQuery.Where( // Somthing here
                              join UserRole in Context.webpages_UsersInRoles on Member.UserId equals UserRole.UserId
                              where Filter.SelectedMemberRoles.Contains(UserRole.RoleId)
                              select /* Somthing */).Any();
}

How can I append the second part of the query wrapped within the if condition to the original query?
Comment: You could move the `join`of the second part as `LEFT OUTER JOIN` to the first part and then add the following to your `where` of the first part:
`&& (Filter.SelectedMemberRoles == null || UserRole != null && Filter.SelectedMemberRoles.Contains(UserRole.RoleId))`
Comment: I would not use contains because it will not always work. In a situation like this I would use Query Expresssion
Comment: What's a situation where contains would fail in the above query?
Answer: You could try this:
var MemberQuery = (from SystemUser
    in SecurityFilter.FilteredMembers(SecurityInfo, Context, DetailLevelEnum.NameOnly)
join Member in Context.webpages_Memberships on SystemUser.ID
    equals Member.UserId
join _UserRole in Context.webpages_UsersInRoles on Member.UserId
    equals _UserRole.UserId into _UserRole
from UserRole in _UserRole.DefaultIfEmpty()
where (Member.IsConfirmed || IncludeUnconfirmed )
&& (
    Filter.SelectedMemberRoles == null || UserRole != null
    && Filter.SelectedMemberRoles.Contains(UserRole.RoleId)
)
select SystemUser)
.Distinct();

Comment: you should put this clause in parenthesys..  Filter.SelectedMemberRoles == null || (UserRole != null
    && Filter.SelectedMemberRoles.Contains(UserRole.RoleId)) because the last filter is bonded at the second filter true value, otherwise you risk that the last filter it is applyed also in case of first filter null
Comment: `AND` beats `OR`, meaning that first `AND` is being interpreted and afterwards `OR`
Comment: ok, you are right.. the "AND" binds together the last two operands as one and it is evaluated only if the first operand is not null
Comment: Am getting an error saying "The name UserRole is not in scope on the right side of equals, Consider swapping the expressions on either side of equals", Which I've tried to swap but I just get another error. I've actually got the original query working in a different way but would still like to test your suggestion out.
Comment: @HitTheSky Oops, you are right. There was an underscore missing. Edited my post


What is the percentage breakdown of different time signatures and their rate of occurrence in popular music?

Question: I'm currently working on a probabilistic, procedural music engine and although I could choose relatively decent arbitrary distributions, I'm curious as to whether or not there have been any formal/academic studies that have looked into this?
More specifically, I'm hoping for links, references or statistics directly from Musical academics/researchers that give a breakdown of data gathered from popular music. I'm primarily interested in Western popular music, but would also be interested in other forms of popular music.
Comment: @jjmusicnotes the header of this stack exchange states "Musical Practice". The musical practice I am involved in is procedural composition, to which probability and statistics can play a huge role.

> "...it is impossible to certifiably quantify every piece of music written"

You seem to have misinterpreted my question - I would never expect to see stats for "all music". However like any strong research, I'd hope that a lot of data was collected (i.e. every song to enter the top 100 for the past X years).
Comment: Musicians are altogether not interested is accumulating statistics of how many times things happen.  We are interested in sounds, why they happen, and how they make us feel. This question is impossible to answer as it is impossible to certifiably quantify every piece of music written. It is akin to asking "what is the most popular number of tree rings" and asking for evidence from every tree in the Americas.
Comment: @jjmusicnotes as an example of similar research, the folks who run [this site](http://www.hooktheory.com/theorytab/common-chord-progressions) have analysed and documented popular chord progressions (from thousands of songs) in order to learn about composition and generate chord progressions using Markov Chains.
Comment: The most common (popular?) is 4/4, but that's in the Western world.That's why it's called common time, although the 'C' at the beginning isn't shorthand for common. And that is often sub-divided into different 'feels'. The term 'popular music' is possibly too wide reaching, making the question too vague ?
Comment: @jjmusicnotes Actually, countless musicians I know (me included) are interested in this type of information. It can have a significant answer with a big enough sample size, and the information can be categorized. The scenarios you are painting are too rigid. I understand that some musicians might not be interested, but saying that "musicians are altogether not interested" is just wrong.
Comment: Thanks, I'm well aware of the popularity of 4/4 and the different types of Time Signatures (i.e. simple, compound, etc). I'll update the question to be more specific.
Comment: @mindTree - I'm quite well aware of procedural composition.  My comment was hyperbolic, extended through my analogy. Note that I didn't express that your question wasn't appropriate for the site. I merely implied that this may not be the most efficient resource for your question. One would think that contacting  the Library of Congress, or ASCAP would be a better use of your time. Additionally, you would need to have a clear definition of what defines "popular" as 100 years ago, the waltz was king, 70 years ago, it was swing.
Answer: You might want to check out David Temperly's work:
http://theory.esm.rochester.edu/rock_corpus/
He's been doing corpus studies on reasonably large samples of pop-rock music, and has published on it as well.


Deprecate multisite in 8.x for removal in 9.x

Question: I am thinking about implementation of some sites with multi-site and idea of solution (one code-base) is perfect for me even if shared table is not supported any more (my question about shared table is here also i'm aware of domain module too).
After some search, I found this topic about plan to deprecate multi site in 8.x and removal in 9.x.
My questions  are:

How serious is deprecation in 8.x and removal plan of multi-site in drupal 9? the topic is in category of plan for two years.
Even if removal happens in 9.x, we have to expect some migration path to removal of 9.x or not? In my idea this migration didn't happen for shared tables.
Proposed solution for removal of multisite in mentioned topic is

The modern approach to multi-site is: git — Same code, different
  sites. Under your control. And well-maintainable.

I can't understand it. How does it works?
Answer: You have a few questions there, so I'll hit them individually:

How serious is deprecation in 8.x and removal plan of multi-site in
  drupal 9? the topic is in category of plan for two years.

It's hard to say. Controversial topics like that can go in circles for years in the open source community. As you can see, that topic started over three years ago, and still has not reached a conclusion, and may well never reach one.

Even if removal happens in 9.x, we have to expect some migration path to removal of 9.x or not? In my idea this migration didn't happen for shared tables.

It will be fine even if you are sharing tables, as you can just migrate each multisite to a new individual site. You may have to do a special database dump and import to get the shared tables into your new system. I did this once when migrating from D6 to D7 for my company site - I was using multi site, and in the upgrade, I just created two sites out of the one.

I can't understand it. How does it works?

Git keeps all your code in a repository, which you can clone as necessary. So any time you need to spin up another site, you just clone the code, and you have a new Drupal instance. As you update sites over time, you can merge the code changes from one repository to another.
In my own company system, we have a central repository for each project. Any time someone new works on the project, they clone the code from the central repository, and they have an exact copy of the site. We then clone the repository to the webroot, so that it is available over the web. When people make changes to the code, they push the changes to that central repository, and then anyone can pull them at any time to their own repository, and/or the repository stored in the webroot of the public site.
Comment: Once you learn GIT, it's excellent. I can update 10 sites three minutes. It's much better than multisite.

I switched from multi-site to two sites when I went from D6 to D7, because D7 caused too many troubles.
Comment: thank you @Jaypan. so idea behind git is same code and not one code. so i think it hasn't benefits like one time update, shared module.....it seems in my case git only increase complexity.
Comment: also about your d6 to d7 migration:  shared table is ok in d7. didn't migration work for multi-site so you decided to go with 2 different sites? also file path in main domain is like sites/default/files/ and for subdomain in multi-site is like sites/subdomain/files/. after separation of two sites you hadn't problem with file load?
Answer: I've used Aegir for multi site management, great tool!
If you have ever used Amazon Web Services, it's similar like that but for Drupal. With a click of a button you can launch specific site builds.
Here is a quick overview tutorial on it
All it takes to update your site is a click of a button (Migrate button, disabled by default, read docs on how to enable it).
Aegir behind the scenes uses Drush to accomplish the bulk of the work, such as drush make files for installation, drush dl to download modules, etc...
Comment: Aegir depends on the multisite functionality as well. Every platform is in fact a multisite 'core': http://docs.aegirproject.org/en/3.x/usage/sites/#multisite
Answer: The Git solution solves the problem of cloning an existing site. Each clone will contain a complete copy of the Drupal environment, which has an overhead of 53 MB as of Drupal 8.1.1 (87 MB actual disk space used in my file system).
Given the cost per MB of today's disk and SS drives, this overhead is not a serious problem for most of us. However, during development we may have many experimental and pedagogical sites saved in our file systems. Drupal's multisite feature, properly configured, can save a lot of file space in this case. This is a strong argument against removal of the feature.


Grade 10 algebra question

Question: Simplify the following:
$\left ( 8^{4+2a} \right )\left ( 16^{a-1} \right )\div 4^{3a+2}$
I don't know how to simplify this expression.
Comment: $8^{4+2a}=\Big(2^3\Big)^{4+2a}$ $=2^{3(4+2a)}$ $=2^{12+6a}$.  And just as $8$ is $2^3$, so $16$ is $2^4$ and $4$ is $2^2$. ${}\qquad{}$
Answer: Hint: Use that
$$4=2^2\qquad 8=2^3\qquad 16=2^4$$
as well as these rules about exponentiation:
$$(a^b)^c=a^{(bc)}\qquad a^b\div a^c=a^{b-c}$$
Comment: Thank you very much :) This hint helped me a lot.
Answer: Note that:
$$8^{4+2a}=\left(2^3\right)^{4+2a}=2^{3(4+2a)}$$
$$16^{a-1}=\left(2^4\right)^{a-1}=2^{4(a-1)}$$
$$4^{3a+2}=\left(2^2\right)^{3a+2}=2^{2(3a+2)}$$
Since they are all raised to the same base $(2)$ you can go ahead and apply the relevant exponential laws to simplify your expression. Namely $a^na^m=a^{n+m}$ to simplify the numerator and $\frac{a^n}{a^m}=a^{n-m}$ to further simplify the remaining expression.
Comment: No problem, glad I could help!
Answer: $\log_2(n)\, =\, (4\!+\!2a)\,3 + (a\!-\!1)\,4 - (3a\!+\!2)\,2\, =\, 4\!+\!4a\, =\, 4(1\!+\!a),\ $ so $\ n = 2^{4(1+a)} = 16^{1+a}$
Answer: Hint: Convert each number to same base. What ever algorithm you do to a numbers those must be in same base. so  in this problem convert to base 2.then do your usual calculation on indices.
Then game is over.

Grade 10 algebra question


Can't track why Boost-Crawler doesn't work

Question: I use Drupal 7.38 and Boost x - 1.0.7, and I Can't get the Boost Crawler to work... Boost itself is working fine (verified formation of cached webpage files at root/cache/...).
Seemingly, I did all I need to active the crawler submodule:

I enabled the module.
I went to Admin > Configure > System > Boost > Crawler, and ticked the checkbox to enable the crawler to run on cron.

After I did these stages, I ran Cron and went to root/cache/... and found only 3-4 cached files that where created by anonyous surfing either way... If the crawler module was working I guess I should have seen at least 60 cached-webpages there.
Since I'm not yet a programmer I have no idea how to even start dealing with this problem. The least I can do is to put here a print screen of my Recent log messages... I could paste everything seem relevant to you from there...
I very much need this submodule to work, please help!,
Answer: What you're seeing may be correct behavior. Boost Crawl (a submodule but without its own drupal.org page) is careful to warn that; "Minimal crawler - expires and regenerates pages only when content is edited and on next cron run" [Emphasis added.] SO, it will track content that you have edited, not crawl the site and thereby refreshing the page cache.
Enabling Boost and boost crawl on my site, and then running cron (using drush -v cron to spy cron output) I essentially saw what you saw, in my case just my home page. Running Xenu (explained below) triggered a populating of the boost cache for my entire site. Maybe this is what you were expecting?
If you want to refresh your site's boost cache index, check out either

xenu link slueth
httrack
or on Mac SiteSucker

You didn't ask, but each of these are invaluable web site QA tools as well.
Comment: wow! Great answer! Thank you very much, messier Screenack!
Comment: I haven't used it, but there is a Drupal module called [link checker](https://www.drupal.org/project/linkchecker). So, it may be possible to run a link check from within Drupal.
Comment: One small question, I see the Xenu link slueth & httrack are downloadable programs. Is there a way to "visit all non-cached wepages at once" from Drupal or purely online? I ask mainly to broaden general knowledge... Is it logical to assume that any broken link checker would "Activate" Boost automatically?


How can I conditionally create a user account based on field in registration?

Question: Here is the scenario:
Prospective employees (PE) who need to access this Drupal site for onboarding resources will be sent an access code from someone in HR (to prevent random people from creating accounts).
The PE goes to Drupal site and "registers" for a user account and they enter the access code into a field.
Only approve the account if the access code is correct. If it is correct, approve account and set role to prospect. If it is not correct, block account (until that user registers with correct access code or alternately, someone in HR manually approves it).
What should the account settings be for who can register account? How to test access value and approve/grant role or block based on registration field? Is there a hook or class to extend?
Comment: Don't have an answer, but if the HR person will have to issue the codes and approve accounts, wouldn't it be easier just to have HR create the account in the first place?
Comment: Because they send the access code in a email that goes out from a template that is part of other onboarding processes and not all prospective employees will want or need to access the site.
Answer:
Create a new field on the user object, field_registration_code.

Set the form field to show on the registration page.

Use hook_form_alter() to hide the field when not registering, if the code is not to be used in the future. Don't hide the form field on the 'manage form' tab, else it will not be rendered on the registration page.

Create a service with the following method:
/**
 * Validates a registration code.
 *
 * This function checks if the submitted  code is a valid
 * registration code, and if it is, invalidates the code, and
 * returns TRUE. If the access code is invalid, it returns FALSE.
 *
 * @param string $registrationCode
 *   The code to be validate.
 *
 * @return bool
 *   TRUE if the code was valid, FALSE otherwise.
 */
 public function validateRegistrationCode(string $registrationCode): bool;

Implement hook_ENTITY_TYPE_insert(), implemented as hook_user_insert(). This is called after the user entity has been saved. You can use that hook to check if the given code is validated, and if not, block the account. It can then be activated by an admin through the admin interface.
function HOOK_user_insert(EntityInterface $user) {
  if ($this->myService->validateRegistrationCode($entity->field_registration_code->value)) {
    // Add roles to user here.
  }
  else {
    $user->block()->save();
  }
}


Site is redirecting to old domain on button submission, files are linking to old domain

Question: I have a D7 site at www.example.com, an old one, not updated since 2012 (Drupal version 7.34). I made a clone copy with separate clone database under dev.example.com
All files like CSS are still linking to www.example.com (while they are available at dev.example.com).
And most important, on /admin/ backend when under dev.example.com if you click any Submit button in any page, it redirects to the www.example.com website. So if I submitted any operation at dev.example.com/admin/* it redirects to same page at www.example.com/admin/*
I've cloned websites million times, I never had this behavior. How do I prevent redirects for files and on submissions?
update: I found in settings.php I have $base_url = www.example.com enabled, can somebody confirm this is the reason?
Comment: Can *you* confirm this *was* the reason?
Answer: Yes, you have to edit it to dev.example.com. In the Drupal code, the modules use a function who returns the base URL. So if this URL is the old site... it resolves to the old site.
It's also used to protect your website against XSS.


Unable to push into empty Array JS

Question: The findOne query is returning a user from the DB. When i console.log(user) it does print out user data. But for some reason isn't pushing into user_contacts. Its just returning as an empty array.
get_contacts: function (req, res){
                var user_contacts = [];
                for(var i=0;i<req.body.contacts.length;i++){
                    User.findOne({_id: req.body.contacts[i]._User}, function (err, user) {
                        if(user){
                            console.log(user);
                            user_contacts.push(user);
                        }else{
                            console.log("Error");
                        }
                    })
                }
            console.log(user_contacts);
            res.json(user_contacts);
            }

This should be so simple, but just cannot see what I am doing wrong. Appreciate the help.
Comment: The DB call is async - when you call `res.json` your DB calls haven't executed yet - hence the empty response.
Comment: but the console.log(user) is still printing out the user data, if the DB calls haven't executed how can I have user data to print?
Answer: Since the call is async - your logs and response are executed before everything is finished. You'll probably also run into some issues with looping that async call - your best bet is to use $in and then return:
get_contacts: function (req, res){
    var ids = req.body.contacts.map(function(contact) { return contact._User });
    User.find({_id: {$in: ids}}, function(err, users) {
        res.json(users)
    });
}

Comment: will this not return only one single user data? .. I am trying to retrieve multiple users data together. Thus created the empty array and tried pushing.
Comment: This will query all the `ids` of the users passed back and return an array @Ani777
Comment: tried it, it works. Thanks a lot.

so basically whats happening is ids is returning all the _User fields in req.body.contacts and the the Query is searching for users with the ids that have been returned. Am i right?

will be reading about $in as well.
Comment: @Ani777 -- Yep - that's exactly what's happening
Answer: User.findOne({}) is async, which mean the callback function where you push data into user_contacts array is executed with delay.
Therefore, the moment you console.log, user_contacts is still empty.
Comment: Thanks for the link to async, reading it right now, hope can make some sense out of it.

Unable to push into empty Array JS


Get all logs from specific PID in android/linux?

Question: see currently in android there is one utility called logcat which shows all user space programs's log on stdout or terminal.
but here I do not want all messages in list. But i want to see only specific application's log only.
So if i need to make such utility then how can i do that?
see if i want all log from pid 132 and 324 then i will run as follows on terminal
logcat_special 132 324

and now it will show all messgaes from that pid.
If this things are hard to implemet with pid then we can  go with application name
as
logcat_special vlc

Answer: Log cat already has a package  based filter . take a look here : Logcat options
also according to this answer you can find app package from its pid.
So combining that with logcat you can achieve the functionality you are after.
This option should work:
logcat <your package name>:<log level>

for example logcat android.test:V
Comment: I coudnt find package base filter option i can go with tag based option adb logcat ActivityManager:I MyApp:D *:S


Does an ES6 shorthand exist for copying a subset of an object's properties into a new object?

Question: Consider the following object:
const obj = {a: 1, b: 2, c: 3, d: 4, e: 5}

Is there a simple syntax for creating a new object that contains:
const obj2 = {a, b, d}

I'm aware that underscore & lodash have .pick(), but I'm hoping there's some kind of destructuring trickery that I may not be aware of.
Comment: I can't think of anything in ES6 that's more readable than doing it the old way—`const obj2 = { a: obj.a, b: obj.b, d: obj.d };`—though repeating `obj` so many times is not that nice.
Answer: Concise one-liner in ES2015 is
const obj2 = (({a, b, d}) => ({a, b, d}))(obj);

It doesn't seem to be possible to avoid {a, b, d} tautology while keeping it compact at the same time.
Comment: @MichaelScheper That's why Lodash `_.pick` is still applicable. The answers in dupe question cover it all.
Comment: Wow, I was all excited about using this ES2015 construct for the first time, but it's still not quite as elegant as I hoped. Oh well, maybe a future version. Thanks!
Answer: You can do it in two steps:
const obj = {a: 1, b: 2, c: 3, d: 4, e: 5};
var {a, b, d} = obj;
const obj2 = {a, b, d};

If you don't want to pollute the scope,
const obj = {a: 1, b: 2, c: 3, d: 4, e: 5};
const obj2 = {};
{
  let {a, b, d} = obj;
  Object.assign(obj2, {a, b, d});
}

Answer: You could use Rest parameters and create custom pick function like this

const obj = {a: 1, b: 2, c: 3, d: 4, e: 5}

function pick(object, ...p) {
  return p.reduce((o, e) => {return o[e] = object[e], o}, {});
}

console.log(pick(obj, 'a', 'b', 'd'))


Playing without boots

Question: Today during Arsenal vs Crystal Palace, Pierre Emerick Aubamayeng's boot came out after a tackle and he couldn't retrieve the ball, but in case if he managed to retrieve the ball, is he allowed to continue to play immediately, without the boot?
Answer: Yes he can, but only until the ball next goes out of play.
According to IFAB Laws of the Game 2019/20  Law 04 Page 58

A player whose footwear or shinguard is lost accidentally must replace it as
  soon as possible and no later than when the ball next goes out of play;
  if before doing so the player plays the ball and/or scores a goal, the goal is
  awarded.

Playing without boots


Minimal distance between points on two graphs

Question: What is the minimal distance $d$ between the graphs of $y_1 = \sin x$ and $y_2 = 2 + \sin x$? The trivial observation is that $d \le 2$ (just set $x = 0$ in both equations), but numerical computations show that for $x_1 \approx 0.4787$ and $x_2 \approx -0.4787$ (it is surprising that $x_1+x_2 = 0$, isn't it?) we have $d((x_1, y_1(x_1)), (x_2,y_2(x_2)) \approx 1.4423$. Can we find the exact value? I already tried using RIES but it gave no results.
Comment: Nice question. I don't have time to solve it now, but I think that defining the distance function as
$$f(x,y)=(x-y)^2+(\sin(x)+2-\sin(y))^2$$
and moving to the variables
$$x'=x-y,\qquad y'=x+y$$
might greatly simplify things.
Comment: It's not so surprising to me that the pair is $(x_1,-x_1)$. Due to the symmetry of the problem, it was either that or there would have to be at least two distinct pairs $(x_1,x_2)$ and $(-x_1,-x_2)$.
Answer: As yohBS commented, the problem is to minimize the square of the distance, that is to say $$F(x,y)=(x-y)^2+(\sin(x)+2-\sin(y))^2$$ Computing the partial derivatives, $$F'_x(x,y)=2 (x-y)+2 \cos (x) (\sin (x)-\sin (y)+2)$$ $$F'_y(x,y)=-2 (x-y)-2 \cos (y) (\sin (x)-\sin (y)+2)$$ What is "clear" is that $$F'_x(x,-x)=4 x+2 (2 \sin (x)+2) \cos (x)$$ $$F'_y(x,-x)=-4 x-2 (2 \sin (x)+2) \cos (x)=-F'_x(x,-x)$$ which make both partial derivatives equal to $0$ if one of them is $0$.
So, the problem reduces to the minimization of $$G(x)=4 x^2+(2 \sin (x)+2)^2$$ that is to say to the solution of $$G'(x)=8 (x+(\sin (x)+1) \cos (x))=0$$ The plot of this function shows a root very close to $-\frac 12$. So, using Newton with $x_0=-\frac 12$, the first iteration gives $$x_1=-\frac{1}{2}-\frac{\left(1-\sin \left(\frac{1}{2}\right)\right) \cos
   \left(\frac{1}{2}\right)-\frac{1}{2}}{1+\left(1-\sin
   \left(\frac{1}{2}\right)\right) \sin \left(\frac{1}{2}\right)+\cos
   ^2\left(\frac{1}{2}\right)}\approx -0.478634$$ while the solution is $\approx -0.478722$ (it is worth to mention that one iteration of Halley method leads to $x_1 \approx -0.478725$)
Using Newton with $x_0=-\frac {\pi} 6$, the first iteration gives $$x_1=-\frac{1}{24} \left(3 \sqrt{3}+2 \pi \right)\approx -0.478306$$ and using Halley would give $$x_1=-\frac{603 \sqrt{3}+4 \pi  \left(87+\sqrt{3} \pi \right)}{4608} \approx -0.478750$$
Using $x_1$ as an approximation of the solution, the minimum distance is then given by an ugly formula (too large to fit on the page); in any manner, at this point $F(x_1,-x_1)\approx 2.08031$ corresponding to a distance $\approx 1.44233$ you already found.
You could notice that $F(-\frac {\pi} 6,\frac {\pi} 6)=1+\frac{\pi ^2}{9}$ to which corresponds a distance $\approx 1.44797$ quite close to the rigorous minimum. Developing $F(x,-x)$ as a third order Taylor series built at $x=-\frac {\pi} 6$ gives a minumum for $$x=-\frac{1}{6} \left(8 \sqrt{3}+\pi -2 \sqrt{39+2 \sqrt{3} \pi }\right)\approx -0.478741$$
All of this can be confirmed by an analysis on the contour plots.
Answer: It is antisymmetric about the point $(1,1)$.
For minimal distance the common normal should be normal to either graph.
The minimal distance = $d$,  $ (d/2)^2 = x^2 + ( 1 - \sin x)^2 $ which simplifies to:
$ ( x- ( 1 - \sin x) \cos x) =0, $  which has a numerical solution $ x = \pm 0.478722$
So the two points for minimum distance are between the antisymmetric points:
$$ (0.478722,.460646), (-0.478722,1.53935 ) $$
Comment: Thanks for the plot ! But it does not show the values you give in your answer.
Comment: No, it is not. The following Mathematica code gives significantly better bound: Sqrt[(x - y)^2 + (Sin[y] + 2 - Sin[x])^2] /. {x -> 0.478, y -> -0.478}.
Comment: @Leon Aragones Code awaited..
Comment: Well, distance between these points is greater than $1.06178-(-1.06178) > 2$, so that's not the answer I am looking for.
Comment: Errors corrected, hope all OK now. Main point is antisymmetry point(0,1) based calculation..


Finding Cumulative Sum In R Using Conditions

Question: I need to create a new variable with the sum of the past three years' amounts for each ID.
If there are not three years' worth of data, there should be an 'NA'.
As an example:
ID YEAR   AMOUNT
1 2010      5
1 2011      2
1 2012      4
1 2013      1
1 2014      3
2 2013      4
2 2014      6
2 2015      9
3 2012      4
3 2013      7
3 2014      2
3 2015      3

Here's what the result should be:
ID YEAR AMOUNT THREE_YR
1 2010      5       NA
1 2011      2       NA
1 2012      4       11
1 2013      1        7
1 2014      3        8
2 2013      4       NA
2 2014      6       NA
2 2015      9       19
3 2012      4       NA
3 2013      7       NA
3 2014      2       13
3 2015      3       12

How would I do this? Thanks!
Comment: See `zoo::rollsum`.
Answer: We can use functions from dplyr and zoo. dt2 is the final output.
# Create example data frame
dt <- read.table(text = "ID YEAR   AMOUNT
1 2010      5
                 1 2011      2
                 1 2012      4
                 1 2013      1
                 1 2014      3
                 2 2013      4
                 2 2014      6
                 2 2015      9
                 3 2012      4
                 3 2013      7
                 3 2014      2
                 3 2015      3",
                 header = TRUE, stringsAsFactors = FALSE)

# Load packages
library(dplyr)
library(zoo)

# Process the data
dt2 <- dt %>%
  group_by(ID) %>%
  mutate(THREE_YR = rollsum(AMOUNT, k = 3, fill = NA, align = "right"))

Update: ID groups with less than 3 records.
The OP asked what to do if there are IDs with only one or two rows. Honestly, I did not find a good way to solve this. The only thing I can think of is dividing the original data frame to two groups, apply the rollsum to the group with all records larger than or equal to three. After that, combine all groups.
# Create example data frame
dt <- read.table(text = "ID YEAR   AMOUNT
                 1 2010      5
                 1 2011      2
                 1 2012      4
                 1 2013      1
                 1 2014      3
                 2 2013      4
                 3 2012      4
                 3 2013      7
                 3 2014      2
                 3 2015      3",
                 header = TRUE, stringsAsFactors = FALSE)

# Load packages
library(dplyr)
library(zoo)

# Process the data
dt2 <- dt %>%
  group_by(ID) %>%
  filter(n() >= 3) %>%
  mutate(THREE_YR = rollsum(AMOUNT, k = 3, fill = NA, align = "right")) %>%
  bind_rows(dt %>% group_by(ID) %>% filter(n() < 3)) %>%
  arrange(ID, YEAR)

Comment: Thanks! I am getting an error: "Error in mutate_impl(.data, dots) : Evaluation error: k <= n is not TRUE." Some of the IDs only have one row (not 3 or more)... Any way to correct this?
Comment: Are you talking about the example dataset or your real dataset? It is likely that for some ID groups you only got one or two records. `rollsum` will fail for those IDs.
Comment: Correct. In my real dataset there are some ID groups with only one or two records. Any idea what would work in such a case?
Comment: Try to change the `mutate` call to this: `mutate(THREE_YR = ifelse(n() >= 3, rollsum(AMOUNT, k = 3, fill = NA, align = "right"), NA))`
Comment: This mutate yields NA straight down the THREE_YR column... [In the dataset I sent, imagine there was only one row for ID 2.] Thanks again!
Answer: With the data.table:
library(data.table)
setDT(dt)
setorder(dt,YEAR)
dt[,.(YEAR,AMOUNT,THREE_YR=AMOUNT+shift(AMOUNT,1)+shift(AMOUNT,2)),by=.(ID)]
#ID YEAR AMOUNT THREE_YR
# 1:  1 2010      5       NA
# 2:  1 2011      2       NA
# 3:  1 2012      4       11
# 4:  1 2013      1        7
# 5:  1 2014      3        8
# 6:  3 2012      4       NA
# 7:  3 2013      7       NA
# 8:  3 2014      2       13
# 9:  3 2015      3       12
#10:  2 2013      4       NA
#11:  2 2014      6       NA
#12:  2 2015      9       19

Answer: Using zoo::rollapplyr() and aggregate()
This will return NA if there are less than three members in a group.
x <- structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L,
  3L, 3L), YEAR = c(2010L, 2011L, 2012L, 2013L, 2014L, 2013L, 2014L,
  2015L, 2012L, 2013L, 2014L, 2015L), AMOUNT = c(5L, 2L, 4L, 1L,
  3L, 4L, 6L, 9L, 4L, 7L, 2L, 3L)), .Names = c("ID", "YEAR", "AMOUNT"
  ), class = "data.frame", row.names = c(NA, -12L))

library(zoo)

rsum <- aggregate(AMOUNT ~ ID, data=x,
  FUN=function(x) rollapplyr(x, 3, fill=NA, partial=TRUE,
  FUN=function(y) if (length(y) >= 3) sum(y) else NA))

x$rsum <- do.call(c, rsum$AMOUNT)
x
#    ID YEAR AMOUNT rsum
# 1   1 2010      5   NA
# 2   1 2011      2   NA
# 3   1 2012      4   11
# 4   1 2013      1    7
# 5   1 2014      3    8
# 6   2 2013      4   NA
# 7   2 2014      6   NA
# 8   2 2015      9   19
# 9   3 2012      4   NA
# 10  3 2013      7   NA
# 11  3 2014      2   13
# 12  3 2015      3   12

# remove one of the 2s
x <- x[-6, ]

rsum <- aggregate(AMOUNT ~ ID, data=x,
  FUN=function(x) rollapplyr(x, 3, fill=NA, partial=TRUE,
  FUN=function(y) if (length(y) >= 3) sum(y) else NA))

x$rsum <- do.call(c, rsum$AMOUNT)
x
#    ID YEAR AMOUNT rsum
# 1   1 2010      5   NA
# 2   1 2011      2   NA
# 3   1 2012      4   11
# 4   1 2013      1    7
# 5   1 2014      3    8
# 7   2 2014      6   NA
# 8   2 2015      9   NA
# 9   3 2012      4   NA
# 10  3 2013      7   NA
# 11  3 2014      2   13
# 12  3 2015      3   12


How to render language select block in page template?

Question: Background information:
I used the following script to list all the twig blocks: drush ev "print_r(array_keys(\Drupal::service('plugin.manager.block')->getDefinitions()))" and when I tried the following twig : {{ drupal_entity('block', '') }} and it is not rendering the twig block–
I developed a Twig page in Drupal 8 to allow my website visitors the ability to select the language they want. I downloaded all the multilingual contrib modules.
I am facing two issues:

How to render a block in the middle of my twig page to display the language drop-down menu? (I already have a block that displays a drop-down menu language from a contrib module).
The CSS background image I had setup is covering one of the Twig field I wanted to test. How can I tweak the CSS in order to display the twig block?
Comment: [Twig Tweak](https://www.drupal.org/project/twig_tweak) lets you render blocks in Twig pretty easily. CSS is off-topic. You can't render Drupal blocks with CSS.
Comment: I already have twig tweak module installed and enabled. I was just listing two related issues I am facing right now. I am aware that blocks cannot be rendered by Twig. The image I added as a background is just covering the render twig field.
Comment: I used the following script to list all the twig blocks: drush ev "print_r(array_keys(\Drupal::service('plugin.manager.block')->getDefinitions()));" but I tried the following and it is not rendering the twig block: {{ drupal_entity('block', '') }}
Comment: And why is this info missing from your question? Please update your question and add everything you tried yourself so far.
Answer: Just place this in the your custom twig page where you want your language switcher links. We are using twig tweak module here. So intall this module before adding this line:
{ # Language switcher # }
{{ drupal_block('language_block:language_interface', wrapper=false) }}

Answer: drupal_entity() is for rendering entities. For rendering block plugins use drupal_block() instead.
The difference is explained very well in the following guide.
https://www.drupal.org/docs/8/modules/twig-tweak/rendering-blocks-with-twig-tweak
Comment: thank you for your help.


Which event should we subscribe to if we want code to be triggered when a new user registers?

Question: I noticed that account.set is the event invoked for a user account.
I want to create an event subscriber which adds a callback invoked when a new user registers on the site. I am not sure whether account.set is the correct event.
Are there other better events for this?
Comment: I'll try to put a proper answer in later when I have time (if no one else has already done it), but have a read through https://www.drupal.org/project/drupal/issues/2551893 for further info. Bottom line is entity CRUD still uses hooks, unless you use one of the contrib modules that add events for them
Answer: AccountEvents::SET_USER isn't the event for user registration. Per the docs:

This event allows modules to perform an action whenever the current user is
  set. The event listener receives an \Drupal\Core\Session\AccountSetEvent
  instance.

The event is fired when Drupal initializes the user object for the current request, not when new users are created.
For responding to new user creation, you can still use hook_user_insert().
Comment: Aww. I was hoping to write an event subscriber and use Drupal 8's new methods to get the job done. What a pity ;-)
Answer:
Aww. I was hoping to write an event subscriber and use Drupal 8's new
  methods to get the job done. What a pity ;-)

You could using the Hook Event Dispatcher module, see README.md file on how to use.

This module dispatches events for several Drupal core hooks. This
  allows you to use the D8 Event Subscriber system, instead of the
  outdated hook system, to react on certain events.


problem with threading JAVA

Question: I'm trying to make so that when I press a button the program starts a method in a new thread.
The problem is that when I press the button the program freezes until the method is done running like i didn't use a thread at all. Does anyone know how to solve this problem?
Thanks Morgan.
public Listeners()
{
  Calendar.ButtonAddReminder.addActionListener(new ButtonAddListener());
}

private class ButtonAddListener implements ActionListener
{
  public void actionPerformed(ActionEvent e) {
      new Thread(Calendar.reminder.Reminderchecker(Calendar.reminder.addReminder(date, str))) .start();
  }
}

Answer: From that, it looks like something in Calendar.reminder.addReminder() or Calendar.reminder.Reminderchecker() is taking some time and locking up the UI since that's what's happening in the EDT.
Edit: Oh, I see. You're not doing what you think you're doing. You're executing Reminderchecker in the current thread. The Runnable returned by that method is what's getting executed in the new thread. To run Reminderchecker in a thread, do something like:
new Thread(new Runnable() {
    public void run() {
        Calendar.reminder.Reminderchecker(...);
    }
}).start();

Better: Don't spawn your own random threads like that. Use an organized concurrency strategy such as provided by an ExecutorService. The Executors class lets you easily create several that cover common uses.
Still better: Check out the SwingWorker and it API docs.
Comment: Yes, Reminderchecker is taking time to run, thats why I want it to run in a new thread without locking up the system. Is it possible to do this?
Answer: You need to make sure that all this happens in the new thread:
Calendar.reminder.Reminderchecker(Calendar.reminder.addReminder(date, str ))

At the moment
Calendar.reminder.addReminder(date, str )

and
Calendar.reminder.Reminderchecker()

are called on the Event Dispatching Thread before the new Thread is constructed and started.
The simplest way to correct this is to create a new Runnable object that carries out all of these steps, and then pass that to the new thread. I guess the returned object from Reminderchecker() is itself a Runnable, in which case you need something like this:
Runnable task = new Runnable() {
    public void run() {
        Runnable r = Calendar.reminder.Reminderchecker(Calendar.reminder.addReminder(date, str ));
        r.run();
    };
new Thread(task).start();

Answer: Assuming that your Calendar class implements Runnable or extends Thread you should not call Calendar.reminder.Reminderchecker(Calendar.reminder.addReminder(date, str )) before starting the new Thread as this calls the run() method of the new thread.
Instead do something like that:
public class Calendar implements Runnable {
    public void run() {
        this.reminder.Reminderchecker(Calendar.reminder.addReminder(date, str ));
    }
}

problem with threading JAVA


Lemma regarding Jordan Form

Question: Here is the lemma:
If $N \in L(V )$ is nilpotent, then there exist vectors
$v_1,\dots,v_n\in V$ and nonnegative integers $m_1,\dots,m_n$ such that
(a) $(N^{m_1}(v_1),\ldots,N(v_1),v1; \ldots ;N^{m_n}(v_n),\ldots N(v_n),v_n)$ is a basis of $V$ and
(b) $N^{m_1+1}(v_1)=\ldots =N^{m_n+1}(v_n)=0$
(The proof is by induction on $\dim(V)$. I need to show the base case($\dim(V=1$)). All the proofs I have seen say this is trivial.  However, I need to show it precisely, and in detail)
Help?
Comment: You need to learn latex.  I tried to fix it for you but your (a) is confusing you have "N^m1(v1)" and "N(v1)" and "v1" what exactly do you mean?
Comment: For the case $\dim V=1$?
Comment: Yes, for the case dimV=1.  Also, in response to Gregory, when I write v1, I mean v with subscript 1.
Answer: Here is a proof of the base case: Assume that $\dim V = 1$. This implies that every linear operator on $V$ is multiplication by a scalar. Thus the only nilpotent operator on $V$ is the $0$ operator. With that information, we have $N = 0$ and we can take $n = 1$, $v_1$ to be any nonzero vector in $V$, and $m_1 = 0$.
Comment: Thanks! I am thrilled to have your help. I have been studying your textbook this semester!

Lemma regarding Jordan Form


How to Unit Test Entity Reference Field Value

Question: I have been tasked with writing a Unit Test for a method where I pass in a Node object, modify an Entity Reference field value, and then return a Node object.
Since this is a Unit test, I am unsure as to how to write an assertion.
Note: just included relevant code.
class ClassIAmTesting {
    public function populateSymbols(Node $node) {

      $node->field_symbols->appendItem(['target_id' => $symbol_id]);
      return $node;
    }
}

I have created a mock for the Entity Reference Field:
$entityReferenceMock = $this->getMockBuilder(EntityReferenceFieldItemList::class)
      ->disableOriginalConstructor()
      ->setMethods(['appendItem'])
      ->getMock();

I have also created a mock of the Node Object
$nodeMock = $this->getMockBuilder(Node::class)
      ->disableOriginalConstructor()
      ->getMock();

$nodeMock->expects($this->any)
      ->method('__get')
      ->with('field_symbols_in_this_story')
      ->willReturn($entityReferenceMock);

The method returns a Node object but how can I assert that the Entity Reference Field Value has changed?
Edit: The class with more details:
class ClassIAmTesting {
  public function populateSymbols(Node $node) {

    $body = $node->field_body->value;

    $dom = Html::load($body);
    $xpath = new \DOMXPath($dom);

    foreach ($xpath->query('//span[@class="tooltip"]') as $xpathNode) {

      $symbol_id = $xpathNode->getAttribute('data-symbol');

      $node->field_symbols->appendItem(['target_id' => $symbol_id]);
    }

    return $node;
  }
}

Comment: EntityReferenceFieldItemList already has tests to assert its values have changed. What's the value in this test? The method is essentially pass in node, get node back. So if you trust core tests, then you can either spy on the appendItem method (using prophecy instead of phpunit mock objects) and the test fails if it's not called correctly. Not sure if questions about phpunit or prophecy are on-topic...
Comment: Hi @mradcliffe thanks for the response. I edited the end of my question to include more of the example class. There is a foreach loop. It looks for data-symbol attributes from the body field and extracts the IDs. Each ID that is extracted is appended to the Entity Reference Field.
Answer: This is a good example of a test that would probably be better suited as a kernel test rather than a unit test since it's dealing with the Field API which can get tricky to mock, and is probably better to test with the real thing.
To test this as a kernel test you need to ensure the following:

Either create your field field_symbols directly in the test's setUp method or place the field config and storage YAML files in a module's config/install directory, and enable that module for the test.

You'll need to also enable the node module, and any other module's that your code depends on

Then, in your test you can execute the custom code and ensure the expected values are set:
public function testFieldSymbols() {
  $node = $this->createNode();

   // Do this, or retrieve the service if your class is a service.
   $fixture = new ClassIAmTesting();

   $fixture->populateSymbols($node);

   $this->assertEquals('expected field value', $node->field_symbols->target_id);


I need tips for increasing concentration for math study

Question: Any tips for increasing concentration? I find it difficult to concentrate for looong periods at a time, after having taken a long break from mathematics. Before I could sit for hours and do calculations and reading. Now I just put down the book or turn to a distraction.
Any biological, practical or philosophical tips would be much appreciated! I need to increase my concentration!
Comment: @DonAntonio I think coffee makes me fidget and get stressed, not pleasant!
Comment: There are some tips but several are illegal in some parts of the world...coffee may help during those looooooong nights of intensive study, though.
Comment: I find regular exercise helps to increase my concentration and reduce the temptation of distractions.
Comment: Well @FrederickG : fidget and stressed is better than asleep one day before final exam...
Answer: Avoid computers, phones, and televisions. If you are studying independently, make yourself assignments for the chapter you're working on, and don't read ahead till you've finished.
Comment: So basically a library or cellar?
Comment: Or outdoors, perhaps.
Comment: Computers can be turned off.  They can also be given to friends for safekeeping.


Confusion about joint probability and conditional probability

Question: This might be trivial, but I just want to make sure I don't struggle on the basics.
I am confused about this:
"Draw one card from a standard deck of playing cards. Let's examine the
independence of 3 events 'the card is an ace', 'the card is a heart' and 'the card is red'.
Define the events as A = 'ace', H = 'hearts', R = 'red'." (Source)
With $P(A) = \frac{1}{13}$, $P(H) = \frac{1}4$ and $P(R) = \frac{1}2$
I get $\frac{1}4$ for $P(H|R)$. So this basically says that $P(H)$ and $P(R)$ are independent, since H and P are independent iff $P(H|R) = P(H)$.
I know that that's not correct from the source, so now I am wondering how I can then calculate the conditional probability for dependent events and how I would know beforehand. Why is $P(H|R)$ actually $\frac{1}2$?
I feel like I am missing one bit of the puzzle or overcomplicating things, so any help is appreciated!
Best regards,
Sam!
Comment: If the card is red it is equally likely to be Hearts or Diamonds (and can't be Spades or Clubs).  More numerically, there are $26$ red cards, $13$ of which are Hearts.
Answer: $P(H|R)$ means you already know the card is red, so your total pool is $26$ red cards. from these $26$ red cards, you want to know the probability for selecting a heart, so there are $13$ heart cards, therefore, you have
$$P(H|R)=\frac{13}{26}=\frac{1}2$$
Comment: No, there is no such a law to guarantee you to do this contextual. It depends on case by case. @DerOeko
Comment: Thanks!!

So, when two events are dependent, the way to figure out the conditional probability is contextual? That is where my confusion is coming from, I think.


Slider via uploaded Image on each node + Fallback

Question: I want to create a slider block shown on every page filled with the images uploaded to the active Basic Page, Article, ...
On these pages just the Uploaded Images of the active page should be shown and if there are no images uploaded (e.g. on View pages, Taxonomy pages, ...)
a fallback Slider should be shown.
I've added a Imagefield called Sliderimage to the Basic Page (and the others), created some pages and uploaded individual images to them.
Then I've created a view block with the following settings:
Format: Slideshow (default values from views_slideshow)
Show: Fields
Field: Content:Sliderimage - Rendered File, Original, Display all values in the same row (no seperator)
Filter Criteria: Published
Contextual filter: Content: Nid
But somehow the node id seems not to be delivered to the filters (or I misunderstood it) because
at the contextual filter I choose "Display all results for the specified field" at WHEN THE FILTER VALUE IS NOT AVAILABLE I get all at the different
pages and with "Hide view" I get nothing would would be right.
If the above issue is solved I want to add  the fallback at "WHEN THE FILTER VALUE IS NOT AVAILABLE" as fixed value or php code.
Would that be the right way?
Comment: Forget about the fallback, that's what I already found out.
Comment: If I define a Fallback, I'll get the fallback on every page even the ones with uploaded images!
Comment: Didn't know that blocks are not able to get the Node-Ids by default, sorry
Comment: Please don't add 'solved' to the question title; if you've solved the issue, please answer your own question with the details. Thanks :)
Comment: Ok, sorry. I wanted to answer my questions but the system told me that I'm not able because of the 8hours rule.
Comment: Ah yes, that little treat I forgot about that. If you have a chance in 5 or so hours it'd be great to add the answer in :)
Comment: Yeah, will to that of course if I don't forget
Answer: Solved because I've found out that block views don't retrieve node-ids by default.
You have to set at "When the filter value is NOT available":
- Provide default value: with type "Content ID from URL"
Now the block view recognizes the ID as well.


Constructing array of term reference labels in php template?

Question: I'm currently trying to set up a simple LMS and have already defined a content type course that contains a term reference field accesstags, which I would like to use for defining view permissions. I.e. the field accesstags will contain multiple terms that will be linked to roles that should have access to the node in question.
To make a long story short: I have created a custom module that contains the function hook_entity_view_mode_alter and I would like to check, whether the term reference field accesstags contains the term "subscription":
function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  ...
  if (in_array('subscription', ?????)) {
    ... allow access ...
  }
  ...
}

However, I'm not sure what to put at the spot that I marked with "?????". I know that I can construct the array of referenced terms by using $entity->get('field_accesstags')->referencedEntities()... but this array then contains the whole structure, whereas I only need the array of labels.
Is there an easy way for getting this array? Maybe even a built-in function?
Any help would be much appreciated.
Comment: Yes, this array of terms is a good starting point. You'll find the label in `$term->getName()` when iterating the array, for example with `array_filter()`.
Comment: Thanks, that was exactly the help that I needed. I ended up using `array_map()` in combination with a small helper function that called `getName()` on the elements of the array built with `referencedEntities()`. Much appreciated. (Would you like to post your comment as an answer so that I can accept it?)
Comment: You can put the final code in an answer.
Answer: Following @4k4's suggestion to post the final code as an answer myself... here's the code that I'm now using and that seems to work well...
First of all, I defined a simple helper function:
function getTermName($term) {
  return($term->getName());
}

This allowed me to extend my code (see my original question above):
function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  ...
  $accesstags = array_map("getTermName", $entity->get('field_accesstags')->referencedEntities());
  if (in_array('subscription', $accesstags)) {
    ... allow access ...
  }
  ...
}

I'm still wondering, if there is a simpler way (without having to iterate over the array of terms), but for now the solution works well. Thanks again for your help, @4k4.


Problemas ao serializar objeto para XML

Question: Após serializar para XML um objeto algumas propriedades desaparecem.
Estes objetos foram gerados automaticamente com o add references services
e não possuem o [System.Xml.Serialization.XmlIgnoreAttribute()]
porém não estão aparecendo no XML apos o objeto ser serializado.
Alguem ja passou por esse problema? alguma ideia de como resolver?
O Fonte que estou usando para este teste está no git https://github.com/ntfrigo/WinBetha2
Answer: Descobri como resolver o problema, então vou deixar documentado para outros que possam precisar.
Todas as propriedades que possuam o "Specified" devem ser definidas com true para que o mesmo possa ser serializado e constar no XML, caso contrario serão removidos.
As propriedades que não contem o "Specified" sempre irão constar no XML.

Problemas ao serializar objeto para XML


Nintendo DS and Neural Networks

Question: i was wondering if DS`s hardware is capable of running a game that utilizes a feedforward neural network using genetic algorithms.
I know that this has to do with the implementation of the homebrew game as well as the nn and the ga, but i am curious...
(i know nothing about how the DS`s ARMs are used, etc, etc, etc)
Thanks in advance :-)
Answer: Yes, devices like the Nintendo DS are plenty powerful enough for this sort of thing.  I haven't worked with the Nintendo DS specifically, but I have written a neural network character recognition app for a Windows Mobile smartphone, which is comparable in processing power.
As you mention, it all depends upon how you write it.  You could just as easily write something that doesn't work on the Nintendo DS.
Comment: @n00ki3: "bwhahaha" is traditionally used when plotting to take over the world. I think you mean "LOL".
Comment: For that matter, you could just as easily write something that doesn't run on a 16-core 128GB monster server either.

Nintendo DS and Neural Networks


Redirect writes to a file to a stream C#

Question: I wanted to ask if it is possible to redirect writes to a specific file, to a memory stream in my application so I can immediately read it.
If it is possible please explain how to do so.
Thanks.
Comment: Is your application writing to the file or another application that is not under your control?
Comment: I think maybe your notion of a stream is incorrect, it sounds what you really mean is.. can I redirect writes to a specific file, to a memory stream in my application.
Comment: @PVitt Yes, it's another application which i don't have control over.
@meandmycode Yes, that's what I meant
Answer: Make sure your application works with Stream, and then you can use the MemoryStream concrete implementation to accomplish streaming without a file.
Comment: Yes, but be aware that a MemStram only has 1 Position - you cannot easily interleave read and write .
Answer: What you need is a stream which writes to a file as well as to another stream which you are watching - a stream splitter, commonly known in the Unix world as tee.
For .NET you can use this implementation of a stream splitter. Pass it a FileStream (so that the file gets written to) and for the second stream, pass a Stream implementation which does whatever you want when the stream is written to (for example, a subclass of MemoryStream with an overridden Write method).
Update: I see from your comment that my answer isn't what you need - I didn't realise from your original question that you had no control over the app writing to file.
In order to get this kind of control, for finest control you will need to go to a low-level driver which intercepts system calls - much like FileMon does. For slightly less control, you can use System.IO.FileSystemWatcher.
Comment: Maybe I didn't understand what the echostream is for, but my scenario is that I have 2 application - one of them is an app I can't get control of, and it is writing to a log file, the other one is is my C# application. Now what I want is somehow redirect the writes to the log into a a stream in my C#. Also, the program writes ALOT of data to the log, and that's why I need it to be fast.
Answer: I don't know how to do this in the way you say but you could use a FileWatcher to hook file. If its written to you'll be notified and you can read it.
Comment: I don't think this would be fast enough.


Como mostrar ID do Firebase do usuário conectado na tela?

Question: Preciso pegar o getUid do usuário conectado e setar o id em um editText. Deixei abaixo só para mostrar o que quero fazer, porque dessa forma não funciona. Como posso chamar um getUid conectado em qualquer parte do código e setar ele como EditText?
<code>private EditText userId;
private FirebaseAuth.AuthStateListener minhaAuthListener;

userId = (EditText)findViewById(R.id.userId);

 minhaAuthListener = new FirebaseAuth.AuthStateListener(){
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            Log.d("meuLog", "Usuário conectado: " + user.getUid());
            userId.setText(user.getUid());
        }
    };
</code>
Answer: Consegui resolver da seguinte forma.
<code>    FirebaseUser user1 = FirebaseAuth.getInstance().getCurrentUser();
    if (user1 != null) {
        for (UserInfo profile : user1.getProviderData()) {
            // Id of the provider (ex: google.com)
            String providerId = profile.getProviderId();
            // UID specific to the provider
            String uid = user1.getUid();
            userId.setText(uid);
        }
    }
</code>


Why can't the logstash syslog_pri filter see the priority in syslog messages

Question: I'm running LS 2.0.0, and I've noticed an issue where the syslog_pri filter doesn't detect the priority at the start of my syslogs. My filter config is as follows:
filter {
  if [type] == "relp" {
    syslog_pri { }
    grok {
      match => { "message" => "%{SYSLOG5424PRI}(?:%{POSINT} |-)+(?:%{TIMESTAMP_ISO8601:syslog5424_ts}|-) +(?:%{HOSTNAME:syslog5424_host}|-) +(-|%{SYSLOG5424PRINTASCII:syslog5424_app}) +%{GREEDYDATA:syslog5424_msg}" }
      add_field => [ "received_at", "%{@timestamp}" ]
      add_field => [ "received_from", "%{syslog5424_host}" ]
      tag_on_failure => "gpf_relp"
    }
    date {
      match => [ "syslog5424_ts", "ISO8601" ]
    }
  }
}

This should be able to pull the PRI from the following logs, but it fails, and reverts to the default (13) priority for all messages:
{
  "_index": "logstash-2015.11.10",
  "_type": "relp",
  "_id": "AVDxXHq4lzuNTbjDHPbE",
  "_score": null,
  "_source": {
    "message": "<86>1 2015-11-10T12:26:20.429088+00:00 integration-gw3 sshd 2587 - -  pam_unix(sshd:session): session closed for user sftpuser\n",
    "@version": "1",
    "@timestamp": "2015-11-10T12:26:20.429Z",
    "type": "relp",
    "host": "10.10.11.23:39532",
    "syslog_severity_code": 5,
    "syslog_facility_code": 1,
    "syslog_facility": "user-level",
    "syslog_severity": "notice",
    "syslog5424_pri": "86",
    "syslog5424_ts": "2015-11-10T12:26:20.429088+00:00",
    "syslog5424_host": "integration-gw3",
    "syslog5424_app": "sshd",
    "syslog5424_msg": "2587 - -  pam_unix(sshd:session): session closed for user sftpuser\n",
    "received_at": "2015-11-10T12:26:20.430Z",
    "received_from": "integration-gw3"
  },
  "fields": {
    "@timestamp": [
      1447158380429
    ]
  },
  "sort": [
    1447158380429
  ]
}

As you can see the PRI is set to 86, and my grok filter picks this up, but the syslog_pri doesn't change these values from default:
    "syslog_facility": "user-level",
    "syslog_severity": "notice",

Can anyone suggest what I am doing wrong?
Comment: What kind of input are you using?
Comment: I'm using the relp input, but as far as I understand it, this should have no effect on how the filter behaves. If I'm wrong please let me know
Answer: In looking at the docs for the syslog_pri filter, it seems it's looking for the priority in a field called syslog_pri, as opposed to the raw message.
Given that you're running that filter before groking the line, it doesn't have anything in that field and as such is returning priority 13 (user.notice), as outlined in the docs above.
For it to work the way you want, you'll need to move the syslog_pri filter after the grok and change it to this:
syslog_pri {
  syslog_pri_field_name => "syslog5424_pri"
}

Comment: Just figured this out myself, couldn't see this in the docs, d'oh! Thanks


Access Dask scheduler from an external docker container

Question: I have started a dask-scheduler at host A. Host A has docker engine installed. So, host A has multiple network interfaces:

192.168.10.250 (default IP for host A)
172.17.0.1 (host A IP address in bridge network (i.e., docker0))

I tested a simple client, from within host A, to both IP addresses and works well
Now, I started a Docker container on the same host A without specifying any networks, so the docker container connects to the default bridge network and receives IP address 172.17.0.2. Within the docker container, I try to start a client that connects to the dask scheduler on the host A as follows:
client=Client('172.17.0.1:8786')
but each time I receive the following error:
IOError: Timed out trying to connect to 'tcp://172.17.0.1:8786' after 10 s: connect() didn't finish in time
I tried to change the network drive for the container to "host" instead of "bridge" but then I receive the following error:
distributed.comm.core.CommClosedError: in : Stream is closed
please help
Regards
Comment: Can you share the actual `docker run` command you used?
Comment: docker run -it --rm --name test [--net host]
Answer: Thanks guys. Problem solved.
I realized the problem was that python 2.7 was used inside docker image. When I used python 3.6, it worked (even without the --net host)
Regards


Netbeans, JPA Entity Beans in seperate projects. Unknown entity bean class

Question: I am working in Netbeans and have my entity beans and web services in separate projects.  I include the entity beans in the web services project however the ApplicaitonConfig.java file keeps getting over written and removing the entries I make for the entity beans in the associated jar file.
My question is:  is it required to have both the EntityBeans and the WebServices share the same project/jar file?  If not what is the appropriate way to include the entity beans which are in the jar file?

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="jdbc/emrPool" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/emrPool</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="eclipselink.ddl-generation" value="none"/>
      <property name="eclipselink.cache.shared.default" value="false"/>
    </properties>
  </persistence-unit>
</persistence>

Based on Melc's input i verified that that the transaction type is set to JTA and the jta-data-source is set to the value for the Glassfish JDBC Resource.  Unfortunately the problem still persists.  I have opened the WAR file and validated that the EntityBean.jar file is the latest version and is located in the WEB-INF/lib directory of the War file.  I think it is tied to the fact that the entities are not being "registered" with the entity manager.  However i do not know why they are not being registered.
Answer: No it is not necessary to be within the same war. You can have a project (I think it is called class library project) with your jpa entities and add that project from the libraries of your web project that contains the web services. The ApplicationConfig is related to the web services and it does not affect the entities. I advise you to check the functionality of the jpa project from a simple servlet of a web project. If it works then it will also work with your jax-rs code.
However take care to properly modify the persistence.xml to not use resource-local,which is the default generation by netbeans for non web projects, but jta along with the proper server data source.
EDIT
Make another test by editing persistence.xml from netbeans and uncheck "Include All Entity Classes in .." , then choose the "Add Class..." option and select all entity classes. Along the entity classes you should also find the one you try to access.
Also it is the contents of the web project's build folder that gf is working on not the war,when running from netbeans. Unless you go to gf's admin console, deploy application and choose your war file. So you better check the contents of that folder as well or simply delete it and let nb recreate it.
The "unknown entity bean class" pops up pretty often with netbeans and glassfish, for example you may also get it while the system is working after redeployment. In that case it gets fixed by restarting the server. Unfortunately it is one of those errors that don't always really mean what they say.
Comment: Verified the points you recommended however those were already in place.  Thanks for your input though.  I do not know why the entities are not being registered with the Entity Manager.
Comment: @Stu updated the answer based on you persistence.xml and the fact you use gf.
Answer: It worked for me after I added this in my persistence.xml:
<jar-file>../lib/my-jpa-models.jar</jar-file>


C for loop, How do I continuously prompt the user?

Question: I am learning about loops such as for and while loops, so I decided to put myself to the test and write a program which you can see the code for below.  The program gives the user a range of options to enter an option, but the problem I have is that i want to be able to continuously ask the user to "Enter a command" after an operation has completed.
For example, if I entered 1, the necessary code would be executed but then the whole program just ends.  How can I enhance this program so it continuously asks the user to enter new commands until the user forcibly exits by entering 0?
#include <stdio.h>

int main()
{
    int n;
    int credit = 0;
    int YN;

    printf("Welcome to Cash booking software Version 2.145\n");
    printf("--------------------------------------------------------\n");

    printf("Use the following options:\n");
    printf("0 -- Exit\n");
    printf("1 -- Display Credit\n");
    printf("2 -- Change Credit\n");
    printf("3 -- Remove Credit\n");

    printf("\n");

    for ( ; ; )
    {
        printf("Enter a command: ");
        scanf("%d", &n);

        if (n == 0)
        {
            return 0;
        }
        else if (n == 1)
        {
            printf("Your credit is £%d", credit);
        }
        else if (n == 2)
        {
            printf("Enter a new credit value: \n");
            scanf("%d", &credit);
            printf("Your new credit value is %d", credit);
        }
        else if (n == 3)
        {
            printf("Are you sure you want to remove your Credit value? (Y=1/N=2)");
            scanf("%d", &YN);
            if (YN == 1)
            {
                credit = 0;
            }
            else
                ;
        }

        return 0;
    }
}

Comment: I think you are at a good point, the error probably is the `return 0;` that should be just after the `}` outside the for loop (that is looping indefinitely like you want).
So put the return just before the last `}` and should be ok.
Comment: When the code is formatted neatly, the error that the final `return 0;` is inside the `for` loop and not after it becomes obvious.  Move it outside the loop and your loop will continue.
Comment: Since you are still getting familiar with the language, I **strongly** suggest to get used to some of the most common tools used with it: for this case it is the debugger. If you are running your programs in a terminal, you can use gdb. If you are using an IDE such as VS Code, they usually have a debugger integrated. With a debugger you will be able to see step by step what the program is doing.
Comment: Is good to use a debugger or format the code properly, but not so easy as a beginner, so we have to let him make some mistakes :) and loose some hours on it. Like everyone of us did! :)
Comment: Thank you all for the help!!!!!!
Comment: Qasim, what should happen if user enters "abc" instead of a number?
Answer: As other users explained return 0; inside of the loop is what is causing the problem and moving it out would solve it, But since you're learning about loops I think this is a great example to teach you something.
Usually you should only use a for loop when you have some parameter that defines de number of times the loop will be executed. The fact that you just used for( ; ; ) is a huge red flag for ther is a betther way to do this.
For example the proper way to write an infinite loop in c is while(1){//code in the loop}. So you could change your for loop with this and it will work fine (relocating return 0; in the correct location).
But since in this code you dont really want an infinite loop (usually they're a bad idea), but you want the loop to run until is pressed 0, the best solution is to use a do{} while(); loop where inside of do you check if either 1, 2 or 3 is pressed and perform their functionality, and then in the while condition you check if 0 has been pressed, and only in that case the program exits.
This is how the code would look like:
do{
  printf("Enter a command: ");
  scanf("%d", &n);
  if (n == 1){
    printf("Your credit is £%d\n", credit); // \n added
  }
  else if (n == 2){
    printf("Enter a new credit value: \n");
    scanf("%d", &credit);
    printf("Your new credit value is %d\n", credit); // \n added
  }
  else if (n == 3){
    printf("Are you sure you want to remove your Credit value? (Y=1/N=2):");
    scanf("%d", &YN);
    if (YN == 1){
      credit = 0;
    }
  }
} while(n != 0);
return 0;

Also note that I added \n in some printf() commands for better visualization.
Comment: But also I dont recomend you to think of for loops as a concise form of while since it's use is completely different most of the time. In a for loop you have an index that is increased (or decreased) at every iteration until some value reaches a defined value. A while loop on the other hand is way more flexible, you dont have to modify the index at every iteration if not needed and you can easily use multiple conditions in the loop.
Comment: Thanks for this amazing answer but I have a question, when you said that the while loop is a better option in this case, wouldn't that be incorrect because a while loop and for loop are exactly the same but a for loop is structured differently on one line.
Comment: Well yes, what I meant is that while(1) is more appropriate because in an empty for loop youre not using the characteristics that make a for loop different from a while since ther'is no counter to be updated at every iteration, but yes, from a performance level they do the same thing.
Answer: use continue statement at the end of each condition , and you can use break statement instead of return 0, so the code will be :
    if (n == 0)
    {
        break;
    }
    else if (n == 1)
    {
        printf("Your credit is £%d ", credit);

        continue;
    }
    else if (n == 2)
    {
        printf("Enter a new credit value: \n");
        scanf("%d", &credit);
        printf("Your new credit value is %d ", credit);

        continue;
    }
    else if (n == 3)
    {
        printf("Are you sure you want to remove your Credit value? (Y=1/N=2) : ");
        scanf("%d", &YN);
        if (YN == 1)
        {
            credit = 0;
            continue;
        }
        else {
            continue;
        }

Comment: Moving 'return 0;' outside of the for loop would have been a way easyer solution.


ODBC connection from 64-bit SQL Server to Informix data source

Question: I am trying to create a linked table in a 64-bit SQL Server to Informix, and the SQL server does not list Informix ODBC in the DSN list. I have downloaded the 64-bit Informix Client SDK, however, despite the fact that it states 64-bit Informix Client SDK, it only appears in the 32-bit ODBC DSN. I tried to create a linked table in a 32-bit SQL Server and I was then able to see Informix ODBC DDN.
I was just wondering that if there is an Informix Client SDK that would show in the 64-ODBC DSN, not the 32-bit?
Also is there a way of linking a 64-bit SQL Server to Informix please?
Thanks.
Answer: Create a DB Link in SQL Server to Informix
I used the following Software environment:

SQL Server 2012
Informix SDK 4.10 FC2
Informix 11.5

First Set some Properties for Ifxoledbc Driver:

Then Create Linked Server:

General Settings - Datasource is your DB and your Server Name

Security Settings - Add valid Informix Database Credentials

Server Options - Set RPC and RPC Out to True

I use the db link for calling a stored Procedure in Informix and writing the data to SQL Server.
Comment: **Chapeau** that's what I call a great answer !!
Comment: Well... Yes and no.  It does deliver a connection from SQL Server to Informix, but it uses an OLE DB Provider for Informix (`Ifxoledbc`), not an ODBC connection as was requested.  (SQL Server is an OLE DB client application, not an ODBC client application; and when you tell SQL Server to target an ODBC DSN, it invisibly uses the Microsoft OLE DB Provider for ODBC to bridge the protocol gap.)
Answer: I was able to set up a linked server without Ifxoledbc. Once my System DSN for the 64-bit ODBC driver was set up (and tested OK), I set up a linked server using the Microsoft OLE DB Provider for ODBC Drivers.
Linked Server: UCCX
Provider: Microsoft OLE DB Provider for ODBC Drivers
Product name: IBM Informix ODBC Driver (probably could be anything but I named it the same as the ODBC Driver and it worked).
Data Source: UCCX (the name of your System DSN).
On the security tab I mapped a local login to the same remote user/password as the one set up in the System DSN itself.
And another way to consume the System DSN is via OPENROWSET. This works even without setting up a linked server:
select *
from    openrowset('MSDASQL', 'DSN=UCCX', '
            select * from ContactCallDetail
            where   StartDateTime >= ''2017-03-10 00:00:00''
            and     StartDateTime < ''2017-04-10 00:00:00''
            limit 10'
        ) p

Answer: Did you use the 64 bit version of ODBCAD32.EXE to create the DSN?
There are two versions of the ODBC administrator.
This one is the 32 bit version:
C:\Windows\SysWOW64\odbcad32.exe

It can only see 32 bit drivers, and only 32 bit processes can see it's DSN's
This one is the 64 bit version:
C:\Windows\System32\odbcad32.exe

It can only see 64 bit drivers, and only 64 bit processes (i.e. SQL Server 64 bit) can see it's DSN's
Even better you could define a DNS-less connection which doesn't use a DSN, it uses the driver directly. Then you can avoid this confusing step altogether.
Comment: Yes 7 confusing steps are not much less confusing than 8 confusing steps.
Comment: Ha! I love the *Then you can avoid this confusing step altogether.* - The **whole** process is confusing, if you ask me!
Answer: I would have used the Comment feature, but I do not have enough "Reputation Points" to do so.
The answer of SGeis, above, is on the money.  It was hard for me to find such a clear, straightforward answer.  Snapshots of the dialog boxes help immensely.
Let me add to his answer the following:

The Data Source fill-in (YourDatabaseName@YourInformixServerName) could be something as simple as Fred@Barney, rather than what I tried, namely, email@example.com or firstname.lastname@example.com:32002 (the latter specifies a port/service number).
Once you create the linked server, if you go back into its General properties page, you will see that you cannot edit what you typed for Linked Server, Product Name (Why isn't this called "Provider Name," since Ifxoledbc is listed under Linked Servers/Providers in the Object Explorer tree?), Data Source, etc.  So, if your connection fails because you mistyped something, it is unclear how to fix it.

Here is what you may do:

Right-click the linked server.
Beneath "Test Connection," look for "Script Linked Server as."
Click the latter, and, then, each of the following:  "DROP And CREATE To"
and "New Query Editor Window."
In the script text that appears, type replacement info for those settings that were grayed-out and uneditable.
Press F5 to run the script and thereby apply your changes.  In doing so, the existing linked server is dropped, and a new one is created.
Open up your linked server's Security properties page and re-enter any connection password (even though asterisks -- suggesting that the password is filled and correct -- may appear in the corresponding entry). Also, examine the General properties page.  Make sure that your changes stuck.  Even though you ran the script and received no error, SQL Server will blank out fill-ins such as "Linked Server," "Product Name," and "Data Source" if, for example, you, as I did, had a brain aneurism and chose the wrong drop-down item for "Provider."
As noted above, click "Test Connection," to verify that your changes work.


Execute Shell-Command over python using subprocess

Question: when I execute a command (while true; do date; sleep 1; done) over a Python-Skript nothing is displyed and no logging.
import logging
import sys
import subprocess as SP

logger = logging.getLogger('logging')
logger.setLevel(logging.INFO)

if not logger.handlers:
    log_handler = logging.FileHandler('test_logging.log')
    formatter = logging.Formatter('%(asctime)s %(message)s')
    log_handler.setFormatter(formatter)
    logger.addHandler(log_handler)
    log_handler.setLevel(logging.INFO)

command = 'while true; do date; sleep 1; done'
p = SP.Popen(command, shell=True, stdout=SP.PIPE, stderr=SP.PIPE)
print p.stdout.readlines()

for line in p.stdout.readlines():
    logger.info(line)
    print line

Answer: p.stdout.readlines() tries to read all the lines of the command's output in a list, which will never finish since the command is an infinite loop: 'while true; do date; sleep 1; done'.
If you're using Python 2, one way of iterating over the lines of the output could be:
for line in iter(p.stdout.readline, b''):
    print line.rstrip()

In Python 3 you can simply iterate over the p.stdout file object.
Comment: @J Richard: Indeed, iterating over the file object doesn't seem to work in Python 2. I've updated the post with a working version.
Comment: This just hangs if using Python 2 (as implied by print syntax) on an Ubuntu 14.04 box.  It works if I use Python 3.  I don't know enough about the internals of `subprocess.PIPE` to speculate on why.
Answer: This works for me (on Python 2.6.6)
import subprocess as SP
command = 'while true; do date; sleep 1; done'
p = SP.Popen(command, shell=True, bufsize=1, stdout=SP.PIPE, stderr=SP.PIPE)
while True:
    print p.stdout.readline()

The bufsize=1 isn't essential, but it turns on line buffering, which should improve the efficiency a little.
Comment: @eugeney: Then it's probably better to use one of the convenience functions, eg `subprocess.check_output`, rather than directly calling `subprocess.Popen`.


create exe file from windows universal app

Question: I have created a windows universal app with WinJS in visual studio 2015. Now I can run it from my visual studio. How can i make an exe file of the app so that i can distribute it to my friends? Is it only possible to upload in windows store?
Answer: I guess you're talking about an app for Windows 10!?
There are several ways to get this done.
The  best way is to distribute it via Windows Store. You can hide the app there so that it is only visible to people who have the direct link to the app.
Your friends can download it directly from the store.
Another option is to provide the live IDs of your friends in the store. Then your friends get an email with a direct link.
The option you might actually be looking for which doesn't involve the store at all is to create an app package and to deploy this package to your friends.  (See screenshot)
 For Windows Store Apps you won't create an .exe-File, you only create .appx Packages.

Choose not to upload to the store in the next dialog. Then click create.
In the output directory you will find the *.appx file (not an *.exe)
You can distribute the appx via sideloading. Simply copy the content of the output folder to your friends's machine and run the ps1 script in Powershell. This will start the installation of the app.
Little hint: This requires your friends PCs to be enabled  for sideloading.
You can set this in the settings dialog. See Screenshot.
Comment: Thank you. That's exactly the answer i wanted :)
Comment: Each time I try this I get `error APPX0107: The certificate specified is not valid for signing`. Does anyone know how to resolve this issue?
Answer: In Current Windows Dev account, you can use Promotional codes to distribute the app to your friends instead of using side load.If the app is company app, I recommend by using sideload method.
Comment: @VinothKrishnan I think this does answer the question, or at least has merit to help someone in the future.


Stochastic Differential Equations - A Few General Questions

Question: I just have a few questions about stochastic differential equations. I generally did a lot of pure math but signed up for a course on probability models and stochastic differential equations because I wanted to try something different. I have really enjoyed it and am actually seriously considering going to graduate school to study this stuff. The main issue is that we didn't do a measure theory approach to it. The professor used a lot of ideas directly from Wiener and we always took a random walk approach.
Anyway, I just wanted to ask:
a) What is the point of simulating SDEs if the solution is always different due to the randomness of the Wiener process? I have been simulating Geometric Brownian Motion and read that it is used in the Black-Scholes model in finance, so how do they actually price stocks based on the SDE?
b) What are the methods used in determining the coefficients in an SDE to calibrate it to data?
c) What is a good textbook for a very applied and computational approach to stochastic calculus with a crash course on measure theory?
Answer: For a)
Simulating the SDE of an underlying stock price is not used to price the stock; that would yield nothing more than a self-fulfilling prophecy.
Rather, practitioners use simulation methodologies to price financial derivatives of an underlying asset.  For example, the "payoff" function for a simple European call option is $\max(0,P_T - K)$, where $K$ is the "strike" price and $P_T$ is the price of the underlying asset at expiry time $T$.
An analyst would simulate the underlying price, and evaluate the payoff function at time $T$.  Finally, the call option value (i.e., price) is simply the present value of the expected value of the payoff function.
For b)
There are several statistical and market-based methods that practitioners use to determine the parameters of the SDE model.  For market makers, the most common methodology involves the use of the term structure of the market implied volatility.  Other methods include non-parametric models of the PDF of the underlying.  Simpler methods include statistical estimations using historical time series data.
For c)
Darrel Duffie's book Dynamic Asset Pricing Theory might be a good one.
Answer: I do not think you can get a solid technical understanding of SDE's without knowing some measure theory - it is worth learning the basics of measure theory (for example, you should be able to comfortably talk about dominated convergence ).
Additionally a touch of functional analysis will not hurt - the Lebesgue spaces are quite crucial (even if not apparent at first sight) in the theory of SDE's and for financial applications.
To add to Dr. Mv's (excellent) answer:
A. It depends on what you mean by 'different'. A reasonable approximation to a SDE, such as the Euler approximation, has desired convergent properties: it is basically the discretised version of an SDE. In a sense, it is not so different. Naturally, some caveats arise: but these are very deep issues that rarely come to play in practice.
B. Least squares optimisation is one method. Another method is to estimate parameters by using historical market data. Another method is to randomise the initial parameters and then use a Monte Carlo scheme to get the parameters such that an implied surface is satisfied.
C. Stefano Iacus - Simulation and Inference for Stochastic Differential Equations. It has explicit examples in the R programming language, which is free to download.