text:
Q: GWT FileUpload with Servlet I try to make a very simple GWT-Application: The User can choose a txt file an upload it to the Server. Later I want to implement more functionality but for now I'm stuck on the FileUpload:
On the client Side I have the following Code working:
public class GwtDemoProject implements EntryPoint {

private static final String UPLOAD_ACTION_URL = GWT.getModuleBaseURL() + "upload";

private FormPanel form;
private Label info;
private FileUpload fileupload;
private Button uploadFileBtn;

public void onModuleLoad() {

    init();

    uploadFileBtn.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            String filename = fileupload.getFilename();

            if(filename.length() == 0) {
                Window.alert("File Upload failed");
            } else if(filename.endsWith(".txt")) {

                form.submit();

            } else {
                Window.alert("File is not a txt-file");
            }
        }
    });

    form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
        @Override
        public void onSubmitComplete(SubmitCompleteEvent event) {

            if(event.getResults().length() == 0) {

            } else {
                Window.alert(event.getResults());
            }
        }
    });

    VerticalPanel vp = new VerticalPanel();
    vp.add(info);
    vp.add(fileupload);
    vp.add(new HTML("
"));
    vp.add(uploadFileBtn);

    form.add(vp);
    RootPanel rp = RootPanel.get();
    rp.add(form);
}

private void init() {
    form = new FormPanel();
    form.setAction(UPLOAD_ACTION_URL);
    form.setEncoding(FormPanel.ENCODING_MULTIPART);
    form.setMethod(FormPanel.METHOD_POST);

    info = new Label("Wähle eine Textdatei aus");

    fileupload = new FileUpload();

    uploadFileBtn = new Button("Upload File");
}
}

On my server side I made the following:
public class FileUploadServlet extends HttpServlet
{

private static final long serialVersionUID = 1L;

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> items = upload.parseRequest(request);

        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            File uploadedFile = new File("C:\\samplePath\\"+item.getName()+".txt");
            item.write(uploadedFile);

        }

    } catch (Exception exc) {

    }
}
}

In the web.xml I added the following to the Servlets:

    <servlet>
        <servlet-name>uploadServlet</servlet-name>
        <servlet-class>de.gwt.demo.server.FileUploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>uploadServlet</servlet-name>
        <url-pattern>/gwtdemoproject/upload</url-pattern>
    </servlet-mapping>

I get no error message but I found out that the List in the Servlet is empty so the while loop is never executed. Is something wrong with the request or the submit?

A: I made some changes to my code:
I changed the application layout: I added a TextArea which displays the content of the uploaded txt file. Now this very simple Application take a txt file uploads it to the server, where it gets saved. Then the Server reads the txt file sends the content to the client and deletes the saved file.
Major changes:
I gave the fileupload a name:
public class GwtFileUploadDemo implements EntryPoint {

private static final String UPLOAD_ACTION_URL = GWT.getModuleBaseURL() + "upload";

private FormPanel form;
private Label info;
private FileUpload fileupload;
private Button uploadFileBtn;
private TextArea outputText;

public void onModuleLoad() {

    init();

    uploadFileBtn.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            String filename = fileupload.getFilename();

            if(filename.length() == 0) {
                Window.alert("File Upload failed");
            } else if(filename.endsWith(".txt")) {

                form.submit();

            } else {
                Window.alert("File is not a txt file");
            }
        }
    });

    form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
        @Override
        public void onSubmitComplete(SubmitCompleteEvent event) {

            if(event.getResults().length() == 0) {
                Window.alert("Something went wrong - Try again");
            } else {
                outputText.setText(event.getResults());
            }
        }
    });

    VerticalPanel vp = new VerticalPanel();
    vp.add(info);
    vp.add(fileupload);
    vp.add(new HTML("
"));
    vp.add(uploadFileBtn);
    vp.add(outputText);

    form.add(vp);
    RootPanel rp = RootPanel.get();
    rp.add(form);
}

private void init() {
    form = new FormPanel();
    form.setAction(UPLOAD_ACTION_URL);
    form.setEncoding(FormPanel.ENCODING_MULTIPART);
    form.setMethod(FormPanel.METHOD_POST);

    info = new Label("Choose a txt file");

    fileupload = new FileUpload();

    //Here I added a name to the fileuploader
    fileupload.setName("uploader");

    uploadFileBtn = new Button("Show content of txt File");

    outputText = new TextArea();
    outputText.setEnabled(false);
}
}

In the Servlet on the Server side I added a check if the parsed List is empty.
I create the file with the path, name, and filePath. Then I read the file with a BufferedReader and I write the context in the response:
public class FileUploadServlet extends HttpServlet
{

private static final long serialVersionUID = 1L;

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    System.out.println("Inside doPost");

    try {
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new FileUploadException("error multipart request not found");
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> items = upload.parseRequest(request);

        if (items == null) {
            response.getWriter().write("File not correctly uploaded");
            return;
        }

        Iterator<FileItem> iter = items.iterator();

        while (iter.hasNext()) {
            FileItem item = iter.next();
            System.out.println("Start writing File");

            String uploadPath = ".";
            String fileName = new File(item.getName()).getName();
            String filePath = uploadPath + File.separator + fileName;

            System.out.println("File-Pfad:" + filePath);

            File uploadedFile = new File(filePath);
            item.write(uploadedFile);

            String content = "";

            FileReader fileReader = new FileReader(filePath);

            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line = null;

            while((line = bufferedReader.readLine()) != null) {
                content = content + line + "\n";
            }

            bufferedReader.close();

            PrintWriter out = response.getWriter();
            response.setHeader("Content-Type", "text/html");
            out.println(content);
            out.flush();
            out.close();

            uploadedFile.delete();

            System.out.println("Finished reading File");
        }

    } catch (Exception exc) {
        exc.printStackTrace();
        PrintWriter out = response.getWriter();
        response.setHeader("Content-Type", "text/html");
        out.println("Error");
        out.flush();
        out.close();
    }
    System.out.println("FileUploadServlet doPost end");
}
}

I think the problem was that I forgot to give the fileupload a name, because after I added the name I tested the Code and suddenly got Errors with writing my file.


text:
Q: How to reconfigure Grub2 setup after moving from LVM to non-LVM setup I reconfigured a Fedora installation from an LVM configuration to use plain partitions running EXT4.  Of course, grub.cfg still contains the old LVM mount names (fedora_localhost-root, fedora_localhost-home, etc.) so I am unable to boot.
I currently have three partitions: boot, root, and swap (but swap is out of scope here).  Is there a way for grubby or grub-mkconfig to figure this out and recreate the correct config files or will I need to do this manually?
If manually, which file is the correct location to make the edits?  I notice that on the boot partition the /boot/grub2/grub.cfg file contains default_kernelopts which reference the old LVM paths but unsure if that is the correct place to edit.  The Grub2 docs imply that file is autogenerated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does there exist any function of two independent variables whose both the repeated limits exist and are unequal and also the double limit exist? Does there exist any function of two independent variables whose both the repeated limits do exist and are unequal and also the double limit exist?
I have tried to find out an example but I fail.Please help me in this regard.
Thank you in advance.


text:
Q: How to enforce my Android web app to ask the user for a browser choice How to enforce my Android web app to ask the user for a browser choice in which the application should be open.
EDITED : I will shed more light into what exactly i am planning to do. Actually i am using jquery mobile to add fixed toolbar function. But when i deploy it on the device i saw some flickering on the toolbar. So, i thought that maybe i should see how my app behaves when i deploy it to something else then opera. I am new to android and web dev so please TOLERATE ;)

A: Users will choose how they want your link to open.


text:
Q: Selecting part of a string in a list I'm trying to write a program that displays the names of the planets in the list Planets in descending order by their position from the Sun.
As you can see below, I've managed to figure out how to sort the different planets by their position from the Sun (third value in the strings) but I can't figure out how to remove the numbers and just display the text, as it displays the whole strings from the list and not just the name of the planet which is what I would want ideally. Any ideas?
planet_tuples=[
    ("Mercury",75,1),
    ("Venus",460,2),
    ("Mars",140,4),
    ("Earth",510,3),
    ("Jupiter",62000,5),
    ("Neptune",7640,8),
    ("Saturn",42700,6),
    ("Uranus",8100,7),
    ]
s=(sorted(planet_tuples,key=lambda planet: planet[2],reverse=True))
s.remove(planet_tuples[])
print (s)

A: You can extract first element of tuple with list comprehension:
print ([x[0] for x in s])

Result:
['Neptune', 'Uranus', 'Saturn', 'Jupiter', 'Mars', 'Earth', 'Venus', 'Mercury']


text:
Q: What is the PYQT6 equivalent of PYQT5 QWinThumbnailToolButton Class? spotify example of thumbnail button
I'm trying to implement these thumbnail buttons for my pyqt6 application, however, it looks like pyqt6 has made the QWinThumbnailToolButton class obsolete.
In the changes module: https://doc.qt.io/qt-6/extras-changes-qt6.html, it says that there are explicit replacements, so I've tried looking around the pyqt6 QWindow, and QWidget documentation for any leads but its gotten me nowhere. Does anyone know of a possible solution in PYQT6?


text:
Q: XDocument problematic characters I'm using XDocument to describe a tree of folders' names.
Some folders have special characters, like " ' " and I get an XmlException saying such characters cannot be included in a name.
I've added the following declaration to the document's constructing:
public XDocument file= new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
but I still get the exception. I'd appreciate any solution that will enable comfortable work.
Thanks.

A: Replace the ' with '.
See http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references for a complete list.
Please note that these will not all work by default with XML (see also the Wikipedia page). Most of these have to be defined. Only the following work by default:
' => '
" => "
& => &
> => >
< => <

A: You can't use those characters in element names or attribute names. You can only specify them in attribute values, XText objects or CDATA sections (so long as they are encoded of course).


text:
Q: error in Inserting data in database Problem : Inserting data into database.
Error:

SQLException was unhandled by the user
Incorrect Syntax near the keyword 'User'

the one the I put arrow is the line that is highlighted seems it was the error i'm not sure.
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data.SqlClient
Imports System.Configuration

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)

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

    Protected Sub addBTN_Click(ByVal sender As Object, ByVal e As EventArgs) Handles addBTN.Click
    Dim cmd As New SqlCommand("insert into User (Name, Gender, Age) values ('" & nameTB.Text & "', '" & genderTB.Text & "', '" & ageTB.Text & "')", con)
    cmd.ExecuteNonQuery()  <------------------------------
    con.Close()
    nameTB.Text = ""
    genderTB.Text = ""
    ageTB.Text = ""

End Sub
End Class

A: User is a reserved word so needs to be in square brackets.  Your query is open to SQL injection so needs to be parameterized.  I would advise opening the connection just before you need it. Also use the Using statement will take care of closing and disposal for you.
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
     Using cmd As New SqlCommand("insert into [User] (Name, Gender, Age) values (@nameTB, @genderTB,@ageTB)", con)
        cmd.Parameters.AddWithValue("@nameTB", nameTB.Text)
        cmd.Parameters.AddWithValue("@genderTB", genderTB.Text)
        cmd.Parameters.AddWithValue("@ageTB", ageTB.Text)
        cmd.CommandType = CommandType.Text
        con.Open()
        cmd.ExecuteNonQuery()
        nameTB.Text = ""
        genderTB.Text = ""
        ageTB.Text = ""
    End Using
