text:
Q: Exceção lançada ao excluir registro utilizando o Entity Framework Core. Como resolver? Ao tentar excluir registro das entidades "Pacientes" e "Médicos" é retornada uma exceção. O estranho é que para a entidade de "Agendamentos" tudo ocorre normalmente.
Segue a exceção:

An unhandled exception occurred while processing the request.
  InvalidOperationException: The instance of entity type 'Paciente'
  cannot be tracked because another instance with the same key value for
  {'Id'} is already being tracked. When attaching existing entities,
  ensure that only one entity instance with a given key value is
  attached. Consider using
  'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the
  conflicting key values.
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap.ThrowIdentityConflict(InternalEntityEntry
  entry)

Usarei o código da entidade "Paciente" como exemplo, mas ocorre da mesma forma para a outra entidade citada.

*

*Form na view que envia a ação
<form asp-action="Delete">
    <input type="hidden" asp-for="Id" />
    <input type="submit" value="Delete" class="btn btn-danger" /> |
    Back to List
</form>

*Cógigo da Controller
public async Task<IActionResult> Delete(Guid id)
{

    var pacienteViewModel = _mapper.Map<PacienteViewModel>(await _pacientesRepository.ObterPorId(id));
    if (pacienteViewModel == null)
    {
        return NotFound();
    }

    return View(pacienteViewModel);
}

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(Guid id)
{
    var pacienteViewModel = _mapper.Map<PacienteViewModel>(await _pacientesRepository.ObterPorId(id));

    if (pacienteViewModel == null) return NotFound();

    await _pacientesRepository.Remover(id);
    return RedirectToAction("Index");
}

*Código na camada de acesso a dados (Comum a todos, está na classe abstrata herdada por todas as entidades)
public virtual async Task Remover(Guid id)
{
    DbSet.Remove(new TEntity { Id = id});
    await SaveChanges();
}

Lembrando que o processo ocorre normalmente para a entidade "Agendamento", já analisei o código e não enxergo nada de diferente.

A: O problema não está no momento em que tentamos excluir, e sim quando obtemos o objeto através do EF Core antes de exlcuir.
O problema ocorre pois o EF Core não permite a alteração e exclusão de objetos mapeados pelo change tracking.
Segue a minha solução:
Problema:
    public virtual async Task<TEntity> ObterPorId(Guid id)
    {
        return await DbSet.FindAsync(id);
    }

Solução:
    public virtual async Task<TEntity> ObterPorId(Guid id)
    {

        return await DbSet.AsNoTracking()
                    .FirstAsync(c => c.Id == id);
    }


text:
Q: SDKs vs APIs - which is safer to implement related to data protection and how can I implement an SDK in the 'safest' way possible? If I want to use a third party SDK or API in my iOS Application - and I want to avoid giving the companies that distribute and offer these SDKs & APIs 'too' much data, if you will, what is the best way to approach integrating their technology - an SDK or API?
When I call an API - what kind of information is that giving them versus using their SDK? To me, it seems SDKs collect far much more data than APIs.
I am deciding whether I want to implement the Giphy iOS SDK into my iOS Application - but I discovered Meta (Facebook) owns this company now and tried to hide their acquisition from the U.S. Government - which makes me not trust Facebook (and now Giphy) far more than I already didn't trust them... I understand Apple uses Giphy via iMessage on iOS / iPad OS but they do it via Bing Search.
My overarching question is - should I use a company's API or SDK if I want to relinquish as little data as possible and how could I do the same using both, for example - How could I implement an SDK in the most safest/secure way possible to where my iOS app indirectly utilizes the SDK -- such as by embedding the static library into an Xcode Project (Framework) then importing said framework into the actual App -- would this make it most secure if I want to use an SDK over an API in order to get X functionality?

A: An SDK (aka Software Development Kit) is usually just a set of libraries or frameworks and accompanying tools, documentation and possibly also services.
An API (Application Programming Interface) is the public part of the interface of a library or framework. It's more like a specification and a contract, but strictly does not contain the behaviour.
So, in oder to answer your question in a non serious way, I would suggest you to use the API; because it does nothing :)
But, the reality is, it does not matter whether you use an SDK (a set for libraries) or a single framework or library. What matters more is, if you have access to the source code and whether you can trust the vendor. And, when you have the source code, whether it is comprehensible by glancing over the code and if you are able to quickly confirm that they don't do harm to you or your users.
Unfortunately, there ARE libraries - especially from vendors from the data collecting association, which do this business for a living, which come with the source, but that source is that large, that even after hours examining the code in an incomprehensible ancient language (Objective-C), you may have still no clue what the heck are they sending in this network request, and what this ominous looking URL is for.
Also, consider that, if you integrate a third party library, the code has the same entitlements as specified in your app.
So, I would recommend to avoid to use overly large and complex libraries, even if they come with source, and if you don't trust them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java URLConnection Issues with Integers I've been trying to get information from a webpage, specifically this site: http://www.ncbi.nlm.nih.gov/pubmed?term=%22pulmonary%20disease%2C%20chronic%20obstructive%22%5BMesh%5D (among other similar ones). I'm using the URL and URLConnection packages to do so. I'm trying to get a certain number from the webpage - on this page, I want the total number of articles (16428).
It says this near the top of the page: "Results: 1 to 20 of 16428" and when I look at the page source manually I can find this. However, when I try to use the java connection to obtain this number from the page source, for some reason the number it gets is "863399" instead of "16428".
Code:
    URL connection = new URL("http://www.ncbi.nlm.nih.gov/pubmed?term=%22pulmonary%20disease%2C%20chronic%20obstructive%22%5BMesh%5D");
    URLConnection yc = connection.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    String html = "";
    String inputLine;
    while ((inputLine = in.readLine()) != null) html += inputLine;
    in.close();

    int startMarker = html.indexOf("ncbi_resultcount");
    int endMarker = html.indexOf("ncbi_op");

    System.out.println(html.substring(startMarker, endMarker));

When I run this code, I get:

ncbi_resultcount" content="863399" />

rather than:

ncbi_resultcount" content="16428" />

Does anyone know why this is / how I can fix it?
Thanks!

A: I can't reproduce your problem and I have no idea why this is happening. Perhaps it's sniffing specific Java user agent versions. You'd then need to try to set the User-Agent header to something else to pretend as a "real" webbrowser.
yc.setRequestProperty("User-Agent", "Mozilla");

Unrelated to the concrete problem, I'd suggest to use a real HTML parser for this job, such as Jsoup. It's then as easy as:
Document document = Jsoup.connect("http://www.ncbi.nlm.nih.gov/pubmed?term=%22pulmonary%20disease%2C%20chronic%20obstructive%22%5BMesh%5D").get();
Element nbci_resultcount = document.select("meta[name=ncbi_resultcount]").first();
System.out.println(nbci_resultcount.attr("content")); // 16433


text:
Q: Reading from XML data from SQL Server reduces performance I am having a SQL view of the below script. As the table stores the data as XML (dbo.TEST.configuration), I have to select each column by reading the xml data. But when the record increases, it is getting too slow to load. Is there any method to improve its performance, please let me know?
WITH XMLNAMESPACES( DEFAULT 'http://tempuri.org/xmlConfiguration.xsd')

SELECT      dbo.TEST.uid, dbo.TEST.name, dbo.TEST.ClassUid, dbo.TEST.xmlData,
                  CAST(REPLACE(CAST(dbo.TEST.configuration AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/batchUid)[1]', 'NVARCHAR(200)') AS batchUid,
                  CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/statusUid)[1]', 'NVARCHAR(200)') AS statusUid,
                  CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/subjectUid)[1]', 'NVARCHAR(200)') AS subjectUid,
                  CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/cultureUid)[1]', 'NVARCHAR(200)') AS cultureUid,
                  CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/format)[1]', 'NVARCHAR(200)') AS format,
                  CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/secondFormat)[1]', 'NVARCHAR(200)') AS secondFormat,
                  CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/standardUid)[1]', 'NVARCHAR(200)') AS standardUid
