text:
Q: Is there a way to exit an if statement from a setTimeout loop in JavaScript? I am creating a percent clock that shows me how much percent I am through a certain time in the day. When I ran it, it had an output of above 100% when it was supposed to be 50% at the time. I realized the error was it wasn't exiting the if statements, and I couldn't figure out a way to do so. I can't use while true statements because they don't work with browsers, so if somebody could find a way to exit the if statement when the seconds variable gets above a certain amount I would be very grateful. Here is my code:

var clock = document.getElementById("clockHeading");

setInterval(() => {

    var today = new Date();
    var hours = today.getHours() * 3600;
    var minutes = today.getMinutes() * 60;
    var seconds = today.getSeconds() + minutes + hours;
    seconds = seconds - 31800;
    if (seconds >= 0 && seconds <= 4140) {
        setInterval(() => {
            var percentage = seconds / 4140;
            percentage = percentage * 100;
            percentage = percentage.toFixed(1);
            percentage = String(percentage) + '%';

            clock.innerHTML = percentage;
        }, 1000)
    }
    if (seconds >= 4200 && seconds <= 7380) {
        setInterval(() => {
            var percentage = seconds / 3240;
            percentage = percentage * 100;
            percentage = percentage.toFixed(1);
            percentage = String(percentage) + '%';

            clock.innerHTML = percentage;
        }, 1000)
    }
    if (seconds >= 8640 && seconds <= 11700) {
        setInterval (() => {
            var percentage = seconds / 3060;
            percentage = percentage * 100;
            percentage = percentage.toFixed(1);
            percentage = String(percentage) + '%';

            clock.innerHTML = percentage;
        }, 1000)
    }
    if (seconds >= 11760 && seconds <= 14700) {
        setInterval (() => {
            var percentage = seconds / 2940;
            percentage = percentage * 100;
            percentage = percentage.toFixed(1);
            percentage = String(percentage) + '%';

            clock.innerHTML = percentage;
        }, 1000)
    }
    if (seconds >= 17520 && seconds <= 20700) {
        setInterval (() => {
            var percentage = seconds / 3180;
            percentage = percentage * 100;
            percentage = percentage.toFixed(1);
            percentage = String(percentage) + '%';

            clock.innerHTML = percentage;
        }, 1000)
    }
    if (seconds >= 20760 && seconds <= 24000) {
        setInterval (() => {
            var percentage = seconds / 3240;
            percentage = percentage * 100;
            percentage = percentage.toFixed(1);
            percentage = String(percentage) + '%';

            clock.innerHTML = percentage;
        }, 1000)
    }
}, 1000)
body{
    font-family: 'Josefin Sans', sans-serif;
}
#clockHeading{
    position: absolute;
    top: 38%;
    bottom: 0%;
    width: 100%;
    text-align: center;
    font-size: 200px;
}
* {
    margin: 0;
    padding: 0;
}
.animation-area {
    background: linear-gradient(to left, #8942a8, #ba382f);
    width: 100%;
    height: 100vh;
}
.box-area {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
}
.box-area li {
    position: absolute;
    display: block;
    list-style: none;
    width: 25px;
    height: 25px;
    background: rgba(255, 255, 255, 0.2);
    animation: animate 20s linear infinite;
    bottom: -150px;
}
.box-area li:nth-child(1) {
    left: 86%;
    width: 80px;
    height: 80px;
    animation-delay: 0s;
}
.box-area li:nth-child(2) {
    left: 12%;
    width: 30px;
    height: 30px;
    animation-delay: 1.5s;
    animation-duration: 10s;
}
.box-area li:nth-child(3) {
    left: 70%;
    width: 100px;
    height: 100px;
    animation-delay: 5.5s;
}
.box-area li:nth-child(4) {
    left: 42%;
    width: 150px;
    height: 150px;
    animation-delay: 0s;
    animation-duration: 15s;
}
.box-area li:nth-child(5) {
    left: 65%;
    width: 40px;
    height: 40px;
    animation-delay: 0s;
}
.box-area li:nth-child(6) {
    left: 15%;
    width: 110px;
    height: 110px;
    animation-delay: 3.5s;
}
@keyframes animate {
    0% {
        transform: translateY(0) rotate(0deg);
        opacity: 1;
    }
    100% {
        transform: translateY(-800px) rotate(360deg);
        opacity: 0;
    }
}
<!DOCTYPE html>

        <title>Percent Clock</title>
        <link href="style.css" rel="stylesheet">
        <link rel="preconnect" href="https://fonts.gstatic.com">
        <link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:ital,wght@1,300&display=swap" rel="stylesheet">

A: You need to clearInterval() every time you want to "exit" the loop. You also need to store the interval variable somewhere to be able to clear it:
See my // comments for the changes I made:
var interval = setInterval(() => { // Store it in a variable

    var today = new Date();
    var hours = today.getHours() * 3600;
    var minutes = today.getMinutes() * 60;
    var seconds = today.getSeconds() + minutes + hours;
    seconds = seconds - 31800;
    if (seconds >= 0 && seconds <= 4140) {
        clearInterval( interval ); // Clear the old one

        interval = setInterval(() => { // Store the new one
            var percentage = seconds / 4140;
            percentage = percentage * 100;
            percentage = percentage.toFixed(1);
            percentage = String(percentage) + '%';

            clock.innerHTML = percentage;
        }, 1000)
    }
    if (seconds >= 4200 && seconds <= 7380) {
        clearInterval( interval ); // Clear the old one

        interval = setInterval(() => {
            var percentage = seconds / 3240;
            percentage = percentage * 100;
            percentage = percentage.toFixed(1);
            percentage = String(percentage) + '%';

            clock.innerHTML = percentage;
        }, 1000)
    }
    if (seconds >= 8640 && seconds <= 11700) {
        clearInterval( interval ); // Clear the old one

        interval = setInterval (() => { // Store the new one
            var percentage = seconds / 3060;
            percentage = percentage * 100;
            percentage = percentage.toFixed(1);
            percentage = String(percentage) + '%';

            clock.innerHTML = percentage;
        }, 1000)
    }
    if (seconds >= 11760 && seconds <= 14700) {
        clearInterval( interval ); // Clear the old one

        interval = setInterval (() => { // Store the new one
            var percentage = seconds / 2940;
            percentage = percentage * 100;
            percentage = percentage.toFixed(1);
            percentage = String(percentage) + '%';

            clock.innerHTML = percentage;
        }, 1000)
    }
    if (seconds >= 17520 && seconds <= 20700) {
        clearInterval( interval ); // Clear the old one

        interval = setInterval (() => { // Store the new one
            var percentage = seconds / 3180;
            percentage = percentage * 100;
            percentage = percentage.toFixed(1);
            percentage = String(percentage) + '%';

            clock.innerHTML = percentage;
        }, 1000)
    }
    if (seconds >= 20760 && seconds <= 24000) {
        clearInterval( interval ); // Clear the old one

        interval = setInterval (() => { // Store the new one
            var percentage = seconds / 3240;
            percentage = percentage * 100;
            percentage = percentage.toFixed(1);
            percentage = String(percentage) + '%';

            clock.innerHTML = percentage;
        }, 1000)
    }
}, 1000)


text:
Q: split an array into a list of arrays How can I split a 2D array by a grouping variable, and return a list of arrays please (also the order is important).
To show expected outcome, the equivalent in R can be done as
> (A = matrix(c("a", "b", "a", "c", "b", "d"), nr=3, byrow=TRUE)) # input
     [,1] [,2]
[1,] "a"  "b"
[2,] "a"  "c"
[3,] "b"  "d"
> (split.data.frame(A, A[,1])) # output
$a
     [,1] [,2]
[1,] "a"  "b"
[2,] "a"  "c"

$b
     [,1] [,2]
[1,] "b"  "d"

EDIT: To clarify: I'd like to split the array/matrix, A into a list of multiple arrays based on the unique values in the first column. That is, split A into one array where the first column has an a, and another array where the first column has  a b.
I have tried Python equivalent of R "split"-function but this gives three arrays
import numpy as np
import itertools
A = np.array([["a", "b"], ["a", "c"], ["b", "d"]])
b = a[:,0]

def split(x, f):
     return list(itertools.compress(x, f)), list(itertools.compress(x, (not i for i in f)))
split(A, b)

([array(['a', 'b'], dtype='<U1'),
  array(['a', 'c'], dtype='<U1'),
  array(['b', 'd'], dtype='<U1')],
 [])

And also numpy.split, using np.split(A, b),  but which needs integers. I though I may be able to use How to convert strings into integers in Python? to convert the letters to integers, but even if I pass integers, it doesn't split as expected
c = np.transpose(np.array([1,1,2]))
np.split(A, c) # returns 4 arrays

Can this be done? thanks
EDIT: please note that this is a small example, and the number of groups may be greater than two and they may not be ordered.

A: You can use pandas:
import pandas as pd
import numpy as np

a = np.array([["a", "b"], ["a", "c"], ["b", "d"]])

listofdfs = {}
for n,g in pd.DataFrame(a).groupby(0):
    listofdfs[n] = g

listofdfs['a'].values

Output:
array([['a', 'b'],
       ['a', 'c']], dtype=object)

And,
listofdfs['b'].values

Output:
array([['b', 'd']], dtype=object)

Or, you could use itertools groupby:
import numpy as np
from itertools import groupby
l = [np.stack(list(g)) for k, g in groupby(a, lambda x: x[0])]

l[0]

Output:
array([['a', 'b'],
       ['a', 'c']], dtype='<U1')

And,
l[1]

Output:
array([['b', 'd']], dtype='<U1')

A: If I understand your question, you can do simple slicing, as in:
a = np.array([["a", "b"], ["a", "c"], ["b", "d"]])

x,y=a[:2,:],a[2,:]

x
array([['a', 'b'],
       ['a', 'c']], dtype='<U1')

y
array(['b', 'd'], dtype='<U1')

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Why was the girl that/who had plenty of money arrested" Why is that used in the  following sentence, instead of who?

Why was the girl that had plenty of money arrested for shoplifting
  some trinkets worth only about two dollars?

A: This response is actually directed to the comments that appear beneath waywardEevee's answer—and in particular to the OP's remark that "Why was the girl that had plenty of money arrested for shoplifting some trinkets worth only about two dollars?" was marked as the correct answer on a certification test for English teachers.
As John Lawler points out in his comments, claiming that either who or that is THE correct answer is arbitrary and ultimately baseless, since either word can validly be used to introduce the dependent clause "had plenty of money."
But whereas Araucaria sees the test designer's preference for that as perhaps striking a blow against an enforced blanket preference for who in all instances involving human referents (such as "girl" in the example sentence), I see it as a survival of another (and even older) arbitrary rule of usage that may be even less firmly connected to real-world usage. This rule asserts that that should be used to introduce all dependent clauses of the that/which/who type, whether the reference is to a person or to a thing; that who should be used only to introduce independent clauses that refer to a person; and that which should be used only to introduce independent clauses that refer to a thing.
Here, according to Frank Vizetelly, A Desk-Book of Errors in English: Including Notes on Colloquialisms and Slang to Be Avoided in Conversation (1908), is how the rule works in practice:

that, who : Discriminate carefully between these words. That implies restriction; who generally denotes coordination. As an illustration of this distinction, Alfred Ayers says ("The Verbalist [1881]," p. 202), "'I met the boatman who took me across the ferry.' If who is the proper word here, the meaning is 'I met the boatman, and he took me across the ferry,' it being supposed that the boatman is known and definite. But if there be several boatmen, and I wish to indicate one in particular, by the circumstance that he had taken me across the ferry, I should use that." That ought, therefore, to be preferred to who or which whenever an antecedent not otherwise limited is to be restricted by the relative clause.

It seems to me that the test designers marked that as the correct answer in the sentence about the affluent shoplifter because they were enforcing the 1881 Alfred Ayers rule for dealing with that/which/who constructions—an exercise in grammatical atavism that no one ought to applaud.

A: Who vs that is kind of a grey area. The general rule is who should be used when referring to a person, that where referring to an object. In practice, though, that has been used as a relative pronoun when referring to an individual for a long, long time.

A: I think it's common to use who when the clause is being used to identify the person, and that when it's used descriptively. E.g.

The girl who had plenty of money was arrested.

implies that there were several girls who might have been arrested, but only the one with plenty of money actually was. You would use the above sentence to answer the quesetion Which girl was arrested?
But

The girl that had plenty of money was arrested.

says nothing about whether other girls were involved. It just means that a girl was arrested, and she also had plenty of money.
However, these are subtle nuances, and not all speakers would obey them. Often the context will make it clear which was intended.


text:
Q: usb flash drive simulation(like cd/dvd rom virtual drive) - is it possible is it possible to simulate usb flash drive with code (asp.net with c# is better - if not with php) or a software like virtual clone drive ?
i have a program with usb flash drive unlocker (4 my laptop) and i want to simulate that usb drive , so i can get rid of that usb flash from my laptop !
thanks in future advance
best regards

A: You will have to go into the kernel to do so. You will need to emulate a full USB root hub,  register it so that you don't mess with the real hubs, and then emulate the transactions between your flash device and your hub.
That being said, did you check that your flash drive is just a flash drive and not some kind of cryptographic token ?


text:
Q: [Processing/Java]Visibility/Layering Issue I'm working on a small sketch in processing where I am making a "clock" using the time functions and drawing ellipses across the canvas based on milliseconds, seconds and minutes. I'm using a for loop to draw all of the ellipses and each for loop is inside its own method. I'm calling each of these methods in the draw function. However for some reason only the first method that is called is being drawn, when ideally I would like to have them all being visibly rendered.
//setup program
void setup() {
  size(800, 600);
  frameRate(30);
  background(#eeeeee);
  smooth();
}

void draw(){
  milliParticles();
  secParticles();
  minParticles();
}

//time based particles
void milliParticles(){
  for(int i = int(millis()); i >= 0; i++) {
      ellipse(random(800), random(600), 5, 5 );
      fill(255);
  }
}

void secParticles() {
  for(int i = int(second()); i >= 0; i++) {
      fill(0);
      ellipse(random(800), random(600), 10, 10 );
  }
}

void minParticles(){
  for(int i = int(minute()); i >= 0; i++) {
      fill(50);
      ellipse(random(800), random(600), 20, 20 );
  }
}

A: Your first method is the only one being executed because the condition which must be false in order for your for loop to stop is always true (i will always be >= 0 if you add 1 to it each time you loop).
I think you want to modify your for loops like so:
for(int i = int(second()); i >= 0; i--) {

This way, i will initially be 0-59, and will decrease until it is -1, at which point i >= 0 will be false. Execution will then exit the for loop and pass to the next method.
I think this was your original intent, unless you wanted each method to run simultaneously and indefinitely (in which case you should use threads).


text:
Q: Convert String Array to JSON Array with custom format I want to ask a question about converting a Array to a jsonArray. Here is my code to get jsonArray
[
  {id=10,job:computer, place:near}
  {id=11,job:computer2, place:near2}
  [
    {id=14,job:computer, place:near3}
    {id=11,job:computer2, place:near2}
    {id=10,job:computer2, place:near2}
  ],
  {id3=101,jobr:computerr, placer:nearr}
  [
    {id3=14,jobr:computerr, placre:nearrrr}
  ],
]

I need this format json. But
var arr =
[
  {
    id:'grid1',
    all:
    [
      {id=14,job:computer, place:near3},
      {id=11,job:computer2, place:near2},
      {id=10,job:computer2, place:near2}
    ],
    change:
    [
      {id=10,job:computer, place:near}
      {id=11,job:computer2, place:near2}
    ]
  },
  {
    id:'grid2',
    all:
    [
      {id3=14,jobr:computerr, placre:nearrrr}
    ],
    change:
    [
      {id3=101,jobr:computerr, placer:nearr}
    ]
  }
]

this my code use
obj = {};

$.each(cols[0].Values,function(key,value){
   obj[value.Value] = value.Display;
});

A: Here is how I solved this problem :
var coords=[]
  coords.push({ 'Id': $(myGrid)[0].id, 'ChangeRecord': coords2, 'all': gridData });


text:
Q: Pegar valores em array de um $post Possuo um form onde estou pegando a escolha do usuário, e inserindo no array mas não acumula e só mostra a escolha atual. Como faço para acumular e a cada new post seja adicionado ao array?

<?php

include "filmelistar.php";
$escolhas = array();
$filme2 = $_POST["filme2"];

$movie = $tmdb->getMovie($filme2);
// returns a Movie Object

$escolhas[] = $movie->getTitle();

echo '

                Adicionado a lista!

';
echo $movie->getTitle();

echo '

';

        echo "
Lista para assistir:
";
        for ($i = 0; $i < count($escolhas); $i++) {
          echo $escolhas[$i];
          echo "
";
        }

?>

A: Por padrão, cada execução de um programa PHP começa "pedra limpa", virgem. Para persistir dados ao longo de diversos acessos do mesmo cliente, é preciso criar uma sessão.
No início do programa, chame
session_start()

e substitua as referências à matriz "escolhas" por
$_SESSION['escolhas']

visto que apenas a matriz associativa $_SESSION é persistida entre sessões, o que você quer que dure, tem de ficar ali dentro.
Para iniciar a matriz na primeira vez (quando ela ainda não existe na sessão corrente) faça
if (! isset($_SESSION['escolhas']))
   $_SESSION['escolhas'] = array();
}

A propósito, vou descrever como funciona o mecanismo de sessão. Como eu disse antes, cada execução de uma página PHP começa do zero absoluto.
A função session_start() gera um código aleatório e insere esse código no cabeçalho da resposta HTTP, que no lado cliente (browse) é armazenada num cookie.
Quando o mesmo cliente acessa outra página do mesmo servidor, o cookie é enviado no cabeçalho da requisição HTTP. A função session_start() detecta esse cookie, e determina que o cliente já é conhecido.
O cookie armazena apenas um "session ID". O conteúdo da variável $_SESSION fica armazenada no servidor, geralmente numa pasta de arquivos temporários (/tmp no Linux).
O cliente não tem como acessar o conteúdo de $_SESSION diretamente, então é considerado seguro deixar informações sensíveis nele.
As informações de uma sessão devem ser consideradas voláteis. Se alguma coisa precisa persistir para além de uma sessão (por exemplo, se um cliente acessa a informação de mais de um computador diferente), aí é preciso guardá-la num banco de dados.
É possível armazenar a sessão em banco de dados, caso em que ela não se perde mesmo se o servidor for resetado ou substituído. Isto é útil, por exemplo, quando há um cluster de servidores respondendo por um mesmo site, e a sessão deva ser mantida mesmo que as requisições do cliente caiam em diferentes máquinas. Também é útil quando o site roda dentro de um container Docker, pois o restart do container já apagaria todas as sessões se elas fossem armazenadas na forma de arquivos temporários.
As sessões são um mecanismo ideal para quando o PHP serve páginas Web tradicionais. Para Webservices, pode-se considerar alguma outra tecnologia como JWT.


text:
Q: Optional Randomization of enum variable I am writing a Testbench using Systemverilog and I want to have the freedom to choose in each test to either randomize some variables or specify their value (from a .do file or from command line). Is there any option in Systemverilog to do this?

A: There are many things you can do, but the simplest is putting +some_variable=value on the command line, and then in your code
if (!$value$plusargs("some_variable=%0d",some_variable)
   some_variable = $urandom;

A: Declare a variable and use $urandom or $urandom_range to generate random values. When you want to pass values from the command line, you can use $value$plusargs.
Read up on Chapter 21 (Input/output system tasks) of the LRM to find examples.


text:
Q: decrypting a AES-256 encrypted file not working I use the Botan library for encrypting and my encrypting code looks like below.
  LibraryInitializer init;
  AutoSeeded_RNG rng;
  string passphrase="mypassword";

  PBKDF* pbkdf = get_pbkdf("PBKDF2(SHA-256)");
  SecureVector<byte> salt = rng.random_vec(16);
  InitializationVector iv(rng,16);
  OctetString aes256_key = pbkdf->derive_key(32, passphrase,&salt[0],   salt.size(), 10000 );
  cout<<"Encryption key : " << aes256_key.as_string() <<endl ;

 ifstream infile ("readme.txt");
 ofstream outfile ("encrypt.txt");

Pipe pipe(get_cipher("AES-256/EAX", aes256_key,iv, ENCRYPTION) );

pipe.start_msg();
infile>>pipe;
pipe.end_msg();

SecureVector<byte> cl = pipe.read_all();

outfile.write((const char*)cl.begin(), cl.size());

outfile.flush();
outfile.close();
infile.close();

this code looks working great and encrypt the input file. i posted this code to determine if there is an error in the encryption. (but I assume that the encryption is done correctly)
now the above encrypted file is tried to decrypt by the following code.
ifstream infile2 ("encrypt.txt");
ofstream outfile2 ("decrypt.txt");

Pipe pipe2 (get_cipher("AES-256/EAX", aes256_key, iv, DECRYPTION) );

pipe2.start_msg();
infile2 >> pipe2;
pipe2.end_msg();

SecureVector<byte> cl2 = pipe2.read_all();

outfile2.write((const char*)cl2.begin(), cl2.size());

outfile2.close();
infile2.close();
}

the same above generated decryption key and the InitializationVector iv is used for the decryption.
the decryption throws an exception AES-256/EAX : message authentication failed
what am I doing wrong here and how to decrypt the above encryptrd file correctly.

A: The problem is that ifstream and ofstream assumes character output. If you configure it to handle binary by using std::ios::binary as second argument then your code should be alright. This is also used by the Botan API reference if it doesn't explicitly encode the ciphertext as well.


text:
Q: Retirar nomes duplicados por aproximação VBA Boa tarde!
Existe algum tipo de código para encontrar/retirar as duplicidades por aproximação? Estou tentando limpar uma base muito grande, porém os nomes que foram inseridos possuem erros de digitação ou letras com a mesma fonética.
Por exemplo: Luiz Carlos Silva ou Luis Carlos Silva
Obrigado!

A: 1a Opção - Fuzzy Lookup Add-In for Excel
Você pode usar o Fuzzy Lookup Add-In for Excel ou criar a própria lógica Fuzzy num programa. Procure por Procura Difusa ou em inglês fuzzy search/lookup.

O Fuzzy Lookup Add-in para Excel foi desenvolvido pela Microsoft Research e uma correspondência difusa de dados de texto no Microsoft Excel. Ele pode ser usado para identificar linhas de duplicatas difusas dentro de uma única tabela ou para junções confusas em filas semelhantes entre duas tabelas diferentes. A correspondência é robusta para uma grande variedade de erros, incluindo erros ortográficos, abreviaturas, sinônimos e dados adicionados / ausentes. Por exemplo, pode detectar que as linhas "Mr. Andrew Hill", "Hill, Andrew R." e "Andy Hill" se referem à mesma entidade subjacente, retornando à pontuação de similaridade com cada partida. Embora a configuração padrão funcione bem para uma grande variedade de dados textuais, como nomes de produtos ou endereços de clientes, a correspondência também pode ser personalizada para domínios ou idiomas específicos. (Tradução Google Tradutor.)

2a Opção - Código VBA
Este código foi testado no Excel VBA e os créditos estão nesta página.
Public Function Similarity(ByVal String1 As String, _
    ByVal String2 As String, _
    Optional ByRef RetMatch As String, _
    Optional min_match = 1) As Single
Dim b1() As Byte, b2() As Byte
Dim lngLen1 As Long, lngLen2 As Long
Dim lngResult As Long

If UCase(String1) = UCase(String2) Then
    Similarity = 1
Else:
    lngLen1 = Len(String1)
    lngLen2 = Len(String2)
    If (lngLen1 = 0) Or (lngLen2 = 0) Then
        Similarity = 0
    Else:
        b1() = StrConv(UCase(String1), vbFromUnicode)
        b2() = StrConv(UCase(String2), vbFromUnicode)
        lngResult = Similarity_sub(0, lngLen1 - 1, _
        0, lngLen2 - 1, _
        b1, b2, _
        String1, _
        RetMatch, _
        min_match)
        Erase b1
        Erase b2
        If lngLen1 >= lngLen2 Then
            Similarity = lngResult / lngLen1
        Else
            Similarity = lngResult / lngLen2
        End If
    End If
End If

End Function

Private Function Similarity_sub(ByVal start1 As Long, ByVal end1 As Long, _
                                ByVal start2 As Long, ByVal end2 As Long, _
                                ByRef b1() As Byte, ByRef b2() As Byte, _
                                ByVal FirstString As String, _
                                ByRef RetMatch As String, _
                                ByVal min_match As Long, _
                                Optional recur_level As Integer = 0) As Long
    '* CALLED BY: Similarity *(RECURSIVE)

    Dim lngCurr1 As Long, lngCurr2 As Long
    Dim lngMatchAt1 As Long, lngMatchAt2 As Long
    Dim I As Long
    Dim lngLongestMatch As Long, lngLocalLongestMatch As Long
    Dim strRetMatch1 As String, strRetMatch2 As String

    If (start1 > end1) Or (start1 < 0) Or (end1 - start1 + 1 < min_match) _
       Or (start2 > end2) Or (start2 < 0) Or (end2 - start2 + 1 < min_match) Then
        Exit Function                            '(exit if start/end is out of string, or length is too short)
    End If

    For lngCurr1 = start1 To end1
        For lngCurr2 = start2 To end2
            I = 0
            Do Until b1(lngCurr1 + I) <> b2(lngCurr2 + I)
                I = I + 1
                If I > lngLongestMatch Then
                    lngMatchAt1 = lngCurr1
                    lngMatchAt2 = lngCurr2
                    lngLongestMatch = I
                End If
                If (lngCurr1 + I) > end1 Or (lngCurr2 + I) > end2 Then Exit Do
            Loop
        Next lngCurr2
    Next lngCurr1

    If lngLongestMatch < min_match Then Exit Function

    lngLocalLongestMatch = lngLongestMatch
    RetMatch = ""

    lngLongestMatch = lngLongestMatch _
                    + Similarity_sub(start1, lngMatchAt1 - 1, _
                                     start2, lngMatchAt2 - 1, _
                                     b1, b2, _
                                     FirstString, _
                                     strRetMatch1, _
                                     min_match, _
                                     recur_level + 1)
    If strRetMatch1 <> "" Then
        RetMatch = RetMatch & strRetMatch1 & "*"
    Else
        RetMatch = RetMatch & IIf(recur_level = 0 _
                                  And lngLocalLongestMatch > 0 _
                                  And (lngMatchAt1 > 1 Or lngMatchAt2 > 1) _
                                  , "*", "")
    End If

    RetMatch = RetMatch & Mid$(FirstString, lngMatchAt1 + 1, lngLocalLongestMatch)

    lngLongestMatch = lngLongestMatch _
                    + Similarity_sub(lngMatchAt1 + lngLocalLongestMatch, end1, _
                                     lngMatchAt2 + lngLocalLongestMatch, end2, _
                                     b1, b2, _
                                     FirstString, _
                                     strRetMatch2, _
                                     min_match, _
                                     recur_level + 1)

    If strRetMatch2 <> "" Then
        RetMatch = RetMatch & "*" & strRetMatch2
    Else
        RetMatch = RetMatch & IIf(recur_level = 0 _
                                  And lngLocalLongestMatch > 0 _
                                  And ((lngMatchAt1 + lngLocalLongestMatch < end1) _
                                       Or (lngMatchAt2 + lngLocalLongestMatch < end2)) _
                                  , "*", "")
    End If

    Similarity_sub = lngLongestMatch

End Function

Que um teste simples é o visto na imagem a seguir:

Que significa que ambos possuem uma similaridade de 94,1176%.
Esta função (Similarity) pode ser utilizada para comparar uma base de dados e a partir de um ponto de ajuste mínimo as duplicatas podem ser encontradas por similaridade em porcentagem. Esta análise pode ser demorada para uma base grande, sendo necessária uma programação de boa qualidade e com ênfase na performance, caso deseje um tempo de processamento melhor.
3a Opção - Distância Levenshtein
Créditos: sysmod
Private Declare Function GetTickCount Lib "kernel32.dll" () As Long

Option Explicit
'Option Base 0 assumed

Sub testLevenshtein()
Dim s1 As String, s2 As String, lTime As Long, i As Long, teste As Long

s1 = "Luiz Carlos Silva"
s2 = "Luis Carlos Silva"

lTime = GetTickCount()

   teste = LevenshteinB(s1, s2)

Debug.Print GetTickCount - lTime; " ms" ' 234  ms
Debug.Print teste
End Sub

'POB: fn with byte array and inline MIN code is 17 times faster
Function LevenshteinB(ByVal string1 As String, ByVal string2 As String) As Long
'http://www.sysmod.com/modLevenshtein.bas
Dim i As Long, j As Long, ByteArray1() As Byte, ByteArray2() As Byte
Dim string1_length As Long
Dim string2_length As Long
Dim distance() As Long
Dim min1 As Long, min2 As Long, min3 As Long
Const UseWSMIN = False

string1_length = Len(string1)
string2_length = Len(string2)
ReDim distance(string1_length, string2_length)
ByteArray1 = string1
ByteArray2 = string2

For i = 0 To string1_length
    distance(i, 0) = i
Next

For j = 0 To string2_length
    distance(0, j) = j
Next

For i = 1 To string1_length
    For j = 1 To string2_length
        'Unicode, compare both even and odd bytes
        If ByteArray1((i - 1) * 2) = ByteArray2((j - 1) * 2) And _
            ByteArray1((i - 1) * 2 + 1) = ByteArray2((j - 1) * 2 + 1) Then
            distance(i, j) = distance(i - 1, j - 1)
        Else
          If UseWSMIN Then
            distance(i, j) = WorksheetFunction.Min _
            (distance(i - 1, j) + 1, _
             distance(i, j - 1) + 1, _
             distance(i - 1, j - 1) + 1)
          Else
            ' spell it out, 50 times faster than worksheetfunction.min
            min1 = distance(i - 1, j) + 1
            min2 = distance(i, j - 1) + 1
            min3 = distance(i - 1, j - 1) + 1
            If min1 <= min2 And min1 <= min3 Then
                distance(i, j) = min1
            ElseIf min2 <= min1 And min2 <= min3 Then
                distance(i, j) = min2
            Else
                distance(i, j) = min3
            End If
          End If
        End If
    Next
Next

LevenshteinB = distance(string1_length, string2_length)

End Function

Que retorna o resultado da imagem:

Neste teste as informações que aparecem são de quantos caracteres são diferentes entre as duas Strings e o tempo para uma comparação que é de menos de 1 ms, para 100 iterações levou 16 ms.
EDIT:
Um código de exemplo para trabalhar com a função de similaridade:
Sub testSimilaridade()
    Dim LastRow As Long, i As Long
    Dim Arr() As Variant, NewArr() As Variant
    Dim Names As Worksheet, ws As Worksheet
    Dim Similaridade As Single, Limite As Single
    Set Names = ThisWorkbook.Worksheets("Names")
    SheetKiller ("NewNames")
    Set ws = Sheets.Add
    ws.Name = "NewNames"
    LastRow = Names.Cells(Names.Rows.Count, "A").End(xlUp).Row

    Arr = Names.Range("a2", Names.Cells(LastRow, 1))
    NewArr = Arr
    Limite = 0.9

    For i = LBound(Arr) To UBound(Arr)
        If Not i = UBound(Arr) Then x = i + 1
        For k = x To UBound(Arr)
            Similaridade = Similarity(CStr(Arr(i, 1)), CStr(Arr(k, 1)))
            If Similaridade > Limite Then
                NewArr(k, 1) = ""
            End If
        Next k
    Next i

    For i = LBound(Arr) To UBound(Arr)
        ws.Cells(i, 1) = NewArr(i, 1)
    Next i
    ws.Range("A:A").Sort Key1:=ws.Range("A2"), Order1:=xlAscending, Header:=xlYes
End Sub

Public Function SheetKiller(Name As String)
    Dim s As Worksheet, t As String
    Dim i As Long, k As Long
    k = Sheets.Count

    For i = k To 1 Step -1
        t = Sheets(i).Name
        If t = Name Then
            Application.DisplayAlerts = False
            Sheets(i).Delete
            Application.DisplayAlerts = True
        End If
    Next i
End Function

Resultados:
Com estes dados de exemplo:

O Resultado é o seguinte:

Outro Teste de Resultado
Um teste pode ser feito com a base de dados "nickname-and-diminutive-names-lookup", que com 2266 entradas, a saída foi de 1509 registros. Realizando em menos de 60 segundos.
Para realizar o parse dos dados, fazer um copiar e colar dos dados raw na célula A2. E depois rodar o seguinte código:
Sub test()

Dim ws As Worksheet, source As Worksheet
Dim LastRowA As Long, LastRowB As Long, i As Long, k As Long
Dim strCell As String
SheetKiller ("Names")
Set ws = Sheets.Add
ws.Name = "Names"
Set source = ThisWorkbook.Worksheets("Planilha1")

LastRowA = source.Cells(source.Rows.Count, "A").End(xlUp).Row

For i = 1 To LastRowA
    strCell = CStr(source.Cells(i, 1))
    Count = Len(strCell) - Len(Replace(strCell, ",", ""))
    For k = 1 To Count
        LastRowB = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
        ws.Cells(LastRowB + 1, 1) = EXTRACTELEMENT(strCell, k, ",")
    Next k
Next i
End Sub

Function EXTRACTELEMENT(Txt As String, n, Separator As String) As String
    On Error GoTo ErrHandler:
    EXTRACTELEMENT = Split(Application.Trim(Mid(Txt, 1)), Separator)(n - 1)
    Exit Function
ErrHandler:
    ' error handling code
    EXTRACTELEMENT = CVErr(xlErrNA)
    On Error GoTo 0
End Function


text:
Q: When I am in a directory using SVN and select to ignore the extension does this affect the whole project? There is a sub-directory of my site, /mysite/admin/logs, and I would like to configure SVN to ignore the log files in this directory.  The log files have an extension, say ".MYEXT" that is NOT unique to only log files.  Other directories in the project contain files with the same extension which are needed in SVN.  I would like to ignore all the ".info" files in the current directory (non-recursive) but not anywhere else in the project.
When using SVN, I right click while inside the log directory and find the option to ignore.  If I select the option "*.MYEXT" will this only ignore the ".MYEXT" files in the current directory or does it cause all the files with the ".MYEXT" extension to be ignored in the entire project?

A: In Tortoise 1.8.4 you have the option to ignore only in this directory, or recursively, when you select the file. For example, when I right click and select Ignore for foo.xyz file I see 4 options in the ignore menu:

*

*foo.xyz

**.xyz

*foo.xyz (recursively)

**.xyz (recursively)

In general, when you ignore a file it only affects the directory you are in. SVN creates/updates the svn:ignore property on the directory (see here). If you look at this section of the documentation you'll find this section (bolding mine):

When found on a versioned directory, the svn:ignore property is
  expected to contain a list of newline-delimited file patterns that
  Subversion should use to determine ignorable objects in that same
  directory. These patterns do not override those found in the
  global-ignores runtime configuration option, but are instead appended
  to that list. And it's worth noting again that, unlike the
  global-ignores option, the patterns found in the svn:ignore property
  apply only to the directory on which that property is set, and not to
  any of its subdirectories. The svn:ignore property is a good way to
  tell Subversion to ignore files that are likely to be present in every
  user's working copy of that directory, such as compiler output or—to
  use an example more appropriate to this book—the HTML, PDF, or
  PostScript files generated as the result of a conversion of some
  source DocBook XML files to a more legible output format.


text:
Q: SQlite database I don't know what's best for me at the moment. I want a part in my app were the users enter their post code in a field box. The data will call company near them once entered.
So I don't know where to start because I have been reading about databases in android. Some people say that SQLite isn't any good. If you can help me and tell me what's best to use.
Thanks people

A: use web services instead of SQlite .
Access MySQL or any other data base using json or xml web services.
For that you have to make webservices using php ,ruby on rails,.NET or any other server side programming language.

A: Using the local SQLite on your device is a good choice to go when the data kind of static, that means it is not changing or expanding a lot. You don't generate too much network trafic. But consider that you have to download the data once from a server, handle changes made on the server, etc. So if your data changes a lot, querying the server database might be better.


text:
Q: CPU register count and access time It has been suggested that one of the reasons typical RISC CPUs stop at 32 architectural integer registers, despite a 32-bit instruction having enough spare bits to specify 64, is that a larger register bank takes more time to access, which would impact clock speed.
However, modern CPUs typically have even more than 64 physical integer registers, using register renaming to map architectural to physical.
Does this mean process technology eventually made circuits fast enough that a large register bank can be accessed quickly after all? Or is there a reason physical registers don't impact access time as much as architectural registers?

A: Unless you provide link who has suggested it and why, there's a huge field for guessing and speculation. I do not know the right answer to your question, and I believe that it may simply be historical.
Consider the following:

*

*The statement you cited is actually true; larger RAM set (and registers are organized as SRAM) required larger decoding circuits, thus more registers leads to more delays, and thus designers of RISC CPU should be lowering clock speed for reliable CPU operation;

*Look at this article, page 8. RISC having 32 registers against CISC's 16 registers was anyway the great breakthrough in computing. It may be that number of registers suffered the same myth of Bill Gates's 640KB RAM statement, and 32 registers was (and maybe still?) considered as enough;

*Discussion about having a lot of registers on the core is similar having a lot of cache. Significant research was made on cache sizes, and (to my knowledge) it was proven that larger cache sizes may hit performance negatively. So the same with registers; for general purpose math and data management software application 32 registers (32 integer plus 32 floating point) may be enough (my personal opinion);

*It would be logical to focus on increasing speed of main RAM access rather than increasing register set. You can increase number of registers to 1024, with significant increase in silicon cost, but you can easily increase external RAM from 256MB to 16GB with a fraction of that cost.

As a conclusion, the architecture of the CPU depends on the purpose it is designed for, the tasks it is going to perform and type of operations it is going to make; size of immediate RAM required (registers), size of all RAM required, etc. And of course the cost of CPU and its supporting logic.
Update:

but never mentions the fact that 32 registers is not enough

Enough or not enough register space is a subjective matter; some people consider 12 * 16-bit registers as enough when application can access 64KB of RAM. A lot of people code in high level language these days, thus do not care about register set at all, conversion into executable is handled by the compiler.

CPUs actually have at least 80 and sometimes more than 100 physical registers

Naming new registers within assembly language (in other words - giving code running direct access to those registers) requires standardization. Might be someone will dare upgrading 32 directly accessible register set into 64, 128 or 256 registers, and then try to promote new standard into the masses. Probably it is not economically viable at this time.

So why doesn't the reason for sticking to 32 architecture registers

Maybe for compatibility reasons? Imagine you release CPU supporting 512 directly addressable registers, and developers will start programming for it (using assembly or through compiler). Resulting low level code will not be easily portable to systems with 32 register set.

entails spending a lot of resources on register renaming

Renaming is not just about using extra registers available; this technique is more about parallelism and performance gained with it - including currently available code oriented (and already assembled) for 32 register set.

A: Okay, according to someone on the RISC-V discussion list, the difference between architectural and physical registers isn't about cost, it's that instruction scheduling strategy is all or nothing. Unless you are going to commit to VLIW/EPIC, physical registers are going to be different from architectural anyway, so moving the architectural register account closer to the physical count doesn't achieve anything.
https://groups.google.com/a/groups.riscv.org/forum/#!topic/isa-dev/_owZu4I1WB0


text:
Q: Enable link after first click
Requirements:

When I clicked first time on menu item which has dropdown menu, It should show its dropdown and when I clicked on the same menu item second time it will redirect to its own page.
Please consider the situation. Menu item redirect to its own page only when its dropdown are opens

Reference Images:

Reference website link:

Reference website link

Note for referaence website:

1) Please open reference website link on mobile view.
2) Click on about page than Dental Page and than again About page , When you second time clicked on about page It goes to its own page. But on this occasion I want to open its dropdown and again If I clicked About page than it goes to its own page
Currently I am using jQuery bind function and disable link through event.preventDefault() but i didn't resolve my problem
Here's my code

jQuery Code:

$(document).ready(function(){
    $(".flexnav li.parent-menu-item > a").bind("click.myclick", function(event) {
        event.preventDefault();
        $(".flexnav li .sub-menu").hide();
        $(this).unbind(".myclick");
        $(this).parents(".flexnav li.parent-menu-item").children(".sub-menu").toggle();
    });
});

Sorry for my language mistakesThanks!

A: Instead of handling the click event inside the $(document).ready function, you should try doing it inline with each li.

    ...

    ...

So, here, what I am doing is to call the ShowMenu() function with the id of the menu I want to show, as the parameter and the url of the page linked to it.
The function then checks if that menu is being displayed or not. If being displayed then it redirects the user to the url. If not, then it proceeds to hide all other dropdowns and shows only the one that was clicked.

A: You can use CSS class toggle to see if the dropdown is open or not and perform the action accordingly. (Assuming your current code is working fine to open dropdown)
$("body").on("click",".flexnav li.parent-menu-item > a",function(e){
   var dropdowns=$(this).parent('li').children(".sub-menu");
   var menu=$(this).parents(".flexnav li.parent-menu-item").children(".sub-menu");
   if(dropdowns.size()>0) {
       if(!menu.hasClass('open')) {
           e.preventDefault();
           menu.addClass('open');
           menu.show();
       }
   }
});


text:
Q: Gems not in Local Gems after bundle install New machine. New rbenv install. New rbenv-gemset install. New ruby-2.0.0 install. New rails 4.0.0 app.
When I
$ bundle install

from the rails app directory, I get
Your bundle is complete!
It was installed into ./vendor/bundle

But, if I then
$ gem list

none of the gems that were supposedly installed show up.
I have run
$ rbenv rehash

Why could this be?
Additional info:
$ which bundle
/usr/local/var/rbenv/shims/bundle
$ rbenv which bundle
/usr/local/var/rbenv/versions/2.0.0-p247/bin/bundle
$ rbenv which ruby
/usr/local/var/rbenv/versions/2.0.0-p247/bin/ruby
$ ruby --version
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.4.0]
$ rbenv gemset active
blog
$ which rails
/usr/local/var/rbenv/shims/rails