End Using

A: User is a reserved word. Enclose the word with square brackets:
 Dim cmd As New SqlCommand("insert into [User] (Name, Gender, Age) values ('" & nameTB.Text & "', '" & genderTB.Text & "', '" & ageTB.Text & "')", con)

Source: https://stackoverflow.com/a/6082422/1271037


text:
Q: What is the volume of an n-dimension cube? What is the volume of an n-dimension cube? Consider the length of each side to be $a$. How to solve this problem?

A: The "area" of this shape can be thought of as multiplying each of the side lengths together for $n$ sides. So we could say that the area is $a^n$, where $n$ is the dimension of Euclidean space you're working in and $a$ is the side length of one of the sides of the hypercube ($n$-dimensional cube)

A: Perhaps it would be easier to imagine the volume of the cube to be the "n-dimensional area". Let's consider what happens in 1D, 2D and 3D first:
n=1:
In the first dimension, the volume would be just the side length or a=$a^1$.
For n=2:
This would be the square whose side length is a and the area is $a^2$
For n=3:
This would be the cube with volume of a^3.
For n>3:
I could do an induction proof on the conclusion, however a more intuitive pattern starts to emerge:
having the dimension be $0<n\in\Bbb Z$, would most certainly mean that Volume(n-dimensional cube with side length a)=V(a,n)=$a^n$.
Keep in mind that the units would be $(units)^n$ for the n-dimensional area of an n-dimensional shape with the above restrictions, The dimension should a counting
The reason I said that an induction proof would not be as good is because I am not at the level of education to do this. I know how to do a very basic induction proof,  but I am unconfident for this one. I guess it would go like this:
A line has n units which I will call u which are line segments so u+u+u+...+u=nu similarly, a square has square units, but also a certain amount of squares in one line segment like row so this would be nu+nu+...nu n times getting us $n^2$ u. We have this dimension being d=2 with n d=1 shapes "within" it. number, ie a positive integer excluding zero.
The reason I said that an induction proof would not be as good is because I am not at the level of education to do this. I know how to do a very basic induction proof,  but I am unconfident for this one. I guess it would go like this: A line has n units which I will call u which are line segments so A=u+u+u+...+u=nu similarly, a square has square units, but also a certain amount of squares in one line segment like row so this would be A=nu+nu+...nu n times getting us $n^2$ u. We have this dimension being d=2 with n d=1 shapes "within" it. This means that our "hypothesis" is a d=N+1 cube has n of the d=N cubes "within" it using the same dimension units. The abbreviation u represents any general unit to the n-th power.
All in all, a d=N+1 cube can be drawn by connecting the corresponding vertices of a d=N cube assuming the connecting edge length is equal to the d=N cube edge length. This means that the hypothesis is "argued out" and so is informally correct with A=($n^{N}+...+n^{N})*u$ n times getting us A=n^{N+1}*units^{N+1}.

If a unit was instead defined by,say a n-tetrahedron, these formulas would not be correct for the space as it would likely be transformed.
I am not completely sure about the zeroth dimension nor fractal/fractional dimensions nor complex dimensions nor other types of dimensions here like negative dimensions.
Here are some links to these other dimensions:
Has the notion of having a complex amount of dimensions ever been described? And what about negative dimensionality?,
https://en.m.wikipedia.org/wiki/Fractal_dimension,
Imaginary and Complex Dimensions
Maybe there are other dimensions?


text:
Q: Updating progress bar in Webview when doing a file upload I have noticed that when doing a file upload in Webview and using a progress bar, onProgressChanged is not called when the file upload takes place.
It looks like onProgressChanged is only being called when Webview is downloading content.
I understand that this is probably be design.
How can I track the progress of the file upload using Webview and visualize this using some kind of progress bar?
I have been trying to use a server progress bar but that did not work using Webview because of the following problem: https://stackoverflow.com/questions/15474663/after-submit-form-updates-not-visible-in-webview-using-innerhtml


text:
Q: Inject a parameter into an entity in symfony2 I feel silly asking this question but I can't find a clear answer anywhere.
I have a token entity which has, among other things, a creation_time.
I have a parameter in parameters.yml called token_lifespan.
For a token, if creation_time < (time() - token_lifespan) then it has expired.
The problem is I can't find a nice way to pass the token_lifespan parameter to the entity. I know I could do something like:
$token->hasExpired($this->getParameter('token_lifespan'))

But that feels really icky. I've been looking at making a service, and dependency injection, as a way to pass the token lifespan to the token when it is created, but I can't work out what I'm doing.
I'm making my tokens with $token = new MyToken(); and I'm getting my tokens from doctrine like so:
$this->getDoctrine()
    ->getRepository('MyBundle:MyToken')
    ->find($token_id);

Do I need to make my repository a service? Something like:
mytoken_repository:
    class:  MyBundle\Entity\MyToken
    factory_service: 'doctrine.orm.default_entity_manager'
    factory_method:  'getRepository'
    calls:
         - [setLifespan, ['%token_lifespan%']]

And what exactly does this mean? Do I still create tokens the same way, with new MyToken()? and just make a setLifespan method in the MyToken class to store the lifespan?
Finally, can I still get tokens back from Doctrine with $this->getDoctrine()...? and what if I need to use the token_lifespan parameter in my repository class?
Sorry there's about a million questions in there. I feel like the dependency injection part of the Symfony docs assumes I know a lot more about the framework than I currently do.

A: Let's focus on this:

I've been looking at making a service, and dependency injection, as a way to pass the token lifespan to the token when it is created, but I can't work out what I'm doing.

I will strongly recommend you using Event Listener, prePersist in particular. Why? Simply, if you pass your lifespan to the event listener, and there you calculate your expiration date, you can set that date to your entity and use it later, when needed. Quote from Doctrine documentation about prePersist events:

prePersist - The prePersist event occurs for a given entity before the respective EntityManager persist operation for that entity is executed. It should be noted that this event is only triggered on initial persist of an entity (i.e. it does not trigger on future updates).

So, what do you need to do? Register the listener class first:
token.listener:
    class: MyBundle\EventListener\TokenListener
    arguments:
        - %token_lifespan%
    tags:
        - { name: doctrine.event_listener, event: prePersist }

With this, you can easily pass your token_lifespan as a constructor to your class.
Then, you need to create the class itself:
namespace MyBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use MyBundle\Entity\Token;

class TokenListener
{
    /**
     * @var int
     **/
    private $token_lifespan = null;

    public function __construct($tokenLifespan) {
        $this->token_lifespan = $tokenLifespan;
    }

    public function postPersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $entityManager = $args->getEntityManager();

        // Do your magic here, only if our class is of type Token
        if ($entity instanceof Token) {
            // Calculate your expiration date here using $this->token_lifespan
            // and once you're done, set the result to the entity

            $entity->setExpirationDate(....);
        }
    }
}

I can explain why creating Repository as a service would not work for you, if you like. But anyway, give this a try.

A: You should get the logic out of the entity and make a service with it. An entity should not have any dependencies.
You configure the service to have %token_lifespan% as an argument and make a method like this:
/**
 * @return boolean
 */
function isExpired(Token $token) {
   //your logic here, add dependencies to constructor and "arguments:" in service configuration
}

I hope this gets you started.


text:
Q: How to get printed output from ctypes C functions into Jupyter/IPython notebook? Introduction
Suppose I have this C code:
#include <stdio.h>

// Of course, these functions are simplified for the purposes of this question.
// The actual functions are more complex and may receive additional arguments.

void printout() {
    puts("Hello");
}
void printhere(FILE* f) {
    fputs("Hello\n", f);
}

That I'm compiling as a shared object (DLL): gcc -Wall -std=c99 -fPIC -shared example.c -o example.so
And then I'm importing it into Python 3.x running inside Jupyter or IPython notebook:
import ctypes
example = ctypes.cdll.LoadLibrary('./example.so')

printout = example.printout
printout.argtypes = ()
printout.restype = None

printhere = example.printhere
printhere.argtypes = (ctypes.c_void_p)  # Should have been FILE* instead
printhere.restype = None

Question
How can I execute both printout() and printhere() C functions (through ctypes) and get the output printed inside the Jupyter/IPython notebook?
If possible, I want to avoid writing more C code. I would prefer a pure-Python solution.
I also would prefer to avoid writing to a temporary file. Writing to a pipe/socket might be reasonable, though.
The the expected state, the current state
If I type the following code in one Notebook cell:
print("Hi")           # Python-style print
printout()            # C-style print
printhere(something)  # C-style print
print("Bye")          # Python-style print

I want to get this output:
Hi
Hello
Hello
Bye

But, instead, I only get the Python-style output results inside the notebook. The C-style output gets printed to the terminal that started the notebook process.
Research
As far as I know, inside Jupyter/IPython notebook, the sys.stdout is not a wrapper to any file:
import sys

sys.stdout

# Output in command-line Python/IPython shell:
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
# Output in IPython Notebook:
<IPython.kernel.zmq.iostream.OutStream at 0x7f39c6930438>
# Output in Jupyter:
<ipykernel.iostream.OutStream at 0x7f6dc8f2de80>

sys.stdout.fileno()

# Output in command-line Python/IPython shell:
1
# Output in command-line Jupyter and IPython notebook:
UnsupportedOperation: IOStream has no fileno.

Related questions and links:

*

*Python ctypes: Python file object <-> C FILE *

*Python 3 replacement for PyFile_AsFile

*Using fopen, fwrite and fclose through ctypes

*Python ctypes DLL stdout

*Python: StringIO for Popen - Workaround for the lack of fileno() in StringIO, but only applies to subprocess.Popen.

The following two links use similar solutions that involve creating a temporary file. However, care must be taken when implementing such solution to make sure both Python-style output and C-style output gets printed in the correct order.

*

*How do I prevent a C shared library to print on stdout in python?

*Redirecting all kinds of stdout in Python
Is it possible to avoid a temporary file?
I tried finding a solution using C open_memstream() and assigning the returned FILE* to stdout, but it did not work because stdout cannot be assigned.
Then I tried getting the fileno() of the stream returned by open_memstream(), but I can't because it has no file descriptor.
Then I looked at freopen(), but its API requires passing a filename.
Then I looked at Python's standard library and found tempfile.SpooledTemporaryFile(), which is a temporary file-like object in memory. However, it gets written to the disk as soon as fileno() is called.
So far, I couldn't find any memory-only solution. Most likely, we will need to use a temporary file anyway. (Which is not a big deal, but just some extra overhead and extra cleanup that I'd prefer to avoid.)
It may be possible to use os.pipe(), but that seems difficult to do without forking.

A: I've finally developed a solution. It requires wrapping the entire cell inside a context manager (or wrapping only the C code). It also uses a temporary file, since I couldn't find any solution without using one.
The full notebook is available as a GitHub Gist: https://gist.github.com/denilsonsa/9c8f5c44bf2038fd000f

