text:
Q: ¿Cómo eliminar duplicados en Excel considerando condiciones? Estoy tratando de entender como hacer una macro en Excel que me elimine duplicados con condiciones especificas, a continuación muestro el ejemplo de lo que quiero hacer,
la tabla ejemplo que muestro a continuación es la tabla sin ningún proceso a resultado

y la tabla ejemplo que muestro a continuación es la tabla con los resultados esperados a obtener

las condiciones que quiero se procesen es esta tabla en una macro que elimine duplicados son estas

Hasta ahora tengo una muy buena macro que elimina duplicados, pero aun no he logrado modificarla para añadir estas condiciones en las líneas de código.
Les comparto la macro, es la siguiente:
Sub RepetidosVH()
    'Declaración del diccionario
    Dim dic As Scripting.Dictionary
    Set dic = New Scripting.Dictionary
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Range("C3").Select
    Do While Not IsEmpty(ActiveCell)
        If dic.Exists(ActiveCell.Text) Then
            ActiveCell.EntireRow.Delete
        Else
            'En esta instrucción lo que interesa es almacenar el valor de la celda como key,
            'el dato equivalente al value no tiene importancia
            dic.Add ActiveCell.Text, "1"
            ActiveCell.Offset(1, 0).Select
        End If
    Loop
    'limpia los recursos utilizados
    dic.RemoveAll
    Set dic = Nothing
    Range("C3").Select
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

Les comparto el archivo de Excel donde esta el ejemplo que muestro anteriormente.
https://drive.google.com/file/d/1KJkYZmBJP8zxgVrcS0NfxxnmZxV1xTr3/view?usp=sharing

A: Prueba esto,
'C)COLOR D)INTERNO_DE  E)CLASE_DEMA F)COUNT_AREA  G)SUM_AREA  H)SUM_LENGTH
Sub EliminarRepetido_Con_Condiciones()
Dim uF&, n&, m&, nVeces%, INTERNO_DE, CLASE_DEMA, COLOR
    uF = Range("C" & Rows.Count).End(xlUp).Row
    For n = 3 To uF
        nVeces = Application.WorksheetFunction.CountIf(Range("D3:D" & uF), Cells(n, "D"))
        If nVeces = 2 Then
            If Cells(n, "E") = "PCP" Or Cells(n, "E") = "PE" Or Cells(n, "E") = "PCC" Then
                Cells(n + 1, "E").EntireRow.Delete
            ElseIf Cells(n, "E") = "PSP47A" Then
                If Cells(n, "G") > Cells(n + 1, "G") Then
                    Cells(n + 1, "G").EntireRow.Delete
                End If
            ElseIf Cells(n, "E") = "RPA" Then
                If Cells(n, "F") = Cells(n + 1, "F") And Cells(n, "F") >= 9 Then
                    Cells(n + 1, "E").EntireRow.Delete
                Else
                    Cells(n, "F") = Cells(n, "F") + Cells(n + 1, "F")
                    Cells(n + 1, "E").EntireRow.Delete
                End If
            ElseIf Cells(n, "E") = "RV" Or Cells(n, "E") = "RE" Then
                    Cells(n, "G") = Cells(n, "G") + Cells(n + 1, "G")
                    Cells(n + 1, "G").EntireRow.Delete
            End If
        ElseIf nVeces = 3 Then
            If Cells(n, "E") = "PCP" Or Cells(n, "E") = "PE" Then
                Cells(n + 2, "E").EntireRow.Delete
                n = n + 1
            End If
        End If
    Next n
End Sub


text:
Q: Java ITextPdf: added fonts not showing up on my pdf using html template i'm trying to generate a pdf using Itextpdf, this is my code:
 public byte[] generatePdf(String template, Map<String, Object> data) {
    if (logger.isDebugEnabled()) {
        logger.debug("generatePdf::start");
    }
    byte[] pdf;
    try {
        OutputStream htmlMod = marker(template, data);
        pdf = createPdf(htmlMod);
    } catch (Exception e) {
        throw new PdfCreationException(e);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("generatePdf::end");
    }
    return pdf;
}

private byte[] createPdf(OutputStream inHtml) throws IOException, DocumentException {
    if (logger.isDebugEnabled()) {
        logger.debug("createPdf::start");
    }
    Document document = new Document();//PageSize.A4, 10, 0, 0, 0);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream);
    writer.setPageEvent(new HeaderFooter());
    writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
    document.open();
    InputStream in = new ByteArrayInputStream(inHtml.toString().getBytes(Charset.forName("UTF-8")));
    CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true);

    HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
    htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
    htmlContext.setImageProvider(new ImageProvider());

    PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
    HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
    CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
    XMLWorker worker = new XMLWorker(css, true);
    XMLParser p = new XMLParser(worker);
    p.parse(in, Charset.forName("UTF-8"));
    document.close();
    if (logger.isDebugEnabled()) {
        logger.debug("createPdf::end");
    }
    return byteArrayOutputStream.toByteArray();
}

i have some custom fonts inside my spring boot application that i added to my html template:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<style type="text/css">
    @font-face {
        font-family: GiustiziaPalace;
    src: url("../assets/fonts/palace-script-mt-semi-bold.ttf");

}
@font-face {
    font-family: GiustiziaArial;
    src: url("../assets/fonts/arial.ttf");
}
@font-face {
    font-family: GiustiziaArialBold;
    src: url("../assets/fonts/arial-bold.ttf");
}
</style>
<body>
    <div style="font-family: GiustiziaArial; padding: 0 10px 10px 10px; display: flex;
flex-direction: column; gap: 10px;">

But unfortunately my fonts are never displayed on the pdf. If i open the html page on chrome, i can see the fonts. How can i fix this? Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Decomposition of an unitary operator by simple operators For quantum computation, it's well known that any unitary operator can be approximated with an arbitrary accuracy by simple operators, for example to approximate an unitary operator on n qubits by no more than $e^n$ universal gates.
What's puzzling me is that: Can we decompose an unitary operator into no more than $e^n$ (or with a similar complexity) simple unitary operators, i.e., as a tensor product of simple unitary operators? Here I am not talking about 'approximation' but a precise 'decomposition'. Also the simple operators need not to be from a finite set as in the universal gate case, we can use any simple operators (for example any 2-level unitary operator).
So I want to have $U=U_1U_2....U_k$, where $U_{i}=I\otimes I \otimes I ...\otimes O_{i1,i2}..\otimes I$. $I$ is the identical operator on a single qubit and $O_{i1,i2}$ is an arbitrary two-level operator on qubit $i1,i2$. Can such kind of decomposition possible? What's the complexity of it, i.e., $k \sim O(e^n)$?
Thanks a lot.

A: Yes, such a kind of exact decomposition is always possible.  This is shown in Barenco et al., Elementary gates for quantum computation (Sec. 8, pg. 27 in the arXiv preprint), based on work by Reck et al. (which gives a corresponding decomposition where each elementary operation is the identity except for a $2\times 2$ submatrix).  The construction given requires $O(n^34^n)$ two-qubit gates.
(This is the same answer as to the cross-post https://physics.stackexchange.com/questions/201770).

A: The possibility of what you want to do would imply, at the very least, that every unitary operator on $k$ systems can be written as a "simple tensor", i.e. that we could write $U = U_1 \otimes \cdots \otimes U_k$ some unitary operators $U_1, \dots, U_k$.
This, however, is not the case. For example, consider $U \in \Bbb C^{2 \times 2} \otimes \Bbb C^{2 \times 2}$ to be defined by
$$
U(e_i \otimes e_j) = e_j \otimes e_i
$$
In particular, we have
$$
U =
\left[
\begin{array}{cc|cc}
1&0&0&0\\
0&0&1&0\\
\hline
0&1&0&0\\
0&0&0&1
\end{array}
\right]
$$
Note that there are no unitary matrices $U_1,U_2$ such that $U = U_1 \otimes U_2$, since the blocks are not all multiples of the same $2 \times 2$ matrix.


text:
Q: Modal Dialogs seem to be a pain in mobile development Currently I'm developing a mobile application using phonegap, backbone.js & jquery mobile. It appeared to me that modal dialogs or popups are really painful. This is because every time you open the "keyboard" on a mobile device the popup or dialog keeps jumping around making the UX really a mess.
I found some solutions like Backbone.ModalDialog by Gareth Elms. But this is somehow unsatisfying because the "jumping problem" remains.
Is there an other solution than making a single page for every small form?

A: Depending on how you first position the popup, either window or origin, you can reposition the popup at any stage after it's open.
To reposition it once keyboard is open, you need to listen to focus event and then _reposition it.
$(document).on("pagecreate", "#pageID", function () { /* pageinit for jQM 1.0 - 1.3 */
  $("#popupID input").on("focus", function () {
    $("#popupID").popup("reposition", {
      y: 0 /* reposition it to window's top */
    });
  }).on("blur", function () {
    $("#popupID").popup("reposition", {
      positionTo: "window" /* reposition it to window when keyboard is hidden */
    });
  });
});


text:
Q: Style Setter Freezing Brush I seem to have run into some behavior regarding WPF ResourceDictionaries, Brushes, and Styles (at least that's what I've noticed so far) that is counter to my understanding of how these things should work.  Basically, if I reference a Brush from a Setter withing a Style in a ResourceDictionary it causes the Brush to become frozen.  The example below illustrates this, as I get an InvalidOperationException when I try to change the Color on the shared Brush within my button's Click event handler.  It should cause both Rectangle's color to change, as they both use the same shared Brush, but I get the exception instead.
<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <SolidColorBrush x:Key="TestBrush" Color="Red" />
        <Style TargetType="Rectangle">
            <Setter Property="Fill" Value="{StaticResource TestBrush}" />
        </Style>
    </Window.Resources>
    <StackPanel>
        <Button Name="Button1" Content="Change Color" Click="Button1_Click" />
        <Rectangle Height="20" />
        <Rectangle Height="20" />
    </StackPanel>
</Window>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button1_Click(object sender, RoutedEventArgs e)
    {
        var brush = (SolidColorBrush)FindResource("TestBrush");
        // InvalidOperationException Here.  Brush is Frozen/Read-Only
        brush.Color = Colors.Blue;
    }
}

If I simply remove the Style (more specifically the Setter) and reference the Brush (still from the ResourceDictionary) directly from each Rectangle, I get the expected behavior of the Rectangles' colors changing in tandem from the button click event.  See code below (button click event hanlder remains the same).
<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <SolidColorBrush x:Key="TestBrush" Color="Red" />
    </Window.Resources>
    <StackPanel>
        <Button Name="Button1" Content="Change Color" Click="Button1_Click" />
        <Rectangle Height="20" Fill="{StaticResource TestBrush}" />
        <Rectangle Height="20" Fill="{StaticResource TestBrush}" />
    </StackPanel>