A: Your default in this app is to install to vendor/bundle. You can tell this by It was installed into ./vendor/bundle text which appears after gems installation.
Bundler documentation specifies that you have to pass --system to install in system location:
--system: Install to the system location ($BUNDLE_PATH or $GEM_HOME) even
          if the bundle was previously installed somewhere else for this
          application

EDIT: More explanation is that your ruby knows only about gems installed with --system option when not using bundle exec. You can see your gems from vendor/bundle or whatever path you've chosen by running bundle exec gem list or (as Casper noticed) bundle list. Now it is your choice whether you want your gems in system location or in application directory.


text:
Q: Is it possible to have Skype Integration using SPFx React Webpart I am working on Skype Integration With SPFx React webpart in Office 365. I tried to refer below URL
http://www.sharepointcolumn.com/lync-presence-indicators-code-snippets-in-sharepoint-2013/
but some of the HTML attributes is not supporting in React Component and IMNImageOnClick function is also undefined in Workbench, may be some reference JS need to load explicitly in SPFx webpart.
any kind of suggestion will be helpful
Thanks

A: you can use dangerouslySetInnerHTML
render() {
    return (<span dangerouslySetInnerHTML={{__html: `

               `}}>
            );
}

Dangerously Set innerHTML


text:
Q: ReactJS how to run an API call when a state has a particular value I'm teaching myself React and one of my exercises is using axios to fetch a list of countries from an API
const fetchCountries = () => {
    axios.get("https://restcountries.eu/rest/v2/all").then(response => {
      setCountries(response.data);
    });
  };

  React.useEffect(fetchCountries, []);

