text:
Q: Invalid argument supplied for foreach() with multiple select I have a html form which has a select list box from which you can select multiple values because its multiple property is set to multiple.
    ¿Quieres agregar complementos?

    <?php
       $sql = "SELECT * FROM complementos";
       $ejecutar = $conn->query($sql);
    ?>

    <select class="form-control select2" multiple="multiple" name="complementos" data-placeholder="Seleccione el/los complementos" style="width: 100%;">

        <?php while ($complemento = $ejecutar->fetch_assoc()): ?>

           <option value="<?php echo $complemento['complemento'] ?>"><?php echo $complemento['complemento'] ?></option>

        <?php endwhile; ?>
    </select>

PHP:
$tipo = $_POST['tipo'];
$nombre = $_POST['nombre_cotizar'];
$mail = $_POST['email_cotizar'];
$telefono = $_POST['telefono_cotizar'];

$complementos = array();

foreach ($_POST['complementos'] as $complemento){
    $complementos [] = $complemento;
}

$resultado_complementos = implode(", ", $complementos);

$mensajeMail = "De: $nombre \nCorreo: $mail \nTeléfono: $telefono \n\nTipo: $tipo \n\nComplementos: $resultado_complementos \n";

mail($destino, "Presupuesto", $mensajeMail);

try {
    $sql = "INSERT INTO Cotizar (Tipo, Adicionales, Nombre, Mail, Telefono) VALUES (?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('sssss', $tipo, $resultado_complementos, $nombre, $mail, $telefono);
    $stmt->execute();
    if($stmt->affected_rows){
        $respuesta = array(
            'respuesta' => 'exito'
        );
    } else{
        $respuesta = array(
            'respuesta' => 'error'
        );
    }
} catch (Exception $e) {
    $respuesta = array(
            'respuesta' => $e->getMessage()
        );
}
die(json_encode($respuesta));

I want to add the option values in a string to save it on the db and send it via email


text:
Q: Line break in Jade/Express within a conditional I need to output plain text in a jade layout (using express) and I need it to appear on separate lines like so -
Hello
There
World"0"
World"1"
World"2"

I would have thought I could do it like this - (jade template coming up)
|Hello
|There
- for (var i=0; i<3; i++)
  |World"#{i}"

But instead this gives me
Hello
ThereWorld"0"World"1"World"2"

For the life of me, I cannot understand how to do a line break within a conditional loop! This is not meant to be HTML text, its plain text for CSV binary output, so the breaks are important and so are the double quotes as well as the escaping to prevent tags.
Is it not possible to do this in Jade? I don't have much experience in Jade, so I'd appreciate any help at all from the experts out there. Thanks!

A: Try this:
- for(var i = 0; i < 3; i++)
    = World + "\n"

A: I've updated the OP to include dynamic variables and double quotes, the stuff I really need.
Played around with the suggestion from @Amberlamps and came up with this for an answer -
|Hello
|There
- for (var i=0; i<3; i++)
  ="\n"
  |World"#{i}"

I'm sure there are other variants to this solution, but this one works for me.
If I ever need to do more advanced templating, I'll definitely check out Moustache or Handlebars - Jade and its docu just doesn't do it for me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does every odd prime power divide a number of the form $\ n^{n-1}+n-1\ $? A conjecture motivated by a factoring project :

For every odd prime power $\ P\ $ , there is an integer $\ n>1\ $ such that $\ P\mid n^{n-1}+n-1\ $. In other words , every odd prime power divides some number of the form $n^{n-1}+n-1$.

Can we prove this conjecture ?
Every prime power $\ p^k\le 10^7 $ with an odd prime $p$ and an integer $\ k>1\ $ satisfies the conjecture which I found out with a brute force search. For the primes however, I only arrived at about $\ P=500\ 000\ $.
I noticed no nice pattern to find a suitable $\ n\ $quickly, so I need (in the case it is too hard to prove the conjecture) a more efficient method to find a suitable $\ n\ $ so that I can at least extend the search limit significantly.
The conjecture is false for arbitary odd numbers $\ P\ $. A counterexample is $\ 171\ $.

A: For $p$ an odd prime this is always true. Take $n$ such that $n\equiv 2\pmod{p-1}$ and $n\equiv\frac{p+1}{2}\pmod p$; this is always possible by the Chinese remainder theorem. Now we have $n-1\equiv 1\pmod{p-1}$, and so $n^{n-1}\equiv n\pmod p$ by Fermat's little theorem. So $n^{n-1}+n-1\equiv 2n-1\equiv p$.
For $P$ a nontrivial prime power this approach (via Euler-Fermat) doesn't work because $P$ and $\phi(P)$ are not coprime.

A: For the case of prime powers, I think we can use induction to find solutions $n$ that are congruent to $2$ mod $p-1$. Let $p$ be an odd prime number, $k \geq 1$, and let $n$ be a positive integer such that $p^k|n^{n-1}+n-1$ (so $n$ and $p$ are coprime) and such that $n=2$ mod $p-1$.
Now, write $m=n+sp^k$ for a positive integer $s$ divisible by $p-1$: then $C=m^{m-1}+m-1$ is congruent mod $p^{k+1}$ to $m^{n-1}+n+sp^k-1$, so $C$ is congruent to $n^{n-1}+(n-1)sp^kn^{n-2}+n+sp^k-1$ mod $p^{k+1}$.
Thus, if we write $n^{n-1}+n-1=tp^k$ for some integer $t$, $p^{k+1}|C$ iff $p^{k+1}|tp^k+(n-1)n^{n-2}sp^k+sp^k$ iff $p|t+(1+(n-1)n^{n-2})s$. If $1+(n-1)n^{n-2}$ is coprime to $p$, then we're done. But $n-2$ can be chosen divisible by $p-1$ (by the accepted answer) so $1+(n-1)n^{n-2}$ is congruent to $n$ mod $p$ so is coprime to $p$.


text:
Q: jQuery AJAX call doesnt work on server side i have a jQuery AJAX webmethod in ASP.Net that works perfectly fine when tested locally. but when uploaded to the server, sometimes it works sometimes it doesnt. when i debugged the code with firebug i see the the webmethod gets called but jumps right away to the error section of the ajax script.
thats my second week of research and i still couldnt find anything to help me.
jQuery code:

the webmethod code is below:
<WebMethod(True)> _
    Public Shared Function GetSchedule(ByVal FinancialDate As String) As String
        Dim StoreNumber_ForWebMethod As String = ConfigurationManager.AppSettings("StoreNumberKey")
        Dim _SqlConnection As New SqlConnection("Data Source=INTRIS;Initial Catalog=*****;User ID=sa;Password=*****")
        Dim _SqlDataAdapter As New SqlDataAdapter("select h.magasin, h.employe, e.nom, h.datefinancier, h.debut, h.fin, h.totalheure, h.annee, h.semaine, h.evenement, h.etat, h.breakstart, h.breakend " _
                                                & "from web.dbo.hours h , web.dbo.employee e " _
                                                & "where h.employe = e.numero and h.magasin = " & StoreNumber_ForWebMethod & " and h.datefinancier = '" & FinancialDate & "'", _SqlConnection)
        Dim _DataSet As New DataSet
        Dim ScheduleBuilder As String = Nothing

        _SqlDataAdapter.Fill(_DataSet, "Schedule")

        If Not _SqlDataAdapter Is Nothing Then
            If _DataSet.Tables("Schedule").Rows.Count > 0 Then
                For i As Integer = 0 To _DataSet.Tables("Schedule").Rows.Count - 1
                    ScheduleBuilder += "
" _
                                    & "" & _DataSet.Tables("Schedule").Rows(i).Item("debut").ToString & "" _
                                    & "" & _DataSet.Tables("Schedule").Rows(i).Item("fin").ToString & "" _
                                    & "" & StrConv(_DataSet.Tables("Schedule").Rows(i).Item("nom").ToString, VbStrConv.ProperCase) & "" _
                                    & "" & _DataSet.Tables("Schedule").Rows(i).Item("debut").ToString & " - " & _DataSet.Tables("Schedule").Rows(i).Item("fin").ToString & "" _
                                    & "" & _DataSet.Tables("Schedule").Rows(i).Item("TotalHeure").ToString & " hrs" _
                                    & "

"
                Next
            End If
        End If

        Return ScheduleBuilder
    End Function

any help would be much appreciated
Update
is JSON and webmethods compatible with SQL Server 2000?

A: Answer
first i would like to thank @patmortech for guiding me in the right direction by showing me what was the error.
once i found out that, used firebug on firefox to debug the problem and it was a single quote missing for
Dim _SqlDataAdapter As New SqlDataAdapter("select h.magasin, h.employe, e.nom, h.datefinancier, h.debut, h.fin, h.totalheure, h.annee, h.semaine, h.evenement, h.etat, h.breakstart, h.breakend " _
                                            & "from web.dbo.hours h , web.dbo.employee e " _
                                            & "where h.employe = e.numero and h.magasin = **'" & StoreNumber_ForWebMethod & "'** and h.datefinancier = '" & FinancialDate & "'", _SqlConnection)

because it is a string.
problem solved :)


text:
Q: UIButton action doesn't work after some time (probably after some garbage collection) I have a UIView with around 60 buttons who call the same method. When clicking the buttons, I open different images by this method - I use button tags to know which button was called and which image to display. Think about it like a gallery.
As the drawing of the buttons was difficult, I used the Interface Builder for that and created a XIB with that UIView. I simply dragged the buttons at the correct spots and connected them to my method at event TouchUpInside. I used this to add the view to my main view:
NSArray *xibContents = [[NSBundle mainBundle] loadNibNamed:@"Tour" owner:self options:nil];
UIView *tour = [xibContents lastObject];
[self.view addSubview:tour];

So far so good, that works well at first glance. Unfortunately, there is some issue when the app has been used for some time. The buttons still highlight (so they are still here!) but there is no action called anymore. There just the highlight but no action.
I don't know why, but somehow the garbage collector seems to destroy the UIButton target. Why? How can I fix that?
Please note I haven't declared the buttons programmatically. I thought placing them in the IB would be enough.
Also I couldn't find a connection between memory warnings and the destruction of the UIButton targets. Memory warnings do appear in my app, but most of the time the buttons still work then.
But it has to be a garbage collector because the bug comes up totally randomly. There is no way to reproduce this error, sometimes it happens after 5 clicks, sometimes after 10 minutes spending in my app.

A: You could try loading your nib like this:
First, create an IBOutlet property in your header.  Then when you create the Nib, wire that UIView IBOutlet to the top level view in the Nib (the one everything sits on).  Then in your implementation, load it like this:
 [[NSBundle mainBundle] loadNibNamed:@"Tour" owner:self options:nil];
 // self.view if in a view controller
 [self addSubview:self.tourView];