</Window>

I only see the Brush becoming frozen when it is referenced as a StaticResource from a Style's Setter.  I can actaully reference the same Brush from other locations within the ResourceDictionary without it becoming frozen; i.e. the contents of ControlTemplates.
Can anyone please explain what is going on with this strange behavior and if it's by-design or a bug?
Thanks,
Brandon

A:
...once a style has been applied, it is sealed and cannot be changed.
  If you want to dynamically change a style that has already been
  applied, you must create a new style to replace the existing one. For
  more information, see the IsSealed property.

See http://msdn.microsoft.com/en-us/library/ms745683.aspx


text:
Q: Assign click handler to newly appended elements How does one go about adding a click handler in the following example? I need to assign it to the newly appended anchor element.
$.each(regions1, function(key, value) {

    var coords = regions1[key].rel.split('-');
    $("#map").append("  ")

    //.click(function(){showPopup(regions1[key].id);})

});

A: You want to use the .live jQuery keyword.
http://api.jquery.com/live/
$('.bullet').live('click', function() {
  // Bound handler called.
});

This sample, btw, needs to sit outside any of your other code and placed within the $(document).ready jQuery method.  It will bind a click event to all items that have a class of "bullet".

A: Try this:
$.each(regions1, function(key, value) {

    var coords = regions1[key].rel.split('-');

    // first, create the element
    var element = $("  ");

    // then add the listener/handler
    element.click(function(){showPopup(regions1[key].id);})

    // finally, append the new element to the dom.
    $("#map").append( element );
});


text:
Q: The column name is not valid. -> Could not JPA just replace it will null in this case? I have searched all over stackoverflow.com but I have not found this discussion.
I know my problem, I was just wondering if JPA can handle this in any way without a lot of work...
What I have is an @Entity that I want to use with multiple SQL-Native-Queries.
@Entity
public class TestEntity {
    @Id
    private String ID;
    private String ID1;
    private String ID2;
    private String ID3;
}

Names in the database are equal to Field names.
I then have two selects:
SELECT ID1, ID2 from DATABASE;
SELECT ID2 from DATABASE;

And two native queries for those selects:
    @Query(value = "SELECT ID2 from DATABASE", nativeQuery = true)
    List<TestEntity> testNativeQuery ();

And the Error I get:
[ERROR] 2021-11-30 10:37:20 [main] [SqlExceptionHelper] The column name ID1 is not valid.

How could I tell JPA that if it does not find the Column name that it should just replace it will

null
?

Would that be so difficult?

Some extra details:
I am using a Stored Procedure - which means I can not change the Query - The Stored Procedures are maintained by someone else.
Stored procedure (which works):
    @Query(value = "STORED_PROC :a, :b", nativeQuery = true)
    List<List<String>> execStoredProc(@Param("a") String a, @Param("b") String b);

Stored procedure that does not work, because I have more fields in the entity that the Procedure return, because I need those fields in other stored procedures:
@Query(value = "STORED_PROC :a, :b", nativeQuery = true)
    List<TestEntity> execStoredProc(@Param("a") String a, @Param("b") String b);

When I remove those field the function works - but I need those fields in other part of my program - and I hoped I could use the same @Entity
Database I am using is MSSQL Database:
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver

A: Simply add the missing columns as null:
@Query(value = "SELECT NULL AS ID, NULL AS ID1, ID2, NULL AS ID3 from DATABASE", nativeQuery = true)
List<TestEntity> testNativeQuery ();


text:
Q: Xpath selenium webdriver I'm trying to make a clickable button which links to www.snaptrude.com. But clicking on the button, it throws an error which goes like:
The left-hand side of an assignment must be a
     variable
    - Syntax error on token "home", invalid
     AssignmentOperator