Then as a user types into an input the list of countries filters down.
  const handleInputChange = event => {

    const filter = event.target.value; // current input value
    let matchingCountries = query !== ''
        ? countries.filter(country => country.name.toLowerCase().indexOf(query.toLowerCase()) !== -1)
        : countries;
    setQuery(filter);
    setMatches(matchingCountries)
    console.log('matches', matches)
    console.log('query', query)
  };

My goal is that when a single country is matched, a new API request is triggered (to fetch the weather, but the what isn't my problem, the timing is). When a single country is matched, I will then render some data about the country, then fetch and render the weather details for the single country's capital city.
One of the problems I'm having is that when I set the state, the value always seems to be one step behind. For example, in this Codepen when you enter FRA you should get "France". However, I have to enter "FRAN" to get the match. This doesn't happen when I don't use a state variable for the matches (just let matches). This becomes a problem because I need to run the next API call when the number of matches = 1, but the length of the matches state is always wrong.
So I would like to know 1. how to get the correct state of the matched countries. And 2. when I should run the second API call without getting into an infinite loop.

A: useEffect solution using separation of concern
1 function should do 1 thing

*

*handleInputChange updates state

*useEffect updates state

But they are not coupled.
Later you might have a new function called handleDropdownChange which updates state
It that case you don't need to modify useEffect
At the end of the day, we (developers) don't like to rewrite things
  const [countries, setCountries] = React.useState([]);
  const [query, setQuery] = React.useState("");
  const [matches, setMatches] = React.useState([]);

  React.useEffect(() => {
    let matchingCountries = query !== ''
        ? countries.filter(country => country.name.toLowerCase().indexOf(query.toLowerCase()) !== -1)
        : countries;

    setMatches(matchingCountries)
  }, [query]);                          // called whenever state.query updated

  const handleInputChange = event => {
    setQuery(event.target.value);       // update state
  };

  const fetchCountries = () => {
    axios.get("https://restcountries.eu/rest/v2/all").then(response => {
      setCountries(response.data);
    });
  };

  React.useEffect(fetchCountries, []);

And there is also solution (not recommended) by directly using event.target.value provided by @Joseph D.

A: The only problem is you are using an old query value in handleInputChange().
Remember setting the state is asynchronous (i.e. doesn't take effect immediately)
Here's an updated version:
const handleInputChange = event => {

  const filter = event.target.value; // current input value
  let matchingCountries = filter ? <code here>
  // ...
  setQuery(filter);
};

UPDATE:
To call the weather api if there's a single country match is to have matches as dependency in useEffect().
useEffect(
  () => {
    async function queryWeatherApi() {
      // const data = await fetch(...)
      // setData(data)
    }

    if (matches.length === 1) {
      queryWeatherApi();
    }
  },
  [matches]
)

A: 1) The reason for your problem is in this line:
let matchingCountries = filter !== ''
        ? countries.filter(country => country.name.toLowerCase().indexOf(query.toLowerCase()) !== -1)
        : countries;

you use query instead of filter variable, your handler function should look like this:
const handleInputChange = event => {

    const filter = event.target.value; // current input value
    let matchingCountries = filter !== ''
        ? countries.filter(country => country.name.toLowerCase().indexOf(filter.toLowerCase()) !== -1)
        : countries;

    setQuery(filter);
    setMatches(matchingCountries)
  };

2) Where to run your next API call:
For studying purpose I do not want to recommend you using some application state management lib like redux.Just calling it right after setFilter and setQuery. It will run as expected. Because calling an API is asynchronous too so it will be executed after setQuery and setFilter what does not happen with console.log, a synchronous function.