My guess is that it might be something where the pointer to the button stops working, but not from garbage collection, as that does not happen
and to debug you might try something like:
 for (UIView* view in self.view.subviews)
     if ([view isKindOfClass:[UIButton class]])
     {
               if([self.view respondsToSelector:@selector(myIBAction:)]){
                   NSLog(@"it still sees the method");
                }

         NSLog(@"Button Rect: .2%f, .2%f, .2%f, .2%f", view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
      }

as I mention in the comments

A: This is the easiest way to add selectors to all of your buttons.
for (UIView* view in self.view.subviews)
    if ([view isKindOfClass:[UIButton class]])
    {
         //Add selector
    }

A: Re-setting the targets when things go awry is telling it to do the wrong thing slightly louder or more insistently.
You have to find the cause of this problem. Run Instruments (Build → Profile), choose the Allocations template and let your app startup. Run until the issue happens, then stop recording in Instruments by pressing the red recording button in the top left.
Select the Allocations instrument in the list at the left, change from Statistics to Objects List in the jump bar going across the window just below the timeline. You now have a row for every object to be allocated, retained, released and deallocated. Click the small arrow to see the history for each object. (Strictly speaking, it's for each memory address; many objects can reuse the same memory address over the app's run.) You can also filter by anything in the top right, unfold the right-hand sidebar for a full stack trace on what's selected and double click an entry to correlate with the source code.
There's a lot to learn about Instruments; check the documentation and search the web. But this will definitely tell you what's happening, so that you may reason about why it's happening or what's not happening.


text:
Q: TypeError: 'NoneType' object has no attribute '__getitem__' in Flask using SQLite3 EDIT: I found out what was causing NoneType error, sorry for bothering you.
In my code I want to open my records.db and get last index in it and then use this index as name of uploaded file (increased by one), but my method works only with normal python script, in Flask i get NoneType error..
Here is my code:
import os
import datetime
import subprocess
import sqlite3
import sys
from flask import Flask, render_template, request, redirect, url_for, g
from werkzeug import secure_filename

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'gro', 'doc', 'docx'])

DATABASE = 'records.db'

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
    return db

def get_id():
    cur = get_db().cursor()
    cur.execute('SELECT id FROM Records ORDER BY id DESC LIMIT 1;')
    number = cur.fetchone()
    filenum = int(number[0])
    return filenum + 1

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload', methods = ['POST'])
def upload():
    num = get_id()
    file = request.files['file']
    if file and allowed_file(file.filename):
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], num.filename))
        subprocess.call(['python', '/home/martyna/Dropbox/programowanie/project_firefox/topologia.py', 'uploads/'+num.filename])
        return "Thank you for uploading"

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0')

And this:         filenum = int(number[0]) causes my error. I would appreciate any help.
Full error trace:
Traceback (most recent call last):
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/martyna/Dropbox/programowanie/project_firefox/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/martyna/Dropbox/programowanie/project_firefox/hello.py", line 46, in upload
    filenum = int(number[0]) + 1
TypeError: 'NoneType' object has no attribute '__getitem__'

A: Probably, there is no element in your Records table. Therefore, cur.fetchone() returns None so you're effectively trying to access None[0], hence the error message.
The error message by the way is telling you that you take [0] of something which is None, so if you look at the line, the only thing that you're taking [0] of is number. So a good way to debug such problems is to add something like print number before the offending line, this often challenges some fundamental believes I have about the contents of my variables :)


text:
Q: Problems with app.yaml api_version migrating Google AppEngine from Go 1.9 to Go 1.11 At $DAYJOB we are using a Go 1.9-based AppEngine application. Now that Google is deprecating version 1.9, I am trying to move to 1.11, using the migration guide. It says that I should set runtime: go111 and remove the api_version: go1.9 value from app.yaml, but when doing so, I get an error message deploying:
ERROR: (gcloud.app.deploy) Staging command [/usr/lib/google-cloud-sdk/platform/google_appengine/go-app-stager /home/peter/src/licensemanager/src/web/app.yaml /home/peter/src/licensemanager/src/web /home/peter/tmp/tmpBB3Yk8/tmpQQPTFj] failed with return code [1].

------------------------------------ STDOUT ------------------------------------
------------------------------------ STDERR ------------------------------------
2019/08/21 07:59:20 invalid api_version value
--------------------------------------------------------------------------------

If I try to add it back, no matter what value I put in it, I get an error message:
╔════════════════════════════════════════════════════════════╗
╠═ Uploading 12 files to Google Cloud Storage               ═╣
╚════════════════════════════════════════════════════════════╝
File upload done.
ERROR: (gcloud.app.deploy) INVALID_ARGUMENT: The following fields are not allowed in app.yaml: api_version.

I am a bit at a loss here, what am I doing wrong?
Running locally with dev_appserver.py works fine.

A: I had mismatching SDK packages installed:
ii  google-cloud-sdk                    259.0.0-0       all          Utilities for the Google Cloud Platform
ii  google-cloud-sdk-app-engine-go      194.0.0-0       amd64        Go runtime for Google App Engine

Upgrading the mismatching packages fixed the issue. Thanks to @icza for the tip!


text:
Q: How to create DDL from output columns in SSIS I have DataFlow task which has been created programmatically,
The data source connected with DBMS via OLE DB Provider,
I can get output columns from the source and map then with input columns of destination component.
But I can't invoke ReinitializeMetaData() for destination component because destination table doesn't exist.
Therefore, I want to get DDL from output columns for creating the table.
Maybe, someone knows which functionality is provided in SSIS for this purpose?
Thanks in  advance


text:
Q: What logic can be used express Hilbert's axiomatization of Euclidian geometry? Can the first order logic be used to express Hilbert axioms for Euclidean geometry as well as all theorems that follow from them? If it is not the case, what logic can be used? Does it have a name? In what way is it more expressive than the first order logic?

A: The first four groups of Hilbert Axioms can be expressed in first order logic, the occurrences of sets are inessential in the first four groups. An example of a formalization is given in GeoCoq.
The fifth group consists of Continuity axioms:
Axiom of Archimedes:

If AB and CD are any segments then there exists a number n such that n segments CD constructed contiguously from A, along the ray from A through B, will pass beyond the point B.

Axiom of line completeness:

An extension (An extended line from a line that already exists, usually used in geometry) of a set of points on a line with its order and congruence relations that would preserve the relations existing among the original elements as well as the fundamental properties of line order and congruence that follows from Axioms I-III and from V-1 is impossible.

Both axioms of group V require second order logic, where one can quantify over predicates.
The line completeness axiom contains a quantification over the models of I-III and from V-1, so to express it one needs to says "forall predicates incidence, betweeness, congruence, which verify ..."
These two axioms (line completeness and axiom of Archimedes) can also be replaced  equivalently by Dedekind cut axiom.
Tarski studied a variant of the Dedekind cut axiom which can be expressed in first order logic using an axiom schema:

Let φ(''x'') and ψ(''y'') be first-order formulae containing no free  instances of either ''a'' or ''b''. Let there also be no free instances of ''x'' in ψ(''y'') or of ''y'' in φ(''x''). Then all instances of the following schema are axioms:
:
$\exists a \,\forall x\, \forall y\,[(\phi(x) \land \psi(y)) \rightarrow Baxy] \rightarrow \exists b\, \forall x\, \forall y\,[(\phi(x) \land \psi(y)) \rightarrow Bxby].$

In fact,  most of Hilbert's theorems about geometric figures can be developed in FOF. In the proof of Pascal's theorems, he may use second order logic when it makes use of congruence classes of segment or angles. But this use is inessential because the statement is first-order.
Hilbert needs these second order axioms only to characterize the models of its axioms as cartesian planes over the reals.
Using Tarski's first order variant of Dedekind's cut, the models are the cartesian planes over a real closed field.
If one only wants to prove theorems within ruler and compass geometry, the first order axioms of line/circle or circle/circle continuity are enough.


text:
Q: Firefox: Communicator presence issue We are using NameCtrl in our application and works fine in IE. But the same is not working in Firefox. The firefox website says that they doesnt support ActiveX controls. http://support.mozilla.com/en-US/kb/ActiveX
Is there a way to show communicator presence in Firefox too?

A: A little late, but this IS possible using browsers other than IE.
if(window.ActiveXObject) {
    nameCtrl = new ActiveXObject("Name.NameCtrl");
} else {
    try {
        nameCtrl = new ActiveXObject("Name.NameCtrl");
    } catch (e){
        nameCtrl = (function(b){
            var c = null;
            try {
                c = document.getElementById(b);
                if (!Boolean(c) && (Boolean(navigator.mimeTypes) && navigator.mimeTypes[b] && navigator.mimeTypes[b].enabledPlugin)) {
                    var a = document.createElement("object");
                    a.id = b;
                    a.type = b;
                    a.width = "0";
                    a.height = "0";
                    a.style.setProperty("visibility", "hidden", "");
                    document.body.appendChild(a);
                    c = document.getElementById(b)
                }
            } catch (d) {
                c = null
            }
            return c
        })("application/x-sharepoint-uc");
    }
}

if(nameCtrl && nameCtrl.PresenceEnabled){
// code here
}

A: The NameCrl is an ActiveX component so it will only work in Internet Explorer.
There is no way to do this without custom development.  I would suggest using the UCMA APis, building a service that queries presence, and building a JavaScript API to call this service.