Here's the  code I'm referencing to
package snaptrude;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class MyProject {

    public static void main(String[] args) {
        // declaration and instantiation of objects/variables

        System.setProperty("webdriver.chrome.driver","C:\\Users\\Kunal\\Desktop\\Selenium\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        String baseUrl = "http://www.snaptrude.com";

        // launch Chrome and direct it to the Base URL
        driver.get(baseUrl);

        driver.findElement(By.name("email")).sendKeys("snaptrude@snaptrude.com");

        WebElement f = driver.findElement(By.id("login"));

        WebElement a = driver.findElement(By.xpath("//*[@id="home"]/div/div/div/div/div/span[2]/h2/strong"));

        a.click();

    }

}

A: You have done syntax error :- please refer below code
        WebElement a = driver.findElement(By.xpath("//*[@id='home']/div/div/div/div/div/span[2]/h2/strong")


text:
Q: Loop over a nested list and add each index of each nested list to another list What I'm trying to do is to put each index 0 of each item of list a in the list x and each index 1 of each item of list a in the list y. When the plot is shown, it only appears one point. Does anybody know what am I doing wrong? Thanks in advance.
a = [[1,2], [2,3], [3,4], [5,6], [6,7]]

for item in a:
    x = [ ]
    y = [ ]
    x.append(item[0])
    y.append(item[1])

plt.plot(x, y, 'ro')
plt.axis([-50, 50, -50, 50])
plt.show()

A: You overwrite the values of x and y every time through the loop, so only the last point is stored. Move your declaration of x and y outside of your loop.
It makes more sense to take advantage of Python's list comprehensions though:
x, y = ([p for p,q in a], [q for p,q in a])
plt.plot(x, y, 'ro')
plt.axis([-50, 50, -50, 50])
plt.show()

List comprehension:
([p for p,q in a], [q for p,q in a])

this piece of code returns a 2-tuple whose elements are two Python lists. The lists are formed using a list comphrehension which takes each list of x,y and splits the xs into the first returned list, and the ys into the second.

A: Try this:
x, y = zip(*a)
It is compact and readable and it should work.


text:
Q: How to only use my max api calls php I am using the raw blockchain api and the docs say that I can do 1 request every 10 seconds, how would I make sure that I don't go over this limit? I'd prefer to keep it server side with php. Thank you for the response

A: After each call to the API add to your internal time counter 10 seconds to know when the next call will be allowed.
class ApiRequest{

   private $nextRequestTime = time();

   private function allowRequest(){
      $local_time = now();
      if($local_time >= $this->nextRequestTime ){
         $this->nextRequestTime = ($local_time + 10);
         return true;
      }
      return false;
   }

   public function doRequest($request){
      if($this->allowRequest()){
         // process the $request...
      }
   }

}

When function ApiRequest::allowRequest() returns false you know that you should process the request later.


text:
Q: sftp: command to select desired files to copy I have a long list of data files that I need to copy over to my server, they have the names
data_1.dat
data_2.dat
data_3.dat
...
data_100.dat

Starting from data_1.dat, I would like to get all the files where the number is increased by 3, i.e. data_4.dat, data_7.dat, data_10.dat, ...
Is there a way to specify this? Right now I am doing in manually using  get data_4.dat, but there must be a way to automatize this.

A: On Linux:
printf -- '-get data_%d.txt\n' $(seq 1 3 100) | sftp -b - user@example.com

On BSD (with no seq(1) in sight):
printf -- '-get data_%d.txt\n' $(jot 100 1 100 3) | sftp -b - user@example.com

A: bash supports C style looping construct, you can leverage that:
for ((i=1; i<=100; i+=3)); do echo file_$i.dat; done

Replace echo file_$i.dat with the operation you want on the file.

Example:
$ for ((i=1; i<=100; i+=3)); do echo file_$i.dat; done
file_1.dat
file_4.dat
file_7.dat
file_10.dat
file_13.dat
file_16.dat
file_19.dat
file_22.dat
file_25.dat
file_28.dat
file_31.dat
file_34.dat
file_37.dat
file_40.dat
file_43.dat
file_46.dat
file_49.dat
file_52.dat
file_55.dat
file_58.dat
file_61.dat
file_64.dat
file_67.dat
file_70.dat
file_73.dat
file_76.dat
file_79.dat
file_82.dat
file_85.dat
file_88.dat
file_91.dat
file_94.dat
file_97.dat
file_100.dat


text:
Q: Can I scrape the raw data from highcharts.js? I want to scrape the data from a page that shows a graph using highcharts.js, and thus I finished to parse all the pages to get to the following page. However, the last page, the one that displays the dataset, uses highcharts.js to show the graph, which it seems to be near impossible to access to the raw data.
I use Python 3.5 with BeautifulSoup.
Is it still possible to parse it? If so how can I scrape it?

A: The data is in a script tag. You can get the script tag using bs4 and a regex. You could also extract the data using a regex but I like using /js2xml to parse js functions into a xml tree:
from bs4 import BeautifulSoup
import requests
import re
import js2xml

soup = BeautifulSoup(requests.get("http://www.worldweatheronline.com/brussels-weather-averages/be.aspx").content, "html.parser")
script = soup.find("script", text=re.compile("Highcharts.Chart")).text
# script = soup.find("script", text=re.compile("precipchartcontainer")).text if you want precipitation data
parsed = js2xml.parse(script)
print js2xml.pretty_print(parsed)

That gives you:
<program>
  <functioncall>
    <function>
      <identifier name="$"/>
    </function>
    <arguments>
      <funcexpr>
        <identifier/>
        <parameters/>
        <body>
          <var name="chart"/>
          <functioncall>
            <function>
              <dotaccessor>
                <object>
                  <functioncall>
                    <function>
                      <identifier name="$"/>
                    </function>
                    <arguments>
                      <identifier name="document"/>
                    </arguments>
                  </functioncall>
                </object>
                <property>
                  <identifier name="ready"/>
                </property>
              </dotaccessor>
            </function>
            <arguments>
              <funcexpr>
                <identifier/>
                <parameters/>
                <body>
                  <assign operator="=">
                    <left>
                      <identifier name="chart"/>
                    </left>
                    <right>
                      <new>
                        <dotaccessor>
                          <object>
                            <identifier name="Highcharts"/>
                          </object>
                          <property>
                            <identifier name="Chart"/>
                          </property>
                        </dotaccessor>
                        <arguments>
                          <object>
                            <property name="chart">
                              <object>
                                <property name="renderTo">
                                  <string>tempchartcontainer</string>
                                </property>
                                <property name="type">
                                  <string>spline</string>
                                </property>
                              </object>
                            </property>
                            <property name="credits">
                              <object>
                                <property name="enabled">
                                  <boolean>false</boolean>
                                </property>
                              </object>
                            </property>
                            <property name="colors">
                              <array>
                                <string>#FF8533</string>
                                <string>#4572A7</string>
                              </array>
                            </property>
                            <property name="title">
                              <object>
                                <property name="text">
                                  <string>Average Temperature (°c) Graph for Brussels</string>
                                </property>
                              </object>
                            </property>
                            <property name="xAxis">
                              <object>
                                <property name="categories">
                                  <array>
                                    <string>January</string>
                                    <string>February</string>
                                    <string>March</string>
                                    <string>April</string>
                                    <string>May</string>
                                    <string>June</string>
                                    <string>July</string>
                                    <string>August</string>
                                    <string>September</string>
                                    <string>October</string>
                                    <string>November</string>
                                    <string>December</string>
                                  </array>
                                </property>
                                <property name="labels">
                                  <object>
                                    <property name="rotation">
                                      <number value="270"/>
                                    </property>
                                    <property name="y">
                                      <number value="40"/>
                                    </property>
                                  </object>
                                </property>
                              </object>
                            </property>
                            <property name="yAxis">
                              <object>
                                <property name="title">
                                  <object>
                                    <property name="text">
                                      <string>Temperature (°c)</string>
                                    </property>
                                  </object>
                                </property>
                              </object>
                            </property>
                            <property name="tooltip">
                              <object>
                                <property name="enabled">
                                  <boolean>true</boolean>
                                </property>
                              </object>
                            </property>
                            <property name="plotOptions">
                              <object>
                                <property name="spline">
                                  <object>
                                    <property name="dataLabels">
                                      <object>
                                        <property name="enabled">
                                          <boolean>true</boolean>
                                        </property>
                                      </object>
                                    </property>
                                    <property name="enableMouseTracking">
                                      <boolean>false</boolean>
                                    </property>
                                  </object>
                                </property>
                              </object>
                            </property>
                            <property name="series">
                              <array>
                                <object>
                                  <property name="name">
                                    <string>Average High Temp (°c)</string>
                                  </property>
                                  <property name="color">
                                    <string>#FF8533</string>
                                  </property>
                                  <property name="data">
                                    <array>
                                      <number value="6"/>
                                      <number value="8"/>
                                      <number value="11"/>
                                      <number value="14"/>
                                      <number value="19"/>
                                      <number value="21"/>
                                      <number value="23"/>
                                      <number value="23"/>
                                      <number value="19"/>
                                      <number value="15"/>
                                      <number value="9"/>
                                      <number value="6"/>
                                    </array>
                                  </property>
                                </object>
                                <object>
                                  <property name="name">
                                    <string>Average Low Temp (°c)</string>
                                  </property>
                                  <property name="color">
                                    <string>#4572A7</string>
                                  </property>
                                  <property name="data">
                                    <array>
                                      <number value="2"/>
                                      <number value="2"/>
                                      <number value="4"/>
                                      <number value="6"/>
                                      <number value="10"/>
                                      <number value="12"/>
                                      <number value="14"/>
                                      <number value="14"/>
                                      <number value="11"/>
                                      <number value="8"/>
                                      <number value="5"/>
                                      <number value="2"/>
                                    </array>
                                  </property>
                                </object>
                              </array>
                            </property>
                          </object>
                        </arguments>
                      </new>
                    </right>
                  </assign>
                </body>
              </funcexpr>
            </arguments>
          </functioncall>
        </body>
      </funcexpr>
    </arguments>
  </functioncall>
</program>

So to get all the data:
In [28]: from bs4 import BeautifulSoup
In [29]: import requests
In [30]: import re
In [31]: import js2xml
In [32]: from itertools import repeat
In [33]: from pprint import pprint as pp
In [34]: soup = BeautifulSoup(requests.get("http://www.worldweatheronline.com/brussels-weather-averages/be.aspx").content, "html.parser")

In [35]: script = soup.find("script", text=re.compile("Highcharts.Chart")).text

In [36]: parsed = js2xml.parse(script)

In [37]: data = [d.xpath(".//array/number/@value") for d in parsed.xpath("//property[@name='data']")]

In [38]: categories = parsed.xpath("//property[@name='categories']//string/text()")

In [39]: output =  list(zip(repeat(categories), data))
In [40]: pp(output)
[(['January',
   'February',
   'March',
   'April',
   'May',
   'June',
   'July',
   'August',
   'September',
   'October',
   'November',
   'December'],
  ['6', '8', '11', '14', '19', '21', '23', '23', '19', '15', '9', '6']),
 (['January',
   'February',
   'March',
   'April',
   'May',
   'June',
   'July',
   'August',
   'September',
   'October',
   'November',
   'December'],
  ['2', '2', '4', '6', '10', '12', '14', '14', '11', '8', '5', '2'])]

Like I said you could just use a regex but js2xml I find is more reliable as erroneous spaces etc.. won't break it.

A: For anyone else who stumbles upon.
If your page is loaded within selenium, you can do the following:
driver.execute_script("return $('#YOUR_ID_LOCATION').highcharts().series[0].processedYData")

Will extract the data for the YData...etc. This assumes driver is a Selenium Webdriver.


text:
Q: highlight listview row on long press I have a customized listview. I want to highlight the row selected on long press. I managed to do it on normal click by using this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:state_activated="true"   android:drawable="@android:color/holo_orange_dark" />
  <item android:state_pressed="false"
    android:state_selected="false"
    android:drawable="@color/light_grey" />
</selector>

but I can't figure out which state acts on long click. any ideas?
thanks in advance.

A: Element in Android have long click action in default . So you just need to define the LongClick event on the super view of adapter
public override View GetView(int position, View convertView, ViewGroup parent)
{
   //...
   View view = convertView;

   view.LongClick += View_LongClick;

   //...

   return view;
}

private void View_LongClick(object sender, View.LongClickEventArgs e)
{
  var view = sender as View;
  view.SetBackgroundColor(Color.Red);
}


text:
Q: How to display DataGrid to XML file? I have a requirement that when I click on GeneratXML button which is below the DataGrid the Datagrid data is converted in one xml file.

A: Something like this would do I think - (I don't know what your data is like, its a two sentence question)  ;)
private function getDataProviderXML ( dp :ArrayCollection ) :String {
    var full :String = '<root>';
    for each ( var o :Object in dp ){
        full += '<row>';
        for each ( var prop :String in o ){
            full += '<' + prop + '>' + o[prop] + '</' + prop + '>'
        }
        full += '</row>';
    }
    return full += '</root>';
}


text:
Q: Find The number of sides of triangle I am giving a Array A consists of integer, I have to choose any two integer from array A and any third integer from range [L,R] , such that all three integer forms a valid triangle.
I have to find the number of integer in range [L,R] which can be used to form a valid triangle, by choosing any two values from array A.
I know if i know two sides then third side must be range a-b<x<a+b
where a and b are any two integer from A.
How to find the number of valid integer in [L,R] in O(N)  N= Size of A time.
L and R and be very large upto 10^20

A: To my understanding, complete enumeration will yield an efficient solution by the following argument. The maximum number of possible solutions occurs in the case where any selection of elements of A yields a consistent choice of side lengths for a triangle. Such an input, for instance, would be an input of N times the value 1. However, the number of triples chosen from A can be bounded by
(n choose 3) =  n!/(3!(n-3))
             =  n!/(6(n-3)!)
             =  (1/6)*(n-2)*(n-1)*n
             <= n^3

(where choose is meant to denote the binomial coefficient) which is a polynomial number of choices. Any choice can be checked for validity in constant time, as only 3 values are involved.

A: Now the contest has ended, so here is my way to solve it in the contest.

The problem is asking how many number x in [L,R]can form triangle with  any pair (a_i, a_j) in A.
Naive method is to brute all pairs which is O(N^2 * (R-L+1)) = O(N^2 * (R-L))
But indeed, we do not need to test all O(N^2) pairs, we only need to test O(N) pairs IF A is sorted, namely, all adjacent pair (a_i-1, a_i) for i > 0

Why? Because in sorted A:
If there is some pair (a_j, a_i) where a_j < a_i and j != i-1, which can form triangle with x
Then (a_i-1, a_i) must form a triangle with x too:

*

*a_i-1 + a_i > a_j + a_i > x

*x + a_i-1 > x + a_j > a_i

*x + a_i > x + a_i-1 > a_j

Therefore checking all (a_i-1, a_i) is sufficient, this is the first core idea to solve this problem.

So now we have a O(NlgN + N*(R-L+1)) = O(N*(R-L)) algorithm.
For the original contest problem, it is still too slow as R-L+1 is as large as 10^18, so we need another tricks.
Note that actually by the triangle inequality, for a pair (a_i-1, a_i), indeed we can find a range of x which can form triangle with this pair:
a_i-1 + a_i > x > a_i - a_i-1 (By above 1 & 2)
For example, (4,5) can form triangle with all 1 < x < 9
So instead of iterating all x in [L,R], we try to find range of x for each pair, which can be done in O(N) as we know the range for x of a pair in O(1). Beware that x must fall in the range of [L,R].
After that we have O(N) ranges  / segments of x which then we can union them and the size of the result set is the desired answer.
Union O(N) segments can be done easily in O(N) as well, I leave you as a homework :)

Combine both tricks, the algorithm is O(N lg N + N  + N) = O(N lg N)


text:
Q: Add a column to SQLScript result on HANA I am facing following issue:
I had Tables

*

*A with columns: [ID, Name]

*B with columns: [ID, Name]

Now I want to UNION those two table with the Table result C:
C with columns [ID, Name, Source]
The Source column in Table C will shows value "A" or "B" to illustrate the source of that line is from Table A or B.
I tried some guides with
(SELECT *, "A" AS SOURCE FROM A) UNION ALL (SELECT *, "B" AS SOURCE FROM B)
But It still seems wrong!
Note: This is for SAP HANA. How I can do now ?

A: The problem with your query is the you used double quotes instead of single quotes for the content of the source column.
Please change your query to:
(SELECT *, 'A' AS SOURCE FROM A) UNION ALL (SELECT *, 'B' AS SOURCE FROM B)

Then it should work


text:
Q: Can someone explain what wp_session_tokens are, and what are they used for? I am trying to understand how WordPress determines where a user is logged in or not? I read that it's done using just the cookies; but with WordPress 4, there's a new addition: wp_session_tokens. I tried to read the codex and searching on the Internet, but there's not much useful information.
Questions:

*

*What's the typical use of wp_session_tokens?

*Can I use them to login/logout a user? Or should I simply rely on set_current_user and set_auth_cookie functions to manage user login?

*Are there any disadvantages of wp_session_tokens?
Would really appreciate if you could space some time to explain what these session tokens do.

A: Normal cookies, as used by WordPress to keep you logged in for a certain period, are the way to check whether a user is logged in. Even if you close your computer they will be there when you switch it on again.
Session tokens are something different. They are meant to transfer information between several page requests. The typical example is the content of a shopping cart that should be displayed while you browse through the pages of an online shop. You could pass that information using query arguments (like www.example.com\?cart="book:Moby_Dick_1799847h4"), but that would involve sending a lot of information every time. In stead, the token is passed and the server knows what cart content to display.
Unless the session token is stored as a cookie on your pc and the server stores the cart content related to that cookie, the sessions disappears as soon as you close your browser. So, session tokens are less permanent than cookies.
You could use session tokens to check if people are still logged in. That would force people to log in every time they open the site. In that case you would also have to disable the normal login procedure.
There might be circumstances where using session tokens to identify users could go wrong. For instance, if you have a large site, distributed over several servers, you may have a valid session with one server, but the load balancer might decide to send you to another, making you lose your session and hence forcing you to login again. The cookies approach would not suffer from this, as all servers will consult the same database to determine whether you are logged in legitimately.
Summing up: unless you're really skilled with security procedures, stick with the one WordPress provides you with.


text:
Q: React CSSTransition Help. Animation resetting. and not setting the enter class right away my React code
    import React from 'react'
import ReactDOM from 'react-dom'
import { CSSTransition } from 'react-transition-group'

import './styles.css';

const Fade = ({ children, ...props }) => (
  <CSSTransition
    {...props}
    timeout={600}
    classNames="slide-filter"
  >
    {children}
  </CSSTransition>
);

class FadeInAndOut extends React.Component {
    state = {
      show: false
    }

  render() {
    return (

        <button onClick={() => this.setState((prevState) => {
          return { show: !prevState.show }
        })}>Toggle</button>

      <Fade in={this.state.show}>

Hello world

      </Fade>

    )
  }
}

My CSS classes
.slide-filter-enter {
  transform: translateX(50%);
  opacity: 0;
  transition: all 0.6s ease-in;
  color:blue;
}
.slide-filter-enter-active {
  transform: translateX(0);
  color:red;
  opacity: 1;
}
.slide-filter-exit {
  transform: translateY(0);
  opacity: 1;
  color:red;
}
.slide-filter-exit-active {
  color:blue;
  transform: translateX(50%);
  transition: all 0.6s ease-in;
}

Ok I can't understand why this is not working. It just resets to its original state after animating.
Also why is the "enter" or "enter-active" class not applied the first time it is rendered on the screen?

A: So you want the position of the "Fade" component to stay at the end position of the animation? Forgive me if this is not the behavior you are looking for but try removing the timeout={1000} prop on line 10.


text:
Q: Summation calculus differentiation problem I am new in calculus. So it will be helpful if anyone solve it and give some hint how it works.
$$E = \frac{1}{3} \sum_{i=1}^3 (mx_i+c-y_i)^2$$
Then what will be $\frac{dE}{dm}$ and $\frac{dE}{dc}$?
Thanks.

A: \begin{align}
\frac{dE}{dm} & =\sum_{i=1}^3 \frac{2}{3}x_i(mx_i+c-y_i) \\
\frac{dE}{dc} & = \sum_{i=1}^3 \frac{2}{3}(mx_i+c-y_i)
\end{align}


text:
Q: How to make "parameter info" work on Constructors in Android Studio In AS (IntelliJ) you can see all of the overloaded method signatures for some method by pressing Ctrl+P:

However, this doesn't work with constructors as this helpful image illustrates:

Why not?  Can this be enabled?


text: Q: How to monitor pool stats in Atomikos with prometheus We were using hikari with prometheus to monitor pool stat. Now we need to switch to Atomikos because of XaDatasource and global transaction. Is there already some way how we keep similar monitoring pool stat in Atomikos or we need to implement it from zero ?


text:
Q: Spring Boot project in Eclipse Oxygen I am creating a Spring Boot Application in eclipse oxygen.I have followed the following steps:
File->New->Spring Boot->Spring Starter Project
When the wizard opens up I am getting the following error::
SunCertPathBuilderException: unable to find valid certification path to requested target

I am connected to Internet and also able to connect to Eclipse Market Place
Can anyone figure out the issue??

A: I too encountered the exactly same issue earlier.  To make it work, changed Network Connections mode to Manual. Follow this path.

Window -> Preferences -> Network Connections Change mode to Manual

A: I don't work with Eclipse anymore ... But, which Java version are you using ?
This error, not especially linked to Eclipse, appears when JCE (Java Cryptography Extension) is not present. Did you try to install it ?

*

*Download JCE

*Copy local_policy.jar and US_export_policy.jar to $JAVAHOME/jre/lib/security.


text:
Q: Raspberry Pi - Error resizing existing FAT partition I tried to install RASPBIAN os using noobs in to my pi. But when I start the pi after coping the noobs into my sd card, it shows the folling error.

Error resizing existing FAT partition

How to fix it, Thanks in advance.

A: This usually happens when raspberry cannot read the SD data, and you can fix it by doing a lot of things, for example:

*

*Change the SD card, format the new one of FAT32 and put all of Raspbian data inside it

*Get your current SD card and format it again, try to check if this is ok to read/write

*Go to this link and check if your SD card compatibility

*Check if your power supply is really 5V, and if its passing to Rasp, sometimes rasp doesn't work well because it hasn't enough power


text:
Q: Triggering event continuously when Button is pressed down in Android I have Button and an TextView. Initially on click of button i an incrementing the count value and display in the TextView. The code i have used to do so is.
buttonDayPlus.setOnClickListener(new OnClickListener()
{
     @Override
     public void onClick(View v)
     {
     count = count + 1;
         textView.setText(Integer.toString(count));
     }
}

But now what i want is if the user pressed the Button, then i want to increment the value one after another and display the increment value in the textView and as soon as user move his hand up...the final increment value is shown in textView. So if anyone knows help me to solve this out

A: You will need to use a Handler object because you have to implement a separate thread for incrementing/decrementing
public class MainActivity extends Activity {

    private boolean autoIncrement = false;
    private boolean autoDecrement = false;
    private final long REPEAT_DELAY = 50;
    private Handler repeatUpdateHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.input);

        class RepetitiveUpdater implements Runnable {

            @Override
            public void run() {
                if (autoIncrement) {
                    increment();
                    repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
                } else if (autoDecrement) {
                    decrement();
                    repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
                }
            }

        }

        up.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                increment();
            }
        });

        up.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                autoIncrement = true;
                repeatUpdateHandler.post(new RepetitiveUpdater());
                return false;
            }
        });

        up.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP && autoIncrement) {
                    autoIncrement = false;
                }
                return false;
            }
        });

    }

    public void increment() {
        if (i < 100) {
            i++;
            TextView no = (TextView) findViewById(R.id.no);
            no.setText(String.valueOf(i));
        }

    }

}