text:
Q: How to extract jquery ajax data to html? I am struggling to understand why it is not working. My .json file is correct but I cannot extract the data to display them on Html.
weather.js:
$(document).ready(function() {
    $.ajax({
        url: "weather.json",
        type: "GET",
        dataType: "json", // Returns JSON
        success: function(response) {
            var sTxt = '';
            $.each(response.weather, function(index) {
                sTxt += '
' + response.weather[index].name + '
';
            });
            $('#weatherlist').append(sTxt);
        },
        error: function() {
            $('#info').html('
An error has occurred
');
        }
    });
});

weather.html:
<!DOCTYPE html>

    <title>Ajax and json Data</title>
    <meta charset="UTF-8">

    <link rel="stylesheet" type="text/css" href="styles.css">

British and Irish Counties - Weather Data

Here is the new Html, with the  before the existing one, I still have an error: jquery.min.js:4 XMLHttpRequest cannot load file:///C:/Users/jull/Desktop/weather.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
<!DOCTYPE html>

    <title>Ajax and json Data</title>
    <meta charset="UTF-8">

    <link rel="stylesheet" type="text/css" href="styles.css">

British and Irish Counties - Weather Data

A: Open your browser's Developer Tools. Look in the Console. It will say:

Uncaught ReferenceError: $ is not defined

You are trying to use jQuery, but you haven't included it.
Add another script element (before the one you have already) and use it to load the jQuery library.

A: You have to use

JSON.parse(response)


text:
Q: First time using coding python, how I fix the can only concatenate str (not "int") to str phrase = "This is amazing"
print("How many characters in the variable phrase " + len(phrase) + "this are the numbers")

It says that can only concatenate str (not "int") to str

A: The case is that you can't concatenate string with integer, since len(phrase) returns the length from phrase that is why you are getting that error. So you cant convert the integer number to string and then concatenate in this way:
phrase = "This is amazing"
print("How many characters in the variable phrase " + str(len(phrase)) + "this are the numbers").

I suggest to use join function for better result when you concatenate strings


text:
Q: How to join split flv files? I'm in my 3rd day of trying to download one 4-minute video.  It's a Flash FLV that's split into three parts, the first two are about 5MB, the third about 3MB.
Only the first part has normal FLV headers, the next two have mostly just an FLV at the start.  I haven't resorted to trying to write something myself, just downloaded and tried a couple hundred megs of junky Windows software that doesn't actually do it.
As it turns out there's no need to download the video parts, you can pull them out of your browser's cache once you've played it through once.  I've tried CamStudio to capture the video from the screen as it's being played, but my fastest computer isn't fast enough.
I can't do this realtime.  I'd like to be doing this from OpenBSD but I've got one machine booted into Windows because there's no Flash for OpenBSD.  I can play it with MPlayer (Windows or OpenBSD), trying to do a simple join of the parts using MEncoder yields a video that stops at the first split.  Tried FFmpeg, too.  I'd like to convert it to anything more normal, like MP4 or AVI.
The 10.1 spec looks a lot different from 10.0 (hotlink to PDF)
The three FLVs in MC viewer (picture); the first is quite different:

A: Not a complete answer yet but FLVMeta and a partial reading of Adobe's spec are beginning to shine light on things.  From an FLVMeta full dump the tags or sections of data look like this:
    --- Tag #1019 at 0xCBEB5 (835253) ---
    Tag type: audio
    Body length: 213
    Timestamp: 124957
    * Sound type: stereo
    * Sound size: 16
    * Sound rate: 44
    * Sound format: AAC
    Previous tag size: 224
    --- Tag #1020 at 0xCBF99 (835481) ---
    Tag type: video
    Body length: 1201
    Timestamp: 124960
    * Video codec: AVC
    * Video frame type: inter frame
    Previous tag size: 1212
    --- Tag #1021 at 0xCC459 (836697) ---
    Tag type: audio
    Body length: 225
    Timestamp: 124980
    * Sound type: stereo
    * Sound size: 16
    * Sound rate: 44
    * Sound format: AAC
    Previous tag size: 236
    --- Tag #1022 at 0xCC549 (836937) ---
    Tag type: video
    Body length: 542
    Timestamp: 125000
    * Video codec: AVC
    * Video frame type: inter frame
    Previous tag size: 553

So you could read the header into one file, put all the tags into 1 file each, then reconstruct however many input files into however many output files you wanted.  Each "tag" I'd call a block, but it's a chunk of data.  You don't have to manipulate them in real time.  Each has a timestamp, you just have to put them together in that order and don't split a tag across files.
I wish FLVMeta had more useful output for moving things around under program control like tab or comma-delimited data.  Maybe even create an SQLite database for each project, put all the audio tags in one table, video in another, script in another.  Maybe I'll do that yet since it's open source and on Github.  It'd be simpler if flvs weren't big-endian and I'm on a little-endian machine.  All integers are big-endian, like on a Mac.

A: Done finally.  I ended up using a C program I wrote to concatenate them once I solved the bug that EOF on the first input file ended up as an FF or -1 in the output file, which stopped players and converters at that point.
flvmeta still gave warnings on the output of this but I was able to convert it to an mp4 using:
    ffmpeg -i out4.flv -vcodec copy -acodec copy out4.mp4

    /*
       My flv concat, a single-use program
    */

    #include <stdio.h>  // don't need most of these headers
    #include <stdlib.h>
    #include <string.h>
    #include <endian.h>  // FLVs have big endian values
    #include <unistd.h>
    #include <fcntl.h>
    #include <inttypes.h>

    FILE *opf;

    void docopy(char *fn, uint ofs) {
      FILE *ipf;
      unsigned char ch;
      ipf = fopen(fn,"r");
      if (ipf == NULL) {
        printf("Failed to open %s\n",fn);
        fclose(opf);
        exit(1);
      }
      fseek(ipf,ofs,SEEK_SET);  // jump to passed in offset
      while (!feof(ipf)) {  // not super efficient
        ch = fgetc(ipf);
      // this DOES have an effect, it stops the -1 from being written
        if (!feof(ipf))
          fputc(ch,opf);
      }
      printf("outfile now at %x\n",(unsigned int) ftell(opf));
      fclose(ipf);
    }

    void outhdr(void) { // write boilerplate flv header
      opf = fopen("out4.flv","w");
      if (opf == NULL) {
        printf("Error creating new output file.\n");
        exit(1);
      }
      fprintf(opf,"FLV%c%c%c%c%c%c",1,5,0,0,0,9); // audio and video enabled
      // This becomes the first PreviousTagSize:
      fprintf(opf,"%c%c%c%c",0,0,0,0);  // flvmeta seems to approve
    }

    int main(void) {
      outhdr();  // write a vanilla header
      docopy("media1.flv", 13);  // copy, starting at byte 13
      docopy("media2.flv", 13);
      docopy("media3.flv", 13);
      fclose(opf);
      return 0;
    }


text:
Q: prolog " how to answer this query" a) Write a predicate heads/2 ( a r g l , arg2) that takes an instantiated list of lists in argl and that computes as arg2 the list of heads of the sublists. For example:
?- heads([[3, 8], [9], [1, 2, 3], [a, b, c]], L).
L = [3, 9, l, a]

