text:
Q: Sinalizar caracteres que ultrapassem limite em textarea como no Twitter Possuo essa função javascript que faz a contagem de caracteres digitados numa textarea e mostra ao usuário:
function countPublishCharactersAbout(val) {
    var len = val.value.length;
    var count = 240 - len;

    if (count < 0) {
        $('#about-textarea-counter').html('' + count + '');
    } else {
        $('#about-textarea-counter').html('' + count + '');
    }
}

Dessa maneira, chamo ela usando o evento onkeyup:
<textarea class="form-control" name="" onkeyup="countPublishCharactersAbout(this)" style="resize: none"></textarea>

Ao ultrapassar o limite (nesse caso, de 240 caracteres) a contagem fica negativa e vermelha, porém quero implementar um efeito igual ao que acontece no Twitter, onde os caracteres que estejam ultrapassando o limite são sinalizados em vermelho, conforme a imagem abaixo.

A: Para teres partes do texto estilizados tens de usar uma div[contenteditable="true"]. A textarea não permite isso.
Assim podes acrescentar ao teu código .slice() para gerar partes do texto. O que está dentro dos limites (240 caracteres) e o que é longo demais.
Junto no meu exemplo uma função do Tim Down para colocar o cursor no fim da div para quando se estiver a escrever.
function countPublishCharactersAbout(element) {
    var text = element.innerText || element.textContent;
    var len = text.length;
    var count = 240 - len;
    if (count < 0) {
        $('#about-textarea-counter').html('' + count + '');
        var ok = text.slice(0, 240);
        var resto = text.slice(241);
        element.innerHTML = ok + '' + resto + '';
        placeCaretAtEnd(element);
    } else {
        $('#about-textarea-counter').html('' + count + '');
    }
}

Exemplo:

function placeCaretAtEnd(el) {
  el.focus();
  if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
    var range = document.createRange();
    range.selectNodeContents(el);
    range.collapse(false);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (typeof document.body.createTextRange != "undefined") {
    var textRange = document.body.createTextRange();
    textRange.moveToElementText(el);
    textRange.collapse(false);
    textRange.select();
  }
}

function countPublishCharactersAbout(element) {
  var text = element.innerText || element.textContent;
  var len = text.length;
  var count = 240 - len;
  if (count < 0) {
    $('#about-textarea-counter').html('' + count + '');
    var ok = text.slice(0, 240);
    var resto = text.slice(241);
    element.innerHTML = ok + '' + resto + '';
    placeCaretAtEnd(element);
  } else {
    $('#about-textarea-counter').html('' + count + '');
  }
}
.form-control {
  height: 300px;
  width: 400px;
}

.form-control span {
  background-color: #fcc;
}

jsFiddle: http://jsfiddle.net/62s11306/


text:
Q: How to make author names bold and make authors name and year in italic in-text citation, natbib apalike I want to make

*

*the authors name and year in the reference list BOLD
example:

Beasley A, Mason W. 2015. Emotional states vs. emotional words in social media. In:
Proceedings of the ACM web science conference. 1–10.

*the authors names and year in italic in intext citation, example:

The online perception reconstructed by forma mentis networks indicates that pay gaps are closely semantically related to both ''gender'' and ''gap'', thus indicating that closing the gender pay gap is key for fighting gender biases in STEM, in agreement with previous relevant studies (Ely, Ibarra & Kolb, 2011; Courey & Heywood, 2018). (used \citep here)
Leder, Steinbock & Martini (2009) take into consideration structural changes of
metamorphic malware. (used \cite here)
Where should make changes in the apalike-1.bst to get like the above examples?
My {format.names} function looks like this :
FUNCTION {format.names}
{ 's :=
  #1 'nameptr :=
  s num.names$ 'numnames :=
  numnames 'namesleft :=
    { namesleft #0 > }
    { s nameptr "{vv~}{ll}{, jj}{ f{}}" format.name$ 't :=   % last name first
      nameptr #1 >
        { namesleft #1 >
            { ", " * t * }
            { numnames #2 >
                { "" * }
                'skip$
              if$
              t "others" =
                { " \textit{et~al.}" * }
                { ", " * t * }
              if$
            }
          if$
        }
        't
      if$
      nameptr #1 + 'nameptr :=
      namesleft #1 - 'namesleft :=
    }
  while$
}

A: In addition to the four desired changes you've mentioned in your posting (make authors' names bold in formatted bib items; make year field bold in formatted bib items; render authors' surnames in italics in the citation call-outs; and render year in italics in the citation call-outs), I've spotted at least six [6!] additional changes you appear to require relative to apalike's default settings:

*

*Use , (comma) rather than the word and as the separator between authors in the formatted entries,

*Don't place a comma between an author's surname and (truncated) given name(s).

*Don't insert a . ("period", "full stop") after authors' truncated first name(s).

*Don't place parentheses around the 'year' block in the formatted entries,

*Insert : (colon) after the word "In" in the booktitle field of entries of type @incollection -- and maybe other entry types as well.

*Do not render the contents of the booktitle field in italics.
With enough time and resources, I believe that it should be possible -- though not particularly advisable -- to achieve all of these formatting objectives by hacking apalike.bst.
Before embarking on such a journey, though, you should remind yourself of the fact that apalike is really old -- it was last updated meaningfully in 1988. Its advanced age -- my apologies if this sounds needlessly ageist... -- entails (at least) three drawbacks, typographically speaking:

*

*apalike doesn't know about fields such as url, doi, isbn, and issn, which are rather commonplace these days.

*apalike doesn't work all that well with the natbib citation management package. E.g., natbib's longnamesfirst option does not work with apalike.

*The apalike bibliography style comes nowhere close to implementing current APA formatting guidelines. This non-adherence to current APA guidelines may or may not be a drawback in practice for you. However, you should at least be aware of this issue.
In view of these drawbacks and of the fact that hacking apalike might be rather tricky to pull off correctly, I believe you'd be better off learning how to use the makebst utility, which is part of the custom-bib package. The makebst utility lets users create a bespoke bibliography style file that implement all of their formatting requirements from the beginning, and in a very robust manner. The makebst utility takes you through a long sequence of questions, each with multiple-choice answers (one of which will be marked as the default). The final question will be whether you want the utility to create the bst file; do answer "y" to that question.
To get going, open a command window and type pdflatex makebst.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting strings from array takes a long time Reading a text file into an array, extracting elements and sorting them is taking a very long time.
The text file is ffmpeg console output for R128 audio analysis. I need to get the highest M and S values. Example:
[Parsed_ebur128_0 @ 0x7fd32a60caa0] t: 4.49998    M: -22.2 S: -29.9     I: -27.0 LUFS     LRA:   9.8 LU  FTPK: -12.4 dBFS  TPK:  -9.7 dBFS
[Parsed_ebur128_0 @ 0x7fd32a60caa0] t: 4.69998    M: -22.5 S: -28.6     I: -25.9 LUFS     LRA:  11.3 LU  FTPK: -12.7 dBFS  TPK:  -9.7 dBFS

The text file can be hundreds or thousands of lines long depending on the duration of the audio file being analysed
I want to find the highest M (-22.2) and S Values (-28.6) and assign them to variables M and S
This is what I am using currently:
ARRAY=()
while read LINE
do
ARRAY+=("$LINE")
done < $tempDir/text.txt

for LINE in "${ARRAY[@]}"
do
echo "$LINE" | sed -n '/B:/p' | sed 's/S:.*//' | sed -n -e 's/^.*M://p' | sed -n -e 's/-//p' >>/$tempDir/R128M.txt
done
for LINE in "${ARRAY[@]}"
do
echo "$LINE" | sed -n '/M:/p' | sed 's/I:.*//' | sed -n -e 's/^.*S://p' | sed -n -e 's/-//p' >>$tempDir/R128S.txt
done

cat $tempDir/R128M.txt
M=( $(sort $tempDir/R128M.txt) )

cat $tempDir/R128S.txt
S=( $(sort $tempDir/R128S.txt) )

Is there a faster way of doing this?

A: Rather than reading in the whole file in memory, writing bits of it out to separate file, and reading those in again, just parse it and pick out the largest values:
$ awk '$7 > m || m == "" { m = $7 } $9 > s || s == "" { s = $9 } END { print m, s }' data
-22.2 -28.6

In your data, field 7 and 9 contains the values of M and S.  The awk script will update its m and s variables if it finds larger values in these fields and then print the largest found at the end. The m == "" and s == "" are needed to trigger initialization of the values if no values has been read yet.
Another way with awk, which may look cleaner:
$ awk 'FNR == 1 { m = $7; s = $9; next } $7 > m { m = $7 } $9 > s { s = $9 } END { print m, s }' data

To assign them to M and S in the shell:
$ declare $( awk 'FNR == 1 { m = $7; s = $9; next } $7 > m { m = $7 } $9 > s { s = $9 } END { printf("M=%f S=%f\n", m, s) }' data )

$ echo $M $S
-22.200000 -28.600000

Adjust the printf() format to use %s instead of %f if you want the original strings instead of float values, or set the number of decimals you might want with, e.g., %.2f in place of %f.

A: First of all, three-process pipe is a bit redundant for a single value extraction, especially taking into account you reinstantiate it anew for every line.
Next, you save all the values into a file and then sort that file, while all you need is the maximum value. You can easily find it during the very first (value extraction) loop, for additional O(N) running time, instead of I/O and sorting with all the I/O overhead and O(NlogN) sorting expenses. See ARITHMETIC EXPANSION and conditional expressions in bash manual.


text:
Q: 400 Bad Request response to calling web api localhost/token url for generating token I have enabled cors for my web api and it works fine for all the allowanonymous methods for now
        // Enable CORS for the Angular App
        var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*");
        config.EnableCors(cors);

But when I try to access the below url from my angular app to get token, I get the response 400 Bad Request.
    const userData = 'username=' + email + '&password=' + ppassword + '&grant_type=password';
    const reqHeader = new HttpHeaders(
        {
        'Content-Type': 'application/x-www-form-urlencoded',
        'No-Auth': 'True',
        'Access-Control-Allow-Origin': '*'
    });
    return this.http.post('http://localhost:59255/token', userData, {headers: reqHeader});

How can I resolve this if at all this is an issue?

A: Posting this because more people need to see how CORS can be so tricky at times. I removed the EnableCors code completely from my WebApiConfig file. Then I added the below line in my Startup file
 public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

This resolved my issue. There is definetly an issue with the order of how cors is integrated in the application. Feel free to add more


text:
Q: При перезаписи данных в тип значения создается новая переменная или нет Например, создается переменная
int a=5;
после в коде она изменяется на a=10;
вопрос: в ячейке памяти в стеке, куда было записано 5 изменилось само значение на 10 или выделилась новая область памяти под нее и туда записалась 10 а 5 так и осталась в памяти?

A: Что касается локальных переменных, то давайте посмотрим во что превратится этот код после компиляции
int a = 5;
Console.WriteLine(a);
a = 10;
Console.WriteLine(a);

А вот во что, откомпилированный ассемблер
mov ecx, 5
call System.Console.WriteLine(Int32)
mov ecx, 10
call System.Console.WriteLine(Int32)

Никакого стека, никакой памяти не используется, используется только регистр процессора ECX. Так как регистры процессора - это то что существует всегда, то можно сказать, что выделения памяти или создания каких-либо сущностей, потребляющих дополнительные ресурсы компьютера не создается, ни в первом, не во втором случае.
Если же переменная будет членом класса
private int a;

a = 5;
Console.WriteLine(a);
a = 10;
Console.WriteLine(a);

То получится вот так
mov dword ptr [esi+4], 5
mov ecx, [esi+4]
call System.Console.WriteLine(Int32)
mov dword ptr [esi+4], 10
mov ecx, [esi+4]
call System.Console.WriteLine(Int32)

[ESI+4] - это адрес ячейки памяти, где лежит a. Как видно, происходит перезапись участка оперативы, новой памяти не выделяется.


text:
Q: Shortcut target path via VBScript I am trying correct a shortcut target path for MS Access using a registry key and the file location on a network share.
App Path of MS Access via Registry:

C:\Program Files\Microsoft Office 15\Root\Office 15\MSACCESS.EXE

Network location of Database:

\\H00t0000vfsrv03\Share\Folder\Database.MDB

I can not get shortcut path to take, gives me

Invalid procedure call or argument, 800A0005.

Code:
Set WSHShell = CreateObject("WScript.Shell")

ServerPath = Chr(32) & "\\H00t0000vfsrv03\Share\Folder\Database.MDB"

If Not WSHShell Is Nothing Then
    DesktopPath = WSHShell.SpecialFolders("Desktop")
    InstallRoot = Chr(34) & WSHShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\MSACCESS.EXE\") & Chr(34)
    TargetName  = InstallRoot & ServerPath
    WScript.Echo TargetName

    CommandName = TargetName
    wscript.echo CommandName
    Set MyShortcut = WSHShell.CreateShortCut(DesktopPath & "\Shorcut" & ".lnk")
    MyShortcut.TargetPath = TargetName
    WScript.Echo MyShortcut.TargetPath
    MyShortcut.WindowStyle = 1
    MyShortcut.Arguments = ""
    MyShortcut.Save
    Set MyShortcut = Nothing
End If

I have added
shortcut.Targetpath = """C:\Program Files\Microsoft Office 15\Root\Office 15\MSACCESS.EXE"" H00t0000vfsrv03\Share\Folder\Database.MDB"

and this last line does not work.  The App Path can vary depending on the MS Access Office version.  Trying to get the correct number of double quotes so that the shortcut can be mapped.

A: Although the .MDB extension is probably associated to MsAccess, I understand you want a shortcut to explicitely use the installed MsAccess.exe to avoid getting into trouble where a user has changed this to some other application.
When creating a shortcut like this, you need to fill in the correct values for the different properties.
The shortcuts TargetPath should be "C:\Program Files\Microsoft Office 15\Root\Office 15\MSACCESS.EXE"
The shortcuts Arguments  should be "\\H00t0000vfsrv03\Share\Folder\Database.MDB"
As you are doing it now, you are trying to set the TargetPath to
"C:\PROGRA~2\MICROS~1\Office15\MSACCESS.EXE" \\H00t0000vfsrv03\Share\Folder\Database.MDB

Try this
Option Explicit

Dim WSHShell
Set WSHShell = CreateObject("WScript.Shell")

If Not WSHShell Is Nothing Then
    Dim ServerPath, DesktopPath, InstallRoot, MyShortcut
    ServerPath  = Chr(34) & "\\H00t0000vfsrv03\Share\Folder\Database.MDB" & Chr(34)
    DesktopPath = WSHShell.SpecialFolders("Desktop")

    'get the long path for MSACCESS.EXE
    InstallRoot = WSHShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\MSACCESS.EXE\Path")
    'there SHOULD be a backslash at the end, but check anyway
    If Right(InstallRoot, 1) <> "\" Then InstallRoot = InstallRoot & "\"
    'add "MSACCESS.EXE" to this path and surround with double quotes
    InstallRoot = Chr(34) & InstallRoot & "MSACCESS.EXE" & Chr(34)

    'create the shortcut on the desktop
    Set MyShortcut = WSHShell.CreateShortCut(DesktopPath & "\ShorcutToDatabase" & ".lnk")
    MyShortcut.TargetPath = InstallRoot
    MyShortcut.WindowStyle = 1
    MyShortcut.Arguments = ServerPath
    MyShortcut.Save

    Set MyShortcut = Nothing
    Set WSHShell = Nothing
End if


text:
Q: Update extension to packaged app in webstore I currently have an extension published in chrome web store.
Now with some additional features, It made more sense to update that to an packaged app.
I have changed the extension to Packaged App.
Now my question is, As I want to retain my current extension users to use Packaged app, Can I directly update the zip file of the New pacakged app to the extension in the chrome store?
Will there be any hiccups in this process? Or do I have to host my new Packaged app separately in web-store (Doing this, I will lose my existing users )?


text:
Q: Get data stored time My Android application is connected to Firebase, and I retrieve data from database successfully. But my question is there is any way to get what time the data stored in ddatabase to retrieve it to my application?
I hope my question is clear.

A:
is there is any way to get what time the data stored in ddatabase

No, Firebase realtime database does not store metadata. You should create your own mechanism by storing the desired time as a timestamp in the database as explained here.


text:
Q: Drop Markers and MarkerCluster together from database I've been working on my map which gets it's details from a MySQL database.
I use MarkerCluster Plus to cluster my markers but would like to add the drop animation to it.
I found this thread, but cannot get it to work with my database.
Using Drop Markers and MarkerClusterer together?
Would anyone please be able to help me figuring out how to add the drop animation to my code? My test map is here: http://mymap.mooo.com
Really appreciate any help or pointers.
 var customIcons = {
  BOO: {
    icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
  },
  CIE: {
    icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
  }
};

var cluster =[];
var min = .999;
var max = 1.001;

function load() {
  var map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(0,28.287167),
    zoom: 3,
    mapTypeId: 'roadmap'
  });

  var infoWindow = new google.maps.InfoWindow;
  var mcOptions = {gridSize: 20, maxZoom: 19};
  // this variable will collect the html which will eventually be placed in the side_bar
  var side_bar_html = "";

  // Change this depending on the name of your PHP file
  downloadUrl("phpsqlajax_genxml2.php", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("assetno");
      var address = markers[i].getAttribute("address");
      var type = markers[i].getAttribute("type");
      var assetdesc = markers[i].getAttribute("assetdesc");
      var location = markers[i].getAttribute("location");
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat"))* (Math.random() * (max - min) + min) ,
          parseFloat(markers[i].getAttribute("lng"))* (Math.random() * (max - min) + min));
      var html = "
" + name + "
" + assetdesc + "
" + location + "
";
      var icon = customIcons[type] || {};

      setTimeout(function() {
        var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon,
            animation: google.maps.Animation.DROP
        });
        return marker;

        setTimeout(function () {
            bindInfoWindow(marker, map, infoWindow, html);
            cluster.push(marker);
            // save the info we need to use later for the side_bar
            // add a line to the side_bar html
            side_bar_html += '' + name + ' - ' + assetdesc +'<\/a>
';
        }, 1500);
      }, i * 50);

    }
    var markerCluster = new MarkerClusterer(map, cluster, mcOptions);
    // put the assembled side_bar_html contents into the side_bar div
    document.getElementById("side_bar").innerHTML = side_bar_html;
  });
}

// This function picks up the click and opens the corresponding info window
function myclick(i) {
    google.maps.event.trigger(cluster[i], "click");
}

function bindInfoWindow(marker, map, infoWindow, html) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);
  });
}

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

function doNothing() {}

A: I think I found the problem with your code. I've highlighted the line below:
setTimeout(function() {
    ...

        icon: icon.icon,
        animation: google.maps.Animation.DROP
    });

    return marker; // <---!!!!!!! This line !!!!!!!!!

    setTimeout(function () {
        bindInfoWindow(marker, map, infoWindow, html);
    ...

}, i * 50);

Calling return marker; here exits the downloadUrl function. Anything after the return statement isn't executed, so the second setTimeout is never reached and the marker is never added to the cluster.
Because your code is all in one function, the second setTimeout has access to the marker variable. Removing return marker; will allow the code contained in the second setTimeout to execute. Note that I can't test that this will fix the issue because I don't have access to your data script and link that you provided doesn't match the example code in the question. But I think it should do the trick.
Update (10/15/2012): Reply to Comment
Ok. I see two problems with your demo code.
First, remove the random number generation. I used that in my example to generate random coordinates. You seem to have lat/lng for all of your points, and multiplying them by a random number is not what you want do.
This:
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat"))* (Math.random() * (max - min) + min) ,
parseFloat(markers[i].getAttribute("lng"))* (Math.random() * (max - min) + min));

Should be:
var point = new google.maps.LatLng(
    parseFloat(markers[i].getAttribute("lat")),
    parseFloat(markers[i].getAttribute("lng"))
);

Secondly, you need to add the markers to an instance of markerCluster. Right now, they are just being added to the array cluster. Either make cluster a markerClusterer instance, or instantiate another variable to use as your markerClusterer instance. For example:  var mc = new MarkerClusterer(map);. Then use mc.addMarker(marker); to add a marker to the cluster in the second setTimeout.
Update (10/16/2012): Reply to 2nd Comment
Sorry--there's still one issue with your code. Because of the way JavaScript works (asynchronously) and the way your code is structured, when the first setTimeout is called, all the variables used to construct the marker (point, type, etc) are actually referencing the last item in your data. You have to break your code into smaller functions (generally a good practice to follow anyway), and use what's called a closure. More on that here: https://stackoverflow.com/questions/111102/how-do-javascript-closures-work. Here is a simplified example how this technique can be used to implement marker animation + markerClusterer: http://jsfiddle.net/WASLk/2/.
Note that I didn't need to do this in my original example because all the data used to build the markers (the random coordinates) was contained within the addMarker function.

A: A blog post from the Author that answered the question you linked to seems to have it figured out.
Looks like you need to add a setTimeout function and return the marker and add it to the cluster.

You may notice that to get the marker animations to work, the map
  attribute of the marker must be set. If not, the marker won't be added
  to the map, and therefore, there will be no animation. However, if you
  set the map and animation for the marker, when you add the marker to
  the cluster, the cluster takes control of the marker being added to
  the map and the animation is lost. To integrate marker animation and
  clustering, you first have to add the marker to the map, then, after
  the animation plays out, add the marker to the cluster. This is
  accomplished by returning the marker object from the addMarker
  function and then adding the marker to the cluster.


text:
Q: Bigquery BQ Alerts for Slots and Query concurrency I'm trying to establish email alerts at a project level to send email alerts for when a certain number of query/job concurrency is reached e.g. 5 concurrent queries. We have a flat-rate pricing model.
I want to do a similar email notification when total slot Usage exceeds a certain threshold as well e.g. slot usage reaching 1000 slots
As a next step I would like to throttle new incoming queries based on the above mentioned thresholds. Meaning if there are already for example 5 queries actively running the 6th one will be put on hold until one of the 5 running earlier have completed.

A: You may create an Alert Policy in which you can set your desired metric type (eg. slots) and then configure your desired threshold similar to below.

In creating an Alert Policy you may also configure the notification channel to email notification which is also included on the same documentation.
For the available metric types for SLOTS in BigQuery, you may refer to this  Google Cloud Metrics for BigQuery documentation.
For your next step, you may code (python, node.js, etc) using BigQuery API to count queries actively running (through JOB ID) and when the count hits 5, you may print "query queue is full" and then wait for the total JOBS to hit below 5 before running the next query. You may refer to this BigQuery Managing Jobs API Documentation.


text:
Q: Creation of dynamic site collection and sub-sites We are having an enterprise system where organization wide operations are maintained. Recently we decided to provide collaboration features for each operation maintained in the system using SharePoint 2013, since that enterprise system did not provide any social/collaboration features.
Assumptions/constraints -

*

*Every year 2500 operations are created

*Each operation can have documents and other content scaling upto 5 GB.

*Only SharePoint provider hosted apps are allowed to build the solution

For seamless integration, we are creating an automation component which will a SharePoint provision site automatically when an Operation is created in the enterprise system (we will get the trigger through web services)
Proposed solution -
After going through Software boundaries and limits for SharePoint 2013, I'm thinking of proposing this architecture -

*

*A windows service will be created which will accept the trigger and
take care of provisioning the entire site

*A maximum of 700 sites will be created per site collection (based on the size calculations and keeping some buffer)

*Once a site collection hits 700 sub-sites, a new site collection is automatically created for provisioning the new sites

*Provision the apps and add them to site pages using powershell/CSOM

Kindly let me know if this approach is effective or any major road-blocks we need to take care of in this.


text:
Q: Advanced Custom Fields is slow on admin screens I'm using ACF to set a series of slots in my page. So the admin screen contains a series of Flexible fields, each of which can be one of the following:

*

*Post

*Category

*Tag

Works great on the front end. I can drag-and-drop, choose posts/categories/tags etc. from the database and generally have a good time.
Unfortunately when trying to add a new slot to the page on the back end, or load it, the time taken to add a new row is killing it. I've only got a few rows there, but it's already taking unacceptably long; I'm fairly sure when I add a few more we'll start getting  timeouts.
The only information I can find about this problem is this support thread on the ACF forums (https://support.advancedcustomfields.com/forums/topic/slow-backend-v-2-5-7/), which basically says:
Yeah, if you've got a big database and try and use flexible fields it's gonna do that.
I'm also using ACF-JSON to no noticeable effect.
Has anyone else experienced this problem? What did you do to work around it? Or did you have to abandon?
(Ideally my solution would keep flexible fields, as they're exactly what the client wants in this situation - but if there's another solution that enables them to edit the back end in linear time, I'm interested in that too.)

A: It's due to the way ACF loads its repeater fields and flexible fields. All layouts in flexible fields are loaded into the dom and hidden, and an absolute ton of javascript logic is applied to all of them. When you click to add a new "slot", it runs a clone of the hidden layout, and attaches all the necessary event handlers to the clone.
If you check the timeline for page DOMContentLoaded vs load (final render event), DOMContentLoaded is actually pretty fast most of the time, but load (everything that happens after the html is loaded) is what eats up most of that time, and memory.
Best I've been able to do is activate the new "Delay Initialization" option for WYSIWYG content fields, and disable "Stylized UI" and "AJAX" options for select, checkbox, and radio fields.
Ultimately, the biggest issues come from having deeply nested repeaters/flexfields inside repeaters/flexifields. Avoid nesting those as much as you can and page load time will decrease significantly.

A: If you are using any extensions that need access to the fields on any page, for example LastPass. Disabling that extension will speed up the page alot.


text:
Q: How to properly print a list of unicode characters in python? I am trying to search for emoticons in python strings.
So I have, for example,
em_test = ['\U0001f680']
print(em_test)
['']
test = 'This is a test string '
if any(x in test for x in em_test):
    print ("yes, the emoticon is there")
else:
    print ("no, the emoticon is not there")

yes, the emoticon is there

and if a search em_test in

'This is a test string '

I can actually find it.
So I have made a csv file with all the emoticons I want defined by their unicode.
The CSV looks like this:

\U0001F600
\U0001F601
\U0001F602
\U0001F923

and when I import it and print it I actullay do not get the emoticons but rather just the text representation:
['\\U0001F600',
 '\\U0001F601',
 '\\U0001F602',
 '\\U0001F923',
...
]

and hence I cannot use this to search for these emoticons in another string...
I somehow know that the double backslash \ is only representation of a single slash but somehow the unicode reader does not get it... I do not know what I'm missing.
Any suggestions?

A: You can decode those Unicode escape sequences with .decode('unicode-escape'). However, .decode is a bytes method, so if those sequences are text rather than bytes you first need to encode them into bytes. Alternatively, you can (probably) open your CSV file in binary mode in order to read those sequences as bytes rather than as text strings.
Just for fun, I'll also use unicodedata to get the names of those emojis.
import unicodedata as ud

emojis = [
    '\\U0001F600',
    '\\U0001F601',
    '\\U0001F602',
    '\\U0001F923',
]

for u in emojis:
    s = u.encode('ASCII').decode('unicode-escape')
    print(u, ud.name(s), s)

output
\U0001F600 GRINNING FACE
\U0001F601 GRINNING FACE WITH SMILING EYES
\U0001F602 FACE WITH TEARS OF JOY
\U0001F923 ROLLING ON THE FLOOR LAUGHING

This should be much faster than using ast.literal_eval. And if you read the data in binary mode it will be even faster since it avoids the initial decoding step while reading the file, as well as allowing you to eliminate the .encode('ASCII') call.
You can make the decoding a little more robust by using
u.encode('Latin1').decode('unicode-escape')

but that shouldn't be necessary for your emoji data. And as I said earlier, it would be even better if you open the file in binary mode to avoid the need to encode it.

A: 1. keeping your csv as-is:
it's a bloated solution, but using ast.literal_eval works:
import ast

s = '\\U0001F600'

x = ast.literal_eval('"{}"'.format(s))
print(hex(ord(x)))
print(x)

I get 0x1f600 (which is correct char code) and some emoticon character (). (well I had to copy/paste a strange char from my console to this answer textfield but that's a console issue by my end, otherwise that works)
just surround with quotes to allow ast to take the input as string.
2. using character codes directly
maybe you'd be better off by storing the character codes themselves instead of the \U format:
print(chr(0x1F600))

does exactly the same (so ast is slightly overkill)
your csv could contain:
0x1F600
0x1F601
0x1F602
0x1F923

then chr(int(row[0],16)) would do the trick when reading it: example if one 1 row in CSV (or first row)
with open("codes.csv") as f:
   cr = csv.reader(f)
   codes = [int(row[0],16) for row in cr]


text:
Q: WordPress: pre_get_posts action combine date_query and meta_query In my WordPress project, I have gotten some problem.
I have many categories. The categories have a child category name New product.
Currently, I have used pre_get_posts to get the posts list in New product pages. If a post which have post_date > 2018/1/15 will be get in the category pages.
I want to add a custom checkbox keep_product in product which will keep product in New product page if post_date < 2018/1/15 when it checked.
So I think the conditions should be post_date > 2018/1/15** OR **keep_product = 1
I try to create a query, but it seem WP_Query only apply AND condition for date_query and meta_query.
function pre_get_posts_function($q){
  //Code in here
    $query->set('date_query', array(
        array(
           'after' => '2018/1/15'
        );
    ));

    $query->set('meta_query', array(
      array(
            'key' => 'keep_product',
            'value' => '1'
        )
    ));
}

I also try to create a posts_where action, but It ignores category condition. The product which is checked keep_after_60_days checkbox will be show in New product pages.
function pre_get_posts_function($q){
    //Code in here
     $query->set('date_query', array(
        array(
           'after' => '2018/1/15'
        );
    ));
    add_filter( 'posts_where', 'postmeta_new_releases',10,1);
}

function postmeta_new_releases( $where = '' ) {
    global $wpdb;
    $where .= "  OR ($wpdb->postmeta.meta_key = 'keep_product' AND $wpdb->postmeta.meta_value = 1)";

    return $where;
}

Could anyone help me. I get mad with it in some days.
Thanks!!


text:
Q: Manpage scandir() prototype weirdness I have a problem with scandir(): The manpage contains this as prototype:
int scandir(const char *dir, struct dirent ***namelist,
  int (*filter)(const struct dirent *),
  int (*compar)(const struct dirent **, const struct dirent **));

Therefore I have this:
static inline int
RubyCompare(const struct dirent **a,
  const struct dirent **b)
{
  return(strcmp((*a)->d_name, (*b)->d_name));
}

And here's the call:
num = scandir(buf, &entries, NULL, RubyCompare);

Finally the compiler says this:
warning: passing argument 4 of 'scandir' from incompatible pointer type

Compiler is gcc-4.3.2,  my CFLAGS are following:
-Wall -Wpointer-arith -Wstrict-prototypes -Wunused -Wshadow -std=gnu99

What is the meaning of this warning? The declaration of RubyCompare looks correct for me and besides the warning the code works completely.

A: Actually, there's no such constraint that you can't pass a pointer to an inline function. The inline keyword serves only as a hint to the compiler to inline calls when it can.
The problem is that the manpage for scandir() is a little misleading. The prototype in  for the 4th parameter is actually int (*cmp)(const void *, const void *).
Therefore you need to change the code like so:
static inline int RubyCompare(const void *a, const void *b)
{
    return(strcmp((*(struct dirent **)a)->d_name,
                  (*(struct dirent **)b)->d_name));
}

I'm not actually sure why you're writing this function, though, because you can use the provided alphasort compare function:
num = scandir(buf, &entries, NULL, alphasort);

A: This prototype has actually changed in recent version of GNU libc to reflect POSIX standard.
If you have code that you want to work on both old and new code, then use the __GLIBC_PREREQ  macro something like
#define USE_SCANDIR_VOIDPTR
#if defined( __GLIBC_PREREQ  )
# if  __GLIBC_PREREQ(2,10)
#  undef USE_SCANDIR_VOIDPTR
# endif
#endif

#ifdef USE_SCANDIR_VOIDPTR
 static int RubyCompare(const void *a,  const void *b)
#else
 static int RubyCompare(const struct dirent **a,  const struct dirent **b)
#endif

...

A: You're giving it a pointer to an inline function? That doesn't make sense, actually I wonder that it even compiles with only a warning.
EDIT: Chris above is right, the inline keyword is just ignored silently when it doesn't make sense / is not applicable.


text:
Q: powershell exchange : if then statement syntax? In my script i'm trying to test for true and false.  Is this syntax incorrect?
$pdaout = ""
if ($pda.ActiveSyncEnabled.tostring() -like "True") {$pdaout = "TRUE"}
if ($pda.ActiveSyncEnabled.tostring() -like "False") {$pdaout = "-"}

write-host $pdaout

A: Seems like it would be better to just check the boolean value directly instead of using ToString():
$pdaout = ""

if ($pda.ActiveSyncEnabled -eq $True) { $pdaout = "TRUE" }
else { $pdaout = "-" }

write-host $pdaout

Here is a blog post from the Windows Powershell team re: Boolean Values and Operators

A: It should be, except may be for the tostring() function (use toString() to make sure there is no issue with the case sensitivity)
Plus, you may want to use elseif to avoid doing a second test if the first one was successful:
if ($pda.ActiveSyncEnabled.toString() -like "True") {$pdaout = "TRUE"}
elseif ($pda.ActiveSyncEnabled.toString() -like "False") {$pdaout = "-"}


text:
Q: How to find median within 3-day time interval using dplyr? My data is in long format with id, day, and recorded measurement. I would like a new variable, which generates the median value within each 3 day interval (not rolling but day 1-3, 4-6, 7-9, etc).
I got as far as this using dplyr for the overall median but not sure how to code for every 3 day interval by id:
test%>%group_by(id)%>%mutate(m=median(o2))

Here is some data:
structure(list(id = c("1A", "1A", "1A", "1A", "1A", "1A", "1A",
"1A", "1A", "1A"), day = 1:10, o2 = c(40L, 70L, 100L, 100L, 30L,
35L, 30L, 30L, 40L, 40L)), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"), spec = structure(list(cols = list(id = structure(list(), class = c("collector_character",
"collector")), day = structure(list(), class = c("collector_integer",
"collector")), o2 = structure(list(), class = c("collector_integer",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector"))), class = "col_spec"))

A: Group by id and 3-day interval, and then calculate the median.
library(dplyr)

test %>%
  group_by(id, interval_id = (day-1) %/% 3) %>%
  mutate(m = median(o2))

#  id      day    o2 interval_id     m
#  <chr> <int> <int>       <dbl> <int>
# 1A        1    40           0    70
# 1A        2    70           0    70
# 1A        3   100           0    70
# 1A        4   100           1    35
# 1A        5    30           1    35
# 1A        6    35           1    35
# 1A        7    30           2    30
# 1A        8    30           2    30
# 1A        9    40           2    30
# 1A       10    40           3    40

A: We can use gl to create groups of 3 days and calculate median in each group.
library(dplyr)

test %>%
  group_by(id) %>%
  mutate(group = gl(n()/3, 3),
         group = cumsum(group != lag(group, default = first(group)))) %>%
  group_by(id, group) %>%
  summarise(med = median(o2))

#  id    group   med
#  <chr> <int> <int>
#1 1A        0    70
#2 1A        1    35
#3 1A        2    30
#4 1A        3    40

A: Since this is a good use for data.table::rleid, here is the data.table answer,
library(data.table)

setDT(dd)[, grp := gl(.N, 3, length = .N), by = id][, .(med = median(o2)), .(id, rleid(grp))]

#   id rleid med
#1: 1A     1  70
#2: 1A     2  35
#3: 1A     3  30
#4: 1A     4  40


text:
Q: Knockout 3.2 components with named templates? I'm trying to use the new components system in knockout 3.2.0.
There isn't much documentation at the moment, but this does work.
ko.components.register('price-input', {
  template: 'price-input'
})

However the template binding allows you to specify a template name that already exists in the DOM, such as:

Then you could do this:

So I tried this:
ko.components.register('price-input', {
  template: {name: 'price_input'}
})

but it doesnt work. Is there a way to use named templates with the new components, or must they be inline or loaded with AMD.
Thanks
Edit: After RP Niemeyer's answer, for clarification here is the template I tried his answer with:

Here is the component code:
ko.components.register('price-input', {
  template: {element: 'ifx_price_input'}
})

It does load the template, but treats it as an escaped string.
Ideas?

A: You can pass an element property that is either an element itself or a string that is the id of the element like:
template: { element: 'myTmpl' }

A: In v3.2.0 beta, this case wasn't handled well, hence the hackery needed by InternalFX.
This will be fixed in v3.2.0 final. It will work as you expect - simply reference a script, template, or textarea element, and its logical contents will be intepreted as template nodes.
In case you're interested, the commit that fixes and tests this is here: https://github.com/knockout/knockout/pull/1454

A: Finally solved this with some hackery...I hope this gets answered better by the knockout devs.
This works. Basically I just load the template text manually and pass it to the register function. So it works as if it was inline.
ko.components.register('price-input', {
  template: $('#ifx_price_input').html()
})


text:
Q: Change WebView url from AppDelegate I'm receiving notifications from Firebase in the AppDelegate class.
This notification contains a String named "notif_url". I've put this value in a var named "desired_url" and now I need to change my WebView url with the "desired_url" value.
But I can't access to the webview to change it url like this :
@IBOutlet weak var my_web_view: UIWebView!

func load_url(server_url: String){
    let url = URL(string: server_url);
    let request = URLRequest(url: url!);
    my_web_view.loadRequest(request);
}

load_url(server_url: desired_url);

Do you know if I can do that and if yes, how ?
Images :

EDIT  1:
After adding breakPoint to know the wrong line, it seem't that the line is this one :
my_web_view.loadRequest(request)

EDIT 2:
If need, that's a part of my AppDelegate class code.
import UIKit
import UserNotifications

import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let gcmMessageIDKey = "gcm.message_id"
    @IBOutlet weak var my_web_view: UIWebView!

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        return true
    }
}

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate{

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void){
        print("Step : 12");
        let userInfo = notification.request.content.userInfo
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey]{
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)
        var url: String = userInfo[AnyHashable("url")] as! String;
        load_url(server_url: url);

        // Change this to your preferred presentation option
        completionHandler([])
    }

    func load_url(server_url: String){
        /*
        let url = URL(string: server_url);
        let request = URLRequest(url: url!);
        my_web_view.loadRequest(request);
         */

        guard let url = URL(string: server_url) else {
            print("Invalid URL")
            return
        }

        print("TRY : "+server_url);

        let request = URLRequest(url: url)
        my_web_view.loadRequest(request)
    }
}

EDIT 3:
If need, that's my ViewController class code.
import Foundation
import UIKit
import SafariServices
import UserNotifications

class ViewController: UIViewController, UIWebViewDelegate{

    @IBOutlet weak var my_web_view: UIWebView!
    @IBOutlet weak var my_loading_view: UIView!
    @IBOutlet weak var spinner : UIActivityIndicatorView!
    @IBOutlet weak var app_logo : UIImageView!

    @IBOutlet weak var deadlinePicker: UIDatePicker!
    @IBOutlet weak var titleField: UITextField!

    var new_url: String = "";

    override func viewDidLoad(){
        super.viewDidLoad()

        let server_url = "https://www.sortirauhavre.com/";

        NotificationCenter.default.addObserver(self, selector: #selector(self.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
        rotated();

        spinner.startAnimating();

        my_web_view.scrollView.bounces = false;
        my_web_view.scrollView.isScrollEnabled = true;

        let url = URL(string: server_url);
        let request = URLRequest(url: url!);
        my_web_view.loadRequest(request);
    }

    // CETTE FONCITON SE LANCE A LA ROTATION DE L'APPAREIL
    func rotated(){
        app_logo.center = my_loading_view.center;
        let y = app_logo.frame.origin.y;
        let h = app_logo.frame.size.height
        app_logo.frame.origin.y = y-(h/2);

        spinner.center = my_loading_view.center;
    }

    // CETTE FONCTION MET EN ARRIERE PLAN L'ANNIMATION DE CHARGEMENT
    func removeLoader(){
        self.view.addSubview(my_web_view);
    }

    // CETTE FONCTION MET EN PREMIER PLAN L'ANNIMATION DE CHARGEMENT
    func addLoader(){
        self.view.addSubview(my_loading_view);
    }

    // CETTE FONCTION SE DECLANCHE QUAND LES PAGES DE LA WEBVIEW COMMENCE A CHANGER
    func webViewDidStartLoad(_ webView: UIWebView){
        addLoader();
        let server_url = "https://www.sortirauhavre.com/";
        _ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.removeLoader), userInfo: nil, repeats: false);
        if let text = webView.request?.url?.absoluteString{
            if text.hasPrefix(server_url){
            }
            else if text != ""{
                UIApplication.shared.openURL(URL(string: text)!)
                my_web_view.goBack()
            }
        }
    }

    // CETTE FONCTION SE DECLANCHE QUAND LES PAGES DE LA WEBVIEW FINI DE CHANGER
    func webViewDidFinishLoad(_ webView: UIWebView){
        let server_url = "https://www.sortirauhavre.com/";
        _ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.removeLoader), userInfo: nil, repeats: false);
        if let text = webView.request?.url?.absoluteString{
            if text.hasPrefix(server_url){
            }
            else if text != ""{
                UIApplication.shared.openURL(URL(string: text)!)
                my_web_view.goBack()
            }
        }
    }
}

A: You are force unwrapping url which is not a valid URL. I would suggest adding a guard statement to prevent the crash if a invalid URL is created:
func load_url(server_url: String) {
    guard let url = URL(string: server_url) else {
        print("Invalid URL")
        return
    }

    let request = URLRequest(url: url)
    my_web_view.loadRequest(request)
}

As you are obtaining the URL in the AppDelegate you cannot simply update the UIWebView from this class. You will need to call a function in the my_web_view's parent class which updates the URL.
// App Delegate

var serverURL: String?

func load_url(server_url: String) {
    serverURL = server_url
    let notificationName = Notification.Name("updateWebView")
    NotificationCenter.default.post(name: notificationName, object: nil)
}

// View Controller

override func viewDidLoad() {
    let notificationName = Notification.Name("updateWebView")
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateWebView), name: notificationName, object: nil)

    updateWebView()
}

func updateWebView() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let serverURL = appDelegate.serverURL

    guard let url = URL(string: serverURL) else {
        print("Invalid URL")
        return
    }

    let request = URLRequest(url: URL)
    my_web_view.loadRequest(request)
}

A: Instead of creating a new instance of your view controller, or trying to duplicate the outlet, you just need to access the current instance of your view controller. You can use either:

*

*A global value for the view controller, or

*A singleton-like pattern.

Then you can access the instance from your app delegate, by calling either myGlobalViewController.webView or ViewController.instance.webView.
So, here's an example:
import UIKit

private var thisViewController: ViewController? // Will hold the instance.

class ViewController: UIViewController {

    static var instance: ViewController {
        guard let thisViewController = thisViewController else { fatalError() } // Don't do this unless you're 100% sure that you'll never access this before the instance is loaded.
        return thisViewController
    }

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        thisViewController = self // Set the property to self.
    }
...
}

After this, you can access the web view from your app delegate:
func load_url(server_url: String){
    guard let url = URL(string: server_url) else {
        return
    }

    let request = URLRequest(url: url)
    ViewController.instance.webView.loadRequest(request)
}


text:
Q: Why we write header and footer element inside of the body element in HTML5? When we code in html5 we usually write code in this format
<!DOCTYPE html>

What Does WWF Do?

WWF's mission:

And like this
<!DOCTYPE html>

Author: Hege Refsnes

hege@example.com

My question is why we do not write them separately when all the three tags has different semantic meaning? I mean this way
<!DOCTYPE html>

 Middle stuff of the website here.

Author: Hege Refsnes

hege@example.com

A:
My question is why we do not write them separately when all the three tags has different semantic meaning?

Because the semantic meaning they have isn't what you think it is.
The  contents data about the document while the  contains the parts of the data that get rendered.
A  and  contain a header and footer for something which could be the  part of the document, or could be a
 or something else.


text:
Q: Maven 3 dependency resolution fails until maven-metadata-local.xml files are deleted [maven-invoker-plugin related] In one of my Maven projects, dependency resolution will succeed once, then fail for later build attempts:
[WARNING] The POM for commons-logging:commons-logging:jar:1.1.1 is missing, no dependency information available
[WARNING] The POM for commons-httpclient:commons-httpclient:jar:3.1 is missing, no dependency information available
[WARNING] The POM for javax.mail:mail:jar:1.4.4 is missing, no dependency information available

…and so on, until I delete the maven-metadata-local.xml files corresponding to the failing artifacts (e.g. ~/.m2/repository/commons-logging/commons-logging/maven-metadata-local.xml).  After those files are deleted, the next mvn invocation proceeds properly; the metadata files are restored by that invocation (presumably as part of the process of checking my upstream repositories/mirrors for updated artifacts), and I am again presented with the above errors until I again delete the metadata files.
This impacts multiple projects, though it appears to be limited to a particular set of dependencies.  I suppose I could go nuclear and blow away my local repo, but I'd like to understand what the problem is.
Thoughts?
Update: It looks like it's the maven-invoker-plugin (which these builds are using for general-purpose integration testing) that is producing these maven-metadata-local.xml files.  I'm not using an integration-testing-only local repo as described here, simply because doing so causes the re-downloading of all transitive dependencies (unless you want to maintain an integration-specific settings.xml file!!!).  I've used the invoker plugin with a variety of other projects in this way with good results -- certainly never encountering a wedged local repository in the process like this.
Update 2 OK, this is repeatable, even after starting with a completely fresh local repository.  This is on OS X, Java 1.6.0_24 with Maven 3.0.3; note that Maven 2.2.1 does NOT exhibit this problem.
Here's one of the projects in question: the 1.3.0-compat branch of rummage.  To reproduce:
> mvn clean test
# no error -- can run this and other builds that don't involve maven-invoker-plugin all day w/o problems
> mvn clean integration-test
# FAIL: "Could not resolve dependencies", with warnings as noted above
> mvn clean test
# FAIL: "Could not resolve dependencies", with warnings as noted above

Once the local repository is borked (by the generation of the maven-metadata-local.xml files, AFAICT), no builds will get past the dependency resolution stage.
Running mvn -X reveals lines like this for each artifact that is later apparently not found:
[DEBUG] Verifying availability of /Users/chas/.m2/repository/javax/mail/mail/1.4.4/mail-1.4.4.jar from []

Of course, /Users/chas/.m2/repository/javax/mail/mail/1.4.4/mail-1.4.4.jar et al. does exist, as does /Users/chas/.m2/repository/javax/mail/mail/1.4.4/mail-1.4.4.pom.  Totally puzzled.  At this point, I'm assuming this is a bug in Maven 3 (or some underlying library), now that I see that 2.2.1 is clean.
Update 3 Bug report filed with Maven project.

A: This issue is resolved in aether 1.12, one rev above the aether 1.11 library that ships with Maven 3.0.3.  Replacing aether 1.11 with 1.12 in one's Maven install results in expected behaviour (as noted in the bug I filed).  Here's hoping Maven 3.0.4 is released with aether 1.12 ASAP. :-)

A: you do not mention what you may have tried, so maybe you didn't try this one: adding the -U option to force update ? (tho maybe this -U option is only relevant for SNAPSHOTs ...)

A: I've seen similar errors caused by corrupted files in my local repository. For example, if a download failed partway through, or a file in a remote repository changed after I downloaded it. Deleting the affected directories under ~/.m2 fixed it.


text:
Q: Quantifying difference in model performance? Probably a very basic question that's been asked before, but ...
I have a set of candidate models (mixed-effects linear regressions) I'm fitting to 1/0 (presence/absence) data in R using glmer. Using AIC scores and delta-AICs, I can determine which models have the best support and relatively how much better they are from the others. But I would like a more intuitive way to describe how much of an improvement the top model is over a lower model. For example, I'd like to be able to make a statement like, "Model One performed 10% better than Model Two" or "the inclusion of this variable improved increased model performance by 10%"
Here's what my AIC output looks like:
Model selection based on AICc:

                  K   AICc Delta_AICc AICcWt Cum.Wt      LL
canopy + nest hab 4 561.34       0.00   0.48   0.48 -276.64
canopy + f hab    4 562.33       0.99   0.29   0.78 -277.13
canopy alone      3 564.32       2.98   0.11   0.89 -279.14
nest hab alone    3 565.46       4.12   0.06   0.95 -279.71
canopy + age      4 565.84       4.51   0.05   1.00 -278.89

I'm particularly interested in comparing the top model the "nest hab alone" model.
Is it possible to calculate something like this? And if so, how?


text:
Q: Virtualbox Not working Modules not working So i am trying to install genymotion on ubuntu 16.04 and i need the modules running so i open up virtualbox, i get some warnings
so i reinstalled virtualbox-dkms and i checked my headers which i got
    (cloudyjr)volt@localhost:~$ uname -r
    3.8.11

for some reason dkms is not detecting my headers. So after that i move on and i try to launch a Vm ignoring the warning and i get

So i go ahead and i try out what it says
    sudo modprobe vboxdrv
    modprobe: ERROR: could not insert 'vboxdrv': Operation not permitted

And now i am stuck Help ME PLEASEEE!!!!?????????

A: I know that this question is too old, but because there is no accepted answer and none of these answers solved the issue in my case; I am writing how I solved this today:
When running this command, get this error:
$ sudo modprobe vboxdrv
modprobe: ERROR: could not insert 'vboxdrv': Required key not available

The problem is that the module is not signed and therefore not loaded with the kernel. This will happen if your computer has the SecureBoot mode activated, something very common in modern equipment.
That's why I get this error opening any machine in the virtual box

Kernel driver not installed (rc=-1908)

Do the following steps to sign a driver, and it is loaded as a kernel module, on Ubuntu systems and also on Debian 9:
1. Install the mkutil package to be able to do signed.
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install mokutil

2. generate the signature file:
openssl req -new -x509 -newkey rsa:2048 -keyout MOK.priv -outform DER -out MOK.der -nodes -days 36500 -subj "/CN=VirtualBox/"

3. Then add it to the kernel:
sudo /usr/src/linux-headers-$(uname -r)/scripts/sign-file sha256 ./MOK.priv ./MOK.der $(modinfo -n vboxdrv)

4. Register it for the Secure Boot.
IMPORTANT! That will ask you for a password, put the one you want, you will only have to use it once in the next reboot.
sudo mokutil --import MOK.der

5. Finally, restart the computer. A blue screen will appear with a keyboard wait, press the key that asks you to interrupt the boot.

When you are inside the blue screen, select Enroll MOK > Continue > and it will ask you for the password that you have previously entered, you will enter it and you will be informed that the operation has been completed successfully.
Now your operating system will start and you can now use VirtualBox without problem :)
Hope this help someone.

A: Sounds like you are referencing the same issues in this post as well: VirtualBox Kernels are not working
I think I understand your issue more clearly now. Your kernel version is from a lower release:
This is for an older release but should update your kernel to the Ubuntu 16.04 version: https://askubuntu.com/questions/364156/ubuntu-13-10-kernel-still-3-8-0-31-generic

A: I have just found this issue on Ubuntu 20.04. This problem can be caused by installing Ubuntu without secure boot. Unfortunately secure boot is a requirement if you want to use VirtualBox due to the closed-source kernel module required. In my case I resolved it by reinstalling Ubuntu.
If you want to use VirtualBox, during the installation procedure there is a question about restricted 3rd party libraries. You need to select this option and then beneath that, select to enable secure boot.


text:
Q: Angular 2 RC 6 Material 2 Alpha 8 Not Working I recently upgraded my project to Angular 2 RC 6 and Material 2.0.0-alpha.8-1 but its not working, can anyone please guide what am I missing here? Can anyone please share a working plunker with Angular 2 RC 6 and Material 2.0.0-alpha.8-1?
I have below packages in my package.json:
"@angular2-material/button": "2.0.0-alpha.8-1",
"@angular2-material/button-toggle": "2.0.0-alpha.8-1",
"@angular2-material/card": "2.0.0-alpha.8-1",
"@angular2-material/checkbox": "2.0.0-alpha.8-1",
"@angular2-material/core": "2.0.0-alpha.8-1",
"@angular2-material/grid-list": "2.0.0-alpha.8-1",
"@angular2-material/icon": "2.0.0-alpha.8-1",
"@angular2-material/input": "2.0.0-alpha.8-1",
"@angular2-material/list": "2.0.0-alpha.8-1",
"@angular2-material/menu": "2.0.0-alpha.8-1",
"@angular2-material/progress-bar": "2.0.0-alpha.8-1",
"@angular2-material/progress-circle": "2.0.0-alpha.8-1",
"@angular2-material/radio": "2.0.0-alpha.8-1",
"@angular2-material/sidenav": "2.0.0-alpha.8-1",
"@angular2-material/slider": "2.0.0-alpha.8-1",
"@angular2-material/slide-toggle": "2.0.0-alpha.8-1",
"@angular2-material/tabs": "2.0.0-alpha.8-1",
"@angular2-material/toolbar": "2.0.0-alpha.8-1",
"@angular2-material/tooltip": "2.0.0-alpha.8-1",

in AppModule I have first imported the below required modules:
import { MdCoreModule } from '@angular2-material/core/core';
import { MdCheckboxModule } from '@angular2-material/checkbox/checkbox';
import { MdProgressBarModule } from '@angular2-material/progress-bar/progress-bar';
import { MdRadioModule, MdUniqueSelectionDispatcher } from '@angular2-material/radio/radio';
import { MdSlideToggleModule } from '@angular2-material/slide-toggle/slide-toggle';
import { MdTabsModule } from '@angular2-material/tabs/tabs';

then added below in the imports list:
imports: [
    ....
    // Material Design
    MdCoreModule.forRoot(),
    MdCheckboxModule.forRoot(),
    MdRadioModule.forRoot(),
    MdSlideToggleModule.forRoot(),
    MdTabsModule.forRoot(),
    MdProgressBarModule.forRoot(),
    ....
],

in Providers:
providers: [
        MdUniqueSelectionDispatcher
]

In my SystemJs Config file I have:
var map = {
    '@angular': 'node_modules/@angular',
    '@angular2-material': 'node_modules/@angular2-material',

    'rxjs': 'node_modules/rxjs',

    'app': 'content/app',
    "angular2-masonry": "node_modules/angular2-masonry"
};

var paths = {
        "masonry-layout": "node_modules/masonry-layout/dist/masonry.pkgd.js"
    };

var packages = {
        'app': { main: 'main.js', defaultExtension: 'js' },
        'rxjs': { defaultExtension: 'js' },
        'angular2-masonry': { defaultExtension: 'js', main: "index" }
    };

var angularPackages = [
    'common',
    'compiler',
    'core',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'forms'
];

angularPackages.forEach(function (name) {
    packages['@angular/' + name] = {
        format: 'cjs',
        main: 'bundles/' + name + '.umd.js', defaultExtension: 'js'
    };
});

var materialComponents = [
        'core',
        'button',
        'card',
        'checkbox',
        'grid-list',
        'icon',
        'input',
        'list',
        'progress-bar',
        'progress-circle',
        'radio',
        'sidenav',
        'slide-toggle',
        'tabs',
        'toolbar'
    ];

    materialComponents.forEach(function (name) {
        packages[("@angular2-material/" + name)] = {
            format: 'cjs',
            main: name + '.umd.js',
            defaultExtension: 'js'
        };
    });

    var config = {
        map: map,
        packages: packages,
        paths: paths
    };

    System.config(config);

Below is the error message shown on console, when I run my applications:
43 Error: SyntaxError: Unexpected token import
at Object.eval (http://localhost:57196/content/app/app.module.js:16:14)
at eval (http://localhost:57196/content/app/app.module.js:328:4)
at eval (http://localhost:57196/content/app/app.module.js:329:3)
Evaluating http://localhost:57196/node_modules/@angular2-material/core/core.js
Evaluating http://localhost:57196/content/app/app.module.js
Evaluating http://localhost:57196/content/app/main.js
Error loading http://localhost:57196/content/app/main.js

A: Got it Fixed! If anyone is still struggling to make Angular 2 RC 6 Material 2 Alpha 8 run in your project, the below configuration might work.
Below is my SystemJS Config File
(function (global) {
    var map = {
        //angular
        '@angular': 'node_modules/@angular',
        '@angular2-material': 'node_modules/@angular2-material',
        'rxjs': 'node_modules/rxjs',

        'app': 'content/app',

        //thirdparty
        "angular2-masonry": "node_modules/angular2-masonry",
    };

    var paths = {
        "masonry-layout": "node_modules/masonry-layout/dist/masonry.pkgd.js"
    };

    var packages = {
        'app': { main: 'main.js', defaultExtension: 'js' },
        'rxjs': { defaultExtension: 'js' },
        "angular2-masonry": { defaultExtension: 'js', main: "index" }
    };

    var angularPackages = [
        'common',
        'compiler',
        'core',
        'http',
        'platform-browser',
        'platform-browser-dynamic',
        'router',
        'forms'
    ];

    angularPackages.forEach(function (name) {
        packages['@angular/' + name] = {
            format: 'cjs',
            main: 'bundles/' + name + '.umd.js',
            defaultExtension: 'js'
        };
    });

    var materialComponents = [
        'checkbox',
        'core',
        'progress-bar',
        'progress-circle',
        'radio',
        'sidenav',
        'slide-toggle',
        'tabs'
    ];

    materialComponents.forEach(function (name) {
        packages[("@angular2-material/" + name)] = {
            format: 'cjs',
            main: name + '.umd.js',
            defaultExtension: 'js'
        };
    });

    var config = {
        map: map,
        packages: packages,
        paths: paths
    };

    System.config(config);

})(this);

AppModule
Imports
//angular
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Http, XHRBackend, HttpModule, RequestOptions, JsonpModule } from '@angular/http';
import { NgModule } from '@angular/core';

//material
import { MdCheckboxModule } from '@angular2-material/checkbox';
import { MdProgressBarModule } from '@angular2-material/progress-bar';
import { MdRadioModule, MdUniqueSelectionDispatcher } from '@angular2-material/radio';
import { MdSlideToggleModule } from '@angular2-material/slide-toggle';
import { MdTabsModule } from '@angular2-material/tabs';

Imports in NgModule
@NgModule({
    imports: [
        //angular
        BrowserModule,
        FormsModule,
        HttpModule,
        JsonpModule,
        ReactiveFormsModule,
        routing,

        //material
        MdCheckboxModule.forRoot(),
        MdRadioModule.forRoot(),
        MdSlideToggleModule.forRoot(),
        MdTabsModule.forRoot(),
        MdProgressBarModule.forRoot(),
        MdProgressBarModule.forRoot()
//.....
    ],

If your are using Radio
providers: [
        MdUniqueSelectionDispatcher
]

A: I use Material 2 along with the 'official' systemjs.config.js file and couldn't get this to work with the .js barrels.
So I went ahead and mapped them to the .umd files, e.g.
map: {
    ...
'@angular2-material/button':  'npm:@angular2-material/button/button.umd.js',
'@angular2-material/card':    'npm:@angular2-material/card/card.umd.js',
'@angular2-material/checkbox':    'npm:@angular2-material/checkbox/checkbox.umd.js',
    ...
}

and removed the associated entries in the packages section. That did the trick for me.


text:
Q: Data structure for Camelcase search (similar to Eclipse and Idea) I'm trying to implement an algorithm for camel case search (skipping letters between capital letters), for example:
Given list and input string.
List:

*

*ManualProxy.java

*MapPropertyBase.java

*MaxProduct.java

*ManualProviderBase.java

*Map.java

Input:

*

*"Ma" - we should return all words from the dictionary because all of
them starts with Ma

*"MaP" - return all except "Map.java", because they start with "Ma"
and the second word starts with "P"

*"MProd" - return MaxProduct.java because the first word starts with
"M" and the second words starts with "Prod"

I consider to use a trie, but the problem is that I need traverse the whole tree to find the second capital letter. Another option is to use trie for capital letters and tries for nodes. But in this case, I have to return from the node and if there are matches continue traverse for the next capital letter.
Is there any better approach to this problem?


text:
Q: error "expected ')' before '&' token" when calling a function with pointers I am getting the error expected ')' before '&' token on this line:
&p1, &p2, &q1, &q2);, which is part of the void calcula_pq (...) function.
I can't figure out how to fix it. Please, help me.
This is my code
#include <stdio.h>
void calcula_pq ( double xi, double yi, double div, double xk, double yk,
double dkv, double x2, double y2, double d2v, double x3, double y3,
double d3v, double *p1, double *p2, double *q1, double *q2);

int main ()
{
    double p1, p2, q1, q2, xi, yi, div, xj, yj, djv, xk, yk, dkv;
    scanf ("%lf%lf%lf%lf%lf%lf%lf%lf%lf", &xi, &yi, &div, &xj, &yj, &djv,
    &xk, &yk, &dkv);
    void calcula_pq ( xi, yi, div, xk, yk, dkv, xk, yk, dkv, xj, yj, djv,
                      &p1, &p2, &q1, &q2);
    printf ("%.10f   %.10f    %.10f   %.10f", p1, p2, q1, q2);
    return 0;
}

void calcula_pq ( double xi, double yi, double div, double xk, double yk,
double dkv, double x2, double y2, double d2v, double x3, double y3,
double d3v, double *p1, double *p2, double *q1, double *q2){

    double pa, pb, qa, qb;

    pa = ( ( (xi*xi) - (x2*x2) + (yi*yi) - (y2*y2) - (div*div) + (d2v*d2v) /
         (2 * (xi - x2) ) );
    pb = ( ( (x3*x3) - (xk*xk) + (y3*y3) - (yk*yk) - (d3v*d3v) + (dkv*dkv) /
         (2 * (x3 - xk) ) );
    qa = ( (y2 - yi) / (xi - x2));
    qb = ( (yk - y3) / (x3 - xk));
    *p1 = pa;
    *p2 = pb;
    *q1 = qa;
    *q2 = qb;
}

A: Method call inside the main having void.. remove that and try
change from
void calcula_pq ( xi, yi, div, xk, yk, dkv, xk, yk, dkv, xj, yj, djv,
                      &p1, &p2, &q1, &q2);

to
calcula_pq ( xi, yi, div, xk, yk, dkv, xk, yk, dkv, xj, yj, djv,
                          &p1, &p2, &q1, &q2);

A: Remove the void before calcula_pq (... or enclose it in parenthesis if you intended to cast there. But I assume you did copy and paste the signature and missed that.
Two closing parenthesis were also missing (in calcula_pq here (2 * (xi - x2) ) ); and here (2 * (x3 - xk) ) );).
#include <stdio.h>
void calcula_pq ( double xi, double yi, double div, double xk, double yk,
double dkv, double x2, double y2, double d2v, double x3, double y3,
double d3v, double *p1, double *p2, double *q1, double *q2);

int main ()
{
    double p1, p2, q1, q2, xi, yi, div, xj, yj, djv, xk, yk, dkv;
    scanf ("%lf%lf%lf%lf%lf%lf%lf%lf%lf", &xi, &yi, &div, &xj, &yj, &djv,
    &xk, &yk, &dkv);
    calcula_pq ( xi, yi, div, xk, yk, dkv, xk, yk, dkv, xj, yj, djv, // remove void
                      &p1, &p2, &q1, &q2);
    printf ("%.10f   %.10f    %.10f   %.10f", p1, p2, q1, q2);
    return 0;
}

void calcula_pq ( double xi, double yi, double div, double xk, double yk,
double dkv, double x2, double y2, double d2v, double x3, double y3,
double d3v, double *p1, double *p2, double *q1, double *q2){

    double pa, pb, qa, qb;

    pa = ( ( (xi*xi) - (x2*x2) + (yi*yi) - (y2*y2) - (div*div) + (d2v*d2v) /
         (2 * (xi - x2) ) ) ); // add )
    pb = ( ( (x3*x3) - (xk*xk) + (y3*y3) - (yk*yk) - (d3v*d3v) + (dkv*dkv) /
         (2 * (x3 - xk) ) ) ); // add )
    qa = ( (y2 - yi) / (xi - x2));
    qb = ( (yk - y3) / (x3 - xk));
    *p1 = pa;
    *p2 = pb;
    *q1 = qa;
    *q2 = qb;
}


text:
Q: UITableView Height does not fit container vertically (bottom) for different iPhone devices I have a UITableView that in one of my Views. I have been testing the app on an iPhone 4S and it has been working great. Now I tried testing it on an iPhone 5S (which has a taller screen). The UITableView is not fitting to the bottom. I know this has to do with Auto Layout But I am not sure how to set that up.
The two approaches that come to my mind are:
1-) Programmatically determine height of screen and then programmatically setting the UITableView Height to Fit screen
2-) Using Auto-Layout in the Interface Builder. But I get warnings that AutoLayout only works for iOS 8 and higher. So how would I implement that for lower versions of iOS?
So my question is: How to set the height of a UITableView dynamically so that it fits to the bottom of the screen regardless of the height of the iPhone screen?
Thanks for any help.

A: You can set different tableview for different screen size like this.
This define in header of the .m file
#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )

This is define in viewDidLoad() method
 if (IS_IPHONE_5) {
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, 320, 568)];
}else{
        // define for 3.5 inch screen
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, 320, 480)];
}

I hope this should help..


text:
Q: How to find all points with certain elevation difference between them in QGIS I have a point layer (xyz) and want to find all points that have elevation difference of 200m or more. I would like to then draw a line between each pair with the largest elevation difference.
The goal is to identify areas that have large elevation difference and (eventually) nearest distance between them in QGIS.

A: The easiest way is to import your points into a format that can be queried with SQL, like PostGIS, SQLite or Shapefile (using OGR).
Then you can query:
SELECT *
FROM [table] a, [table] b
WHERE a.[featureid] <> b.[featureid]
    AND ST_Z(a.[geometry]) - ST_Z(b.[geometry]) >= 200;

Or you can query and make lines in one step:
SELECT ST_MakeLine(a.[geometry], b.[geometry]) AS geom
FROM [table] a, [table] b
WHERE a.[featureid] <> b.[featureid]
    AND ST_Z(a.[geometry]) - ST_Z(b.[geometry]) >= 200;

It might help to filter out any points that cannot be >= 200m from another point first, because this is an O(n^2) query -- if you have a lot of points, it'll take a long time. You can also restrict the matching to within a certain distance to employ the index and speed it up.
Note: replace the [names] here with your own table/column names.
Edit:
I couldn't find where to execute an SQL query in QGIS, but here's how to do it in ogr2ogr on the command line:
ogr2ogr \
    -f "ESRI Shapefile" \
    -dialect "SQLITE" \
    -sql "SELECT * FROM input a, input b WHERE ST_Z(a.GEOMETRY)-ST_Z(b.GEOMETRY) < 200 AND a.FID<>b.FID" \
    output.shp input.shp

The -f switch tells the program what kind of file to produce. The -dialect switch says to use SQLite's SQL engine to perform the query. The -sql argument is the query. GEOMETRY and FID are built-in field names that you can use in your query.
Now, this query is going to be extremely slow because there's no index. It's going to try to match every point to every other point. Using the documentation here I tried to get the query to use a spatial index, but it doesn't seem to work and I don't have time to mess with it at the moment.
Loading the same point set into SpatiaLite goes something like this:
spatialite> .loadshp input input UTF-8 2956
spatialite> select createspatialindex('input', 'geometry');
spatialite> create table output as select * from input a, input b where st_z(a.geometry)-st_z(b.geometry) < 200 and a.rowid<>b.rowid and a.rowid in (select rowid from spatialindex f_table_name='stations' and search_frame=b.geometry);
spatialite> .dumpshp output 'geometry' output UTF-8

The first line loads the shp file, the second creates a spatial index, the third creates a new table from the query and the fourth dumps the new table to a new file. (Docs here.)
This is much faster than the ogr2ogr solution (for me).


text:
Q: Remove leading "0" in day and month in jQuery UI datepicker My question is similar to Remove Leading "0" in day of month SimpleDateFormat
Is it possible to remove the leading "0" in jquery UI datepicker?
The DateFormat option is as close as I could get from the documentation:
$( ".selector" ).datepicker({ dateFormat: "yy-mm-dd" });

But what I need is on a date like Dec 5th, 2012, datepicker shows it as 12/05/2012 whereas I would like to have 12/5/2012. Same goes for April 5th: 4/5/2013 for example.
Can this be done without an extensive logic?

A: Try
$( ".selector" ).datepicker({ dateFormat: "yy-m-d" });
Source:Jquery DateFormats


text:
Q: Choosing $6$ of $20$ people in a row such that there is at least one other chosen beside any of them There are $20$ people in a row. What is the number of ways to choose $6$ of them such that there is at least one adjoining person beside every chosen person.
I was trying to count number of ways of its complement. But it gets harder. Actually, I have no idea how to find an approach.

A: Each admissible arrangement can be encoded as a binary word of length $20$ containing exactly $6$ ones. The $14$ not chosen people (zeros) create $15$ slots where groups of chosen people (ones) may be squeezed in. These groups may have sizes $(6)$, $(4,2)$, $(3,3)$, and $(2,2,2)$. It follows that the total number of admissible arrangements is given by
$${15\choose 1}+2\cdot{15\choose 2}+{15\choose 2}+{15\choose3}=785\ .$$

A: Just to provide an alternative approch, we may utilise regular expressions.
This is equivalent to counting binary words of using the alphabet $\{A,B\}$ length $20$ with $6$ $A$s and 14 $B$s such that there are no isolated $A$s.
Consider that the regular expression for binary words with no isolated $A$s must be of the form
$$f=1 +f_A+f_B\tag{1}$$
where $1$ is the empty word, $f_A$ are all such words ending with $A$ and $f_B$ all such words ending with $B$.
It should be clear that words in $f_A$ either consist entirely of $A$s or are $f_B$ with $2,3,4\ldots$ $A$s appended
$$f_A=(A+AA+AAA+\cdots) +f_B(AA+AAA+AAAA+\cdots)$$
$$\implies f_A=(1+f_B)A^2(1-A)^{-1}\tag{2}$$
similarly words in $f_B$ consist entirely of words containing $B$ or are $f_A$ with $1,2,3,\ldots$ $B$s appended
$$f_B=(1+f_A)B(1-B)^{-1}\tag{3}$$
solving $(2)$ and $(3)$ simultaneously gives
$$f_A=\left(\frac{BA^2}{(1-A)(1-B)}+\frac{A^2}{1-A}\right)\left(1-\frac{BA^2}{(1-B)(1-A)}\right)^{-1}\tag{4}$$
$$f_B=\left(\frac{BA^2}{(1-A)(1-B)}+\frac{B}{1-B}\right)\left(1-\frac{BA^2}{(1-B)(1-A)}\right)^{-1}\tag{5}$$
plugging $(4)$ and $(5)$ into $(1)$ yields (after some simplification)
$$f=\frac{A^2-A+1}{1-A-B+AB-A^2B}\tag{6}$$
For this problem we evaluate the coefficient of $A^6B^{14}$ in the expansion of $f$ using sage input
y=var('y')
taylor((x^2-x+1)/(1-x-y+x*y-x^2*y),(x,0),
(y,0),25).coefficient(x^6).coefficient(y^14)

This evaluates to
$$[A^6B^{14}]\frac{A^2-A+1}{1-A-B+AB-A^2B}=785\tag{Answer}$$


text:
Q: Normal distribution in every segment, what is the final distribution? Suppose a ball start at $x=\mu$ when $t=0$; when $t=1$, the ball's coordinate distribution satisfies $N(\mu, \sigma^2/N)$; Suppose the ball's coordinates is at $x=x_1$ at $t=1$, then the ball's coordinate distribution satisfies $N(x_1,\sigma^2/N)$ when $t=2$;$\cdots$ the same idea goes on, question: what is the distribution at $t=N$? In the limit of $N\to\infty$, the answer is lognormal distribution, but I don't know how to derive it.
Here is my try, the PDF of $X_2$ is:
$$
f_2(X=x)=\int_{-\infty}^{\infty}\frac{1}{\sqrt{2\pi\sigma^2/N}}e^{-(x-x_1)^2/(\sigma^2/N)} \frac{1}{\sqrt{2\pi\sigma^2/N}}e^{-(x_1-\mu)^2/(\sigma^2/N)} dx_1
$$
This integral can be done, but the following deduction seems more and more complex...


text:
Q: UITableView dynamic cell height breaks on transition or rotation Currently I am messing around with swift and dynamic table cell heights. I developed a simple app for iOS8.1 on xcode6.1:  https://github.com/ArtworkAD/DynamicCellTest
So to achieve a cell height that stretches with the cell's content I do the following:

*

*in storyboard set label lines to 0

*set labels font to system

*set constraints for label in cell

*add self.tableView.rowHeight = UITableViewAutomaticDimension

*don't override heightForRowAtIndex method

Minimal code is needed:
class MyTableViewController: UITableViewController {

    var entries:Array<String> = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        //create dummy content
        var i = 0
        while i < 10 {
            entries.append("\(i) Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor")
            entries.append("\(i+1) Lorem ipsum dolor sit amet")
            i = i + 2;
        }

        self.tableView.rowHeight = UITableViewAutomaticDimension

    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int)  -> Int {
        return self.entries.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = self.tableView.dequeueReusableCellWithIdentifier("basic_cell", forIndexPath: indexPath) as UITableViewCell

        var label = cell.viewWithTag(13)

        if let unwrappedLabel = label as? UILabel {
            unwrappedLabel.text = self.entries[indexPath.row]
        }

        return cell
    }
}

The left image shows the result of the above code. The cell height grows with the content of the label, all nice. However when you click on the disclosure indicator to the detail view and move back again, you get the right image. Why is this happening??

A bad solution for this problem is to override this methods:
override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    self.tableView.reloadData()
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    self.tableView.reloadData()
}

override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
    self.tableView.reloadData()
}

This way the above problem is solved, but this solution seems not right? A side effect of it is, that when self.tableView.reloadData() is called the table view port jumps to the first cell which doesn't look nice.
Does anyone has an idea what I am doing wrong? Feel free to clone my repo https://github.com/ArtworkAD/DynamicCellTest and test it out.

A: Adding this seems that it is able to fix rotation problem.
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    self.tableView.estimatedRowHeight = 36.5
}

However, I have another case that there are 4 labels in the cell, which has the same rotation problem, adding this is not enough and I ended up replacing the self.tableView.estimatedRowHeight = 36.5 with reloading visible cells.

A: I've just solved exactly that problem by overriding tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) in UITableViewDelegate object.
func tableView(tableView: UITableView,
               estimatedHeightForRowAtIndexPath indexPath: NSIndexPath)
               -> CGFloat {
    return 200
}

Changing the exact returned value apparently have no effect. The cells are always properly self-sizing. I've got no idea why providing estimated height causes the autolayout to kick in, but it does. iOS 8.1.2, Xcode 6.1.

A: The link provides a good explanation of what needs to be done.
Using Auto Layout in UITableView for dynamic cell layouts & variable row heights
For your specific problem you are missing two lines of code.
In viewDidLoad under your tableView.rowHeight add self.tableView.estimatedRowHeight = 64
The above will provides allow the tableView to assign estimated height values for offscreen cells to enhance performance and it also calculates the scroll bar height.
The main problem is you are missing unwrappedLabel.preferredMaxLayoutWidth = CGRectGetWidth(tableView.bounds) in cellForRowAtIndexPath this tells the label its preferred maximum width so it can calculate the height it requires for multi-line text. Usually you would do this in the table view cell subclass.
I have tested this in your project and it works

A: You have to set estimatedRowHeight:
// setup automatic row height
self.tableView.rowHeight = UITableViewAutomaticDimension

// whatever you think is the approximate row height
self.tableView.estimatedRowHeight = 44

A: Also came across an alternative here http://useyourloaf.com/blog/2014/08/07/self-sizing-table-view-cells.html. A comment mentions -
Simply make the cell layout its subviews before returning it from cellForRowAtIndexPath:
[cell setNeedsDisplay];
[cell layoutIfNeeded];


text:
Q: Query Pull Requests by CommitID without Repository ID Can I get the Pull Requests by commit ID without providing a repository ID?  I am auditing releases and need information provided by PRs.  I am starting without repository info in the data so currently need to query the Repository api and then associate the commits to the repositories before I can make the Pull Request query.
Additionally, can this be done with a Get requests? It seems like it should be a get request but currently requires a Post with a body. Instead of an additional api, shouldn't the filtering for PR type just be in the uri parameters?

A: Have you tried it with GetPullRequestByProject instead?
https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull%20requests/get%20pull%20requests%20by%20project?view=azure-devops-rest-5.1
Since you already have commit Id, from the response, you can query JSON to retrieve the required information. That will also fulfill the second requirement on GET operation.


text:
Q: VBA - Delete lines from text file based on previous lines I have a big text file with 2k plus lines. The code for the moment is looking for specific tags and it put in a column. At tag Value Date is creating a new row.
One of the things is: I have tag AMT and until the code creates a new row, AMT is overwritten by another AMT value.  The only way to avoid this is somehow to load in memory 2 lines from text and based on the previous value to print or not the next value.
I could accept a code to input the text file and output with AMT fixed and then run my below code.
   Sub OpenFilesConvertTexttoCOL()

   Dim MyFolder As String
   Dim MyFile As String
   Dim textline As String

   MyFolder = "C:\Folder\"
   MyFile = Dir(MyFolder & "\*.txt")
   Dim filename As String
   Dim currentrow As Long: currentrow = 2

Do While MyFile <> ""  'This will go through all files in the directory, "Dir() returns an empty string at the end of the list

    filename = MyFolder & "\" & MyFile  'concatinates directory and filename

    Open filename For Input As #1

Do Until EOF(1)  'reads the file Line by line
        Line Input #1, textline
        'text = text & textline
        If (textline = " ") Or _
        (textline Like "*Amount:      Cur:*") Then   'error handler, if line was empty, ignore

        Else
            Dim splitline() As String
            splitline() = Split(textline, ": ", -1, vbTextCompare)
        ' because of how my specific text was formatted, this splits the line into 2 strings.  The Tag is in the first element, the data in the second

            If IsError(splitline(0)) Then
                splitline(0) = ""
            End If

            Select Case Trim(splitline(0)) 'removes whitespace
                Case "Currency"
                    'currentrow = currentrow + 1 'files that didn't have a description row, resulted in empty rows in the spreadsheet.
                   ActiveSheet.Range("A" & currentrow).Cells(1, 1).Value = Split(Trim(splitline(1)), " ")(0) '= splitline(1) ,= Trim(splitline(1)), " ")

                Case "Value Date"
                    ActiveSheet.Range("B" & currentrow).Cells(1, 1).Value = Trim(Right(splitline(1), 42)) 'Trim(Right(splitline(1), 42))
                    currentrow = currentrow + 1 'files that didn't have a description row, resulted in empty rows in the spreadsheet.

                Case "Reffor the A O"
                   ActiveSheet.Range("C" & currentrow).Cells(1, 1).Value = Split(Trim(splitline(1)), " ")(0)

                Case "Amt"
                    ActiveSheet.Range("D" & currentrow).Cells(1, 1).Value = Split(Trim(splitline(1)), " ")(0)

                Case "Ref"
                    ActiveSheet.Range("E" & currentrow).Cells(1, 1).Value = Split(Trim(splitline(1)), " ")(0)

                Case "DCM"
                    ActiveSheet.Range("F" & currentrow).Cells(1, 1).Value = Split(Trim(splitline(2)), " ")(0)

                Case "NO. TR"
                    ActiveSheet.Range("H" & currentrow).Cells(1, 1).Value = Split(Trim(splitline(1)), "VOR")(0)

                Case "Id Code"
                    ActiveSheet.Range("I" & currentrow).Cells(1, 1).Value = Split(Trim(splitline(1)), " ")(0)

                Case "ZGR"
                    ActiveSheet.Range("K" & currentrow).Cells(1, 1).Value = Trim(splitline(1))

                'Case "Supplementary Details"
                    'ActiveSheet.Range("L" & currentrow).Cells(1, 1).Value = splitline(1)

                    '...etc. etc... so on for each "tag"

            End Select

            'different Separators

            splitline() = Split(textline, "XXX-", -1, vbTextCompare)
            Select Case Trim(splitline(0))
            Case "YOUR REF "

                ActiveSheet.Range("G" & currentrow).Cells(1, 1).Value = Trim(splitline(1))
            End Select

           splitline() = Split(textline, "-ZAHLUNG", -1, vbTextCompare)
            Select Case Trim(splitline(0))
            Case "/REMI/AUSLANDS"
                ActiveSheet.Range("J" & currentrow).Cells(1, 1).Value = Trim(splitline(1))
            End Select

        End If
    Loop
    Close #1
    MyFile = Dir()  'reads filename of next file in directory
    Loop
   End Sub

If is needed I could put a template of my TXT file, but due to the privacy of the data it will take some time to clear the file.
LATER EDIT:
My TXT example:
enter code here

     Block 3
     Block 4
     F20: T R N

     F25: A I - A
     F28C: St Number/Se Number
               Statement Number:          00109
               Sequence Number:          /002
     F60M: O B - D/C - Date - Cur - Amt
               DCMark: D/C Mark:          C
               Date:          180606          2000 Apr 01
               Currency:          EUR          EURO
               Amt:          21489135,63          #21489135,63#
     F61: SSLL
               Value Date:          180606          2000 Apr 01
               DCM: Debit/Credit Mark:          C
               Amt:          694,88          #694,88#
               Transaction Type:          N
               Id Code:          TRF
               Reffor the A O:          43000180606Z9257
     Ref:          //034542452450

               Supplementary Details:

     F86: info22
                /BENM//GT2543534534534   aaa aaaa
                /ORDP/aaaa aaa aaaaa 8/18
                /REMI/UBERWEISUNG OUR REF: 034564654456
               YOUR REF: 43000180606Z9257 S103 FAV Y/ddsdsXXX
               ZGR: HHFHD SFOI DNNDS AGT: EUR 694,88
               /AT934300030233977005      BIC:VBOEATWWXXX
     F61: SSLL
               Value Date:          180606          2000 Apr 01
               DCM: Debit/Credit Mark:          C
               Amt:          2000,00          #2000,00#
               Transaction Type:          N
               Id Code:          TRF
               Reffor the A O:          3801920873
     Ref:          //03GT180606136336

               Supplementary Details:

                         /TGDFD/EUR2000,00/
     F86: info1
                /BENM//GT39FEMA16126000011201000470400 S-K, HA
                /ORDP/
                /REMI/UIS OUR REF: 03GT180606136336
               YOUR REF: 3801920873       S103 FAV Y/ddsdsXXX
               ZGR: /RFB/WITHDRAWAL       AGT: EUR 2.000,00

     F61: SSLL
               Value Date:          180606          2000 Apr 01
               DCM: Debit/Credit Mark:          C
               Amt:          2845,00          #2845,00#
               Transaction Type:          N
               Id Code:          TRF
               Reffor the A O:          FTT7681198 01
     Ref:          //014454154564

               Supplementary Details:

                         /GTF/EUR2845,00/
     F86: info22
                //ewrewtweqterqyfrgdfgaddfag
                /343253256346456/gfdgadfgasdadf
                /REMI/UBERWEISUNG OUR REF: 180606192446
               YOUR REF: 4354356346
               ZGR: /fdgafg/3464363434   AGT: EUR 2.845,00

     F62M: C B  - D/C - Date - Currency - Amt
               DCMark: D/C Mark:          C
               Date:          180606          2000 Apr 01
               Currency:          EUR          EURO
               Amt:          354543634          #54654656#
     Block 5

If you put the code applied on upper text you will result in row 5 excel: AMT 354543634 instead of 2845,00. This is happening because AMT is overwritten and is imposibile, for me, that function EOF to ignore a string based on previous string.
Line "F**:" is always the same so if i can relate to this line to ignore X numbers of lines it will solve my situation.
Any other suggestion to work around is accepted including other software of extracting the data.
Many thanks for future help.
Origin of my code from other source link


text:
Q: Implementing JQuery for search box in wordpress I'm trying to implement an expanding searchbox in wordpress. I have applied the HTML in my search-form.php and CSS in my style.css. However, I'm not sure how to apply the Jquery part. Is it as follows:-
add_action ('wp_footer','vr_search_head',1);
function vr_search_head() {
?>

<script>
  $(document).ready(function(){
        var submitIcon = $('.searchbox-icon');
        var inputBox = $('.searchbox-input');
        var searchBox = $('.searchbox');
        var isOpen = false;
        submitIcon.click(function(){
            if(isOpen == false){
                searchBox.addClass('searchbox-open');
                inputBox.focus();
                isOpen = true;
            } else {
                searchBox.removeClass('searchbox-open');
                inputBox.focusout();
                isOpen = false;
            }
        });
         submitIcon.mouseup(function(){
                return false;
            });
        searchBox.mouseup(function(){
                return false;
            });
        $(document).mouseup(function(){
                if(isOpen == true){
                    $('.searchbox-icon').css('display','block');
                    submitIcon.click();
                }
            });
    });
        function buttonUp(){
            var inputVal = $('.searchbox-input').val();
            inputVal = $.trim(inputVal).length;
            if( inputVal !== 0){
                $('.searchbox-icon').css('display','none');
            } else {
                $('.searchbox-input').val('');
                $('.searchbox-icon').css('display','block');
            }
        }
</script>

<?php
}

search box from http://codepen.io/nikhil/pen/qcyGF/
I tried applying the above code in my child themes functions.php but it doesnt seem to work. On clicking search, the search box doesnt open.
Thanks


text:
Q: Maximum steepness of hill A hill is given by
$$ z = f(x,y) = \frac {32}{1 + x^2 + y^2}$$
where $z$ is the height of the hill in meters. At what height is the hill the steepest?
The standard way to do it, which is how I would do it, is to determine the gradient on vector form and then maximize $\| \text{grad} f(x,y)\|^2$ with respect to $x^2 + y^2 = r^2$ (I'll maximize the square since it is hairy to deal with square roots).
But what I would like to know is what other, perhaps more clever and sophisticated, ways there are to solve the same problem.

A: The graph you give has rotational symmetry about the $z$-axis.
To see this, put $x=r\cos\theta$ and $y=r\sin\theta$. We get
$$\frac{32}{1+x^2+y^2} = \frac{32}{1+r^2}$$
This is independent of $\theta$. We might as well consider a planer cross section, e.g. the plane $y=0$.
This gives the curve $z=\frac{32}{1+x^2}$. For the steepest points you want to maximise or minimise the gradiet, i.e. solve $\frac{\mathrm{d}^2z}{\mathrm{d}x^2}=0$. Doing so gives $x=\pm\frac{1}{\sqrt{3}}$. Checking the sign of $\frac{\mathrm{d}^3z}{\mathrm{d}x^3}$ shows that $x=\frac{1}{\sqrt{3}}$ is a minimum and $x=-\frac{1}{\sqrt{3}}$ is a maximum.
These two points correspond to the circle $x^2+y^2 = \frac{1}{3}$.


text:
Q: Few font size-related layout issues I am using a default font size of 26px and stackoverflow's layout seems to not work well with such a large sizes.
The most important issue is that many inputs tend to overflow and partially get hidden below side text. This includes one with login, 'Title' and — the most important issue — the editor, which makes writing posts a little painful.
Another important one is that sometimes 'search' field doesn't fit in topbar and jumps lower, being partially hidden by logo. I met that issue on stackoverflow itself only while serverfault & meta display fine (but that may be related to rep or sth).
There's one minor issue too — navbar is too narrow and 'Ask Question' jumps below — but this one looks quite nice (maybe it's even intended?).
Screenshot: (click to enlarge)

A: Why don't you use browser zoom instead of font scaling?
http://www.codinghorror.com/blog/archives/001212.html
We only support +1 and -1 font sizes, but browser zoom works (almost) infinitely in either direction.

A: Sounds like an edge case. I understand that some may use higher font sizes, but there does come a point where a design typically won't scale. This is particularly true of sites like S[OFU], which are not "fluid" designs in the traditional sense.
Technically, yes, it's a bug -- it makes the site harder to use for some users. However, if it were my code, time and effort, I'd probably file it as a very low-prio bug, unless it could be shown to be affecting a non-trivial number of users.


text:
Q: Getting TabSpec id from activity I'm using a tabhost in my Android application that contains 4 tabs. I'm navigating to the same activity from all these 4 tabs. So I need to distinguish between those 4 tabs.
How to get the tag (specified while creating tabspec) from the called activity?