Do the same for decrement.
Courtesy: Github, author: Jeffrey F. Cole

A: I just answered this question here
https://stackoverflow.com/a/41466381/2991628
I created a CounterHandler class to do all the counting and event handling. This is how it works.
 new CounterHandler.Builder()
            .incrementalView(buttonPlus)
            .decrementalView(buttonMinus)
            .minRange(-50) // cant go any less than -50
            .maxRange(50) // cant go any further than 50
            .isCycle(true) // 49,50,-50,-49 and so on
            .counterDelay(200) // speed of counter
            .counterStep(2)  // steps e.g. 0,2,4,6...
            .listener(this) // to listen counter results and show them in app
            .build();

You can find this class from my gist
https://gist.github.com/nomanr/d142f4ccaf55ceba22e7f7122b55b9b6

A: You should use OnTouchListener instead of OnClickListener.
However, your question is ambiguous. If you want to increment the value only once when the button is released you would do something like this:
button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            count++;
        }
    }
};

If you want to increase count while the user is holding down the button you would do it like this:
button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        count++;
        myTextView.setText("Click count: "+count);
    }
};

Where myTextView of course is the textview you want to show the clicks on.

A: Use custom touch listener like this,
public class CustomTouchListener implements View.OnTouchListener {
    public boolean onTouch(View view, MotionEvent motionEvent) {
    switch(motionEvent.getAction()){
            case MotionEvent.ACTION_DOWN:
           count = count + 1;
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
          textView.setText(Integer.toString(count));
                break;
    }
        return false;
    }
}

and set these listener to your button. May it helps you.

A: As @shalini gave answer is right but there are little change as per your requirement is
public class CustomTouchListener implements View.OnTouchListener {
    public boolean onTouch(View view, MotionEvent motionEvent) {
    switch(motionEvent.getAction()){
            case MotionEvent.ACTION_DOWN:
               count = count + 1;
               textView.setText(Integer.toString(count));
            break;

           case MotionEvent.ACTION_CANCEL:

           case MotionEvent.ACTION_UP:

                break;
    }
        return false;
    }
}


text:
Q: Socket.io multiple nodes using redis adpater returns 400 bad request With multiple nodes using redis adapter, socket returns 400 bad request and response is 1 Sid unknown.
Socket disconnection reason is timedout and transport close.
It works fine while running on single pods, when we scale pods to 2, sockets gets frequent disconnection.
React application + nginx + socket.io redis adapter + node Js
Socket client: 4.5.4
Socket server: 4.5.4.
Everything works fine in local but when deployed to kubernetes it starts disconnecting.

*

*Verified client and server versions to be same(4.5.4)

*have set transport as websocket on socket client

*used redis adapter for mutiple nodes.

*socket client and server connects to same path.


text:
Q: Error en array android studio JAVA Obtengo este error ;

attempt to get length of null array

En el siguiente codigo:
    try {

    path = rutas.obtener_ruta();
    carpeta = new File(path);
    listado = carpeta.list();
    imagenes= new ArrayList();

    for (int a=0;a<listado.length;a++)
    {
        if (   (obtener_extension(listado[a]).equalsIgnoreCase("jpg"))  || (obtener_extension(listado[a]).equalsIgnoreCase("JPG")) || (obtener_extension(listado[a]).equalsIgnoreCase("png")) || (obtener_extension(listado[a]).equalsIgnoreCase("PNG")) )
        {
            imagenes.add(path + listado[a]);
        }
    }

}
catch(Exception gfgf)
{
    Toast.makeText(this, gfgf.toString(), Toast.LENGTH_LONG).show();
}