b) Define mply to take two inputs; an integer and list of integers. The result is a list of
integers formed by multiplying each integer in the list by the input integer. For example:
?- mply(5, [1, 2, 3], X).
X = [5, 10, 15]

c)Write a Prolog program called compute (Expr, Value) that will compute the
value (Value) of an arithmetic expression Expr. The requirement are as follows:
• An arithmetic expression is either a single number or a list in the form [Exprl,
Operator, Expr2]
• Exprl and Expr2 are arithmetic expressions
• Operator is either the atom plus or the atom minus.
Your program should work for the following queries:
?- compute(7, Val).
Val = 7

?- compute([2,plus,[9,minus,1]], Val).
Val = 10

I'm doing revision about prolog and very appreciate any help, thanks

A: For a) and b) you are required to traverse a list and perform a simple computation. General list traversal works as follows:
list_traverse([]).
list_traverse([H|T]) :- list_traverse(T).

Hence, in general your solutions should add input and output to the schema above.
Specifically, for a)
heads([],[]).
heads([H|T],[HH|TT]) :- H = [HH|_], heads(T,TT).

and for b)
mply(_,[],[]).
mply(X,[H|T],[HH|TT]) :- HH is X*H, mply(X,T,TT).

c) requires a slightly more elaborate processing since you have to distinguish between addition and subtraction:
compute([Val],Val) :- number(Val).
compute([E1,plus,E2],Val) :- compute(E1,V1), compute(E2,V2), Val is V1+V2.
compute([E1,minus,E2],Val) :- compute(E1,V1), compute(E2,V2), Val is V1-V2.

