text:
Q: Having issues with bingmap in android 4.4 (kitkat) i m using bingmap in my app and its working fine till jellybean version.
When i set the target to 4.4, the bing map is just loading the continents alone and not pointing the current location.
On Debugging, found out that the  map loaded event handler callback is not getting called.
Below is the code snippet for maploadedlistener.
       //Add a map loaded event handler
     bingMapsView.setMapLoadedListener(new MapLoadedListener() {
        public void onAvailableChecked() {
            mIsMapReady = true;
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    _gpsLayer = new EntityLayer(Constants.DataLayers.GPS);
                    bingMapsView.getLayerManager().addLayer(_gpsLayer);
                    updateGPSPin();
                }
            });
        }
    });

Has anyone faced the same issue with android 4.4?
ALso please suggest some remedy.

A: My temporary solution now is hide the map first and show after finish loading and I also lock the touch function while zooming.


text:
Q: Custom segue and custom unwind segue in swift I have implemented custom segue and custom unwind segue in a sample app using swift. custom segue is working properly but custom unwind segue give the following error:
2015-06-22 21:05:58.929 Test_Segue[7162:336393] -[__NSSetM perform:]: unrecognized selector sent to instance 0x7ffc89c190c0
2015-06-22 21:05:58.933 Test_Segue[7162:336393] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSetM perform:]: unrecognized selector sent to instance 0x7ffc89c190c0'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010d27bc65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010b228bb7 objc_exception_throw + 45
    2   CoreFoundation                      0x000000010d2830ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x000000010d1d913c ___forwarding___ + 988
    4   CoreFoundation                      0x000000010d1d8cd8 _CF_forwarding_prep_0 + 120
    5   UIKit                               0x000000010b46bda2 -[UIApplication sendAction:to:from:forEvent:] + 75
    6   UIKit                               0x000000010b57d54a -[UIControl _sendActionsForEvents:withEvent:] + 467
    7   UIKit                               0x000000010b57c919 -[UIControl touchesEnded:withEvent:] + 522
    8   UIKit                               0x000000010b4b8998 -[UIWindow _sendTouchesForEvent:] + 735
    9   UIKit                               0x000000010b4b92c2 -[UIWindow sendEvent:] + 682
    10  UIKit                               0x000000010b47f581 -[UIApplication sendEvent:] + 246
    11  UIKit                               0x000000010b48cd1c _UIApplicationHandleEventFromQueueEvent + 18265
    12  UIKit                               0x000000010b4675dc _UIApplicationHandleEventQueue + 2066
    13  CoreFoundation                      0x000000010d1af431 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    14  CoreFoundation                      0x000000010d1a52fd __CFRunLoopDoSources0 + 269
    15  CoreFoundation                      0x000000010d1a4934 __CFRunLoopRun + 868
    16  CoreFoundation                      0x000000010d1a4366 CFRunLoopRunSpecific + 470
    17  GraphicsServices                    0x000000010eeb4a3e GSEventRunModal + 161
    18  UIKit                               0x000000010b46a900 UIApplicationMain + 1282
    19  Test_Segue                          0x000000010acd8e87 main + 135
    20  libdyld.dylib                       0x000000010df33145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

The source code of this sample app is uploaded on github, the link is as follows:
source code

A: I implement segue and add the animation and it works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sort a list of lists I have a list of lists in Python that represents the edges of a graph and I want to sort it, so that the second value of the first list is the same as the first value of the next list. For example I have this list:
[('AT', 'TG'), ('GT', 'TG'), ('TG', 'GG'), ('GG', 'GC'), ('GC', 'CG'), ('CG', 'GT'), ('GC', 'CA'), ('TG', 'GC'), ('CA', 'AA'), ('AA', 'AT')]

And I want to change the order so that the list is like this:
[('AT', 'TG'), ('TG', 'GG'), ('GG', 'GC'), ('GC', 'CG'), ('CG', 'GT'),  ('GT', 'TG'),  ('TG', 'GC'),  ('GC', 'CA'),  ('CA', 'AA'), ('AA', 'AT')]

How can i do that?

A: Maybe this helps. It prints all possible "orderings":
from collections import defaultdict

l = [('AT', 'TG'), ('GT', 'TG'), ('TG', 'GG'), ('GG', 'GC'), ('GC', 'CG'), ('CG', 'GT'), ('GC', 'CA'), ('TG', 'GC'), ('CA', 'AA'), ('AA', 'AT')]

lookup = defaultdict(set)
for k, v in l:
    lookup[k].add(v)

def sort(l, s):
    k = l[-1][1]
    pairs = set([(k, v) for v in lookup[k]]) - s
    if len(pairs) == 0:
        return [l]
    results = set()
    for k, v in pairs:
        results.update(sort(l + ((k, v), ), s | set([(k, v)])))
    return results

results = sort((('AT', 'TG'), ), set([('AT', 'TG')]))

for result in  results:
    print list(result)

Output:

[('AT', 'TG'), ('TG', 'GG'), ('GG', 'GC'), ('GC', 'CG'), ('CG', 'GT'), ('GT', 'TG'), ('TG', 'GC'), ('GC', 'CA'), ('CA', 'AA'), ('AA', 'AT')]
[('AT', 'TG'), ('TG', 'GC'), ('GC', 'CA'), ('CA', 'AA'), ('AA', 'AT')]
[('AT', 'TG'), ('TG', 'GC'), ('GC', 'CG'), ('CG', 'GT'), ('GT', 'TG'), ('TG', 'GG'), ('GG', 'GC'), ('GC', 'CA'), ('CA', 'AA'), ('AA', 'AT')]
[('AT', 'TG'), ('TG', 'GG'), ('GG', 'GC'), ('GC', 'CA'), ('CA', 'AA'), ('AA', 'AT')]


text:
Q: Maximize the distance between a w shaped line construction and two points I am trying to hang string lights on my rectangular porch in a W-shaped fashion. There are two ceiling fans interrupting the pattern and I need to maximize the distance between the ceiling fan blades and the string lights. The perpendicular distance from the center of each ceiling fan to each line should be equal. I tried to use cad to solve this and I am close but I'd like to get an exact solution if possible. I believe one way to go about it is to use the following Theorem and solve that set of equations along with the equations of the lines. There might also be a derivative involved since we are maximizing something. I began using the theorem and things got pretty nasty right away. I am hoping someone might have a more elegant solution. The unknown variables are x_1, x_2 and x_3.

A: Just a few suggestions.
Notation: let's call the four diagonal lines $L1$, $L2$, $L3$, $L4$, and let's call the circle centers $C1$ and $C2$. Define some distances $d1 = distance(L1, C1)$, $d2 = distance(L2, C1)$, $d3 = distance(L3, C12)$, and $d4 = distance(L4, C2)$. We want $d1=d2=d3=d4$.

*

*Using a CAD system, or even just PowerPoint, you can move the diagonal lines around until the four distances look roughly equal. This would probably be close enough.

*If your CAD system supports constraint solving, you can dimension the four distances, tell the system you want them to be equal, and let the constraint solver do its thing.