text:
Q: Finding the signal $y[n]$ that results from the linear transformation of $x[n]$ I have this two signals $$x[n]=4\delta[n+1]+\delta[n-2]-2\delta[n-5]$$ $$y[n]=(3n-5)(u[n-1]-u[n-4]$$
I know that $y[n]$ results by the linear transformation of $x[n]$ and I have to find the parameters that make this possible.
Since $x[-1]=y[3]$ and $x[2]=y[2]$, solving this system $\left\{\begin{matrix}
x[-1]=x[3a-b]& \\
x[2]=x[2a-b]&
\end{matrix}\right.$ I got that $a=-3$ and $b=-8$, so the linear transformation is characterized by a time shift of $-8$ and a time scaling of $-3$.
My question is how to do the other way around, that is, imagine I have $$x[n]=4\delta[n+15]+2\delta[n+5]-8\delta[n-3]$$ and apply a time scaling of $a=4$ and a time shift of $b=9$ and I need to find the signal $y[n]$. How can I do this?

A: I think the solution in the first part of you post is wrong (your solution is shifted by a sample). If I understand correctly, it looks like you are trying to solve the following system:
$$
\begin{array}{l}
3 a + b = -1 \\
2 a + b = 2
\end{array}
$$
which gives $a = -3$ and $b = 8$. With these numbers you'll find that $x[-3n + 8] = y[n]$.
To find $x[4n - 9]$, just substitute $4n-9$ wherever $n$ appears in the definition of $x$:
$$
x[4n-9] = 4\delta [4n +6] +2\delta[4n-4] - 8 \delta[4n-12]
$$


text:
Q: _block_type_is_valid(phead- nblockuse) because of delete command ifstream ifile("Library.dat",ios::in|ios::binary);

Book *book_obj=new Book; //Book is the class name
if(ifile)
 {
    while(ifile.read((char*)book_obj,sizeof(Book)))
     book_obj->Display_BookDetails();
}
ifile.close();

delete book_obj; //Runtime Error is coming here.If I comment out this, then it works fine

I am reading content from a file named Library.dat. When I execute above code I get runtime error Access violation reading location 0x004B9B44. Commenting out delete book_obj works perfectly fine. How shall I delete book_obj to stop memory leakage.

A: Your class contains non-POD members. You can't read the structure as a block of bytes without running into problems. You'll have to serialize on your own by creating your own std::istream& operator>>(std::istream&, Book&) function:
std::istream& operator>>(std::istream& is, Book& b)
{
    // extract individually into b's data members
}

Now you can do:
while (ifile >> book_obj)
{
    book_obj->Display_BookDetails();
}


text:
Q: How do you iterate through two list and count the true positive I'm trying to iterate through a list of predictions and ground truths and count the true positives.
This is the solution I came up with:
    tp = 0
    for p, g in zip(predicted, ground_truth):
        if p and g == True:
           tp += 1
        return tp

I am getting an error message saying: SyntaxError: 'return' outside function. But the return is inside the function.

A: Try this:
def count_true(predicted, ground_truth):
    tp = 0
    for p, g in zip(predicted, ground_truth):
        if p and g == True:
           tp += 1
    return tp

count= count_true([True, False, True], [True, True, False])
print(count)

This should return:
1
You need to declare a function with def

A: def count_true(predicted, ground_truth):
   tp = 0
    for p, g in zip(predicted, ground_truth):
        if p and g == True:
           tp += 1
        return tp

You need to define a function, def count_true(p, g)


text:
Q: Why do algebraic varieties contain curves passing through two given points Let $X$ be an algebraic variety over the complex numbers. My definition of an algebraic variety is a finite type separated $\mathbf C$-scheme.
Someone told me that such varieties have the following property.
For all $x,y\in X$, there exists a smooth quasi-projective connected curve $C$ and a morphism $\gamma:C\to X$ such that the image of $\gamma$ contains $x$ and $y$. (Note that I allow the image of $C$ to be singular.)
I know that this is true for projective varieties. The argument is classic. But why is this true in general?
Maybe I'm wrong, and this fails for quasi-projective varieties. But can anyone then give me a counterexample?

A: I guess the argument you mention is the following:
If $\dim_{\mathbb C} X = 1$ the statement is tautological. Assume that $\dim X = d > 1$ and $X \hookrightarrow \mathbb{P}^n$ is projective. Choose any two points $x, y \in X$. Then there exists a projective subspace $H \subset \mathbb{P}^n$ of dimension $n-d+1$ which passes through both $x$ and $y$.
Consider $S := H \cap X$. If $\dim S = 1$, we are done. Otherwise do the same trick with $S \hookrightarrow H$ itself and use the induction by the dimension.
Clearly the same argument works with quasi-projective varities. The only specification is that the curve you've constructed does not have to be complete. Moreover there is a case when it never does: take a projective $\overline{X}$  and $X := \overline{X} \setminus D$, where $D$ is a hyperplane section divisor. Then any curve on $\overline X$ will intersect the hyperplane which cuts out the $D$ and therefore will intersect $D$ itself.
I thing in a general case of algebraic variety you can try to find an affine (and hence quasi-projective) chart which would contain both of your points $x$ and $y$, find a quasi-projective curve on this chart and then take its closure in the ambient variety (I suspect that the separateness and the finite-type conditions allow you to do this).
After all, I have to mentioned that I have never met a complex algebraic variety  which is not quasi-projective. This seemes to be something rather exotic. The accurate generalization of complex projective varities is a notion of Kähler manifold. For arbitrary Kähler manifold the property you're asking about fails.


text:
Q: How to use xtext language services from Angular I'm working on a DSL developed using xtext. I am using autocomplete using orion editor. It works great with the auto generated web editor. But, we want to integrate it with another web app developed using Angular 4. I got to configure the editor, but somehow all calls to language services (e.g. Occurrences, hover, etc) fails with 404. While same calls work fine with the auto generated embedded editor. What I'm missing here?
Here is how my code to create editor looks like in typescript:
xtext.createEditor({
    'serviceUrl': 'http://localhost:8080/xtext-service',
    'syntaxDefinition': 'http://localhost:8080/xtext-resources/generated/dsl-syntax.js',
    'parentClass': 'xtext-editor',
    'enableCors': true,
    'loadFromServer': false
  })

If I compare AJAX calls made by angular app and web editor, significant difference I see is, the web editor sends few cookies, which angular app doesn't. Can that be a reason? If so, how can I fix angular app accordingly?

A: In case anyone else is stuck with the same situation, I resolved it by adding
sendFullText: true

to the config object passed to the createEditor method. This property configures the editor to use language services in stateless mode and doesn't expect cookie/session to be passed.


text:
Q: Tamaño de memoria agotado, PDO estoy realizando una consulta a Mysql, en la que obtengo aproximadamente 55k registros, posterior a esto se exporta en un archivo excel.
SELECT CONCAT(cl,'-', id, '/', year) folio, nombre,evento,estado,impacto,equipo,proveedor,replace(comentarios,'\\n',' ') comentarios,lugar,area,fecha_falla,fecha_soporte,fecha_fin_falla,ROUND(TIMESTAMPDIFF(SECOND, fecha_soporte, fecha_fin_falla) / 60,2) tiempo,
reporte_refaccion,cantidad_refaccion,codigos_refaccion,cod_ref_proveedor,sit,fecha_escalado,reporte_escalado,fecha_fin_escalado,emp
FROM bi_view;

Inicialmente estaba recuperando los datos con la siguiente instrucción:
$result->fetchAll(PDO::FETCH_NUM);
pero al aumentar la cantidad de registros esto se volvió un problema, por el tema de la memoria excedida.
Lo que hice fue cambiar la forma en la que almaceno la información de la consulta:
$reportes = array();
while ($fila = $result->fetch(PDO::FETCH_NUM)) {
    $reportes[] = $fila;
}

Sin embargo se sigue mostrando en error: Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) no quisiera modificar el archivo de configuración para permitir más uso de memoria porque entiendo que sería solo un "parche" temporal.
Para generar el fichero en excel utilizó:
$reportes = Bitacora::ReportesExcel(); //método que devuelve el array de datos
foreach ($reportes as $key => $value) {
    $writer->addRow( WriterEntityFactory::createRowFromArray($value, $styleBody));
}

¿Alguna recomendación a modificar en el código?

A: Como te mencioné en comentarios, no debes crear un arreglo con esa cantidad de datos. La primera opción es devolver el resultado de ejecutar la consulta y crear el ciclo leyendo cada fila:
$result = Bitacora::ReportesExcel(); // Resultado de consulta, no un arreglo
while($fila = $result->fetch(PDO::FETCH_NUM)) {
    $writer->addRow( WriterEntityFactory::createRowFromArray($fila, $styleBody));
}

Esto ayudará a prevenir que el arreglo consuma la memoria disponible, sin embargo, si estás usando PHPSpreadSheet, este tampoco es muy amigable al manejar grandes cantidades de datos y sugiere algunas acciones para ahorrar memoria, que también puede ocasionar otros problemas, especialmente en tiempo de ejecución.
Alternativa
Te sugiero echarle un vistazo a Box / Spout que en su descripción menciona:

Spout is a PHP library to read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way. Contrary to other file readers or writers, it is capable of processing very large files while keeping the memory usage really low (less than 3MB).

En resumen: Contrario a otros lectores o generadores de hojas de cálculo, es capaz de procesar archivos muy grandes mientras mantiene el uso de memoria realmente bajo (menos de 3mb).
Solo faltaría comprobar si el soporte para estilos cumple con tus necesidades.


text:
Q: Bourbaki exercise about "ramified" ordered sets This is Exercise III.2.8 of Bourbaki's Theory of Sets.
An ordered set $E$ is said to be ramified if, for each pair of elements $x,y$ of $E$ such that $x<y$, there exists $z>x$ such that $y$ and $z$ are not comparable. $E$ is said to be completely ramified if it is ramified and has no maximal elements.
(a) Let $E$ be an ordered set and let $a$ be an element of $E$. Let $\mathfrak{R}_a$ denote the set of ramified subsets of $E$ which have $a$ as least element. Show that $\mathfrak{R}_a$, ordered by inclusion, has a maximal element.
(b) If $E$ is branched, show that every maximal element of $\mathfrak{R}_a$ is completely ramified.
(An ordered set $E$ is said to be branched if for each $x\in E$ there exist $y,z$ in $E$ such that $x\leq y$, $x\leq z$ and the intervals $\left[y,\rightarrow\right[$ and $\left[z,\rightarrow\right[$ do not intersect.)
The proof of (a) is a straightforward application of Zorn's Lemma.
For (b), I would like to argue in the following way. Suppose $F$ is a maximal element of $\mathfrak{R}_a$ and $x$ is a maximal element of $F$. Then there is $y,z$ in $E$ such that $x\leq y$, $x\leq z$ and $\left[y,\rightarrow\right[\cap\left[z,\rightarrow\right[=\emptyset$. Then $F\cup\{y,z\}$ is ramified.
But I haven't been able to show that $F\cup\{y,z\}$ is ramified, and I'm not sure that it's true, since if $b\in F$ and $b<y$, I don't see a way to conclude that $b\leq x$ or $b<z$. On the other hand, there is no natural way of adding further elements to $F\cup\{y,z\}$ such that it becomes a ramified set.

*

*Any hints at the solution or general thoughts about the problem are greatly appreciated.

*Bourbaki seems to be the only mathematician to use the words "branched" and "ramified" for those properties. Are there other more common words, or are these properties without interest?

A: I'm not sure if this counts as a rigourous proof, but what if you think of $F$ as a directed graph.  Then $F' = F \cup \{y,z\}$ is formed from $F$ by adding $y$ and $z$ as vertices, and just two edges, one from $x$ to $y$ and one from $x$ to $z$. Now two elements satisfy $u<v$ if and only if there is a directed path from $u$ to $v$. Then it's clear that if $b<y$ then also $b\leqslant x$ since you can just take a directed path from $b$ to $y$ and remove the last arrow, and you get a directed path from $b$ to $x$; the same logic shows that $b<z$, and since $y$ and $z$ are by construction incomparible, this shows that $F'$ is a ramified set, contradicting the maximality of $F$.

A: Here's a counterexample. Let $\{0,1\}^*$ denote the set of finite binary strings. Define E to be the set
$$E=\{a\} \cup \{bw \mid w\in\{0,1\}^*\} \cup \{cw \mid w\in\{0,1\}^*\}$$
with $a\leq bw\leq cw$ for all $w$, and $cw\leq cw'$ if $w$ is a prefix of $w'$.
Let $E'=\{a\}\cup \{bw \mid w\in\{0,1\}^*\}$. I claim that $E$ is branched, and $E'$ is a maximal element of $\mathfrak{R}_a$, but $E'$ is not completely ramified.
Every element $x\in E$ satisfies $x\leq cw$ for some $w$, so $x\leq cw0,cw1$, but $\left[cw0,\rightarrow\right[$ and $\left[cw1,\rightarrow\right[$ do not intersect. Hence $E$ is branched. (This is pretty much 1, Exercise 24 (b).)
Let $E''$ be a proper superset of $E'$. There is a prefix-minimal $w$ such that $cw\in E''$. There is no $z>bw$ incomparable with $cw$, but $bw,cw\in E''$. So $E''$ is not ramified. Hence $E'$ is a maximal element of $\mathfrak{R}_a$.
Finally, $b01010$ (and every other element of the form $bw$) is maximal in $E'$. So $E'$ is not completely ramified.


text:
Q: Define symbol as UserID or UserId? In Go I've seen some people defining symbols (methods, variables, etc) like this: UserID, GetSomeURL() with UPPERCASE letters of ids, urls, etc.
Is this a standard way?
Even my editor, that uses go-lint, warns me that I should change it (because I use UserId).
I read some of the golang source code https://golang.org/src/ and I never saw some like UserID.
Is this going to be another "tabs" vs "spaces" thing? LOL
I know this does not cause any problems compiling or any other problem, but I'm just trying get some "standard" on this.

A: UserID and GetSomeURL (or simply SomeULR()) would be idiomatic.
Source: https://github.com/golang/go/wiki/CodeReviewComments#initialisms:

Words in names that are initialisms or acronyms (e.g. "URL" or "NATO")
  have a consistent case. For example, "URL" should appear as "URL" or
  "url" (as in "urlPony", or "URLPony"), never as "Url". Here's an
  example: ServeHTTP not ServeHttp.
This rule also applies to "ID" when it is short for "identifier," so
  write "appID" instead of "appId".

You are right, golint is useful to identify deviations from the standard naming convention - it's good to follow its advices (especially when the code is worked on by multiple people and coding style consistency is even more valuable).


text:
Q: How can I prevent having to restart Safari when blocking sites via /etc/hosts file? I have modified my /etc/hosts file to block website.com and www.website.com.
I know the formatting of my hosts file is correct because when I restart Safari, the block takes effect. I can also enter into a private window, and the block takes effect. If I do not take any action, Safari will eventually start blocking the sites from my host file after about 5 minutes. Is therany wayay I can expedite this?
When I test in Chrome, there is no need to restart Chrome, my blocks immediately start working.
I've attempted:
sudo killall -HUP mDNSResponder

and
sudo dscacheutil -flushcache

I've also read attempted all of the formatting suggestions on stack exchange for the etc/hosts file, but nothing seems to work. No matter what, Safari needs to be reset for the blocks to take place.
I would like for a solution that can be done programmatically (i.e. through a terminal command or some sort of script - not through some GUI application) so that I can package this in with my application.

A: I've discovered that if I disconnect from wifi for about 10 seconds and then reconnect, that will force safari to read the hosts file correctly. Anyone know what type of data gets cleared when you disconnect and reconnect to wifi? Maybe that can guide me to a workaround.


text:
Q: "Undefined method where" error in query I have spent the last day trying different things and searching the internet on the answer but I am just plain stuck.
I have a rails app (4.0) which logs PB's made in the gym for different lifts.
I would like to display the highest weight for 1 rep, 3 reps and 5 reps.
My controller looks like this.
@history = current_user.workouts.order("weight DESC","reps DESC").group_by(&:lift)

The code in my view is then as follows...
<% @history.each do | lift, workout | %>
  <% name = lift[lift].downcase.gsub(/[ &]/,'') %>

    <%= link_to lift[lift], send("workouts_lift_#{name}_path") %>
    <%= workout.where(:reps => 1).max_by(&:weight).weight %> kg
    <%=  workout.where(:reps => 3).max_by(&:weight).weight %> kg
    <%=  workout.where(:reps => 5).max_by(&:weight).weight %> kg

<% end %>

I keep getting a error for the where method. I'm unclear as to what the problem is as I can get it to work in the rails console using
user.workouts.where(:reps=> 1).where(:lift => "Snatch")

A: In your view, the workout variable that is yielded in the each block is an instance of the Workout class, not the class itself. ActiveRecord query methods such as where are only available on classes or relationships, hence the error. Without knowing the underlying architecture of your models and relationships, it's hard to say exactly what you can do to fix it though.


text:
Q: Total size of a SVN repository? I have a SVN repository that is 8 GB when I measure the folder size on the server.
But when I check it out locally (simply checking out the full repository from the root, all branches/tags) its 50+ GB (still counting).
It seems that SVN does a good job at compressing its content. How come the size is so different?
And is there any way of computing the actual size of the repository without having to do a full checkout locally?

A: When you make a branch of a folder in repository the contents of that folder is not actually copied. No point in wasting space on mere duplication of data. For more info see the chapter about branching in the good book, especially boxed text at the end of the section Creating Branches, titled Cheap Copies.
As for the question of the actual size, there is no way to compute that that I know of, but I doubt if it is necessary. If there is no room, then make some room. Main point is that you don't need all the branches in your working copy, so checkout only what you really need.

A: You can try to calc size of revision without checkout (require some tricks and hand-work) for any subtree in repo of full tree (full tree is, anyway, bad idea and wasted space)

*

*svn ls -v -R ROOT/OF/ > file.log

*Remove all strings about directories, not files, in this log

1300 lazybadg              май 07  2014 city/

(slash in last position of string, string contain one field lesser, than file-related string)

*Sum all values (in bytes) from 3-rd field (in terms of awk) of every string in cleaned log

625 Infinity         1272 янв 22  2010 city/Siberia.bmp

Sample from my small repo
Full ls
  5 lazybadg              фев 07  2014 ./
  2 lazybadg              ноя 28  2013 branches/
  2 lazybadg              ноя 28  2013 branches/FullHTML/
  2 lazybadg      1521542 ноя 28  2013 branches/FullHTML/natasha_i_budushee.html
  2 lazybadg          146 ноя 28  2013 readme.textile
  1 www-data              ноя 27  2013 tags/
  5 lazybadg              фев 07  2014 trunk/
  5 lazybadg        46394 фев 07  2014 trunk/G1.txt
  2 lazybadg        22203 ноя 28  2013 trunk/G10.txt
  2 lazybadg        18974 ноя 28  2013 trunk/G11.txt
  2 lazybadg        23795 ноя 28  2013 trunk/G12.txt
  2 lazybadg        24996 ноя 28  2013 trunk/G13.txt
  2 lazybadg        27358 ноя 28  2013 trunk/G14.txt
  2 lazybadg        24855 ноя 28  2013 trunk/G15.txt
  2 lazybadg        22481 ноя 28  2013 trunk/G16.txt
  2 lazybadg        40970 ноя 28  2013 trunk/G17.txt
  2 lazybadg        27761 ноя 28  2013 trunk/G18.txt
  2 lazybadg        33974 ноя 28  2013 trunk/G19.txt
  2 lazybadg        38287 ноя 28  2013 trunk/G2.txt
  2 lazybadg        30880 ноя 28  2013 trunk/G20.txt
  2 lazybadg        24692 ноя 28  2013 trunk/G3.txt
  2 lazybadg        38140 ноя 28  2013 trunk/G30.txt
  2 lazybadg        36509 ноя 28  2013 trunk/G31.txt
  2 lazybadg        57408 ноя 28  2013 trunk/G32.txt
  2 lazybadg        74241 ноя 28  2013 trunk/G34.txt
  2 lazybadg        74800 ноя 28  2013 trunk/G36.txt
  2 lazybadg        22123 ноя 28  2013 trunk/G4.txt
  2 lazybadg        12631 ноя 28  2013 trunk/G5.txt
  2 lazybadg        32373 ноя 28  2013 trunk/G6.txt
  2 lazybadg        16433 ноя 28  2013 trunk/G7.txt
  2 lazybadg        25243 ноя 28  2013 trunk/G8.txt
  2 lazybadg        17669 ноя 28  2013 trunk/G9.txt

Dirs removed
  2 lazybadg      1521542 ноя 28  2013 branches/FullHTML/natasha_i_budushee.html
  2 lazybadg          146 ноя 28  2013 readme.textile
  5 lazybadg        46394 фев 07  2014 trunk/G1.txt
  2 lazybadg        22203 ноя 28  2013 trunk/G10.txt
  2 lazybadg        18974 ноя 28  2013 trunk/G11.txt
  2 lazybadg        23795 ноя 28  2013 trunk/G12.txt
  2 lazybadg        24996 ноя 28  2013 trunk/G13.txt
  2 lazybadg        27358 ноя 28  2013 trunk/G14.txt
  2 lazybadg        24855 ноя 28  2013 trunk/G15.txt
  2 lazybadg        22481 ноя 28  2013 trunk/G16.txt
  2 lazybadg        40970 ноя 28  2013 trunk/G17.txt
  2 lazybadg        27761 ноя 28  2013 trunk/G18.txt
  2 lazybadg        33974 ноя 28  2013 trunk/G19.txt
  ...

Summation is not shown due to obviousness, BUT!!!
Real size of checkout will be bigger, than calculated size just because .svn dir with metadata also require some space in WC

*

*Sum of plain size: 2336878

*Size of real fresh checkout: 4725986

A:
I have a SVN repository that is 8 GB when I measure the folder size on
  the server.
But when I check it out locally (simply checking out the full
  repository from the root, all branches/tags) its 50+ GB (still
  counting).

Do not checkout a working copy from the repository root unless you need to have all project branches, tags and shelves on your workstation. Normally you don't need such a working copy for daily work with SVN.

It seems that SVN does a good job at compressing its content. How come
  the size is so different?

Branches, tags, shelves (and copy operations) do not take much space in the repository storage system in the server side. For example, a new branch in the repository should take minimum of space (several kilobytes). A branch or tag in SVN is a cheap copy. When you create a branch or tag, Subversion doesn't actually duplicate any data in the repository. Moreover, SVN repos use several other techniques to save the space.
However, a local working copy of the repo root on your workstation will contain all the branches as is and will take up much more space than in the repository.

And is there any way of computing the actual size of the repository
  without having to do a full checkout locally?
Disk usage or size of my entire Subversion repository

Just check the size of the repositories on disk.
In case you use VisualSVN Server, try the Measure-SvnRepository cmdlet. It will produce the following output:
Name                                Revisions                 Size           SizeOnDisk
----                                ---------                 ----           ----------
MyRepo                                    498             3,340 KB             4,529 KB
MyRepo2                                   479            21,313 KB            22,571 KB
MyRepo3                                   201             1,032 KB             2,226 KB
MyRepo5                                     2                71 KB                90 KB

You can also view and examine the repository storage statistics with the svnfsfs stats tool. Here is an example:
svnfsfs stats C:\Repositories\MyRepository


text:
Q: Error when I'm installing parse frameworks: linker command failed with exit code 1 (use -v to see invocation) I tried to install the frameworks of Parse, but even when I installed it manually, and also when I installed it through Cocoapods (terminal) that gave me the following error:

A: You have to install bolts frameworks also.
add this line to your pod file.
pod 'Bolts'
https://github.com/BoltsFramework/Bolts-iOS


text:
Q: Unable to Push Master After Resetting, Branching, and Merging I made a few unstable commit changes that were also pushed.  My imaginary commit tree is as follows:

A -> B -> C -> D

Commit "A" was the latest stable commit.  Upon finding that the later changes were unstable, I went back to the last stable revision using

git checkout A

I then created a new branch "stable" with

git checkout -b stable

And continued working in that branch.  Now I want to merge to master, but I don't want to delete the changes I previously had, so I wanted to add them to a new branch instead of using revert.  Following the advice in this thread, I did the following from the master branch:

git branch unstable
git reset --hard HEAD~3

So now HEAD points to commit A, and the new branch "unstable" starts at commit B.  But I want to merge my stable changes (in branch "stable") so I use

git merge stable

And it completes successfully with no conflicts, and HEAD now points to the latest revision with the the stable changes merged in.  I can now push all branches to my repository except master, which reports a non-fast-forward error.  If I pull, it seems to pull all the unstable changes I had from earlier.
There appears to be a large number of posts similar to this, but it seems that mostly people want to just use revert to undo the commits they had, whereas I want to keep my unstable commits, but in a separate branch as I have it now.  What am I doing incorrectly?

A: The key question here is whether anyone else is using your master branch, and might already fetched that version.  If not, then it's safe for you to do a "forced" push, which will overwrite the old version of master.  You can do that with:
 git push -f origin master

However, if anyone might have used the master branch, you don't want to rewrite public history.  In that case, you can do:
 git fetch origin
 git merge -s ours origin/master
 git push origin master

The "ours" merge strategy says to create a merge commit, but ignore all the content that you're merging in (i.e. your old master branch).  Then your history will contain the history of master in origin, so you'll be able to push it without having to use the -f (--force) option.
Your unstable branch will still exist locally in both cases, of course.


text:
Q: E-mails per day problem This is an exam problem from probability and statistics that I failed, and still cannot figure out. Thanks in advance.
The number of e-mails that a person receives in a work day (monday to friday) can be modeled with the poisson distribution with an average of 6 e-mails a day. The number of e-mails a person receives during the weekend can also be modeled with the poisson distribution with an average of 3 e-mails a day.
a) What is the probability that person does not receive any e-mails, if we do not know which day it is?
b) A day is chosen at random from the week. If that person didn't receive a an e-mail on that day, what is the probability that day is a work day?

A: Let $p_1=\exp(-6)$ be the probability of receiving $0$ emails on a week-day and $p_2=\exp(-3)$ be the probability of receiving $0$ emails on a weekend (from the definition of a Poisson random variable). If the day of the week is not known (but all days have the same probability), then the probability of receiving $0$ emails is $\tfrac{5}{7}p_1+\tfrac{2}{7}p_2$.
The probability that today is a workday AND no emails were received is $\tfrac{5}{7}p_1$ so the probability that today is a workday given that no emails were received is $\tfrac{\tfrac{5}{7}p_1}{\tfrac{5}{7}p_1+\tfrac{2}{7}p_2}$.


text:
Q: floating-point error fligner.test r function? I have noticed that using the statistical test fligner.test from the r stats package provides different results with a simple transformation, even though this shouldn't be the case.
Here an example (the difference for the original dataset is much more dramatic):
g  <- factor(rep(1:2, each=6))
x1 <- c(2,2,6,6,1,4,5,3,5,6,5,5)
x2 <- (x1-1)/5 #> cor(x1,x2) [1] 1
fligner.test(x1,g) # chi-squared = 4.2794, df = 1, p-value = 0.03858
fligner.test(x2,g) # chi-squared = 4.8148, df = 1, p-value = 0.02822

Looking at the function code, I have noticed that the median centering might be causing the issue:
x1 <- x1 - tapply(x1,g,median)[g]
x2 <- x2 - tapply(x2,g,median)[g]
unique(abs(x1)) # 1 3 2 0
unique(abs(x2)) # 0.2 0.6 0.4 0.2 0.0 <- repeated 0.2

Is this a known issue, and how should this inconsistency be resolved?

A: I think your analysis is correct here. In your example the problem ultimately occurs because (0.8 - 0.6) == 0.2 is FALSE unless rounded to 15 decimal places.  You should file a bug report, since this is avoidable.
If you are desperate in the meantime, you can adapt stats:::fligner.test.default by applying a tiny bit of rounding at the median centering stage to remove floating point inequalities:
fligner <- function (x, g, ...)
{
  if (is.list(x)) {
    if (length(x) < 2L)
      stop("'x' must be a list with at least 2 elements")
    DNAME <- deparse1(substitute(x))
    x <- lapply(x, function(u) u <- u[complete.cases(u)])
    k <- length(x)
    l <- lengths(x)
    if (any(l == 0))
      stop("all groups must contain data")
    g <- factor(rep(1:k, l))
    x <- unlist(x)
  }
  else {
    if (length(x) != length(g))
      stop("'x' and 'g' must have the same length")
    DNAME <- paste(deparse1(substitute(x)), "and",
                   deparse1(substitute(g)))
    OK <- complete.cases(x, g)
    x <- x[OK]
    g <- g[OK]
    g <- factor(g)
    k <- nlevels(g)
    if (k < 2)
      stop("all observations are in the same group")
  }
  n <- length(x)
  if (n < 2)
    stop("not enough observations")
  x <- round(x - tapply(x, g, median)[g], 15)
  a <- qnorm((1 + rank(abs(x))/(n + 1))/2)
  a <- a - mean(a)
  v <- sum(a^2)/(n - 1)
  a <- split(a, g)
  STATISTIC <- sum(lengths(a) * vapply(a, mean, 0)^2)/v
  PARAMETER <- k - 1
  PVAL <- pchisq(STATISTIC, PARAMETER, lower.tail = FALSE)
  names(STATISTIC) <- "Fligner-Killeen:med chi-squared"
  names(PARAMETER) <- "df"
  METHOD <- "Fligner-Killeen test of homogeneity of variances"
  RVAL <- list(statistic = STATISTIC, parameter = PARAMETER,
               p.value = PVAL, method = METHOD, data.name = DNAME)
  class(RVAL) <- "htest"
  return(RVAL)
}

This now returns the correct result for both your vectors:
fligner(x1,g)
#>
#> Fligner-Killeen test of homogeneity of variances
#>
#> data:  x1 and g
#> Fligner-Killeen:med chi-squared = 4.2794, df = 1, p-value = 0.03858

fligner(x2,g)
#>
#> Fligner-Killeen test of homogeneity of variances
#>
#> data:  x2 and g
#> Fligner-Killeen:med chi-squared = 4.2794, df = 1, p-value = 0.03858


text:
Q: object detection algorithm outputs an image with no bounding boxes around the detected objects after testing the algorithm my partner and I are have created a modified faster rcnn algorithm and it doesn't seem to have any bounding boxes when it outputs an image after testing the algorithm but it only outputs the Mean Average Precision. so far what I've tried doing is uninstalling and reinstalling TensorFlow but the problem still persists.

A: Try changing the confidence Threshold so, that you are able to see bounding boxes having lower confidences, this way you can verify whether there is a problem with the postprocessing code or your model is not able to learn any useful patterns.
Also please provide some insight to your code, so that we can help better


text:
Q: Rails 3 uninitialized constant ActiveRecord::RecordInvalid application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery

  rescue_from ActiveRecord::RecordInvalid,  :with => :error_render_method
  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

  def error_render_method
  end

  def record_not_found
  end

end

When I run rspec I get this error:
uninitialized constant ActiveRecord::RecordInvalid (NameError)

I have googled and found that some people add require 'active_record/errors' to that file, yet when I do the error still persist.
I am using rails (3.2.9)

A: I got the same problem when I started Unicorn.
I solved it by just quoting the constant "ActiveRecord::RecordInvalid".
(Not naked constant ActiveRecord::RecordInvalid.)
I don't know the reason but it seemed like ActiveRecord::RecordInvalid hadn't loaded when starting Unicorn.

A: This seems to have been fixed between Rails 4.0 and 4.1.


text:
Q: Is there an emulator (VM) out there that can "restrict" processing power? I've developed some JavaScript to test the ability of a computers processing by comparing "perfect" times (0 lag, doesn't exist) and "real" times (how long it actually took).
Now I need something to test it to see what's what.
Is there something out there that restricts power so that I may emulate what kind of lag a slower system would use?
i.e., restrict to 2.2ghz processor with 4gb RAM

A: Using Oracle's VirtualBox you can limit the VMs RAM, the amount of cores and the CPU time in percent.


text:
Q: Facet counts aren't displaying correct numbers after filtering on a different facet If you have two facets, let's say category and tag, initially the counts are correct, but they don't go down after filtering on one of the facets. The idea being that if there are no records within category X with tag Y, and we're filtering by category X, tag Y should have a facet count of 0.
Of course, other facet counts in the same term (other categories) facet counts don't go down because they would be an OR rather than an AND.

A: How are you filtering your facets?  Like this?
GET /_search
{
  "query": {.....},
  "filter": { "term": { "some_field": "some_value"}},
  "facets: {.....}
}

If so, then it's not surprising. The top level filter parameter is for filtering your search results AFTER having calculated facets.  In fact, in 1.0 it has been renamed to post_filter precisely because of this confusion.
You want to use a filtered query instead:
GET /_search
{
  "query": {
    "filtered": {
      "query": {.....},
      "filter": { "term": { "some_field": "some_value"}}
    }
  },
  "facets: {.....}
}


text:
Q: How to modify width of standard dialog form sharepoint 2010 Please, help me!
I need to modify width of standard dialog form for adding element into library.
If I click to ribbon button for adding element, form opened with width=402px:

If I click to button under all elements of current library, form opened with width=1032px:

I can't understand, what I need to do for opening in the second case form with width=402px.
Maybe need enter some code in Upload.aspx? (this form generate automatically) I guess, this page open for creating new element, because schema.xml for my list definition contain this code:
<Forms>
   <Form Type="DisplayForm" SetupPath="pages\form.aspx" Url="Forms/DispForm.aspx" WebPartZoneID="Main" />
   <Form Type="EditForm" SetupPath="pages\form.aspx" Url="Forms/EditForm.aspx" WebPartZoneID="Main" />
   <Form Type="NewForm" Url="Forms/Upload.aspx" WebPartZoneID="Main" />
</Forms>

But if modify this part of Upload.aspx (add .ms-dglContent class), it doesn't help me:
<asp:Content ContentPlaceHolderId="PlaceHolderBodyAreaClass" runat="server">

</asp:Content>

If I modify css files:
.ms-dglContent {width:402px!important;}

it modify all dialog forms, but in my case is unacceptable.
I would be grateful for any attempt to help!

A: @Kate Ponomareva
sorry for the delayed reply (wasn't online), follow below steps to add html form webpart
1 : through SPD, create your required forms for the respective list and set them as default or you could use the default form itself
2 : go to your sharepoint site, click on the list from View All Site content or Quick Launch
3 : in top ribbon click on List (List Tools)
4 : towards right you will see option as Form Web Parts, click on it, the three forms will be listed there [New Form, Display Form, Edit Form]
5 : select the one on which you want to increase the width/height
6 : it will open in edit mode, click on Add a Web Part
7 : Click on Forms [Categories] => HTML Form Web Part
8 : After adding the HTML Form Web Part, click on Edit Webpart
9 : Click on Source Editor, Remove all code from it and put a empty HTML table with width and height as per your requirement
ex. to increase width

10: save the form and check out your respective modal by clicking on the same in your list view

A: In SharePoint Designer 2010, turns out you just go to Data View Tools > Web Part > Width, and type in the new width of the form. In the code, it looks like:
<WebPartPages:DataFormWebPart runat="server" ......   Width="1000">

A: insert a html form webpart into the add form , include code into the same of a blank html table setting the width as per your preference.


text:
Q: Gradle sync failed on Android studio after windows 10 update I have a problem.
After update my windows 10, gradle sync failed on android studio 3.0. I use gradle 4.5. Error message:

The newly created daemon process has a different context than
  expected. Java home is different. Expecting: 'C:\android-studio\jre'
  but was: 'C:\Program Files\Java\jre1.8.0_74'. Please configure the JDK
  to match the expected one.

I run"studio64.exe". I try to add java.home to gradl.properties but it dosen't work. It's wierd because before update averythink was ok...

A: It seems your Android studio and JAVA_HOME environment
 variable refers to different directories. Check if these to values are same and they should refer to jdk path not jre.


text:
Q: How to use result of a regrex for further matching? Say i have a regrex like this
[\d%]+

so for 4500%, it will match. Now i want this matched string be further used in regrex. How can i write such regrex. In this example, i would like to write a nested kind of regrex for the matched string 4500% that should match only numeric and trim off the %.

A: This RegEx creates a group that you can simply call using $1, which is the numeric part:
([0-9\.]+)%


text:
Q: PyQT Editor for XML Configuration Files - tools/components? We have a program that stores in configuration across several XML files.
Originally, my plan was to write an Elixir (http://elixir.ematia.de/trac/wiki) model to represent our configuration, write a PyQT GUI wrapper around this, and have the program export to XML when finished.
The database/Elixir layer would make it easier to validate certain things, and to represent certain relational structures in the configuration (e.g. user accounts).
However, the preference is now to just write a direct wrapper around the XML files themselves.
So my question is, what sort of tools can I use to make it easier to write a PyQT based GUI editor for XML files?
We have the XSD files for the configuration, and on the validation front, I know can use QtXMLPatterns to validate the schema:
http://labs.qt.nokia.com/2009/02/03/w3c-xml-schema-validation-with-qt/
http://labs.qt.nokia.com/2009/07/31/qt-46-with-xml-schema-support/
However, are there any shortcuts, libraries or components/tools available in PyQT to writing the actual GUI itself?
Cheers,
Victor


text:
Q: Passing a Javascript object to PHP without creating a query string I have an HTML table on the front-end (back-end doesn't have the data) and there's a button to export the table into an Excel spreadsheet using PhpSpreadsheet. Currently when clicking the button, a script parses the table and builds an object with all the header and data so that I can pass this to a PHP script and then the library will take care of creating the Excel file afterwards.
My approach uses AJAX but I keep getting errors because the library changes the Content Type.
Here's my code:
$(document).on('click', '.export-btn', function() {
  let parsed = {
    header: [],
    data: []
  };

  ... // build the object from the table

  $.ajax({
    method: "POST",
    url: 'export.php',
    dataType: "json",
    data: parsed,
    beforeSend: function(jqXHR, settings) { ... },
    success: function(data, status, jqXHR) { ... },
    error: function(jqXHR, textStatus, errorThrown) { ... }
  });
});

export.php:
... // build the spreadsheet

# Redirect output to a client's web browser (Xlsx)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
header('Cache-Control: max-age=0');

# If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

# If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');                # Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');   # always modified
header('Cache-Control: cache, must-revalidate');                 # HTTP/1.1
header('Pragma: public');                                        # HTTP/1.0

$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');

$spreadsheet->disconnectWorksheets();
unset($spreadsheet);

With the table being large, I don't think I can do a simple redirect to export.php with the data passed as a query string.


text:
Q: Insert XML in SQL Server Good afternoon all.
Currently, I have make a small demo with XML in SQl Server.
I have table with name: tb_xml_demo(ID, Name, Descr)
And each time when I insert to this table. ID column like this:
001, 002, 003 ....

This is my procedure
alter proc sp_xml_demo_cud
@p_xml xml
as
begin
    declare @dochandle int;

    exec sp_xml_preparedocument @dochandle output,@p_xml;

    insert into tb_xml_demo(id, name, descr)
        select
            (select
                 format(isnull(convert(int, max(id)), 0) + 1, '000')
             from tb_xml_demo) id,
            name,
            descr
        from
            OPENXML(@dochandle,'/root/item',2)
        with
            (name nvarchar(50),
             descr nvarchar(50),
             crud varchar(1)
            )
    end;

And this is my xml:
exec sp_xml_demo_cud
    '<root>
         <item>
            <name>9876543</name>
            <descr>1sdfsd</descr>
         </item>
         <item>
            <name>333</name>
            <descr>333</descr>
         </item>
     </root>';

And this is result after executing the procedure:
    id  Name     Descr
    001 9876543  1sdfsd
    001 333      333

Please help me.
Thanks a lot.

A: I would recommend doing this:

*

*create your table with a ID INT IDENTITY(1,1) column to let SQL Server handle the generation of unique ID values

*add a computed column (I called it PaddedID) that uses the system-generated, valid ID to display with leading zeroes

*parse the XML with the built-in, native XQuery functionality (instead of the legacy OPENXML stuff which is notorious for memory leaks)

This gives me this code:
-- create your table
CREATE TABLE tb_xml_demo
       (ID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
        PaddedID AS RIGHT('0000' + CAST(ID AS VARCHAR(4)), 4) PERSISTED,
        Name VARCHAR(50),
        Descr VARCHAR(100)
       )

-- declare your INPUT XML document
DECLARE @input XML = '<root>
         <item>
            <name>9876543</name>
            <descr>1sdfsd</descr>
         </item>
         <item>
            <name>333</name>
            <descr>333</descr>
         </item>
     </root>'

-- parse the XML using XQuery and insert the results into that newly created table
INSERT INTO dbo.tb_xml_demo
        (Name, Descr)
    SELECT
        ItemName = xc.value('(name)[1]', 'varchar(50)'),
        ItemDescr = xc.value('(descr)[1]', 'varchar(100)')
    FROM
        @input.nodes('/root/item') AS XT(XC)

-- select the values from the table
SELECT * FROM dbo.tb_xml_demo

and this results in an output of:


text:
Q: CodeIgniter: Maximum function nesting level of '100' reached, aborting! I'm getting the above error, is there any built in support for a stack trade in code igniter?  I have an infinite loop somewhere I'm trying to figure out where it is...

A: Try using the xDebug plugin for PHP for the functionality you seek:
http://www.xdebug.org/

A: If you use hmvc, check if you have not loaded something in the wrong way, i.e, $this->load->module() instead of $this->load->model().
I faced the same issue and that was the cause of that message.


text:
Q: JsonArrayRequest returning null? I am trying to write a get request using the volley library for frontend and spring boot for backend. I've tested the backend and it works just fine but the response on the volley is null, any ideas as to why this may be?
heres my volley request:
RequestQueue queue = Volley.newRequestQueue(Lobby.this);
        String url = "http://10.0.2.2:8080/lobby/1";
        JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        gameLobby = response;
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(Lobby.this, "ERROR: " + error, Toast.LENGTH_SHORT);
                    }
                }
            );
        queue.add(request);RequestQueue queue = Volley.newRequestQueue(Lobby.this);
        String url = "http://10.0.2.2:8080/lobby/1";
        JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        gameLobby = response;
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(Lobby.this, "ERROR: " + error, Toast.LENGTH_SHORT);
                    }
                }
            );
        queue.add(request);

and my backend controller:
  @GetMapping(value = "lobby/{id}", produces = "application/json")
    public ResponseEntity<List<GameLobby>> getLobbyByHost(@PathVariable("id") int hostID) {
        return new ResponseEntity<List<GameLobby>>(gameLobbyRepository.findByHostID(hostID), HttpStatus.OK);
    }

I am trying to get a JSONObject from the database to use somewhere else


text:
Q: update website_id and store_id using sql command i'm going to move all customers to one site from an other site, i planned to use sql command to do this
Update customer_entity set website_id = 4 where website_id = 3

but when i ran this command, there is an error
1062 - Duplicate entry 'someone@email.com-4' for key 'UNQ_CUSTOMER_ENTITY_EMAIL_WEBSITE_ID'
there is an email duplicated and a unqiue key disallowed me to perform this action.
Any ideas to solve this?
Re:i run the script but there is an error
Fatal error: Uncaught exception 'Mage_Customer_Exception' with message 'This customer email already exists' in /home/prd1/public_html/app/Mage.php:580 Stack trace: #0 /home/prd1/public_html/app/code/core/Mage/Customer/Model/Resource/Customer.php(99): Mage::exception('Mage_Customer', 'This customer e...', 3) #1 /home/prd1/public_html/app/code/core/Mage/Eav/Model/Entity/Abstract.php(1122): Mage_Customer_Model_Resource_Customer->_beforeSave(Object(Mage_Customer_Model_Customer)) #2 /home/prd1/public_html/app/code/core/Mage/Core/Model/Abstract.php(318): Mage_Eav_Model_Entity_Abstract->save(Object(Mage_Customer_Model_Customer)) #3 /home/prd1/public_html/au_asia.php(16): Mage_Core_Model_Abstract->save() #4 {main} thrown in /home/prd1/public_html/app/Mage.php on line 580

A: try this SQL Command :
UPDATE `customer_entity` SET `website_id` = '4' WHERE `customer_entity`.`website_id` = '3' AND `customer_entity`.`email` != 'someone@email.com-4';

OR
Add bellow code in test.php file at magento root folder and run in browser
<?php
require_once('app/Mage.php');
Mage::app('default');
class AR
{
    public function index()
    {
        $currentWebsiteId = 3;
        $updateWebsiteId = 4;
        $collection = Mage::getResourceModel('customer/customer_collection')
            ->addAttributeToSelect('website_id', $currentWebsiteId);
        foreach($collection as $customer) {
            $customer->setWebsiteId(2);
            $customer->setId($customer->getId());
            $customer->save();
        }
    }
}
$obj = new AR();
$obj->index();
?>

A: I found the OP's solution to work where I needed to move only customers belonging to a particular Customer Group
UPDATE customer_entity SET website_id = 4, store_id = 4
WHERE website_id = 3 AND group_id = 9 AND email IN
(SELECT tt.email FROM (SELECT email FROM customer_entity WHERE website_id IN (3,4)
GROUP BY email HAVING count(email) <= 1) AS tt)


text:
Q: JAVA RESTFull server get POST data with "%" (percentege) as value @FormParam I`m making and REST client that recive a POST with data to use as filter on a query.
My problem is when the client send me a "%" to search for all the values.
Jersey send me the following error
11:36:35,857 ERROR [Jersey REST Service]:260 - Servlet.service() for servlet Jersey REST Service threw exception
java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "%ip%"

The code who is generating this error is:
@POST
    @Path("/Comercial/{campo}")
    @Produces("application/json; charset=utf-8")
    public static Response findAll(
                @PathParam(value = "campo") String campo,
                @FormParam("filtro") String filtro){

        Object resposta = null;

        resposta = new JSONArray();
        campo = campo.substring(7);
        resposta = SequenciaControl.findDataByTable(campo,filtro);

        return Retorno.send(resposta);
    }

this works if i recive as a GET using @QueryParam, but i need this as a POST
Thanks!

A: The percentage has to be escaped using %25 while sending it as a request.
So, "%ip%" should be "%25ip%25"


text:
Q: Retina display image resolution using media queries What is the best way to use media queries to both detect a retina display and also specify max-width?
I can detect retina using
@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (   min--moz-device-pixel-ratio: 2),
only screen and (     -o-min-device-pixel-ratio: 2/1),
only screen and (        min-device-pixel-ratio: 2),
only screen and (                min-resolution: 192dpi),
only screen and (                min-resolution: 2dppx) {

}

How do I add it to the media queries? Do I write
@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (   min--moz-device-pixel-ratio: 2),
only screen and (     -o-min-device-pixel-ratio: 2/1),
only screen and (        min-device-pixel-ratio: 2),
only screen and (                min-resolution: 192dpi),
only screen and (                min-resolution: 2dppx) {
 @media screen and ( max-width: 2000px){
     .holer{
         background:url("background@2x.png");
       }
  }
}

Or is there any better method for changing images for retina displays? ( adding media queries for screen size to media queries for retina display)

A: You'd probably cover all retina displays according to this article by CSS-tricks. I guess you already found that out. Another option is to use SVG's, but I wouldn't use them for background images. The SVG format is perfect for two dimensional shapes and icons, altough icon fonts render faster.
As for the question "how to add media queries for screen size to media queries for retina display", the code you posted should work fine. Another way would be to just add the second clause to the first ones, like so:
@media
only screen and (-webkit-min-device-pixel-ratio: 2) and ( max-width: 2000px),
only screen and (   min--moz-device-pixel-ratio: 2) and ( max-width: 2000px),
only screen and (     -o-min-device-pixel-ratio: 2/1) and ( max-width: 2000px),
only screen and (        min-device-pixel-ratio: 2) and ( max-width: 2000px),
only screen and (                min-resolution: 192dpi) and ( max-width: 2000px),
only screen and (                min-resolution: 2dppx) and ( max-width: 2000px) {
    .holer {
        background:url("background@2x.png");
    }
}

If you're using SCSS, create a mixin as explained here. This would save you alot of time and drastically improves readability.


text:
Q: send value from php file to js file i want pass value from php to js file , code like this
but not working
what wrong ?
thanks
php file
$var = 10;
<script>
var phpVar = "<?php echo json_encode($var) ?>;";
</script>
<script type="text/javascript" src='vendor/circliful/circliful.custom.js'></script>

js file
$("#overallProgress").circliful({
        animationStep: 5,
        foregroundBorderWidth: 12,
        backgroundBorderWidth: 6,
        percent: 'alert(phpVar);', **<-- place value from php**
        fontColor: '#000000',
        foregroundColor: '#1a8e5f',
        backgroundColor: 'rgba(0, 0, 0, 0.1)',
//      icon: '\eab4',
        iconColor: '#1a8e5f',
        iconPosition: 'middle',
//      text: 'Statistik',
        textBelow: true,
        animation: 1,
        animationStep: 1,
        start: 2,
        showPercent: 1,
    });

sorry all i have mistake code in php
this right code
<?php
$var = 67;
?>
<script>
var phpVar = <?php echo json_encode($var) ?>;
</script>
<script type="text/javascript" src='vendor/circliful/circliful.custom.js'></script>

A: alert is a javascript function which display a message box, also you can't wrap it in a single quote, just add phpvar variable and test
percent: phpVar,


text:
Q: How i can specifiy the datatype when import google sheet with gspread_pandas? I have a google sheet with a fixed number of columns and variabile numer of rows that are the value of environment sensors.
the sheet format is

im able to import it in a data frame with gspread-pandas
s=Spread(spread=gsheet_id,config=gspread_pandas.conf.get_config(conf_dir=conf_path,file_name=service_file))

pd.DataFrame=s.sheet_to_df(sheet='06-2020')

the problem is the type of Dataframe Series, each series has a dtype('0').
>>pd.DataFrame['T_PREP_[°C]'].dtypes
dtype('O')

To import a google sheet with correct type,i need to specify the data of each columns or i need to convert with pandas?
thanks in advance!

A: I'm the author of gspread-pandas. Unfortunately, there's no way to do so right now. I have an issue out there for a while about it, but haven't had time to work on it. Any PRs welcome: https://github.com/aiguofer/gspread-pandas/issues/18.
What I've done in the past is to manually convert columns using something like:
pd.DataFrame['T_PREP_[°C]'] = pd.DataFrame['T_PREP_[°C]'].astype(<conversion_type>)


text:
Q: Why are products that are not linked to a category visible in search results? In my webshop products that are enabled but not linked to any Category are being displayed in the search result. Is there a way to prevent this?

A: AJ Fast,There are two solution
1. Change the Visibility of all products to Catalog.
2. Disable the  product  make all products status ->Disable

A: Why do you have them on your site at all if you don't want them to be visible?
If you have discontinued products that you want to remove from the front end, you can switch their status to 'disabled'. They will still be searchable in the backend. Or you can delete them completely.


text:
Q: Using focus on useRef is throwing the error: "property 'focus' does not exist on type 'never'"   const textInputRef = useRef();
  useEffect(() => {
    if (textInputRef && textInputRef.current) {
      textInputRef.current?.focus(); // property 'focus' does not exist on type 'never'
    }
  }, []);

  return (
      <input ref={textInputRef} />
  )

The textInputRef.current?.focus() line is throwing property 'focus' does not exist on type 'never'
I'm on React 16.13.1, typescript 4.0.2 using hooks and function components

A: The useRef needs a type passed to it. This is the type of the value it's expected to contain. Typescript can't crawl your code to see where the ref is used and figure out the type from that. You have to provide it when there is no default value.
In your case that would be:
const textInputRef = useRef<HTMLInputElement>(null);

See playground


text:
Q: How to make a string from separate int values I'm trying to make a string out of 3 elements with the following format '0/5'.
int start = 0;
int finish = 5;
I've tried doing this:
    char string[20];

    string[0] = (char) start;
    string[1] = '/';
    string[2] = (char) finish;

    string[strlen(string)] = '\0';

But when I printf I get nothing.
    char buffer[10];
    char aux[5] = {'/', '\0'};
    char aux2[5];
    sprintf(buffer, "%d", start);
    strcat(buffer, aux);
    sprintf(aux2, "%d", finish);
    strcat(buffer, aux2);

This is what is working but seems very inefficient.

A: When you print a char using printf, it's ASCII value is used. In this specific case, you could use
string[0] = (char) (start + '0');
string[1] = '/';
string[2] = (char) (finish + '0');

Or you could use string[0] = (char) start + 48;. The ASCII value of '0' is 48.
Or better initialize start and finish as char start = '0', char finish = '5', etc.
In addition, make sure that start and finish are between 0 and 9. Other values, will give you unexpected results.
Also, the last line should be string[3] = '\0'. strlen works by iterating till it encounters a \0 and thus is useless in this case.
Demo

A: If your integers are more than 1 digit long then maybe you should consider using something like sprintf()
char string[20];
int start = 13;
int finish = 21;

sprintf(string, "%d/%d", start, finish);

It works exactly like printf() but instead of printing to the console it prints to a string you supply to it.

A: char *tosomething(char *buff, int start, int end)
{
    sprintf(buff, "%d/%d", start, end);
    return buff;
}

A: The code you posted can be made more efficient by just replacing the last 4 lines with a single sprintf().
    char buffer[10];
    char aux[5] = {'/', '\0'};
    char aux2[5] = {'\0'};
    sprintf(buffer, "%d%s%d%s", start, aux, end, aux2);


text:
Q: Get invoke listener name and URL from DAO class Is it possible to get the invoked method name in JSF other than using PhaseListener? What i want is to log the invoke listener name and the url from the dao class.
ie,

Bean --calls--> Service --calls--> Repository (executes query
  and need to write the invoked url and the invoked bean method name to
  log file).

Is this possible?


text:
Q: Google Drive OAuth2 get token I just started learning Google tree up play and I have some questions.

*

*How to log in with login link?
session_start();
require_once 'api/src/Google/Client.php';
require_once 'api/src/Google/Service/Drive.php';

$drive = new Google_Client();

$drive->setClientId('XXXXXXXX-hc0ap9uujjvqpsci9ceitqsrro1d8415.apps.googleusercontent.com'); // Client ID

$drive->setClientSecret('XXXXXXXXXXX'); //Client Secret

$drive->setRedirectUri($url);

$drive->setScopes(array('https://www.googleapis.com/auth/drive'));

$url = $drive->createAuthUrl();

*How to get access_token?

A: You will get the URL to log in to Google from the $drive->createAuthUrl(). Google will return the credentials, including the access_token to the redirected URI.
I have set up a simple commented repo about using oAuth and Drive functions with the API in GitHub. You can find it here:
https://github.com/numsu/google-drive-sdk-api-php-insert-file-parent-example
Good luck learning! :)


text:
Q: Empty file with Ghostscript PDF printer and "big" page size I need to generate PS (or PDF) files from CAM350 (an application that manage Gerber files) running on Windows 7 x64.  From CAM350 there is no way to save PS or PDF files so I use a "Ghostscript PDF printer" (output to ":FILE" port) installed using the driver ghostpdf.inf I've found in the /lib directory of the GS (I have version 9.22 x64) installation directory. I open Gerber files and then I print the file from CAM350 using the Ghostscript PDF printer.
I usually print 348x247mm pages using "custom page size" setting from the Printer Setup dialog at 3600dpi (set using the advanced properties of the Ghostscript printer driver) and I'm satisfied with the output.
Now I need to print 550x420mm pages always at 3600dpi but the .ps file that the printer generates is empty. I've tried many different settings but it is clear that exceeding a certain page size will generate some error that causes the printer to output empty files.
If I set a 600 dpi resolution in the advanced printer options then the printer works, the file is generated, but when I print the page (using my TANTO 6120 fotoplotter) the resolution is not enough and some dimensions of the printed work are not correct.
I've tried to increase the Buffer size using the printer settings in the device and printer page of the Windows setup but it didn't solve the problem. I also tried to edit the .PPD file and increase the FreeVM value from 10.000.000 to 134.000.000 (written without thousand separator) because i see a PPD file from my TANTO 6120 fotoplotter that has this value.
I cannot use TANTO PPD files because they are not compatible with x64 versions of Windows and I cannot find a newer driver.
I need to print PS files from CAM350 and generate .PS files for my Tanto 6120 RIP, if Ghostscript printer has a bug can you please tell me if there is a commercial PS printer that can do the job?
Is there a way to see the GS errors using the Ghostscript PDF printer driver?
Thank you
Francesco


text:
Q: char array wont print in C unless previously printed So this is strange- below is my code to create a tokenizer object and the main method:
struct TokenizerT_ {
    char * sep;
    char * toks;
};

TokenizerT *TKCreate(char *separators, char *ts) {

    if (ts==NULL) {
        return NULL;
    }

    int lin = (int) strlen(separators);
    char yr[lin];
    yr[0] = *separators;
    int lim = 1;
    int h = 1;

    for(h=1; h<strlen(separators); h++){
        char tmp = *(separators+h);
        int z=0;

        for (z=0; z<lim; z++) {
            if (tmp==yr[z]) {
                z=-1;
                break;
            }
        }
        if(z>-1){
            yr[h] = tmp;
            lim++;
        }

    }
    TokenizerT inu = {yr, ts};
    printf("%s\n", inu.sep);
    return &inu;
}

int main(int argc, char **argv) {

    char * arr = argv[1];
    char * y = argv[2];
    TokenizerT jer = *TKCreate(arr, y);

    printf("%s\n", jer.sep);
    printf("%s\n", jer.toks);
    return 0;
}

If I run the program with arguments "tes" and "testing", I get the following results:
tes
tes
testing
However, if I run the program with the printf statement in TKCreate commented out, I get:
testing.
The printf("%s\n", jer.sep) stops working and I've done nothing to the code except commenting out that printf statement in TKCreate. Why is that happening?

A: There are a number of problems here:

*

*inu is a local variable. You return the address of it. When you attempt to read from that address in main, you are accessing a variable that is no longer in scope. That is undefined behaviour.

*The sep field of inu is assigned yr. Now, yr is a local variable, a character array, which decays to a pointer. Again, accessing that once the function has returned means accessing a variable whose scope has ended. Again, undefined behaviour.

*You are using a variable length array, a VLA. I suspect that is not intentional. Generally speaking, VLAs are advanced features that should only be used when you are clear on the implications.

I suggest the following changes:

*

*Allocate the character arrays dynamically using malloc.

*Return the struct by value.

On top of that I suspect that you have other problems. It appears to me that yr is not null-terminated, and some elements may not be initialized at all. Is that intentional? Perhaps you actually meant to initialise yr to be equal to separators when you wrote yr[0] = *separators. Note that your code simply assigns a single character. To allocate yr dynamically, and initialise it to be equal to separators you can write:
yr := malloc(strlen(separators)+1);
strcpy(yr, separators);

Why do you call strlen(separators) multiple times? You appear to call it 1+strlen(separators) times. You should call it once only.

A: In C you can never return a pointer to a local function variable. Well, you can, but it won't work. Even if it seems to work, it is only waiting for a good opportunity to not work.
So you absolutely cannot do this:
TokenizerT inu = {yr, ts};
return &inu;

What you need to do is either pass in a pointer to the object you want to build, or use malloc to allocate a new one. If you use malloc you will need to remember to free the object later. And because of Windows and its multiple C runtimes it is a very good idea to free your objects inside a function just for that. Because if you were to have the code in a library, and malloc in the Debug runtime and free in the Release runtime, bad things happen.
So for the malloc example:
struct box* create_box(int x, int y) {
    struct box* b = malloc(sizeof(*b));
    if(!b) abort();
    b->x = x;
    b->y = y;
    return b;
}

void destroy_box(struct box* x) {
    free(x);
}

And for passing an object in:
void init_box(struct box* b, int x, int y) {
    b->x = x;
    b->y = y;
}

void f() {
    struct box b;
    init_box(&b, 10, 20);
}

A: You need to allocate memory for an object that is to be returned from a function. This puts the object on the heap (permanent memory) vice on the stack (memory that is recycled by the program as soon as the current function ends).
You can do that by making these changes in your TKCreate function:
TokenizerT *TKCreate(char *separators, char *ts) {
    ...
    # change 'char yr[lin];' to:
    char* yr = (char*)malloc(lin * sizeof(char));

    ....
    TokenizerT* inu = (TokenizerT*)malloc(sizeof(TokenizerT));
    inu->sep = yr;
    int->yoks = ts;
    printf("%s\n", inu->sep);
    return inu;
}

You can also clean up your main() function by only sharing one copy of the object. You could call free() on any allocate memory once you are done with it:
int main(int argc, char **argv) {
    char * arr = argv[1];
    char * y = argv[2];
    TokenizerT jer* = TKCreate(arr, y);

    printf("%s\n", jer->sep);
    printf("%s\n", jer->toks);
    free(jer);
    return 0;
}


text:
Q: Catching errors from one function inside another JavaScript React I have two functions, login (in fileB.js):
export const login = async (data) => {
  try {
    const response = await auth.login(data);
    return response;
  } catch (e) {
    return new Error(e);
  }
};

and loginProcess (in fileA.js):
const loginProcess = (data) => {
    login(data)
      .then((response) => {
        if (response.status === 200) {

        }
      })
      .catch((e) => {
        setError(true);
      });
  };

If I have an error inside login() function it returns new Error(e) but inside loginProcess() the error from login() is not caught by catch but with then. I need to catch the new Error from login() inside catch in loginProcess(), how can I fix it?

A: You are converting promise rejection into promise fulfilment by returning an error object.
Retuning a non-promise value from the catch block will fulfil the promise returned by the login function with the return value of the catch block.
To reject the promise returned by the login function:

*

*Re-throw the error caught by the catch block, or

*Remove the try-catch block from the login function and let the calling code handle the error.
login function could be re-written as:
export const login = (data) => {
    return auth.login(data);
};

I suggest that you choose the second option and re-write the login function as shown above. There is no need for a catch block that just re-throws the error.


text:
Q: How to get six weeks data from a week column? I have a legacy query in which I am looking data for six weeks as shown below. In my below AND condition I get data for past six weeks and it worked fine in 2020 middle and end. But since 2021 started, this stopped working because of obvious subtraction I am doing with 6.
AND data.week_col::integer BETWEEN DATE_PART(w, CURRENT_DATE) - 6 AND DATE_PART(w, CURRENT_DATE) - 1

There is a bug in above query because of which it stopped working in 2021. How can I change above condition so that it can work entire year without any issues and give me data for past 6 weeks.
Update
Below is my query which I am running:
select *,
dateadd(d, - datepart(dow, trunc(CONVERT_TIMEZONE('UTC','PST8PDT',client_date))), trunc(CONVERT_TIMEZONE('UTC','PST8PDT',client_date)) + 6) as day,
date_part(week, day) as week_col
from holder data
where data.week_col::integer BETWEEN DATE_PART(w, CURRENT_DATE) - 6 AND DATE_PART(w, CURRENT_DATE) - 1

client_date column has values like this - 2021-01-15 21:30:00.0. And from that I get value of day column and from day column I get value of
week_col column as shown above.
week_col column has values like 53, 52 .... It's a week number in general.
Because of my AND condition I am getting data for week 1 only but technically I want data for 49, 50, 51, 52, 53 and 1 as it is past six weeks. Can I use day column here to get correct past six weeks?

A: Would this serve as a solution? I do not know much about the redshirt syntax but I read it supports dateadd(). If you are normalizing client_date to a time zone converted day with no time then why not simply use that in the comparison to the current date converted to the same time zone.
WHERE
    client_date BETWEEN
    DATEADD(WEEK,-6,trunc(CONVERT_TIMEZONE('UTC','PST8PDT',CURRENT_DATE)))
    AND
    DATEADD(WEEK,-1,trunc(CONVERT_TIMEZONE('UTC','PST8PDT',CURRENT_DATE)))

If the above logic works out then you may want to convert the -6 and -1 week to variables, if that is supported.
Solution 2
This is a bit more verbose but involves virtualizing a calender table and then joining your current date parameter into the calender data, for markers. Finally, you can join your data against the calender which has been normalized by weeks in time chronologically.
This is SQL Server syntax, however, I am certain it can be converted to RS.
DECLARE @D TABLE(client_date DATETIME)
INSERT @D VALUES
('11/20/2020'),('11/27/2020'),
('12/4/2020'),('12/11/2020'),('12/18/2020'),('12/25/2020'),
('01/8/2021'),('01/8/2021'),('1/15/2021'),('1/22/2021'),('1/29/2021')

DECLARE @Date DATETIME = '1/23/2021'
DECLARE @StartDate DATETIME = '01/01/2010'
DECLARE @NumberOfDays INT = 6000

;WITH R1(N) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
    R2(N) AS (SELECT 1 FROM R1 a, R1 b),
    R3(N) AS (SELECT 1 FROM R2 a, R2 b),
    Tally(Number) AS (SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM R3)

,WithTally AS
(
    SELECT CalendarDate = DATEADD(DAY,T.Number,@StartDate)
    FROM Tally T
    WHERE T.Number < @NumberOfDays
)
,Calendar AS
(
    SELECT
        CalendarDate,
        WeekIndex = DENSE_RANK() OVER(ORDER BY  DATEPART(YEAR, CalendarDate), DATEPART(WEEK, CalendarDate))
    FROM
        WithTally
),
CalendarAlignedWithCurrentDateParamater AS
(
    SELECT *
    FROM
        Calendar
        CROSS JOIN (SELECT WeekIndexForToday=WeekIndex FROM Calendar WHERE Calendar.CalendarDate=@Date  ) AS X
)
SELECT
    D.*,
    C.WeekIndex,
    C.WeekIndexForToday
FROM
    CalendarAlignedWithCurrentDateParamater C
    INNER JOIN @D D ON D.client_date = C.CalendarDate
WHERE
    C.WeekIndex BETWEEN C.WeekIndexForToday-6 AND C.WeekIndexForToday-1

OPTION (MAXRECURSION 0)


text:
Q: Cannot find name for "en_UK" locale code - error in Sylius So I'm setting up a sylius project using docker and am getting an error when I first tried to load the page. The docker set up on sylius website didn't seem to work so I made my own docker files and can successfully start the docker containers. The error is below:
An exception has been thrown during the rendering of a template ("Cannot find name for "en_UK" locale code").

During the installation, sylius asks whether you want en_US or something different so I typed en_UK, presuming that was the notation required. Upon setup completion, I tried to load root page and I get the error message above. However, strangely, on the symfony toolbar on the error page it says US web store.
If anyone could help at all it would be greatly appreciated. Thank you in advance.

A: Possible ways:

*

*go to localhost/admin, enter your login/password which you entered at the install moment, open Channels section, and there add change default locale/add new to locale list;

*modify a <project-root>/config/services.yaml and change locale value to another;

*in the worst case try to run php bin/console sylius:install command and reinstall database with a en_US at the beginning, then edit Admin section to en_UK

A: en_UK means "English (Ukraine)". No wonder it was missing. What you wanted was probably en_GB.


text:
Q: Watch with Process Substitution I often run the command
squeue -u $USER | tee >(wc -l)

where squeue is a Slurm command to see how many jobs you are running. This gives me both the output from squeue and automatically tells how many lines are in it.
How can I watch this command?
watch -n.1 "squeue -u $USER | tee >(wc -l)" results in
Every 0.1s: squeue -u randoms | tee >(wc -l)                                                                                Wed May  9 14:46:36 2018

sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `squeue -u randoms | tee >(wc -l)'

A: From the watch man page:

Note that command is given to "sh -c" which means that you may need to use extra quoting to get the desired effect.

sh -c also does not support process substitution, the syntax you're using here as >().

Fortunately, that syntax isn't actually needed for what you're doing:
watch -n.1 'out=$(squeue -u "$USER"); echo "$out"; { echo "$out" | wc -l; }'

...or, if you really want to use your original code even at a heavy performance penalty (starting not just one but two new shells every tenth of a second -- first sh, and then bash):
bash_cmd() { squeue -u "$USER" | tee >(wc -l); } # create a function
export -f bash_cmd            # export function to the environment
watch -n.1 'bash -c bash_cmd' # call function from bash started from sh started by watch