A: ad a) What does it mean to compute the head of an empty list? I assume that the predicate should then fail:

:- use_module(library(lambda)).

list_heads(XXs, Xs) :-
   maplist(\[X|_]^X^true,XXs, Xs).

mply(F, Xs, Zs) :-
   maplist(F+\X^Z^(Z is X*F), Xs, Zs).

compute([I],Val) :-
   Val is I.
compute([E1,plus,E2],Val) :- compute(E1,V1), compute(E2,V2), Val is V1+V2.
compute([E1,minus,E2],Val) :- compute(E1,V1), compute(E2,V2), Val is V1-V2.

Note that compute([_],V) will now issue an instantiation_error which is a much better idea than failing silently.


text:
Q: salesforce1 image upload on android
I added the html tag for bring up the file upload on Salesforce1. It works on the iphone but it doesn't work on the android phone ( Samsung Note 4 comes with Android 4.4.2 )
Is there anything missing or SF1 file upload doesn't work on the android

A: Google intentionally removed the functionality to open a file chooser from webviews in Android 4.4 (chromium 30 based webviews), as it wasn't a public API.  This impacts Cordova/Phonegap which Salesforce1 is built on top of.
According to this Android issue tracker thread it should be fixed in Android 4.4.3 (chromium 33 based webviews), though this appears to be a partial fix as some people appear to be still experiencing problems with that and 4.4.4.
There's some more detail from the Cordova perspective on their bug reporting system.


text:
Q: Force close on reading group SMS Hi I am developing an android SMS app and fetching the SMS from built in messaging app as
    Uri uriSMSURI = Uri.parse("content://mms-sms/conversations?simple=true");
    Cursor cursor = getContentResolver().query(uriSMSURI, new String[] {"*"}, null, null, "date desc");

        while (cursor.moveToNext())
        {
            snippet = cursor.getString(cursor.getColumnIndexOrThrow("snippet"));
            Long date = cursor.getLong(cursor.getColumnIndexOrThrow("date"));

            recipient_ids = cursor.getString(cursor.getColumnIndexOrThrow("recipient_ids"));
            recipient_ids.split(" ");

            Cursor c = getContentResolver().query(Uri.parse("content://mms-sms/canonical-addresses"), null, "_id = " + recipient_ids, null, null);
            c.moveToFirst();
            phonenumber= c.getString(c.getColumnIndexOrThrow("address"));

        }

When there are any group SMS , I am getting a force close in myApp as below
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.Sms}: android.database.sqlite.SQLiteException: near "8": syntax error: , while compiling: SELECT _id, address FROM canonical_addresses WHERE _id = 4 8

How do I read Group SMS and compare them with _id. Please Help.
Thanks!

A: I think the space between "4" and "8" is the problem.


text:
Q: wse3 PasswordDigest authentication from cxf I'm extending a legacy .NET ASP application (it cannot be upgraded). It will have a SOAP web service which will be called from CXF (java). I have installed and configured WSE3 extensions on the .NET side and now I can call my simple service from outside of ASP world with soap ui. Everything seems to work ok - I can block access for certain users authenticating with username and plaintext password. However, when I set the WSS-Passoword-Type to "PasswordDigest" in soap-ui I get the following message:

The security token could not be authenticated or authorized --->
  WSE562: The incoming username token contains a password hash. The
  built-in UsernameTokenManager does not support this type of
  UsernameToken. Please see the documentation for more details on the
  UsernameTokenManager.AuthenticateToken method

This service will be called from outside by an ESB - thus I don't have much choice for choosing auth scheme. I need the service to support "PasswordDigest".
Is there a way to implement it?
I know I can implement a custom UsernameTokenManager - but it has to return user password while it gets only hashed value. It doesn't help me.
Below for reference is the request I'm making:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:tem="http://tempuri.org/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
   <soap:Header>
      <wsse:Security soap:mustUnderstand="true" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
         <wsse:UsernameToken wsu:Id="UsernameToken-22">
            <wsse:Username>user</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">xHxNY51954nB9l3ulEp8fRX8HdE=</wsse:Password>
            <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">TEU+Z/yfS0oDTOxMZG+AXA==</wsse:Nonce>
            <wsu:Created>2012-07-02T11:39:17.695Z</wsu:Created>
         </wsse:UsernameToken>
      </wsse:Security>
   </soap:Header>
   <soap:Body>
      <tem:HelloWorld/>
   </soap:Body>
</soap:Envelope>


text:
Q: how could I get checkbox value in email after submit from https://formsubmit.co? hi I use https://formsubmit.co as form submit.

I could use select and text input, but I couldn't get value from checkbox.
 subscription
      <input
         type="checkbox"
         checked="checked"
         name="subscription"
         value="on"
         id="subscription"
       />

How could I get checkbox value in email after submit?
Thank you!

A: Checkbox value is not sent when it's unchecked, that's how HTML works. In order to send unchecked value, put hidden field before checkbox with same name and default unchecked value:

FormSubmit Demo

  <form target="_blank" action="https://formsubmit.co/your@email.com" method="POST">

    <input type="hidden" name="subscription" value="off">

    subscription
      <input
         type="checkbox"
         checked="checked"
         name="subscription"
         value="on"
         id="subscription"
       />

    <button type="submit" class="btn btn-lg btn-dark btn-block">Submit Form</button>
  </form>


text:
Q: Derivation of Stirling approximation from CLT In Casella Berger exercise 5.35, we have a sequence of sample means from the exponential $exp(1)$. Then, we can derive:
$$P\Bigg(\frac{\overline{X}_n - 1}{1/\sqrt{n}} \leq x\Bigg) \rightarrow P(Z \leq x)$$
where $Z \sim n(0, 1)$.
Now, the author suggests to show the Stirling approximation by taking the derivative on both sides. In short, he suggests:
$$\frac{d}{dx}P\Bigg(\frac{\overline{X}_n - 1}{1/\sqrt{n}} \leq x\Bigg) \approx \frac{d}{dx}P(Z \leq x)$$
from where the Stirling approximation follows.
Why are we justified doing this? Wiki article on weak convergence says:
"In general, convergence in distribution does not imply that the sequence of corresponding probability density functions will also converge."
Why is taking the derivative justified according to the author?
If it is allowed, can be it shown in some simple way without measure theory? Or link to the relevant theorems.

A: Let $f_n$ be the pdf of $Z_n=\sqrt{n}(\sum_i X_i/n-1)$ and $f$ be the pdf of a standard Gaussian. Then the exercise leads you to
$$f_n(0)=\frac{1}{n!}\left(\frac{n}{e}\right)^n \sqrt{n}$$
As you mention, from there we cannot simply use convergence in distribution to conclude that $f_n(0)\to f(0)=1/\sqrt{2\pi}$. Here is an argument based on characteristic functions to bypass this issue.

Let $\Phi_n(t)=e^{-it\sqrt{n}}(1-it/\sqrt{n})^{-n}$ be the characteristic function of $Z_n$ (note that it converges pointwise to $e^{-t^2/2}$, either by the CLT or by direct computation). Then,
$$|\Phi_n(t)|= \left| 1-\frac{it}{\sqrt{n}}\right|^{-n}=\left(1+\frac{t^2}{n}\right)^{-n/2}=\exp\left(-\frac{n}{2}\ln\left(1+\frac{t^2}{n}\right)\right)$$
Now it is just a simple exercise in real analysis to show that $|\Phi_n(t)|$ is uniformly dominated by an integrable function (treat the cases $t^2\le n$ and $t^2>n$ separately). Thus, from an inversion theorem and dominated convergence,
$$f_n(0)=\frac{1}{2\pi}\int_{-\infty}^{\infty} \Phi_n(t)\,dt\to 1/\sqrt{2\pi}.$$


text:
Q: How do I fix this incorrect emulator command line run by VS 2013 MDA when I target Android Emulator When I try to use "Android Emulator" as the target in Visual Studio for my Cordova app (running VS Tools for Cordova latest in VS 2013), I get about 6 or 7 errors. I noticed that the command line that VS tries to launch is missing quotes around the path to node.exe and uses double quotes around the path to emulator.js.
If I paste this into a cmd prompt and correct the quote problem, the emulator starts correctly. How can I fix this?
Here is the command line VS tries to run:
Starting launch process C:\Program Files (x86)\nodejs\node.exe ""C:\Users\Jason Learmouth\AppData\Roaming\npm\node_modules\vs-mda\emulator.js"" --platform android --path "c:\code..."

A: This is a known issue which will be fixed in next update. Workaround is to use user name without any spaces. Visual Studio is putting double double quotes because of space in emulator.js path like C:\Users\**Jason Learmouth**\AppData\Roaming\npm\node_modules\vs-mda\emulator.js