Part 1: Preparing the C library in Python
import ctypes

# use_errno parameter is optional, because I'm not checking errno anyway.
libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)

class FILE(ctypes.Structure):
    pass

FILE_p = ctypes.POINTER(FILE)

# Alternatively, we can just use:
# FILE_p = ctypes.c_void_p

# These variables, defined inside the C library, are readonly.
cstdin = FILE_p.in_dll(libc, 'stdin')
cstdout = FILE_p.in_dll(libc, 'stdout')
cstderr = FILE_p.in_dll(libc, 'stderr')

# C function to disable buffering.
csetbuf = libc.setbuf
csetbuf.argtypes = (FILE_p, ctypes.c_char_p)
csetbuf.restype = None

# C function to flush the C library buffer.
cfflush = libc.fflush
cfflush.argtypes = (FILE_p,)
cfflush.restype = ctypes.c_int

Part 2: Building our own context manager to capture stdout
import io
import os
import sys
import tempfile
from contextlib import contextmanager

@contextmanager
def capture_c_stdout(encoding='utf8'):
    # Flushing, it's a good practice.
    sys.stdout.flush()
    cfflush(cstdout)

    # We need to use a actual file because we need the file descriptor number.
    with tempfile.TemporaryFile(buffering=0) as temp:
        # Saving a copy of the original stdout.
        prev_sys_stdout = sys.stdout
        prev_stdout_fd = os.dup(1)
        os.close(1)

        # Duplicating the temporary file fd into the stdout fd.
        # In other words, replacing the stdout.
        os.dup2(temp.fileno(), 1)

        # Replacing sys.stdout for Python code.
        #
        # IPython Notebook version of sys.stdout is actually an
        # in-memory OutStream, so it does not have a file descriptor.
        # We need to replace sys.stdout so that interleaved Python
        # and C output gets captured in the correct order.
        #
        # We enable line_buffering to force a flush after each line.
        # And write_through to force all data to be passed through the
        # wrapper directly into the binary temporary file.
        temp_wrapper = io.TextIOWrapper(
            temp, encoding=encoding, line_buffering=True, write_through=True)
        sys.stdout = temp_wrapper

        # Disabling buffering of C stdout.
        csetbuf(cstdout, None)

        yield

        # Must flush to clear the C library buffer.
        cfflush(cstdout)

        # Restoring stdout.
        os.dup2(prev_stdout_fd, 1)
        os.close(prev_stdout_fd)
        sys.stdout = prev_sys_stdout

        # Printing the captured output.
        temp_wrapper.seek(0)
        print(temp_wrapper.read(), end='')

Part Fun: Using it!
libfoo = ctypes.CDLL('./foo.so')

printout = libfoo.printout
printout.argtypes = ()
printout.restype = None

printhere = libfoo.printhere
printhere.argtypes = (FILE_p,)
printhere.restype = None

print('Python Before capturing')
printout()  # Not captured, goes to the terminal

with capture_c_stdout():
    print('Python First')
    printout()
    print('Python Second')
    printhere(cstdout)
    print('Python Third')

print('Python After capturing')
printout()  # Not captured, goes to the terminal

Output:
Python Before capturing
Python First
C printout puts
Python Second
C printhere fputs
Python Third
Python After capturing

Credits and further work
This solution is fruit of reading all the links I linked at the question, plus a lot of trial and error.
This solution only redirects stdout, it could be interesting to redirect both stdout and stderr. For now, I'm leaving this as an exercise to the reader. ;)
Also, there is no exception handling in this solution (at least not yet).

A: I spend a whole afternoon to revise it for python2, damn, it's tricky, the key is to reopen the tempfile with io.open
Then I try a better solution, just write a Logger class for python stdout
# -*- coding: utf-8 -*-

import ctypes
# from ctypes import *
from ctypes import util

# use_errno parameter is optional, because I'm not checking errno anyway.
libraryC = ctypes.util.find_library('c')
libc = ctypes.CDLL(libraryC, use_errno=True)

# libc = cdll.msvcrt

class FILE(ctypes.Structure):
    pass

FILE_p = ctypes.POINTER(FILE)

# Alternatively, we can just use:
# FILE_p = ctypes.c_void_p

# These variables, defined inside the C library, are readonly.
##cstdin = FILE_p.in_dll(libc, 'stdin')
##cstdout = FILE_p.in_dll(libc, 'stdout')
##cstderr = FILE_p.in_dll(libc, 'stderr')

# C function to disable buffering.
csetbuf = libc.setbuf
csetbuf.argtypes = (FILE_p, ctypes.c_char_p)
csetbuf.restype = None

# C function to flush the C library buffer.
cfflush = libc.fflush
cfflush.argtypes = (FILE_p,)
cfflush.restype = ctypes.c_int

import io
import os
import sys
import tempfile
from contextlib import contextmanager
#import cStringIO

def read_as_encoding(fileno, encoding="utf-8"):
    fp = io.open(fileno, mode="r+", encoding=encoding, closefd=False)
    return fp

class Logger(object):
    def __init__(self, file, encoding='utf-8'):
        self.file = file
        self.encoding = encoding

    def write(self, message):
        self.file.flush()  # Meed to flush
        # python2 temp file is always binary
        # msg_unicode = message.('utf-8')
        self.file.write(message)

@contextmanager
def capture_c_stdout(on_output, on_error=None, encoding='utf8'):
    # Flushing, it's a good practice.
    sys.stdout.flush()
    sys.stderr.flush()
    ##cfflush(cstdout)
    # cfflush(cstdcerr)

    # We need to use a actual file because we need the file descriptor number.
    with tempfile.NamedTemporaryFile() as temp:
        with tempfile.NamedTemporaryFile() as temp_err:
            # print "TempName:", temp.name
            # print "TempErrName:", temp_err.name

            # Saving a copy of the original stdout.
            prev_sys_stdout = sys.stdout
            prev_stdout_fd = os.dup(1)
            os.close(1)
            # Duplicating the temporary file fd into the stdout fd.
            # In other words, replacing the stdout.
            os.dup2(temp.fileno(), 1)

            if on_error:
                prev_sys_stderr = sys.stderr
                prev_stderr_fd = os.dup(2)
                os.close(2)
                os.dup2(temp_err.fileno(), 2)

            # Replacing sys.stdout for Python code.
            #
            # IPython Notebook version of sys.stdout is actually an
            # in-memory OutStream, so it does not have a file descriptor.
            # We need to replace sys.stdout so that interleaved Python
            # and C output gets captured in the correct order.
            #
            # We enable line_buffering to force a flush after each line.
            # And write_through to force all data to be passed through the
            # wrapper directly into the binary temporary file.
            # No need to use TextIOWrapper in python2, in python2, tempFile is always binary according to official document
            ##temp_wrapper = io.TextIOWrapper(
            ##   read_as_encoding(temp.fileno(), encoding=encoding), encoding=encoding, line_buffering=True) ##, write_through=True)

            # temp_wrapper_python = io.TextIOWrapper(
            #    read_as_encoding(temp.fileno(), encoding=encoding), encoding='ascii', line_buffering=True)
            temp_wrapper_python = Logger(temp, encoding=encoding)
            sys.stdout = temp_wrapper_python

            if on_error:
                # temp_wrapper_err = io.TextIOWrapper(
                #   read_as_encoding(temp_err.fileno(), encoding=encoding), encoding=encoding, line_buffering=True) ##, write_through=True)
                temp_wrapper_python_err = Logger(temp_err, encoding=encoding)
                # string_str_err = cStringIO.StringIO()
                sys.stderr = temp_wrapper_python_err

            # Disabling buffering of C stdout.
            ##csetbuf(cstdout, None)

            yield

            # Must flush to clear the C library buffer.
            ##cfflush(cstdout)

            # Restoring stdout.
            os.dup2(prev_stdout_fd, 1)
            os.close(prev_stdout_fd)
            sys.stdout = prev_sys_stdout

            if on_error:
                os.dup2(prev_stderr_fd, 2)
                os.close(prev_stderr_fd)
                sys.stderr = prev_sys_stderr

            # Printing the captured output.
            # temp_wrapper.seek(0)
            # print "Reading: "
            # print temp_wrapper.read()
            if on_output:
                temp.flush()
                temp.seek(0)
                on_output(temp.read())
            temp.close()

            if on_error:
                temp_err.flush()
                temp_err.seek(0)
                on_error(temp_err.read())
                temp_err.close()

import repo_checker_cpp

def on_capture_output(input_stream):
    if input_stream:
        print "Here is captured stdout: \n", input_stream

def on_capture_err(input_stream):
    if input_stream:
        print "Here is captured stderr: \n", input_stream

if __name__ == '__main__':
    with capture_c_stdout(on_capture_output, on_capture_err) as custom_output:  # redirection here
        # repo_checker_cpp is a ctypes.CDll module
        print >> sys.stderr, "Hello World in python err\n"
        repo_checker_cpp.test_exception()  # throw an exception an capture inside cpp module then output to std::cerr
        print "Hello World in python\n"
        repo_checker_cpp.hello_world()  # simple std::cout << "Hello World" << std::endl; std::cerr << "Hello World in cerr" << std::endl;

I can't get cstdin = FILE_p.in_dll(libc, 'stdin') alike lines working.  I comment them with ## to indicate they are originally written by Denilson.  And thank Denilson for your work.
It works fine in my Window10 + python 2.7, outputs:
Here is captured stdout:
Hello World in python
Hello World(C++)

Here is captured stderr:
Hello World in python err
RepoCheckCpp_TestException, Reason: ensure failed : false
xxxxx\repocheckercpp.cpp(38)
context variables:
    error : This is a test exception

Hello World(C++) in cerr

Everything is perfectly captured

A: One simple way is to pass a wrapped callback to c function
@ctypes.CFUNCTYPE(None, ctypes.c_char_p)
def print_callback(a):
   print(a.decode())

dll.myfunc(print_callback)

extern "C" {

void myfunc(void (*print_callback)(const char *s)) {
  print_callback("print to notebook\n");
}
}

reference:
Callbacks with ctypes (How to call a python function from C)


text:
Q: boost python raw_function method I want to expose a class method using raw_function. Something like:
namespace py = boost::python;

class MyObject {
public:
    py::object foo(py::tuple args, py::dict kwargs) {
        // whatever
    }
};

Right now, I can use raw_function to wrap a static function that has to pull self out, so something like:
static py::object MyObject_foo(py::tuple args, py::dict kwargs) {
    MyObject& self = py::extract<MyObject&>(args[0]);

    // the docs allege that I can do args.slice(1), but that doesn't
    // compile on boost 1.55 at least, with no matching function
    // call to 'boost::python::tuple::slice(int ) const
    self.foo(py::extract<py::tuple>(args.slice(1, py::len(args))),
             kwargs);
}

py::class_<MyClass>("MyClass")
    .def("foo", py::raw_function(&MyObject_foo, 1));