*You have the formula for the distance from a point to a line, so you can write three equations that express the requirements $d1 = d2$, $d2=d3$ and $d3=d4$. Now we have to solve these three equations to get $x_1$, $x_2$, $x_3$. Solving these equations by hand is likely to be a big mess, unless someone can spot a clever algebra trick (I can't). You can try to solve the equations using a computer algebra system like Wolfram Alpha (free) or Mathematica (far from free). If those systems can't give you an exact algebraic solution, they will at least give you one computed by numerical methods.

A: You'll likely be forced to solve numerically no matter what, but here goes:
I'm assuming the optimal solution will have a radius $r$ from the center $C_1$ to the tangent lines $L_1$ and $L_2$ and similarly for $C_2$. I don't know that that's necessarily the case for the optimum, but it's what I'm going with.
For a given $r$, we can calculate $x_1$ by identifying the angle the tangent line $L_1$ makes with the y-axis.
$$x_1 = 110\tan(\frac{\pi}{2} - \arctan(\frac{55}{105.5})-\arcsin(\frac{r}{\sqrt{55^2 + 105.5^2}}))$$
$x_3$ can be found the same way.
$$x_3 = 292 - 110\tan(\frac{\pi}{2} - \arctan(\frac{55}{81}) - \arcsin(\frac{r}{\sqrt{55^2+81^2}}))$$
Once $x_1$ and $x_3$ are found, we can use the tangent lines $L_2$ and $L_3$ and find their intersections with the top of the rectangle. These won't necessarily agree for a given r, but will give two options $x^L_{2}$ and $x^R_{2}$.
$$x^L_2 = \frac{\sqrt{110^2 + x_1^2} \cdot \sin(2\arcsin(\frac{r}{x_1}))}{\sin(\pi - 2\arcsin(\frac{r}{x_1})-\arctan(\frac{55}{105.5})-\arcsin(\frac{r}{\sqrt{55^2+105.5^2}})}$$
and
$$x^R_2 = 292 - \frac{\sqrt{110^2 + (292-x_3)^2} \cdot \sin(2\arcsin(\frac{r}{x_3}))}{\sin(\pi - 2\arcsin(\frac{r}{x_3})-\arctan(\frac{55}{81})-\arcsin(\frac{r}{\sqrt{55^2+81^2}})}$$
Setting those two equal to each other and solving for $r$ should get you where the tangents meet at a common $x_2$. Barring my tangency assumptions about the optimum being wrong or me misreading the diagram, that gives me $r = 29.6833$, $x_1 = 122.2463$, $x_2 = 149.9779$, and $x_3 = 205.5175$

A: I put it into CAD. Then checked it against the previous solution. Keep in mind that the tolerance is set to 1/64.

Column got in the way!


text:
Q: Flash Player, domain name of webpage it is embedded in? I have developed a flex application (Flex 4.5.1). I want the flex application to be used only by the domain names that I allow. As soon as the application is loaded, I check with the remote database if the domain name is valid.
The problem is that flash player only returns the domain name of the user's machine. What I want is the domain name of the website that the flex application is part of. For instance, if the webpage I browse for my flash application is www.abc.com/index.html, I need www.abc.com or abc.com. Is that possible? Every method I have tried only returns the name of the website visitor's computer.
Thanks

A: You can add a Flash ExternalInterface call to a javaScript function. The javaScript function could return the location
e.g
//javascript
function getLocation() {
    return window.location;
}

and
//AS3
var windowLocation:String=ExternalInterface.call(getLocation) as String;

EDIT
For those who do not want to do this by Javascript: YOU DO NOT NEED JAVASCRIPT :)
Just send a request to your server from Flash.
Then check the server-side variable corresponding to the http referrer (in ColdFusion, its CGI.HTTP_REFERRER. In PHP, its $_SERVER['HTTP_REFERER'];)
This will contain the url of the swf file sending the request.

A: There's no 100% reliable way to get the current url of your swf (I asked this before in the MochiMedia forums: https://www.mochimedia.com/community/forum/topic/reliably-find-the-page-url#d5fe7e47). The main problems:

*

*You can use stage.loaderInfo.url, but that returns the url of the swf, which could be hosted somewhere else (perhaps that could also work). Also if the site uses a custom preloader, then it's probably the url of this preloader rather than your swf.

*You can use ExternalInterface, but firstly, Javascript needs to be enabled, and it will break if the site you're using it on embeds your swf using an iframe

*You can use PHP and referral headers, but it'll suffer under the same problem as the js version.

I use something like SecureSWF (http://www.kindi.com) as they have site locking as well as the encryption etc. I couldn't really tell you how it works though, or if it's different from the 3 methods above


text:
Q: Story about spacemen encountering city of the dead When I was a child I remember reading a story in a comic book about two spacemen who encounter a city in space that, legend has it, only the dead can see. The story ends with one of the spacemen questioning whether they were dead or not and how it was possible for them to see the mythical city. The comic book was in colour. I don't know if it was a Marvel comics publication or some other publisher. One of the spacemen's names was (I think) "Jake Radic"
If I try Googling this name, it comes up (not surprisingly) with lots of people from Serbia!


text:
Q: Color the row of a HTML table from a cell value (from an SQL server) I am trying to create a code which colors the row/line of a specific table depending on a cell`s value. The data comes from a Microsoft SQL server
For example:
if the cell named "files_link" is with a value 0 - color the whole line red (or if it is possible, color another row from that line red)
The idea is if the cell is:
0 - red color
1 - green color
2 - yellow

Sadly I cannot add a working version in the code snippet because I am getting the data from an SQL server.

$(function() {
    $('tr > td:odd').each(function(index) {
        var scale = [['no', 0], ['yes', 1]];
        var score = $(this).text();
        for (var i = 0; i < scale.length; i++) {
            if (score <= scale[i][1]) {
                $(this).addClass(scale[i][0]);
            }
        }
    });
});
table {
    width: 20em;
}

#score {
    width: 50%;
}

#name {
    width: 50%;
}

th {
    border-bottom: 2px solid #000;
    padding: 0.5em 0 0.1em 0;
    font-size: 1.2em;
}

td {
    border-bottom: 2px solid #ccc;
    padding: 0.5em 0 0.1em 0;
}

th:nth-child(even),
td:nth-child(even) {
    text-align: center;
}

.yes {
    background-color: #b6d8b0;
}

.half {
    background-color: #ffc16f;
}

.no {
    background-color: #CC5959;
}

<title>AV.31.U</title>

AV.31.U

            Home

    Проект
    Машина
    te
    video_link
    te
    files_link
    te
    draw_link

<?php
$username = 'censored';
$password = 'censored';
$servername = 'censored';
$database = 'censored';
  ini_set('display_errors', '1');
  error_reporting(E_ALL);
 $db = odbc_connect("Driver={SQL Server};Server=$servername;Database=$database;", $username, $password) or die ("could not connect
");

  $stmt = "Select * from machine";

  $result = odbc_exec($db, $stmt);

  if ($result == FALSE) die ("could not execute statement $stmt
");

  while (odbc_fetch_row($result)) // while there are rows
  {
     print "
\n";
     print "  " . odbc_result($result, "project_ID") . "\n";
     print "  " . odbc_result($result, "machine_project_ID") . "\n";
     print "  " . odbc_result($result, "video_link") . "\n";
     print "  " . odbc_result($result, "files_link") . "\n";
     print "  " . odbc_result($result, "draw_link") . "\n";
     print "  " . odbc_result($result, 'has_draw') . "\n";
     print "  " . odbc_result($result, "has_video") . "\n";
     print "  " . odbc_result($result, "has_files") . "\n";
     print "
\n";
  }

  odbc_free_result($result);

  odbc_close($db);
?>

A: Easiest would be to add a class with PHP in your while loop.
In your PHP code:
$colorclass = [0 => 'red', 1 => 'green', 2 => 'yellow'];
while (odbc_fetch_row($result)) // while there are rows
{
   $classtext = '';
   $x = odbc_result($result, "has_video");
   if( in_array($x, $colorclass) )
   {
      $classtext = " class='".$colorclass[$x]."'";
   }
   print "
\n";
   print "  " . odbc_result($result, "project_ID") . "\n";
   print "  " . odbc_result($result, "machine_project_ID") . "\n";
   print "  " . odbc_result($result, "video_link") . "\n";
   print "  " . odbc_result($result, "files_link") . "\n";
   print "  " . odbc_result($result, "draw_link") . "\n";
   print "  " . odbc_result($result, 'has_draw') . "\n";
   print "  " . odbc_result($result, "has_video") . "\n";
   print "  " . odbc_result($result, "has_files") . "\n";
   print "
\n";
}

In your CSS:
.red { background: red; }
.green { background: green; }
.yellow { background: yellow; }

A: I'm not a PHP developer, but if I understand the question right, you want to color the whole table row background if it contains a "0" value to red, "1" value to green, etc.?
In this case you could create a function in php which could add a custom attribute to that specific row like this:

and for the css you could easily select this row like this:
tr[my-attribute="0"]{
  background-color: red;
}
tr[my-attribute="1"]{
  background-color: green;
}
tr[my-attribute="2"]{
  background-color: yellow;
}

A: First, place data in the
 of the table. Second, dates can be formatted as Strings using toLocaleDateString. This function uses the Intl.DateTimeFormat formatting options.
Now, you can get the value of the seventh column of each row and set a data attribute i.e. data-has-link. You can declare styles for rows i.e.  with a particular data attribute. This is much easier to work with than abusing classes.

$(function() {
  var $table = $('table');
  $table.find('#current_date').text(getCurrentDate());
  colorRows($table); // Color the rows!
});

function getCurrentDate () {
  return new Date().toLocaleDateString('en-GB', {
    year: 'numeric',
    month: 'numeric',
    day: 'numeric'
  });
}

function colorRows($table) {
  var hasLink;
  $table.find('tbody > tr').each(function(rowIndex) {
    const $row = $(this);
    $row.find('td').each(function(colIndex) {
      const $cell = $(this).removeAttr('data-has-link');
      const cellValue = $cell.text().trim();
      if (isFinite(cellValue)) {
        // Color cell based on individual data
        const hasLink = cellHasLink(parseInt(cellValue, 10));
        if (hasLink !== 'maybe') {
          $cell.attr('data-has-link', hasLink);
        }
      }
    });
    // Color row based on 7th column
    var i = parseInt($row.find('td:nth-child(7)').text(), 10);
    $row.attr('data-has-link', cellHasLink(i));
  });
}

function cellHasLink(value) {
  switch (value) {
    case 0  : return 'no';
    case 1  : return 'yes';
    default : return 'maybe';
  }
}
table { width: 20em; border-collapse: collapse; }

th {
  border-bottom: 2px solid #000;
  padding: 0.5em 0 0.1em 0;
  font-size: 1.2em;
}

td {
  border-bottom: 2px solid #ccc;
  padding: 0.5em 0 0.1em 0;
}

th:nth-child(n + 2),
td:nth-child(n + 2) {
  text-align: center;
}

[data-has-link="no"]    { background-color: #F77; }
[data-has-link="yes"]   { background-color: #7F7; }
[data-has-link="maybe"] { background-color: #FD7; }

#score, #name {  width: 50%; }

AV.31.U

      Home

      Project
      Machine
      te
      Video Link
      te
      File Link
      te
      Draw Link

      22005
      22003652
      Link
      Open
      Open
      0
      0
      1

      22012
      22003652
      Link
      Open
      Open
      1
      1
      1

      22012
      22003652
      Link
      Open
      Open
      1
      3
      1

Modifying existing PHP
Modify your PHP to wrap the table header and body appropriately.

AV.31.U

      Home

      Проект
      Машина
      te
      video_link
      te
      files_link
      te
      draw_link

    <?php
    $username = 'censored';
    $password = 'censored';
    $servername = 'censored';
    $database = 'censored';

    ini_set('display_errors', '1');
    error_reporting(E_ALL);

    $db = odbc_connect("Driver={SQL Server};Server=$servername;Database=$database;", $username, $password) or die ("could not connect
");

    $stmt = "Select * from machine";
    $result = odbc_exec($db, $stmt);

    if ($result == FALSE) die ("could not execute statement $stmt
");

    while (odbc_fetch_row($result)) // while there are rows
    {
      print "
\n";
      print "  " . odbc_result($result, "project_ID") . "\n";
      print "  " . odbc_result($result, "machine_project_ID") . "\n";
      print "  " . odbc_result($result, "video_link") . "\n";
      print "  " . odbc_result($result, "files_link") . "\n";
      print "  " . odbc_result($result, "draw_link") . "\n";
      print "  " . odbc_result($result, 'has_draw') . "\n";
      print "  " . odbc_result($result, "has_video") . "\n";
      print "  " . odbc_result($result, "has_files") . "\n";
      print "
\n";
    }

    odbc_free_result($result);
    odbc_close($db);
    ?>


text:
Q: line numbering including blank (empty lines) I have a latex document and I would like to include line numbers in it, the tricky part is that I need to count the blank (empty) lines too (emulating what MSWord does :(.
I know I could use the package lineno but it doesn't seem to have an option for counting blank lines.
any ideas? thanks

A: You can insert a blank line that will be marked using a macro

\documentclass{article}

\usepackage{lineno,lipsum}

\newcommand{\markblankline}{\par\mbox{}\par}

\begin{document}

\linenumbers

\lipsum[1]

\markblankline

\lipsum[2]

\markblankline

\lipsum[3]

\end{document}

Using such explicit blank-line-numbering seems extreme. However, your document may contain a whole host of formatting options that might not interact well with lineno as it stands.
If your document contains straight-forward text, perhaps the following may be of use:
\documentclass{article}

\usepackage{lineno,lipsum,everyhook}

\newcommand{\markblankline}{\par\mbox{}\par}

\begin{document}

\linenumbers

\lipsum[1]

\PushPreHook{par}{\hspace*{-\parindent}\makebox[\linewidth]{}\\\hspace*{\parindent}}

\lipsum[2-3]

\end{document}

The above code provides the same output by appending a blank line with every issue of \par thanks to the everyhook package.


text:
Q: node js - ReferenceError: navigator is not defined what I want is to register my service worker in my progressive web app. I created my sw.js file and in my app.js file I wanted to do this:
if('serviceWorker' in navigator){
    navigator.serviceWorker
        .register('/sw.js')
        .then(function(){
            console.log('Service worker registered!');
        });

}

but this is the error that I am receiving: ReferenceError: navigator is not defined.
What should I do?
I expected it to work, but it is not working.

A: A service worker is a script that runs independently in the browser background , not server side.
For using ServiceWorker in node.js use node-service-worker


text:
Q: What is the difference between "He saw me talking" and "He saw me talk"? Can anybody tell me the difference between the following two sentences:

He saw me talking to her.
He saw me talk to her.

Please let me know if both the statements are valid and grammatically correct. If valid, please explain the meaning of both the statements and what is the difference between the two.

A: These are complements of sense verbs (the first case discussed in this answer) and have a number of peculiarities. Of particular interest is the fact that the non-volitional sense verbs can take all four varieties of complement. Which includes gerund and infinitive complements, like these.
The difference between infinitive and gerund complements, "roughly speaking", according to McCawley, is that gerunds correspond to events, while infinitives correspond to situation types.
There is minimal or no difference between the meanings of

*

*He saw me talking to her.

*He saw me talk to her.
because of facts about vision and conversation, and the usages of complements.

*

*He saw me talking to her means he witnessed my conversational activity with her.

*He saw me talk to her means he knows that I talked to her because he witnessed the event.

In other words, if he saw one, he saw the other. This is not necessarily true for all predicates;
i.e, He saw me running the marathon does not necessarily mean He saw me run the marathon.

A: Although both are correct, there is a slight difference in meaning.
The first implies that he saw part of the conversation, while the second is more likely to imply that he saw the whole conversation take place.

A: Both are grammatically correct and mean the same. The only difference is, the first sentence is more commonly used than the second.


text:
Q: Custom REST Service HTTPS error I am building an apex REST service to be hosted on a public site using the approach outlined here (basically hosting a REST service on a site allows you to perform actions against it without authentication, which is nice for javascript integration).
http://blogs.developerforce.com/developer-relations/2012/02/quick-tip-public-restful-web-services-on-force-com-sites.html
My service works perfectly in Sandbox, but when attempting to access it in prod, it always throws
<Errors>
    <Error>
        <errorCode>UNSUPPORTED_CLIENT</errorCode>
        <message>HTTPS Required</message>
    </Error>
</Errors>

This error happens even when accessing the service via HTTPs.
Here is my functional sandbox one
https://fpitesters.testbed.cs7.force.com/webServices/services/apexrest/respondentPortal/
You will get an auth token error there, that is expected. It's just a basic security measure.
And here is the production one
https://fpitesters.force.com/webServices/services/apexrest/respondentPortal/
UPDATE: So as Josh Birk pointed out, you do need to use the secure sub domain. If you try to just use HTTPs on the regular URL you do get redirected to a regular http domain. So with that in mind, the url for my service should be
https://fpitesters.secure.force.com/webServices/services/apexrest/respondentPortal/
However that URL says that the service couldn't be found.
<Errors>
    <Error>
        <errorCode>NOT_FOUND</errorCode>
         <message>Could not find a match for URL /respondentPortal/</message>
    </Error>
</Errors>

Not really sure where to go from here. Is this a bug?

A: Your production endpoint is only HTTP however.  Remember that secure Force.com site has a specific domain, so I think you need:
https://fpitesters.secure.force.com/FPITestersIndex

A: Got it figured out. It was due to a permissions error it seems. Somehow an object for the services profile had an impossible permission setup (it had full read write modify all on an child object where it did not have read write modify all on the parent object (an opportunity)). So fixing the permissions and making sure the service had read/write to all objects and fields it required seems to have fixed this error.

A: I was receiving the same error:
Could not find a match for URL

but the issue turned out to be namespacing. The Apex controller had Namespace Prefix mynamespace, with @RestResource(urlMapping='/Widgets/*'), and the URL ended up being
https://mydomain.myhost.force.com/mysitecustomurl/services/apexrest/mynamespace/Widgets/


text:
Q: SQL Server 2008 R2 - How to rename multiple columns name? I haven´t much experiences with SQL Server 2008, I´d like to rename all columns in my database (add to existing name some prefix).
I'm thinking something like:
Foreach( column in table)
(
    column_name = prefix+column_name
)

Is there any way to do it??
Thanks so much.

A: You can try the following solution: iterate through records from sys.columns table using cursor and for each record excute the sp_rename system stored procedure.
I think there can be problems with integrity while renaming, so you need to be careful with other objects (for example stored procedures) that refers for these columns.
UPDATE: MVP says:

if you have any indexes, primary keys, unique keys, or foreign keys, they need to be dropped, and then readded, after the columns have been renamed. If you don't do this in the correct order, you will get lots of nasty error message.

A: you may try using sp_RENAME. it does allow only single column at a time. but you can do it on your code to loop on each of the columns. hope it helps. thanks!


text:
Q: Killed process that didn't show sign of memory leaks? I have a script that runs in the background written in PHP that connects to other servers multiple times (one by one).
I specially worked on the memory leaks in order to properly close the resources used, and I have implemented a real time output of what the script is using, with the memory_get_usage() function from PHP.
The script runned for about an hour, and the memory indicated something around 340kb (up to 360kb max).
But then, it stopped. Without any error message or anything else.
When I looked at dmesg, here what I saw :

Out of memory: Kill process 3147 (php5) score 905 or sacrifice child
Killed process 3147 (php5) total-vm:651064kB, anon-rss:475032kB,
  file-rss:48kB

(For information, I have a 512Mb Digital Ocean server)
With a list of process before, including a message with lowmem_reserve
I'm starting to think that the script contains some memory leak. Could you confirm this? But if that's the case, why memory_get_usage didn't increased? is it reliable? Is there a better way to trace the potential memory leaks?
UPDATE 1: Here's the current state of my server
  PID USER      PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND
 2283 root      20   0 67104 6724  900 S   0,0  1,3   0:05.97 fail2ban-server
 4100 cyril     20   0 21416 4156 1672 S   0,0  0,8   0:00.16 bash
 4094 root      20   0 81856 3976 3136 S   0,0  0,8   0:00.00 sshd
 4192 root      20   0 20568 3384 1732 S   0,0  0,7   0:00.09 bash
 2370 root      20   0 62032 2264 1196 S   0,0  0,4   0:00.13 console-kit-dae
 4099 cyril     20   0 81856 1676  848 S   0,0  0,3   0:00.00 sshd


text:
Q: Splitting posted text using space and inserting into mysql database if (mysqli_connect_errno()==0)
{ // if successfully connected

  $sent_dt=$_POST['scts'];
  // important: escape string values
  $txt=mysqli_real_escape_string($con, $_POST['text']);
  $snd=mysqli_real_escape_string($con, $_POST['sender']);

  // creating an sql statement to insert the message into the SMS_IN table
  $sql="INSERT INTO SMS_IN(studentID,lastname,firstname,class) VALUES ('34','Lekan','Balogun','Grade8')";
  // executing the sql statement
  $insert_sms_success = mysqli_query($con,$sql);

  // closing the connection
  mysqli_close($con);
}

Have recieved some info which are not very clear. I want to be able to split an incoming sms (e.g 32 Lekan Balogun Grade8) using spaces in between to seperate each text as field. What I currently have is the whole sms message. I want to be able to split it using spaces in between the text into my MySql database. Thanks in anticipation as this is my class assignment

A: You can use the Explode function in PHP to do this quite easily:
$yourOriginalText="Splitting posted text using space and inserting into mysql database";
$yourArrayofData=explode(" ", $yourOriginalText);
print_r($yourArrayofData);

You can then very easily work out how to insert the right data into the columns you want.
$sql="INSERT INTO SMS_IN(studentID,lastname,firstname,class)
    VALUES
    ('".$yourArrayofData[0]."',
    '".$yourArrayofData[1]."',
    '".$yourArrayofData[2]."',
    '".$yourArrayofData[3]."')";

Be aware though that this will simply take the data in the order it comes in - if someone mucks up an SMS, it will happily continue along. Also as you are passing user data into the database, you really want to do some injection protection.


text:
Q: How to listen for an "Insufficient cpu/memory" event in an AWS ECS service? I am interested in listening/reacting to the event, that a service cannot start start a task because of insufficient cpu or memory. This information can be viewed in the console, if i chose the specific service and look in its "Events" tab. There, an event like the following would be displayed:
"service X was unable to place a task because no container instance met all of its requirements. The closest matching container-instance Y has insufficient CPU units available. For more information, see the Troubleshooting section."
The container instances in the cluster are managed in an AutoScalingGroup, so the appropriate action would be to react to this event, by scaling in an additional instance, which would then allow the task to be scheduled to run. Now, my problem is, how do i react to this event?
I have a LogGroup that contains data from the following files from all the EC2 instances in the cluster:

*

*/var/log/dmesg

*/var/log/messages

*/var/log/docker

*/var/log/ecs/ecs-init.log.*

*/var/log/ecs/ecs-agent.log.*

(The EC2 instances are based on amazon-ecs-optimized images)
Initially, i thought i that the "service X was unable to place a task..." message would appear in one of these log files (more specifically in the ecs-agent.log or ecs-init.log), but that was not the case.
I then realized that "ECS Evenets" is a thing (see more at http://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_cwe_events.html). But unfortunately, this specific event, is not one that is supported by the "ECS Events". Only:
Container Instance State Change Events and Task State Change Events. NOT "Service State Change Events". Even though, one would think that the events from the "Events" tab in the service would be streamed as well, they are not. I came to realize the documentation even says that:
"You can use Amazon ECS event stream for CloudWatch Events to receive near real-time notifications regarding the current state of both the container instances within an Amazon ECS cluster, and the current state of all tasks running on those container instances."
And thereby, "Amazon ECS Event Stream for CloudWatch Events" is not steaming service events (and thereby not events for tasks that are prevented from running). I really hope that "Service State Change Events" would be included in the future, that way i could make a CloudWatch Event Rule that matches this event, triggers a Lambda function which would then determine if the event was an event of type "service X was unable to place a task...", and based on that, manipulate the AutoScalingGroup to scale in an additional instance to the cluster.
But as stated, this is not supported at the moment. Is there any other way that i can "listen" for this event? I even thought about running a lambda every 2-3 minutes that uses the CLI to invoke "aws ecs describe-services --service X" to output the list of events, and then match on the "service X was unable to place a task..." event. But that just seems wrong...
Any help is very appreciated. Thanks!

A: I am able to get these events with Cloudwatch event rule. I have created a Cloudwatch event rule with a target and using "Part of the matched event" with below pattern to filter these events.
$.detail.responseElements.service.events

These events are in the AWS API Call Via Cloudtrail.
Steps:

*

*Create an event rule with below configurations of event pattern.
Service Name: ECS
   Event Type: AWS API Call Via Cloudtrail

*Choose Target: SNS

*Configure input - Part of the matched event -> Enter $.detail.responseElements.service.events into the box.

*Create a rule.
JSON After Filtering Events is like:
[
  {
    "id": "fb7dbb37-ff2a-443c-b414-1ead7276f550",
    "createdAt": "Oct 18, 2018 7:24:16 AM",
    "message": "(service sample) has reached a steady state."
  },
  {
    "id": "598dbdc0-e1b5-4673-8d5c-0b531d349789",
    "createdAt": "Oct 18, 2018 1:24:11 AM",
    "message": "(service sample) has reached a steady state."
  },
  {
    "id": "5aa89799-c661-4f6c-bbf0-8e7c93dfa31e",
    "createdAt": "Oct 17, 2018 7:24:04 PM",
    "message": "(service sample) has reached a steady state."
  },
  {
    "id": "db535112-786d-4090-9855-147a7301761b",
    "createdAt": "Oct 17, 2018 1:23:34 PM",
    "message": "(service sample) has reached a steady state."
  },
  {
    "id": "15e4b4d7-8cb7-4fd7-b616-bec0fdbc5e6c",
    "createdAt": "Oct 17, 2018 1:01:35 PM",
    "message": "(service sample) was unable to place a task because no container instance met all of its requirements. The closest matching (container-instance 05016874-f518-4b7a-a817-eb32a4d387f1) has insufficient memory available. For more information, see the Troubleshooting section of the Amazon ECS Developer Guide."
  },
  {
    "id": "f744736c-6213-40bc-aee4-9e928f9be263",
    "createdAt": "Oct 17, 2018 1:01:26 PM",
    "message": "(service sample) has started 1 tasks: (task 3af3f916-1d6f-4543-a179-c2b06da8487e)."
  },
  {
    "id": "3af31b15-1386-4fd5-be80-42b7e4cdce54",
    "createdAt": "Oct 17, 2018 12:51:35 PM",
    "message": "(service sample) was unable to place a task because no container instance met all of its requirements. The closest matching (container-instance 05016874-f518-4b7a-a817-eb32a4d387f1) has insufficient memory available. For more information, see the Troubleshooting section of the Amazon ECS Developer Guide."
  }
]


text:
Q: Volume in a manifold and wedge product Let's say we have some 4D maniforld $M$ in which the differential volume is given by Hodge's star $\star$ as
$$
dV :=\star\ 1 = \sqrt{|g|}\ dx^0\wedge dx^1\wedge dx^2\wedge dx^3
$$
Where $g$ is the determinant of the metric tensor on $M$
Now, this $dV$ should be equal to the usually $dv$ given as
$$
dv = \sqrt{|g|}\ dx^0dx^1dx^2dx^3
$$
since both of them are the same concept, represent the same quantity. But since the wedge product is define as
$$
dx\wedge dy = \frac{1}{2}(dx\otimes dy - dy\otimes dx)
$$
I don't see how $dV$ and $dv$ are equal and moreover I don't understand quite well the importance of $\otimes$ in the wedge's definition. What would be the difference betweeen integrating a function $f(x, y)$ with $dx\otimes dy$ instead of $dy\otimes dx$? And how to prove $dV = dv$?


text:
Q: Python unexpected EOF while parsing (python2.7) Here's my python code. Could someone show me what's wrong with it?
I try to learn an algorithm on solving 24 - point game.
But I really don't know why this program has an error.
from __future__ import division
import itertools as it
__author__ = 'linchen'

fmtList=["((%d%s%d)%s%d)%s%d", "(%d%s%d)%s(%d%s%d)",
"(%d%s(%d%s%d))%s%d", "%d%s((%d%s%d)%s%d)", "(%d%s(%d%s(%d%s%d))"]
opList=it.product(["+", "-", "*", "/"], repeat=3)

def ok(fmt, nums, ops):
    a, b, c, d=nums
    op1, op2, op3=ops
    expr=fmt % (a, op1, b, op2, c, op3, d)
    try:
        res=eval(expr)
    except ZeroDivisionError:
        return
    if 23.999< res < 24.001:
        print expr, "=24"

def calc24(numlist):
    [[ok(fmt, numlist, op) for fmt in fmtList] for op in opList]

for i in set(it.permutations([3,3,8,8])):
    calc24(i)

And Here's what happens:
Traceback (most recent call last):
  File "D:\Program Files\JetBrains\PyCharm 4.0.5\helpers\pydev\pydevd.py", line 2217, in <module>
    globals = debugger.run(setup['file'], None, None)
  File "D:\Program Files\JetBrains\PyCharm 4.0.5\helpers\pydev\pydevd.py", line 1643, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:/Users/linchen/PycharmProjects/untitled/calc24.py", line 26, in <module>
    calc24(i)
  File "C:/Users/linchen/PycharmProjects/untitled/calc24.py", line 22, in calc24
    [[ok(fmt, numlist, op) for fmt in fmtList] for op in opList]
  File "C:/Users/linchen/PycharmProjects/untitled/calc24.py", line 15, in ok
    res=eval(expr)
  File "<string>", line 1
    (8+(3+(3+8))
               ^
SyntaxError: unexpected EOF while parsing

Could anyone told me how to fix this problem?

A: You're last fmtList item has unbalanced parenthesis:
"(%d%s(%d%s(%d%s%d))"

should be:
"(%d%s(%d%s(%d%s%d)))"

And that explains the traceback -- Python is looking for a closing parethesis -- instead it encounters and end of line (when using eval, the end of line is interpreted as "End Of File" or EOF) and so you get the error.


text:
Q: Visualize/list/check dependencies I have to mock in unit test? Given a unit test for old, hard-to-read C# legacy code, what are the best ways to:

*

*find the dependencies (visualize them, or outoput a list for a single method)

*check after refactoring that all dependencies got broken, that the unit test is really isolated.  No hidden invocation of DateTime.Now, no Database/File/Service access, no calls to anything which is not a stub or mock (other than some trusted .NET framework stuff, etc.)

Most probably a question about tooling.
I could manually look through the code and assume I didn't forget to break all dependencies, but that's error-prone. The thing I do right now is marking (via some hidden resharper feature) all usings of certain (non-interface-only, custom) namespaces. But there are assemblies which mix interfaces and implementations, plus not all of my coworkers use Resharper, plus I have the gut feeling it could be even easier, e.g. simple yes/no check.
If tehre is some great commercial tool for that, that's fine, too.
EDIT: maybe I should expresse it in a cleaner way: how can I easily, within Visual Studio, see what non-interface dependencies my class/method depends on? There gotta be tools for that (I hope), money is a secondary concern.

A: My answer may not be of any use for you anymore, given that the question was asked a long time ago, but in case anyone else has a similar problem to solve:
http://msdn.microsoft.com/en-us/magazine/cc163641.aspx


text:
Q: Parameter estimation of exponential distribution depending on multiple factors/attributes for a simulation I'll need to simulate project delays.
I've data on 20k projects with delays in quarters. Some of them were finished ahead of plan (i.e. neg. delays) others with a delay of 1-16 quarters. I assume a delay of 0 for everything finished ahead of plan as this does not get awarded in my case. The histogram looks like an exponential distribution would be a good fit.
I want to differentiate the distribution parameter (ie. lamda) depending on multiple attributes/factors of the project (3-5 factors, eg. region (south, north, west, east), project manager (X, Y, Z), type (basic, premium), etc.)). So I'm wondering what is the best approach to estimate the matrix of coefficients?
Individual estimation (for each combinations of factors):

*

*Should I extract subsamples for each possible combination of factors and estimate the lambdas in a regular way for each (eg MLE, LSE, etc.)?

*What must hold, that I could run the parametrization on each dimension (eg region) independently and then somehow cross the coefficient vectors to get the matrix? (rather then going through all combinations)

*Which test would you recommend to identify the 1-2 most sensitive dimensions/factors for the delay distribution (would ANOVA work assuming an exp. distribution and 5-8 groups each dimension)?

Multi-dimensional estimation:

*

*Any method allowing to run a multi-dimensional parametrization on the whole data set and will this be more accurate?

Many thanks for any input and ideas!
Serge

A: If you're familiar with R (or Python, or many other statistical packages), using a sparse.model.matrix with a general model-builder like xgboost will automatically separate out the categories for variables and give you their relative importance.
If you actually need to encode the model somewhere else instead of just making predictions on a new data set, many generalized linear models can give you coefficients, and as long as you cast your data as a sparse matrix, those individual categories will survive.

A:
for a simulation I'll need to simulate project delays.

I've data on 20k projects with delays in quarters. Some of them were finished ahead of plan (i.e. neg. delays) others with a delay of 1-16 quarters. I assume a delay of 0 for everything finished ahead of plan as this does not get awarded in my case.

The histogram looks like an exponential distribution would be a good fit.

Presumably that's the marginal distribution you're looking at; this can be misleading, since what you're trying to discuss is the conditional distribution (conditional on the attributes you mention)
Also being quarterly, it's discrete (or, arguably interval-censored) rather than continuous. The exact zeroes may be an issue because they probably don't fit with the patter of the rest; you might perhaps need to consider zero-inflated distributions

I want to differentiate the distribution parameter (ie. lamda) depending on multiple attributes/factors of the project (3-5 factors, eg. region (south, north, west, east), project manager (X, Y, Z), type (basic, premium), etc.)). So I'm wondering what is the best approach to estimate the matrix of coefficients?

Likely a generalized linear model (or similar) with a conditional distribution suited to the fact that times will be right skew and likely heteroskedastic. Perhaps a negative binomial or a zero-inflated gamma model.

Should I extract subsamples for each possible combination of factors and estimate the lambdas in a regular way for each (eg MLE, LSE, etc.)?

No, generally it's better to do it all in one model

What must hold, that I could run the parametrization on each dimension (eg region) independently and then somehow cross the coefficient vectors to get the matrix? (rather then going through all combinations)

This won't work in general. e.g. see Simpson's paradox

Multi-dimensional estimation:
Any method allowing to run a multi-dimensional parametrization on the whole data set and will this be more accurate?

See the above suggestion.


text:
Q: Jtable shows "old" text even though render-component has no text anymore i use Jpanel with a Jlabel on it as render-component in my jtable. i add "fake-entries" (=JLabel without text) if there are not enough entries to fill the whole table.
it happens from time to time that text is displayed in the jtable after deleting it. each entrie contains the text of the last table entrie (before the delete) e.g. "Gegeben Bar..."
Even calling a repaint doesn't solve the problem. Only after inserting a new row the table gets displayed correctly. jre is 1.4_09 on running on linux
here's what i do after clearing table-elements
model.fireTableRowsDeleted( firstRow, firstRow + rowCount - 1);
model.fireTableDataChanged();

i've a function to log the table elements and component when the problem occures
     for(int i=0; i < model.getRowCount();i++){
        try
        {
            bw.newLine();
         bw.write("el"+i+" "+model.getValueAt(i, 1)+"->" +model.getValueAt(i, 1).hashCode());
         bw.newLine();
         bw.write(" ->"+((JPanel)renderer.getTableCellRendererComponent(this, model.getValueAt(i,1),false, false, i, 0)).getComponent(0).hashCode()+"->" +((JPanel)renderer.getTableCellRendererComponent(this, model.getValueAt(i,1),false, false, i, 0)).getComponent(0));
         bw.newLine();
         if(observedElement.getElements().size()>i)
             bw.write(" -> "+observedElement.getElements().get(i));
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
     }

in the output you can see the neither the element nor the jlabel contain text
el0 ->5840819
 ->20546691->javax.swing.JLabel[,4,0,273x19,alignmentX=0.0,alignmentY=null,border=,flags=8,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEFT,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=,verticalAlignment=CENTER,verticalTextPosition=CENTER]
 ->
el1 ->5840819
 ->20546691->javax.swing.JLabel[,4,0,273x19,alignmentX=0.0,alignmentY=null,border=,flags=8,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEFT,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=,verticalAlignment=CENTER,verticalTextPosition=CENTER]
 ->
el2 ->5840819
 ->20546691->javax.swing.JLabel[,4,0,273x19,alignmentX=0.0,alignmentY=null,border=,flags=8,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEFT,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=,verticalAlignment=CENTER,verticalTextPosition=CENTER]
 ->
...

any idea what might be the cause of the problem or how to solve it?


text:
Q: Correct way to join two double linked list In the Linux kernel source, the list_splice is implemented with __list_splice:
static inline void __list_splice(const struct list_head *list,
                                 struct list_head *prev,
                                 struct list_head *next)
{
        struct list_head *first = list->next; // Why?
        struct list_head *last = list->prev;

        first->prev = prev;
        prev->next = first;

        last->next = next;
        next->prev = last;
}

Isn't the list already pointing to the head of a linked list?
Why do we need to fetch list->next instead?

A: The double linked list API in the Linux kernel is implemented as an abstraction of circular list. In that simple scheme the HEAD node does not contain any payload (data) and used explicitly to keep starting point of the list. Due to such design it's really simple to a) check if the list is empty, and b) debug list because unused nodes have been assigned to the so called POISON — magic number specific only to the list pointers in the entire kernel.
1) non-initialized list
+-------------+
|    HEAD     |
| prev | next |
|POISON POISON|
+-------------+

2) empty list
+----------+-----------+
|          |           |
|          |           |
|   +------v------+    |
|   |    HEAD     |    |
+---+ prev | next +----+
    | HEAD   HEAD |
    +-------------+

3) list with one element
+--------------+--------------+
|              |              |
|              |              |
|       +------v------+       |
|       |    HEAD     |       |
|   +---+ prev | next +--+    |
|   |   |ITEM1   ITEM1|  |    |
|   |   +-------------+  |    |
|   +--------------------+    |
|              |              |
|       +------v------+       |
|       |    ITEM1    |       |
+-------+ prev | next +-------+
        |    DATA1    |
        +-------------+

4) two items in the list
      +----------+
      |          |
      |          |
      |   +------v------+
      |   |    HEAD     |
   +------+ prev | next +----+
   |  |   |ITEM2   ITEM1|    |
   |  |   +-------------+    |
+----------------------------+
|  |  |          |
|  |  |   +------v------+
|  |  |   |    ITEM1    |
|  |  +---+ prev | next +----+
|  |  |   |    DATA1    |    |
|  |  |   +-------------+    |
|  +-------------------------+
|     |          |
|     |   +------v------+
|     |   |    ITEM2    |
+---------+ prev | next +----+
      |   |    DATA2    |    |
      |   +-------------+    |
      |                      |
      +----------------------+

In the lock less algorithm there is a guarantee only for next pointer to be consistent. The guarantee wasn't always the case. The commit 2f073848c3cc introduces it.


text:
Q: .Net Core configure start up for different builds I'm trying to figure out an efficient way to configure my Startup.cs for different builds with out using a lot of nasty IfDefs.  If I were to configure a normal class, I would usually just swap out a component in the Dependency Injector and everything would be done, but since the startup class is used to configured DI, this isn't possible.
Currently I'm hard coding things like:
services.AddAuthentication(options =>
{
     options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
}).AddIdentityServerAuthentication(AuthenticationRule.ConfigureForStaging());
//.AddIdentityServerAuthentication(AuthenticationRule.ConfigureForProduction());

I have a bunch of statement commented out throughput the code base
const string connection = @"Server=StagingServer.com;Database=MyStagingDB;Trusted_Connection=True;";
//const string connection = @"Server=localhost;Database=MyLocalDB;Trusted_Connection=True;";

This is not very efficient, and definetly error prone.  How can I configured my startup class to make switching builds easy?

A: Here's one idea.
public class Program
{
    public static bool IsProduction = false; // shouldn't actually be hard coded.

    public static void Main(string[] args)
    {
        var hostCommon =
            new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration();

        var host =
            IsProduction
                ? hostCommon.UseStartup<StartupProduction>()
                : hostCommon.UseStartup<StartupStaging>();

        host.Build().Run();
    }
}

You could then put the common portions in a Helper class of some kind, and call whatever portions you need for each Startup class from each individual Startup class.
If you have more than two environments, you could use a Dictionary<string, Type> or Dictionary<string, Func<IWebHostBuilder, IWebHostBuilder>> and key off of the environment name.
Alternatively, you could use the Convention-based approach mentioned by  Camilo Terevinto. From Microsoft:

An alternative to injecting IHostingEnvironment is to use a
  conventions-based approach. The app can define separate Startup
  classes for different environments (for example, StartupDevelopment),
  and the appropriate startup class is selected at runtime. The class
  whose name suffix matches the current environment is prioritized. If
  the app is run in the Development environment and includes both a
  Startup class and a StartupDevelopment class, the StartupDevelopment
  class is used.


text:
Q: Include custom module block within phtml file? I've created a custom module for a distributor search with a php class/block inside.
Module Structure:
- /Distributor Search
    - /Block
         - DistributorSearch.php
    - /etc
        - module.xml
    - /view
         - /frontend
              - /template
                  - distributor-search.phtml
    - registration.php

I've tried to reference the DistributorSearch block when adding my phtml to the page in my default.xml in my theme.
<block class="Autosmart\DistributorSearch\Block\DistributorSearch" name="distributor.search" template="Autosmart_DistributorSearch::distributor-search.phtml"></block>

I've also tried to keep the phtml file within my theme and include like:
 <block class="Autosmart\DistributorSearch\Block\DistributorSearch" name="distributor.search" template="Magento_Theme::html/distributor-search.phtml"></block>

However I keep getting 500 errors and struggling to get the phtml to show on the page using our module class/block.
I can get the phtml to show on the page by but then I cannot use our methods inside my class DistributorSearch.php?
<block class="Magento\Framework\View\Element\Template" name="distributor.search" template="Autosmart_DistributorSearch::distributor-search.phtml"></block>

Any help to get this working would be appreciated.
UPDATE:
Block class content:
<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Autosmart\DistributorSearch\Block;

/**
 * Local Distributor Search Header Block
 */
class DistributorSearch extends \Magento\Framework\App\Config\ScopeConfigInterface
{
    /**
     * Retrieve store name
     *
     * @return string
     */
    public function getStoreName()
    {
        return "testx";
    }
}

distributor-search.phtml contents:
<?php
echo $block->getStoreName();
?>
Test Content

A: My best guess is that your block is extending \Magento\Framework\App\Config\ScopeConfigInterface instead of \Magento\Framework\View\Element\Template.
A block should always be a child of \Magento\Framework\View\Element\AbstractBlock, since it contains certain logic to render the HTML and handle layout updates.
I think you're getting the 500 error because your block class is not a Block.


text:
Q: Do photons emitted from a LED show bunching? If photons are emitted from a thermal source, we get photon bunching. For coherent radiation, the detection probability doesn't change after detecting a photon. For single photon sources, we get anti-bunching.
A LED isn't a thermal source but it isn't coherent either. Does this mean that we still have some amount of bunching?
I didn't find anything in the literature because everybody is all over single photon LEDs.

A: One thing that you can be sure of is, for a large enough LED, you will get poisson statistics to a very good approximation. Neither bunching nor anti-bunching. The reason is simple: One photon comes from a certain part of the LED, the next photon is likely to come from a totally different part of the LED and head in a totally different direction. There's no way that either of these photons can influence the other.
The question is, what do I mean by "large enough LED"? 100 microns is definitely large enough. 100 nanometers is probably not. In between those, I don't know. I hope someone else will give a better answer!! :-D
(I'm referring to the size of the active area on the chip, not the size of the package.)

A: An LED is a collection of discrete atoms. When a current flows, an electron excites one every so often. The excited atom decays after a while and emits a photon. Assuming the current is uniform, variations in intensity come from randomness in arrival times and excited state lifetimes. Some time slices have many photons, some fewer. This distribution is called Shot noise.
An LED with polished ends is a laser. Light is generated by stimulated emission. An excited population of atoms is maintained. The LED is filled with photons all in the same state. Every so often, one will stimulate an excited atom to emit a photon in the same state. If everything else is uniform, this will be subject to the same randomness as an ordinary LED. So again, you get Shot noise.


text:
Q: Postgres select all columns but group by one column I have a simple table with a unit_id oid, time timestamp, diag bytea. The primary key is a combination of both time and unit_id.
The idea behind this query is to get the latest row (largest timestamp) for each unique unit_id. However the rows for each unit_id with the latest time are not always returned.
I really want to group by just the unit_id, but postgres makes me use diag also, since I am selecting that.
SELECT DISTINCT ON(unit_id) max(time) as time, diag, unit_id
FROM diagnostics.unit_diag_history
GROUP BY unit_id, diag

A: Any time you start thinking that you want a localized GROUP BY you should start thinking about window functions instead.
I think you're after something like this:
select unit_id, time, diag
from (
    select unit_id, time, diag,
           rank() over (partition by unit_id order by time desc) as rank
    from diagnostics.unit_diag_history
) as dt
where rank = 1

You might want to add something to the ORDER BY to consistently break ties as well but that wouldn't alter the overall technique.

A: You can join the grouped select with the original table:
SELECT d.time, d.diag, d.unit_id
FROM(
    SELECT unit_id, max(time) as max_time
    FROM diagnostics.unit_diag_history
    GROUP BY unit_id
) s JOIN diagnostics.unit_diag_history d
ON s.unit_id = d.unit_id AND s.max_time = d.time


text:
Q: Case When with CTE SQL Server 2019 I have a query which it has to return one value.
My query returns 2 rows. But I have to make condition : if my column [STJH_DATE_ACTION] <= GETDATE(), I have to show only the first row
If my column [STJH_DATE_ACTION] < GETDATE() I want to show second row.
I tried this query :
WITH CTE AS
(
    SELECT
        ROW_NUMBER () OVER (PARTITION BY ST_ID, STJ_JOUR ORDER BY A.STJH_DATE_ACTION DESC) AS RN,
        *
    FROM
        bloc.W_TMD_JOUR_HISTORIQUE A
)
SELECT *
FROM CTE
WHERE CTE.ST_ID = 268 AND CTE.STJ_JOUR = 1

How can I add the Case When expression?
I have this result

A: I would much rather have a minimally reproducible sample code to use. I'm blindly going by your code sample above, and your description. I added a CASE expression to your CTE. Then in the main SELECT, I order by the CASE expression and add TOP 1 to make sure we only get one row. The only issue I'm not completely knowledgeable on is weather calling GETDATE() twice will always produce the same result as I used it.:
WITH CTE AS (
    SELECT
        ROW_NUMBER () over (partition by ST_ID, STJ_JOUR order by A.STJH_DATE_ACTION DESC) as RN
        , *
        , CASE
            WHEN [STJH_DATE_ACTION] = GETDATE() THEN 1
            WHEN [STJH_DATE_ACTION] < GETDATE() THEN 0
          END as isCurrent
    FROM bloc.W_TMD_JOUR_HISTORIQUE A
)
SELECT TOP 1
    CTE.*
FROM CTE
WHERE
    CTE.ST_ID = 268
    AND CTE.STJ_JOUR = 1
ORDER BY CTE.isCurrent DESC

Update: CASE "expressions" not statements.


text:
Q: Create background process in Heroku without using worker My web application will need to execute 1 specific function every 1 hour. Does it have anyway to deploy it into Heroku without using worker (I'm using Python)?

A: Use the Heroku scheduler addon to trigger your function every hour, it's free and it doesn't require a dedicated worker.
You just need to make sure it's callable from a single file (i.e. python do_something.py)


text:
Q: On batch size, epochs, and learning rate of DistributedDataParallel I have read these threads [1] [2] [3] [4], and this article.
I think I got how batch size and epochs works with DDP, but I am not sure about the learning rate.
Let's say I have a dataset of 100 * 8 images. In a non-distributed scenario, I set the batch size to 8, so each epoch will do 100 gradient steps.
Now I am in a multi-node multi-gpu scenario, with 2 nodes and 4 GPUs (so world size is 8).
I understand that I need to pass batches of 8 / 8 = 1, because each update will aggregate the gradients from the 8 GPUs. In each worker, the data loader will load still 100 batches, but each of 1 sample. So the whole dataset is parsed exactly once per epoch.
I checked and everything seems like that.
But what about the learning rate?
According to the official doc

When a model is trained on M nodes with batch=N, the gradient will be
M times smaller when compared to the same model trained on a single
node with batch=M*N if the loss is summed (NOT averaged as usual)
across instances in a batch (because the gradients between different
nodes are averaged). [...] But in most cases, you can just treat a
DistributedDataParallel wrapped model, a DataParallel wrapped model
and an ordinary model on a single GPU as the same (E.g. using the same
learning rate for equivalent batch size).

I understand that the gradients are averaged, so if the loss is averaged over samples nothing changes, while if it is summer we need to account for that. But does 'nodes' refer to the total number of GPUs across all cluster nodes (world size) or just cluster nodes? In my example, would M be 2 or 8? Some posts in the threads I linked say that the gradient is divided 'by the number of GPUs'. How exactly is the gradient aggregated?

A: Please refer to the following discussion:
https://github.com/PyTorchLightning/pytorch-lightning/discussions/3706
"As far as I know, learning rate is scaled with the batch size so that the sample variance of the gradients is kept approx. constant.
Since DDP averages the gradients from all the devices, I think the LR should be scaled in proportion to the effective batch size, namely, batch_size * num_accumulated_batches * num_gpus * num_nodes
In this case, assuming batch_size=512, num_accumulated_batches=1, num_gpus=2 and num_noeds=1 the effective batch size is 1024, thus the LR should be scaled by sqrt(2), compared to a single gpus with effective batch size 512."


text:
Q: ArrayList Length I'm having trouble getting the arraylist length to show in my for loop. I'm a beginner/novice with programming so I might be completely off base here. The output for the ArrayList is showing up as 0. What I'm trying to do it compare a string from a jTextBox with an arraylist and see if the String exists within the List.
public static void ValidateProtocolCompatiblity(FAS_Define[] faslist, String selectedProtocol, String selectedFAS){
     for (int index=0; index < faslist.length;index++){
        if (faslist[index].getName() == selectedFAS)
            for (int j=0; j < faslist[index].getSupportedProtocol().toArray().length;j++){
                fasProtocolList.add(faslist[index].getSupportedProtocol().toString());

            }
    }

Here is my original array list based on the constructor
        FAS_Define[] fasList = new FAS_Define[10];
        fasList[0] = new FAS_Define("FAS2552", new ArrayList(Arrays.asList("iSCSI", "FCoE")));

        ValidateProtocolCompatiblity(fasList,protocolField, fasField);

Class for the getter/setter/constructor outlining the original array list
public class FAS_Define {
private int id;
private String name;
private List<String> supportedProtocol;

private static int numberofDevice = 0;

public FAS_Define(String cName, ArrayList<String> cSupportedProtocol){
    this.name = cName;
    this.supportedProtocol = new ArrayList<String>();

    numberofDevice++;
    id = numberofDevice;
}
public String getName(){return name;}
public void setName(String name){this.name = name;}

public List<String> getSupportedProtocol(){return supportedProtocol;}
public void setSupportedProtocol(List<String> supportedProtocol){this.supportedProtocol = supportedProtocol;}

A: Instead of
faslist[index].getSupportedProtocol().toArray().length

Use:
faslist[index].getSupportedProtocol().size()

There's no need to convert the arrayList to array. And for getting the element of the array list at a given index, use:
faslist.get(index).getSupportedProtocol().toString()

Instead of
faslist[index].getSupportedProtocol().toString()


text:
Q: HTML table rounded corner I am new to HTML and CSS. I want to achieve rounded-corner for my table and it is not working. Any ideas how can I make it work?
Here is my CSS for table:
    table {
        border: 1px solid #CCC;
        border-collapse: collapse;
        font-size:13px;
        color:white;
    }

    td {
        border: none;
    }

Currently, it looks like this:

And I want the corner of the table to be rounded.
Many thanks.

A: You can make the rounded table using the border-radius CSS attribute based on border-collapse: separate as follows.

table {
  border: 1px solid #CCC;
  font-size: 13px;
  color: white;

  background: red;

  border-collapse: separate;
  border-radius: 10px;
  -moz-border-radius: 10px;
}

td {
  border: none;
}

    Hello World
    Hello World
    Hello World
    Hello World
    Hello World

    Hello World
    Hello World
    Hello World
    Hello World
    Hello World

    Hello World
    Hello World
    Hello World
    Hello World
    Hello World

    Hello World
    Hello World
    Hello World
    Hello World
    Hello World

A: Use border radius on the table.
 table {
        border: 1px solid #CCC;
        border-collapse: collapse;
        border-radius: 20%;
        font-size:13px;
        color:white;
    }

    td {
        border: none;
    }

A: you need to give border-radius to make table border rounded so try this :
table {
        border: 1px solid #CCC;
        border-radius:50px;
        border-collapse: collapse;
        font-size:13px;
        color:white;
    }

    td {
        border: none;
    }


text:
Q: How do I break line sequence of images on Reactstrap? I am using Reactstrap to make this column of 3 elements, and I don't know how to renderize my fourth element downside my first (breaking the line). I already tried to adjust my width and that happens: the element goes away forward infinite.
Here is the code of my black div, which I'm trying to make to hold all of the elements created (max: 3).
<div className="align-items-center bg-dark">

The another divs (sons) are being renderized as list-inline and list-inline-item.


text:
Q: Access Upload Data Error I have a form on MS Access, where I am trying to upload an excel spreadsheet into the database.
It has been working for other spreadsheets, but for some reason I am trying to upload data into a table, and I continue to get the error:
"you cannot record changes because a value you entered violates the settings defined for this table or list (for example, a value is less than the minimum or greater than the maximum). correct the error and try again"
Can someone explain to me why I am getting this error, and how to fix it?
I have already made sure that:
- In the access table, there are no "required" fields
- The appropriate data type is associated to the field


text:
Q: django AJAX POST request is showing 500 error? MY ajax code is
   $(function(){
        $('#search').keyup(function(){
        $.ajax({
       type:"POST",
       url:"/abc/search/",
       data:{'search_text':$('#search').val(),
              'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val(),
       },
       success: searchsuccess,
       datatype: 'html'
     });
   });
 });

 function searchsuccess (data, textStatus, jqXHR){
 $('#search_result').html(data);
}

my view is
def search_college(request):
if request.method == 'POST':
    search_text=request.POST['search_text']
else:
    search_text = ""
colleges = Collage.objects.filter(col_name__contains=search_text)
render(request, "ajax_search.html", {'colleges': colleges})

my Form is-
             <form>{% csrf_token %}
            <input type="text" id="search" name="search">
            </form>

I am 500 (internal server error ) after ajax post call? How can i solve it??


text:
Q: Re-'new' TCHAR* array will a re-new of a TCHAR* array has negative/undefined effect? Or even maybe not recommended? Below code has been working fine so far. Need inputs. Thanks!
//e.g.
TCHAR *tc1 = new TCHAR[1];

// later:

//resize TCHARs
tc1 = new TCHAR[size1];
tc1[size1] = { L'\0' };

A: This is a memory leak. You need to delete anything created by a new call. If you do that, everything is fine:
//e.g.
TCHAR *tc1 = new TCHAR[1];

// later:

//resize TCHARs
delete [] tc1;
tc1 = new TCHAR[size1];
tc1[size1] = { L'\0' };

Although on an unrelated note, your last line is writing behind the array you allocated. That's not fine. But it has nothing to do with your allocation of memory, it's a mistake on it's own.
A lot of this can be avoided if you use a string class. Either std::string or if you are using the MFC, CString.

A: The negative effect of the "re-newing" is that you lose the pointer to the free-store memory originally allocated. It will remain occupied throughout the rest of your program, without any chance to reclaim it.
Of course, you may have some other pointer pointing to the memory, but that would be a very strange and unnecessarily complex piece of code.
Avoid all those problems by using std::vector instead of new[].

tc1 = new TCHAR[size1];
tc1[size1] = { L'\0' };

In addition to the memory leak, this is undefined behaviour because size1 is one past the last valid index.

Here's a std::vector example:
std::vector<TCHAR> tc1(1);

// later:

//resize TCHARs
tc1.resize(size1);
tc1[size1 - 1] = L'\0';

Perhaps even std::string or std::wstring is sufficient for your needs.


text:
Q: Given an array of N elements. The task is to check if the elements in the array are first strictly increasing then strictly decreasing
*

*Example:
Input: arr[] = [-3, 9, 11, 20, 17, 5, 1]
Output: YES

Input: arr[] = [5, 6, 7, 8, 9, 10, 1, 2, 11]
Output: NO
I tried with method but its throwing error as list index out of range.
And also do i need to increment 'i' in every iteration?
def checkType(arr,n):
  for i in range(len(arr)):
    #print(i)
    if (arr[i]<=arr[i+1]): #and (arr[n-1]<=arr[n-2]):
      print('YES')
    else:
      print('NO')
if __name__ == "__main__" :
  arr=[-3, 9, 11, 20, 17, 5, 1]
  n=len(arr)
  checkType(arr,n)

IndexError: list index out of range

A: You could do it like this:-
arr = [-3, 9, 11, 20, 17, 5, 1]

if sorted(arr) == arr or sorted(arr, reverse=True) == arr:
  print('The array is ordered - either ascending or descending')
else:
  print('The array is not ordered')

A: Try this code below:
arr = [-3, 9, 11, 20, 17, 5, 1]
lst = [x - y for x, y in zip(arr, arr[1:])]
y = 1
value = 'YES'
for i in lst:
    if ((i < 0) != y) and (y == 1):
        y = 0
    elif ((i < 0) != y) and (y == 0):
        value = 'NO'
        break
print(value)

Output:
YES


text:
Q: Ошибка в обновлении рекламных обьявлений Использую метод для редактирования объявлений.
В ответ получаю вот такую ошибку:
 ["error_code"]=>100
 ["error_msg"]=>"One of the parameters specified was missing or invalid: data[data][ad_id] is invalid"

Сам массив data:
string(185) "{"data":{"0":{"ad_id":"15142751","cpc":4.4},"1":{"ad_id":"15142643","cpc":4.4},"2":{"ad_id":"15210287","cpc":4.4},"3":{"ad_id":"15210280","cpc":4.4},"4":{"ad_id":"15210269","cpc":4.4}}}"

ID объявлений верны, скорее всего я неврно формирую массив объектов.
  $data = json_encode(array('data' => $data), JSON_FORCE_OBJECT);

Полный ответ с ошибкой:
 array(1) {
  ["error"]=>
  array(3) {
    ["error_code"]=>
    int(100)
    ["error_msg"]=>
    string(84) "One of the parameters specified was missing or invalid: data[data][ad_id] is invalid"
    ["request_params"]=>
    array(5) {
      [0]=>
      array(2) {
        ["key"]=>
        string(5) "oauth"
        ["value"]=>
        string(1) "1"
      }
      [1]=>
      array(2) {
        ["key"]=>
        string(6) "method"
        ["value"]=>
        string(13) "ads.updateAds"
      }
      [2]=>
      array(2) {
        ["key"]=>
        string(10) "account_id"
        ["value"]=>
        string(10) "xxxxxxxxxx"
      }
      [3]=>
      array(2) {
        ["key"]=>
        string(4) "data"
        ["value"]=>
        string(151) "{"data":[{"ad_id":22981362,"cpc":4.4},{"ad_id":22975854,"cpc":4.4},{"ad_id":22721708,"cpc":4.4},{"ad_id":26690417,"cpc":0},{"ad_id":22690359,"cpc":0}]}"
      }
      [4]=>
      array(2) {
        ["key"]=>
        string(1) "v"
        ["value"]=>
        string(4) "5.62"
      }
    }
  }
}

A: *

*account_idAdvertising account ID required parameter, int (number) А у вас нет.

*Из документации:  ad_id integer, required  А вы строки отдаете.

*И для чего используете , JSON_FORCE_OBJECT? API  хочет массив объектов dataSerialized JSON array of objects that describe changes in ads.
Похоже что API, ждет:
// $data = json_encode(['data' => json_encode($data)]);
{
    "data": '[{"ad_id": 123,"cpc":4.4},{"ad_id": 321,"cpc":7.7}]',
    "account_id" : 123
}

А у вас:
{
    "data": {
        "1": {"ad_id": "123","cpc":4.4},
        "2": {"ad_id": "321","cpc":7.7}
    }
}


text:
Q: why cannot coerce type 'S4' to vector of type 'integer'? Can anyone tell me why I am getting this error:
Error in as.integer(tm) : cannot coerce type 'S4' to vector of type 'integer?
I have been searching the internet but couldn't solve my problem.

      library(Matrix)
     long <- file("C:\\New folder (5)\\inra.bin", "rb")
     A=readBin(long, integer(), size=2,n=67420*1, signed=F)
    ta<-t(A)
  lot <- file("C:\\New folder (5)\\lat.img", "rb")
    B=readBin(lot, integer(), size=2,n=67420*1, signed=F)
     tb<-t(B)
       wind <- file("C:\\Wind_WFD_200201.bin", "rb")
       C=readBin(wind, double(), size=4,n=67420*248, signed=TRUE)
        D<-matrix(C,nrow=248,ncol=67420)
         for(d in 1:31)
       {
        M <- Matrix(-9999, 360, 720)
         tm<-t(M)
       for(i in 1:67420)
       {
    tm[ta[i],tb[i]]= 10 * ((D[(d-1)*8+1,i] + D[(d-1)*8+2,i] +D[(d-1)*8+3,i] +D[(d- 1)*8+4,i] +D[(d-1)*8+5,i] +D[(d-1)*8+6,i] +D[(d-1)*8+7,i] +D[(d-1)*8+8,i] ) / 8)

 }###gooooooood
 to.write <- sprintf("C:\\Yar_%0d.bin", d)
 writeBin(as.integer(tm), size=2,to.write)

}

A: Take a look at How to split and write to a file for S4 object in R .  In your case, it appears that Matrix returns an S4 object.  Try this:
foo <- Matrix(10,10,10)
slotnames(foo)

That may give a suggestion as to what you want to extract from your tm object.
But why are you using Matrix in the first place?  If you just use base::matrix this problem should disappear.
Edit: peeking at the documentation for package Matrix, it's clear that as.integer is not supported.  You probably would have to use as(x,matrix) first.


text:
Q: Retrieve SSL session id in asp.net Is there any way to retrieve the SSL session Id serverside in asp.net?

A: the short answer is no.  This is an intentional limitation of IIS, so as to prevent people from taking a dependency on something that isn't dependable.
Out on the market, you will find various hardware load-balancers that will offer features like server persistence based on SSL Session ID, but they don't work very well because SSL renegotiation can happen at any time.  In Internet Explorer 8, for example, a new SSL session is negotiated for every tab that is opened to a web site.  You can expect similar behaviour from other multi-process browsers.  So, I must stress that you should not use SSL Session ID for any kind of user identification purposes.
That said -- If you really need the SSL Session ID information for some specialized task, I recommend using Apache, mod_ssl and mod_proxy as a front-end to your IIS system.  With a bit of fiddling, you could coerce mod_ssl into giving you the session ID, which you could then add to a proxied request to your IIS server as a query string parameter.... or you could store it in a database.

A: Tim,
Are you really "just" trying to retrieve the Session ID string or do you maybe lose all session information when switching to SSL? this would be a quite common problem, because the session on serverside is lost when using "InProc" session storage, and the session cookie on the client might be lost when not stored in a common domain.
Therefore, you should switch to state server or sql server session management in Web.config file, for example:
<sessionState mode="SQLServer"
   cookieless="true"
   regenerateExpiredSessionId="true"
   timeout="30"
   sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;"
   stateNetworkTimeout="30" />

Beside that, I don't really know why you shouldn't be able to retrieve HttpContext.Current.Session.SessionID also in SSL mode as well.
Some MSDN Links:

*

*MSDN: HttpSessionState.SessionID Property

*MSDN: ASP.NET Session State Overview
Maybe this helps somehow.
Best regards


text:
Q: ListView not updating after item class is modified in swiftui I have a list view of Task items. Every 10 seconds a timer triggers the function randomTasks that is responsible to modify the title and the description of each tasks in the list but the ListView doesn't reflect the changes.I tried to use objectWillChange.send() but it doesn't work.
I've noticed that when a task is modified with a different id the ListView updates and I can see the changes but when i'm in the detail view whenever randomTaskTitle is triggered the view is dismissed automatically.
class Task {
    var id: String = UUID().uuidString
    var title: String
    var description: String

    init(title: String, description: String) {
        self.title = title
        self.description = description
    }
}

import SwiftUI

struct TasksView: View {

    @EnvironmentObject var viewModel: TasksViewModel

        let timer = Timer.publish(every: 10, on: .main, in: .common).autoconnect()

    var body: some View {

        NavigationView {
          List {
            ForEach(viewModel.tasks, id: \.id) { task in
               NavigationLink(
                  destination: DetailView(task: task)
               ) {
                  VStack {
                    Text(task.title)
                    Text(task.description)
                  }
               }
          }
        }
        .onReceive(timer) { time in
            Task {
                await viewModel.randomTasks()
            }
        }

    }
}

struct TasksViewNew_Previews: PreviewProvider {
    static var previews: some View {
        TasksView()
    }
}

import Foundation

@MainActor
class TasksViewModel: ObservableObject {

    @Published var tasks = [Task]()

    init() {
      self.tasks = [Task(title: "TaskA", description: "DescriptionA"),
                    Task(title: "TaskB", description: "DescriptionB"),
                    Task(title: "TaskC", description: "DescriptionC"),
                    Task(title: "TaskD", description: "DescriptionD"),]
    }

    func randomTasks() {
      tasks.forEach { task in
        task.title = randomTitleTask()
        task.description = randomDescriptionTask()
      }
    }

}

A: try something simple like this, that works well for me:
@MainActor
class TasksViewModel: ObservableObject {

    @Published var tasks = [Task]()

    init() {
        self.tasks = [Task(title: "TaskA", description: "DescriptionA"),
                      Task(title: "TaskB", description: "DescriptionB"),
                      Task(title: "TaskC", description: "DescriptionC"),
                      Task(title: "TaskD", description: "DescriptionD"),]
    }

    func randomTasks() {
        tasks.forEach { task in
            task.title = randomTitleTask()
            task.description = randomDescriptionTask()
        }
        objectWillChange.send()   // <--- here
    }
}

struct TasksView: View {
    @EnvironmentObject var viewModel: TasksViewModel
    let timer = Timer.publish(every: 10, on: .main, in: .common).autoconnect()

    var body: some View {
        NavigationView {
            List {
                ForEach(viewModel.tasks, id: \.id) { task in
                    NavigationLink(destination: DetailView(task: task)) {
                        VStack {
                            Text(task.title)
                            Text(task.description)
                        }
                    }
                }
            }
            .onReceive(timer) { time in
                // no need for Task here since randomTasks is not an async
                viewModel.randomTasks()  // <--- here
            }
        }
    }
}

A: The @Published array from classes does not know when your objects have changed. It can only keep track of when you add/remove them.

*

*You can tell your ObservableObject that something has changed explicitly by calling objectWillChange.send() before your modifications

objectWillChange.send()
tasks.forEach { task in
    task.title = UUID().uuidString
    task.description = UUID().uuidString
}

*Convert your class into a struct, and change items by index, like

tasks.indices { i in
    tasks[i].title = UUID().uuidString
    tasks[i].description = UUID().uuidString
}

*Check out ObservableArray from this answer

A: Instead of @ObservedObject use @StateObject


text:
Q: Is this a privacy concern when adding URL to footnote when generating PDF? I am writing a completely anonymous PDF criticism to a paper, and I added a footnote which links to a video to support my arguments. However, when I click on the link in Adobe Reader, a warning is created which shows the path of link and the path contains my FIRST AND LAST NAME (blanked out and truncated).  I can reproduce this privacy intrusion on multiple other PDF readers such as SumatraPDF.
Is this a warning that is only displayed to my system or is it displayed for anyone who sees the PDF? Why would the entire path be embedded for the hyperlink?

A: Use \href{<URL>}{<text>} instead of only \url, as in
\href{http://youtube.com/watch?v=aztd}{\texttt{youtube.com/watch?v=aztd}}

with an explicit http:// protocol directive.


text:
Q: Can't Open Page in New Tab Using Javascript I can't figure out how to open a new tab using JavaScript. I went through related questions but nothing worked for me. I want the browser to open a new tab when someone clicks on the link (example.com) below. What code should I add and where should I place that code?
My html code is here -

Thank you in advance.

A: Use the attribute newtab on the a element.
Code for driver for newtab a attribute:
(()=>{document.getElementsByTagName("a").map((e)=>{if(e.newtab==="newtab"){e.target="_blank";e.rel="noopener noreferrer";}return e;});})();

Beautified version without an anonymous function:
document.getElementsByTagName
(
  "a"
).map
(
  (e) =>
  {
    if (e.newtab === "newtab") {
      e.target = "_blank";
      e.rel = "noopener noreferrer";
    }
    return e;
  }
);

  You can only put the compressed version on your page due to uncompressed-code checking.


text:
Q: Tower of Hanoi - n peg solution algorithm I was implementing the tower of hanoi problem to understand more about recursion. I was able to implement it using the 3 peg case, however, when I wanted to use more pegs (to generate less moves) I understand the Frame-Stewart solution where I have to break the number of disks I have and stack onto one peg and never touch that peg while I am transferring disks from the source peg to the destination pegs with all the intermediate pegs. However, I don't understand how write something like move(disks, 1, i, {2...K}) as a function. How can I write the names of all the pegs in the function prototype when I don't even know them from the beginning? I have given below what I worked up for the 3 disk solution, but I need help with the more general case.
// private member function: primitive/basic move of the top disk
    // from the source peg to the destination peg -- and legality-check
    void move_top_disk(int source, int dest)
    {
        cout << "Move disk " << towers[source].front() << " from Peg ";
        cout << source+1 << " to Peg " << dest+1;
        towers[dest].push_front(towers[source].front());
        towers[source].pop_front();
        if (true == is_everything_legal())
            cout << " (Legal)" << endl;
        else
            cout << " (Illegal)" << endl;
    }

    // private member function: recursive solution to the 3 Peg Tower of Hanoi
    void move(int number_of_disks, int source, int dest, int intermediate)
    {
        if (1 == number_of_disks)
        {
            moves++;
            move_top_disk (source, dest);
        }
        else
        {
            moves++;
            move (number_of_disks-1, source, intermediate, dest);
            move_top_disk (source, dest);
            move (number_of_disks-1, intermediate, dest, source);
        }
    }

I don't understand what kind of changes I would need to make to my "move" function to solve for a 6 pegs case. Thanks

A: You will need to modify the last block of code, where it does move, move-top-disk, move.
And here is the article regarding solution of Hanoi towers for N pegs: Towers of Hanoi with K pegs


text:
Q: Mock Grails Spring Security Logged in User Looking for a way to mock spring security in some unit/integration tests.

*

*Grails: V2.1.0

*Spring Security Core: V1.2.7.3

Controller has the following:
// some action
def index(){
   def user = getLoggedInUser()
   render ....
}
...

private getLoggedInUser(){
    return User.get(springSecurityService.principal.id)
}

I tried the following and various other ways but can't see to get it to work:
void testSomething(){
    def dc = new SomeController()
    dc.springSecurityService = [
            encodePassword: 'password',
            reauthenticate: { String u -> true},
            loggedIn: true,
            principal: [username:"Bob"]]
    dc.index()
    ... assertion....

It seems that the user is not getting created and can't get the principal.id. Any suggestions or better alternatives?

A: I think the user is just being created, but not saved, and that's why it doesn't have an ID.
The solution could be this:
void testSomething(){
    def dc = new SomeController()
    def loggedInUser = new User(username: "Bob").save() // This way the user will have an ID
    dc.springSecurityService = [
        encodePassword: 'password',
        reauthenticate: { String u -> true},
        loggedIn: true,
        principal: loggedInUser]
    dc.index() ... assertion....

There's an alternative:
void testSomething(){
    def dc = new SomeController()
    def loggedInUser = new User(...).save()
    dc.metaClass.getLoggedInUser = { loggedInUser }
...

I would suggest a refactor to getLoggedInUser:
private getLoggedInUser(){
    return springSecurityService.currentUser
}

With this change, you could write:
void testSomething(){
    def dc = new SomeController()
    def loggedInUser = new User(...).save()
    dc.springSecurityService = [
        encodePassword: 'password',
        reauthenticate: { String u -> true},
        loggedIn: true,
        getCurrenUser: { loggedInUser }]
...


text:
Q: Microsoft.Speech.Synthesis выдает ошибку "Исключение из HRESULT: 0x8004503A" Создаю через C# Microsoft.Speech.Synthesis;
SpeechSynthesizer ss = new SpeechSynthesizer();
ss.SetOutputToDefaultAudioDevice
ss.Speak("hello");

И выдает ошибку

System.IO.FileNotFoundException: "Исключение из HRESULT: 0x8004503A"

я брал пример с Написать синтез речи


text:
Q: Unable to resolve XXX. Where no service registrations found and number of Rules.FallbackContainers: 0 and number of Rules.UnknownServiceResolvers: 0 My app gets error in last line:
 var ioc= new DryIoc.Container();
 var Task = DryIoc.Resolver.Resolve<XXX>(ioc);

Error received:

Unable to resolve XXX. Where no service registrations found   and
  number of Rules.FallbackContainers: 0   and number of
  Rules.UnknownServiceResolvers: 0

My code:
class XXX: AAA
{ ...
}

A: I had to register Class first:
DryIoc.Registrator.Register(container, typeof(XXX));