text:
Q: How to calculate totals on a memo Field in MS Access 2010? I have imported data from MS Access (mdt) file to MS SQL. Now I would like to test that the long text was not truncated during the import. I calculated minimum, average, maximum and sum of lengths of texts in the resulting data, like this
SELECT
    MIN(DATALENGTH([LongField]))
    ,AVG(DATALENGTH([LongField]))
    ,MAX(DATALENGTH([LongField]))
    ,SUM(DATALENGTH([LongField]))
FROM TheExportedTable

Results:
0   725 7574    2156708

I would like to check in MS Access that the original statistics on this field was the same. The type of the field in MS Access is memo. How can I do it? I tried adding a calculated field, it just did not work. When I tried adding a calculated field, nothing happened...

A: In Access you would use LEN instead of DATALENGTH:
SELECT
    MIN(LEN([LongField]))
    ,AVG(LEN([LongField]))
    ,MAX(LEN([LongField]))
    ,SUM(LEN([LongField]))
FROM TheExportedTable


text:
Q: ormLite createOrUpdate depends of 2 values in table I want to override createOrUpdate function in ORMLite, that it is depen on two value: group_id and type. What I want to obtain:
scenario:
In database I have object Model1 and the group_id=1 and type=small

*

*Want to add Model2 with group_id=1 and type=small - update record

*Want to add Model23 with group_id=1 and type=big - create new record

When I made additional field id and set it to generatedID, I allways adding to database but setting  group_id to id is not a good idea.
I suppose I need to override OrmLiteSqliteOpenHelperclass but I dont know where and how to do it

A: Maybe you can use ohibernate instead of ORMlite
https://github.com/10uroi/OHibernate

redpajama_set_name: RedPajamaStackExchange


text:
Q: Displaying image in ASP.NET C# I am converting Base64 code to image and I am using following way to save and display that image.
var kpin = Base64ToImage(TextBox1.Text);
kpin.Save(@"e:\myim.png");
Image1.ImageUrl = @"e:\myim.png";

and class is
public Image Base64ToImage(string base64String)
{
    byte[] imageBytes = Convert.FromBase64String(base64String);
    MemoryStream ms = new MemoryStream(imageBytes, 0,
      imageBytes.Length);
    ms.Write(imageBytes, 0, imageBytes.Length);
    Image image = Image.FromStream(ms, true);
    return image;
}

and this process working fine but I need an image not to be saved in hard disk. How to display this image directly without saving to hard disk and retrieving back.

A: Instead of setting the Image1.ImageURL to the path of your image, you can instead do one of several things:

*

*Use an img tag with the Base64 data in it directly - http://www.sweeting.org/mark/blog/2005/07/12/base64-encoded-images-embedded-in-html
Not all browsers support this.

*Create an Action or Webform (depending on whether you're using ASP.NET MVC or not) that takes as input whatever you need to either retrieve or generate the Base64 encoded data, and then set the response headers to serve the correct content type (image/png or something) and write the image directly to the Response.OutputStream (or use ContentResult in ASP.NET MVC). Tons of examples via Stackoverflow on how to do either.

-M

A: Don't bother with the image object at all, and just do it direct:
public void Base64ToResponse(string base64String)
{
    Response.ContentType = "text/png"; //or whatever...
    byte[] imageBytes = Convert.FromBase64String(base64String);
    Response.OutputStream(imageBytes, 0, imageBytes.Length);
}


text:
Q: Looking for a quote which is like "it's not for their sins, it's ours" I came across this quote some years back and I don't remember it correctly. If I understood it correctly it implied that when some things go wrong (especially relationships) it's not the other person's fault, it's ours that we let go that relationship. I am not sure about the meaning but it was close.
It has 'sins' in the quote.
Can you help me find the quote? Thanks in advance.

A: "It's not you, it's me."
From Wikipedia:

It's not you, it's me is a popular phrase used in the context of breaking up, and is intended to ease the dumpee's feeling in the knowledge that it wasn't their fault, but rather the fault of the dumper.

However, it's become something of a cliche, which is often taken to mean the opposite of it's original intended purpose.
The quoted article continues:

Merriam-Webster described it as a "much-reviled, often-used excuse." The Huffington Post described it as "overworked and cliched." Psychology Today argues that "opening with 'It's not you, it's me' is just going put your partner on the defensive from the start.


text:
Q: pt-table-checksum does't work with multi source (mariadb) Edit pt-checksum is getting to never ending loop in multi-source (channel based) replication :
A multi source replication in my environment

n1 -> n2 (created n1 as channel replication)
    n2 -> n3
    n1 -> n3 (n3 will replicate from both n1 and n2 channels)

Whenever without channel wise replication pt-checksum is working fine. (traditional replication/default replication works without any issues)
Once i enabled as channel wise(only n1, removed the n2 channel) replication (n1->n3) , the pt-checksum is not going through.

Replica n3-VirtualBox is stopped. Waiting.
        Replica n3-VirtualBox is stopped. Waiting.

from general log n1:

Query    SELECT 'pt-table-checksum keepalive'
             Query    SELECT 'pt-table-checksum keepalive'

A: I resolved the problem by following method:
On Master DB Server
(i) For safe side, I made copy of original /bin/pt-table-checksum
cp /bin/pt-table-checksum /bin/pt-table-checksumorg
(ii) Open the /bin/pt-table-checksum file
vi /bin/pt-table-checksum
(iii) Go to line number 8590
 Press esc, type 8590 , press shift g
(iv) replace the line
   my @lagged_slaves = map { {cxn=>$_, lag=>undef} } @$slaves;
by
    my @lagged_slaves = ();
the program immediately works and returns the expected results.

A: I have same problem. I also get infinite loop of "Replica dbslave is stopped." However if I break the output by pressing "Ctl + c", I get the inconsistent database and table name. I verified it and found the inconsistency in slave. Then I used pt


text:
Q: jQuery: event listener not getting triggered I am trying to add an event listener to a html element using Jquery.
test.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script src="test.js"></script>

  <body>
      <select id="options" >
         <option value="volvo">Volvo</option>
         <option value="saab">Saab</option>
         <option value="mercedes">Mercedes</option>
         <option value="audi">Audi</option>
      </select>
  </body>

test.js
alert("outside function");
$('#options').change(function() {

    alert("inside function");
    var x = $('#options option:selected').text();
    alert(x);
});

Now when I open file:///home/ronnie/check/popup.html and if I select anyone of the options my jquery function doesn't get triggered and I just get outside function popup.
I tried the same code in jsfiddle and it works absolutely fine http://jsfiddle.net/Vj9LK/.
So, my question is why it is not working in chromium.

A: You're selecting $("#options") in test.js, which is defined in the <script> tag before the <body> is constructed. jQuery has a function to wait until everything is constructed, so that you can select elements:
$(document).ready(function() {
  // contents of test.js
});

A: have you put the change function within document(ready)?
Try this
alert("outside function");

$(document).ready(function(){
    $('#options').change(function() {
        alert("inside function");
        var x = $('#options option:selected').text();
        alert(x);
    });
});

A: The DOM is not loaded yet. You need to use .ready function - http://api.jquery.com/ready/
alert("outside function");
$(function(){
  $('#options').change(function() {

    alert("inside function");
    var x = $('#options option:selected').text();
    alert(x);
  });
});

A: put your code in $(document).ready()
$(document).ready(function(){
    alert("outside function");
    $('#options').change(function() {

        alert("inside function");
        var x = $('#options option:selected').text();
        alert(x);
    });
})

A: I suspect the reason could be this:
When you do <script src="test.js"></script> in your html file, you haven't defined the options select tag yet, thus the onchange function is not getting registered properly. So try it after you define the select tag.
Or choose $(document).ready(function(){}) which gives you desired result.

A: use this code its working, be sure always write   after
    <html>
    <head>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>

     <select id="options" >
             <option value="volvo">Volvo</option>
             <option value="saab">Saab</option>
             <option value="mercedes">Mercedes</option>
             <option value="audi">Audi</option>
          </select>
     <script>
       $('#options').change(function() {

        alert("inside function");
        var x = $('#options option:selected').text();
        alert(x);
    });
    </script>
    </body>
    </html>


text:
Q: Singletons testing and subclassing I saw this while using picocontainer. They say you have to avoid singletons.
because the Singleton pattern makes it almost impossible for the class (and possibly all other classes which depend on it) to be testable. It's very hard to subclass, or to create a mock object for a Singleton class.
But if you absolutely need it , Is there a workaround for the testing and subclassing issue ?

A: What makes it hard to test singletons is the code enforcing their singleton-ness (meaning the public static MySingleton getInstance() {...} boilerplate). Using an inversion-of-control container, like Picocontainer or Guice or Spring, removes that concern from the object, so now:

*

*It can be instantiated and have collaborators plugged into it in tests without a problem.

*The code calling a singleton doesn't have to know what class it is looking up (which it would need to know if it had to call a static method).
I interpret the advice on picocontainer's website as being similar to this. What they are telling you is, let our container manage the scope of your components for you, don't hard-wire the scope-enforcing code into them.

A: If you must have singletons:

*

*Have an interface describing each singleton

*Access your singletons from a global/singleton ServiceLocator

*Switch the instances registered in the ServiceLocator during testing

Example:
interface IBankApi
{
   public void MakeDeposity(int accountNumber, int dollarAmount);
   // ...
}

public class RealBankApi : IBankApi { ... }

// startup code
serviceLocator.Register<IBankApi>(new RealBankApi());

// code using the API
serviceLocator.Resolve<IBankApi>().MakeDeposit(...);

// test code setup
class FakeBankApi : IBankApi { ... }
serviceLocator.Register<IBankApi>(new FakeBankApi());

A: Using IOC (inversion of control) rather than singletons initiated at first use is advantageous for other reasons too.
Singleton-initialisation can suffer (famously) from multi-threading issues where two threads try to access it for the first time simultaneously. Subsequent access is likely to be correctly synchonised but the first one is much harder to do.
Another huge advantage I have found of using IOC is when an error may occur in initialisation. You do not want this to happen on "first use", you want to know of this failure at an early stage, and certainly it is easier to handle the error this way.
Finally, with regards to testing, IOC provides the perfect model to isolate components, substitute them as necessary and bring together different combinations in a more flexible way, thus providing the perfect harness for both unit-testing and integration testing, as well as a good rollback mechanism without actually having to revert any code at all.
The general reason singletons are so often used is not for the one-ness but for the global-ness. If your project is managed correctly you have a single global object to which all the others "register" (thus your IOC model hangs off it) and are available globally whilst still being configurable.


text:
Q: Toggle click issue with checkbox Please find the code below
$("#chkCopy").toggle(function () {
   copyDetails();
},
function () {
   emptyCopyDetails();
});

// functions which do not have any effect on the checkbox
function copyDetails() {

}

function emptyCopyDetails() {
}

The issue is that checkbox is not showing the checked state.
Demo
Thanks in advance

A: The .toggle() interrupts the check, since .toggle() actually calls e.preventDefault() on the click event underneath.  Instead of that approach, I'd recommend something like this instead:
$("#chkCopy").change(function () {
  if(this.checked) {
    copyDetails();
  } else {
    emptyCopyDetails();
  }
});

Here's an updated/working version of your demo with the above approach.

A: $("#chkCopy").change(function () {                alert("1");

            },
            function () {
                alert("2");
            });

use change instead of toggle

A: From the documentation:

Since .toggle() internally uses a
  click handler to do its work, we must
  unbind click to remove a behavior
  attached with .toggle(), so other
  click handlers can be caught in the
  crossfire. The implementation also
  calls .preventDefault() on the event,
  so links will not be followed and
  buttons will not be clicked if
  .toggle() has been called on the
  element.

So you can't use toggle() if you want the check box to be checked and unchecked. You can use click() instead:
$("#chkCopy").click(function() {
   if (this.checked) {
       copyDetails();
   } else {
       emptyCopyDetails();
   }
});

A: take a look at this answer you would accomplish the same thing
Jquery toggle event is messing with checkbox value


text:
Q: How to map a group entity class from a "group name" column in NHibernate? I have a table in my database looking roughly like this:
create table Foo (
    Id             int identity       not null,
    Name           varchar(100)       not null,
    GroupName      varchar(100)       not null,
    constraint PK_Foo primary key (Id)
)

Now I want to map this table into two entity classes like this:
class Foo {
    public virtual in Id { get; private set; }
    public virtual string Name { get; set; }
    public virtual Group Group { get; set; }
}

class FooGroup {
    public virtual string Name { get; set; }
    public virtual ISet<Foo> Foos { get; private set; }
}

Is this possible with NHibernate? I have tried to search the net and NH docs, but I really don't know what to look for - ideas for search queries would be appreciated.
Maybe I can make a mapping for FooGroup that uses a custom HQL/SQL query to select the distinct group names, and another custom query to select the appropriate set of contained items?

A: I don't think it's possible to do what you want purely in the NHibernate mapping ... although I could be proved wrong by someone else  :-)
OTOH it's pretty easy to define a straightforward mapping from your table into:
class RawFooData
{
    public virtual in Id { get; private set; }
    public virtual string Name { get; set; }
    public virtual string GroupName { get; set; }
}