He comprobado que la ruta que almacena "path" si existe, en Android 9 funciona bien pero tengo un Android que dice tener Android 10 y me da ese error.
Actualizacion:
He comprobado mediante codigo y las rutas si existen
public String obtener_ruta() {
    ruta1 = new File(ruta_interna);
    ruta2 = new File(ruta_externa);

    if (ruta1.isDirectory()) {
        return "storage/emulated/0/DCIM/";

    } else {
        return "storage/emulated/0/DCIM/";

    }

}

A: Bueno realice una verificación a tu código.
Primeramente recomendaria utilizar Environment.getExternalStorageDirectory() en lugar de una ruta fija, ejemplo:
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "DCIM";
File file = new File(path);
if (file.isDirectory())
    return path;

Ahora bien no olvides que deberás otorgar permisos para acceder a los directorios Manifest.permission.READ_EXTERNAL_STORAGE o Manifest.permission.WRITE_EXTERNAL_STORAGE según requieras, puedes encontrar información para los permisos en este enlace.
Lo probé en Android 10, espero te funcione. Saludos ;)

A: Gracias por comentar aun asi tenia errores al querer acceder a imagenes en Android 10, en un foro encontré con que agregar un permiso en el AndroidManifest dentro del meta "application" y eso soluciono mi problema:
android:requestLegacyExternalStorage="true"


text:
Q: Implementing caching technique in closest pair algorithm I am trying to optimize the closest pair brute force algorithm and compare it with the non cached program but I am stuck.
The main problem, is that I get worse performance when I cache the calculations with the for loops its almost cached time = 2 x non-cached time. Its like nothing happens if i change the size of the block... I use a struct point array P for x,y cordinates
Here is the non-cached code:
void compare_points_BF(int *N, point *P){
    int i, j, p1, p2;
    float dx, dy, distance=0, min_dist=inf();
    long calc = 0;

    for (i=0; i<(*N-1) ; i++){
        for (j=i+1; j<*N; j++){
            dx = P[i].x - P[j].x;
            dy = P[i].y - P[j].y;
            //calculate distance of current points
            distance = (dx * dx) + (dy * dy);
            calc++;
            if (distance < min_dist){
                min_dist = distance;
                p1 = i;
                p2 = j;
            }
        }
    }
    printf("%ld calculations\t", calc);
}

And here is the cached version:
    void compare_points_BF(int *N, int *B, point *P){
        int i, j, ib, jb, p1, p2, num_blocks = (*N + (*B-1)) / (*B);
        float dist=0, min_dist=inf();
        long calc=0;

        //break array data in N/B blocks
        for (i = 0; i < num_blocks; i++){
            for (j = i; j < num_blocks; j++){
                for (jb = j * (*B); jb < min((j+1) * (*B), *N); jb++){
                    //avoid double comparisons that occur when i block = j block
                    for (i == j ? (ib = jb + 1) : (ib = i*(*B)); ib < min((i+1) * (*B), *N); ib++){
                        calc++;
                        //calculate distance of current points
                        if((dist = (P[ib].x - P[jb].x) * (P[ib].x - P[jb].x) +
                                (P[ib].y - P[jb].y) * (P[ib].y - P[jb].y)) < min_dist){
                            min_dist = dist;
                            p1 = ib;
                            p2 = jb;
                        }
                    }
                }
            }
        }
        printf("%ld calculations\t", calc);
}

For example the output of non-cached program is:
N = 8192     Run time: 0,080 sec
N = 16384    Run time: 0,330 sec
N = 32768    Run time: 1,280 sec
N = 65.536   Run time: 5,290 sec
N = 131.072  Run time: 21,290sec
N = 262.144  Run time: 81,880sec
N = 524.288  Run time: 327,460 sec

But with the cached example I get:
33550336 calculations   Block_size = 128    N = 8192    Run time: 0.402 sec
33550336 calculations   Block_size = 256    N = 8192    Run time: 0.383 sec
33550336 calculations   Block_size = 512    N = 8192    Run time: 0.384 sec
33550336 calculations   Block_size = 1024   N = 8192    Run time: 0.381 sec
33550336 calculations   Block_size = 2048   N = 8192    Run time: 0.398 sec
33550336 calculations   Block_size = 4096   N = 8192    Run time: 0.400 sec
33550336 calculations   Block_size = 8192   N = 8192    Run time: 0.401 sec
33550336 calculations   Block_size = 16384  N = 8192    Run time: 0.383 sec

134209536 calculations  Block_size = 128    N = 16384   Run time: 1.579 sec
134209536 calculations  Block_size = 256    N = 16384   Run time: 1.610 sec
134209536 calculations  Block_size = 512    N = 16384   Run time: 1.630 sec
134209536 calculations  Block_size = 1024   N = 16384   Run time: 1.530 sec
134209536 calculations  Block_size = 2048   N = 16384   Run time: 1.537 sec
134209536 calculations  Block_size = 4096   N = 16384   Run time: 1.562 sec
134209536 calculations  Block_size = 8192   N = 16384   Run time: 1.520 sec
134209536 calculations  Block_size = 16384  N = 16384   Run time: 1.626 sec

536854528 calculations  Block_size = 128    N = 32768   Run time: 6.170 sec
536854528 calculations  Block_size = 256    N = 32768   Run time: 6.207 sec
536854528 calculations  Block_size = 512    N = 32768   Run time: 6.219 sec
536854528 calculations  Block_size = 1024   N = 32768   Run time: 6.131 sec
536854528 calculations  Block_size = 2048   N = 32768   Run time: 6.077 sec
536854528 calculations  Block_size = 4096   N = 32768   Run time: 6.216 sec
536854528 calculations  Block_size = 8192   N = 32768   Run time: 6.130 sec
536854528 calculations  Block_size = 16384  N = 32768   Run time: 6.181 sec

I have checked over and over the code and it seems to be correct. What am I missing here?
Does the compiler optimize the code to implement better cache usage than what I am trying to achieve?
Thanks in advance!

A: Been a long time but just to answer-close the question.
float compare_points_BF(register int N, register int B, point *P, register point *p1, *p2;){

register int i, j, ib, jb, iin, jjn, num_blocks = (N + (B-1)) / B;
register float distance=0, min_dist=FLT_MAX, regx, regy;

    //break array data in N/B blocks
    for (i = 0; i < num_blocks; i++){
        for (j = i; j < num_blocks; j++){
          iin = ( ((i+1)*B) < N ? ((i+1)*B) : N);
          jjn = (((j+1)*B) < N ? ((j+1)*B) : N);
          //reads the moving frame block to compare with the i block
          for (jb = j * B; jb < jjn; jb++){
            //avoid float comparisons that occur when i block = j block
            //Registers Allocated
            regx = P[jb].x;
            regy = P[jb].y;
            for (i==j ? (ib=jb+1):(ib=i*B); ib < iin; ib++){
               //calculate distance of current points
               if((distance = (P[ib].x - regx) * (P[ib].x - regx) +
                        (P[ib].y - regy) * (P[ib].y - regy)) < min_dist){
                min_dist = distance;
                p1 = &P[ib];
                p2 = &P[jb];
               }
             }
           }
         }
    }
    return sqrt(min_dist);
}

This use of cache can speed up to 10%.
Here are some results.
Block
Size    Number of elements
        8192    16384   32768   65536   131072  262144  524288  1048576
128     0,079   0,310   1,260   4,960   19,740  78,990  315,661 1.260,862
256     0,079   0,310   1,250   4,940   19,830  78,820  315,410 1.258,402
512     0,080   0,320   1,260   4,920   19,640  78,480  313,851 1.253,141
1024    0,080   0,320   1,250   4,870   19,430  77,540  310,120 1.237,772
2048    0,079   0,310   1,240   4,850   19,340  77,061  308,211 1.229,892
4096    0,079   0,300   1,210   4,890   19,670  78,300  313,310 1.250,572
8192    0,078   0,310   1,210   4,870   19,510  78,110  312,770 1.249,091
16384           0,300   1,200   4,860   19,420  77,870  312,151 1.246,192
32768                   1,190   4,780   19,310  77,460  310,970 1.242,102
65536                           4,760   19,230  77,660  312,191 1.249,872
131072                                  18,972  76,850  310,470 1.246,261
262144                                          76,400  307,521 1.239,402