That works, but is pretty verbose. I actually have several raw functions that I need wrapped and would prefer not to have to go through this intermediate step on each one of them. Is there a shorter way to wrap MyObject::foo?

A: You can skip the extra function by using a static member function, then extracting self in the same way, i.e.
namespace py = boost::python;

class MyObject {
public:
    static py::object foo(py::tuple args, py::dict kwargs)
    {
        MyObject& self = py::extract<MyObject&>(args[0]);
        // Do stuff with the self object
    }
};

py::class_<MyObject>("MyObject")
    .def("foo", py::raw_function(&MyObject::foo, 1));

It's not quite wrapping a class method directly, but it's cleaner than using an intermediate function.


text:
Q: How to use double-float? I am struggling a little trying to figure out how to tell Lisp that I want to use double-float values. Suppose I have:
(let ((x 1)) (format t "~A~%" (/ x 3.0)))

Which gives:
0.33333334

If I want to use double-float, I tried this:
(let ((x 1)) (declare (type double-float x)) (format t "~A~%" (/ x 3.0)))
0.33333334

So the result is not a double-float. I can, however, force double-float like this:
(let ((x 1)) (format t "~A~%" (/ x 3.0d0)))
0.3333333333333333d0

And now I get a double-float result.
So my question is: if I'm defining a form or function in which I want arithmetic to be in double-float, how do I establish that? I've read lots of online resources on using declare, proclaim, etc, but haven't been able to apply it to getting the result I'm after. I'm not convinced I know how to utilize these in this context, or even if they are the correct mechanism to use.
Same question would apply if I were trying to do long-float or anything else that isn't the default.

A: As you noted you can type d0 after the number.  E.g.,
* 3.0d0
; => 3.0d0
* (type-of 3.0d0)
;=> DOUBLE-FLOAT

However, that's the literal notation for a double float, just like 1 is the literal notation for an integer. You can customize the default type of floating point numbers from the reader with *read-default-float-format*, and Rainer Joswig's answer shows how.  The declaration
(declare (type double-float x))

is a promise to the compiler that the value of the variable x is a double float.  You're lying to the compiler.   To get a double float, you'll need to either write one as a literal (e.g., 1.0d0) or convert one with the float function:
* (float 1 0.0d0)
;=> 1.0d0