and then process this to get out the values you want:
IEnumerable<FooGroup> groups = allRawFooData.Select(data => data.GroupName)
                                        .Distinct()
                                        .Select(name => new FooGroup()
                                                        {
                                                           Name = name
                                                        });

foreach(var group in groups)
{
    group.Foos = allRawFooData.Where(data => data.GroupName == group.Name);
}

I think you will only find performance issues here if you are dealing with very large quantities of data (e.g. 10K rows or more).


text:
Q: Geckofx get specific links from a page var links = new List<GeckoElement>();
foreach (var link in geckoWebBrowser1.Document.Links)
{
    if (!String.IsNullOrEmpty(link.GetAttribute("href").ToString()))
        links.Add(link);
    }
}

I have this code to collect all links in the page, but I cant figure it out how can I filter to some specific links that starts with for example "ow.ly". Rest in the list should be ignored.
Tryed this but didnt seem to work
if (links.Count > 0)
{
    if (links.Equals("ow.ly"))
    {

    }
}

When I debug if links equals ow.ly it shows 0 reults.

A: links is a a List<GeckoElement>. So it's unlikely that the list equals to the string "ow.ly". Instead, you want to filter the list for items, which href property contains that text.
You could do that for example like this:
var owlyLinks = geckoWebBrowser1.Document.Links.Where(link =>
{
    string hrefAttribute = link.GetAttribute("href").ToString();
    return !string.IsNullOrEmpty(hrefAttribute) && hrefAttribute.Contains("ow.ly");
}).ToList();

You might want to adjust the check so that "ow.ly" needs to appear somewhere special instead of just somewhere inside the string. For example, you could parse the whole Url, and then check that the host name equals to ow.ly.


text:
Q: Postgresql support which type of sanitization processes? If we just drop the database from PostgreSQL then can we say that data deleted permanently, and securely?
How can we follow industry-standard sanitization processes, e.g., NIST 800-88 with postgresql ?