FROM         dbo.TEST INNER JOIN
                  dbo.batch ON CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/batchUid)[1]', 'NVARCHAR(200)') = dbo.batch.uid INNER JOIN
                  dbo.status ON CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/statusUid)[1]', 'NVARCHAR(200)') = dbo.status.uid INNER JOIN
                  dbo.vFormat ON CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/format)[1]', 'NVARCHAR(200)') = CONVERT(NVARCHAR(200), dbo.vFormat.uid) OR
                  CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/secondFormat)[1]', 'NVARCHAR(200)') = CONVERT(NVARCHAR(200), dbo.vFormat.uid) INNER JOIN
                  dbo.standard ON CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/standardUid)[1]', 'NVARCHAR(200)') = dbo.standard.uid INNER JOIN
                  mainDb.dbo.Class ON dbo.TEST.ClassUid = mainDb.dbo.Class.uid INNER JOIN
                  dbo.subject ON CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/subjectUid)[1]', 'NVARCHAR(200)') = dbo.subject.uid INNER JOIN
                  mainDb.dbo.culture ON CAST(REPLACE(CAST(dbo.TEST.xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '')
                  AS XML ).value('(/xmlConfiguration/cultureUid)[1]', 'NVARCHAR(200)') = mainDb.dbo.culture.uid

Thanks in advance.
Sample xml data is below;
 <?xml version="1.0" encoding="utf-8"?>
 <xmlConfiguration xmlns="http://tempuri.org/xmlConfiguration.xsd">
 <secondFormat>3bd3d9cc-ad0a-e611-b086-00e04c6804ad</secondFormat>
 <batchUid>c7b4743b-4493-df11-981e-00221933d118</batchUid>
 <statusUid>f0b159ec-4193-df11-981e-00221933d118</statusUid>
 <subjectUid>d07b5d66-3b5b-de11-b569-001143e78e41</subjectUid>
 <cultureUid>c6644752-93d7-df11-981e-00221933d118</cultureUid>
 <name>test</name>
 <standardUid>dc19869b-3ea9-df11-981e-00221933d118</standardUid>
 <format></format>
</ConnectorConfiguration>

A: ;WITH XMLNAMESPACES( DEFAULT 'http://tempuri.org/xmlConfiguration.xsd')
SELECT
    x.uid,
    x.name,
    x.ClassUid,
    x.xmlData,
    x.batchUid,
    x.statusUid,
    x.subjectUid,
    x.cultureUid,
    x.format,
    x.secondFormat,
    x.standardUid
FROM (
    SELECT *,
        x.value('(/xmlConfiguration/batchUid)[1]', 'NVARCHAR(200)') AS batchUid,
        x.value('(/xmlConfiguration/statusUid)[1]', 'NVARCHAR(200)') AS statusUid,
        x.value('(/xmlConfiguration/subjectUid)[1]', 'NVARCHAR(200)') AS subjectUid,
        x.value('(/xmlConfiguration/cultureUid)[1]', 'NVARCHAR(200)') AS cultureUid,
        x.value('(/xmlConfiguration/format)[1]', 'NVARCHAR(200)') AS format,
        x.value('(/xmlConfiguration/secondFormat)[1]', 'NVARCHAR(200)') AS secondFormat,
        x.value('(/xmlConfiguration/standardUid)[1]', 'NVARCHAR(200)') AS standardUid
    FROM (
        SELECT *, x = CAST(
                CAST(REPLACE(CAST(xmlData AS VARCHAR(MAX)), 'encoding="utf-8"', '') AS XML
            ).query('.') ---- .query('.')
        FROM dbo.TEST
    ) T
) x
JOIN dbo.batch ON x.batchUid = dbo.batch.uid
JOIN dbo.status ON x.statusUid = dbo.status.uid
JOIN dbo.vFormat ON CONVERT(NVARCHAR(200), dbo.vFormat.uid) IN (x.format, x.secondFormat)
JOIN dbo.standard ON x.standardUid = dbo.standard.uid
JOIN mainDb.dbo.Class ON dbo.TEST.ClassUid = mainDb.dbo.Class.uid
JOIN dbo.subject ON x.subjectUid = dbo.subject.uid
JOIN mainDb.dbo.culture ON x.cultureUid = mainDb.dbo.culture.uid


text:
Q: How can black holes have charge and gravitate? I seem to misunderstand the whole concept of calibration bosons.
Let`s imagine a charged black hole. It does not let out anything that travels at any speed less than or equal to the speed of light, right?
So how can we even know the black hole is massive and it has a charge if nothing (which also includes all force-conveying particles) can be faster than light?
Okay, for quantum gravity there is no conclusive theory as of now, and the graviton is yet to be discovered experimentally. But what about the electric charge?


text:
Q: How to refresh a counter on the UI without blocking the rest, in codename one? I try to get a score count on the UI, to be refreshed several times per second. The refresh should not prevent the other elements of the UI from working (Buttons should remain clickable etc.)
I read the doc on the EDT and tried to add a method called from the constructor of the Form:
  private void loopScore() {
        Display.getInstance().callSerially(
                () -> {
                    while (true) {
                        try {
                            MyApplication.score = MyApplication.score + 1;
                            this.gui_Score.setText(String.valueOf(MyApplication.score));
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                            //do something
                        }
                    }
                });
    }

But this does not update gui_Score and it blocks the rest of the UI. Help?

A: A solution is to override the animate method of the Form.
This method is called at each new cycle of the EDT (which is every millisecond or so) to verify if there is a need to repaint anything.
Overriding the method allows to insert a line of code updating the text of the Label where the score is:
@Override
public boolean animate() {
    if (System.currentTimeMillis() / 1000 > lastRenderedTime / 1000) {
        lastRenderedTime = System.currentTimeMillis();
        computeScore();
        this.gui_Score.setText(String.valueOf(MyApplication.score));
        return true;
    }
    return false;

}

private void computeScore() {
    MyApplication.score = MyApplication.score + 3;
}

Then, you need to register this animation with the registerAnimated method. I do it from the constructor of the Form:
public Form1(com.codename1.ui.util.Resources resourceObjectInstance) {
    initGuiBuilderComponents(resourceObjectInstance);
    lastRenderedTime = System.currentTimeMillis();
    registerAnimated(this);
}

Now the Label with the counter refreshes every second, showing an increment of 3. The rest of the UI remains responsive, nothing is blocking.
(solution found by fiddling with the animation of a clock demonstrated on this page)


text:
Q: How to print a nested dictionary member value in docker volume ls --format I want to print the backend volume name of a docker volume using
docker volume ls --format ,
following is the output of docker volume inspect
docker volume inspect 3812bd5a8e286eb9ff9
[
    {
        "CreatedAt": "0001-01-01T00:00:00Z",
        "Driver": "oie",
        "Labels": null,
        "Mountpoint": "",
        "Name": "3812bd5a8e286eb9ff9",
        "Options": null,
        "Scope": "global",
        "Status": {
            "volume_detail": {
                "oie_vol_name": "dcv-TL0SoIuHQvCStS1F-B5i-A",
                "backend": "4000",
                "compression": null,
                "cpg": "cpg1",
                "domain": null,
                "flash_cache": null,
                "fsMode": null,
                "fsOwner": null,
                "mountConflictDelay": 30,
                "provisioning": "thin",
                "size": 20,
                "snap_cpg": "cpg1"
            }
        }
    }
]

I am able to pull up driver name using docker volume ls -f driver=hpe --format "{{.Driver}}"
oie
But when i want to pull field oie_vol_name which is inside "Status": { "volume_detail":  using " docker volume ls -f driver=hpe --format "{{.Status{.volume_detail{.oie_vol_name}}}}""
It shows

Template parsing error: template: :1: unexpected bad character U+007B '{' in command

A: Try this
docker volume inspect -f "{{ .Status.volume_detail.oie_vol_name }} 3812bd5a8e286eb9ff9

Hope this helps.


text:
Q: Simple Audio Play Stop In Android I am Beginer in Android.
I want To create an  app
When Clicking an Image(Play button Image) a MP3 file starts to play and image chnage to another image(Pause Button image) and Map3 Stops
How to create this app?

A: See a simple example to start, stop and pause the audio play.
Drag three buttons from pallete to start, stop and pause the audio play. Now the xml file will look like this:
File: activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="30dp"
        android:text="Audio Controller" />

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="48dp"
        android:text="start" />

    <Button
        android:id="@+id/button2"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/button1"
        android:layout_toRightOf="@+id/button1"
        android:text="pause" />

    <Button
        android:id="@+id/button3"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/button2"
        android:layout_toRightOf="@+id/button2"
        android:text="stop" />

</RelativeLayout>

Activity class
Let's write the code to start, pause and stop the audio player.
File: MainActivity.java
package com.example.audioplay;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    Button start,pause,stop;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        start=(Button)findViewById(R.id.button1);
        pause=(Button)findViewById(R.id.button2);
        stop=(Button)findViewById(R.id.button3);
        //creating media player
        final MediaPlayer mp=new MediaPlayer();
        try{
                //you can change the path, here path is external directory(e.g. sdcard) /Music/maine.mp3
        mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Music/maine.mp3");

        mp.prepare();
        }catch(Exception e){e.printStackTrace();}

        start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.start();
            }
        });
        pause.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.pause();
            }
        });
        stop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.stop();
            }
        });
    }
}


text:
Q: What exactly is a "weight" in machine learning algorithms I'm currently learning about perceptron learning algorithms in python and I came across the term "weight" when reading about Rosenblatt's perceptron rule. Can anyone explain to me exactly what this term means?

A: In terms of perceptron, weight stands for a "strength of the synaptic connection" (in interpretation) and for "parameter that you multiply by signal connected through given connection". It is also a common usecase to call the "connection" itself - a weight.
Thus in case of perceptron, your model is of form
perceptron(x) = sign( SUM_i w_i x_i )
                            ---
                             |
                           weight

Why is it called this way? Because you compute weighted sum of your features x_i, and corresponding w_i are weights of each features.


text:
Q: Having a issue with php statement using loop mysqli Hello Please forgive me if I'm not asking this right. I have the following code.
      <?php

      //Connect to mysql server
    include ("Data.php");
    if (!$con) {
    die ("connection error". mysqli_connect_error());
    }

$sql1 = "SELECT * FROM PMList where AssetNum= '$AssetNum' and Plant= '$Plant';";
    $result = mysqli_query($con, $sql1) or die(mysqli_error($con));

if ($result->num_rows > 0)
$count = 0;
$Task = 1;
while($row = mysqli_fetch_array($result))
{
            $Task++;
            echo "";
            echo "";
            echo $row['Task$Task'];
            echo " 	";
            echo "<input type='radio' name='Task$Task' value='Yes'>Yes";
            echo "  <input type='radio' name='Task$Task' value='No'>No";
            echo "
";
            }
    while ($count++ < 16) {
}
        $con->close();
?>

What I am trying to do is add the $task value to the echo $row['Task$Task']; So that the value turns to task1 then task2 , task3 ect. There can be up to 15 tasks. I'm close just not sure on where I'm messing up. Any help would be great. been stuck on this one for awhile now. Thank you in advance!!

OK now this is what I have its displaying almost correctly.
$sql1 = "SELECT * FROM PMList where AssetNum= '$AssetNum' and Plant= '$Plant';";
    $result = mysqli_query($con, $sql1) or die(mysqli_error($con));

if ($result->num_rows > 0)
$count = 0;
$Task = 1;

while($row = mysqli_fetch_assoc($result))
do
{
            echo "";
            echo "";
            echo $row['Task'.$Task];
            echo " 	";
            echo "<input type='radio' name='Task$Task' value='Yes'>Yes";
            echo "  <input type='radio' name='Task$Task' value='No'>No";
            echo "
";
            $Task++;
            }
    while ($count++ <= 13);
        $con->close();
?>

Now it is looping however, If the task is empty I need to not echo the radio buttons and stop where it ends. capture. Thank you guys your all awesome!! How do I add a if statement thst can see if the $row['Task'.$Task]; is null then stop the loop?

A: You should use " to make string  with variable or use . dot to concatenation , either
    echo $row["Task$Task"];

Or
  echo $row['Task'.$Task];

A: Note(This is just for example and prone to sql injection you should check
how to Use PDO's and Sanitize php input
<?php

//Connect to mysql server
include ("Data.php");
if (!$con) {
die ("connection error". mysqli_connect_error());
}

$sql1 = "SELECT * FROM PMList where AssetNum= '$AssetNum' and Plant= '$Plant';";
    $result = mysqli_query($con, $sql1) or die(mysqli_error($con));

if ($result->num_rows > 0)
$count = 0;
$Task = 1;
$rows = mysqli_fetch_array($result)
foreach($rows as $row )
{
            $Task++;
            echo "";
            echo "";
            echo $row["Task".$row["id"]];
            echo " 	";
            echo "<input type='radio' name='$row["Task".$row["id"]]' value='Yes'>Yes";
            echo "  <input type='radio' name='$row["Task".$row["id"]]' value='No'>No";
            echo "
";
            }
        $con->close();
?>

or
<?php

//Connect to mysql server
include ("Data.php");
if (!$con) {
die ("connection error". mysqli_connect_error());
}

$sql1 = "SELECT * FROM PMList where AssetNum= '$AssetNum' and Plant= '$Plant';";
    $result = mysqli_query($con, $sql1) or die(mysqli_error($con));

if ($result->num_rows > 0)
$count = 0;
$Task = 1;
while($row = mysqli_fetch_assoc($result))
{
            $Task++;
            echo "";
            echo "";
            echo $row["Task".$row["id"]];
            echo " 	";
            echo "<input type='radio' name='$row["Task".$row["id"]]' value='Yes'>Yes";
            echo "  <input type='radio' name='$row["Task".$row["id"]]' value='No'>No";
            echo "
";
            }
        $con->close();
?>


text:
Q: VS15 does not recognize files cloned by git after 1803 update Last night Win10 did an update to version 1803.
Since then Visual Studio (2015) cannot compile any new cloned project anymore.
I clone from a gitlab server via Bash on Windows. Old projects that were already on disk before the update still compile without complaining.
It seems that Visual Studio is not able to locate/find the files anymore, since trying to compile gives error messages like:
c1xx : fatal error c1083: cannot open source file: ...

Does anybody encounter the same problem or has a glue why this could happen?
Edit:
After some digging it boils down to the problem that the CL.exe compiler seems not to be allowed to read any subdirectory created by git. However, it has the right to read in the main git directory.
More Edit:
It turns out to be a problem of the Ubuntu subsystems. Directories created via the WSL cannot be read by some programs (in our case the CL.exe) anymore.
What a pity... before the update WSL and VS worked together like a charme!
Solution so far: Using the git-Bash until MS fixes the problem...

A: I ran into this same issue. Based on the link provided by @Biswapriyo, I was able to understand what is causing this issue.
Windows Subsystem for Linux (WSL) recently added support for case-sensitive files/folders. However, when using the cl.exe (c1xx) compiler, it won't find files in a folder created (or cloned) in the current version of WSL. The reason is that cl.exe makes the file and path uppercase. So if your source file is called main.c in c:\tmp, the compiler looks for C:\TMP\MAIN.C. Thus a case-sensitive file match won't work and the compiler "cannot open source file".
To fix this issue, create the file /etc/wsl.conf in your WSL environment
Add the following text to wsl.conf
[automount]

options=case=off

I have verified that this fixed the issues that I have seen with the updates to WSL. However, it will break WSL handling filenames that only differ in case that are in the same folder.


text:
Q: Why Does Air Hold More Water When the Air is Warmer? I know that when the temperature of the air rises, the maximum amount of Water it can hold before the water condenses to water droplets increases. But why is this - has it got something to do with entropy or thermodynamics?

A: This has everything to do with entropy: when the temperature is higher, the benefit of having more water molecules in the air (giving rise to greater entropy) become energetically more favored. This is why water "dissolves better in air" at higher temperatures.
Another way of looking at this (pure statistical thermodynamics): when water is cold, few molecules have the energy to "escape" the surface tension forces that hold molecules in the liquid - and thus few molecules escape. By contrast any water molecule in the air that hits the water has a good chance of becoming part of the liquid. When the rate of escape is low, the equilibrium concentration is also low.
Contrast this with high temperature water: lots of molecules escape so you can have far more molecules in the vapor phase at equilibrium.
Both approaches give you the same answer... saturated vapor pressure increases with temperature.

A: This phenomenon has nothing to do with the properties of the air, but the properties of the water in it. Hot air means hot water in the air. Cold air means cold water in the air. Cooling water causes it to condense. This is considering a constant volume.


text:
Q: "mongod" works to connect do database but i cant reach the shell because "mongo" doesn't work
I can not access the mongodb shell but I can access the port 27017 after I type mongod in cmd, also mongo doesnt work but mongod does. The path in environment variables is correct which is C:\Program Files\MongoDB\Server\6.0\bin but there is no .exe called mongo only mongod and mongos I want to access to mongodb shell


text:
Q: Go: function pointer to function with receiver Can I set function pointer to function with receiver simpler than creating function around it?
package main

import "fmt"

type hello struct {
  name string
}

func (obj *hello) hello() {
  fmt.Printf("Hello %s\n", obj.name)
}

func ntimes(action func (), n int) {
  for i := 0; i < n; i++ {
    action()
  }
}

func main() {
  obj := hello{"world"}
  // Can I do following simpler?
  ntimes(func() {obj.hello();}, 3)
}

A: Not right now. But with Go 1.1 this will be possible. Go 1.1 Function Calls
Go 1.1 will be ready when the blue line touches zero.


text:
Q: React useEffect is complaining about missing dependency even after destructuring Before you mark this as a duplicate - please understand that I have tried following most of the articles here on SO but none of them seem to help me out, perhaps I am overlooking something or I am having a brain fart today. So please excuse me for asking this question again.
In my component , I have the following code gist.
  let { teamid } = props.currentTeam
  useEffect(() => {
    if (teamid) {
      props.teamMembers(teamid);
    }
  }, [teamid]);

As you can verify from the code above , I am only using teamid in my useEffect. I am not using the entire props object. However, React stil complains with this message
React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect  react-hooks/exhaustive-deps
Please let me know what I am doing wrong here. Any help will be well appreciated.

A: Try to pass currentTeam and teamMembers to useEffect
let { currentTeam, teamMembers } = props

  useEffect(() => {
    if (currentTeam.teamid) {
      teamMembers(currentTeam.teamid);
    }
  }, [currentTeam, teamMembers]);

A: Basically what the react-hooks/exhaustive-deps warning is telling you is that you're still referencing the props object within the effect, which you are - you're not destructuring the props item out fully:
let { teamid } = props.currentTeam
useEffect(() => {
  if (teamid) {
    props.teamMembers(teamid); // PROPS STILL REFERENCED - ISSUE
  }
}, [teamid]); // NO DEPENDENCY FOR PROPS - ISSUE

Destructure the props object fully and include all the dependencies - with this the props object can update, and if the currentTeam or teamMembers properties don't change then your effect doesn't either:
const { currentTeam, teamMembers } = props // FULLY DESTRUCTURED

useEffect(() => {
  if (currentTeam.teamid) {
    teamMembers(currentTeam.teamid)
  }
}, [currentTeam.teamid, teamMembers]) // NO PROPS DEPENDENCIES


text:
Q: Django ORM annotate Query I have a subquery which returns an array. I want to perform certain operations to pick one data out of that array. I am not able to figure out how to do it.
 query_obj = MySecurity.objects.filter(
            valid_data=True
        ).values(
            "id",
            "rate",
        ).annotate(
            rating_val=Subquery(
                MySecurity.object.order_by("-date_of_credit")
                .values("credit_code")
                ),
            )
        )

I want to process my rating_val which will be an array. I tried pass the subquery result to a fun like:
   annotate(
            rating_val=myFun(Subquery(
                MySecurity.object.order_by("-date_of_credit")
                .values("credit_code")
                )),
            )
        )

The above subquery will populate rating_val with ['AA', 'B(CO)'].
I want to process this array and find out the lowest rating based on my hierarchy, which I define in const file (rating_hirarchy=['AA', 'B(CO)', '-BB']). According to rating hirarchy 'AA' is greater than 'B(CO) and B(CO) is greater than '-BB'. So now rating_val should have 'B(CO)' as its value
But I am not able to access subquery value.
I also tried passing later part of subquery to model manager but again I am not able to access subquery response.

A: While using subquery, you need to tell Django how the inner query is related to the outer query, and Django provides OuterRef to help filtering the inner query.
Below example is from Django's doc

newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
Post.objects.annotate(newest_commenter_email=Subquery(newest.values('email')[:1]))

In your code, you did a subquery on self without giving filter conditions, which results in annotating the same value to each row of query. And it's hard to deduce how you really want the subquery related to the outer query.


text:
Q: Using S3 Java SDK to talk to S3 compatible storage (minio) I am trying to use aws-sdk-java AwsS3client to talk to a minio storage. From the CLI I am able to do:
aws --profile=minioplay  --endpoint-url https://play.minio.io:9000 s3 cp logback.xml s3://miniohstest-jixusroqeb --debug

thus using a non default profile and a custom endpoint.
Not sure how to do this (would I be able to ?) from the java sdk.
I roughly translated the above awscli command to this scala snippet :
val cred = ...
val endpoint = "https://play.minio.io:9000"
val client = AmazonS3ClientBuilder
      .standard()
      .withCredentials(cred)
      .withEndpointConfiguration(
        new EndpointConfiguration(
          endpoint,
          AwsHostNameUtils.parseRegion(endpoint, AmazonS3Client.S3_SERVICE_NAME)
        )
      )
      .build()

Using the above client I am only able to make very simple requests such as :
client.listBuckets().asScala.foreach(println(_))

which works. But when I try to do something advanced such as :
val listRequest = new ListObjectsRequest()
      .withBucketName("miniohstest-jixusroqeb")
      //.withPrefix(r.getURI.getPath)
      //.withDelimiter(delimiter)

val res = client.listObjects(listRequest)
res.getObjectSummaries.forEach(x => println(x.getKey))

it throws the following exception :
Exception in thread "main" com.amazonaws.SdkClientException: Unable to execute HTTP request: miniohstest-jixusroqeb.play.minio.io
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleRetryableException(AmazonHttpClient.java:1114)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1064)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:743)

What am I doing wrong?

A: I resolved this by setting withPathStyleAccessEnabled(true).


text:
Q: Curvature calculation for a non-smooth curve How to calculate curvature for a non-smooth curve e.g., at the vertex of a triangle or at the vertex of a cone. I would really appreciate it if you can suggest me some reading.

A: It's impossible. There is no curvature there. It's like asking for a derivative at a point of discontinuity.
But if you force me to say something, I think the most sensible alternative is a Dirac $\delta$.
Curvatures are often there to be integrated. Here are two examples:
You integrate the curvature of a curve over the entire coffee, you find how much its direction has changed from start to finish. The points you're after are instantaneous changes of direction. So if you let the curvature at those points be Dirac $\delta$s, appropriately scaled, then you preserve this property.
You integrate the curvature of a closed surface over the entire surface, and you get (up to a factor) its Euler characteristic. If you give points like the vertices of cubes or cones a Dirac $\delta$ curvature, appropriately scaled, then this still works.


text:
Q: Importing SQL Server 2008 stored procedure into Excel 2016 I get an error I am importing a stored procedure from SQL Server 2008 into Excel 2016, and get an error when I execute it in Excel:

Error converting data type nvarchar to date

This is the stored procedure [LA_VOTER].[Temp].[dmv_import]:
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:           Arash B
-- Create date: 6/5/2018
-- Description:      test for creating dynamic 'Data Entry Signature Verification' worksheeet
-- =============================================
ALTER PROCEDURE [Temp].[dmv_import]
    @date DATE = NULL
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @date_work DATE

    IF @date IS NULL
       SET @date_work = GETDATE()
    ELSE
       SET @date_work = @date

    /*count of processed*/
    SELECT
        vi.import_code as 'DMV Category',
        SUM(CASE WHEN CONVERT(date, vi.createdate, 101) = @date_work THEN 1 ELSE 0 END) AS 'received',
        SUM(CASE WHEN CONVERT(date, vi.processed_date, 101) = @date_work THEN 1 ELSE 0 END) AS 'processed'
    FROM
        DIMSNet.dbo.voter_import vi
    WHERE
        vi.import_type IN ('DMV')
        AND import_code < 13
    GROUP BY
        import_code
END

I access it in Excel through  Data – From Other Sources shown below.
I select from SQL and enter "slavote-dr1" for server to connect to; "DIMSNet" the selected table and any random table as instructions indicated.
Once I reach the "Import Data" pop-up window I select the Cell in the excel worksheet I want to drop the table onto and click on the "properties" button.
Chose the "Definition" tab and changed command type to "SQL".
Entered the executable in the "Command Text box". Since the database use to connect I inserted the full path for the stored procedure on the command line.
Execute "LA_VOTER"."Temp"."dmv_import" ","

I click "OK" and return to the "Import Data" window.  I click "Ok" to import the table.
I get the error stated above.
I looked at the script and could not see where this error was coming from. Is there anything that you can suggest?
PS. Added 6/12/18  ----- The SP runs fine in SQL.  It is only when importing into Excel that the issue occurs.

A: The failure is undoubtedly in the stored procedure.  It is almost certainly in these lines:
sum(case when convert(date, vi.createdate, 101) = @date_work then 1 else 0 end) as received,
sum(case when convert(date, vi.processed_date, 101) = @date_work then 1 else 0 end) as processed

I would suggest that you find the problems in the data and fix them.  You can possibly fix the problem by doing:
sum(case when isdate(vi.createdate) = 0 then 0
         when convert(date, vi.createdate, 101) = @date_work then 1
         else 0
    end) as received,
sum(case when isdate(vi.processed_date) = 0 then 0
         when convert(date, vi.processed_date, 101) = @date_work
         then 1
         else 0
    end) as processed

A: OK used a different method and got it working.
Used the "From Microsoft Query" and my Execute script was:
{CALL LA_VOTE.tmp.dmv_import(?)} and it imported the data I needed into the fields I wanted.
http://codebyjoshua.blogspot.com/2012/01/get-data-from-sql-server-stored.html


text:
Q: Dc Replication issue when on one of the Dc moved to another location We have one Domain controller in Dallas office and other 2 in Chicago.
An administrator in Chicago moved 1 domain controller to Salt lake, now the problem starts here Chicago location and salt lake can communicate with each other, But the domain controller in Dallas cannot communicate with salt lake but it can communicate with Chicago Domain controller. Can it be resolved via Ad sites and services.?

A: It will be necessary to set up a new site for Salt Lake in AD Sites and Services, which you have probably already done. You'll then need to create and assign a subnet to the site and make sure that connectors are set up in AD Sites and Services to replicate between all DCs. With that simple setup you'll be fine with connectors from all DCs to each other.
Once that's done ensure that the DNS settings (in the adapter settings) of each DC still valid addresses, and that none of them are using the now dead IP address in Chicago as a DNS server, and in the DNS server settings on each host make sure all the records that had the old IP are updated to the new IP. That should be enough to get it working. You may find you have to wait a while for it to come good, or you can try forcing replication.
This article also has the steps that should have been taken to move the DC, as a reference: https://technet.microsoft.com/en-us/library/cc794722%28v=ws.10%29.aspx
Another method if it's an option (sounds like it's not) is to demote the Salt Lake domain controller, wait for AD to replicate between Chicago and Dallas, confirm that the DC is gone from AD, and then promote the Salt Lake server to a DC again.


text:
Q: Macbook Pro suddenly lagging video playback + Flash sites I have a Macbook Pro, OSx Lion, Intel Core2 Duo, 4GB Ram, NVidia Geforce 8600M GT 128 MB Ram, Intel x25m SSD. Approximately 4 years old.
I've been running Flash sites and playing videos without any problems for years. Then suddenly 3 months ago, a flash site like http://thefwa.com is lagging in all browsers. Even mouseover animations - anything.
Also video playback in e.g VLC and Quicktime is now lagging. Same videos I used before, I tried installing an older version of VLC without any luck.
Playing back video in VLC utilizes the CPU almost 100%, and Flash sites like thefwa.com easily takes up 50-60%.
It's as if the hardware acceleration stopped working, or the GPU lost its magic.
UPDATE: Same issues also occurred on Snow Leopard
Has anyone experienced something similar, or do you know what might be wrong?

A: I suspect the SSD. The non-G2 models on x25m didn't have very good TRIM support. Try this bootable ISO to diagnose: http://downloadcenter.intel.com/Detail_Desc.aspx?agr=Y&DwnldID=18363


text:
Q: IE's visual filters not displaying within the WebBrowser control all. Is there anyway to get IE's visual filters to render when using the WebBrowser control? Thanks!

A: I thought the WebBrowser control was based on IE4 or 5.  It wouldn't know how to handle filters.


text:
Q: Tikz mix of undirected and directed edges I want to have a graph with mixed of undirected and directed edges. I am using the following code.
\begin{tikzpicture}[main_node/.style={shape          = rectangle,
                                         rounded corners,
                                         draw,                    %% here
                                         double=red,              %% here
                                         double distance =1pt,    %% here
                                         fill           = black!30!white,
                                         minimum width  = 0.1cm,
                                         minimum height = 0.1cm,
                                         align          = center,
                                         text           = black}
                                         ]

    \node[main_node] (affect) at (0,0) {affect};
    \node[main_node] (alert) at (-1, -1.5)  {alert};
    \node[main_node] (track) at (1, -1.5) {track};
    \node[main_node] (advice) at (3, -1) {advice};
    \node[main_node] (pain ) at (5, -1) {pain};
    \draw (affect) -- (alert) -- (track) -- (affect);  (advice) to (pain);

\end{tikzpicture}

But it doesn't draw the edge from advice to pain.

A: Found two small syntax errors.  Do not include spaces in node name descriptors.  Second, a semicolon terminates the draw command so an additional draw commmand was needed.  Revised Code below.
\documentclass[10pt,letterpaper]{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[main_node/.style={shape          = rectangle,
                                         rounded corners,
                                         draw,                    %% here
                                         double=red,              %% here
                                         double distance =1pt,    %% here
                                         fill           = black!30!white,
                                         minimum width  = 0.1cm,
                                         minimum height = 0.1cm,
                                         align          = center,
                                         text           = black}
                                         ]

    \node[main_node] (affect) at (0,0) {affect};
    \node[main_node] (alert) at (-1, -1.5)  {alert};
    \node[main_node] (track) at (1, -1.5) {track};
    \node[main_node] (advice) at (3, -1) {advice};
    \node[main_node] (pain) at (5, -1) {pain};  % REMOVED SPACE FROM NODE NAME
    \draw (affect) -- (alert) -- (track) -- (affect);
    \draw (advice) to (pain);  % A semicolon ends the command so a second was needed

\end{tikzpicture}
\end{document}

EDIT #1
Revised Code with addition of a directed arrow edge and loading the correct library.
\documentclass[10pt,letterpaper]{article}
\usepackage{tikz}
\usetikzlibrary{arrows}
\usetikzlibrary{decorations.pathreplacing}
\usepackage{environ}
\usepackage{tikz-cd}
\begin{document}
\begin{tikzpicture}[main_node/.style={shape          = rectangle,
                                         rounded corners,
                                         draw,                    %% here
                                         double=red,              %% here
                                         double distance =1pt,    %% here
                                         fill           = black!30!white,
                                         minimum width  = 0.1cm,
                                         minimum height = 0.1cm,
                                         align          = center,
                                         text           = black}
                                         ]
\tikzset{edge/.style = {->,> = latex'}}

    \node[main_node] (affect) at (0,0) {affect};
    \node[main_node] (alert) at (-1, -1.5)  {alert};
    \node[main_node] (track) at (1, -1.5) {track};
    \node[main_node] (advice) at (3, -1) {advice};
    \node[main_node] (pain) at (5, -1) {pain};
    \draw (affect) -- (alert) -- (track) -- (affect);
    \draw[edge] (advice) to (pain);

\end{tikzpicture}

\end{document}


text:
Q: How can I connect a pod which runs a python program with another pod which runs a database I have created a simple program written in Python which interacts with a redis database take a list of elements which is stored in my db and sort them.
PYTHON CODE :
import redis
import numpy as np

r = redis.Redis(host='redis-master', port=6379, db=9, socket_connect_timeout=2, socket_timeout=2)

array = np.array([]);

vector = np.vectorize(int);

while(r.llen('Numbers')!=0):
    array = vector(np.append(array, r.lpop('Numbers').decode('utf8')))

sorted_array = np.sort(array);

print("The sorted array : ");
print(sorted_array);

I have created an image with the following Docker file :
FROM python:3
WORKDIR /sorting
COPY sorting.py ./
RUN apt-get update
RUN pip3 install numpy
RUN pip3 install redis
CMD python3 sorting.py

Also for the redis deployment and service I have the following yaml file :
apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis-master
  labels:
    app: redis
spec:
  selector:
    matchLabels:
      app: redis
      role: master
      tier: backend
  replicas: 1
  template:
    metadata:
      labels:
        app: redis
        role: master
        tier: backend
    spec:
      containers:
      - name: master
        image: redis
        ports:
        - name: "redis-server"
          containerPort: 6379

---
apiVersion: v1
kind: Service
metadata:
  name: redis-master
  labels:
    app: redis
    role: master
    tier: backend
spec:
  ports:
  - port: 6379
    targetPort: 6379
  selector:
    app: redis
    role: master
    tier: backend

and for the python programm deployment and service I have the following:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: sortingapp
  labels:
    app: sortingapp
spec:
  selector:
    matchLabels:
      app: sortingapp
  replicas: 1
  template:
    metadata:
      labels:
        app: sortingapp
    spec:
      containers:
      - name: sortingapp
        image: sorting-app:latest
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 8080

---
apiVersion: v1
kind: Service
metadata:
  name: sorting-app
spec:
  type: NodePort
  ports:
  - name: http
    port: 9090
    targetPort: 8080
  selector:
    app: go-redis-app

My redis pod seems to work properly, but when I try to run my sortingapp it creates the pod but the status is CrashLoopBackOff. I tried to show the logs and it shows the prints of my python program
The sorted array :
[]

So as I understand something is wrong with the connection between the app pod and the redis pod.
Any suggestion about what I am doing wrong?

A: You are doing it the right way, I tested your code locally and when you pass a wrong database host name to your python script, it fails, so since you have the output The sorted array : [] That means that the connection to the database has been made properly.
However, you have to know that by deploying this kind of one-executing script in Kubernetes (or docker), the container will restart again and again since it only runs one time and stops.
So if you don't want this error to come out, just make your script an app that runs continuously OR use kubernetes job, for example, if you want to run it manually when needed.
Another thing: Since redis is a stateful application, consider using a StatefulSet object in Kubernetes instead of a Deployment. But since its not related to the problem, you can do it whenever you want.
A little advice: you should pass the host configuration of your redis database in your python code in the environment variable, it will be better if one day you need to execute the container elsewhere you would just modify the environment variable instead of rebuilding your docker image.
A big problem for the future: look at your Python Kubernetes service, it contains the selector: app: go-redis-app instead of app: sorting-app
Basically it's a python problem, not a Kubernetes database connection problem, so good job.


text:
Q: issue with creating method in js <script>
var mango =  new Object ();
mango.color = "yellow";
mango.shape= "round";
mango.sweetness = 8;
Object.prototype.howSweetAmI = function () {
console.log("Hmm Hmm Good");
}
console.log(mango);
</script>

Question:
I can change this line:  Object.prototype.howSweetAmI to mango.howSweetAmI, and both of them can work. But what is the difference between them? usually we use which way to create method?

A: Usually you would not add anything to Object.prototype, because then it would be added to everything. It would be usable for example with "".howSweetAmI(), and that wouldn't make much sense.
Normally you have a specific type where you add methods to the prototype, for example:
function Fruit(color, shape, sweetness) {
  this.color = color;
  this.shape = shape;
  this.sweetness = sweetness;
}

Fruit.prototype.howSweetAmI = function() {
  return this.sweetness;
};

var mango = new Fruit("yellow", "round", 8);

Adding the method to the prototype means that all instances uses the same method. If you add a method as a property to the instance, only that instance has the method, and different instances can have different implementations of the method. For example:
var mango = new Fruit("yellow", "round", 8);
var banana = new Fruit("yellow", "bent", 70);

mango.howSweetAmI = function() { return this.sweetness; };
banana.howSweetAmI = function() { return this.sweetness * 0.1; };

A: Adding a function to the Object prototype will make that function available on every javascript object. (console.log(window.howSweetAmI)). Moving it to mango will make it a property of that single object.


text:
Q: System error dialog box keeps popping up Randomly when I am using my computer a dialog pops up saying "Ubuntu 12.04 has found an error in your system. Would you like to report it?" and also often times my applications just randomly close. I am not sure if they are corolated. I just got ubuntu on this computer yesterday so I don't think that I could have screwed up yet. When I click on more details it says that it has to do with some gnome-control-center thing. Also my computer is not letting me download any packages. It just says that it has failed whether I do it with sudo apt-get or with Ubuntu software center.
Thanks in Advance,
Eli

A: open terminal CTRL +ALT + T
then write
nano /var/log/syslog
(location of your systems error logs)
Find the time stamp, when these errors occur and paste it here.


text:
Q: HTML/JavaScript Countdown Timer I have a countdown timer that currently allows the user to input a time and start the countdown from there.
I would like to have the text change colour after a certain amount of time, for example:
Text to go orange at 50%, then text to red when only 25% of the input time is left.
I'm pretty out of my depth already so would be very grateful for some detailed advice, thanks!
Here is my current code:

var secondsRemaining;
var intervalHandle;

function resetPage() {
  document.getElementById('inputArea').style.display = 'block';
}

function tick() {
  //grab h1
  var timeDisplay = document.getElementById('time');

  //turn seconds into mm:55
  var min = Math.floor(secondsRemaining / 60);
  var sec = secondsRemaining - (min * 60);

  //add leading 0 if seconds less than 10
  if (sec < 10) {
    sec = '0' + sec;
  }
  //concatenate with colon
  var message = min.toString() + ':' + sec;
  // now change the display
  timeDisplay.innerHTML = message;

  //stop if down to zero
  if (secondsRemaining === 0) {
    alert('Countdown Finished!');
    clearInterval(intervalHandle);
    resetPage();
  }
  // subtract from seconds remaining
  secondsRemaining--;
}

function startCountdown() {
  //get contents
  var minutes = document.getElementById('minutes').value;
  //check if not a number
  if (isNaN(minutes)) {
    alert("Please enter a number!");
    return;
  }
  //how many seconds?
  secondsRemaining = minutes * 60;
  //call tick
  intervalHandle = setInterval(tick, 1000);
  //hide form
  document.getElementById('inputArea').style.display = 'none';
}

window.onload = function() {

  // create text input
  var inputMinutes = document.createElement('input');
  inputMinutes.setAttribute('id', 'minutes');
  inputMinutes.setAttribute('type', 'text');
  inputMinutes.setAttribute('placeholder', 'Enter Time');
  //create button
  var startButton = document.createElement('input');
  startButton.setAttribute('type', 'button');
  startButton.setAttribute('value', 'Start Countdown');
  startButton.onclick = function() {
    startCountdown();
  };
  // add to DOM
  document.getElementById('inputArea').appendChild(inputMinutes);
  document.getElementById('inputArea').appendChild(startButton);
}
html,
body {
  font-family: helvetica;
  color: #222;
  background: #eaeaea;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#container {
  width: 400px;
  margin: auto;
}

h1 {
  font-size: 30em;
  text-align: center;
  margin: 40px 0;
  padding: 0;
  border-right: none;
  border-left: none;
}

input {
  display: block;
  width: 80%;
  border: 5px solid #E6E6E6;
  background: #fff;
  height: 50px;
  margin-bottom: 5px;
  margin-top: 10px;
  margin-left: auto;
  margin-right: auto;
  font-size: 19px;
  text-align: center;
  border-radius: 5px;
}

input[type=button] {
  line-height: 30px;
  font-size: 19px;
  border: 2px solid #E6E6E6;
  background: #f5b932;
  color: #333;
  font-weight: bold;
  margin-top: 5px;
  transition: .4s ease-in-out;
}

input[type=text]:focus {
  outline: none;
}

input[type=button]:focus {
  outline: none;
}

input[type=button]:hover {
  background: #f5b934;
  cursor: pointer;
}

.center-count {
  position: absolute;
  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  height: 20vw;
}

0:00

A: Try this:
    function tick() {
  //grab h1
  var timeDisplay = document.getElementById('time');

  //Convert remaining seconds to presentage of total seconds
  precentageS = Math.floor(secondsRemaining/totalSeconds)*100

  //Change color based on persentage
  if(precentageS <= 50){
          document.getElementById("time").style.color = "orange";
  }else if(precentageS <= 25){
          document.getElementById("time").style.color = "red";
  }else{
          document.getElementById("time").style.color = "blue";
  }

  //turn seconds into mm:55
  var min = Math.floor(secondsRemaining / 60);
  var sec = secondsRemaining - (min * 60);

  //add leading 0 if seconds less than 10
  if (sec < 10) {
    sec = '0' + sec;
  }
  //concatenate with colon
  var message = min.toString() + ':' + sec;
  // now change the display
  timeDisplay.innerHTML = message;

  //stop if down to zero
  if (secondsRemaining === 0) {
    alert('Countdown Finished!');
    clearInterval(intervalHandle);
    resetPage();
  }
  // subtract from seconds remaining
  secondsRemaining--;
}

function startCountdown() {
  //get contents
  var minutes = document.getElementById('minutes').value;
  //check if not a number
  if (isNaN(minutes)) {
    alert("Please enter a number!");
    return;
  }
  //how many seconds?
  secondsRemaining = minutes * 60;
  totalSeconds = secondsRemaining;
  //call tick
  intervalHandle = setInterval(tick, 1000);
  //hide form
  document.getElementById('inputArea').style.display = 'none';
}

What I've done is added a totalSeconds variable after the secondsRemaining so I can keep track of how many seconds we started with. I then convert the secondsRemaining into a percentage of the totalSeconds And have if statements depending on the number of times you would like to change color.

A: Try something like this:

*

*Extracted minutes to be able to calculate percentage on the run.

*Added two condition to change color...

var secondsRemaining;
var intervalHandle;

// Total time
var minutes;

function resetPage() {
  document.getElementById('inputArea').style.display = 'block';
}

function tick() {
  //grab h1
  var timeDisplay = document.getElementById('time');

  //turn seconds into mm:55
  var min = Math.floor(secondsRemaining / 60);
  var sec = secondsRemaining - (min * 60);

  //add leading 0 if seconds less than 10
  if (sec < 10) {
    sec = '0' + sec;
  }
  //concatenate with colon
  var message = min.toString() + ':' + sec;
  // now change the display
  timeDisplay.innerHTML = message;

  // Change color by percentage
  // Below 25% = 60 / 4 : red
  if (secondsRemaining < minutes * 15) {
    timeDisplay.style.color = "red";
  }
  // Below 50% = 60 / 2 : orange
  else if (secondsRemaining < minutes * 30) {
    timeDisplay.style.color = "orange";
  }

  //stop if down to zero
  if (secondsRemaining === 0) {
    alert('Countdown Finished!');
    clearInterval(intervalHandle);
    resetPage();
  }
  // subtract from seconds remaining
  secondsRemaining--;
}

function startCountdown() {
  //get contents
  minutes = document.getElementById('minutes').value;
  //check if not a number
  if (isNaN(minutes)) {
    alert("Please enter a number!");
    return;
  }
  //how many seconds?
  secondsRemaining = minutes * 60;
  //call tick
  intervalHandle = setInterval(tick, 1000);
  //hide form
  document.getElementById('inputArea').style.display = 'none';
}

window.onload = function() {

  // create text input
  var inputMinutes = document.createElement('input');
  inputMinutes.setAttribute('id', 'minutes');
  inputMinutes.setAttribute('type', 'text');
  inputMinutes.setAttribute('placeholder', 'Enter Time');
  //create button
  var startButton = document.createElement('input');
  startButton.setAttribute('type', 'button');
  startButton.setAttribute('value', 'Start Countdown');
  startButton.onclick = function() {
    startCountdown();
  };
  // add to DOM
  document.getElementById('inputArea').appendChild(inputMinutes);
  document.getElementById('inputArea').appendChild(startButton);
}
html,
body {
  font-family: helvetica;
  color: #222;
  background: #eaeaea;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#container {
  width: 400px;
  margin: auto;
}

h1 {
  font-size: 30em;
  text-align: center;
  margin: 40px 0;
  padding: 0;
  border-right: none;
  border-left: none;
}

input {
  display: block;
  width: 80%;
  border: 5px solid #E6E6E6;
  background: #fff;
  height: 50px;
  margin-bottom: 5px;
  margin-top: 10px;
  margin-left: auto;
  margin-right: auto;
  font-size: 19px;
  text-align: center;
  border-radius: 5px;
}

input[type=button] {
  line-height: 30px;
  font-size: 19px;
  border: 2px solid #E6E6E6;
  background: #f5b932;
  color: #333;
  font-weight: bold;
  margin-top: 5px;
  transition: .4s ease-in-out;
}

input[type=text]:focus {
  outline: none;
}

input[type=button]:focus {
  outline: none;
}

input[type=button]:hover {
  background: #f5b934;
  cursor: pointer;
}

.center-count {
  position: absolute;
  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  height: 20vw;
}

0:00

A: I would go with a percentage approach, here's your code with that verification.
Set a new variable for initialTime asked.
var initialTime;

var secondsRemaining;
var intervalHandle;

function resetPage() {
  document.getElementById('inputArea').style.display = 'block';
}

function tick() {
  //grab h1
  var timeDisplay = document.getElementById('time');

  //turn seconds into mm:55
  var min = Math.floor(secondsRemaining / 60);
  var sec = secondsRemaining - (min * 60);

  //add leading 0 if seconds less than 10
  if (sec < 10) {
    sec = '0' + sec;
  }
  //concatenate with colon
  var message = min.toString() + ':' + sec;
  // now change the display
  timeDisplay.innerHTML = message;

Then on each tick, check what's the actual percentage left on the counter.
    var remainingPercentage = secondsRemaining*100/initialTime;

    if (remainingPercentage === 75) {
    timeDisplay.style.color = "orange";
    }

    if (remainingPercentage === 50) {
    timeDisplay.style.color = "yellow";
    }

    if (remainingPercentage === 25) {
    timeDisplay.style.color = "red";
    }

  //stop if down to zero
  if (secondsRemaining === 0) {
    alert('Countdown Finished!');
    clearInterval(intervalHandle);
    resetPage();
  }
  // subtract from seconds remaining
  secondsRemaining--;
}

function startCountdown() {
  //get contents
  var minutes = document.getElementById('minutes').value;
  //check if not a number
  if (isNaN(minutes)) {
    alert("Please enter a number!");
    return;
  }
  //how many seconds?

When first setting secondsRemaining, store it in initialTime too.
  secondsRemaining = initialTime = minutes * 60;

  //call tick
  intervalHandle = setInterval(tick, 1000);
  //hide form
  document.getElementById('inputArea').style.display = 'none';
}

window.onload = function() {

  // create text input
  var inputMinutes = document.createElement('input');
  inputMinutes.setAttribute('id', 'minutes');
  inputMinutes.setAttribute('type', 'text');
  inputMinutes.setAttribute('placeholder', 'Enter Time');
  //create button
  var startButton = document.createElement('input');
  startButton.setAttribute('type', 'button');
  startButton.setAttribute('value', 'Start Countdown');
  startButton.onclick = function() {
    startCountdown();
  };
  // add to DOM
  document.getElementById('inputArea').appendChild(inputMinutes);
  document.getElementById('inputArea').appendChild(startButton);
}


text:
Q: Bug in vote count, since status update Hi,
I was pleased to see the new votes cast item on the user status hover over thingy...  However, I think it might have broken the restriction on the number of votes that can be cast in a day.  I appear to have voted 31 times today on stackoverflow(see picture)...
There was also no warning when I was approaching the 30 limit if that's relevant...

EDIT: After reading the link from mmyers, I still think there's a bug...
I've voted (according to the view), 31 times.  If I try to vote on an answer, I do indeed get told I can't vote.  However, it's saying:

Come back to vote in on more answers in 2 hours, or use your remaining 8 question votes now.

From the link, the number of question votes should be 10, so a combined total would be 40, not 31+8 (39), or am I missing something?
As an aside, it would be nice to get some kind of warning if I use my last 'general purpose vote', even if it is on a question.
EDIT2:
Yesterday, I have a different, but related issue.  I cast 28 votes (a lot of them were probably on questions), however I couldn't cast one of my final 30 votes on an answer.  I went round the pages a couple of times to make sure it wasn't because I was on the same page...
From Profile Page:

From Status View

Error when casting vote:

A: Since I totally revamped the way this works, I am closing this as status-completed see:
Please don't require answer votes to be cast before question votes


text:
Q: Twilio 5x C# Libraries - Gather digits while message is being read The new Twilio 5x libraries have introduced a bit of an odd approach to gathering DTMF digits on phonecalls.
The old 4x code for a gather would have looked something like:
twiml.BeginGathertwiml.BeginGather(new { numDigits = "1", action = "/TwilioCallbacks/InputResponse" });
if(x == 10){
    twiml.Say("I am saying a thing because x = 10");
}
else{
    twiml.Say("I am saying the other thing");
}
twiml.EndGather();

Now, if you wanted to let the user punch digits on the keypad while your bot was talking to them, that'd work just fine.
However in Twilio 5x, it looks like this:
twiml.Say("I am saying a really long thing where the user must wait until the twiml script reaches the gather phrase");
twiml.Say("press 1 if stack overflow is awesome, press 2 to quit programming forever");
twiml.Gather(
            numDigits: 1,
            input: new List<InputEnum>() { InputEnum.Dtmf },
            timeout: 10,
            method: "POST",
            action: new System.Uri(Startup.hostAddress + "/TwilioCallbacks/InputResponse")
        );

Right after Gather(...) you have a short window to collect the response, if you set a timeout on the response, the twiml won't proceed to the next say until the timeout expires.
How can I Gather digits in such a way that the user can interact with the keypad at any point during the message? The new approach seems to be a step backward.
edit:
Clarified the 4xx use case, such that folks can understand why chaining .Say won't work here.
edit:
Some people below are suggesting chaining the .Say() verb right after .Gather().
This actually doesn't behave as expected either. This is the C# code.
    twiml.Gather(
        numDigits: 1,
        input: new List<InputEnum>() { InputEnum.Dtmf },
        timeout: 10,
        method: "POST",
        action: new System.Uri(Startup.hostAddress + "/TwilioCallBot/InputResponse")
    ).Say("this is a test");

This is the resulting twiml:
<Gather input="dtmf" action="https://callbot21.ngrok.io/RCHHRATool//TwilioCallBot/InputResponse" method="POST" timeout="10" numDigits="1">
</Gather>
<Say>this is a test</Say>

The say verb needs to be inside the gather tag to get the behavior we're looking for.

A: Okay I've found the issue. It looks like fourwhey was correct to point at the API docs there. What I didn't catch was that the .Say was being appended to the gather in a specific way.
This:
twiml.Gather(...).Say("say a thing");

doesn't work the same as this:
var gather = new Twilio.TwiML.Voice.Gather(...).Say("say a thing");

best I can work out is that there's actually two gather methods, and that twiml.Gather(...) is actually calling Twilio.TwiML.Gather.
From here we can build our dynamic voice message and nest the Say verb like so:
gather.Say("Say a thing");
gather.Say("Say another thing");

And the twiml will get spit out the way we intended like so:
<gather>
    <say>say a thing</say>
    <say>say another thing</say>
</gather>


text:
Q: Join zero-terminated string with ; I have output from $(realpath -z foo bar), which I need to join with a ; into a string to pass it to CMake.
How could I do this using no Bash specific methods?

A: I don't know what you mean by no Bash specific methods. In most shells you can do:
$ realpath -z foo bar | tr '\0' ';' | sed 's,;$,,'.

Add && echo at the end if you want a newline.


text:
Q: How to have radio buttons using vb script? I was looking to set time on my computer. For that I'm scripting 3 radio buttons of three different countries so that user can set the time zone by selecting one of the radio buttons.
Also please help in below error:
Set objExecObject = objShell.Exec("tzutil.exe /s """ & TimeZoneFriendlyName & "")
WScript.Echo "Setting the time zone sucessfully."

Error message

A:
Search where

<INPUT Name=tb2 TYPE=RADIO CHECKED AccessKey=w> Google <INPUT Name=tb2 TYPE=RADIO> Wikipedia <INPUT Name=tb2 TYPE=RADIO> Nethack <INPUT Name=tb2 TYPE=RADIO> MSDN <INPUT Name=tb2 TYPE=RADIO> Australia <INPUT Name=tb2 TYPE=RADIO> Maps

And
Sub Search
'   On Error Resume Next
    Set WshShell = CreateObject("WScript.Shell")
    If tb2(5).Checked=True then WshShell.Run "https://www.google.com/maps/place/" & Replace(tb1.value, " ", "+")
    If tb2(4).Checked=True then WshShell.Run "https://www.google.com/search?q=" & Replace(tb1.value, " ", "+") & "&cr=countryAU"
    If tb2(3).Checked=True then WshShell.Run "https://www.google.com/search?q=site:msdn.com+" & Replace(tb1.value, " ", "+")
    If tb2(2).Checked=True then WshShell.Run "https://www.google.com/search?q=nethack+" & Replace(tb1.value, " ", "+")
    If tb2(1).Checked=True then WshShell.Run "https://en.wikipedia.org/wiki/" & tb1.value
    If tb2(0).Checked=True then WshShell.Run "https://www.google.com/search?q=" & Replace(tb1.value, " ", "+")
    WshShell.RegWrite "HKCU\Software\StackOverflow\VBS\Searchterm", tb1.value & vbtab & WshShell.RegRead("HKCU\Software\StackOverflow\VBS\Searchterm")
    If tb3.checked=true then window.close
End Sub

You also have got your quotes wrong. Cmd /k will allow you to see what happens in CMD, remove it once it works.
 WScript.CreateObject("WScript.Shell").Run "cmd /k tzutil.exe /s """ & TimeZoneFriendlyName & """"

Here's an HTA showing radio buttons, check boxes, buttons, and shows how to implement keyboard access.

<TITLE>Search</TITLE>
  <HTA:APPLICATION ID="oMyApp"
    APPLICATIONNAME="Search"
    BORDER="normal"
    BORDERSTYLE="sunken"
    CONTEXTMENU="yes"
    CAPTION="yes"
    ICON="C:\windows\system32\shell32,-5"
    SCROLL="no"
    SHOWINTASKBAR="yes"
    SINGLEINSTANCE="yes"
    SYSMENU="yes"
    WINDOWSTATE="normal"
  />

Enter search term

<INPUT Name=tb1 TYPE=Text size=60 AccessKey=s> <INPUT Type=Button onclick=paste Value=Paste AccessKey=p>

History

<SELECT NAME="HistoryList" SIZE="4" Onclick=LBTransfer OnKeyPress=LBTransferK AccessKey=h>
</SELECT>

Search where

<INPUT Name=tb2 TYPE=RADIO CHECKED AccessKey=w> Google <INPUT Name=tb2 TYPE=RADIO> Wikipedia <INPUT Name=tb2 TYPE=RADIO> Nethack <INPUT Name=tb2 TYPE=RADIO> MSDN <INPUT Name=tb2 TYPE=RADIO> Australia <INPUT Name=tb2 TYPE=RADIO> Maps

<INPUT NAME="Search" TYPE="SUBMIT" VALUE="Search" OnClick=Search> <INPUT Name=tb3 TYPE=CHECKBOX CHECKED AccessKey=c> Close on search

A: You cannot create a radio button with VBscript. You will need to use an HTA or a different wrapper.
The error seems to be a problem of you not setting the shell object
So to use
Set objExecObject = objShell.Exec("tzutil.exe /s """ & TimeZoneFriendlyName & "")
WScript.Echo "Setting the time zone sucessfully."

You first have to have a
Set objShell = CreateObject("Wscript.Shell")

before that


text:
Q: What exactly does this sentence mean: " ... typically 10-100 times that of a plain-vanilla email campaign"
"That extra effort is what gives traditional media its added oomph—typically 10-100 times that of a plain-vanilla email campaign"

This sentence is used in below paragraph:

They work because, to your prospect, it's a given that you've put in more effort. (A printed sales pack costs you more to put together; a telephone call takes 100% of one person's attention for its duration.) That extra effort is what gives traditional media its added oomph—typically 10-100 times that of a plain-vanilla email campaign.

I think that it means: extra effort can make the media more appealing. But the next part of the sentence is ambiguous  for me:

*

*typically 10-100 times that of a plain-vanilla email campaign

A: It means
traditional media campaigns usually have 10-100 times more oomph than ordinary email campaigns.

A: A traditional media [campaign] (in long-established forms such as radio, television, and newspapers)
has more oomph (strength, power, [sex] appeal)
than a plain-vanilla email campaign (standard, basic, without any added features)
It's a pretty vacuous thing to say, since it's almost impossible to measure/quantify the efficacy of an advertising campaign, and totally impossible to quantify the "oomph/power/appeal" of a campaign except by using "increased sales" as a proxy.
I assume the writer means that if you run, say, a newspaper ad campaign, your sales increase will be 10-100 times greater than it would have been if you'd spent the same amount sending "spam" emails. Obviously if you run a properly-targeted email campaign (only contacting past customers, or people otherwise known to have a particular interest in your product), you'll get much better results. But that costs much more than sending spam.


text:
Q: Using bitbucket pipelines pipes with arrays and loops Im looking at creating a pipes repo which can call other repositories and deploy to specific environments of which we have many (multiple dev and test environments).
The intention of this is to have a single repo where a user can select an envionrment, and it would then go deploy the master branch of all repositories in its list to that environment.
Ive like to avoid having too much duplication of code and ideally be able to just iterate over a list or either the environments, or the repositories.
Is there any documentation on examples someone can point me to if this is even possible?
thanks


text:
Q: How do I set default player names, nations and AI difficulty? When I want to start a new game of Freeciv, I am always presented with a screen like this:

I want to set some defaults so that I don't have to manually select the player nations every time I want to start a new game (this becomes tedious when the number of players is 30+).
I know how to set the default number of AI players (by using the aifill server option). But how can I set the default AI skill level, the default player names, and the default player nations?
In other words, I'd like to be automatically presented with something like this when I want to start a new game:

How can I achieve this?
EDIT: Freeciv issue tracker: https://www.hostedredmine.com/issues/855495

A: The default AI level can be set with the hard server command. You can set it in a file with server commands and start Freeciv with the -r option to read that file.
A default player name or default nations cannot be set, as far as I'm aware, but my Freeciv knowledge is rusty.

A: The server file or CLI can help you setup players
there are commands for levels of difficulty

*

*hard

*normal

*easy
commands like that

there are also commands for the number of AI players that appear by default
set aifill 3
makes sure that AI players will fill up the number players to 3
if you set that value to zero
set aifill 0
you can create new AI players as well and depending on the build, set the AI package for a player and a name for the player
create [name] [aitype]
allows you to create a player with [name] and then give it a particular [aitype], such as classic, for instance
Hope that helps


text:
Q: Is there a maximal finite depth infinite index irreducible subfactor? A subfactor $N \subset M $ is irreducible  if $N' \cap M = \mathbb{C} $.
It's maximal if it admits no non-trivial intermediate subfactors $N \subset P \subset M $.
It's cyclic if its lattice of intermediate subfactors is distributive (see here).
For "index" and "depth", see Jones-Sunder (1997) pages 29 and 91.
$\begin{array}{c|c|c|c|c|c}
\text{cyclic}^{1} & \text{maximal} & \text{finite}& \text{finite}&\text{irreducible}& \text{examples}^{23} \newline
      &    &   \text{depth}  & \text{index} &  &  \newline
 \hline
 &     \times    &   &         & \times& L(S_{\mathbb{N}^{*}}) \subset L(S_{\mathbb{N}}) \newline
 \hline
 &   \times       &   & \times & \times & A_{\infty}\text{-subfactors}  \newline
  \hline
 &   \times       & \times  & \times& \times& \mathbb{Z}/p\mathbb{Z} , \  S_{n} \subset S_{n+1}  ,  \text{Haagerup}\newline
 \hline
 \times  &   & \times  & \times& \times& \mathbb{Z}/m\mathbb{Z}, A_{n}\otimes A_{n+1}\text{-subfactor} \newline
 \hline
      \times   &   & \times  &         & \times& \mathbb{Z}  \newline
 \hline
&   \times       &  \times &         & \times& \textbf{?}
\end{array}$
$^{1}$ cyclic and non-maximal (obviously, maximal $\Rightarrow$ cyclic)
$^{2}$  $p \in \mathbb{P}$ , $n \ge 2$ and $ m\notin \mathbb{P}$
$^{3}$ the groups $G$ or $G_{1} \subset G_{2}$ correspond to the subfactors $R^{G} \subset R$ or $R^{G_{2}} \subset R^{G_{1}}$

Question: is there a maximal finite depth infinite index irreducible subfactor ?


text:
Q: Calendar to show today's current date with the next 60 days I have created a calendar that successfully displays todays current date. It also shows the remaining months however I am trying to change the functionality of the calendar so that it only shows the next 60 days from today's current date.
The code so far:
var todayDate = new Date();
var finalDate = new Date(todayDate)
finalDate.setDate(todayDate.getDate() + 60)
var dayNumber = todayDate.getDate();
var month = todayDate.getMonth();
var year = todayDate.getFullYear();
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];

var calendarTable = document.getElementById("calendar-body");

document.getElementById("month").innerHTML = months[month];
document.getElementById("year").innerHTML = year;

function createCalendar(month, year) {
 var firstDay = new Date(year, month).getDay();
 var totalDays = daysInMonth(month, year);

 blankDates(firstDay);
 for (var day = 1; day <= totalDays; day++) {
   var cell = document.createElement("li");
   var cellText = document.createTextNode(day);
   if (
     dayNumber === day &&
     month === todayDate.getMonth() &&
     year === todayDate.getFullYear()
   ) {
     cell.classList.add("todays-day");
   }

   cell.setAttribute("data-day", day);
   cell.setAttribute("data-month", month);
   cell.setAttribute("data-year", year);

   cell.classList.add("singleDay");
   cell.appendChild(cellText);
   calendarTable.appendChild(cell);
 }
}

function daysInMonth(month, year) {
 return new Date(year, month + 1, 0).getDate();
}

function blankDates(count) {
 for (var x = 0; x < count; x++) {
   var cell = document.createElement("li");
   var cellText = document.createTextNode("");
   cell.appendChild(cellText);
   calendarTable.appendChild(cell);
 }
}

createCalendar(month, year);

Any ideas would be great. Thanks :)

A: First you need to find the number of dates between two dates,
In this case is finalDate and todayDate
 var diff =  Math.floor(( Date.parse(finalDate) - Date.parse(todayDate)) / 86400000);

You get the difference days (or NaN if one or both could not be parsed). The parse date gived the result in milliseconds and to get it by day you have to divided it by 24 * 60 * 60 * 1000
The output of the diff now is 60
Then you add the diff variable into the for loop.
Woking example

A: Just an idea.
But you could generate an array of the dates between now and 60 days.
Then loop through that array to build the calendar.
This way the Date functions can be used for each date in the array.
Here's a simple function to generate such array.

function getDateRange(pStartDate, pDays) {
  let days = pDays || 1;
  let dates = [];
  let n = 0;
  let startDate = new Date(pStartDate.toISOString().slice(0,10));
  let endDate = new Date(startDate.getTime() + (days * 86400000));

  do {
    dates.push(new Date(startDate.getTime() + (n * 86400000)));
    n++;
  } while (n <= days);
  let obj = {
     startDate : startDate,
     endDate : endDate,
     days : dates.length,
     dates : dates
  }
  return obj;
}

var dateRange = getDateRange(new Date(), 60);

console.log(dateRange.dates);


text:
Q: Generalized Notion of Group Equivariance One notion of group equivariance as applied to functions $f$ between sets $X,Y$ acted on by a group $G$ is: $f(gx)=gf(x)$ for all $x\in X$ and all $g\in G$.
Is there a way to generalize this to the case where we have a different group, $G'$, say, acting on $Y$? That is a way to make rigorous for all $x\in X, g\in G, h\in G'$ we have $f(gx)=hf(x)$? My hunch is that this could be made to work if $G$ is homomorphic (isomorphic?) to (a subgroup of) $G'$, but if this has already been done I don't want to reinvent the wheel.


text:
Q: python request login to display my profile fails to bring my profile I was trying to read extract profile using Python Request libraries, it defaults back to login screen again as opposed to my profile screen. It is probably due to missing captcha. Any recommendation?
import sys
import requests

headers = {
    'User-Agent': "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
    'Accept-Encoding': 'gzip, deflate',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}

loginInfo={
    'session-key' : 'username@gmail.com',
    'session-password' : 'password'
}

URL='https://www.linkedin.com/uas/login-submit'
s=requests.session()
s.post(URL,data=loginInfo,headers=headers)

response=s.get('http://www.linkedin.com/nhome')

# print response.txt


text:
Q: Getting $_GET value within loop I can't see the problem with this bit of code it seems simple enough, i have a basic webpage:
<?php

include('includes/db_connection.php');
include('includes/functions.php');
include('includes/arrays.php');

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Payday Dreams</title>
<link href='http://fonts.googleapis.com/css?family=Nunito:400,300,700' rel='stylesheet' type='text/css'>
<link href="templates/css/main.css" rel="stylesheet" type="text/css" />
<link href="templates/css/bootstrap_v3.css" rel="stylesheet" type="text/css" />

  Unlock this page to continue!

TEST

<?php
  // get offers from the database
  $rows = DB::getInstance()->select('SELECT * FROM `offers` ORDER BY RAND() LIMIT 5');
?>
<?php foreach ($rows as $row) { ?>
<?php
 print_r($_GET);
 $p = $_GET['p'];
 echo $p;
?>

        <td class="offerDiv" title="<?php echo $row['offer_title']; ?>" style="height:30px; vertical-align:middle">

  <a href="click.php?c=<?php echo $row['offer_title_id']; ?>&l=&p=<?php echo $p; ?>" target="_blank"><?php echo $row['offer_title']; ?>

<?php } ?>

</form>

The URL is like this: http://www.site.co.uk/page.php?l=1p=7 what i'm trying to do is get the value of $_GET['p'] and use it within the foreach loop, when i try to print the value out within the loop it's blank but shows fine before it enters the loop, i have racked the brains i can't think of an alternate way of getting that value, any help would be appreciated.

A: Is your URL correct at your guess? Believably, what you are trying to do is: http://www.site.co.uk/page.php?l=1&p=7 Notice the & in the URL. You had: http://www.site.co.uk/page.php?l=1p=7. Was that intentional?

A: In your URL, the two query string parameters need to be separated by &. It's unable to recognize what p is.
http://www.site.co.uk/page.php?l=1&p=7


text:
Q: Keep text in text field after submit I'm building a form, and I want that all the inserted values will be kept, in case of form submit failure. This is my code:
<?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $name = $_POST["name"];

   // Verify $_POST['name'] greater than 4 chars
   if ( strlen($name) < 4 ){
        $error= 'Name too short!';
    }
}
?>

    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
       <input type="text" placeholder="Name" id="name" name="name" value=""/>
       <input type="submit" value="submit"/>
    </form>
        <?php
            echo "
Input:
";
            echo $name;
            if($error) {
                // No Update AND refresh page with $name in text field
                echo "
" . $error;
            } else {
                // Update name in DB
            }
       ?>

I would like that name field keeps the inserted input text, after submit. I tried to do with php code in input value but doesn't work. Any ideas?

A: Solved. This is the solution that I was looking for.
I added in value tag of input the following:
<?php if (isset($_POST['name'])) echo $_POST['name']; ?>

Therefore input field would look like:
<input type="text" placeholder="Name" id="name" name="name" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"/>

Thanks for your responses, helped me.

A: <?php
$error = "";
$name = isset($_POST["name"])?$_POST["name"]:""; //Added condition

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $name = $_POST["name"];

   // Verify $_POST['name'] greater than 4 chars
   if ( strlen($name) < 4 ){
        $error= 'Name too short!';
    }
}
?>

    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
       <input type="text" placeholder="Name" id="name" name="name" value="<?php echo $name; ?>"/>
       <input type="submit" value="submit"/>
    </form>
        <?php
            echo "
Input:
";
            echo $name;
            if($error) {
                // No Update AND refresh page with $name in text field
                echo "
" . $error;
            } else {
                // Update name in DB
            }
       ?>

A: You can just echo $_POST['name'] in the value attribute of the input.
Make sure you check POST values to avoid XSS.
I also put up the update DB function, as you don't need to show the form to the user if the name in longer the 4 chars!
 <?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (isset($_POST['name'])){ //change name content only if the post value is set!
       $name = filter_input (INPUT_POST, 'name', FILTER_SANITIZE_STRING); //filter value
   }
   // Verify $_POST['name'] greater than 4 chars
   if ( strlen($name) < 4 ){
        $error= 'Name too short!';
    } else {
        // Update name in DB
        // Redirect
    }
}
?>

    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
       <input type="text" placeholder="Name" id="name" name="name" value="<?php echo $name; ?>"/>
       <input type="submit" value="submit"/>
    </form>
        <?php
            echo "
Input:
";
            echo $name;
            if($error) {
                // No Update AND refresh page with $name in text field
                echo "
" . $error;
            };
       ?>

A: If you want to keep all values/inputs for further use you could achieve that with php session values.
Besides - you should use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']
Mars


text:
Q: Angular, exported enum not found during compilation Inside models.ts i have the following enum defined:
export enum REPORTTYPE {
  CUSTOMER, EMPLOYEE, PROJECT
}

Then i use it inside another class
console.log(REPORTTYPE.CUSTOMER);

The IDEA automatically imports the enum among other classes/interfaces from model.ts:
import {REPORTTYPE, ...more} from '../../../_models';

Everything seems to work fine, the IDEA is suggesting me the correct autocompletions so the imported file is working correctly. But then, when i compile it i get the following error:
ERROR in ./classpath... 59:20-30
"export 'REPORTTYPE' was not found in '../../../_models'

Every other import from models.ts is compiling and working correctly. He just cant find REPORTTYPE for some reason although i declared it as an exported enum and the IDEA also recognizes it correctly.

A: Try to rename the file and/or the enum. Check usage of index.ts and try direct import instead.


text:
Q: WooCommerce - How to display unavailable (out of stock, invisible) variations in the variations drop-down on the single product page? On a website, I need to display out-of-stock variations in the drop-down grayed out and with the additional text "sold out". This was possible through a Woocommerce hook. But I had to disable the Woocommerce checkbox to "hide out-of-stock items from the catalog", because otherwise the out-of-stock variations would be hidden completely from the drop-down.
The problem: Products with out-of-stock variations are still shown in archives (shop page, categories, attribute archives, search results) and this is not desired.
So the only possibility might be to "hide out-of-stock items from the catalog" and still display the out-of-stock variations in the dropdown.
I tried to overwrite the WooCommerce wc_dropdown_variation_attribute_options() function to modify the select options. The <options> there are populated by the $terms variable. When I var_dump() this variable right before the <select>, I see that all attributes are in place (visible and invisible ones). But they are hidden from the HTML, obviously by AJAX.
How can I make them visible?

A: function woocommerce_hide_out_of_stock_items( $pre_option ) {

    // Disable hide option dynamicaly on product page only
    if(is_product()){
        return 'no';
    }

    return $pre_option;
}
add_filter( 'pre_option_woocommerce_hide_out_of_stock_items', 'woocommerce_hide_out_of_stock_items' );


text:
Q: Symmetric continued fraction Let (a_i)_{1<=i<=n} be a sequence of positive integers and c be a positive integer such that c divides a_1.
Suppose that we have this symmetric of continued fraction
[a_n, a_n-1,...,a_1]=c^{-1}[a_1, a_2, ...., a_n].
Can we assume that n is even and a_{n-k}=c^(-1)^{k+1}a_{k+1}, for 0<=k<=n-1?


text:
Q: Org-mode: using special properties in the drawer Org manual says special properties "should not be used as keys in the properties drawer". However i want to use org-mode on a more high level and i want to put all special properties in the :PROPERTIES: drawer.
This can be used for many reasons, for example, i can write an external parser, that can understand org-mode files, that consist of only entries with properties, without needing to know about TODO, tags, priorities and their syntax in the headline. This should change the behavior of all org-mode commands, that usually obey the ad hoc org-mode syntax. For example, org-todo would change a TODO property in the drawer, instead of changing the headline, and so on.
In other words, I want to generalize org-mode syntax a bit. How can i do that in theory and practice? What should i need to know and do?

A: The only way (both theoretically and practically) is to rewrite org-mode to enable that.  The special properties (closed, scheduled etc) are assumed by existing code to be outside drawers, immediately below the header, todo items must be immediately after the stars and :tags: on the first line.
Tags should be easiest to reroute to a drawer as some functionality does this already. Closed, scheduled and deadline are well defined and movable. Placing todo status in drawers may be a big job.


text:
Q: how to pass parameters to component using react route link I'm using react and am trying to link to another page using the  tag. For example, I want to link back to the login screen with a parameter signupCompleted like so:
<Link to={{ pathname: '/', query: { signupCompleted: true } }}>
    <Button bsStyle="primary" onClick="sendSignupRequest" className="pull-
     right confirm-button-style">Send</Button>
</Link>

My component is routed to a path in my app.js:
<Route exact path='/' component={LoginPage} />

and in loginPage.js I try to reach the passed parameter in the constructor:
this.state = {
      signupCompleted: props.signupCompleted,
    };

However that is never set to true. I've looked at Pass props in Link react-router, but nothing seems to do the trick.
Any ideas?

A: As stated Here you can pass object as :
pathname: A string representing the path to link to.
search: A string represenation of query parameters.
hash: A hash to put in the URL, e.g. #a-hash.
state: State to persist to the location.
<Link to={{
  pathname: '/courses',
  search: '?sort=name',
  hash: '#the-hash',
  state: { signupCompleted: true }
}}/>

above is copied from here
Now inside your Login.js
You can do it initially set signupCompleted to false :
this.state = { signupCompleted: false };

A: Define the route as following:
<Route path="/login/:signupCompleted" component={LoginPage} />

The Link should be:
<Link to={`/login/${signupCompleted}`}>Login</Link>

And in the LoginPage component, this.props.match.params.id is the value of signupCompleted.


text:
Q: I cant find the elements using FindViewById I have 2 LinearLayouts inside of each other one the horizontal one is inside the vertical one . Some of the elements are not detected that are inside the horizontal Liner Layout using FindViewById (EditText , and a button) . And Yes I tried to save ...Thanks In advance. What I am basically doing is trying to create a web browser.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/llb"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="10px"
android:minWidth="10px"
android:orientation="vertical">

<LinearLayout
    android:id="@+id/ll1"
    android:layout_width="match_parent"
    android:layout_height="200px"
    android:layout_weight="1"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/t1"
        android:layout_width="300px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:hint="URL"
        android:imeActionLabel="GO"
        android:inputType="textWebEmailAddress" />

    <EditText
        android:id="@+id/t2"
        android:layout_width="300px"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:hint="data" />

    <Button
        android:id="@+id/button1"
        android:layout_width="300px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:text="New Tab"
        android:textColor="@color/material_blue_grey_800" />

    <Button
        android:id="@+id/button2"
        android:layout_width="300px"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:text="History"
        android:textColor="@color/material_blue_grey_800" />

</LinearLayout>

<LinearLayout
    android:id="@+id/llo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" />

</LinearLayout>

A: In your code , on onCreate() you need to do as follow :
View view = findViewById(R.id.llb); // root linear layout
View view1 = view.findViewById(R.id.ll1); //first child of root

then you can access your EditText :
EditText et = view1.findViewById(R.id.t1);

That's because you use nested layouts.
Also, please use CTRL+ALT+L for formatting your xml file for being more readable.