text:
Q: Lenovo G510 Wi-fi driver problems I'm new with Linux. Here is my story: I have installed Ubuntu 14.10 today on my laptop Lenovo G510 with the BCM43142 wireless card...  Everything works well except the wi-fi that i can't use. I have tried sudo apt-get bcmwl-kernel-source and it doesn't work. I have a wired connection in case that I need to download something to help me out resolving this issue. Help me please!
PS: Maybe it will help:
lspci -vvnn | grep -A 9 Network

08:00.0 Network controller [0280]: Broadcom Corporation BCM43142 802.11b/g/n [14e4:4365] (rev 01)
    Subsystem: Lenovo Device [17aa:0611]
    Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx-
    Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-
    Latency: 0, Cache Line Size: 64 bytes
    Interrupt: pin A routed to IRQ 11
    Region 0: Memory at b9500000 (64-bit, non-prefetchable) [size=32K]
    Capabilities: <access denied>

09:00.0 Ethernet controller [0200]: Qualcomm Atheros QCA8172 Fast Ethernet [1969:10a0] (rev 10)

A: You apparently forgot 'install.' The command you want is:
sudo apt-get install bcmwl-kernel-source

Reboot and your wireless should be working.

A: I'm using a Lenovo G510/I3 unit with Ubuntu 14.04.
I came across the same issue (wifi NOT working).And found the solution via an exhaustive search..
If you are interested in learning more about this issue - pls read through the below link (thanks to the community)
Installing Broadcom Wireless Drivers
Short answer:
1) First run below on the terminal
lspci -nn -d 14e4:
Which will most likely give you the below output :
02:00.0 Network controller [0280]: Broadcom Corporation BCM43142 802.11b/g/n [14e4:4365] (rev 01)
2) In that pls note the PCI.ID & the Rev number.
 [14e4:4365] (rev 01)

3) Run Update :
sudo apt-get update
4) Then install the firmware pakage.
sudo apt-get install  bcmwl-kernel-source
5) Reboot the system
sudo reboot
After that your wireless will be working :-D
Good luck...
Ps - I believe your Bluetooth is also not working ? SO far trying to find a solution to that . DO let me know if you find a solution...


text:
Q: Send mail with PHPMailer on iPage I have trouble sending emails from my iPage webserver.
Firstly I watched a tutorial on how to use PHPMailer and the guy used gmail smpt server. That method worked flawlessly on localhost, but it doesn't work on the webserver and I cant find a solution for this anywhere. Seems like the authentication didn't work because I've got an email from google security saying someone was trying to log in to my gmail (it was 100% ipage), even accepting the new login doesn't work
If there is a possibility I'd like to send mail from my custom domain email rather than form 3rd party gmail.
    require 'phpmailer/PHPMailer.php';
    require 'phpmailer/SMTP.php';
    require 'phpmailer/Exception.php';
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;
    $mail = new PHPMailer();
    $mail->isSMTP();
    $mail->Host = "smtp.gmail.com";
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = "tls";
    $mail->Port = "587";
    $mail->Username = ".....@gmail.com";
    $mail->Password = ".....";
    $mail->Subject = ".....";
    $mail->setFrom('.....@gmail.com');
    $mail->isHTML(true);
    $mail->Body = ".....";
    $mail->addAddress('.....@....');
    if ($mail->send()) echo "OK";
    else echo "BAD";
    $mail->smtpClose();


text:
Q: How does this data frame example in the Websocket RFC equal "Hello"? The first example of Section 5.7 of Websocket Protocol RFC 6455 reads:

A single-frame unmasked text message

*

*0x81 0x05 0x48 0x65 0x6c 0x6c 0x6f (contains "Hello")

What are the first two octets in this example and why are they there?
Looking up the UTF-8 codes for the last five octets I can see how those bytes would translate to Hello.

A: The first two octets in this example contain metadata about the data frame and the payload it contains.  The last five octets represent the payload or Hello.
The first two octets 0x81 0x05 are hexadecimal representations of two bytes or 16 bits of data.  In binary they translate to: 1000 0001 0000 0101.
Using the Data Frame Diagram from the RFC you can see what these bits tell us about the data frame.  To summarize:

*

*1st bit (FIN): indicates this is the final fragment of the message being sent

*5th-8th bits (opcode): the payload is a text message in UTF-8

*9th-16th bits (payload length): the length of the payload is 5


text:
Q: Excel - Auto fetching data from website to excel I am trying to write code which automatically could get data from the website,
I would like to replace last part of the URL address (text: "22A") with any text I have in a cell, for example, "G1"
Code from recorded macro:
    Sub USA()
'
' USA N-numbers Macro
'

'
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://www6.landings.com/cgi-bin/nph-search_nnr?pass=193800885&&nnumber=22A" _
, Destination:=Range("$A$1"))
.Name = "nph-search_nnr?pass=193800885&&nnumber=22A"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "18"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
Columns("A:A").ColumnWidth = 28.29
Columns("B:B").ColumnWidth = 4.57
End Sub

When I replace 22A with Range("G1").Value I am getting Compile error: "Expected: list separator or )"
Anybody knows what is wrong in my coding?

A: Replace:
"URL;http://www6.landings.com/cgi-bin/nph-search_nnr?pass=193800885&&nnumber=22A"
With:
"URL;www6.landings.com/cgi-bin/nph-search_nnr? pass=193800885&&nnumber=" _
   & Range("G1").Value


text:
Q: What is the difference between initialization a useState inside a useEffect? const [state, set_state] = useState(1);

vs
const [state, set_state] = useState();
useEffect(() => {
  set_state(1);
}, [])

Is there any real difference between the two in terms of in what cycle the update actually happens? Does using a useEffect cause an additional cycle, etc?

A: You're probably looking for the lazy initial state functional argument:

Lazy initial state
The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded. If the initial state is the result of an expensive computation, you may provide a function instead, which will be executed only on the initial render:
const [state, setState] = useState(() => {
  const initialState = someExpensiveComputation(props);
  return initialState;
});

But rather than just supply a link, let's examine the different behaviors of the code you showed (in addition to the lazy initial state functional argument).

A note about the code examples below:
They use a custom helper hook to record information about when component renders occur and when state values are updated. The outputs are serialized as JSON, so when a state value is undefined, it is represented as null in the JSON (because undefined is not a valid JSON type). Because of the restrictions of Stack Overflow's code snippet mechanism, there's a lot of repeated boilerplate — the code in focus is in the body of the App function.

Creating state initialized with a value:
const [state, setState] = useState(1);

In this case, the state is initialized once and never updated. The component is rendered one time:

Creating state uninitialized, then updating in a useEffect callback:
const [state, setState] = useState();

useEffect(() => {
  setState(1);
}, []);

In this case, the state is initialized with an implicit undefined value and the component is rendered. Then the useEffect hook's callback function is invoked and the state is updated, causing the component to render a second time:

Creating state initialized with a lazily-invoked function:
const [state, setState] = useState(() => 1);

Similar to the first example: in this case, the state is initialized once (using a function whose return value becomes the initial state value) and never updated. The component is rendered one time:

One more consideration is this: when using Strict Mode in development, React will unmount and re-mount your entire app's tree of nodes, effectively causing an extra render.

References:

*

*My React Component is rendering twice because of Strict Mode

*What is the difference between React running in development and production?


text:
Q: Open ppt from URL in android In my android app, I required open .ppt file from server url. But I don't
find any how I can open in my app or any third party app.
For example: Url > http://example.com/ppt/11_4_201611_04_22AM.ppt
If you know please let me know.
Thanks.

A: you have about three options
1) open it via google docs like below
WebView webview = (WebView)findViewById(R.id.containWebView);
webview.setWebViewClient(new AppWebViewClients());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setUseWideViewPort(true);
webview.loadUrl("http://docs.google.com/gview?embedded=true&url="
            + "YOUR_DOC_URL_HERE");
 public class AppWebViewClients extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // TODO Auto-generated method stub
    view.loadUrl(url);
    return true;
}
@Override
public void onPageFinished(WebView view, String url) {
    // TODO Auto-generated method stub
    super.onPageFinished(view, url);
 }
}

2) download the file and pass it through an intent to Microsoft powerpoint app
import android.support.v4.app.ShareCompat;
Uri pptUri = Uri.parse("file://sdcard/sdcard0/test.ppt");
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
                                     .setText("open ppt")
                                         .setType("application/vnd.ms-powerpoint")
                                         .setStream(pptUri )
                                         .getIntent()
                                 .setPackage("com.google.android.apps.docs");
startActivity(shareIntent);

3) download the file and use third party library to help you parsing the file and displaying it like itsrts/pptVieweer but look at issues first , as you cant release a signed apk while using this library.


text:
Q: plug-in for MOODLE How can i add a plug-in that i developed in MOODLE, considering the fact that MOODLE is an open source project?

A: Here is the documentation on installing contributed modules to moodle.  You have to be approved before your plugins are available to everybody.  If you wanted to get your plugin added as a core component, you should contact the development team.  Make sure you follow the guidelines for your contributed code.

A: Check the guidelines for contributed code. They should include everything you need to know about contributing to the moodle project. They describe that you have to submit it on their bugtracker, etc. -- for further question, I suggest you contact the moodle people directly.

A: The code checker plug in developed by the Open University (moodle.org/plugins/view.php?plugin=local_codechecker) is an invaluable tool for anyone hoping to contribute an extension to Moodle and incorporates general coding good practice.
I would recommend using this for any software you are planning to share with other Moodle users and using the forums at moodle.org to get some feedback on beta versions and your concept while developing your plug-in.

A: Moodle contributes code guidelines.
http://docs.moodle.org/dev/Guidelines_for_contributed_code#How_to_submit_code
Read the How to request that your code be tested/reviewed section.
Pay particular attention to following the moodle API
http://docs.moodle.org/dev/Coding


text:
Q: QMessageBox cerrar automaticamente Favor si alguien me puede ayudar diciendo como puedo hacer para generar un QMessageBox que se cierre automáticamente después de x segundos sin presionar ningún botón.
dejo un ejemplo del código que tengo
QMessageBox Logo;
Logo.setIconPixmap(QPixmap(":/icons/Logo.jpg").scaled(QSize(185,215),Qt::KeepAspectRatio));
Logo.setStandardButtons(0);
    Logo.show();
    //sleep(3); /*al ejecutar esto solo genera que se demore en aparecer la imagen */
Gui::MainWindow win;
    //Logo.close();/*no me esta cerrando el QMessageBox*/
    win.show();
    return app.exec();

Pd: todo esta ejecutado en el main

A: ya lo solucione dejo solución si a alguien le interesa, espero que les sirva
Gui::MainWindow win;
QMessageBox Logo;
    Logo.setIconPixmap(QPixmap(":/icons/Logo.jpg").scaled(QSize(185,215),Qt::KeepAspectRatio));
    Logo.setStandardButtons(0);
    Logo.show();
    QTimer timer;
    QObject::connect(&timer ,  SIGNAL(timeout ()),&Logo,SLOT(accept()));
    QObject::connect(&timer ,  SIGNAL(timeout ()),&win,SLOT(show()));
    timer.start(3000);//esto es solo por si alguien quiere que se espere 3 segundos antes de iniciar el win.show()

    return app.exec();