A: There is no support for that built into PostgreSQL, since that belongs to the physical properties of the file system, and PostgreSQL uses the kernel's file system API and has no knowledge about the file system's inner workings.
Even if PostgreSQL went as far as overwriting files with random data before deleting them (which it doesn't), that wouldn't achieve anything on a copy-on-write file system after a snapshot has been taken.
You are approaching this on the wrong layer. This requirement has to be handled on the file system level.


text:
Q: Get the value of git command in shell script I want to use husky to run a shell script to return exit 1 if a user includes the --tags option in a git push command.
I have husky set up like this in my package.json
"husky": {
  "hooks": {
    "pre-push": "sh stopTagPush.sh"
  }
}

When I run the command git push origin --tags this runs my script but I don't know how to get access to the value of the git command git push origin --tags to see if --tags is present. Is there a git variable that I can use to access the command value inside the script?


text:
Q: Button does not appear on the table The following code adds a Accept/Decline Button per row. But for some reason, the decline button does not appear. I dont know whats wrong. Been stuck for a while now. Help would be appreciated. Thanks!!
<?php
                    $con=mysqli_connect("localhost","root","","rabco");
                    // Check connection
                    if (mysqli_connect_errno())
                    {
                    echo "Failed to connect to MySQL: " . mysqli_connect_error();
                    }

                    $result = mysqli_query($con,"SELECT * FROM service_request");

                    echo "

                    Service ID
                    Service Type
                    Schuduled Date
                    Scheduled Time
                    Client Reference
                    Client ID
                    Admin ID
                    Special Instructions
                    Status
                    Approve
                    Decline

";

                    while($row = mysqli_fetch_array($result))
                    {
                    echo "
";
                    echo "" . $row['Service_ID'] . "	";
                    echo "" . $row['Service_type'] . "	";
                    echo "" . $row['Sched_date'] . "	";
                    echo "" . $row['Sched_time'] . "	";
                    echo "" . $row['Client_reference'] . "	";
                    echo "" . $row['Client_IDN'] . "	";
                    echo "" . $row['Admin_IDN'] . "	";
                    echo "" . $row['Special_instructions'] . "	";
                    echo "" . $row['Request_status'] . "	";
                    echo "Approve	";
                    echo "Decline	";
                    echo "
";
                    }
                    echo "
";

                    mysqli_close($con);
                ?>

A: There is a missing closing quote here:
echo "Approve	";

Change to:
echo "Approve	";

A: You are missing the closing quotes on your href attributes, which is creating malformed HTML output.
You need to change:
echo "Approve	";
echo "Decline	";

to
echo "Approve	";
echo "Decline	";


text:
Q: Algorithm to merge time intervals while keeping input id information I need to build an algorithm to merge time intervals from multiple arrays (for simplification considering only one date) while keeping input id information. What are some approaches to do it?
Input:
{"input_id": "1", "ranges": [{"from": 07:00, "to": 13:00}, {"from": 15:00, "to": 15:30}],
{"input_id": "2", "ranges": [{"from": 08:00, "to": 14:30}]}

Expected output:
{"ranges":[
{"from": 07:00, "to": 08:00, "inputs": [1]},
{"from": 08:00, "to": 13:00, "inputs": [1,2]},
{"from": 13:00, "to": 14:30, "inputs": [2]},
{"from": 15:00, "to": 15:30, "inputs": [1]},
]}

A: One way to do it is to create a sequence of "events" sorted in order of when they occur. An "event" is either a time when an id's range begins or a time when an id's range ends. Once you have the sorted list of events, you can process the events in order one at a time to produce the required output.


text:
Q: if differentiable and derivative is bound then total variation is bounded I am having problem with this question (from Erhan Cinlar's Probability and Stochastic Chapter 1 Section 5 Question 24b):
Let $\mathscr{A}$ be a collection of disjoint intervals of the form $(,]$ whose union is $(s,t]$.
Let $V_f(s,t)=\sup\limits_{\mathscr{A}}\sum\limits_{(u,v]\in\mathscr{A}}|f(v)-f(u)|$.
If $f$ is differentiable and its derivative is bounded by $b$ on $[s,t]$, then $V_f(s,t)\leq(t-s)\cdot b$.
My attempt:
$\forall \mathscr{A}$
By Triangle Inequality, $\sum\limits_{(u,v]\in\mathscr{A}}(f(v)-f(u))\leq\sum\limits_{(u,v]\in\mathscr{A}}|f(v)-f(u)|$
Thus $\forall \mathscr{A}, f(t)-f(s)\leq\sum\limits_{(u,v]\in\mathscr{A}}|f(v)-f(u)|$, since union of intervals in $\mathscr{A}$ is $(s,t]$
Thus $f(t)-f(s)\leq V_f(s,t)$, by definition of supremum
$\implies$ $\frac{f(t)-f(s)}{t-s}\leq\frac{V_f(s,t)}{t-s}$, since $t>s$
$\implies$ $f'(c)\leq \frac{V_f(s,t)}{t-s}$, By Mean Value theorem, $\exists c\in(s,t), f'(c)=\frac{f(t)-f(s)}{t-s}$
But I am unable to use the derivative is bounded since the inequality seems to be in the wrong direction
Can I have a hint please?

A: $$\sum_{(u,v]\in \mathscr A} |f(u)-f(v)|=\sum_{(u,v]\in \mathscr A}|f'(c_{u,v})||u-v|$$$$\leq \sum_{(u,v]\in \mathscr A}M |u-v|\leq M(t-s).$$
Here, $|f'|\leq M$. Note that the intervals in $\mathscr A$ are disjoint and contained in $(s,t]$. So sum of  lengths of the intervals in $\mathscr A$ is less or equals to length of $(s,t]$.


text:
Q: Faster calculation of cumulative sum in attribute table in QGIS I have a shapefile attribute table in QGIS that I would like to calculate the cumulative sum. The thing is that it has over 1.5 million features.
Type of device: HDD.
The attribute table looks like this:

I have tried to calculate in a new field the cumulated sum for "Equitativo" like this:
 with_variable (
    'ID_FINAL',
    ID_FINAL,
    sum(Equitativo, filter:=ID_FINAL<=@ID_FINAL)
)

The problem is that is taking way too long (it's running for 17 hours now). How could I make this in a faster way?

A: Your expression is not efficient because it calculates the same sum over and over again: for feature no. 100, it is adding 100 numbers (feature1, feature2, ... feature100), even though adding 99% of these values (from feature1 to feature99) was done before.
Better rely on the already calculated sum of the last feature: for feature 100, something like (pseudocode):
sum (feature100) = sum (feature99) + value (feature100)
So try this expression:
attribute (get_feature_by_id(@layer, $id),'Equitativo')+
attribute (get_feature_by_id(@layer, $id-1),'Equitativo')

Will definitely take more time then the Python-skript by @Kadir Şahbaz, so you might want to stick to this. This solution here is just to show how to do it using QGIS expressions only.

A: You can use the script below in QGIS Python Editor. It takes about 45 seconds (including saving to source file) for 1.5 million features in SSD or HDD. Select the layer first.
import time
start_time = time.time()

layer = iface.activeLayer()

# Add CUM_SUM field if not exist
field_index = layer.fields().indexFromName("CUM_SUM")
if field_index == -1:
    field = QgsField('CUM_SUM', QVariant.Double, len=20, prec=3)
    layer.dataProvider().addAttributes([field])
    layer.updateFields()

# Get field indices
id_index = layer.fields().indexFromName("ID_FINAL")
eq_index = layer.fields().indexFromName("Equitativo")
cum_sum_index = layer.fields().indexFromName("CUM_SUM")

cum_sum = 0
attribute_map = {}
request = QgsFeatureRequest().addOrderBy('ID_FINAL').setFlags(QgsFeatureRequest.NoGeometry).setSubsetOfAttributes(['ID_FINAL', 'Equitativo'], layer.fields())
for feature in layer.getFeatures(request):
    cum_sum += feature["Equitativo"]
    attribute_map.update({feature.id(): {cum_sum_index: cum_sum}})

layer.dataProvider().changeAttributeValues(attribute_map)

print("%s seconds" % (time.time() - start_time))


text:
Q: JPA Query for a simple SQL query SELECT * FROM tableA a
WHERE id IN (
SELECT DISTINCT extId
FROM tableB
);

A: You can try this:
@Query(nativeQuery=true, value="SELECT a FROM tableA a WHERE id IN ( SELECT DISTINCT extId
FROM tableB ")


text:
Q: Reorganise the LQ, FP and LA queues to have one queue about improving and guiding and one about deciding deletion TL;DR: Split the low-quality queue in two, separating posts with possible quality issues (autoflagged posts) and posts that may need to be deleted (NAA, gibberish), as having both of them together causes confusion and mistreatment of posts. To keep things simple, reorganise the FP, LA and LQ queues, while you are at it.
Looking at the triage and help-and-improvement queue over at Stack Overflow and the Meta posts on that, I sometimes think that this is planned already, but then again sometimes statements make me think that the idea has never crossed anybody's mind. So, here I am, suggesting it anyway.
Three notes:

*

*I will start of ignoring questions for this at first, as this only complicates the explanations.

*I will also keep my proposal as close to the status quo as reasonably possible (except for the restructuring). This is not about the details, this is about the general direction.

*This is not written from the perspective of Stack Overflow with its special needs. I do not see any argument why it could not apply there though.

Proposal

*

*Create two review queues:

*

*Help and improvement (HI)– The interface and processing of posts in this queue are identical to the first-posts and late-answers queues with the only exception that a post may need more than one review to be dequeued.

*Not an answer queue (NAA) – Interface and processing are identical to the low-quality queue except for the wording (which should be along the lines of what I suggested here).

*Introduce a needs improvement flag for answers saying something along the lines of:

This answer can be severely improved by editing or the author needs guidance on answering.

*The queues are fed as follows:

*

*First posts, late answers and answers flagged with needs improvement are sent to the HI queue and so are answers that would be autoflagged and sent do the low-quality queue nowadays due to heuristics. If a post is sent there for more than one reason (or is already in the queue), the number of required reviews is increased (details need to be determined, this request could be considered).

*Posts flagged not an answer are sent to the NAA queue.

*Retire the first-posts, late-answers and low-quality queue as well as the very-low-quality flag or morph them into one of the above.
What does this actually change?
First posts and late answers receive the same treatment as before – only that one person cannot review the same post in both queues (and the low-quality queue on top). Correctly flagged not-an-answers also receive the same treatment. Answers whose only problem is a lack of quality, however, get sent to a queue that is not about deleting them but about improving them. Also, the very-low-quality flag gets removed, as it is pointless in its current form anyway (see below). Instead there is a needs improvement flag, which essentially sends a post to the late answers queue.
So essentially, I could have proposed a new separate queue for low-quality posts, but then I would have received complaints about yet another queue or wanting to reintroduce the 10 k queue. Also, restructuring seems like a good idea.
Depending on how the queues are organised internally, this may be rather easy to implement.
Why do we need this?
The current low-quality queue is about deciding whether a post is actually an answer and about improving low-quality posts. This is the cause of a lot of problems. The wording of this queue is mainly aimed at improving posts, but if a post is just low quality (e.g., a short and unelaborate answer), there is no proper action to take. Thus a post that gets autoflagged (due to heuristics) may be deleted because only the original author can improve it and nobody wants to click Looks OK. This leads to a lot of confusion, disappointment and disgruntling of new users, who sometimes just need a little bit of help to write proper answers. I wrote about this more extensively in these answers of mine.
Therefore posts that are autoflagged should first be sent to somebody willing to improve them in a queue that is not about deleting them (HI queue). If such posts turn out to be not-an-answers, they can still be flagged such there.
The very-low-quality flag was probably intended to say this post needs improvement at some time, and apparently some sites and people use it as such (see here and some of the comments and and answers on this question), but the current wording does not reflect this:

This answer has severe formatting or content problems. This answer is unlikely to be salvageable through editing, and might need to be removed.

According to my understanding, unsalvagable severe content problems are cat-on-keyboard or unparsable English – but those can as well be flagged as not an answer. I have no idea how unsalvagable formatting problems even look like; if I can identify formatting as the source of a problem, I can also solve it. So, there is no need for this flag in its current form. What we might need, is a low-quality flag that sends salvageable posts to those who have the time, temper and expertise to improve them – which is the purpose of the needs improvement flag.
Noteworthy issues

*

*At what reputation shall the queues be available? The most straightforward solution would be 500 for the HI queue (same as first posts and late answers) and 2 k for the NAA queue (same as the low-quality queue). The main effect of this would be that autoflagged posts and posts flagged very low quality/needs improvement would now be sent to a queue which is available to users without editing privileges. I have no problem with this, as first posts often require edits as well and often for the same reasons, but one could also make these posts available later in the same queue (just as tag-wiki edits only become visible in the suggested-edits queue at 5 k reputation).

*Answers that are autoflagged or flagged needs improvement are sent to a queue that allows to vote. I do not consider this a big problem, but if it turns out to be one, this can be fixed by not uniting the queues or disallowing votes for those posts specifically.

*The number of queues would be reduced by one and so would be the number of times a given reviewing badge can be earned.

*Autoflagged posts are not directly sent to a queue that is about deciding their deletion anymore. Thus, utter junk detected by autoflagging may take a tiny bit longer to be deleted (this may be counteracted by having a flag from the HI queue count like recommend deletion/delete from the LQ queue, if the user has sufficient reputation).

*The needs improvement flag may do more harm than good as it allows users to lazily delegate the responsibility for a bad post they found instead of editing it themselves. On the other hand, sometimes you really lack the expertise, time or temper to edit a bad post yourself, in which case the flag would be appropriate.
What about questions?
The triage and help-and-improvement queues on Stack Overflow pretty much go into the same direction as what I propose, in particular by separating improving questions and weeding out questions without any value. Moreover, the problems described above do not apply that much to questions anyway, as the correlation between low quality and closeworthiness is much stronger for questions, the close queue and low-quality queue are separate and the very-low-quality flag for questions is hardly used in my experience (but even more pointless than for answers, IMHO).
It is however uncertain whether and how those two will be implemented on sites other than Stack Overflow. However the mentioned stand-alone implementation of the help-and-improvement queue on other sites pretty much corresponds to my suggestion, I would just unite it with the first-posts queue, as the two are mainly about the same thing anyway.

A: I'm not persuaded that this is an improvement, but explaining why requires an answer of some length.  This proposal conflates two or three independent proposals:

*

*Removing the VLQ flag.

*Introducing the "needs improvement" flag and a "help and improvement" queue.

*Separating out queues based upon reviewing criteria.
Each of those has its own pros and cons.  Bundling them all together makes it hard to comment on your proposal, but I'll try.
"Needs improvement" flag
Let me give you some common-sense advice that eliminates the need for a "needs improvement" flag:
If you see an answer that needs severe editing: edit it.
Don't be lazy.  Flagging it for someone else to edit is not helpful.  There's nothing preventing you from editing it yourself.  Anything the reviewer can do, you can do.
Philosophically, flags are for exceptional situations that the flagger can't handle on their own and that needs help from someone with more privileges.  "Needs severe editing" doesn't meet any of those criteria.  It's not exceptional -- I see all too many answers that this could be applied to.  It's not a situation that the flagger can't handle on their own: anything a reviewer could do, the flagger could do.
Pragmatically, "needs severe editing" is not a situation that is useful to flag.  The hard part is not identifying such answers; I run into plenty of them every day.  The hard part is finding enough time to edit everything that could benefit from editing.  Flagging as "needs improvement" isn't helpful.  Flagging effectively says "This answer could be improved, but I can't be bothered to do it; let's create work for someone else".
Also, I'm concerned that flagging "needs improvement" is a one-bit signal, but it doesn't indicate what specifically needs to be improved or how to do it.  It's not actionable.  It's just a flag saying "this sucks" but without explaining exactly how it could be better.
You could also run into cultural issues on some sites.  Some sites discourage heavy edits from third parties.  I have a mental list of sites where I've tried making edits to improve answers and discovered that such edits are unwelcome -- and I'm not even talking about severe edits at the level you seem to be contemplating.
Finally, I expect that on larger sites the "help and improvement" queue will be one that might grow unceasingly and never get emptied.  There's a boatload of answers that "need improvement", but I'm not persuaded there's enough capacity among reviewer-editors to fix all of them or even a majority of them.
Removing the VLQ flag
The premise seems to be that answers we're currently flagging as VLQ could be either flagged as NAA or could be saved if they just went into a "help & improve" queue.  I'm not persuaded by this premise.  Or, to state it more constructively: I think it'd help if you presented data to show how this would help.
When answers are flagged with VLQ, usually that's because the answer is so bad that there is no reasonable way to improve it (short of editing it to replace it entirely with something entirely new that's so good it could have been posted as a new answer).  Typically, the right answer for those VLQ answers is to delete them.
When we have a terrible, very-low-quality answer, it seems like the right thing to do is to delete it.  If you can see how to craft a good new answer from scratch, starting from nothing, then post it as a new answer.
And philosophically, if an answerer puts so little effort into their answer that it deserves a VLQ flag, then I have zero motivation to rescue their answer for them.  I'm fine with helping and improving answers where the answerer has put in 80% of the work and has some good stuff, but needs help for the remaining 20%.  But if the answer has put in 0% of the work, or 5%, and reviewers are supposed to put in 100% of the work, or 95%, then I don't think that's a reasonable thing to ask reviewers to do.  In my experience, usually when you've got a VLQ answer, turning that into a good answer is no easier than writing a good answer from scratch.
That's my anecdotal impression.  I could be persuaded by data showing that my impression is wrong.  Do you have data?  Perhaps you could do a review of answers that have been flagged VLQ, and analyze them to see if my sense is correct?
Misconceptions about VLQ vs NAA
The question seems to imply there's no difference between VLQ and NAA flags.  That's not quite right.  There is a difference.  NAA is for answers that don't even try to answer the question.  If you've got an answer that is trying to answer the question but is total garbage, you need to use VLQ, not NAA.  VLQ shouldn't be used to flag answers that are merely wrong, but if it's got severe problems that can't be rescued through editing, then a VLQ flag can potentially be appropriate.  For instance, I've seen answers where they are only one sentence long, the answerer thinks they're trying to answer the question, but the reasoning is gibberish or reflects a fundamental irreparable confusion.  For some such answers, a VLQ flag is appropriate, as a way to get enough 10K users to take a look and vote to delete.
So, when you say that anything currently flagged with VLQ could instead just be flagged with NAA, that's simply not correct.  In my experience, many of those NAA flags will be rejected.


text:
Q: customising ISBN, location, venue, volume, edition, series, dates, etc. fields of books, proceedings, etc. in biblatex APA style I have the following MWE:
\RequirePackage{filecontents}
\begin{filecontents*}{biblatextest.bib}
@article{W00,
  author = "Wayne, J.",
  title = "Article with volume number and doi",
  journal = "Journal A",
  volume = "X",
  number = "Y",
  pages = "1-2",
  year = "2000",
  doi  = "10.1007/...",
  url  = ""
}
@article{L00,
  author = "Lee, B.",
  title = "Article without volume number, but with url",
  journal = "Journal B",
  volume = "",
  number = "Y",
  pages = "3-4",
  year = "2000",
  doi  = "",
  url  = "https://..."
}
@book{J92,
  author = "Jordan, M.",
  title = "{Fundamentals of Basketball}",
  edition = "1",
  publisher = "Chicago University Press",
  location  = "Chicago",
  isbn = "87654321",
  doi = "",
  url = "",
  year = "1992"
}
@inproceedings{D21,
  author = "Delon, A.",
  title = "{Article title}",
  editor = "Edith, I.",
  booktitle = "{Proceedings of Symposium A}",
  series = "Series of Symposia Proceedings",
  volume = "1",
  edition = "2",
  pages = "5-6",
  publisher = "Cambridge University Press",
  location = "London",
  isbn = "12345678",
  doi = "",
  url = "",
  year = "2021",
  eventtitle = "Symposium A",
  venue = "Oxford",
  eventdate = "2020-09-01/2020-09-05"
}
\end{filecontents*}

\documentclass{article}
\usepackage{fullpage}

\usepackage[american]{babel}
\usepackage{csquotes}

\usepackage[style=apa, natbib=true, backend=biber]{biblatex}
\DeclareLanguageMappingSuffix{-apa}

\usepackage{hyperref}
\hypersetup{allcolors=blue,colorlinks=true,linktocpage,bookmarksopen,bookmarksnumbered}

\usepackage{xpatch}
  \xpretobibmacro{doi+url}{\printfield{isbn}}{}{}

\makeatletter
\renewbibmacro*{cite:plabelyear+extradate}{%
  \iffieldundef{labelyear}{}
    {\clearfield{labelmonth}% don't want months in citations
     \clearfield{labelday}% don't want days in citations
     \clearfield{labelendmonth}% don't want months in citations
     \clearfield{labelendday}% don't want days in citations
     \iffieldsequal{labelyear}{labelendyear}% Don't want no-op year ranges
       {\clearfield{labelendyear}}
       {}%
     \iffieldundef{origyear}
       {}
       {\printorigdate%
        \setunit*{\addslash}}%
     \iffieldundef{related}
       {}
       {\iffieldequalstr{relatedtype}{reprintfrom}
         {\entrydata*{\thefield{related}}{\printlabeldateextra}%
          \setunit*{\addslash}}
         {}}%
     \printlabeldateextra}}

\renewbibmacro*{citeyear}{%
  \iffieldundef{labelyear}
    {\usebibmacro{cite:init}}
    {\iffieldequals{fullhash}{\cbx@lasthash}
       {\setunit{\compcitedelim}%
        \printtext[bibhyperref]{\usebibmacro{cite:plabelyear+extradate}}}
       {\printtext[bibhyperref]{\usebibmacro{cite:plabelyear+extradate}}%
        \savefield{fullhash}{\cbx@lasthash}}}%
  \setunit{\multicitedelim}}

\renewbibmacro*{cite:author}{%
  \iffieldequals{fullhash}{\cbx@lasthash}
   {\setunit{\compcitedelim}%
    \printtext[bibhyperref]{\usebibmacro{cite:plabelyear+extradate}}}%
   {\printtext[bibhyperref]{%
      \ifnameundef{labelname}
        {\usebibmacro{cite:noname}%
          \savefield{fullhash}{\cbx@lasthash}}
        {\ifnameundef{shortauthor}
          {\printnames{labelname}}%
          {\cbx@apa@ifnamesaved
             {\printnames{shortauthor}}
             {\ifnameundef{groupauthor}
               {\printnames[labelname]{author}}
               {\printnames[labelname]{groupauthor}}%
              \addspace\printnames[sabrackets]{shortauthor}}}%
           \savefield{fullhash}{\cbx@lasthash}}}}%
   \setunit{\multicitedelim}}

\renewbibmacro*{cite}{%
  \iffieldequals{fullhash}{\cbx@lasthash}
   {\setunit{\compcitedelim}%
    \printtext[bibhyperref]{%
      \usebibmacro{cite:plabelyear+extradate}}}%
   {\printtext[bibhyperref]{%
      \ifnameundef{labelname}
       {\usebibmacro{cite:noname}%
         \setunit{\printdelim{nameyeardelim}}%
         \usebibmacro{cite:plabelyear+extradate}%
         \savefield{fullhash}{\cbx@lasthash}}
       {\ifnameundef{shortauthor}
         {\printnames{labelname}}%
         {\cbx@apa@ifnamesaved
           {\printnames{shortauthor}}
           {\ifnameundef{groupauthor}
             {\printnames[labelname]{author}}
             {\printnames[labelname]{groupauthor}}%
            \addspace\printnames[sabrackets]{shortauthor}}}%
         \setunit{\printdelim{nameyeardelim}}%
        \usebibmacro{cite:plabelyear+extradate}%
        \savefield{fullhash}{\cbx@lasthash}}}}%
   \setunit{\multicitedelim}}

\renewbibmacro*{textcite}{%
  \iffieldequals{fullhash}{\cbx@lasthash}
% Compact cite - more than one thing for same author
    {\setunit{\compcitedelim}%
     \printtext[bibhyperref]{%
       \usebibmacro{cite:plabelyear+extradate}}}
% New cite
    {\ifbool{cbx:parens}
       {\bibcloseparen\global\boolfalse{cbx:parens}}
       {}%
     \setunit{\textcitedelim}%
     \ifnameundef{labelname}
     % No author/editor
       {\iffieldundef{shorthand}%
    % Cite using title
         {\printtext[bibhyperref]{\usebibmacro{cite:noname}}%
      \setunit{\global\booltrue{cbx:parens}\addspace\bibopenparen}%
          \printtext[bibhyperref]{\usebibmacro{cite:plabelyear+extradate}}}
    % Cite using shorthand
         {\printtext[bibhyperref]{\usebibmacro{cite:shorthand}}}}
  % Normal cite with author/editor
  % Normal full cite
       {\printtext[bibhyperref]{%
          \ifnameundef{shortauthor}%
    % Normal full cite
       {\printnames{labelname}}
    % Cite using short author
           {\cbx@apa@ifnamesaved
             {\printnames{shortauthor}}
             {\ifnameundef{groupauthor}
               {\printnames[labelname]{author}}
               {\printnames[labelname]{groupauthor}}}}}%
  % Year
        \setunit{\global\booltrue{cbx:parens}\addspace\bibopenparen}%
  % Put the shortauthor inside the year brackets if necessary
        \printtext[bibhyperref]{%
          \ifnameundef{shortauthor}
           {}
           {\cbx@apa@ifnamesaved
             {}
             {\printnames{shortauthor}%
              \setunit{\printdelim{nameyeardelim}}}}%
  % Print prenote (belongs to first cite)
          \ifnumequal{\value{citecount}}{1}
             {\usebibmacro{prenote}}
             {}%
  % Actual year printing
          \usebibmacro{cite:plabelyear+extradate}}%
  % Save name hash for checks later
        \savefield{fullhash}{\cbx@lasthash}}%
    \stepcounter{textcitecount}}}
\makeatother

\addbibresource{biblatextest.bib}

\begin{document}
\sloppy

\citep{W00}

\citet{L00}

\citep{J92}

\citet{D21}

\printbibliography

\fussy
\end{document}

As you see, not all fields from the book and proceedings references are standardly written on the .pdf output file when using APA style. How can I have all these fields written? Note that I already could write the ISBN field (which is not standardly printed in APA style) with the two code lines after the hyperref package setup (though the ISBN font is different, so it could be that this is a rather quick fix). The large piece of code after that until the start of the document has to do with hyperlinking author + year, which was addressed in a separate question. Also note the wicked year output for the proceedings. Probaly, one should use a date field, instead of an year field, across the whole .bib file when using biblatex. I will try to add a book collection type of entry in the coming hours. With that, one should hopefully address costumisation of most if not all relevant type of bibliographic entries in APA style. I am aware that one might instead of customising APA style, customise some other style like authoryear or its variants, but please bear in mind that the target is to have essentially APA style, but with all fields from books, proceedings, book collections, and so forth an so on, printed or at least have the option to do so. A secondary target could be also to drop the comma before & (or to keep the comma and drop all &s as seen in some "Harvard styles") for two-author references; but that has less priority.
Thanks for any help!


text:
Q: js peerConnection doesn't connect if using mobile internet Description:
I'm using peerConnection between two computers and send mediaStream from canvas to the video-element of other computer
Problem:
If I'm using mobile internet on computer that connect's to host computer then connection readyState standing still in connecting
Ice candidates received correctly and remote and local descriptions was sended successfuly too. But channel wasn't opened
Question:
So I don't have any idea why does it happend?


text:
Q: jquery scrollTop and href="#" I use this function to scroll to a desired container:
function scrolear(destino){
    var stop = $(destino).offset().top;
    var delay = 1000;
    $('body').animate({scrollTop: stop+'px'}, delay);
    return true;
}

The problem comes when is used like this:
go

Because the href="#" makes body to scroll to top of page.
Is there a way to prevent this?

A: Update
Consider using javascript to progressively enhance your site rather than relying on it for the site to function correctly. In your example this would be achievable by the following:
HTML:
go

Javascript:
$(function() {
  $('a[href^="#"]').click(function(e) {
    e.preventDefault();
    var target = $(this).attr('href');
    var stop = $(target).offset().top;
    var delay = 1000;
    $('body').animate({scrollTop: stop + 'px'}, delay);
  });
});

This would intercept clicks on all links where the href started with a # and add in the animation for you. If the user did not have javascript enabled clicking the link would still take them to the correct place.
Hope this helps!

A: since you use jquery I would do
go

$("a").click(function() {
    e.preventDefault(); // cancel's the '#' click event
    scrolear('#container');
});

A: go

This will just assign a javascript function to the href, which will do nothing at all,so no page scroll happens like with #

A: corrected answer from @rich.okelly
function scrollTosec(){
     $('a[href^="#"]').click(function(e) {
            e.preventDefault();
            var target = $(this).attr('href');
            var stop = $(target).offset().top;
            var delay = 200;
            $('body').animate({scrollTop: stop + 'px'}, delay);
          });
}


text:
Q: How to profile a method with arguments in a loop? I have a class Foo and it implements a method compute. I would like to see how long compute takes and where it spends most of its time when executing. To resolve the first problem, I used timeit.default_timer in a loop and averaged:
import numpy as np
from timeit import default_timer as Timer

foo = Foo()
n = int(10e8)
times = np.empty(n)

for i in range(n):
    start = Timer()
    foo.compute(i)
    times[i] = Timer() - start

print(np.sum(times) / times.size)

This tells me what the average execution time of each compute call was, easy enough; except its slower than I thought.
Now I would like to break down the execution profile of compute, but the followingn doesn't seem to do the trick:
import cProfile

for i in range(n):
    cProfile.run(foo.compute(i))

I didn't think it would work anyhow, but the docs seem to suggest I would have to put this loop in a method and then profile that loop? So I tried that but it doesn't show whats going on inside compute which is what I desire. How can this be accomplished?

A: Instead of using run(), you can use runctx(), which provides arguments to supply globals and locals dictionaries.
cProfile.runctx("foo.compute(n)", {"n": n, "foo": Foo()}, {})

To aggregate the results from multiple profile runs, see How to calculate the average result of several cProfile results?.

A: To use cProfile, you need to pass the function as a string argument or "command". So, simply modifying your original code should work:
for i in range(n):
    cProfile.run("foo.compute(i)")

However, in your case, it seems like you want to profile the execution of a "real world" case and see where you have bottlenecks that you can optimize. Profiling the function is not the same as benchmarking it. The Python documentation on profilers also states:

Note The profiler modules are designed to provide an execution profile for a given program, not for benchmarking purposes (for that, there is timeit for reasonably accurate results).

When benchmarking, you want to execute the command many times in a loop, in order to get the average execution time +- standard deviation, which should be representative of what happens in reality and allows you to compare different solutions. However, profiling breaks down a single run of the command. This should be enough to identify which specific components of the method take more time than others (vs. how long they actually take), and this order of magnitude shouldn't really change between runs (although the specific time it takes might fluctuate).
If you do actually want to calculate statistics on the average run, you could generate the stats over many runs and then extract the data to manipulate it further:
pr = cProfile.Profile()
pr.enable()

for i in range(n):
    foo.compute(i)

pr.disable()
pr.create_stats()
stats = pr.stats

(pr.stats is a dictionary that gets formatted into the print statement you see when you profile)


text:
Q: Minify many js files to one with yuicompressor I have 2 js files: test1.js and test2.js. I want to minify it with yuicompressor to one file.
I tried:
./yuicompressor-2.4.7.jar --nomunge test1.js test2.js -o test3.js

But there is only one file in test3.js. How can i minify multiply files to one?
Thank you.

A: Merge them first using either:

*

*copy and paste to a new file

*script in the editor you're using collecting the file contents to a new file

*use a file join command from command line or batch file

Then apply the the YUI compressor.


text:
Q: Move index on iframe I'm doing some test with iframe.
I've done a scene, from aframe demo, with 4 buttons.
Every button change the background.
This is a snipped of body

      <audio id="click-sound" crossorigin="anonymous" src="https://cdn.aframe.io/360-image-gallery-boilerplate/audio/click.ogg"></audio>

I've got few questions

*

*Is it possible to split the 4 "buttons" and set them in different positions?

*Is it possible, instead of change bk, open an url?

A: *

*Yes, you can move the buttons out of the wrapper entity and position them anywhere in space. Currently, the layout component aligns them in a line with a margin of 1.5 meters. Like .

*Currently, the set-image component is handling the background change. Try going into that component's JS and changing the image swapping code to a URL swapping code (window.location.href = data.url).


text:
Q: Sorting order of teams in league table by direct matches between teams in dart & flutter I am creating league table simulator (4 teams in table) - user can put scores and table is updating (i use provider to get data from user).
I want sort order of teams in table by few factors:

*

*number of points

*goals difference

*goals scored

*direct matches between teams who have this same values in earlier factors.

For first three i have sorting method but how to compare direct matches between teams? It is not one value like in the other keys and it depends on which teams will we compare. Is there any rational way for it?
const keys = ['points', 'goalsdifference', 'goalsfor'];

final mapsort = Map.fromEntries(
  points.entries.toList()
    ..sort(
      (b, a) {
        int index = 0;
        String currentKey = keys[index];
        while (a.value[currentKey]!.compareTo(b.value[currentKey]!) == 0 &&
            index < keys.length - 1) {
          ++index;
          currentKey = keys[index];
        }
        return a.value[currentKey]!.compareTo(b.value[currentKey]!);
      },
    ),
);

Map where that data is:
 Map<dynamic, dynamic>? points = {
   'Team1': {
     'points': simulator.data.team1points,
     'goalsfor': simulator.data.team1goalsfor,
     'goalsagainst': simulator.data.team1goalsagainst,
     'goalsdifference': simulator.data.team1goalsdifference
       },
   'Team2': {
     'points': simulator.data.team2points,
     'goalsfor': simulator.data.team2goalsfor,
     'goalsagainst': simulator.data.team2goalsagainst,
     'goalsdifference': simulator.data.team2ogoalsdifference
       },
   'Team3': {
     'points': simulator.data.team3points,
     'goalsfor': simulator.data.team3goalsfor,
     'goalsagainst': simulator.data.team3goalsagainst,
     'goalsdifference': simulator.data.team3goalsdifference
       },
   'Team4': {
     'points': simulator.data.team4points,
     'goalsfor': simulator.data.team4goalsfor,
     'goalsagainst': simulator.data.team4goalsagainst,
     'goalsdifference':simulator.data.team4goalsdifference
       },
     };

This is how it looks in my class for team number 1 (this same is for another teams):
int scoreEqualityValue(left, right) => left == right ? 1 : 0;
int scoreBetterValue(left, right) => left > right ? 3 : 0;

team1match1 = team1match1  //this is number of goals for team1 in first match

team1match2 = team1match2

team1match3 = team1match3

team1points = scoreBetterValue(team1match1, team2match1) + scoreEqualityValue(team1match1, team2match1) + scoreBetterValue(team1match2, team3match2) + scoreEqualityValue(team1match2, team3match2) + scoreBetterValue(team1match3, team4match3) + scoreEqualityValue(team1match3, team4match3)

team1goalsfor = team1match1 + team1match2 + team1match3

team1goalsagainst = team2match1 + team3match2 + team4match3

team1goalsdifference = team1match1 + team1match2 + team1match3 - team2match1 - team3match2 - team4match3


text:
Q: What is the PID on ps -ef | grep certb I'm not technically sounded on ubuntu.
I'm trying to kill a process from terminal. I tried to find process ID using
ps -ef | grep certb
and killed as follows
ps -ef | grep certb | awk '{print $2}'
But it not seems working.
I have following response from ps -ef | grep certb
user  22354 10667  0 16:15 pts/0    00:00:00 grep --color=auto certb

I the above result which one is Process ID? 22354 OR 10667?
Any help will  be greatly appreciated

A: Let's suppose a process certb is currently running.
When you now run ps -ef | grep certb you get a list of processes
that contain the text certb somewhere.
The moment you run the command, there will be two such processes:
the process certb itself and the process grep certb.
That's why you may already have seen the following instead:
ps -ef | grep certb | grep -v grep

This grep -v grep is to further filter out the grep command
from the process list. There are other tricks to achieve the same
result, but this is the most commonly used one.
As for your actual question: The output of ps -ef shows the PID of
the process in the 2nd column and the PID of the parent's process
(aka PPID) in the 3rd column.


text:
Q: Get primary key from SqlAlchemy before commit the object I have been using sqlalchemy with postgres and dont know how to solve the issue bellow.
I want to get the value of primary key before commit to DB.
I have a class called process that has proc_id and another element called proc_num.
class process(db.Model):
    __tablename__ = 'tb_processos'
    proc_id = db.Column(db.Integer, primary_key=True, nullable=False,
                        autoincrement=True, unique=True)
    proc_num = db.Column(db.String(20))

For my reasons the proc_num must to be a String type.
When I create my object I want the proc_num receives the proc_id.
How is the best way to do this?
Sorry for my english :/
Thx

A: You can use flush() method, the changes aren't persisted permanently to disk, until you call commit():
p = process(proc_num=45)
db.session.flush(p)
p = process.query.filter_by(proc_num=45)
p.proc_id

# finally you can call commit
db.session.commit()


text:
Q: is it possible to Connect two Linux Machines via a Wireless Router to Transmit real-time voice? SO i am trying to connect two linux computers via a wireless connection (in this case my home router) and send real time speech signals ( bi-directional ). Both computers shall be able to receive speech signals and play them back through speakers and also record speech and send it to the other computer.
This whole process shall be done through UDP sockets and RTP( real time protocol ) since TCP would not work properly because of the re-transmission algorithms which exist in TCP/IP and are not desired.
I have the following code which has the functionality of the Echo between a server and client:
/*
    Simple udp server

*/
#include<stdio.h> //printf
#include<string.h> //memset
#include<stdlib.h> //exit(0);
#include<arpa/inet.h>
#include<sys/socket.h>

#define BUFLEN 512  //Max length of buffer
#define PORT 8888   //The port on which to listen for incoming data

void die(char *s)
{
    perror(s);
    exit(1);
}

int main(void)
{
    struct sockaddr_in si_me, si_other;

    int s, i, slen = sizeof(si_other) , recv_len;
    char buf[BUFLEN];

    //create a UDP socket
    if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
    {
        die("socket");
    }

    // zero out the structure
    memset((char *) &si_me, 0, sizeof(si_me));

    si_me.sin_family = AF_INET;
    si_me.sin_port = htons(PORT);
    si_me.sin_addr.s_addr = htonl(INADDR_ANY);

    //bind socket to port
    if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1)
    {
        die("bind");
    }

    //keep listening for data
    while(1)
    {
        printf("Waiting for data...");
        fflush(stdout);

        //try to receive some data, this is a blocking call
        if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1)
        {
            die("recvfrom()");
        }

        //print details of the client/peer and the data received
        printf("Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
        printf("Data: %s\n" , buf);

        //now reply the client with the same data
        if (sendto(s, buf, recv_len, 0, (struct sockaddr*) &si_other, slen) == -1)
        {
            die("sendto()");
        }
    }

    close(s);
    return 0;
}

and the client code :
/*
    Simple udp client

*/
#include<stdio.h> //printf
#include<string.h> //memset
#include<stdlib.h> //exit(0);
#include<arpa/inet.h>
#include<sys/socket.h>

#define SERVER "127.0.0.1"
#define BUFLEN 512  //Max length of buffer
#define PORT 8888   //The port on which to send data

void die(char *s)
{
    perror(s);
    exit(1);
}

int main(void)
{
    struct sockaddr_in si_other;
    int s, i, slen=sizeof(si_other);
    char buf[BUFLEN];
    char message[BUFLEN];

    if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
    {
        die("socket");
    }

    memset((char *) &si_other, 0, sizeof(si_other));
    si_other.sin_family = AF_INET;
    si_other.sin_port = htons(PORT);

    if (inet_aton(SERVER , &si_other.sin_addr) == 0)
    {
        fprintf(stderr, "inet_aton() failed\n");
        exit(1);
    }

    while(1)
    {
        printf("Enter message : ");
        gets(message);

        //send the message
        if (sendto(s, message, strlen(message) , 0 , (struct sockaddr *) &si_other, slen)==-1)
        {
            die("sendto()");
        }

        //receive a reply and print it
        //clear the buffer by filling null, it might have previously received data
        memset(buf,'\0', BUFLEN);
        //try to receive some data, this is a blocking call
        if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1)
        {
            die("recvfrom()");
        }

        puts(buf);
    }

    close(s);
    return 0;
}

i thought if I replaced the IP of the server by the destination computer WLAN IP ( 192.168.178.xxx) it should work but it doesn't.
Can anyone help me with some answers.


text:
Q: Ubuntu 12.04 displays a blank screen with no wallpaper and no refresh My system specs:
- Intel Core 2 Duo T7500@2.2GHz
- Graphic Card Intel Mobile GM965/GL960
Operating System - Grub Tripple Boot System:

*

*Ubuntu 12.04 with CairoDock 3.0.0 and Compiz Cube activated and working

*Ubuntu 11.04

*Windows 7

I updated my Ubuntu 12.04 - After this update I rebooted and was able to log in. There are no wallpapers showing and the main screen is not refreshing (this is when moving a window around the desktop there are drag-lines showing all over the screen). The only way to refresh is to activate the 3D cube. In addition the mouse-over activates inactive windows and when writing a letter moves the cursor wherever the mouse pointer is). Everything is working as before, except that I can not activate a second monitor to extend the desktop. This produces the following error:
Error: GDBus.Error:org.freedesktop.DBus.Error.UnknownMethod: No such interface `org.gnome.SettingsDaemon.XRANDR_2' on object at path /org/gnome/SettingsDaemon/XRANDR

Before the update no proprietary drivers were activated or necessary and everything was working perfectly (Unity 3D, Compiz Cube 3D, Wobbly Windows, Cairo Dock 3.0.0, Wallpaper Changer etc.).
I was already looking for a way to revert to the last update but there seems to be too many programs that were changed. I looked it up in the Update Change Log in
var/log/apt/history.log
Among the updates were

*

*Kernel Update to 3.2.0-56

*xserver-common i386 (3.4.2-Oubuntu 0.12, Oubunti 0.13)

*xsever-xorg-core i386 (1.11.4-Oubuntu10.13,1.11.4-Oubuntu 10.14)
This problems are very annoying and I am considering to reinstall Ubuntu 12.04 and avoiding the Kernel and Xserver updates! But before I do this I thought to raise the question here in order to get an answer how to fix this stupid problem more elegantly!  :-)
Oh, in case anybody asks, the other Operating Systems (Ubuntu 11.04 and Windows 7) are both still working without any problem because there is any hardware change or problem!
Any suggestions are highly welcome!!!

A: The same happened here under Ubuntu 13.04 after a recent update. Draglines appear on the desktop as if the process that draws the desktop background is broken. Desktop icons appear, the Unity menu appears, all else works.
Workaround: Enable the compiz-fusion wallpaper feature.

A: I had the same problem with screen refresh after updating a large number of apts on 12.04 (Precise).
The login screen was normal. After logging in, however, the login box would still be visible, with my desktop icons above it. The screen would then black out (icons still visible) and the refresh rate would be extremely slow. Window drag lines would be seen. There was no problem launching programs though.
I fixed this by launching CompizConfig and checking and unchecking options. Part of my screen was still visible as I did this, so I could see if the option had an effect on my screen. Finally I found that unchecking the "Wobbly Windows" option under "Effects" seemed to fix the screen refresh problem.


text:
Q: Cannot start terminal on Ubuntu 15.10 I have a problem with terminal. When I click on the "terminal" icon on the left side, nothing happens - cursor just stays in wait mode for a few seconds. I tried to reinstall gnome-terminal from tty, but it didn't help. How can I fix it?

A: If it doesn't work, use these:
1. Ctrl + Alt + F2
2. UXTerm
Go to Unity Dash Search and type in 'UXTerm'
3. XTerm
Go to Unity Dash Search and type in 'XTerm'
4. Look for terminal alternatives in Software Center

A: Terminal in itself is just another software to access a shell(Bash) there are many of these around gnome-terminal, konsole, xterm, rxvt, kvt, nxterm, and eterm.
try installing an alternative!
this is an alternative however it won't fix the issue!
I came across this which provides details on how to install gnome-terminal maybe you can try removing it and installing it again!
you can try this to fix a package, however you need to execute these commands from a terminal alternative!


text:
Q: MongoDB: How to delete all comments of a deleted post? I'm following Thinkster's MEAN stack tutorial (https://thinkster.io/tutorials/mean-stack), which doesn't tell how delete operations should be implemented.
I currently have the following schemas:
var PostSchema = new mongoose.Schema({
  title: {type: String, required: true, maxlength: 140},
  link: {type: String, required: true, maxlength: 300},
  comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});

var CommentSchema = new mongoose.Schema({
  body: {type: String, maxlength: 200, minlength: 1},
  post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }
});

I have an Angular factory for CRUD operations. I currently delete posts with the following factory method:
o.deletePost = function(id) {
  return $http.delete('/posts/' + id, null, {}
  }).success(function(res){
    $window.location.href = '/#/home';
    return res.data;
  });
};

And my router for delete looks like this:
// DELETE a post
router.delete('/posts/:post', function(req, res, next) {
    Post.remove({_id: req.params.post}, function(err, post) {
        if (err)
            res.send(err);

        res.json({ message: 'Successfully deleted' });
    });
});

Unfortunately, when I delete a post like this any related comments are left somewhere in the database. So, my question is how could I delete all comments related to a post while deleting that post?
I've tried to Google for the answer and it seems I should somehow use MongoDB's middleware. I've tried:
// Remove Post
module.exports.removePost = function(id, callback){
    Post.findById(id, function (err, doc) {
        if (err) {}

        doc.remove(callback);
    })
}

//Remove comments related to post
PostSchema.pre('remove', function(next) {

    this.model('Comment').remove({ post: this._id }, next);
});

But this doesn't do anything, since I don't know how to call it from my CRUD factory. Don't know if it would be right even if I did. So, any help would be welcome. :)

A: Mongoose middleware will be automatically triggered when you call remove() on a Mongoose document. The code in the delete route above won't trigger the middleware, because it's calling remove() on the model instead of the document (conversation about this here).
I think you have all the pieces, you just need to move them around. Keep the logic from your removePost() function and pre('remove') middleware, and incorporate the logic into your delete route:
// DELETE a post
router.delete('/posts/:post', function(req, res, next) {
    Post.findById(id, function (err, post) {
        if (err) res.send(err);
        post.remove(function (err, doc) {
            if (err) res.send(err);
            res.json({ message: 'Successfully deleted' });
        });
    })
});

I approach "deleting" differently though. Rather than actually deleting the document, I add a deleted field to my schemas and update that field to true on delete. In some cases it makes sense to actually delete the document, but this is something to keep in mind.

A: In case anyone's wondering what exactly solved my question, here are two different solutions:
The first one that works, suggested by gh0st, was changing my router for delete as follows:
// DELETE a post
router.delete('/posts/:post', function(req, res, next) {
    Post.remove({_id: req.params.post}, function(err, post) {
        if (err) {res.send(err);}

        Comment.remove({post: req.params.post}, function(err, post) {
        if (err) {res.send(err);}
        });

        res.json({ message: 'Successfully deleted' });
    });
});

The second one that also works, suggested by the holla, was changing my router for delete as follows:
// DELETE a post
router.delete('/posts/:post', function(req, res, next) {

    Post.findOne({ _id: req.params.post}, function (err, post) {
      if (err) {res.send(err);}

      post.remove(function (err) {
        if (err) {res.send(err);}

        res.json({ message: 'Successfully deleted' });
      });
    });
});

And then adding a pre hook to my schema file:
// Remove comments related to a post
PostSchema.pre('remove', function(next) {
    this.model('Comment').remove({ post: this._id }, next);
});


text:
Q: resultant demand rate in central depot from K local depots assume I have 1 disposable product (a pump for example). It fails according to exponential distribution.
plant 1 <----- local depot 1 <---
                                 |---- central depot
plant 2 <----- local depot 2 <---

local depot 1 & 2 are supplied from central depot. plant 1 inventory is supplied from local depot 1 and same is true for local depot 2 and plant 2 .
Each failure of pump creates a demand at a rate of $\lambda$.
My opinion is that even rates at plant 1 & 2 are exponential and each rate is same  as $\lambda$, one can NOT say that result demand rate at central depot is also exponential and rate is 2$\lambda$
my reason: distribution of demand of pump in central inventory will be something different than exponential
Am I correct? If I am not correct can you please explain at least basically why i am not correct? (for the details I can read sources over web)
thanks
regards

A: You are correct. The sum of identically distributed independent exponentially distributed variables is Gamma (or Erlang) distributed. See the Wikipedia article, or this earlier question: Sum of exponential random variables follows Gamma, confused by the parameters.


text:
Q: Erro: stack smashing detected Estou tendo o erro:

* stack smashing detected *:  terminated no meu programa

Uso o compilador g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0, aqui está o código:
#include    <iostream>

using namespace std;

int main()

{
    int C[3], F[3];

    int Ct,Ft;

    cin >> C[3] >> F[3];

    Ct = (C[1] * 3)+C[2];
    Ft = (F[1] * 3)+F[2];

    if ((Ct > Ft) || (Ct == Ft && C[3] > F[3]))
    {
        /* code */
        cout << "C" << endl;
    }else if ((Ft > Ct) || (Ft == Ct && F[3] > C[3]))
    {
        /* code */
        cout << "F" << endl;
    }else
    {
        cout << "=" << endl;
    }

    return 0;
}

A entrada que coloco é : 10 5 18 11 1 18, deveria retornar C, mas ele retorna F.

A: Esse código não faz sentido. Está declarando dois arrays (do jeito do C e não do jeito do C++) com tamanho 3 cada. Então os elementos vão do 0 ao 2 em cada.
Em seguida manda ler dados no console e manda guardar na posição 3 de cada array, só que essa posição não está reservado para ele, então está esmagando a pilha onde deveria ficar esse dado. Pode não dar problema em alguma situação, mas poderia dar em outra, é perigoso. Provavelmente queria guardar o dado na posição 2, que é a última.
Depois pega dados contidos na posição e 1 e 2 do array, provavelmente queria pegar a 0 e 1. Mas mesmo que conserte isso ainda é um problema porque essas posições não foram inicializadas, então pegará lixo da memória e o cálculo provavelmente dará o resultado errado.
Além de resolver o problema do limite do array precisaria resolver a questão conceitual do cálculo.


text:
Q: Polly -how do I log final error and continue? I'm trying to set up Polly in .Net Core 3.1 (Azure Functions v3).
I want to create a Policy in the Startup class which I can inject into functions.
The behaviour that I'm looking for is:
It should wait And retry 3 times - if the final try fails - it should catch and log the exception (Serilog) otherwise just continue.
At the moment I have the following piece of code:
AsyncRetryPolicy emailRetryPolicy = Policy.Handle<Exception>()
    .WaitAndRetryAsync(3, retryAttempt =>
     TimeSpan.FromMilliseconds(retryAttempt * 500));

As you see I miss the part where it logs the error after 3 tries - and just continue. Any Idea how to do that?
Serilog is also added in Startup class (Partial code shown)
builder.Services.AddLogging(al => al.AddSerilog(logger));

I'm going to send an email with MailKit and want to log if it for some reasons fails. It should not stop the program for running.

A: The retry policy works in the following way:

*

*It tries to execute the action

*

*If it fails and the policy handles it then it will wait a predefined amount of time before it makes the next try

*It if fails and the policy does not handle it then it will return with the original value (which can be an exception)

*After the max retries has been reached (1st initial attempt + n retry attempts) and it still fails then it will return with the original value

Depending on your business logic, which you would like to wrap with this retry policy, you have the following two options:

*

*If it is a function, then you can use a Fallback policy. (Obviously if you can provide a fallback value.) In your Fallback you do the logging and then return with the fallback value. You can chain these two policies with the Policy.WrapAsync, but be aware of their order.

Sample fallback policy:
var fallbackPolicy = Policy<YourResponse>
    .Handle<Exception>()
    .FallbackAsync( (ct) =>
    {
         logger.LogError("Operation has been failed after several retries ...");
         return Task.FromResult(new YourResponse { ... });
    });

var combinedPolicy = Policy.WrapAsync(fallbackPolicy, retryPolicy);

*If it a method then you can use the onRetryAsync callback of the AsyncRetryPolicy
Sample retry policy:
var retryPolicy = Policy
    .Handle<Exception>()
    .WaitAndRetryAsync(
        settings.RetryCount,
        _ => TimeSpan.FromMilliseconds(settings.SleepDurationInMilliseconds),
        onRetryAsync: (ex, count, context) =>
            logger.LogError("Operation has been failed after several retries ...");
    );

I would like to emphasize that retry policy is designed for idempotent operations. Any service call, which might send an e-mail as a side-effect is not an idempotent operation.

A: Also had that issue and it took me some time to figure this out, so sharing my solution here.
It's important to note that the order of policies wrapped matters
My case:
var retryPolicy = Policy
    .Handle<EmptyResponseException>()
    .Or<Exception>()
    .Or<HttpOperationException>()
    .WaitAndRetryAsync(
        retryCount: 3,
        sleepDurationProvider: _ => TimeSpan.FromSeconds(3),
        onRetryAsync: (e, i) => LogHandler.WarningAsync("Retrying due to " + e.Message + " Try " + i + " next."));
var fallbackPolicy = Policy.Handle<EmptyResponseException>()
    .Or<Exception>()
    .Or<HttpOperationException>()
    .FallbackAsync
    (
        async ct =>
            {
                await Task.FromResult(true);
                await LogHandler.CriticalAsync("i'm a fallback action");
                /* do something else async if desired */
            },
        async ex =>
        {
            await LogHandler.CriticalAsync("i'm an actual fallback");
            //throw ex; <<< if you throw here, the fallback action won't happen
        }

    );

_policy = Policy.WrapAsync(fallbackPolicy, retryPolicy);

Result:

It doesn't quite matter what the fallbackPolicy or retryPolicy are in my case, but if I were to use this instead:
_policy = Policy.WrapAsync(retryPolicy, fallbackPolicy);

We'd get the fallback execute first, and the retry wouldn't work:


text:
Q: What would be the purpose of having a static method? While not positive, I'm pretty sure the static keyword makes methods and fields belong to a class and not an instance of a class. For fields, this makes sense to me, as static fields become global variables essentially. For methods though, I don't understand why it would be advantageous or hurtful to make a static method.
For example, what would be the difference between:
class RandomClass {
  public static void Method() {
    Console.WriteLine("Hello World");
 }
}
class Program {
 static void Main(string[] args) {
  RandomClass.Method();
 }
}

and
class RandomClass {
  public void Method() {
    Console.WriteLine("Hello World");
 }
}
class Program {
 static void Main(string[] args) {
  RandomClass randomObject = new RandomClass();
  randomObject.Method();
 }
}

A: A static method in C# is a method that keeps only one copy of the method at the Type level, not the object level. That means, all instances of the class share the same copy of the method and its data. The last updated value of the method is shared among all objects of that Type.
Reference: https://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/static-methods-in-C-Sharp/#:~:text=A%20static%20method%20in%20C%23,all%20objects%20of%20that%20Type.


text:
Q: PHP - Multiple bind_params Failing I'm trying to execute delete SQL statement upon button press, which was working if I binded 1 parameter, but I want to make the delete.php generic, as not to have multiple of them just for referencing different tables:
<?php
include "header.php";
include "db.php";

$_POST['table'] = "customer";
$_POST['column'] = "cID";
$_POST['del_id'] = 26;

if(isset($_POST['del_id']))
{
    if ($stmt = $conn->prepare("DELETE FROM customer WHERE ? = ?"))
    {
        $stmt->bind_param('si', $_POST['column'], $_POST['del_id']);
        $stmt->execute();
    }
    else echo("Oops");
}

This binding executes but doesn't do anything to the table, only binding the final value 'del_id', executes correctly, and binding 3 arguments including the table name, just causes prepare() to fail.
I am setting the _POST vars in other places from AJAX POSTs, above is just for testing that this bit works or not. I also haven't gotten round to doing validation yet before that comes up.
Very PHP nooby, likely a simple mistake, or just something I'm not aware of, in which case I'd be rather curious as to why the table/column names can't be parameterised, as it's been eluding me for some time. As a workaround, would some form of concatenation work instead, to be able to drop dynamic names into this query from multiple different places?

A: Yes, to achieve this you will need to have a combination of concatenation and parameters for the Prepared Statement:
if ($stmt = $conn->prepare("DELETE FROM " . $_POST['table'] . " WHERE " . $_POST['column'] . " = ?"))
    {
        $stmt->bind_param('si', $_POST['del_id']);
        $stmt->execute();
    }

Make sure you pay attention on additional validations you will need on the table and column names. This should be validated against your data model and not just making sure its a valid identifier. Further, take a look at some ORMs/Query Builders to learn how to elaborate upon this idea. It's a good learning exercise.

A: You should validate both the table name and column name before running the delete.
Since you can't prepare either the table or column names, just put them in the sql statement before the prepare.
<?php
    include "header.php";
    include "db.php";

    $_POST['table'] = "customer";
    $_POST['column'] = "cID";
    $_POST['del_id'] = 26;

    //  Add code to prevent SQL injection
    $table = $_POST['table'] == 'customer' ? $_POST['table'] : '';
    $column = $_POST['column'] == 'customer' ? $_POST['column'] : '';

    if(isset($_POST['del_id']) && $table != '' && $column != '') {
        if ($stmt = $conn->prepare("DELETE FROM `".$table."` WHERE `".$column."` = ?"))
        {
            $stmt->bind_param('i', $_POST['del_id']);
            $stmt->execute();
        }
        else echo("Oops");
    }


text:
Q: PIC 16f877A C program for ADC averaging For the need of more accuracy in my adc value, I have to average the adc value for particular time, what are the types of techniques handled in the averaging Can anyone help me with the example C programs for different types of averaging techniques PIC 16f877A.

A: First of all, if your input is noisy, you can simply take a number of readings inside a tight loop, say 10, and use the average value from that as your reading.
To average over a period of time, you want to use a rolling average, such as implemented by the following code.  Readings are added to an array, and then the average of all the readings is computed and returned.  I did not include the initialization of the ADC module, and the ADC channel is hard-coded as 0.
Because of the limited register size of the PIC16, I am using #if statements to select the smallest variable sizes possible (i.e. unsigned char index if array is less than 256).
#define MAX_ADC_VALUES  20
#define ADC_CHANNEL  0

unsigned short adcValues [MAX_ADC_VALUES];   // array of ADC readings
#if MAX_ADC_VALUES < 256
unsigned char adcValueIndex = 0;       // current index into array
#else
unsigned short adcValueIndex = 0;
#endif
unsigned char fullArray = 0;       // set to 1 after we have filled array

// call this on a periodic basis
unsigned short getAveragedAdcReading()
{
#if MAX_ADC_VALUES < 256
unsigned char i;
#else
unsigned short i;
#endif
unsigned short adcReading;         // latest reading from ADC
#if MAX_ADC_VALUES < 66
unsigned short adcAverage;         // 10-bit ADC; sum of 65 readings just fit in an unsigned  short
#else
unsigned long adcAverage;
#endif

    // if your input is noisy, then add a loop here to take several readings in a row and average
    ADCON0bits.CHS = ADC_CHANNEL;  // channel set here
    ADCON0bits.GO = 1;             // start ADC conversion
    while (ADCON0bits.nDONE);      // wait till ADC conversion is over

    adcReading = (ADRESH<<8) + ADRESL ;   //merge the MSB and LSB of the result
    adcValues[adcValueIndex++] = adcReading;    // overwrite oldest reading with newest one

    adcAverage = 0;
    for (i=0; i < MAX_ADC_VALUES; i++)
    {
        adcAverage += adcValues[i];
    }
    if (fullArray)
    {
        adcAverage /= MAX_ADC_VALUES;          // get average of MAX_ADC_VALUES readings
    }
    else
    {
        adcAverage /= adcValueIndex;          // use this if array not filled yet
    }

    if (adcValueIndex >= MAX_ADC_VALUES)
    {
        adcValueIndex= 0;          // if at end of array, loop around
        fullArray = 1;             // we have now filled array, can divide by MAX_ADC_VALUES from now on
    }

    return (unsigned short)adcAverage;    // cast only needed if adcAverage is unsigned long
}

A: Have a look at this book: The Scientist and Engineer's Guide to Digital Signal Processing
It is available completely free of charge online on: http://www.dspguide.com/pdfbook.htm
You should take a look at Chapter 15: Moving Average Filters. It is a very simple, yet powerful  technique to increase the accuracy of your ADC.


text:
Q: Finding quadratic factors Show that $(x-√3)$ and $(x+√3)$ are factors of $x^4+x^3-x^2-3x-6$. Hence write down one quadratic factor of $x^4+x^3-x^2-3x-6$, and find a second quadratic factor of this polynomial.
My attempt:
$f(x)=x^4+x^3-x^2-3x-6$
$f(3^\frac12)=(3^\frac12)^4+(3^\frac12)^3-(3^\frac12)^2-3(3^\frac12)-6=0$
$f(-3^\frac12)=(-3^\frac12)^4+(-3^\frac12)^3-(-3^\frac12)^2-3(-3^\frac12)-6=0$
I know the first quadratic factor is $x^2-3$ but I don't know how to arrive to the second quadratic factor.

A: You can solve all the questions in one formula: since you correctly identified $x^2-3$ as the quadratic factor, try polynomial long division by $x^2-3$. This will
a. prove that $\pm \sqrt{3}$ are roots of the polynomials (since the remainder is zero),
b. give the other quadratic factor (as the quotient).

A: We know that there exist $a,b$ with
$$
x^4+x^3-x^2-3x-6=(x^2-3)(x^2+ax+b),
$$
and comparison of the coefficients on both sides immediately gives $a=1$ and $b=2$.

A: Lets try it like this:

*

*Suppose $(x+ \sqrt3)(x-\sqrt3)$ are both factors.

*Expand the expression above to get $x^2 - 3$.

*Perform polynomial long division with $x^2 -3$.

*You will get $x^2 + x + 2$ as the second quadratic factor.

*Re-expanding the quadratic factors $(x^2 -3)(x^2 +x+2)$ gives the     original quartic polynomial. I uploaded a picture of my work with this reply.


text:
Q: Can you tell me which method should be called in inheritance in java?    Class A {
    dog()
   }
   Class B extends A {
    cat()
   }
   public static void main(String args[]) {
    A obj1 = new A();
    B obj2 = new B();
    A obj3 = new B();
   }

when class A object is created then obj1 will call dog(),whenClass B's object is created then obj2 will call cat() and dog().but A obj3= new B() is created which method should be called?please answer
Thanks

A: To give a quick and dirty answer, from what I think you mean:
Both methods CAN be called. (In your example, neither method WILL be called because, excluding the other errors, you aren't actually calling any of the methods)
I won't get fully into polymorphism but I will try my best:
If you have:
Class A {
    public void doSomething() {
        System.out.println("Bark!");
    }
}

and
Class B extends A{
    public void doSomething() {
        System.out.println("Meow!");
    }
}

and I do
public static void main(String[] args) {
        A obj1 = new A();
        B obj2 = new B();
        A obj3 = new B();

        // And you want to see what happens when you do:
        obj1.doSomething();
        // Prints Bark!
        obj2.doSomething();
        // Prints Meow!
        obj3.doSomething();
        // Prints Meow!
}

Notice that the important thing here is that BOTH classes have the exact same name for the method, even
though it does different things!
That is the (I think) key concept to polymorphism you are trying to understand: You
can redefine what a method does in a subclass! HOWEVER, to redefine a method, the method has to have the same
name! Then, the compiler will pick the version of the method that is defined at the lowest level.
In your example
Class A {
    public void dog() {
        System.out.print("Dog!");
    }
}
Class B extends A {
    public void cat() {
        System.out.println("Cat!");
    }
}

public static void main(String args[]) {
    A obj1 = new A();
    B obj2 = new B();
    A obj3 = new B();

    obj1.dog()
    // This is the only method class A has, as that is what you defined. It will print Dog!
}

However, B defines its own method, called cat(). So you can do b.cat().
BUT DON'T FORGET: B also extends A, so what A has, B also has.
So you can also call b.dog()!
obj3 since it is linked to a new B() can call both dog() AND cat().
If they were named the same thing, obj3 would call the version of the method defined in class B.
 However, in your case, they are two seperate methods, one is NOT overriding the other.
To answer your question.
If we return to my code, calling
     A obj3 = new B();
obj3.doSomething();
// Prints Meow!

This is because we defined obj3 as a new B() so it takes on the method doSomething() in they way class B defines it.


text:
Q: Getting values from Elastic-Stack I'll initial get dates from elastic stack.
At first just any data set, just to proof it works.
I set up the connection and than I try to get a data set.
I show you my code and the error message below.
You got any suggestions where to look for the missing values?
Thanks, Frank

            string elasticSearchConnectionString = configuration.GetConnectionString("ElasticSearchConnection");
            string elasticSearchIndex = configuration.GetValue<string>("ElasticSearchIndex");
            Uri uri = new Uri(elasticSearchConnectionString);
            ConnectionSettings settings = new ConnectionSettings(uri).DefaultIndex(elasticSearchIndex);
            ElasticClient = new ElasticClient(settings);
            IGetResponse<_doc> result = ElasticClient.Get<_doc>(1);

Invalid NEST response built from a unsuccessful low level call on GET: /hybif/_doc/1
  Audit trail of this API call:
   - 1 BadResponse: Node: http://10.211.226.31:9200/ Took: 00:00:00.3149405
   OriginalException: Elasticsearch.Net.ElasticsearchClientException: Request failed to execute. Call: Status code 404 from: GET
  /hybif/_doc/1

  Request:

  force it to be set on the response.>

  Response:

  ConnectionSettings to force it to be set on the response.>
00:00:00.3149405
   OriginalException: Elasticsearch.Net.ElasticsearchClientException: Request failed to execute. Call: Status code 404 from: GET /hybif/_doc/1
   Request:

   Response:

A: That works now...:
The search at my RecordsRepository.cs:
        var result = ElasticClient.Search<_doc>(document =>
            document
            .Query(q => q
                .Match(m => m
                    .Field(f => f.DataRecordId)
                    .Query(search)
                )
            )
        );

and the _doc.cs:
public class _doc
{
    [JsonProperty("contextName")]
    public string ContextName { get; set; }

    [JsonProperty("resourceId")]
    public string ResourceId { get; set; }

    [JsonProperty("componentId")]
    public string ComponentId { get; set; }

    [JsonProperty("processStepId")]
    public string ProcessStepId { get; set; }

    [JsonProperty("dataRecordId")]
    public long DataRecordId { get; set; }

    [JsonProperty("timestamp")]
    public object Timestamp { get; set; }

    [JsonProperty("value")]
    public double Value { get; set; }
}


text:
Q: Привязка к статическому идексатору У меня возникла проблема с привязкой статического свойства в XAML.
Руководствовался данным ответом.
В классе у меня определена статическая переменная:
class Worker
{
    public static ObservableCollection<int> CountInDirections { get; set; }
    static Worker()
    {
        CountInDirections = new ObservableCollection<int>
        {
            0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
        };
    }
}

Но в XAML коде появляется следующая ошибка:
Член "CountInDirections[6]" не распознан или недоступен.

Вот что в XAML:
<Label Content="{Binding Path=(local:Worker.CountInDirections[6])}"/>

Ошибка появляется при обращении по индексу.
Как исправить?

A: Для доступа по индексу к статичной коллекции при привязки следует воспользоваться следующим способом:
<Window.Resources>
    <local:Worker x:Key="WorkerQ"/>
</Window.Resources>
...
<Label Content="{Binding Source={StaticResource WorkerQ}, Path=CountInDirections[6]}"/>

A: Попробуйте так:
{Binding Path=(local:Worker.CountInDirections)[6]}


text:
Q: Simplifying circuit Can someone help me understand why the circuit has been simplified as seen in the picture?

A: There is an implicit assumption: that we are only connecting at points A and B.
The two circuits are not the same if you connect at X and Y (and lots of other nodes).
Circuit 1.

simulate this circuit – Schematic created using CircuitLab
Circuit 2.

simulate this circuit
If we're considering the only connections to be at A and B, then it's easy to reduce circuit 1 into circuit 2.  As said in comments, you can start with circuit 2, easily see that a voltage applied across A and B will produce the same voltage at X as at Y.  And so as no current will flow, regardless of the resistance R4 so you can add whatever you like.
Circuit 3.

simulate this circuit
Connected across A and B you can see Circuit 3 is the same as the previous two.

A: By symmetry the voltages across the resistors which are omitted in the simplified circuit are zero, so the resistors can be removed without affecting the behavior at the terminals. No calculations are necessary.

A: It is symmetry because of which voltage across nodes 1 and 3 and voltage difference between nodes 2 and 4 is zero. No current flows between them and the connections between nodes 1-3 and 2-4 become open circuits. Therefore, the resistors between nodes 1-3 and 2-4 can be removed.

A: My initial thought is to take a look at the Δ-Y transform shown in this Wikipedia article. This assumes that there is additional circuitry that you haven't included in your original images. If you perform the appropriate transform operations on each edge, my guess is that you'll see the result you're expecting pretty quickly.


text:
Q: Exactness of a pairing and the trace morphism If $X\longrightarrow S$, where $S=\operatorname{Spec}(k)$, is a proper smooth morphism of dimension $p$ between $\mathbb{F}_{p}$ schemes with Frobenius $F$, then there is an exact pairing $\wedge:\Omega^{i}(M)\times\Omega^{n-i}_{X/S}\longrightarrow\Omega^{n}_{X/S}$.
I am currently reading Deligne and Illusie's paper (https://eudml.org/doc/143480), and I am stuck on page 255. The authors make the claim that the above-mentioned exact pairing induces another one
\begin{equation*}
F_{*}\Omega^{i}_{X/S}\times F_{*}\Omega^{p-i}_{X/S}\longrightarrow F_{*}\Omega^{p}_{X/S}\longrightarrow H^{p}F_{*}\Omega^{\bullet}_{X/S}\longrightarrow\Omega^{p}_{X/S}
\end{equation*}
They make the claim that the last morphism (the inverse of which they construct a few paragraphs earlier) "is just the trace morphism" and that the exactness of the pairing somehow follows from this claim. I don't quite get what they mean by that and why that pairing is exact. Can somebody please explain it to me in as much detail as possible?


text:
Q: How to compile new source code in vuejs boilerplate using webpack I'd like to ask you something easy which is difficult for me.
It's about vuejs compile based on webpack.
I am a newbie in vuejs especially in this boilerplate(https://github.com/chrisvfritz/vue-enterprise-boilerplate).
I want to make an app based on this boilerplate.
I installed this boilerplate and then added "vuetify" (responsive GUI plugin) to make an app. With responsive UI
it was not easy but finally they are working together.
Image showing vue and vuetify working together
When i added vuetify, helloWorld.vue is also added in ./src/components automatically,
but it is not complied (transpiled) so whenever i run "yarn dev" to launch dev server,  I see a message like below:

./HelloWorld in
./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/app.vue?vue&type=script&lang=js&

I want to know how I can compile HelloWorld.vue and make it included in output file like app.js.
Additionally, moving HelloWordl.vue to ./src was not working as well.
I just want to know small hints for that.
Thanks in advance.
June, Chung

A: I found out the reason.
I added statement like this in app.vue

import HelloWorld from './components/HelloWorld'

it made an error( it must be ./components/HelloWorld.vue )
I thought it is okay when I import the component without its extension.


text:
Q: getting 404 even aftr 48 hours - azure VM and azure CDN I have a LAMP based wordpress installation running on an azure VM. its working fine and publicly accessible.
I wanted to try azure CDN - Verizon for serving my images.
I made cdn, using the new resource manager, added my endpoint of filmycurry.com (my origin server). I am using http only, hence configured the same in endpoint.
My problem is that even  after 48 hours. I still cant access any media using cdn. you may try the below links
working - vm based - http://filmycurry.com/wp-content/uploads/2016/05/yu-2.jpg
not working cdn - http://filmycurry.azureedge.net/wp-content/uploads/2016/05/yu-2.jpg
pls note, I had also configured the path correctly to /wp-content/uploads, since beginning.


text:
Q: Python if statement delay I am trying to make a 'game' while learning about both Python and GPIO on the Raspberry Pi. This is what I have ATM:
while playing == 1:
        if (GPIO.input(9) == 0):
            GPIO.output(18, GPIO.LOW)
            print("Well done!!")
            time.sleep(1)
        else:
            print("Wrong!")
            lives = lives - 1
            time.sleep(1)
        playing = 0

Now, my problem is that the program is hitting the if statement and is going straight to the else (as you would expect), however, I want the program to wait on the first part of the if statement for a second, then go to the else.
Thanks in advance!

A: Perhaps you could rewrite it like so:
while playing == 1:
   for _ in range(10):
       if GPIO.input(9) == 0:
           GPIO.output(18, GPIO.LOW)
           print("Well done!!")
           break
       time.sleep(0.1)
   else:
       print("Wrong!")
       lives = lives - 1

This polls the GPIO pin ten times 100ms apart. The else is hit if the GPIO pin stays high throughout the ten attempts.
(If you haven't come across Python's for-else construct, see Why does python use 'else' after for and while loops?.)
Alternatively, you could use GPIO module's more advanced features, such as edge detection and callbacks. See the documentation.