text:
Q: Can/Should custom $resource action methods be tested? In a angular service I have $resource action methods such as :
class FooService {
  /*@ngInject*/
  constructor($resource) {
    this.Foo = $resource('/foo/:fooId/',
                          {fooId: '@fooId'},
                          {
                             bar: {
                                method: 'GET',
                                url: '/foo/:fooId/bar/',
                                isArray: true
                          }
                );
  }
  getAllFoo() {
    return this.Foo.query();
  }
}

is bar testable ?
I already have tests for methods such as getAllFoo(), but I am not so sure about $resource action methods.
Is it ok to use them directly in controller, as in
this.FooService.Foo.bar(params).$promise.then ?
Should they be tested ?
And if so, how ?
EDIT:
I know how to test getAllFoo() :
describe('FooService', () => {
    let $rootScope, $resource, $httpBackend, $log, $interval;
    let makeFooService, translateMock;
    let mockAllFoo = [
        {"id": 123,"stuff": "asdf asdf"},
        {"id": 124,"stuff": "hjghjg"}
    ];

    beforeEach(window.module(FooModule.name));

    beforeEach(inject((_$rootScope_, $q, _$resource_, _$httpBackend_, _$log_) => {
        $rootScope = _$rootScope_;
        queryDeferred = $q.defer();
        $resource = _$resource_;
        $httpBackend = _$httpBackend_;
        $log = _$log_;
        translateMock = { use: () => ({}) };
        makeFooService = () =>  new FooService(_$resource_);
    }));

    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });
    describe('Service', () => {
    it('has a resource-property [Foo]', () => {
        let service = makeFooService();
        expect(service.Foo).not.toBeNull();
    });

    it('should load all foos when getAllFoo() is called', () => {
        $httpBackend.expect('GET', /(.+)\/foo/).respond( () => [200, mockAllFoo, 'success'] );
        let service = makeFooService();
        let allFoo = service.getAllFoo();
        $httpBackend.flush();
        expect(allFoo.length).toBe(2);
    });

So I know how to test getAllFoo() but not how to test bar();
If bar is testable and usable in a controller directly, then I dont see the point of doing methods such as getAllFoo() that are simply wrapper around $resource action methods. I need clarifications on the best practices here.

A: I think it's a good idea test resources, some resource can have response transformers or some logic to create the URL request. Angular provides $httpBackend to performer test in http requests being able to mock the http response.
Mock the request
$httpBackend.when('GET', '/foo').respond({foo: 'bar'}, {'A-Token': 'xxx'});

Release the HTTP response
$httpBackend.flush();

https://docs.angularjs.org/api/ngMock/service/$httpBackend
Yes, In my option there is no needed to create a "wrapper" only if you need do some logic before call the actual resource.
In order to test "bar" you will need do something similar to the following code:
it('should call the correct url and handler the response right', (done)=>{
    $httpBackend.expect('GET', '/foo/bar_id/bar/').respond( () => [200, {'id': 124,'stuff': 'hjghjg'}, 'success'] );
    let service = makeFooService();

    service.bar({fooId: 'bar_id'}).$promise.then(result =>{
        expect(result).toEqual({'id': 124,'stuff': 'hjghjg'});
        done();
    });
    $httpBackend.flush();
});

Also I think it's okay call the resource method directly from the controller. $resource provides a particular functionality that you don't need treat the promise, you can assign the response value directly to a var like:
var bar = this.FooService.Foo.bar(params);

https://docs.angularjs.org/api/ngResource/service/$resource


text:
Q: Can the form action attribute call a javascript function in an external javascript file? I have the form tag written as such:
<form id="form" action="mail.php" method="post"><!--form here--></form>

Currently this poses some problems, so I am switching the form action to an AJAX solution, however, I would like the AJAX function to be in an external JavaScript file. I know that you can link the form action attribute to a file, but how would I tell the form to look at the specific function in the file?
Any help is greatly appreciated!

A: just include the script file using <script src="file.js" type="text/javascript" /> and call the function in file wherever you want... you don not need to tell the program where to look for function .. all the script code is included within the file with the use of <script>

A: you can use:
onsubmit="SubmitFormViaAjax();return false;"

This way the form won't submit itslef (return false) and you can use any function in the included form to submit the form's data directly to the recipient via ajax.
Just make sure to include the ajax functions file in the page.


text:
Q: How to trigger increment/decrement on row insertion or deletion? I have a table of members and a table of articles.
The members can vote on an article. Each individual vote is recorded.
I would like to increment by 1 the article authors vote tally when a vote row is added, and decrement by 1 when the article author's vote tally when a vote row is removed.
How would I do that in MySQL? I know that you can use triggers but how do I do it?

A: You can do it like this
CREATE TRIGGER tg_ai_article_votes
AFTER INSERT ON article_votes
FOR EACH ROW
  UPDATE articles
     SET votes = COALESCE(votes, 0) + 1
   WHERE id = NEW.article_id;

CREATE TRIGGER tg_ad_article_votes
AFTER DELETE ON article_votes
FOR EACH ROW
  UPDATE articles
     SET votes = COALESCE(votes, 0) - 1
   WHERE id = OLD.article_id;

You didn't provide your specific table schema so I improvised with table and column names in my example.
Here is SQLFiddle demo


text:
Q: JQuery won't work after Ajax call Why does my JQuery only work on the first page of my endless scroll? I am using the .on() method...isn't this not supposed to happen with .on()?
Here is my JQuery in custom.js:
$(document).ready(function(){
  $(document).on('click', '.article_description', function() {
     $('.article_description').toggleClass("article_description article_description_full");
  });
});

And my HTML:

        <img src="<%=asset_path "#{article.image}">

<%= link_to article.title, "#{article.location}", :target => "_blank"%>

<%= article.description.html_safe%>

<%= article.date_published %>  &nbsp|&nbsp <%= link_to article.source, "http://www.#{article.source}", :target => "_blank"%>

         <%=article.notes%>

A: Here's a working example, please run the code snippet below,

$(document).on('click', '.article_description', function() {
  $(this).toggleClass("article_description_full");
});
var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   console.log(st);
   if (st > lastScrollTop){
     // downscroll code
     if ((Math.round(st/100)*100) % 800 == 0) {
  $("#wrapper").addClass("spinner");
  // insert a cloned article_well_main after 2 seconds
  setTimeout(function(){
    var that = $(".article_well_main:first").clone(false);
           that.insertAfter(".article_well_main:last").find(".article_description")
           .removeClass("article_description_full");
    that.hide().fadeIn();
    $("#wrapper").removeClass("spinner");
  }, 2000);
     }
   } else {
      // upscroll code
   }
   lastScrollTop = st;
});
.article_description {
 border:1px solid red;
 background-color: #DDD;
 cursor: pointer;
}
.article_description.article_description_full {
 min-height: 100px;
}
.spinner {
 background: url("https://i1.wp.com/cdnjs.cloudflare.com/ajax/libs/galleriffic/2.0.1/css/loader.gif") no-repeat bottom center;
}
.container-fluid {
 min-height: 800px;
 padding-bottom: 800px;
}
@media only screen and (min-width: 768px) {
    .container-fluid {
     min-height: 1200px;
     padding-bottom: 1200px;
    }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-MfvZlkHCEqatNoGiOXveE8FIwMzZg4W85qfrfIFBfYc= sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">

<%= link_to article.title, "#{article.location}", :target => "_blank"%>

<%= article.description.html_safe%>

<%= article.date_published %>  &nbsp|&nbsp <%= link_to article.source %>

            <%=article.notes%>

Note: I am using a timer to mimic an endless scroll

A: Instead of using on method please use bind method
try the following code

$(document).bind('click', '.article_description', function() {
     $('.article_description').toggleClass("article_description article_description_full");
  });

The above working perfectly for me
let me know if you have any query
Thanks


text:
Q: Using Django signals to identify a present user session i want to use django signals to identify if a user is logged-in twice and if so, revoke his first session so that only one user session can be present at once.
i used the following example but it seems that my signals.py does not even gets reconcnized and i dont know why.
Example:
How to prevent multiple login in Django
accounts/signals.py
from django.contrib.auth import user_logged_in
from django.dispatch.dispatcher import receiver
from django.contrib.sessions.models import Session
from .models import UserSession

@receiver(user_logged_in)
def remove_other_sessions(sender, user, request, **kwargs):
    # remove other sessions
    Session.objects.filter(usersession__user=user).delete()

    # save current session
    request.session.save()

    # create a link from the user to the current session (for later removal)
    UserSession.objects.get_or_create(
        user=user,
        session=Session.objects.get(pk=request.session.session_key)
    )

accounts/models.py
# Model to store the list of logged in users
class UserSession(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    session = models.OneToOneField(Session, on_delete=models.CASCADE)

accounts/apps.py
from django.apps import AppConfig

class AccountsConfig(AppConfig):
    name = 'Accounts'

    def ready(self):
        import Accounts.signals

but for some reason nothing gets written onto the database for that table.
do i maybe miss something here, this is the very first time i get in touch with signals so i might missed something at the configuration.

A: Try this,
default_app_config = 'Accounts.apps.AccountsConfig'

Add this line in __init__.py file of your apps.py file directory.


text:
Q: Autocomplete design I'm trying to autocomplete an input[type='search'], so the idea is when the user change the value of this input, he'll get a list of the strings which are contains the written string.
Dealing that, when I try to write a string, I get it but its design format is very weird.

Its such a
Nectarys
 which is added by default. How can I fix this, by just displaying a simple list which extends the input[type='search']?
Here is the code that I'm using in HTML :
<input type="search" name="nomPoste" id="nomPoste" class="form-control" />

Any brilliant idea, please ?

A: Include the jqueru ui css file on your page.

A: Use CSS to format the list however you ilke.
Note that the different browsers are likely to handle something like this very differently, so I would recommend combining your custom CSS with a CSS reset.


text:
Q: For cycle with strings I have several files named for example name_a, name_b, name_c, anothername_a, anothername_b,... Now I would like to make a for loop, such as
for(i = a,b,c){
dosomething
}

Is that possible in C++, if so, how? I am a beginner in programming and so far I have seen only iterating over numbers.
Thank you!

A: Store the names in a container(std::vector is a good default) and iterate over it.
std::vector<std::string> filenames = {"foo.bar", "apa.bepa", "cepa.baz"};
for (const auto& name: filenames)
{
    std::ifstream input(name);
    // ...
}

A: With modern c++ you can almost do exactly what you want:
#include <fstream>
int main()
{
    for ( const auto& file: { "name_a", "name_b", "name_c", "anothername_a", "anothername_b" } )
    {
        std::ifstream input( file );
    }
}


text:
Q: What are some real life examples of Design Patterns used in software I'm reading through head first design patterns at the moment and while the book is excellent I also would like to see how these are actually used in the real world.
If you know of a good example of design pattern usage (preferably in a OSS program so we can have a look :) then please list it below.

A: An ah-ha moment for me for the observer pattern was to realize how closely associated it is with events. Consider a Windows program that needs to acheive loosely communications between two forms. That can easily be accomplished with the observer pattern.
The code below shows how Form2 fires an event and any other class registered as an observer get its data.
See this link for a great patterns resource:
http://sourcemaking.com/design-patterns-and-tips
Form1's code:
namespace PublishSubscribe
{
    public partial class Form1 : Form
    {
        Form2 f2 = new Form2();

        public Form1()
        {
            InitializeComponent();

            f2.PublishData += new PublishDataEventHander( DataReceived );
            f2.Show();
        }

        private void DataReceived( object sender, Form2EventArgs e )
        {
            MessageBox.Show( e.OtherData );
        }
    }
}

Form2's code
namespace PublishSubscribe
{

    public delegate void PublishDataEventHander( object sender, Form2EventArgs e );

    public partial class Form2 : Form
    {
        public event PublishDataEventHander PublishData;

        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click( object sender, EventArgs e )
        {
            PublishData( this, new Form2EventArgs( "data from form2" ) );
        }
    }

    public class Form2EventArgs : System.EventArgs
    {
        public string OtherData;

        public Form2EventArgs( string OtherData )
        {
            this.OtherData = OtherData;
        }
    }
}

A: I use passive view, a flavor of the Model View Presenter pattern, with any web forms like development (.NET) to increase testability/maintainability/etc
For example, your code-behind file might look something like this
Partial Public Class _Default
    Inherits System.Web.UI.Page
    Implements IProductView

    Private presenter As ProductPresenter

    Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
        MyBase.OnInit(e)
        presenter = New ProductPresenter(Me)
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        presenter.OnViewLoad()
    End Sub

    Private ReadOnly Property PageIsPostBack() As Boolean Implements IProductView.PageIsPostBack
        Get
            Return Page.IsPostBack
        End Get
    End Property

    Public Property Products() As System.Collections.Generic.List(Of Product) Implements Library.IProductView.Products
        Get
            Return DirectCast(gridProducts.DataSource(), List(Of Product))
        End Get
        Set(ByVal value As System.Collections.Generic.List(Of Product))
            gridProducts.DataSource = value
            gridProducts.DataBind()
        End Set
    End Property
End Class

This code behind is acting as a very thin view with zero logic.  This logic is instead pushed into a presenter class that can be unit tested.
Public Class ProductPresenter
    Private mView As IProductView
    Private mProductService As IProductService

    Public Sub New(ByVal View As IProductView)
        Me.New(View, New ProductService())
    End Sub

    Public Sub New(ByVal View As IProductView, ByVal ProductService As IProductService)
        mView = View
        mProductService = ProductService
    End Sub

    Public Sub OnViewLoad()
        If mView.PageIsPostBack = False Then
            PopulateProductsList()
        End If
    End Sub

    Public Sub PopulateProductsList()
        Try
            Dim ProductList As List(Of Product) = mProductService.GetProducts()
            mView.Products = ProductList
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
End Class

A: Use code.google.com
For example the search result for "Factory" will get you a lot of cases where the factory Pattern is implemented.

A: The Chain of Responsibility pattern is implemented in the handling of DOM events. For example, (and simplifying slightly) when an element is clicked on, that element gets the first opportunity to handle the event, and then each ancestor in tern until the top level document is reached or one of them explicitly stops the event "bubbling" any further.

A: C#, Java and Python have a standard implementation of the Iterator pattern. In C# and Python this has been intergrated in the language so you can just use yield return statements.

A: Template pattern is commonly used in the implementation of dotnet events to set up preconditions and respond to postconditions. The degenerate case is
void FireMyEvent(object sender, EventArgs e)
{
  if (_myevent != null) _myEvent(sender, e);
}

in which the precondition is checked. In this case the precondition is that handlers can be invoked only when at least one has been bound. (Please don't tell me I should invoke the handlers asynchronously. I know that. I am illustrating Template pattern, not asynchronous programming technique.)
A more elaborate precondition might involve checking a property that governs the firing of events.
Template pattern is also commonly used to implement hooks, for example
public virtual void BeforeOpenFile(string filepath)
{
  //stub
}
public virtual void AfterOpenFile(string filepath)
{
  //stub
}
public sealed void OpenFile(string filepath)
{
  BeforeOpenFile(filepath); //do user customisable pre-open bits
  //do standard bits here
  AfterOpenFile(filepath); //do user customisable post-open bits
}

A: If you're familiar with Python, check out the Twisted framework.
http://twistedmatrix.com/trac/

A: Perhaps a good example, as pointed out in the Head First Design Patterns too, is the JAVA Swing API which implements the Observer pattern. More specifically, the JButton (or the superclass AbstractButton) is the Observable class and provides methods to add and remove "Observers", or "Listeners" as they are called in Swing.

A: Composite is used extensively in UI. Components can be leaf components e.g. buttons and labels or composites e.g. panels, that can contain other leaf or composite components. From the point of view of the client, all components are treated the same, which greatly simplifies the client code.

A: The Command pattern is used everywhere you have Undo functionality.


text:
Q: navigationoptions won't work in React Native I'm following this tutorial here: https://www.youtube.com/watch?v=cgg1HidN4mQ&list=PLy9JCsy2u97lNUL3e3R-uoMQv5GDvf22T
The guy in the tutorial are using TabNavigator, but that is not longer the right way to do It, so I'm using createBottomNavigator instead.
Here is my code of the MainScreen component
import React from 'react';
import {
    View,
    Text,
    StyleSheet
} from 'react-native';

import ProfileTab from './AppTabNavigator/ProfileTab'
import LikesTab from './AppTabNavigator/LikesTab'
import SearchTab from './AppTabNavigator/SearchTab'
import AddMediaTab from './AppTabNavigator/AddMediaTab'
import HomeTab from './AppTabNavigator/HomeTab'

import { TabNavigator } from 'react-navigation'
import { createBottomTabNavigator } from 'react-navigation'

import { Icon } from 'native-base'

class MainScreen extends React.Component {

    static navigationOptions = {
        headerLeft: <Icon name="ios-camera-outline" style={{paddingLeft: 10}} />,
        title: "Instagram",
        headerRight: <Icon name="ios-send-outline" style={{paddingRight: 10}}/>
    }
}

// export default MainScreen;
export default createBottomTabNavigator({
    HomeTab: HomeTab,
    SearchTab: SearchTab,
    AddMediaTab: AddMediaTab,
    LikesTab: LikesTab,
    ProfileTab: ProfileTab
})

const styles = StyleSheet.create({
    container:{
        flex:1,
        alignItems: 'center',
        justifyContent: 'center'
    }
})

My problem Is that navigationoptions won't work. They don't show up when I start the application. I can guess that this has something to do with the use of createBottomNavigator?

A: I made a snack on expo.io to do what I think you're trying to do. It's a little unclear because you're trying to set a left and right icon for the header, but tab navigators don't have headers.
I've nested a stack navigator on the settings screen in this example, and you can see how I'm using a single components static navigation options to override the "global" navigation options for the whole stack navigator.
Here's the snack.
If you want the header on every tab no matter what, just reverse the nesting and put your tab navigator inside a stack navigator. Here's a snack for that, too.
https://snack.expo.io/rk3hoalVm


text:
Q: Why my string replace is not working in JavaScript? I'm trying to replace a placeholder in a string I'm generating.
My string looks like this:
 var s = 'module("SlapOS UI Basic Interaction"); ' +
         'asyncTest( "${base_url}", function() { ' +
         ' expect( __number__ ); ' +
         ' ok(testForElement("div#global-panel"), "element present");' +
         ' start(); })';

And I want to replace __number__.
I can get the index correctly like so:
 s.indexOf("__number__");

but replacing does not work...
 s.replace("__number__", "1");

Question:
What am I doing wrong here? Makes no sense to my why it does not work.

A: The replace method does not modify the existing string. It returns a new one.
var result = s.replace("__number__", "1");


text:
Q: Which type of ANOVA? I would like some help in which type of analysis (ANOVA) would be the best for the following information:
Tests dealt with whether a good or bad day tomorrow versus a good or bad day one year into the future is viewed as being better or worse. Subjects had to rate possible future events from -3 (most negative) to 3 (most positive), with zero being neutral.
So the variables are good day, bad day, tomorrow, one year and how they are viewed. Thanks for the help.

A: Since the dependent variable is ordinal, you probably want ordinal logistic regression. But your independent variables are very unclear; it sounds like they should be "type of day" and "date of prediction".  What you've got written here looks like the levels of your independent variables.


text:
Q: Start coroutines when the class is not a MonoBehaviour EDIT: The answer that solves this problem is indeed in the answer of the post whose duplicate is this one. If you have the same problem as in the title, please refer to the other post.
I made a simple rig that moves stuff over time like this:
 Transform from;
 Transform to;
 float overTime;
 IUIAnimationEvent chain;
 public delegate void UIchain();
 public event UIchain NEXT_FUNCTION;
 public MoveAction(Transform from, Transform to, float overTime, IUIAnimationEvent chain)
 {
     this.from = from;
     this.to = to;
     this.overTime = overTime;
     this.chain = chain;
 }
 public void Move()
 {
     MonoBehaviour _lead = new MonoBehaviour();
     if (moveRoutine != null)
     {
         _lead.StopCoroutine(moveRoutine);
     }
     moveRoutine = _Move(from, to, overTime);
     _lead.StartCoroutine(moveRoutine);
 }
 IEnumerator _Move(Transform from, Transform to, float overTime)
 {
     Vector2 original = from.position;
     float timer = 0.0f;
     while (timer < overTime)
     {
         float step = Vector2.Distance(original, to.position) * (Time.deltaTime / overTime);
         from.position = Vector2.MoveTowards(from.position, to.position, step);
         timer += Time.deltaTime;
         yield return null;
     }
     if(NEXT_FUNCTION != null)
     {
         NEXT_FUNCTION();
     }
 }

However, to make it work like I wish, I have to instantiate them, so they can't be a MonoBehaviour. Notice what I did with the _lead variable. I made it so I could start coroutines like any other. If my class is NOT a MonoBehaviour, how to start a coroutine from it?
Or if that isn't possible, how to instantiate classes that ARE MonoBehaviour? I noticed the _use AddComponent instead, but the classes are not components. They are used by another component and will not be put on a GameObject from the inspector.

A: Coroutines must be bound to a MonoBehaviour. Or in other words, you will need at least one MonoBehaviour to start a coroutine. And sadly, you cannot instantiate a MonoBehaviour:
var mono = new MonoBehaviour(); // will not work

There is a workaround that I can think of right now. You write your coroutine as usual and then you start it from another class that inherits from MonoBehaviour. That is, a function only needs to return IEnumerator in order to be started as Coroutine.

If another is started, the already started coroutine is stopped and a
  new one is called

If you want to do it inside a non-MonoBehaviour class I'm afraid it will not be possible.

Remember: You will need at least one MonoBehaviour to start a coroutine.

I will call what you want to achieve: a Coroutine Management feature and my understanding is that you want to include that feature inside your non-MonoBehaviour class. But thanks to my Remember quote above you cannot do it right now.
But including it in-side a .dll might be possible as a .dll can contain many classes. And you can use Access Modifiers to enforce your rules (the internal modifier is my favorite).
If I were you I would treat Coroutine Management as a separate problem and would build a .dll to handle them separately so that it would not mess up with my game-play business.

A: You can't start coroutines from a class that is not a MonoBehaviour as the method StartCoroutine() is part of this class.
Just create a new GameObject and then add your class as a Component on it
You can instantiate your class that inherit from MonoBehaviour (for this example MyClass) like this:
GameObject baseObject = new GameObject();
baseObject.AddComponent<MyClass>();

See singleton pattern for example


text:
Q: lazy type Exception when trying to get resultset I am trying to get the orders by using the getOrders(String domain) function from domain DAO
this is the code:
Set<Order> orders;
orders = domainService.getOrders('google.com');

but I keep getting this error

failed to lazily initialize a collection of role: com.latinon.reportator.model.Domain.ordersDomain, could not initialize proxy - no Session

which one is the correct way to set the lazy type without getting the error
pojos
domain
@Entity
@Table(name="Domain")
public class Domain {

    private Set<Order> ordersDomain = new HashSet<Order>(0);
    private Set<User> userDomain = new HashSet<User>(0);

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(name="Order_Domain", joinColumns={
            @JoinColumn(name="Order_Domain_Domain_id")
    },inverseJoinColumns={
            @JoinColumn(name="Order_Domain_Order_id", nullable=false,updatable=false)
    })
    public Set<Order> getOrdersDomain() {
        return ordersDomain;
    }
    public void setOrdersDomain(Set<Order> ordersDomain) {
        this.ordersDomain = ordersDomain;
    }
}

order
@Entity
@Table(name="Order")
public class Order {

    private Set<Domain> orderDomains = new HashSet<Domain>(0);

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(name="Order_Domain", joinColumns={
            @JoinColumn(name="Order_Domain_Order_id",nullable=false,updatable=false)
    }, inverseJoinColumns={
            @JoinColumn(name="Order_Domain_Domain_id",nullable=false,updatable=false)
    })
    public Set<Domain> getOrderDomains() {
        return orderDomains;
    }
    public Set<Domain> getOrderDomains() {
        return orderDomains;
    }
}

DAOs
Domain
public interface DomainDAO {
    public void saveDomain(Domain domain);
    public void updateDomain(Domain domain);
    public Domain getDomainById(Integer id);
    public Domain getDomain(String domain);
    public void deleteDomain(Integer id);
    public Set<Order> getOrders(String domain);
}

Order
public interface OrderDAO {
    public void saveOrder(Order order);
    public void updateOrder(Order order);
    public Order getOrderById(Integer id);
    public void deleteOrder(Integer id);
    public Order getOrderByAdUnit(String adUnitId);
}

servicios
domain
public interface DomainService {
    public void saveDomain(Domain domain);
    public void updateDomain(Domain domain);
    public Domain getDomainById(Integer id);
    public void deleteDomain(Integer id);
    public Domain getDomain(String domain);
    public Set<Order> getOrders(String domain);
}

domain service implementation
@Service
public class DomainServiceImpl implements DomainService {
    private DomainDAO domainDao;
    public DomainDAO getDomainDao() {
        return domainDao;
    }
    public void setDomainDao(DomainDAO domainDao) {
        this.domainDao = domainDao;
    }

    public DomainServiceImpl() {
        // TODO Auto-generated constructor stub
    }
    @Transactional
    public Set<Order> getOrders(String domain) {
        Domain domainAux = this.domainDao.getDomain(domain);
        return domainAux.getOrdersDomain();
    }
}

order
public interface OrderService {
    public void saveOrder(Order order);
    public void updateOrder(Order order);
    public Order getOrderById(Integer id);
    public void deleteOrder(Integer id);
    public Order getOrderByAdUnit(String adUnitId);
}

order service implementation
@Service
public class OrderServiceImpl implements OrderService {

    private OrderDAO orderDAO;

    public OrderDAO getOrderDAO() {
        return orderDAO;
    }
    public void setOrderDAO(OrderDAO orderDAO) {
        this.orderDAO = orderDAO;
    }

    public OrderServiceImpl() {
        // TODO Auto-generated constructor stub
    }
    @Transactional
    public Order getOrderByAdUnit(String adUnitId) {
        return this.orderDAO.getOrderByAdUnit(adUnitId);
    }
}

A: In Hibernate if something is lazily loaded, it should be loaded while a session is available. After session is closed, it can't be loaded (lazy init exception)
Inside DomainServiceImpl.getDomain method say something like:
Hibernate.initialize(domainAux.getOrdersDomain())

If your DAO's are your session boundaries, do above in respective DAO methods.


text:
Q: Angular 7: Custom Async Validator I'm trying to create a custom async validator for my registration form where it checks if an email already exists. The backend returns 404 if the email does not exist and 200 if it does exist (can't change this old code).
I have found a couple tutorials but didn't find one using the latest rxjs library. I created this Validation class:
export class UniqueEmailValidator {
    static createValidator(httpClient: HttpClient, degree: number, wlId: number) {
        return (control: AbstractControl) => {
            return httpClient.get(`${url}?degree=${degree}&email=${control.value}&wl_id=${wlId}`)
                .pipe(
                    map(
                        (response: Response) => {
                            return response.status === 404 ? null : { emailNotUnique: true };
                        }
                    )
                );
        };
    }
}

and in my ts file creating the form I'm using this
this.registerForm = this.fb.group({
            email: ['', [Validators.required, Validators.email], UniqueEmailValidator.createValidator(
                this.httpClient, this.wlService.wl.degree, this.wlService.wl.id)],

The xhr call is being done and returned correctly but the form control of email is staying as pending. Any ideas on what I did wrong?

A: Figured it out after a while and more research.
Validation class:
@Injectable()
export class UniqueEmailValidator {
    constructor(private http: HttpClient) {}

    searchEmail(email: string, degree: number, wlId: number) {
        return timer(1000)
            .pipe(
                switchMap(() => {
                    // Check if email is unique
                    return this.http.get<any>(`${url}?degree=${degree}&email=${email}&wl_id=${wlId}`);
                })
            );
    }

    createValidator(degree: number, wlId: number): AsyncValidatorFn {
        return (control: AbstractControl): Observable<{ [key: string]: any } | null> => {
            return this.searchEmail(control.value, degree, wlId)
                .pipe(
                    map(
                        (response: Response) => {
                            return null;
                        },
                    ),
                    catchError(
                        (err: any) => {
                            return err.status === 404 ? of(null) : of({ emailNotUnique: true });
                        },
                    ),
                );
        };
    }
}

Not sure if timer can be changed but I found it in an article and it works fine. Would love some confirmation on that.
Basically I'm doing a catchError since the response from the backend returns 404 and returning an observable again from the catchError.
Then in the form creation I'm doing:
        this.registerForm = this.fb.group({
            email: ['', [Validators.required, Validators.email], this.uniqueEmailValidator.createValidator(
            this.wlService.wl.degree, this.wlService.wl.id
        )],

And I added the UniqueEmailValidator as a provider in the module and injected in this component constructor.


text:
Q: Error in FactoMineR's summary.FAMD when printing categories I am doing a FAMD with FactoMineR treating NAs with imputeFAMD. The FAMD works fine, but the summary() produces an error just when it comes to printing the categories. There are 19 continuous and 2 categorial variables.
library(FactoMineR)
library(missMDA)#handle missing values
n = c(2, 3, 5, 3, 4, 6, 7, 3, 7, 3, 7, 8, 11, 4, 13)
s = c("aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc")
b = c(1, 4, NA, NA, 2, 1, 7, 1, 2, NA, NA, 2, 1, 7, NA)
all = data.frame(n, s, b)
complete = imputeFAMD(all)
FAMDall = FAMD(all, tab.comp = complete)
summary(FAMDall, nbelements = Inf, ncp=4)

after the continuous variables, the output of summary(FAMDall, nbelements = Inf, ncp=4) stops like this:
Categories
Error in mat[, indice + nb.col * (0:(ncp - 1))] <- obj$cos2[1:nbelements,  :
  number of items to replace is not a multiple of replacement length

A: The problem seems to be in the tab.comp argument. The FactoMineR documentation on ?FAMD asks for the entire object resulting from imputeFAMD, but what you need is the imputed matrix in the $tab.disj list element. See Examples section in ?imputeFAMD. This should work:
n = c(2, 3, 5, 3, 4, 6, 7, 3, 7, 3, 7, 8, 11, 4, 13)
s = c("aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc", "aa", "bb", "cc")
b = c(1, 4, NA, NA, 2, 1, 7, 1, 2, NA, NA, 2, 1, 7, NA)
all = data.frame(n, s, b)
complete = imputeFAMD(all)
FAMDall = FAMD(all, tab.comp = complete$tab.disj)
summary(FAMDall, nbelements = Inf, ncp=4)


text:
Q: Render Partial View to String and Convert to PDF Is there a way to render my Partial View to String or Html? and used that to convert to PDF?
I guess, the only item I need to accomplish is to Render my Partial View to String or HTML, if it's possible.
I already have a tool that can get .htm/.html files and convert it to PDF.
Thank you.


text:
Q: Conversion of individual mp4 files to ts yields unexpected playback I'm converting three mp4 files (h264, no audio, each with a duration of three seconds) to the mpeg-ts format like so.
ffmpeg -i 1.mp4 -c copy 1.ts
ffmpeg -i 2.mp4 -c copy 2.ts
ffmpeg -i 3.mp4 -c copy 3.ts

Please note: I can't combine the mp4 files beforehand. Each one has to be converted individually as shown above since they're being generated by a live recorder.
Then, I manually created a .m3u8 manifest like this one, so I could play those 3 ts files in sequence:
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-PLAYLIST-TYPE:VOD
#EXT-X-TARGETDURATION:3
#EXTINF:3,
1.ts
#EXTINF:3,
2.ts
#EXTINF:3,
3.ts
#EXT-X-ENDLIST

When I run the ffplay index.m3u8 command:

*

*1.ts is played for three seconds as expected;

*2.ts is played "for a split second" (maybe just a frame);

*3.ts is played for three seconds as expected.

Can someone explain why 2.ts is shown for such a brief time? When I run ffmpeg -i 2.ts, the output is correctly displaying a duration of three seconds.
Input #0, mpegts, from '2.ts':
  Duration: 00:00:03.00, start: 1.480000, bitrate: 49 kb/s

How can I change my mp4 -> ts conversion commands so that each file can play for their whole duration (i.e. three seconds each)? I'd like to avoid reencoding if possible.
Thank you, I'm adding a link to the three files and the manifest for completeness.

A: Ok, I found out this behavior if affected by the 'start' value which is being set by ffmpeg to '1.480000', as seen in the original question.
By setting a different, proper start value for each file, playback will work fine. This is done via the -muxdelay flag which represents the "maximum demux-decode delay" (i.e. an offset). For some reason, at least in my case, the flag should be provided with half the intended value (e.g 1.5 if the previous video(s) played for 3 seconds)
ffmpeg -i 1.mp4 -muxdelay 0 -c copy 1.ts
ffmpeg -i 2.mp4 -muxdelay 1.5 -c copy 2.ts
ffmpeg -i 3.mp4 -muxdelay 3.0 -c copy 3.ts

Problem's solved but I'm still wondering why only 2.ts was affected by the problem.