You could also use coerce here:
* (coerce 1 'double-float)
;=> 1.0d0

When there's an option, it's reasonable to compare them.  In SBCL, it turns out that these two options actually compile to the same thing:
CL-USER> (disassemble (compile nil (lambda (x) (coerce x 'double-float))))
; disassembly for (LAMBDA (X))
; 039C33E8:       488BD6           MOV RDX, RSI               ; no-arg-parsing entry point
;      3EB:       488B059EFFFFFF   MOV RAX, [RIP-98]          ; #<FDEFINITION object for SB-KERNEL:%DOUBLE-FLOAT>
;      3F2:       B908000000       MOV ECX, 8
;      3F7:       FF7508           PUSH QWORD PTR [RBP+8]
;      3FA:       FF6009           JMP QWORD PTR [RAX+9]
;      3FD:       CC0A             BREAK 10                   ; error trap
;      3FF:       02               BYTE #X02
;      400:       18               BYTE #X18                  ; INVALID-ARG-COUNT-ERROR
;      401:       54               BYTE #X54                  ; RCX
NIL

CL-USER> (disassemble (compile nil (lambda (x) (float x 0.0d0))))
; disassembly for (LAMBDA (X))
; 03BC5B18:       488BD6           MOV RDX, RSI               ; no-arg-parsing entry point
;       1B:       488B059EFFFFFF   MOV RAX, [RIP-98]          ; #<FDEFINITION object for SB-KERNEL:%DOUBLE-FLOAT>
;       22:       B908000000       MOV ECX, 8
;       27:       FF7508           PUSH QWORD PTR [RBP+8]
;       2A:       FF6009           JMP QWORD PTR [RAX+9]
;       2D:       CC0A             BREAK 10                   ; error trap
;       2F:       02               BYTE #X02
;       30:       18               BYTE #X18                  ; INVALID-ARG-COUNT-ERROR
;       31:       54               BYTE #X54                  ; RCX
NIL

It sounds like you're trying to do some automatic conversion, and I don't think you're going to find a way to do that.  If you've got a number coming in, and you want a double-float you'll have to convert it yourself.  If you want to check that a value coming in is a double-float you might have some luck with declarations, but a type declaration is just a promise to the compiler that something will have a particular type;  this usually means that the compiler can omit checks since it's been promised that the value will have a certain type.  That said, you might have some luck;  in SBCL:
> (defun foo (x)
    (declare (double-float x))
    (+ x 2.0d0))

> (foo 3)
; The value 3 is not of type DOUBLE-FLOAT.
;    [Condition of type TYPE-ERROR]

You might get different results if you change the safety optimization, though.  If you want to ensure a type check, then use check-type:
> (defun foo (x)
    (check-type x double-float)
    (+ x 2.0d0))

> (foo 3)
; The value of X is 3, which is not of type DOUBLE-FLOAT.
;    [Condition of type SIMPLE-TYPE-ERROR]

A: If you want to compute with a special float format you have to tell it. Usually if you divide double-floats, the result will be a double float. If you have constants, you need to denote them as such.
The Common Lisp standard says: The result of a numerical function is a float of the largest format among all the floating-point arguments to the function..
The interpretation of the following depends on a few things. It depends on how the reader reads numbers. For integers the base can be specified. For floats it depends on the default float format.
(let ((x 1)) (format t "~A~%" (/ x 3.0)))

Let's see how *read-default-float-format* affects it:
CL-USER 9 > *read-default-float-format*
SINGLE-FLOAT

CL-USER 10 > (let ((x 1)) (format t "~A~%" (/ x 3.0)))
0.33333334
NIL

CL-USER 11 > (setf *read-default-float-format* 'double-float)
DOUBLE-FLOAT

CL-USER 12 > (let ((x 1)) (format t "~A~%" (/ x 3.0)))
0.3333333333333333
NIL

Also note that you can specify the type for literal numbers by using an exponent marker:

*

*d = double-float

*e = float of *read-default-float-format*

*f = single-float

*l = long-float

*s = short-float

Example:
CL-USER 15 > (setf *read-default-float-format* 'single-float)
SINGLE-FLOAT

CL-USER 16 > (let ((x 1)) (format t "~A~%" (/ x 3.0d0)))
0.3333333333333333D0
NIL

You can also coerce numbers to a certain type. The function COERCE makes it explicit which type you mean:
CL-USER 17 > (let ((x 1))
               (format t "~A~%" (/ (coerce x 'double-float) 3.0)))
0.3333333333333333D0
NIL


text:
Q: iOS 13 : Allow Once Location permission with WiFi SSID result in error : [ ] nehelper sent invalid result code [1] for Wi-Fi information request I have been using WiFi Information in my app. I have been using this functionality perfectly till now but since iOS 13 and introduction of new location permission "Allow Once" it throws me this error: [ ] nehelper sent invalid result code [1] for Wi-Fi information request. This error comes when I try to switch to the WiFi Setting page to connect to WiFi SSID for the second time in my app.
Allow Once Permission:
It gives provisional authorization which is similar to 'When in Use' permission but active for only a single session. So, If a user chooses the allow once permission option, your app can access their current location until your app is moved to the background and becomes inactive. If your app becomes active again, you have to ask for location permission again.
Below is my code to get location permission:
locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.requestAlwaysAuthorization()

In my case, I select Allow once permission then goes to the background twice to select the WiFi access point 2 times in total. It works for the first time, however, in 2nd time it does not give me connected WiFi SSID information and instead it gives me this error: [ ] nehelper sent invalid result code [1] for Wi-Fi information request. How can I have connected WiFi SSID all the time in 'Allow Once' location permission? As per the new changes in iOS 13 as below:

WiFi configuration is using CNCopyCurrentNetworkInfo which returns the
  current network information for a given network interface. So this
  dictionary is containing our current network Info mainly SSID of wifi
  network.
The requesting app must meet the following requirements:
The app uses Core Location and has the user's authorization to use
  location information.
An app that fails to meet the above requirements receives the
  following return value:
An app linked against iOS 12 or earlier receives a dictionary with
  pseudo-values. In this case, the SSID is Wi-Fi (or WLAN in the China
  region), and the BSSID is 00:00:00:00:00:00.
An app linked against* iOS 13* or later receives NULL.
If you don't meet the above conditions CNCopyCurrentNetworkInfo will always return nil in iOS 13.
Reference:
  [https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo][1]


text:
Q: Form is validating but still sends through even after error message I am building a web form with validation and when the form is submitted with none of the fields filled in It pops up with the error message but then still goes through. Maybe someone else can see my mistake. Below I added the scripts for both the form and validators.
Thank you in advance!
function validateForm()
{
    var x=document.forms["contactform"]["fname"].value;
    if (x==null || x=="" || x=="First Name*" )
    {
        alert("Please Provide your First Name");
        return false;
    }

    var y=document.forms["contactform"]["lname"].value;
    if (y==null || y=="" || y=="Last Name*" )
    {
        alert("Please Provide your Last Name");
        return false;
    }

    var em = document.forms["contactform"]["email"].value;
    if (em == null || em == "" || em == "Email*")
    {
        alert("Please Provide your Email");
        return;
    }

    var atpos=em.indexOf("@");
    var dotpos=em.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=em.length)
    {
        alert("E-mail address is not valid");
        return false;
    }

    var ph = document.forms["contactform"]["phone"].value;
    if (ph ==null || ph=="" || ph=="Phone*" )
    {
        alert("Please Provide your Phone Number");
        return;
    }

        document.contactform.submit();

}

<form class="cmxform" id="contactform" method="post" action="contact-life-factor2.asp" >
                <input name="fname" type="text"class="required" onBlur="if(this.value=='')this.value=this.defaultValue;" onFocus="if(this.value===this.defaultValue)this.value='';" value="First Name*" />
                <input name="lname" type="text"class="required" onBlur="if(this.value=='')this.value=this.defaultValue;" onFocus="if(this.value===this.defaultValue)this.value='';" value="Last Name*" />
                <input name="company" type="text"class="" onBlur="if(this.value=='')this.value=this.defaultValue;" onFocus="if(this.value===this.defaultValue)this.value='';" value="Company" />
                <input name="email" type="text" class="required" onBlur="if(this.value=='')this.value=this.defaultValue;" onFocus="if(this.value===this.defaultValue)this.value='';" value="Email*"/>
                <input name="phone" type="text" class="" onBlur="if(this.value=='')this.value=this.defaultValue;" onFocus="if(this.value===this.defaultValue)this.value='';" value="Phone*"/>

Comments:

                <textarea name="comments" cols="" rows="" onBlur="if(this.value=='')this.value=this.defaultValue;" onFocus="if(this.value===this.defaultValue)this.value='';" value="comments" ></textarea>

                <input type="submit" value="Submit" name="submit" class="submit" onClick="javascript:validateForm();"  style="margin-right:44px;"/>
                </form>

A: So there are a couple of issues:

*

*return; is not equivalent to return false; or return true;, you need to be explicit with your return value as this will dictate whether or not your form submits (true) or not (false).

*Remove the onclick from your submit button and move it to your form tag as an onsubmit event
onsubmit="return validateForm()"

A: onclick of submit validation doesnt stop.use onsubmit in form
<form class="cmxform" id="contactform" method="post" onsubmit="return validateForm();" action="contact-life-factor2.asp" >

function validateForm()
{
var x=document.forms["contactform"]["fname"].value;
if (x==null || x=="" || x=="First Name*" )
{
    alert("Please Provide your First Name");
    return false;
}

var y=document.forms["contactform"]["lname"].value;
if (y==null || y=="" || y=="Last Name*" )
{
    alert("Please Provide your Last Name");
    return false;
}

var em = document.forms["contactform"]["email"].value;
if (em == null || em == "" || em == "Email*")
{
    alert("Please Provide your Email");
    return false;
}

var atpos=em.indexOf("@");
var dotpos=em.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=em.length)
{
    alert("E-mail address is not valid");
    return false;
}

var ph = document.forms["contactform"]["phone"].value;
if (ph ==null || ph=="" || ph=="Phone*" )
{
    alert("Please Provide your Phone Number");
    return;
}

}


text:
Q: Objective-C does not execute change method for a NSPopUpButton I have a view with a popup menu. In the view controller I implemented a method for reading which tag/item is selected by the user.
- (IBAction)popUpChanged:(id)sender
{
    self.item = [sender selectedTag];
}

If I choose a menu entry/item the method popUpChanged is executed.
In another class I have a button. By clicking this button the popup menu of the view controller should be set to the item no. 1. Therefore the button-action executes the following line.
[_viewController.popUp selectItemWithTag: 1];

After executing the selectItemWithTag:1 the popup menu is set to the item 1, like expected. The state/item of the popup menu is change, but the button click does not result in the execution of the method popUpChanged?
Can somebody please explain it to me why the method popUpChanged is not executed?

A: -popUpChanged: is what you set as the action method for the pop-up menu. Programmatically changing the pop-up menu is not an "action" on that pop-up menu. The action is only triggered for user interactions with the pop-up menu.
It is a fairly general pattern within Cocoa that programmatic operations on controls don't go through the same pathways as user manipulations of those controls. For example, a control can be disabled so the user can't change it, but you can still change it programmatically. Or a window's delegate can prevent closing the window in its -windowShouldClose:, but programmatically closing the window with -close is not subject to that (although -performClose: is).
In any case, given that you're programmatically changing the selected item in the pop-up menu, you can programmatically invoke the action method or, more usually, do the same operation as the action method would (e.g. [_viewController.popUp selectItemWithTag: 1]; _viewController.item = 1;).
Or, even better, bind the pop-up button's selectedTag binding to the view controller's item property and a) eliminate the action method, and b) replace your programmatic manipulation of the pop-up with programmatic setting of the view controller's item property.


text:
Q: Applying LSA on term document matrix when number of documents are very less I have a term-document matrix (X) of shape (6, 25931). The first 5 documents are my source documents and the last document is my target document. The column represents counts for different words in the vocabulary set. I want to get the cosine similarity of the last document with each of the other documents.
But since SVD produces an S of size (min(6, 25931),), If I used the S to reduce my X, I get a 6 * 6 matrix. But In this case, I feel that I will be losing too much information since I am reducing a vector of size (25931,) to (6,).
And when you think about it, usually, the number of documents will always be less than number of vocabulary words. In this case, using SVD to reduce dimensionality will always produce vectors that are of size (no documents,).
According to everything that I have read, when SVD is used like this on a term-document matrix, it's called LSA.

*

*Am I implementing LSA correctly?

*If this is correct, then is there any other way to reduce the dimensionality and get denser vectors where the size of the compressed vector is greater than (6,)?

P.S.: I also tried using fit_transform from sklearn.decomposition.TruncatedSVD which expects the vector to be of the form (n_samples, n_components) which is why the shape of my term-document matrix is (6, 25931) and not (25931, 6). I kept getting a (6, 6) matrix which initially confused me. But now it makes sense after I remembered the math behind SVD.

A: If the objective of the exercise is to find the cosine similarity, then the following approach can help. The author is only attempting to solve for the objective and not to comment on the definition of Latent Semantic Analysis or the definition of Singular Value Decomposition mentioned by the questioner.

Let us first invoke all the required libraries. Please install them if they do not exist in the machine.
from sklearn.metrics.pairwise import cosine_similarity
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer

Let us generate some sample data for this exercise.
df = {'sentence': ['one two three','two three four','four five','six seven eight nine ten']}
df = pd.DataFrame(df, columns = ['sentence'])

The first step is to get the exhaustive list of all the possible features. So collate all of the content at one place.
all_content = [' '.join(df['sentence'])]

Let us build a vectorizer and fit it now. Please note that the arguments in the vectorizer are not explained by the author as the focus is on solving the problem.
vectorizer = TfidfVectorizer(encoding = 'latin-1',norm = 'l2', min_df = 0.03, ngram_range = (1,2), max_features = 5000)
vectorizer.fit(all_content)

We can inspect the vocabulary to see if it makes sense. If needed, one could add stop words in the vectorizer above and supress them to see if they are indeed supressed.
print(vectorizer.vocabulary_)

Let us vectorize the sentences for us to deploy cosine similarity.
s1Tokens =  vectorizer.transform(df.iloc[1,])
s2Tokens = vectorizer.transform(df.iloc[2,])

Finally, the cosine of the similarity can be computed as follows.
cosine_similarity(s1Tokens , s2Tokens)


text:
Q: Python: get all items from a list between 2 known string or Indexes I am trying to find all the items between two given indexes.
for eg: i have list that looks like this:
mylist = ['ABC', 'COMMENT', 'YES', 'YES', 'NO', '123', 'COMMENT','GONOW','MAKE','COMMENT', 'YES','COMMENT']

i want the output to be show as below:
Note: Below outputs are the index value between two 'COMMENT'.
First output  :  'YES', 'YES', 'NO', '123'
second output :  'GONOW','MAKE'
third output  :  'YES'

I have two thoughts to handle this situation:
1) if i know the search_string as 'COMMENT' then i should be able find everything between two known strings, something like this :
string = 'COMMENT'
find_values = mylist[findfirst(comment)-findsecond(comment)]
find_values = mylist[findsecond(comment)-findthird(comment)]

2) if i know the index of all 'COMMENT' then i should be able find_all between two known indexs, something like this :
idx1_comment = 1
idx2_comment = 6
idx3_comment = 9

print mylist(range(2-5))
print mylist(range(6-8))

Any ideas?
Thanks...
Also, i have another request.
For #1 option, if i have list wherein i have a lot of items between strings 'comment' and 'border' then what be the way for that as well?
Btw, i tried following this article, but with no benefit.
Python: get items from list between 2 known items

A: Why not simply iterate the list once:
result = []
sublist = []

separators = ('COMMENT', 'BORDER')
mylist = ['ABC', 'COMMENT', 'YES', 'YES', 'NO', '123', 'COMMENT','GONOW','MAKE','COMMENT', 'YES','COMMENT', 'BORDER', 'FOO', '123']

for x in mylist:
    if x in separators:
        if sublist:
            result.append(sublist)
        sublist = []
    else:
        sublist.append(x)
result.append(sublist)

print (result)

Returns:
[['ABC'], ['YES', 'YES', 'NO', '123'], ['GONOW', 'MAKE'], ['YES'], ['FOO', '123']]

A: If all you want is to filter out the strings between two predefined strings, this code will do:
def filter_output_between_strings(input: [str], separator: str):
    separator_indexes = [index for index, word in enumerate(input) if word == separator]
    for example_index, (start, end) in enumerate(zip(separator_indexes[:-1], separator_indexes[1:]), start=1):
        print('Example: {}: {}'.format(example_index, input[start + 1:end]))

if __name__ == '__main__':
    input = ['ABC', 'COMMENT', 'YES', 'YES', 'NO', '123', 'COMMENT', 'GONOW', 'MAKE', 'COMMENT', 'YES', 'COMMENT']
    filter_output_between_strings(input, 'COMMENT')

Output:
Example: 1: ['YES', 'YES', 'NO', '123']
Example: 2: ['GONOW', 'MAKE']
Example: 3: ['YES']

A: You could leverage islice on itertools:
from itertools import islice

mylist = ['ABC', 'COMMENT', 'YES', 'YES', 'NO', '123', 'COMMENT','GONOW','MAKE','COMMENT', 'YES','COMMENT']

# get indexes of all 'COMMENT'
idx = [i for i,v in enumerate(mylist) if v in [ 'COMMENT']]
print(idx)

# calculate tuples of data we are interested in:
#   ( commentIdx+1 , next commentIdx ) for all found ones
idx2 = [ (idx[i]+1,idx[i+1]) for i in range(len(idx)-1)]
print(idx2)

# slice the data out of our list and create lists of the slices
result = [ list(islice(mylist,a,b)) for a,b in idx2]

print(result)

Output:
[1, 6, 9, 11]  # indexes of 'COMMENT'

[(2, 6), (7, 9), (10, 11)]  # Commentindex +1 + the next one as tuple

[['YES', 'YES', 'NO', '123'], ['GONOW', 'MAKE'], ['YES']]

You could also skip idx2:
result = [ list(islice(mylist,a,b)) for a,b in ((idx[i]+1,idx[i+1]) for i in range(len(idx)-1))]

As for your 2nd question - which should probably be solved by yourself or posted as seperate question:
It depends on the data - do they intermix (C = COMMENT, B = BORDER) ?
[ C, 1, 2 , C , 3 , B , 4 , B, 5,  C ]

Best probably to try it yourself or post a new question with sample data and wanted output. The above one could be
[ [1,2],[3],[4] ] or [ [1,2],[3],[3,4,5],[4,5],[5] or something in between - the first uses strict C-C and B-B and no C-B or B-C matches. The latter allowes C-B and B-C as well as C-......-C ignoring/removing B's in between


text:
Q: Need to refresh page to see results in ASP.NET? I have an if statement that checks whether the user is logged in or not to display different elements in the navigational bar (Log in if not a user and Log Out if a user).
Below is the if-statement, located in Master.master (Master page, obviously)
            <% if (HttpContext.Current.User.Identity.IsAuthenticated || Session["email"] != null)
               { %>

Browse

Popular

Reservations

            <form method="post" runat="server" role="form">

My Account

Log Out

            </form>
            <% }
               else
               { %>

Browse

Popular

                    Login

                        <form id="loginform" method="post" runat="server" class="form-horizontal" role="form">

                                <input id="login-email" type="email" class="form-control" name="email" placeholder="email" />

                                <input id="login-password" type="password" class="form-control" name="password" placeholder="password" />

                                Login

                                        <input id="login-remember" type="checkbox" name="remember" />
                                        Remember me

                                Don't have an account?
                                Register here!

                        </form>

            <% } %>

When clicking the log out button, this is the event fired.
public void LogOutUser(object sender, System.EventArgs e)
{
    FormsAuthentication.SignOut();
    Session.Abandon();
}

The problem I am facing is that if the user clicks log out, the page will refresh, and nothing will happen. If I refresh the page, though, I see the change. How can I change it so that I get the results without another page refresh?
Edit: Pasted where the if statement is.

A: Here is what is going on here. User clicks the log out button, and the postback occurs. The if statement you have is executed during the initialization phase, and at that moment of time user is not logged out yet. Then the event handling happens, and user is logged out by the code you have in the LogOutUser handler. Now the user is logged out indeed, but the if in markup is already executed and won't be executed again during this page loading! So nothing changes on the page.
However when you refresh the page user is already logged outwhen initialization happens, so if statement is evaluated as you expect it to.
To fix this you can, instead of simple if, wrap the markup in ContentPlaceHolder and setup its visibility on PreRender whe authentication status is known for sure:
<asp:ContentPlaceHolder runat="server" ID="PlaceHolder1">

    ...
</asp:ContentPlaceHolder>

protected void Page_PreRender(object sender, EventArgs e)
{
    if (HttpContext.Current.User.Identity.IsAuthenticated || Session["email"] != null)
    {
        PlaceHolder1.Visible = true;
    }
    else
    {
        PlaceHolder1.Visible = false;
    }
}

A: I'd like to suggest to put breakpoint on LogOutUser and Page_PreRender, in order to determine calling order.
Could be linked to page lifecycle management
See:
http://www.codeproject.com/Articles/667308/ASP-NET-Page-Life-Cycle-Events
Maurizio

A: Solved it temporarily by adding Response.Redirect(Request.RawUrl)
My code turned out like so:
protected void LogOutUser(object sender, System.EventArgs e)
{
    FormsAuthentication.SignOut();
    Session.Abandon();
    Response.Redirect(Request.RawUrl);
}


text:
Q: How to extract data from field in json line format and store it in a new file in python as a text I have json file that looks like this:
{"reviewerID": "A11N155CW1UV02", "asin": "B000H00VBQ", "reviewerName": "AdrianaM", "helpful": [0, 0], "reviewText": "I had big expectations because I love English TV, in particular Investigative and detective stuff but this guy is really boring. It didn't appeal to me at all.", "overall": 2.0, "summary": "A little bit boring for me", "unixReviewTime": 1399075200, "reviewTime": "05 3, 2014"}
{"reviewerID": "A3BC8O2KCL29V2", "asin": "B000H00VBQ", "reviewerName": "Carol T", "helpful": [0, 0], "reviewText": "I highly recommend this series. It is a must for anyone who is yearning to watch \"grown up\" television. Complex characters and plots to keep one totally involved. Thank you Amazin Prime.", "overall": 5.0, "summary": "Excellent Grown Up TV", "unixReviewTime": 1346630400, "reviewTime": "09 3, 2012"}
{"reviewerID": "A60D5HQFOTSOM", "asin": "B000H00VBQ", "reviewerName": "Daniel Cooper \"dancoopermedia\"", "helpful": [0, 1], "reviewText": "This one is a real snoozer. Don't believe anything you read or hear, it's awful. I had no idea what the title means. Neither will you.", "overall": 1.0, "summary": "Way too boring for me", "unixReviewTime": 1381881600, "reviewTime": "10 16, 2013"}

I need to extract data from fields "summary" and "reviewText" and store it in two new files for further analysis, like tokenization.
I am trying this:
import json
rt = open("review.txt", "a") #creates new file for storage
su = open("summary.txt", "a")

with open("/Users/anano/Desktop/MAXWELL/SPRING/NLP/Amazon_Instant_Video_5.json") as json_file:
    for line in json_file: #runs the loop to extract info
        data = json.loads(line)
        rt.write(data['reviewText'])
        su.write(data['summary'])
        rt.close()
        su.closed()

Because sentences in summary do not have suspension points (dots) at the end, it saves all strings as one sentence, like this:
A little bit boring for meExcellent Grown Up TVWay too boring for meRobson Green is mesmerizing

This makes tokenization impossible. How can I sove this problem?

A: All you need to do is adding \n to end of sentences. (\n is an escape character for strings that is replaced with the new line object)
So, your code evulates to this:
import json
rt = open("review.txt", "a") #creates new file for storage
su = open("summary.txt", "a")

with open("/Users/anano/Desktop/MAXWELL/SPRING/NLP/Amazon_Instant_Video_5.json") as json_file:
    for line in json_file: #runs the loop to extract info
        data = json.loads(line)
        rt.write(data['reviewText'] + '\n')
        su.write(data['summary'] + '\n')

    rt.close()
    su.close()


text:
Q: Android adapter.notifyDataSetChanged() not working? I'm writing an app that requires getting input from the user, passing it off to a server, which returns a JSON string, and then displaying its parsed contents in a ListView. I'm currently accomplishing this by extending AsyncTask:
//stripped down version
public class main extends ListActivity {

ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
final EditText input = (EditText)findViewById(R.id.input);

input.addTextChangedListener(new TextWatcher() {
    public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(!input.getText().toString().equals("")) {
            new GetDataTask().execute(input.getText().toString());
        }

    }
});

private class GetDataTask extends AsyncTask<String, Void, ArrayList<String>> {
        protected ArrayList<String> doInBackground(String... query) {

        URL url = new URL("http://myserversaddressgoeshere.com/search/thequerygoeshere");
        URLConnection conn = url.openConnection();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            ArrayList<String> items = new ArrayList<String>();
        //the code that parses the JSON goes here; it writes some strings to items
        return items;
        }

        protected void onPostExecute(ArrayList<String> items) {
            listItems = items;
        adapter.notifyDataSetChanged();
        }
}

}

(This is my first post so I apologize in advance if my attempt to make that a code block fails)
In the onPostExecute method, after setting listItems equal to items, if I print the contents of listItems, they're exactly what I want. But, for some reason, when executed from onPostExecute, adapter.notifyDataSetChanged() seems to do nothing (when it's called from the main thread, it works fine).
If anyone has any idea of what's going on and/or how to fix it, I'd really appreciate it. Thanks!

A: can you try this
    protected void onPostExecute(ArrayList<String> items) {
        listItems.clear();
        listItems.addAll(items);
        adapter.notifyDataSetChanged();
    }

and i do hope you are already doing something this
adapter = new ArrayAdapter<String>(listItems);


text:
Q: Exception when deserializing a Json string to an user defined object I'm having a problem that raises an exception Newtonsoft.Json.JsonSerializationException in Newtonsoft.Json.dll when trying to deserialize an Json formatted string to an user defined object. The string that I'm reading from the file has been written before using the same object.
This is the code of deserielization (exception at the last line).
 storageFile   = await storageFolder.GetFileAsync(filePath);
 string JsonDB = await FileIO.ReadTextAsync(storageFile);

 MyDB myDB = Newtonsoft.Json.JsonConvert.DeserializeObject<MyDB>(JsonDB);

Here is the object class (Tag and Astro are enums):
public class MyDB
{
    public string Version;
    public DateTime Date;
    public List<PhotoSpot_v0_1> Lista_v0_1;
}

public enum version
{
    v0_1
}

public class PhotoSpot_v0_1
{
    public int      ID          { get; set; }
    public string   Title       { get; set; }
    public string   Description { get; set; }
    public int      Rating      { get; set; }
    public bool     Reminder    { get; set; }
    public bool     Toast       { get; set; }

    private double   Latitude   { get; set; }
    private double   Longitude  { get; set; }
    private double   Altitude   { get; set; }

    public Geopoint Geopoint    { get; set; }
    public Geopoint Landmark    { get; set; }

    public TimeZoneInfo TimeZone { get; set; }

    public string MainTag { get; set; }

    public version Version { get; set; }
    public Landmark_v0_1             Landmarks    { get; set; }
    public List<Image_v0_1>          Images       { get; set; }
    public List<URL_v0_1>            URLs         { get; set; }
    public List<globalVars.Tag>      Tags         { get; set; }
    public List<Date_v0_1>           Dates        { get; set; }

    public bool Downloaded { get; set; }
    public bool Exportable { get; set; }
}

public class Landmark_v0_1
{
    public bool             freeLandmark  { get; set; }
    public string           Title         { get; set; }
    private double          Latitude      { get; set; }
    private double          Longitude     { get; set; }
    private double          Altitude      { get; set; }
    public globalVars.Astro Astro         { get; set; }
}

public class Image_v0_1
{
    public string imageURI { get; set; }
    public bool   isDownloaded { get; set; }
}

public class URL_v0_1
{
    public string sURL { get; set; }
}

public class Tag_v0_1
{
    //public string TagName { get; set; }
    public globalVars.TagImageURL TagName { get; set; }
}

public class Date_v0_1
{

    private double DateStart;
    private double DateEnd;

    public DateTime DateTimeStart()
    {
        return CoreTime.JDToDateTime(DateStart);
    }

    public DateTime DateTimeEnd()
    {
        return CoreTime.JDToDateTime(DateEnd);
    }

    public void SetDateTimeStart(DateTime dt)
    {
        DateStart = CoreTime.DateTimeToJD(dt);
    }

    public void SetDateTimeEnd(DateTime dt)
    {
        DateEnd = CoreTime.DateTimeToJD(dt);
    }

}

I've checked that the Json string, before writing, after writing and when read are the same. Here it is if it's helpful. If something more is needed I'll post it.
   {
  "Version": "v0_1",
  "Date": "2020-01-08T10:49:04.6992512+01:00",
  "Lista_v0_1": [
    {
      "ID": 2,
      "Title": "Abadi gaztelua",
      "Description": "",
      "Rating": 0,
      "Reminder": false,
      "Toast": false,
      "Geopoint": {
        "Position": {
          "Latitude": 43.380954170570355,
          "Longitude": -1.7520569699123154,
          "Altitude": 87.749645113013685
        },
        "AltitudeReferenceSystem": 2,
        "GeoshapeType": 0,
        "SpatialReferenceId": 4326
      },
      "Landmark": null,
      "TimeZone": {
        "Id": "Romance Standard Time",
        "DisplayName": "(UTC+01:00) Brussels, Copenhagen, Madrid, Paris",
        "StandardName": "Romance Standard Time",
        "DaylightName": "Romance Daylight Time",
        "BaseUtcOffset": "01:00:00",
        "SupportsDaylightSavingTime": true
      },
      "MainTag": "Monument",
      "Version": 0,
      "Landmarks": {
        "freeLandmark": false,
        "Title": null,
        "Astro": 0
      },
      "Images": [],
      "URLs": [],
      "Tags": [],
      "Dates": [],
      "Downloaded": false,
      "Exportable": true
    }
  ]
}

A: I think your class is not proper. I tried your code and it's working.
string filepath = "../../../json.txt";
            var test =  File.ReadAllText(filepath);
            Example myDB = JsonConvert.DeserializeObject<Example>(test);

pl check your following class as per your json
public class Position
    {
        public double Latitude { get; set; }
        public double Longitude { get; set; }
        public double Altitude { get; set; }
    }

    public class Geopoint
    {
        public Position Position { get; set; }
        public int AltitudeReferenceSystem { get; set; }
        public int GeoshapeType { get; set; }
        public int SpatialReferenceId { get; set; }
    }

    public class TimeZone
    {
        public string Id { get; set; }
        public string DisplayName { get; set; }
        public string StandardName { get; set; }
        public string DaylightName { get; set; }
        public string BaseUtcOffset { get; set; }
        public bool SupportsDaylightSavingTime { get; set; }
    }

    public class Landmarks
    {
        public bool freeLandmark { get; set; }
        public object Title { get; set; }
        public int Astro { get; set; }
    }

    public class ListaV01
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public int Rating { get; set; }
        public bool Reminder { get; set; }
        public bool Toast { get; set; }
        public Geopoint Geopoint { get; set; }
        public object Landmark { get; set; }
        public TimeZone TimeZone { get; set; }
        public string MainTag { get; set; }
        public int Version { get; set; }
        public Landmarks Landmarks { get; set; }
        public IList<object> Images { get; set; }
        public IList<object> URLs { get; set; }
        public IList<object> Tags { get; set; }
        public IList<object> Dates { get; set; }
        public bool Downloaded { get; set; }
        public bool Exportable { get; set; }
    }

    public class MyDB
    {
        public string Version { get; set; }
        public DateTime Date { get; set; }
        public IList<ListaV01> Lista_v0_1 { get; set; }
    }


text:
Q: want to execute onload event only five times in a day Dear all, I am facing problem in execution of onload even for fix number of time.
Actually my requirement is : I have to show a rating script to every single user untill he/she did not rate it. But condition is that, this script has to shown only five time in a day not more than that and this should not shown to user over life time once he get rated it. Showing of script 5 times(1 time per page load) in a day will be continue...till is is not rated...

A: You could use the browser's localstorage to keep track of how often you have shown it to a user on this day and if the user has already rated.
The concrete implementation obviously depends on what exact behavior you expect.


text:
Q: Blank Admin after trying to install GoogleShoppingApi from github I am wanting to use the Google Shopping Api from the github link below
https://github.com/bluevisiontec/GoogleShoppingApi
I have tried multiple times and followed all instructions without issue, but am getting a blank page in Admin. Error says:
a:5:{i:0;s:72:"Mage registry key "_singleton/googleshoppingapi/observer" already exists";i:1;s:1329:"#0 /home5/username/public_html/app/Mage.php(223): Mage::throwException('Mage registry k...')
#1 /home5/username/public_html/app/Mage.php(477): Mage::register('_singleton/goog...', false)
#2 /home5/username/public_html/includes/src/__default.php(22026): Mage::getSingleton('googleshoppinga...')
#3 /home5/username/public_html/app/Mage.php(448): Mage_Core_Model_App->dispatchEvent('controller_acti...', Array)
#4 /home5/username/public_html/includes/src/__default.php(14363): Mage::dispatchEvent('controller_acti...', Array)
#5 /home5/username/public_html/includes/src/Mage_Adminhtml_Controller_Action.php(160): Mage_Core_Controller_Varien_Action->preDispatch()
#6 /home5/username/public_html/includes/src/__default.php(14241): Mage_Adminhtml_Controller_Action->preDispatch()
#7 /home5/username/public_html/includes/src/__default.php(18698): Mage_Core_Controller_Varien_Action->dispatch('login')
#8 /home5/username/public_html/includes/src/__default.php(18228): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#9 /home5/username/public_html/includes/src/__default.php(21056): Mage_Core_Controller_Varien_Front->dispatch()
#10 /home5/username/public_html/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#11 /home5/username/public_html/index.php(83): Mage::run('', 'store')
#12 {main}";s:3:"url";s:17:"/index.php/admin/";s:11:"script_name";s:10:"/index.php";s:4:"skin";s:5:"admin";}

Any ideas on how to fix this?

A: Rename(Disable) extension from App > etc > moduels.
Clear cache and then Run Compilation.
Maybe this is the problem.

A: I believe the observer names defined in the config.xml should be unique and not the same. Although I could be wrong.

*

*https://github.com/bluevisiontec/GoogleShoppingApi/blob/master/app/code/community/BlueVisionTec/GoogleShoppingApi/etc/config.xml#L99-L120
That said, I can't find any version this module supports, but see it's been recently updated.
Also, it could be the fact you are using compilation and the module doesn't support it.  It's also best to just use APC or Aoe_ClassPathCache module or using a new version of PHP with an Opcode cache already included, as compilation tends to break a few 3rd party modules.

*

*is it safe to run magento compiler?


text:
Q: Typescript - How to type guard the existence of a module when using dynamic import? I'm currently using 'react-i18next' and 'i18next-locize-backend') in react native.
I want to use locize differently for each environment(development, production).
For example, in the production environment, I want to use the downloaded translation json file. but in the development environment, I want to receive translation data through backend api on the locize site.
I don't want to download the translation json file in the development environment, but unfortunately, typescript makes a compilation error Cannot find module or its corresponding type declarations.
How can I prevent that compilation error?
The code below is what I wrote.
import i18n, { InitOptions } from 'i18next'
import { initReactI18next } from 'react-i18next'
import { isProduction } from '../src/utils'
import { LOCIZE_PROJECT_ID, LOCIZE_API_KEY } from 'react-native-dotenv'

const initOptions: InitOptions = {
  compatibilityJSON: 'v3',
  debug: false,
  lng: 'en',
  interpolation: {
    escapeValue: false,
  },
}

if (isProduction) {
  ;(async function () {
    const en = await import('./locales/en-US/translation.json') // where the error occurs.

    i18n.use(initReactI18next).init({
      ...initOptions,
      resources: { en: { translation: en },
    })
  })()
} else {
  const backendOptions = {
    projectId: LOCIZE_PROJECT_ID,
    apiKey: LOCIZE_API_KEY,
    referenceLng: 'en',
    version: 'latest',
  }

  import('i18next-locize-backend').then(({ default: LocizeBackend }) => {
    i18n
      .use(LocizeBackend)
      .use(initReactI18next)
      .init({ backend: backendOptions, ...initOptions })
  })
}

tsconfig.json
{
    "compilerOptions": {
      "allowJs": true,
      "allowSyntheticDefaultImports": true,
      "esModuleInterop": true,
      "isolatedModules": true,
      "jsx": "react-native",
      "lib": ["es2017"],
      "moduleResolution": "node",
      "noEmit": true,
      "strict": true,
      "module":"ESNext",
      "target": "esnext",
      "resolveJsonModule": true
    },
    "typeRoots": ["./src/types"],
    "exclude": [
      "node_modules",
      "babel.config.js",
      "metro.config.js",
      "jest.config.js"
    ]
  }

babel.config.js
module.exports = {
  presets: [
    'module:metro-react-native-babel-preset',
    '@babel/preset-typescript',
  ],
  plugins: [
    [
      'module:react-native-dotenv',
      {
        moduleName: 'react-native-dotenv',
      },
    ],
  ],
}

node : 14.17.5.
react native : 0.64.1.
i18next : 21.4.2.
react-i18next : 11.14.1.
typescript : 4.4.4.
i18next-locize-backend : 4.2.3


text:
Q: How to get the last match of a string over a column and print the subsequent column's value in excel I am forced to use excel for work reasons and I am a novice with that...so forgive me for the stupid question.
I have an excel sheet like that:

I would like to have in cell B53 (the green coloured one) the last satus registered in column F for SN0006 --> status "READY". So, steps are:

*

*Find all the occurrences that matches cell A53 content, id est SN0006, in the column B ("SN")

*Take the last occurrence (at the n-1 row). Dunno if it could help but consider that column "EVENT ID" is ordered in an ascending manner so that the last occurrence will have a higher index

*Print in cell B53 the content of the column "STATUS" respect to the last SN0006 occurrence row.

Until now I was able to print the STATUS of the first SN0006 occurrence "BRING UP" in that way:

=INDEX(F39:F51;MATCH(A53;B39:B51;0))

Thank you in advance for any help!

A: This is an array formula which will work in Excel 2007 and later
=INDEX(F39:F51,MAX((A53=B39:B51)*ROW(B39:B51))-38)

A: Finally I also find a way but I didn't understand how it works...

=INDEX(F39:F51;MATCH(2;1/(B39:B51=A53)))


text:
Q: Copying data from a datagrid view to a new form with a new datagrid view VB I am using Visual Studio 2010. I have created a new VB Windows forms application that uses several forms.
On one of those forms (form2), I create a datagridview based on a number of items that a user picks on form1.
The end user can then add information on the datagridvew and then they go to a third form (form3). On the third form, I would like to copy the same information as the first three columns of the datagrid on form2 into a new datagrid.
To copy the items from the listbox on form1 I use code similar to the following:
For Each Feature As Object in form1.listbox1.SelectedItems
Me.DatagridView(Col, Row).Value = DirectCast(CustomerFeature, DataRowView)("Feature").ToString()
Row +=1
Next

I want to use:
For Each row As DGVRow In form2.DatagridView.Rows
    'add information to the new datagrid
Next

on my Form3. However, when I try to access form2 data, it doesn't show up in intellisense, nor will it let me type out the information manually. When I try to run the program I get:
"Error  1   Reference to a non-shared member requires an object reference."
I can't even access the public variables that I have declared on that form. I should mention that form2 is called using:
Private Sub BTN_Next_Click(sender As System.Object, e As System.EventArgs) Handles BTN_Next.Click
        Dim frm_PI_01 As New form2(PIMethod, StartTime, TheUser, TheComputer)
        frm_PI_01.ShowDialog()
    End Sub

and the new method uses:
Public Sub New(ByVal PIMethod As String, ByVal StartTime As Date, ByVal TheUser As String, ByVal TheComputer As String)
    ' This call is required by the designer.
    InitializeComponent()
    PI_Method = PIMethod
    Start_Time = StartTime
    The_User = TheUser
    The_Computer = TheComputer
End Sub

The datagrid is filled in during the onload event.

A: "Error 1 Reference to a non-shared member requires an object reference."
As this message says: You need a instance of form2 - object of type form2created with New sub, which you created inside of BTN_Next_Click. But local variable frm_PI_01 can be used only inside of that function.
With name of class form2 you can used only Shared member or functions/subs MSDN Shared members in VB
My opinion if you need transfer some information/variables from form to another then in your case(when you transfer data only once when creating form) use a parameters in form constructors.
Add another parameter to you form3 constructor. For example reference of your datagridview(this is may be not good practice referenced controls to another form, better create some variable with needed data and reference that, but only for example it is easiest way):
'Of course create private variable for datagridview
private _dgvForm2 as dataGridView
//Constructor of form3
Public Sub New(dgvForm2 as DataGridView)
    ' This call is required by the designer.
    InitializeComponent()
    Me._dgvForm2 = dgvForm2
End Sub

After this you can use it in Load function...


text:
Q: Heegaard Diagrams Understanding I have a question /understanding problem with some Heegaard diagrams (see below).
As far as I understand the concept correctly then the Heegaard diagram explains uniquelly how two handlebodies $H_1, H_2$ with same genus $g$ (therefore they are especially isomorphically) are glued together along their boundaries.
With this aim in mind it suffice to say how the boundaries of the minimal system of discs $D_1, D_2, ..., D_g$ of $H_1$ (therefore closed paths $\gamma_i = \partial D_i$) are glued together with boundaries of the minimal system of discs $D_1',  ..., D_g' $ of $H_2$.
Remark: Minimal systems of discs referes to the minimal number of discs inside a handlebody such that after cutting along them the handlebody becomes homeomorphic to a $3$-ball $D^3$.
Here an example which coincides with my understanding of Heegaard diagrams:

The green paths are pairwise glued with the red paths. This data suffice to define uniquelly (up to isomorphy) how the hendlebody $H_1 $ is glued with $H_2$ (here $g=3$) along the boundaries $\partial H_1, \partial H_2$, if we enumerate the tree red and green parts with $1,2,3$ and endow them with an orientation.
Now, here are the two diagrams which I dont understand:
(1)

Should the "gluing paths" be given pairwise? How to cope here with the green, glue and red paths? What kind of glueing occures here? I'm not sure if it is allowed to glue all three toghether (source: http://www.profmath.uqam.ca/~powell/HFHseminar.html)
(2)

Here the problem for me is that neither the red nor the blue paths are boundaries of discs which have property that if one cuts along them then the handlebody become a $3$-ball. I thought that by definition either the discs of $H_1$ or $H_2$ should have this property.
Could anybody explain to me the errors in my resonings considering these Heegaard diagrams and their general concept?

A: Regarding your first example, until you label the red and green paths --- 1,2,3 for red and 1,2,3 for green so that you know which goes to which, and put arrows on all paths to indicate orientation so you know which orientation goes to which orientation --- the gluing is not uniquely specified.
Regarding your figure (1), I looked at that link and there is no explanation, it seems to be an illustration plucked out of context and put at the top of the web page because it looks cool. Without context, I have no idea what is intended.
Finally, regarding your figure (2), a Heegard diagram can be specified by drawing two curve systems on the surface, a red curve system and a blue curve system, as long as the surface minus the red curve system is a 2-sphere with $2g$ holes removed, and similarly for the blue curve system. The reason this works is because those two curve systems tell you how to abstractly glue in the discs --- red discs on one side of the surface (abstractly), and blue discs on the other side of the surface (abstractly) --- which is all that is needed in order to specify a Heegard decomposition of a 3-manifold.


text:
Q: How to do component test for mat stepper? I have the below mat-stepper steps:
<button mat-raised-button (click)="isLinear = !isLinear" id="toggle-linear">
 {{!isLinear ? 'Enable linear mode' : 'Disable linear mode'}}
</button>
<mat-horizontal-stepper [linear]="isLinear" #stepper>
<mat-step [stepControl]="firstFormGroup">
<form [formGroup]="firstFormGroup">
  <ng-template matStepLabel>Fill out your name</ng-template>
  <mat-form-field>
    <mat-label>Name</mat-label>
    <input matInput placeholder="Last name, First name" formControlName="firstCtrl" required>
  </mat-form-field>

    <button mat-button matStepperNext>Next</button>

 </form>
</mat-step>
<mat-step [stepControl]="secondFormGroup" label="Fill out your address">
<form [formGroup]="secondFormGroup">
  <mat-form-field>
    <mat-label>Address</mat-label>
    <input matInput formControlName="secondCtrl" placeholder="Ex. 1 Main St, New York, NY"
           required>
  </mat-form-field>

    <button mat-button matStepperPrevious>Back</button>
    <button mat-button matStepperNext>Next</button>

  </form>
 </mat-step>

How can I do a unit test to check if button next is clicked, it actually moves to the next index?

A: See official documentation here
// Imports
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatStepperHarness, MatStepperNextHarness } from
'@angular/material/stepper/testing';

// Declare your harness loader variable inside the describe block
describe('CreateLovedeedDialogComponent', () => {
    let loader: HarnessLoader;
});

// Reference the loader in beforeEach
beforeEach(() => {
    ...
    component = fixture.componentInstance;
    fixture.detectChanges();
    loader = TestbedHarnessEnvironment.loader(fixture);
});

it('should go forward when pressing the next button', async () => {
    const stepper = await loader.getHarness(MatStepperHarness);
    const steps = await stepper.getSteps();

    // Should have 6 steps
    expect(steps.length).toEqual(6);

    // The first step should be selected by default
    expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([true, false, false, false, false, false]);

    // Get and click on the first step's next button
    const firstStep = steps[0];
    let nextButton = await firstStep.getHarness(MatStepperNextHarness);
    await nextButton.click();

// The second step should be selected
    expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([false, true, false, false, false, false]);
});

In the above example, there is a stepper with 6 steps.
https://stackblitz.com/run?file=src/app/stepper-harness-example.ts


text:
Q: Spree command not found Can't figure out what I am doing wrong. Have successfully managed to create new storefront using the command:
rails g spree:install
But whenever I try to use the command 'spree' in the command line I get the error:
'command not found: spree'
This is proving problematic for creating extensions. Any help would be greatly appreciated.

A: Problem solved. Forgot to rehash rbenv.


text:
Q: Transition for scikit learn to xgboost: Where can I find a comprehensive documentation for xgboost? (Python) As the internet seems to be conviced that xgboost is well worth a shot when working with decision trees anyways, I set out to try it. I deal with a binary classification problem.
Up to now, I was working with the scikit learn library and I always refered to the respective documentation; e.g. gradient boosting. It tells me which input parameters I can use and which methods I can apply.
Is there something comprehensive like this available for xgboost as well? I found which input parameters I can use, but not which methods can be applied.
What I've tired (and what worked surprisingly well) was simply using the methods I was using with the scikit learn gradient boosting classifier:
import xgboost as xgb
from sklearn.model_selection import train_test_split

X = my_data
y = my_data_target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)

xgbm = xgb.XGBClassifier().fit(X_train, y_train)

xgbm_accTrain = xgbm.score(X_train, y_train)
xgbm_acc = xgbm.score(X_test, y_test)
xgbm_pred = xgbm.predict(X_test)
xgbm_predProb = xgbm.predict_proba(X_test)[:,1]

i = ["Gradient Boost", xgbm_accTrain, xgbm_acc, xgbm_pred, xgbm_predProb]

av_pres = average_precision_score(y_test, i[4]) #calculated before as it will be needed more often
print(
    "{:<33} {:5.03f}".format("Accuracy (training):", i[1]),
    "{:<33} {:5.03f}".format("Accuracy:", i[2]),
    "{:<33} {:5.03f}".format("F-score:", f1_score(y_test, i[3])),
    "{:<33} {:5.03f}".format("Precision:", precision_score(y_test, i[3])),
    "{:<33} {:5.03f}".format("Recall:", recall_score(y_test, i[3])),
    "{:<33} {:5.03f}".format("Average precision (PR-curve):", av_pres),
    "{:<33} {:5.03f}".format("AUC (ROC-curve):", roc_auc_score(y_test, i[4])),
    sep="\n"
)

Can I do this? The results seem reasonable, but I want to be sure.
One more thing: Several xgboost tutorials use a DMatrix (This iris classification, for instance). Why? I mean, it worked for me without it.
Thanks a lot for your help!

A:
Is there something comprehensive like this available for xgboost as well?

https://xgboost.readthedocs.io/

What I've tired (and what worked surprisingly well) was simply using the methods I was using with the scikit learn gradient boosting classifier. Can I do this?

Yes. Is there something particularly that you're worried about?

Several xgboost tutorials use a DMatrix (This iris classification, for instance). Why?

The DMatrix is a specialized data type that's optimized for use in estimating an xgboost model. Specialized loaders exist to read data directly into the DMatrix format. You might find that it is more expedient than using numpy or pandas types if all of your use case is covered by the more limited DMatrix functionality.


text:
Q: Type refinements in Scala but without using refined I am trying to create a HexString type based on String which should fulfill the condition "that it contains only hexadecimal digits" and I would like to have the compiler typecheck it for me, if possible.
One obvious solution would be to use refined and write something like this:
type HexString = String Refined MatchesRegex[W.`"""^(([0-9a-f]+)|([0-9A-F]+))$"""`.T]
refineMV[MatchesRegex[W.`"""^(([0-9a-f]+)|([0-9A-F]+))$"""`.T]]("AF0")

Now, I have nothing against refined, it's that I find it a bit of an overkill for what I am trying to do (and have no idea whether I am going to use it in other places at all) and I am reluctant to import a library which I am not sure will be used more than once or twice overall and brings syntax that might look like magic (if not to me, to other devs on the team).
The best I can write with pure Scala code, on the other hand, is a value class with smart constructors, which is all fine and feels lightweight to me, except that I cannot do compile-time type checking. It looks something like this at the moment:
final case class HexString private (str: String) extends AnyVal {
  // ...
}

object HexString {
  def fromStringLiteral(literal: String): HexString = {
    def isValid(str: String): Boolean = "\\p{XDigit}+".r.pattern.matcher(str).matches

    if (isValid(literal)) HexString(literal)
    else throw new IllegalArgumentException("Not a valid hexadecimal string")
  }
}

For most of the codebase, runtime checking is enough as it is; however, I might need to have compile-time checking at some point and there seems to be no way of achieving it short of using refined.
If I can keep the code as localized and as understandable as possible, without introducing much magic, would it be possible to use a macro and instruct the compiler to test the RHS of assignment against a regex and depending on whether it matches or not, it would create an instance of HexString or spit a compiler error?
val ex1: HexString = "AF0" // HexString("AF0")
val ex2: HexString = "Hello World" // doesn't compile

Other than ADT traversal and transformation programs I've written using Scala meta, I don't really have experience with Scala macros.

A: If you want fromStringLiteral to work at compile time you can make it a macro (see sbt settings)
import scala.language.experimental.macros
import scala.reflect.macros.blackbox

def fromStringLiteral(literal: String): HexString = macro fromStringLiteralImpl

def fromStringLiteralImpl(c: blackbox.Context)(literal: c.Tree): c.Tree = {
  import c.universe._

  val literalStr = literal match {
    case q"${s: String}" => s
    case _ => c.abort(c.enclosingPosition, s"$literal is not a string literal")
  }

  if (isValid(literalStr)) q"HexString($literal)"
  else c.abort(c.enclosingPosition, s"$literalStr is not a valid hexadecimal string")
}

Then
val ex1: HexString = HexString.fromStringLiteral("AF0") // HexString("AF0")
//val ex2: HexString = HexString.fromStringLiteral("Hello World") // doesn't compile

If you want this to work like
import HexString._
val ex1: HexString = "AF0" // HexString("AF0")
//val ex2: HexString = "Hello World" // doesn't compile

then additionally you can make fromStringLiteral an implicit conversion
implicit def fromStringLiteral(literal: String): HexString = macro fromStringLiteralImpl