text:
Q: Demoiselle 2.4.0: Erro ao executar teste com JUnit Tenho um projeto construído a partir do arquétipo do Demoiselle para Maven. A aplicação gerada é aquela que exemplifica o Demoiselle, contendo um cadastro de bookmarks.
O programador que gerou a revisão zero da aplicação não mais se encontra acessível. Esta aplicação foi alterada para implementar diversos cadastros específicos, deixando de ser a aplicação exemplo para se tornar uma aplicação própria do nosso domínio de negócio.
O objetivo agora é adicionar funcionalidades e para a implementação de tais, fazer uso de TDD para primeiramente escrever os casos de teste e depois o código da aplicação em si (é uma aplicação legada, onde o TDD não foi utilizado em sua gênese).
Ao adicionar o primeiríssimo caso de teste, colocado abaixo, recebo uma exception stack. Os detalhes estão colocados abaixo.
O caso de teste é o seguinte:
package br.ufpr.sap.hibernate.tests;
// imports diversos
@RunWith(DemoiselleRunner.class)
public class AlunoRepositorioTests {
    @Inject
    AlunoRepository alunos;
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }
    @Before
    public void setUp() throws Exception {
    }
    @After
    public void tearDown() throws Exception {
    }
    @Test
    public void shouldSelecionarUmAlunoESeusObjetosRelacionados() {
        // Preparar
        Long idAluno = 31106L;

        // Executar
        Aluno aluno = alunos.itemPorId(idAluno);

        // Avaliar
        assertNotNull(aluno);
    }
}

As exceções recebidas são estão abaixo. A lista de chamadas foi recortada para facilitar a leitura.
org.jboss.weld.exceptions.WeldException: WELD-000049 Unable to invoke [method] @PostConstruct public br.gov.frameworkdemoiselle.internal.producer.EntityManagerFactoryProducer.loadPersistenceUnits() on br.gov.frameworkdemoiselle.internal.producer.EntityManagerFactoryProducer@68de8813
    at org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:400)
        ... muitas chamadas
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        ... muitas chamadas
    at org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:398)
    ... 69 more
Caused by: br.gov.frameworkdemoiselle.DemoiselleException: javax.persistence.PersistenceException: [PersistenceUnit: gd0] Unable to build EntityManagerFactory
    at br.gov.frameworkdemoiselle.internal.producer.EntityManagerFactoryProducer.loadPersistenceUnits(EntityManagerFactoryProducer.java:107)
    ... 79 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: gd0] Unable to build EntityManagerFactory
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)
        ... muitas chamadas
    at br.gov.frameworkdemoiselle.internal.producer.EntityManagerFactoryProducer.loadPersistenceUnits(EntityManagerFactoryProducer.java:105)
    ... 79 more
Caused by: org.hibernate.service.jndi.JndiException: Error parsing JNDI name [java:jboss/env/jdbc/gd]
    at org.hibernate.service.jndi.internal.JndiServiceImpl.parseName(JndiServiceImpl.java:92)
        ... muitas chamadas
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:905)
    ... 85 more
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
    at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.getNameParser(Unknown Source)
    at org.hibernate.service.jndi.internal.JndiServiceImpl.parseName(JndiServiceImpl.java:86)
    ... 101 more

O que está faltando?
Desde já agradeço!

A: Aparentemente o probelma está na configuração do ambiente para que AlunoRepository.itemPorId possa funcionar. Se você remover esta chamada funciona?
Pode ser que o persistence.xml que o seu teste está usando esteja tentando fazer um bind JNDI para um InitialContext nulo, visto que a aplicação de teste não roda no servidor de aplicação.
Para isso os testes precisam redefinir a configuração estabelecendo a conexão com o banco de dados diretamente via JDBC. A aplicação "bookmark" gerada pelo arquétipo demoiselle-jsf-jpa já traz um exemplo pronto no arquivo src/test/resources/META-INF/persistence.xml. Este irá sobrepor o persistence.xml da sua aplicação que se encontra em src/main/resources/META-INF/persistence.xml.
Caso esteja tudo desta forma e mesmo assim o problema continue, tente rodar os testes pela linha de comando com o Maven diretamente. Se funcionar, o problema está na IDE.


text:
Q: why filter function in python3 always returns empty result? I am learning generator in python.
data = read_fake_data("./data/fake_data.csv") # genrator function
data_day = day_grouper(data) # generator function, group data by key
print("data grouped:",list(data_day))
# it prints:
# data grouped: [('2019-01-01', <itertools._grouper object at 0x000002294D296EB8>)]
# work well

then I want function #check_anomaly# to filter anomalous data:
ddd = filter(check_anomaly, data_day)
print("data filtered:",list(ddd))

only find that it prints empty list in console
I suspect error may occure in function , so I try to keep all data to debug:
ddd = filter(lambda x: x, data_day)
print("data filtered:",list(ddd))

It still returns empty result!
data filtered: []

Why is this happening? Can anybody help me with this???


text:
Q: Is it allowed to generate temporary files? I have not yet submitted any Office add-in.
For the add-in I am developing, a JavaScript function will generate a temporary .txt file, which will be treated by another JavaScript function. Does anyone know if the server of Office Add-ins permits of generating temporary files like that?
Is there any example in https://github.com/OfficeDev that uses temporary file?
If it is not allowed, which would be the data type to represent large unstructured information (like text) to be passed among JavaScript functions?

A: Since all web-based Office add-ins use JavaScript, you have no interaction with the local PC nor the web server where the add-in's pages are hosted.  If you need to do file manipulation you could for example call REST endpoints (via Ajax from your JavaScript) on your web server which could use server-side code (such as the ASP.NET Web API, NodeJS, etc.) to do the file work and return results to your JS code.


text:
Q: iOS Action Extension not opening my main app I want to be able to open Safari links in my app. For this I have created an Action Extension. I have tried multiple variations of the following code to test but none of them open my main app:
First try:
func openContainerApp() {
        var responder: UIResponder? = self as UIResponder
        let selector = #selector(openURL(_:))
        while responder != nil {
            if responder!.responds(to: selector) && responder != self {
                responder!.perform(selector, with: URL(string: "awesome://item?id=20036169")!)
            }
            responder = responder?.next
        }
        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
    }

Second try:
func redirectToHostApp() {
        let url = URL(string: "awesome://item?id=20036169")
        let selectorOpenURL = sel_registerName("openURL:")
        let context = NSExtensionContext()
        context.open(url! as URL, completionHandler: nil)

        var responder = self as UIResponder?

        while (responder != nil){
            if responder?.responds(to: selectorOpenURL) == true{
                responder?.perform(selectorOpenURL, with: url)
            }
            responder = responder!.next
        }

    }

I have added the "awesome" URL scheme in my main app. I am also returning "true" for all possible openURL delegate methods in my app delegate:
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        return true
    }

    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return true
    }

I have set the NSExtensionActivationSupportsWebURLWithMaxCount in my action extension to 1.
Despite all this, my main app doesn't open. Tapping on the action extension in Safari does nothing.
I have tried these solutions but none work:
https://stackoverflow.com/a/28037297/1634905
https://forums.developer.apple.com/thread/65621

A: I figured it out by myself and wanted to share this in case someone gets stuck with the same.
My problem was that I was calling the openContainerApp or redirectToHostApp functions from viwDidLoad() where the UIResponder is apparently not ready yet.
I moved the function call to viewWillAppear() and it worked.
override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        openContainerApp()
}


text:
Q: get object value inside function coffeescript title = ->
  $("#post_title").keyup ->
    @value

When I try to call to title() function I'm getting [object Object].
I have to add to the function value to this code:
"
" + "
" + "<a href='/en" + "/posts/preview_search/" + "?post[title]=" +  title() + "" + "
" + "
"

How can I get the @value returned by the object instead of the object?
Thanks!

A: The keyup event will happen after the function returns, therefore it can't be assigned to title using the function's return value. One way would be to do whatever you need to do with title inside the function:
$("#post_title").keyup ->
  title = @value
  # use title

A: Try:
title = ->
      $("#post_title").keyup (e) ->
        $(e.target).attr 'value'


text:
Q: QThread doesn't start Sorry for the length of this post. But I am stuck for two days now....
I am working on a Qt 4.6 Windows application that communicates with a hardware device through ActiveX.
When I send a command, the device does some stuff and when it's done (can take up to one minute) it emits a signal. I need to wait this signal to know if everything went okay (or not) and do some actions in consequence.
A command is sent to the device when a user clicks a button. And obviously, I don't want the HMI to freeze.
I am convinced I have to use threads. So I identified three threads:

*

*the main thread corresponding to the HMI

*the hardware controller (which locks after a command is sent and waits a signal)

*a hardware notification listener that continuously gets signals from the hardware and unlock the thread 2

Here is the class diagram:

And a sequence diagram to show how I see things:

Explanations:
When the user launches my application, the HMI is created. The constructor of the HMI calls the constructor of the Worker. It constructs the hardware QAxObject. Then it constructs the HardwareListener giving in reference: the QAxObject, the QMutex and the QWaitCondition. Then the constructor of the Worker moves the HardwareListener  object to another thread and starts it. Finally, the constructor of the HMI starts the thread of the Worker.
Then, when the user clicks a button, the HMI sends a signal to the Worker. The Worker sends a command to the hardware (that command may block the thread several seconds that's why I need the HardwareListener in another thread not to miss a signal). Then the Worker waits for a QWaitCondition (after having locked the QMutex).
After that, the hardware device sends a signal to the HardwareListener which wakes up the QWaitCondition. Therefore, the Worker thread stops waiting and finishes its actions. Finally, the Worker informs the HMI.
Problem:
The Worker and HardwareListener threads aren't created/started. Everything is done in the main thread so, obviously, it doesn't work. I don't exchange any special object between threads (so no need for qRegisterMetaType())
Question:
Is my design acceptable? There may be some other ways to do but it seems to me this is the most straightforward (taking into account the complexity).

EDIT:
I've changed my code to remove the QThread inheritance. I use the moveToThread() method instead.
Now the threads work fine. HOWEVER I have an ActiveX error: QAxBase: Error calling IDispatch member NewProject: Unknown error.
It seems the interfacing with the hardware is broken... Any idea?
Here is something interesting:
You cannot move a QAxObject to another thread once it has been created.

SOLUTION:
Here is what I have found.

A: Inheriting from QThread is not good design. If the work you are doing is computational heavy I would recommend using QThreadPool. I not than its better to use an asynchronous design. This means only calling function which never block and instead connect to signals notifying you that something happened.
So for example sending the command to the hardware and emitting a signal once the hardware is done. If the hardware API doesn't supply async functions than you are stuck with using threads.
QtConcurrentRun can help with that. Usually you should not need to touch threads yourself; and its a hell of a lot easier without.