text:
Q: MongoDB - The type initializer for 'MongoDB.Bson.ObjectId' threw an exception I'm just wondering if anyone has ever seen this exception? I'm using the C# driver and have successfully run this code on many servers. We are seeing this on one particular production server.
The first time I see this is on the first insert into a new collection. After that it seems to occur each time I call InsertBatch for that collection.
I've successfully called InsertBatch on other collections successfully during the same run.
Error** Message = The type initializer for 'MongoDB.Bson.ObjectId' threw an exception., Stack Trace =    at MongoDB.Bson.ObjectId.GenerateNewId()
   at MongoDB.Bson.Serialization.IdGenerators.BsonObjectIdGenerator.GenerateId(Object container, Object document)
   at MongoDB.Driver.MongoCollection.InsertBatch(Type nominalType, IEnumerable documents, MongoInsertOptions options)
Thanks,
Paul

A: Check your inner exceptions. Since Mongo does not implement FIPS and that's mandatory in some operative system configurations, you might get this error even with authentication disabled while trying to read or generate an ObjectId (since they have an encrypted id value). To solve this problem either replace your encrypted "_id" field values on your collection, or modify the Windows registry to allow applications not implementing FIPS.

A: I have seen the same error on PHP today. Found out that it was a known issue (see https://jira.mongodb.org/browse/PHPC-460). I know this is C# but maybe it is a similar problem.

A: It is interesting with BSonId serialization which has implemented at 2013 from someones
https://github.com/SharpRepository/SharpRepository/issues/56
In my case downgrading Asp.net Core 3.0 to 2.2 has worked out.
I think mongodb.csharp driver needs to System.Runtime.Serialization.Formatters reference
at 3.0 version
https://github.com/dotnet/core/issues/2611
And an update will come on second separate of 2019
https://github.com/mongodb/mongo-csharp-driver/pull/372


text:
Q: WPF Ribbon Menu tab permanently visible I'm programming an application in WPF using the Ribbon menu, part of the requirements for the application is that I need a commands tab, but this tab should be visible at all times and depending on the active document I would enable/disable the appropriate commands.
My question is, does anyone know a way to split the ribbon menu so that the commands tab is always visible on the right side of the menu?
I'm sure there's an easy answer for this, I just haven't found it yet.
Thanks & Regards!

A: It's not within the functionality of the ribbon. Why not build a grid with 2 columns, and have the ribbon in the left pane and the custom control on the right? Then you can just style the custom control to match the ribbon.
You can get the source code for the ribbon from CodePlex so you would be able to get the exact style.
It might not be what you wanted to hear, but I think it would be ideal.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can CAPTCHA be tweaked by bots? Now a days text recognition within image is possible.
For example in Microsoft onenote you can search a text in image.
So is it a chance for bots to tweak the CAPTCHA ?
By using the same technique can bots answer some CAPTCHA.

A: In case you haven't noticed, the text is usually visually garbled and mutilated to make it difficult/impossible for OCRs to work in CAPTCHAs. Non-altered, straightly rendered texts are easy to OCR out. But of course the recognition gets better and better. The race is on, but as humans suffer from difficult texts as well, new approaches are preferable.

A: http://decaptcher.com/client/
Read there. Not to mention, they also convert scanned books to highlightable digital books by having a sample of users decode the same captcha.

A: Of course the captcha can be deciphered by bots , google's reCaptcha is the work of bots, the bot generates the captcha images it cannot decipher while digitizing real books and then throws it at humans to decipher it . They are continually modifying the code to obscure the text making it more difficult for bots to decipher. But eventually bots do catchup , afterall recaptcha is the work of a bot reading scanned text :)


text:
Q: problem with xslt attribute and urlencodeing (or decoding) using XsltProcessor in PHP I have tried several things to get it work.
Here is my problem.
I have this XML content
<?xml version="1.0" encoding="UTF-8"?>
<csw:GetRecordByIdResponse xmlns:csw="http://www.opengis.net/cat/csw/2.0.2">
  <csw:Record xmlns:dct="http://purl.org/dc/terms/" xmlns:ows="http://www.opengis.net/ows" xmlns:geonet="http://www.fao.org/geonetwork" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <dc:identifier>b6ebec90-96ac-477f-bfcf-ccef920e3e99</dc:identifier>
  <dc:title>Physiographic Map of North and Central Eurasia (Sample record, please remove!)</dc:title>
  <dct:abstract>Physiographic maps ... </dct:abstract>
  <dc:rights>copyright</dc:rights>
  <dc:language />
  <dc:source />
  <ows:BoundingBox crs="urn:ogc:def:crs:::Lambert Azimuthal Projection">
    <ows:LowerCorner>156 -3</ows:LowerCorner>
    <ows:UpperCorner>37 83</ows:UpperCorner>
  </ows:BoundingBox>
  <dc:URI protocol="image/gif" name="thumbnail">resources.get?id=14&fname=phy_s.gif&access=public</dc:URI>
  </csw:Record>
</csw:GetRecordByIdResponse>

and I'm trying to use the value of <dc:URI protocol="image/gif" name="thumbnail">resources.get?id=14&fname=phy_s.gif&access=public</dc:URI> as the src of an img tag.
Note that the value in the XML is encoded (& instead of &)
Here's the xsl I use to transform the XML to HTML
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
xmlns:dct="http://purl.org/dc/terms/"
xmlns:geonet="http://www.fao.org/geonetwork"
xmlns:ows="http://www.opengis.net/ows"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:fn="http://www.w3.org/2005/xpath-functions"   >

<xsl:output method="html" encoding="UTF-8" indent="yes" />
<xsl:template match="csw:GetRecordByIdResponse">

            <meta charset="utf-8" />

                <xsl:apply-templates select="csw:Record" />

</xsl:template>

<xsl:template match="csw:Record">

<xsl:value-of select="dc:title" /><xsl:value-of select="dc:identifier" />

<xsl:value-of select="dc:title" />

        <xsl:for-each select="dc:URI">
            <xsl:if test="@name = 'thumbnail'">

                    <xsl:value-of select="." disable-output-escaping="yes" />
                    <xsl:element name="img">
                        <xsl:attribute name="src"><xsl:text>http://localhost:8080/geonetwork/srv/en/</xsl:text><xsl:value-of select="." disable-output-escaping="yes" /></xsl:attribute>
                    </xsl:element>

            </xsl:if>
        </xsl:for-each>

</xsl:template>

I'm using PHP to process it
<?php
$xp = new XsltProcessor();
// create a DOM document and load the XSL stylesheet
$xsl = new DomDocument;
$xsl->load('sample.xsl');

// import the XSL styelsheet into the XSLT process
$xp->importStylesheet($xsl);

$xml_doc = new DomDocument;
$xml_doc->loadXML(file_get_contents('sample.xml'));
// transform the XML into HTML using the XSL file
if ($html = $xp->transformToXML($xml_doc))
    echo $html;
?>

I'm still getting this output ...
resources.get?id=14&fname=phy_s.gif&access=public

 ... Note that the value in the src attribute still has & while the other one his outputting correctly &.
Thanks in advance,
Jack

A:
Note that the value in the href attribute still has & while the other one his outputting correctly &.

No, the correct and required writing is & in href attributes within the output. I'm lazy in typing, for an explanation see the question Remove &amp from string when writing to xml in PHP and particulary this answer.
Even the other one of which you wrongfully thought it's correct (&) must be written as & correctly.


text:
Q: C# Any CPU option and VirtualQueryEx I have found a comportement that i can't explain and I would have liked someone to explain to me why it happend.
To resume my situation i'm trying to read memory regions with VirtualQueryEx to a 64 bit program (notepad.exe)
What i already figure out:

*

*From a 32bits process i can read only 32bits process with using the MEMORY_BASIC_INFORMATION32 struct msdn doc

*From a 64bits process i can read 64bits and 32bits process with using the MEMORY_BASIC_INFORMATION64 struct msdn doc

*From "Any CPU" configuration i get exactly same comportement than if i run my program as x86 32bits program.

Then my question is : why ?
I mean, i checked on msdn documentation they are saying that it should be runned in 64bits mode normaly because my computer is a 64bits OS. Then why it behaves like a 32bits process ?
Thank you a lot for your futur answer. I'm really curious to know.

A: Thank to @hans-passant for the answear:

The solution platform name is irrelevant in C# projects, it only matters to C++ projects. The kind of projects where using different build tools is important. The only settings that matters are the ones on your EXE project, the ones that force a particular jitter to get used. Project > Properties > Build tab > Prefer 32-bit and Platform target. They tried to change this in VS2010 btw, giving C# projects a solution platform name of "x86". Big fail whale, back to AnyCPU in VS2012

Then the solution that worked for me was just to uncheck "Prefer 32-bits" to see visual choose the 64bit program as solution for Debug and Release mode.
Thank you again.


text:
Q: SQL Server: compare two values only if none of them is null The thing I'm trying to do is compare two columns but only if none of the is null.
In more detail, I want to get all the product_ids that have a product_id,color_id pair in both stock and price tables or a null color_id in any of them.
I came up with this which seems to do the work:
SELECT DISTINCT
    stock.product_id product_id
FROM
    stock, price
WHERE
    stock.product_id = price.product_id
    AND
    (stock.color_id = price.color_id
     OR price.color_id IS NULL OR stock.color_id IS NULL)

But I am wondering if there is a more elegant solution.
Thank you.

A: I think You can do this way.
I don't know about the performance of the query Coz I am new to performance of SQl.
But I think Subquery will be the good option for you.
Here is the query that might help you.
SELECT
*
FROM
(
SELECT
    DISTINCT
    stock.product_id Stock_ProductId,
    price.product_id Price_ProductId,
    isnull(stock.color_id,0) Stock_color_id,
    isnull(price.color_id,0) Price_color_id,
FROM
    stock
    ,price
) AS A
WHERE
    Stock_ProductId = Price_ProductId
AND
    ( Stock_color_id = Price_color_id OR Price_color_id  = 0 OR Stock_color_id  = 0)

I hope that this answer might help you.
Note : This query is not tested

A: Here is another point of view. You may have a product with ten colors, seven of them in stock, six of them having a price, four matches. It would suffice to find one match. So why match all? And then even have to use DISTINCT to get rid of multiple matches?
The following is essentially your select, only put in an EXISTS clause. The dbms may make use of this and use quick lookup loops. I guess it depends on how many products and how many colors are in the tables, whether this is faster or not.
select id
from product
where exists
(
  select *
  from stock s
  join price p
    on s.product_id = p.product_id
    and (s.color_id = p.color_id or p.color_id is null or s.color_id is null)
  where s.product_id = product.id
);

A: Not tested, but should work:
where ... and coalesce(stock.color_id, price.color_id, 0) = coalesce(price.color_id, stock.color_id, 0)

A: There is nothing wrong with the statement and it shouldn't be modified.
Applying functions to arguments in JOIN or WHERE clauses prevents the query optimizer from using any underlying indexes, thus forcing a full table scan instead of a much cheaper index seek.
Moreover, the statement says return values that either match on color including those that have no color. In this case, NULL is used as a wildcard. Any modification with ISNULL or COALESCE would also modify the logic to return only those that match or both have no color. This would be equivalent to:
stock.color_id = price.color_id OR (price.color_id IS NULL AND stock.color_id IS NULL)

This statement could be simplified if Color_Id contained a special value for No Color, eg -1. In this case you could simply write
stock.color_id = price.color_id

This won't simplify the original statement though, as the logic requires that you check both table for the No Color value


text:
Q: Can't save data using push button (MATLAB) I'm trying to create a figure where the user can select cells to turn on or off. Then, the user can click a button 'Enter' to save the board as an array. I successfully found a way to create interactivity in my plot thanks to a very useful explanation I found here. I just made some changes to suit my needs.
However, I can't find a way to save the board. The button is working (or at least isn't not working), but the data isn't saved. And I don't know how to fix that. Any help would be appreciated.
Here is my code:
function CreatePattern
    hFigure = figure;
    hAxes = axes;
    axis equal;
    axis off;
    hold on;

    % create a button to calculate the difference between 2 points
    h = uicontrol('Position',[215 5 150 30],'String','Enter','Callback', @SaveArray);

    function SaveArray(ButtonH, eventdata)
        global initial
        initial = Board;
        close(hFigure)
    end

    N = 1; % for line width
    M = 20; % board size
    squareEdgeSize = 1;

    % create the board of patch objects
    hPatchObjects = zeros(M,M);
    for j = M:-1:1
        for k = 1:M
            hPatchObjects(M - j+ 1, k) = rectangle('Position', [k*squareEdgeSize,j*squareEdgeSize,squareEdgeSize,squareEdgeSize], 'FaceColor', [0 0 0],...
                'EdgeColor', 'w', 'LineWidth', N, 'HitTest', 'on', 'ButtonDownFcn', {@OnPatchPressedCallback, M - j+ 1, k});
        end
    end

    %global Board
    Board = zeros(M,M);
    playerColours = [1 1 1; 0 0 0];

    xlim([squareEdgeSize M*squareEdgeSize]);
    ylim([squareEdgeSize M*squareEdgeSize]);

    function OnPatchPressedCallback(hObject, eventdata, rowIndex, colIndex)
        % change FaceColor to player colour

        value = Board(rowIndex,colIndex);
        if value == 1
            set(hObject, 'FaceColor', playerColours(2, :));
            Board(rowIndex,colIndex) = 0; % update board
        else
            set(hObject, 'FaceColor', playerColours(1, :));
            Board(rowIndex,colIndex) = 1; % update board
        end

    end
end

%imwrite(~pattern,'custom_pattern.jpeg')


text:
Q: How to control if json response return white page I have a problem that, due to my little knowledge of python, I can't solve. I have this code, and when arrives at this command, the code stops working:
req_ORDER_CURRENT = req_ORDER_CURRENT.json()

I noticed that if I launch the get on the browser, it returns me a blank page but response code is 200:
 req_ORDER_CURRENT = requests.get("http://" + ip + "/order/current")
 statusCodeReq     = req_ORDER_CURRENT.status_code
 print(req_ORDER_CURRENT)
 if statusCodeReq == 200:
    req_ORDER_CURRENT      = req_ORDER_CURRENT.json()
    print(req_ORDER_CURRENT.json())

Is there a system to control this situation?


text:
Q: How to properly specify and reference a provider I'm trying to integrate Angular into my MVC 5 app.
So far, I have my module definition, my service definition and my controller definition all in a single file:
var frontEndApp = angular.module('frontEndApp', []);

frontEndApp.factory('customersRepository', function ($resource) {
    return {
        get: function () {
            return $resource('http://localhost/ServiceHub.Web/api/Customers/').query();
        }
    }
});

 function UserRequestCtrl($scope,  customersRepository) {
     $scope.ShortName;
     $scope.FirstName;
     $scope.LastName;
     $scope.UserEmail;
     $scope.UserOrgRole;
     $scope.UserPhoneNumber;

     $scope.customerInstances = customersRepository.get();

     var list = [];

     $scope.checkit = function () {

         for (var p in $scope.customerInstances) {
             if ($scope.customerInstances[p].checked) {
                 list.push($scope.customerInstances[p].CustomerName);

                 console.log("selected customer:  " + $scope.customerInstances[p].CustomerName);
             }
         } return list;
     }

     $scope.saveUser = function () {

         var UserDetail =
             {
                 shortName: $scope.ShortName,
                 firstName: $scope.FirstName,
                 lastName: $scope.LastName,
                 userEmail: $scope.UserEmail,
                 userOrgRole: $scope.UserOrgRole,
                 userPhoneNumber: $scope.UserPhoneNumber,
                 isAdministrator: $scope.UserCitizenship,
                 customerInstances:
                list.filter(function (itm, i, a) {
                    return i == a.indexOf(itm);
                }).toString(),
             }
         console.log("User Detail:  short name  " + $scope.ShortName + "  first name  " + $scope.FirstName + "   last name" + $scope.LastName + "   email  " +
                    $scope.UserEmail + "   org role  " + $scope.UserOrgRole + "   phone  " + $scope.UserPhoneNumber + "   citizenship  " + $scope.UserCitizenship);
         console.log(list.filter(function (itm, i, a) {
             return i == a.indexOf(itm);
         }).toString());

     }
 };

When I run this I get this error:
Error: [$injector:unpr] Unknown provider: customersRepositoryProvider <- customersRepository
http://errors.angularjs.org/1.2.16/$injector/unpr?p0=customersRepositoryProvider%20%3C-%20customersRepository

What is the proper way for me to define and reference these 3 parts to make them work together?

A: customersRepository is bound to your angular module, so you just need to hook your controller to the same module like so:
frontEndApp.controller('UserRequestCtrl', function($scope,  customersRepository) {
...
});


text:
Q: Retrofit cannot extract JSON in an object I am studying how to use Retrofit to stop using AsyncTask. I have an interface named Network that makes my GET request, a ServiceGenerator class that creates my Retrofit.Builder and my HTTP interceptor and finally my MainActivity (I also have implemented the object class named Results).
The problem is, in my onResponse method (.enqueue) in MainActivity: I don't know how to extract JSON and put a "name" tag in the view.
Here is my ServiceGenerator class:
public class ServiceGenerator {
    //URL base do endpoint. Deve sempre terminar com /
    public static final String API_BASE_URL = "https://randomuser.me/";

    public static <S> S createService(Class<S> serviceClass) {
        //Instancia do interceptador das requisições

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS);

        httpClient.addInterceptor(loggingInterceptor);
        //httpClient.addInterceptor(loggingInterceptor).build();

        //Instância do retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(new Gson()))
                .client(httpClient.build())
                .build();

        return retrofit.create(serviceClass);
    }
}

Here is my interface Network:
public interface Network {

    @GET("api/")
    Call<Results> randomUser();

}

Finally, the main activity:
public class MainActivity2 extends AppCompatActivity {

    private TextView nome;
    private TextView sobrenome;
    private TextView email;
    private TextView endereco;
    private TextView cidade;
    private TextView estado;
    private TextView username;
    private TextView senha;
    private TextView nascimento;
    private TextView telefone;
    private ImageView foto;
    private ProgressDialog load;
    public String gender;
    public Results results;
    public static final String BASE_URL = "https://randomuser.me/";

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

        nome = (TextView) findViewById(R.id.nome);
        sobrenome = (TextView) findViewById(R.id.sobrenome);
        email = (TextView) findViewById(R.id.email);
        endereco = (TextView) findViewById(R.id.endereco);
        cidade = (TextView) findViewById(R.id.cidade);
        estado = (TextView) findViewById(R.id.estado);
        username = (TextView) findViewById(R.id.username);
        senha = (TextView) findViewById(R.id.senha);
        nascimento = (TextView) findViewById(R.id.nascimento);
        telefone = (TextView) findViewById(R.id.telefone);
        foto = (ImageView) findViewById(R.id.foto);

        Network network = ServiceGenerator.createService(Network.class);

         Call<Results> requestUser = network.randomUser();

        requestUser.enqueue(new Callback<Results>() {
            @Override
            public void onResponse(Call<Results> call, Response<Results> response) {
                if (response.isSuccessful()) {

                    ProgressDialog progress = new ProgressDialog(MainActivity2.this);
                    progress.setTitle("sending...");
                    progress.show();
                    Results r = response.body();

                    /*MAYBE I SHOULD PUT SOMETHING HERE:*/

                    if (r != null) {

                        System.out.println();

                       // r.setGender(results.getGender());

                        nome.setText((CharSequence) results.setName(r.getName()));

                        //System.out.println("USER 2: " + response.raw() );

                        //r.setGender(r.getGender());
                        //Results r = new Results();

                        progress.dismiss();

                      //  nome.setText(results.gender.toString());

                        // System.out.println("random user: CARAIO  " + user.random);
                           //nome.setText((CharSequence) r.gender);

                    } else Toast.makeText(MainActivity2.this,"ERROR IN GET JSON",Toast.LENGTH_LONG).show();
                }

                }

            @Override
            public void onFailure(Call<Results> call, Throwable t) {

            }
        });

    }
}

My Results class also:
public class Results {

    public static String gender;

    public Results(){};

    public static String getGender() {
        return gender;
    }

    public static void setGender(String gender) {
        Results.gender = gender;
    }

    public List<Name> getName() {
        return name;
    }

    public Object setName(List<Name> name) {
        this.name = name;
        return null;
    }

    public List<Location> getLocation() {
        return location;
    }

    public void setLocation(List<Location> location) {
        this.location = location;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public List<Login> getLogin() {
        return login;
    }

    public void setLogin(List<Login> login) {
        this.login = login;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public List<Picture> getPicture() {
        return picture;
    }

    public void setPicture(List<Picture> picture) {
        this.picture = picture;
    }

    public List<Name> name;
    public List<Location> location;
    public String email;
    public List<Login> login;
    public String phone;
    public List<Picture> picture;

}

If you guys could help, it will be very gratefull, thank you.

A: You will need this:
https://github.com/square/retrofit/tree/master/retrofit-converters/jackson
add it to gradle and sync.
While creating retrofit instance, call on builder
.setConverter(new JacksonConverter())
Use jackson for json deserialization.
Update your model class using
@JsonProperty("put name of field here")
Then all should work correctly/

A: Change your Network Interface like this
public interface Network {

    @GET("api/")
    Call<RandomUserServiceResponse> randomUser();

}

add this response Model in your project. It is the base response for your JSON response
 public class RandomUserServiceResponse {

    private List<Result> results = null;
   // private Info info;

    public List<Result> getResults() {
        return results;
    }

    public void setResults(List<Result> results) {
        this.results = results;
    }

}

after you do all of this your response
 Call<RandomUserServiceResponse> requestUser = network.randomUser();

        requestUser.enqueue(new Callback<RandomUserServiceResponse>() {
            @Override
            public void onResponse(Call<RandomUserServiceResponse> call, Response<RandomUserServiceResponse> response) {

                if (response.isSuccessful()) {

                    ProgressDialog progress = new ProgressDialog(MainActivity2.this);
                    progress.setTitle("sending...");
                    progress.show();
                    RandomUserServiceResponse r = response.body();

                /* if you want to get NAME tag please */
                Name name = r.getResults().getName();
               /* now you can get Name properties
               name.getTitle(),name.getFirst(),name.getLast() */

                    if (r != null) {

                        System.out.println();

                       // r.setGender(results.getGender());

                        nome.setText((CharSequence) results.setName(r.getName()));

                        //System.out.println("USER 2: " + response.raw() );

                        //r.setGender(r.getGender());
                        //Results r = new Results();

                        progress.dismiss();

                      //  nome.setText(results.gender.toString());

                        // System.out.println("random user: CARAIO  " + user.random);
                           //nome.setText((CharSequence) r.gender);

                    } else Toast.makeText(MainActivity2.this,"ERROR IN GET JSON",Toast.LENGTH_LONG).show();
                }

                }

            @Override
            public void onFailure(Call<RandomUserServiceResponse> call, Throwable t) {

            }
        });

here is your result class
public class Result {

    private String gender;
    private Name name;
    private Location location;
    private String email;
    private Login login;
    private String dob;
    private String registered;
    private String phone;
    private String cell;
    private Id id;
    private Picture picture;
    private String nat;

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Name getName() {
        return name;
    }

    public void setName(Name name) {
        this.name = name;
    }

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Login getLogin() {
        return login;
    }

    public void setLogin(Login login) {
        this.login = login;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public String getRegistered() {
        return registered;
    }

    public void setRegistered(String registered) {
        this.registered = registered;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getCell() {
        return cell;
    }

    public void setCell(String cell) {
        this.cell = cell;
    }

    public Id getId() {
        return id;
    }

    public void setId(Id id) {
        this.id = id;
    }

    public Picture getPicture() {
        return picture;
    }

    public void setPicture(Picture picture) {
        this.picture = picture;
    }

    public String getNat() {
        return nat;
    }

    public void setNat(String nat) {
        this.nat = nat;
    }

}

and this is the Name Class
public class Name {

    private String title;
    private String first;
    private String last;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }

    public String getLast() {
        return last;
    }

    public void setLast(String last) {
        this.last = last;
    }

}

and your Picture Class
public class Picture {

    private String large;
    private String medium;
    private String thumbnail;

    public String getLarge() {
        return large;
    }

    public void setLarge(String large) {
        this.large = large;
    }

    public String getMedium() {
        return medium;
    }

    public void setMedium(String medium) {
        this.medium = medium;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }

}

this is your Login class
public class Login {

    private String username;
    private String password;
    private String salt;
    private String md5;
    private String sha1;
    private String sha256;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public String getMd5() {
        return md5;
    }

    public void setMd5(String md5) {
        this.md5 = md5;
    }

    public String getSha1() {
        return sha1;
    }

    public void setSha1(String sha1) {
        this.sha1 = sha1;
    }

    public String getSha256() {
        return sha256;
    }

    public void setSha256(String sha256) {
        this.sha256 = sha256;
    }

}

here is Location class
public class Location {

    private String street;
    private String city;
    private String state;
    private Integer postcode;

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public Integer getPostcode() {
        return postcode;
    }

    public void setPostcode(Integer postcode) {
        this.postcode = postcode;
    }

}

this is your Info class (you don't need to import this one )
public class Info {

    private String seed;
    private Integer results;
    private Integer page;
    private String version;

    public String getSeed() {
        return seed;
    }

    public void setSeed(String seed) {
        this.seed = seed;
    }

    public Integer getResults() {
        return results;
    }

    public void setResults(Integer results) {
        this.results = results;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

}

and the last one is ID class
public class Id {

    private String name;
    private Object value;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}


text:
Q: Cohort analysis in R (independent of first time seen) I'm trying to build a retained cohort table, but I'm having trouble to set it up to return distinct count ids for each period independent of first time seen (as in not related to the first period they are seen in the data).
I've been trying a solution, but mostly I get the new users each period instead of if they appeared in the period regardless of having appeared in the previous period.
Ex: For this set of values:
id  quarter
7   Q1
7   Q1
5   Q1
8   Q1
3   Q1
6   Q1
10  Q1
3   Q2
10  Q2
8   Q2
2   Q2
7   Q2
6   Q2
6   Q3
9   Q3
6   Q3
4   Q3
9   Q3
2   Q3
5   Q4
8   Q4
10  Q4
7   Q4
1   Q4
8   Q4

instead of this: (the user is only counted in the cohort if its the first time he is seen in the data)
#   [,1] [,2] [,3] [,4]
#Q1    6    5    1    5
#Q2    1    1    0    0
#Q3    2    0    0    0
#Q4    1    0    0    0

I want this: (the user is counted in the cohort if he appeared in the period regardless of being the first time)
#   [,1] [,2] [,3] [,4]
#Q1    6    5    1    4
#Q2    6    2    3    0
#Q3    4    0    0    0
#Q4    5    0    0    0

What I've tried:
test <- list(id = c(7, 7, 5, 8, 3, 6, 10, 3, 10, 8, 2, 7, 6,
                    6, 9, 6, 4, 9, 2, 5, 8, 10, 7, 1, 8), quarter = c("Q1", "Q1",
                                                                      "Q1", "Q1", "Q1", "Q1", "Q1", "Q2", "Q2", "Q2", "Q2", "Q2", "Q2",
                                                                      "Q3", "Q3", "Q3", "Q3", "Q3", "Q3", "Q4", "Q4", "Q4", "Q4", "Q4",
                                                                      "Q4"))

test <- as.data.table(test)
quarts <- sort(unique(test$quarter))
test$occur <- 1
mat <- dcast.data.table(test, id ~ quarter, value.var = "occur", fun.aggregate = sum)
mat[mat > 1] <- 1
mat<-as.data.frame(mat)

res2<-matrix(0, nrow = ncol(mat)-1, ncol = ncol(mat)-1)
res2<-as.data.frame(res2)
i<-2

for (i in 2:ncol(mat)){
  res2[i-1,1]<-sum(mat[,i])
}

for (i in 2:ncol(mat)){
  for (t in 1:nrow(mat)){
    if (mat[t,i] > 0) {
     res2[i-1,i]<-res2[i-1,i]+mat[i,i+1]
    }
  }
}

But it gives me an error.
Would appreciate any suggestion.
Thank you!

A: I think I figured it out for anyone that needs it:
library (dplyr)
library(data.table)

test <- list(id = c(7, 7, 5, 8, 3, 6, 10, 3, 10, 8, 2, 7, 6,
                    6, 9, 6, 4, 9, 2, 5, 8, 10, 7, 1, 8), quarter = c("Q1", "Q1",
                                                                      "Q1", "Q1", "Q1", "Q1", "Q1", "Q2", "Q2", "Q2", "Q2", "Q2", "Q2",
                                                                      "Q3", "Q3", "Q3", "Q3", "Q3", "Q3", "Q4", "Q4", "Q4", "Q4", "Q4",
                                                                      "Q4"))

test <- as.data.frame(test)
quarters <- as.vector(unique(test$quarter))

f<-1
my_list <- list()
for(i in quarters) {
  print(i)
  d1<- setDT(test)[, sum(unique(id) %in% test[quarter==i, id]), by = quarter]
  print(d1)
  my_list[[f]]<- d1[,2]
  f=f+1
}
print(my_list)

mydf <- data.frame(my_list)
print(mydf)
final<-mydf
for (i in 1:ncol(mydf)){
final<-final %>% mutate_at(c(i), funs(lead), n = i-1 )
}
print(final)
final <-t(final)


text:
Q: find f(x) using integration I was given this problem for homework and its very confusing and my professor isn't answering my emails so I am asking for help deciphering the problem. here it is:
Find $f(x)$ if
$\int 5{(x^5+5x)}^3f(x)dx=14{(x^5+5x)}^4+C$
Can anyone figure this problem out and give me a hand with solving it?

A: Equation is of the form $\int 5\alpha^3 f(x)dx=14\alpha^4 +c$ And you know that $\int 4\alpha^3d\alpha=\alpha^4+c$ .So think what can $f(x)$ be so that $\alpha$'s power is increased.. Then multiply siutable constants to make the perfect RHS..

A: We have $$\int 5(x^5+5x)^3 f(x)dx=14(x^5+5x)^4+C$$
As you probably know, if we integrate a function and then take the derivative of the result, we end up with the original function. The original function in this case is $5(x^5+5x)^3 f(x)$. We integrated it and got $14(x^5+5x)^4+C$, so let's take the derivative of that and equate it to our original function:
$\dfrac {d}{dx}[ 14(x^5+5x)^4+C]$
$14 (5x^4+5) \cdot 4 (x^5+5x)^3$ (chain rule)
$56 (5x^4+5)(x^5+5x)^3$ (simplify)
$56 (5x^4+5)(x^5+5x)^3=5(x^5+5x)^3f(x)$
Now just divide both sides by $5(x^5+5x)^3$ to solve for $f(x)$
$$f(x)=\dfrac {56}{5}(5x^4+5)$$
Further simplifying it
$$f(x)={56}(x^4+1)$$.


text:
Q: C#, Windows 7: how can I reliably check if a process is still writing into file? I have a C# utility that needs perform some actions as soon as a specific file is released by another process, i.e. that process stops writing into the file. I am using the code below but it's behaving inconsistently on a Windows 7 system.
private static bool FileWritten(string filename)
    {
        try
        {
            using (FileStream inputStream = File.Open(filename, FileMode.Open,
                        FileAccess.Read,
                        FileShare.None))
            {
                return true;
            }
        }
        catch (IOException e)
        {
            return false;
        }
    }

Sometimes it would return false even though it seems that the file has already been released. I am calling FileWritten() in a while(true) loop that keeps checking calling FileWritten() as long as it returns false, and then exits after some max time. Debugging this is difficult since it seems to work fine under debugger (i.e. it returns true as soon as the file is actually released) but then does not work when I launch my code directly. Also, even adding debug prints seems to affect its behavior.
Is there a more reliable way to check if a file has been written to and released, that would work Win 7 and, preferably, also on Win XP?

A: There is no perfect solution for this problem.
Even if your code was working fine on Windows 7, there would still be race conditions.
Imagine FileWritten returns false at a certain point in time. Your code assumes the file is not locked anymore and continue its execution... but the file could be locked again the next millisecond and the next time you try to access to the file it'll throw an exception...
Can't you just try to access to your file, and catch the exception if you can't access to it? You could then wait a few amount of time then try again. It would be cleaner IMO than a function that tries to returns a boolean indicating if the file is used by a process or not.

A: You could use FileSystemWatcher to listen for events on the file. A few of the options will allow you to see if the file has been changed. You can sleep your thread for a certain amount of time, using a popcorn effect (resetting the timer) whenever you receive a notification that the file changed. Then execute your code (but actually have it do your work in the True path while you have the lock). If the file is still locked, you'll get false, sleep some more waiting for events.
Other than having the other process rename/copy the original file to a new location when it's done, there's no universal API that will give you the file lock immediately after another process drops it. (That I know of).


text:
Q: second argument to .addEventListner i.e callback function is being executed without event happening I'm selecting all the elements with class ".calc-button" by .querySelectorAll method. Then appling .forEach on the 'catched' array to .addEventListner but the callback function is being executed without the occurance of event 'clicked'. (Also how can I get the innerHTMl value of each event.target ?)

let calcButton = document.querySelectorAll(".calc-button");

calcButton.forEach((button) => button.addEventListener("click", clicked()));

function clicked() {
  console.log("clicked");
}
let calcButton = document.querySelectorAll(".calc-button");

calcButton.forEach((button) => button.addEventListener("click", clicked()));

function clicked() {
  console.log("clicked");
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>JS Calculator</title>
    <link rel="stylesheet" href="style.css" />

0

        <button class="calc-button stretch-2" op>C</button
        ><button class="calc-button">←</button
        ><button class="calc-button op">%</button>

        <button class="calc-button">1</button
        ><button class="calc-button">2</button
        ><button class="calc-button">3</button
        ><button class="calc-button op">-</button>

        <button class="calc-button">1</button
        ><button class="calc-button">2</button
        ><button class="calc-button">3</button
        ><button class="calc-button op">x</button>

        <button class="calc-button">1</button
        ><button class="calc-button">2</button
        ><button class="calc-button">3</button
        ><button class="calc-button op">+</button>

        <button class="calc-button stretch-3">0</button
        ><button class="calc-button op">=</button>


text:
Q: cache coherence MESI protocol This is a bus-based shared memoty multiprocessor system with 2 CPUs, MESI (Illionois) Protocol and write-back caches. Both CPUs access the shared variables B and C. I filled out the following state caches but i'm not sure about what happens after a variable is modified..does it go back to shared state?

A: When a cache line is written to, the state of the line becomes 'M'.  In all other caches the state becomes 'I'.
Thus the last two lines of your table are not correct.  When P1 writes C, it invalidates the line in P0.  So the 'M' in the P0 cache - VarC should be an 'I'.
A line transitions from the 'M' state to the 'S' state if cache other than the one who has written the line does a read.


text:
Q: RuntimeError: qtutils is only compatible with version 2 of the PyQt4 The program that I am trying to run is importing the following packages in an anaconda environment:
from PyQt4 import QtCore, QtGui
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named PyQt4

I installed PyQt4 by following the instructions in this link
However, I am getting the following error after installing:
RuntimeError: qtutils is only compatible with version 2 of the  PyQt4 API.Whilst you can import PyQt4 prior to importing qtutils (in order to tell qtutils to use PyQt4), either set the API version to 2 yourself, or import qtutils (which will set it for you) prior to importing QtGui or QtCore.

The program is trying to import
from PyQt4 import QtCore, QtGui
from qtutils import inmain_later,inthread,inmain

Do you have any suggestion?

A: As the error message says, import PyQt4 after importing qtutils.
Qtutils sets the PyQt4 sip API to version 2, which must be done before importing PyQt4.


text:
Q: Functional programming: pair items in list I have an array that I would like to re-order by grouping items together. e.g:
[1, 1, 0, 1, 0, 1, 0] => [1, 1, 0, 1, 1, 0, 0]
OR
[1, 1, 0, 1, 0, 1, 0] => [[1, 1], [0], [1, 1], [0, 0]]
In this example, 1s have been grouped together with a maximum group size of 2 items. I do not want to group all items together – I only want to pair values.
What's the best way to write my function? Reduce? Sort? I'm looking for a clean solution using functional programming techniques, preferably in multiple steps if this allows for better abstractions. I'm using JavaScript but I'll accept any language as an answer, if the logic is clear.
Some background: I have a list of photos and I want to re-order the list so that square photos (aka 1 in my example) appear side-by-side in the list.

A:
What's the best way to write my function?

Probably in an imperative, yet pure way - we are looking for an O(n) solution.

Reduce?

Well, basically every array traversal is a reduce of some sort. So we can definitely use it, but it doesn't necessarily make the code more readable in JavaScript.

Sort?

No. We're not sorting your list.

I'm looking for a clean solution using functional programming techniques, preferably in multiple steps if this allows for better abstractions. I'm using JavaScript but I'll accept any language as an answer, if the logic is clear.

Well, in Haskell it would probably look like
import Control.Arrow
import Data.Either

groupRightPairs = groupNRights 2

groupNRights :: Int -> [Either a b] -> [Either a [b]]
groupNRights 0 xs          = undefined
groupNRights n []          = []
groupNRights n (Left x:xs) = Left x : groupNRights n xs
groupNRights n xs          = uncurry (:) $ first Right $ second (groupNRights n) $ spanNRights n xs
                          {- let (rs, rest) = spanNRights n xs
                             in (Right rs) : (groupNRights n rest) -}
  where
    spanNRights :: Int -> [Either a b] -> ([b], [Either a b])
    spanNRights 0 xs = ([], xs)
    spanNRights n [] = ([], [])
    spanNRights n (Left x:xs) = second ((Left x):) (spanNRights n xs)
    spanNRights n (Right x:xs) = first (x:) (spanNRights (n-1) xs)

However, JavaScript does not have cons-lists, so while you could translate this into JS it does not look as good any more (though without the type restrictions it gets a bit simpler). Instead, you'll rather do this:
function getOnePairs(arr) {
    return getOneGroups(arr, n);
}
function getOneGroups(arr, n) {
    var result = [],
        group = [];
    for (var i=0; i<arr.length; i++) {
        if (arr[i] != 1) {
            result.push(arr[i]);
        } else {
            if (group.length >= n)
                result.push(group = []);
            group.push(arr[i]); // this mutation is not very functional
        }
    }
    return result;
}


text:
Q: Change value when is uploaded reactjs So I'm making a code that receive value from python scripts, it works, If you console it you can the the value.
    fetch('/upload', {
        method: 'POST',
        body: data

    }).then(response => response.json()
    ).then(json => {
        setData(json)
        console.log(json)
    });

And I have this too
        <textarea id="text">
            {data}
        </textarea>

The problem is that when the code works and console the value, nothing appears in the textarea, how can I refresh the text area when the fetch happen.

A: const [data, setData] = useState("")
<textarea value={data}/>


text:
Q: How to get user country name by google signin API? I am new in android developement. I am developing mobile app. In this app, It is need to user country, Plz help to me, how to get user country when user sign in by google account. I am wasting much more time, but did not get any solution.
Scope myScope = new Scope("https://www.googleapis.com/auth/user.birthday.read");
    Scope myScope2 = new Scope(Scopes.PLUS_ME);
    Scope myScope3 = new Scope(Scopes.PROFILE); //get name and id

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(myScope, myScope2, myScope3)
            .requestEmail()
            .requestProfile()
            .requestEmail()
            .build();

mGoogleApiClient = new GoogleApiClient //this is the line of the error
                .Builder(this)
                .enableAutoManage(this,(GoogleApiClient.OnConnectionFailedListener) this)
                .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        Toast.makeText(getApplicationContext(),"La conexión alcliente api de Google ha fallado",Toast.LENGTH_LONG).show();
                    }
                })
                //.addApi(Plus.API)
                .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
                .build();

 GoogleSignInAccount acct = result.getSignInAccount();
        System.out.println("Display Name:="+acct.getDisplayName());
        System.out.println("Display Name:="+acct.getEmail());
        System.out.println(""+ acct.getGivenName());
        System.out.println(""+acct.getFamilyName());

A: Sorry, but Shutting down Google+ and login APIs for consumer (personal) accounts on April 2, 2019


text:
Q: Why is my alert(1) running in case 1 but not in case 2? I'm polishing my XSS skills, but one thing I don't get is why in case 2 my injection is not executing when I'm in fact escaping from the functioning and starting my own code. This code I got from W3Schools so is not anything malicious.
The question is: Why doesn't case 2 works and how would you change it for it to work.
Thank you.
Update: The injection in case 2 starts after: x="Good day";}...
so I cannot add a closing comments at the end of the script. I'm just curious as to why isn't the alert(1) working in the second case, is the browser not parsing that js because it is missing */  at the end? or because the injection didn't properly escaped from that function.
http://www.w3schools.com/js/tryit.asp?filename=tryjs_ifthen
Case 1:
function myFunction()
{
    var x="";
    var time=new Date().getHours();
    if (time<20)
    {
       x="Good day";
    }
    document.getElementById("demo").innerHTML=x;
}

alert(1); //My injection

Case 2:
function myFunction()
{
    var x="";
    var time=new Date().getHours();
    if (time<20)
    {
        x="Good day";
    }
    var i =0;} alert(1);/*My injection is in this line
document.getElementById("demo").innerHTML=x;
}

A: You had an unterminated comment
function myFunction() {
    var x="";
    var time=new Date().getHours();
    if (time<20)
    {
        x="Good day";
    }
    var i =0;
}

alert(1);  /*My injection is in this line document.getElementById("demo").innerHTML=x; }*/

http://jsfiddle.net/2xeYP/


text:
Q: A quick clarification about elementary row operations? I was solving a homework question that asks me why 3R2 - 2R1 is not an elementary row operation. Is it because we are doing subtraction instead of addition? However, I feel like that it not it. I mean 3R2 + -2R1 is the same thing. I'm adding now and multiplying R1 by negative 2.

A: There are three types of elementary row operations.

*

*Swap two rows

*Multiply a row by a non-zero constant

*Add a multiple of one row to another row

You are trying to do the two elementary row operations at once: multiply row $1$ by $-2$ (item 2) and add $3$ lots of row $2$ to row $1$ (item 3).

A: I will agree that your operation is a combination of two elementary row operations and that is why it is non-elementary but I will note that every invertible matrix can be expressed as the product of elementary row operations and I feel that it would defeat the point if every invertible matrix was considered elementary.
This is more of an explanation why the combination of elementary row operations is not considered elementary.


text:
Q: LTSpice: When running a linear AC simulation, how to view the voltage ratio between two voltages? For example, how would I see the ratio between Vi and Vo for a linear AC simulation?

A: As you can read here, LTSpice can plot a mathematical function of the traced variables.  You just have to edit the plot to specify the functions.
An example from the from the linked page is shown below.  As mentioned in the comments, to edit the plot function you can right click on the name.  The plot name is the green string starting with "1.1*pow...".

A: What you see in an AC simulation is the ratio, but expressed in decibels. To see the ratio properly you would need to change the Y axis from logarithmic to linear. (right click)

This will be expressed in volts still but you can change the expression from V(y) to V(x)/V(y) as in crj11's answer.


text:
Q: npm live-server not running on mobile Everything runs correctly when I start the npm live-server from my laptop, but when I type the address on the iPhone's browser 127.0.0.1:8080 it says the address can't be found.
I remember before that when running the live server from the terminal you can also see the web page from mobile too.
I'm not using file:// to run the page.
Appreciate the help.
Thanks

A: according to the documentation page, I can see that it seems to work like ng serve, and you need to add the parameter --host 0.0.0.0 to make the server bind to all IPs and not just 127.0.0.1 (which is not reachable from your phone)


text:
Q: How can I smooth out this on mouseover animation? I have a div that it animating left and right based on the mouse's position, but it's too jittery (especially in IE).
I'm pretty sure it has something to do with a .stop() being inside the mousemove function, thus being called hundreds of times in seconds, but it's the best I can get it.  I want it to be a clean, continuous animation...
jQuery
$('#videoThumbContainer').mousemove(function(e){

    var offset = $(this).offset(),
    containerWidth = $(this).width(),
    runnerWidth = $('#videoThumbRunner').width(),
    relativeX = e.pageX - offset.left,
    difference = parseInt(containerWidth - runnerWidth),
    position = (relativeX / containerWidth) * difference;

    if (runnerWidth > containerWidth) {

        $('#videoThumbRunner').stop().animate({left: position}, 50, 'linear');
    }
});

Demo
http://jsfiddle.net/cbXh5/


text:
Q: Write performance is decreased when collection is increased My problem : MongoDB poor write performance on large collection
Begin: peformance is 70,000 doc/sec (empty collection)
For a while, my collection is getting larger.
End: performance is  < 10,000 doc/sec (0.4 billion docs in collection)
There are my records below:
Write Performance with Time
Write Performance with Collection
And then, I make a new collection in the same database,
I write two collection at the same time.
The Large collection (ns: "rf1.case1") performance is still slow,
but New collection (ns: "rf1.case2") performance is pretty fast.
I have already read MongoDB poor write performance on large collections with 50.000.000 documents plus , but I still no idea !
Is my configuration wrong?

3 Servers are the same Hardware Specfication:

*

*CPU: 8 core

*Memory: 32GB

*Disk: 2TB HDD (7200rpm)

My Scenario:
    There are 3 shards(Replica Set):
    Server1 : primary(sh01) + secondary(sh03) + arbiter(sh02) + configsvr + mongos
    Server2 : primary(sh02) + secondary(sh01) + arbiter(sh03) + configsvr + mongos
    Server3 : primary(sh03) + secondary(sh02) + arbiter(sh01) + configsvr + mongos

Mongod sample:
    /usr/local/mongodb/bin/mongod --quiet --port 20001 --dbpath $s1 --logpath $s1/s1.log --replSet sh01 --shardsvr --directoryperdb --fork --storageEngine wiredTiger --wiredTigerCollectionBlockCompressor snappy --wiredTigerCacheSizeGB 8

Two Collection:
(chunksize = 64MB)
            rf1.case1
                    shard key: { "_id" : "hashed" }
                    chunks:
                            host1   385
                            host2   401
                            host3   367
                    too many chunks to print, use verbose if you want to force print
            rf1.case2
                    shard key: { "_id" : "hashed" }
                    chunks:
                            host1   11
                            host2   10
                            host3   10


text:
Q: Reading a txt file and sending it to an Array C# I have a text file that looks like this
Words Words
Words Words
Words Words
1    34.4e+1
2    34.3e+1
3    34.2e+1
4    34.1e+1.... // and so on

I need to get the string number and concert it to decimal/double and then send it to an array where I can the use the array outside of the for loop to get the average via Enumerable.Chunk

decimal[] raw = new decimal[] { };
decimal[] rawAvgList = new decimal[] { };
decimal RawAvg = 0m;

try
{
   string bPath = aPath + "\\" + fileName.Name + "\\textfilename.txt";
   string[] readText = File.ReadAllLines(bPath);
   readText = readText.Skip(3).ToArray();

   foreach (var line in readText)
   {
      raw = new decimal[] { Decimal.Parse(line.Substring(9).ToString(), style1) };

      for (int i = 0; i < raw.Length; i++)
      {
         Console.WriteLine("{0} \t {1}", raw[i], i++);
      }

   }

   rawAvgList = raw.Chunk(20).Select(chunk => chunk.Average()).ToArray();
   RawAvg = rawAvgList.Average();
}

So for when I call the array outside of the loop it only grabs the last number in the text file. Am I calling the information wrong? I swear I have tried all the different way to call the numbers from the text file and I just keep running into errors. The error range from it not liking me using skip and substring at the same time or and enumerable error where it returned the error and not the number. Anything to help, Thanks!

A: You are assigning the variable raw to a new value on each loop iteration, wiping out any value that was stored previously. The end result is that after the loop terminates, it will only contain the value from the last line in the file as you are seeing.
You can declare raw as a List<decimal> instead, then within the loop, you would do
raw.Add(Decimal.Parse(line.Substring(9).ToString(), style1));

This way, once the loop finishes, you'll have all the numbers and not just the last one.


text:
Q: Fetching the specific columns JPA, Spring boot I am working on fetching the specific columns and then stored their values in String var.
If I am using List<String> var = new ArrayList<>(); then it works well. But actually I don't need the List<String>   I just need only one String var to store the value. The code I'm currently using.
        List<String> name = new ArrayList<>();
        List<String> address = new ArrayList<>();

        try {
            Connection connection = connectionService.createConnection();
            PreparedStatement statement = connection.prepareStatement("select name,address from students where students_id=" + students_id + "");
            ResultSet rs = statement.executeQuery();

            while (rs.next()) {
                name.add(rs.getString("name"));
                address.add(rs.getString("address"));
            }
        } catch (Exception e){
            log.error(e.toString());

        }

If I replace the List<String> name with String name then it gives me the error resultset-exception-before-start-of-result-set.
  How could I do the expected.

A: Use a repository like this
@Query("SELECT new map ( s.name as name, s.address as address) FROM Students s where s.studentsId = ?1")
List<Students> getAllStudents(long id);


text:
Q: fix for a gap in IE for an image I have read the answers posted for this issue and tried them all, but still have the gap.  See link to the site I am working on http://www.poolboy.ca/.  It's the gap between the top of the pool and the menu bar. Please help!

A: There's a really easy fix here.
Your doctype (first line) is currently this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

That doctype triggers Quirks Mode in IE.
If you change your doctype to this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

IE will be in Standards Mode instead, and your gap will magically disappear.
You could instead just use the HTML5 doctype, which is much shorter:
<!DOCTYPE html>

A: add to your css i cant promise anything but this will set all boxes to have 0px margin padding and border by default this is something i can not fathom about ie but it normally fixes it
* {
    padding: 0px;
    margin: 0px;
    border: 0px;
}


text:
Q: Data Programming Using Excel I have an data set in an spreadsheet that I would like to have applied to a series of several hundred separate data sets to create a new version of that dataset.
[Data 1] x [Data Series] = [New Data]
I am wondering if I should make a batch file, python script or use google script.
Any advice on where to start would be a good help.
Previously I have been hand formatting these files.
I tried using VBA now and although it works it takes a considerable amount of time to run.


text:
Q: C++ collection of abstract base classes how can I create STL collection of classes which implement abstract base class using the base class as collection value, without using pointers?
is there something in Boost that allows me to implement it?  The collection specifically is map.
Thanks

A: You cannot avoid pointers completely. You must store pointers in the collection if you want to avoid Object slicing. Boost has a container that hides the pointers pretty well: ptr_map

A: The Boost Pointer Container Library does what you want.

A: You can't
Think about how the compiler would generate code to do that ?
No pointers means that the storage has to be allocated "in the collection itself" in a static array or something. But the storage required for the subclasses can change ! So how would the compiler do it ? ... it can't ...


text:
Q: Method toString cannot be applied to given types error in Android Studio I'm trying to learn Android by creating a calculator app. I have buttons with Ids button0 to button9. On clicking the button, their value should be be added to textViewAbove but I can't seem to be able to convert an integer into a string. I feel that the Android studio is taking my toString() method to be of integer.toString() type.
Code:
int[] buttonId = {R.id.button0, R.id.button1, R.id.button2, R.id.button3, R.id.button4,
        R.id.button5, R.id.button6, R.id.button7, R.id.button8, R.id.button9};

Button[] bt = new Button[10];
for (int i = 0; i < 10; i++) {       //If this doesn't work then do it separately.
    final int I = i;
    bt[I] = (Button) findViewById(buttonId[I]);

    bt[I].setOnClickListener(
            new Button.OnClickListener() {
                public void onClick(View v) {

                    textViewAbove.append(toString(I));
                    //Enter action methods here.
                }
            }
    );
}

Error:
Error:(111, 50) error: method toString in class Object cannot be applied to given types;
required: no arguments
found: int
reason: actual and formal argument lists differ in length

Note that the code is inside the onCreate method in the MainActivity class.

A: You are attempting to invoke the method String toString() of the anonymous subclass of Button.OnClickListener. This method takes no parameters, so it is complaining when you try to give it an int parameter.
You should invoke some other toString method which does accept an int (or Integer) parameter, e.g. Integer.toString(int).

A: You should use Integer.toString(I);

A: The toString method, which is inherited from the Object class, does not take any arguments.
Instead, you can use implicit conversion like textViewAbove.append(""+I);
Or more favorably the textViewAbove.append(String.valueOf(I));

A: Replace your int I with
final String I = i +"";

and remove the toString() method and simply use
textViewAbove.append(I);


text:
Q: css: why has  effect on parent div's width Consider the following HTML
HTML:

        <input type="file"/>
        <button>Upload</button>

CSS:
.container {
    margin-left: 10% ;
    margin-right: 10% ;
    height: 100px ;
    background-color: lightgrey ;
}
img {
    height: 100% ;
}

.bc {
    display: inline-block;
    height: 100px;
    background-color: grey ;
    vertical-align:middle
}
input {
    visibility: hidden ;
    width: 0;
    height: 0;
    display:inline;
}

When I remove the 'input' element, the width of 'bc' is more or less equal to the button, but when it precent, 'bc' gets huge (in width). Here is my jsfiddle. Can someone explain why this is and how I can undo that effect (because I need the input field there)?

A: visibility: hidden;

makes your element invisible, but it is "still there",
display:none;

gets rid of it from the flow of elements, and it won't affect any other elements.

A: You can use css to remove the  field by setting display: none;. This will fix the problem.
input {
   display: none;
}

A: Added width to your input element in CSS and it works fine.
 input {
        visibility: hidden ;
        width: 50px;
        display:inline;
    }


text:
Q: Dactyl-ManuForm vs Kinesis Advantage 360 I am in the market for a split orthonormal ergonomic keyboard. I have an issue with my shoulder that gets worse when I type.
I bought an Ergodox EZ and while I thought it was a definite improvement I ended up returning it. After doing more research I learned that I should have gotten the modeled keycaps, but I got the backlit Ergodox EZ which doesn't support these keycaps and the molded keycaps on the Ergodox was a worse version of what the Dactyl-ManuForm and Kinesis Advantage 360 were delivering with their truly concaved form factors.
I am trying to determine which is the "best" ergonomic keyboard for me. I am leaning towards the Dactyl-ManuForm. But I don't have the time, means, or interest to build my own. I am looking at this option: https://taikohub.com/products/dactyl-manuform-keyboard-v2 but I am curious whether the 5 Keyed Thumb Cluster or the 6 Keyed Thumb Cluster is a better option. Also, I am currently in Los Angeles, does anyone know another option (around here or otherwise) for configuring and buying a prebuilt Dactyl-ManuForm?
It looks like the Kinesis Advantage 360 is another good option that delivers a similar form factor. Has anyone tried both and can they recommend one over the other?
Lastly, I really liked that the Ergodox EZ had the ORYX software which allowed you not only to configure the keyboard but also a series of training exercises. I am not a great touch typer but it is something I will need to get skilled with in order to properly use these keyboards (especially if I get a dactyl without markings on the keycaps, like the rebuilt one I linked). Is there an analogous software training tool for the Dactyl-ManuForm and/or Advantage 360?
Any insights or recommendations would be greatly appreciated.


text:
Q: Character occurrence in string (Case Sensitive) A string is passed as input, an integer denoting the alphabetic position value, And a character 'u' or 'l' which denotes upper or lower case are passed as input. The output should give the number of N value alphabet (case sensitive) occurrence.
Code is working, 3 Hidden test cases passes and 3 Hidden test cases failed out of 6 hidden test cases. Please do help !! :(
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int N,Count=0,i,len;
    char Ar[26]={'a','b','c','d','e','f','g','h','i','j','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'},M,Str[1000];
    scanf("%[^\n]",Str);
    //printf("%s",Str);
    scanf("%d ",&N);
    //printf("%d",N);
    scanf("%c",&M);
    //printf("%c",M);

    len=strlen(Str);
    if(M=='L' || M=='l')
     {
        for(i=0;i<len;i++)
        {
            if(Str[i]==Ar[N-1])
            {
                Count++;
            }
        }
     }
    else if(M=='U' || M=='u')
    {
        for(i=0;i<len;i++)
        {

            if(Str[i]==toupper(Ar[N-1]))
            {
                Count++;
            }
        }
    }
    if(Count==0)
    {
        printf("-1");
    }
    else
    {
        printf("%d",Count);
    }

}

A: @VishnuPriya , I think the mistake is with your array char Ar[26] .Few characters are repeating in that array *('h','i','j')*.
Modify the array to :-
char Ar[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}

Make sure that none of characters are repeating.


text:
Q: Dialog not available within 60 seconds I am trying to use Dialog handler twice in a function. For first time it executes well but on second time it hangs the system with dialog box open and showing Ok and Cancel butoon but never able to click it. Also it times out with an error "Dialog not available within 60 seconds"
Dim cdhPopup As ConfirmDialogHandler
cdhPopup = New ConfirmDialogHandler()
If (ie.Button(Find.ById("btnDelete")).Exists) Then
    'Cancel the booking '
    ie.AddDialogHandler(cdhPopup)
    ie.Button(Find.ById("btnDelete")).ClickNoWait()
    cdhPopup.WaitUntilExists()
    cdhPopup.OKButton.Click()
    ie.WaitForComplete() 'Wait for page to finish loading '
Else
    Assert.Fail("Could not found the Cancel Button")
End If

Using this at 2 places in my code, First time it executes fine and second time within same function it gives dialog not available whereas it is available error.

A: My best guess is that in the second pass you are again calling
ie.AddDialogHandler(cdhPopup), thereby registering it a second time, which is somehow crashing the program when the handlers are invoked (cross thread access to internal variables maybe?)
You should perform a check if the handler is registered, and only register it if it isn't.


text:
Q: Multi-threading using Microsoft R rxXYZ() functions Do all Microsoft R functions (specifically the functions with prefix rx, e.g., rxImport(), rxDataStep(), rxBTrees(), etc.) use multi-threading by default?
If yes, how can I monitor how many cores (or threads) of my local computer are being used while executing these functions? I have seen that while I execute rxBTrees(), in Task Manager, 'Microsoft ML Engine' process starts which consumes ~50-60% of CPU. Does this mean that parallel computing is happening? How to monitor/control the number of threads?
If the answer is 'not all functions use multi-threading', then which functions do/do not?
Thanks.

A: As I understand all rx functions use parallel processing and 4 cores by default (atleast thats the setting in MS Machine Learning server). You can set number of cores with rxOptions(numCoresToUse = 2)


text:
Q: How to execute a JavaScript function that has its name as a string How can I call the following?
var ccall="search.clearMultiSelect";

I have tried the following:

*

*window[ccall]();

*ccall();
Both didn't work (and I get why). I was able to achieve it by eval but is there any other way without using eval?
I cannot split the string or manipulate the string, except for adding something at the beginning or end.
Basically the server, in it's response, contains the name of the function to execute on success of an operation, which in this case is as above.

A: window[ccall]() wouldn't work because window doesn't contain a function by the name "search.clearMultiSelect". If you can use split, try something like:
window[ccall.split('.')[0]][ccall.split('.')[1]]();

For a function of depth greater than 2, you can loop through the split('.') array:
var f = window;
var ccallArray = ccall.split('.');
for (var i = 0; i < ccallArray.length; i++){
    f = f[ccallArray[i]];
}
f();

DEMO

A: You must have a finite number of functions to call.
To protect against eval issues, you could manually do:
if (ccall == "search.func1") func1();
else if (ccall == "search.func2") func2();
else if ....

Not a very exciting answer,  but it should work and avoid an eval.
This also decouples your client and sever.
The server can send back search.func1 while the client decides to respond by calling newfunc1() or vice versa.

A: You could split the string along the '.' and then use repeated lookups with [].

A: You can use eval().
Here is a little example :
var myFunction = "alert('test');";
eval(myFunction);

Here is a link to test the example above:
http://jsfiddle.net/labzus/WzpK8/


text:
Q: Unioning and Joining in 1 Query? I have the following tables:
TABLE1:
A   B   C
1   2   3
2   4   6
3   6   9

TABLE2:
A   B   C
4   8   12
5   10  15
6   12  18

TABLE3:
A   D
2   X
4   Y
6   Z

I need one query that gives:
A   B   C   D
1   2   3
2   4   6   X
3   6   9
4   8   12  Y
5   10  15
6   12  18  Z

Is that possible?
I can do it in 2 queries, but the person I'm doing it for wants it in 1.
Thanks!

A: Try this (example on sqlfiddle):
SELECT x.a, x.b, x.c, d
FROM (
  SELECT a, b, c FROM table1
  UNION ALL
  SELECT a, b, c FROM table2
) x
LEFT JOIN table3 ON ( table3.a = x.a )

A: Sure:
select v1.*, table3.d
from
  (select table1.a, table1.b, table1.c
   from table1
   union all
   select table2.a, table2.b, table2.c
   from table2
  ) v1
left join table3 on v1.a = table3.a


text:
Q: Show that if series $a_n$ converges then series $(-1)^n a_n$ converges - True or false? Show that if series $a_n$ converges then series $(-1)^n a_n$ converges.

Is that true? A quick proof is highly appreciated.Thanks

A: This is not true. Let $a_n = (-1)^n \frac{1}{n}$. As

*

*$\lim_{n \rightarrow \infty }\frac{1}{n} = 0$,

*$\frac{1}{n} >0$ for any $n \geq 1$,
and

*$\frac{1}{n+1}<\frac{1}{n}$ for any $n \geq 1$,

we know by alternating series test that $\sum_{n=1}^\infty a_n$ converges. However
$\sum_{n=1}^\infty (-1)^n a_n = \sum_{n=1}^\infty \frac{1}{n}$, and this does not converge.
We have identified a sequence $a_n$ such that $\sum_{n=1}^\infty a_n$ converges but $\sum_{n=1}^\infty (-1)^n a_n$ diverges.
Please let me know if there is any clarification necessary.


text:
Q: How to prepend a list Item in react correctly i have trouble to prepend a dynamically generated list item correctly
to show what i mean i setup this jsfiddle

*

*add new item (type in 1)

*add new value (type in a)

*add new item (type in 2)

you will see that the value stays on top and is now inside item 2.
how do i fix this behavior so that the second added item has empty value and the first item keeps his value?
  class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
        items: []
    }
  }

  addItem = (e) => {
    this.setState({
        items: [e.target.value, ...this.state.items]
    })
  }

  render() {
    return (

Add new Item

        <input type="text" onChange={this.addItem}></input>

        {this.state.items.map(item => (

{item}

add New Value

            <input type="text"></input>

        ))}

    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))

A: The problem is here:
        {this.state.items.map(item => (

            ...

The key prop is used by React as a reference to each item in a list, so it should be unique (and stable) for each item. Your item doesn't have an id property, it's just a string value from the input, so item.id is undefined. You could use item itself (the input value) as the key, as long as you don't expect any duplicate item names.
To make this more robust, you can store your items as objects with value and id properties, and generate a unique ID for each item as it's created. This is one simple way of doing that:
class TodoApp extends Component {

  state = {
    items: []
  }

  lastID = 0;

  addItem = (e) => {
    this.setState({
      items: [{ value: e.target.value, id: this.lastID++}, ...this.state.items]
    })
  }

  render() {
    ...
    {this.state.items.map(item => (

{item.value}

        ...
  }
}

Note that we're mutating lastID, but in this case that's OK since it's a class property and not stored in state (it won't cause a re-render when it changes).


text:
Q: passing image to a matlab function i have a function
function[a,b,c] = segmentimage(image)

i am not able to give the image 'bird.png' to this function.

*

*i get an error if i write
segmentimage('bird.png')

as
 Error: File: segmentimage.m Line 27 Column: 66

*if i declare
 image= imread(bird.png)

before the function declaration, then also i am getting an error
Function definitions are not permitted at the prompt or in scripts.

please help. thanks in advance

A: In option 2 I think you're doing something like this in your script,
image= imread(bird.png)
function[a,b,c] = segmentimage(image)

First of all, you should have
image = imread('bird.png');

and you should not declare anything in the function script, so, erase the first line.
it should be,
function[a,b,c] = segmentimage(image)

%your code here,

im = imread(image);
%a = ...
%b = ...
%c = ...

end

then you can call your function in another script,
[a, b, c] = segmentimage('bird.png');

About the first error, you have to post some code, especially the line in which the error occurs so we can help.


text:
Q: MCMC with progressive demollification of delta distributions Edit: I simplified the example to a canonical case for clarity.
Given an integral $\int_{\Omega}{g(\mathbf{x})}$ with a well-posed integrand $g(\mathbf{x})$ defined on some multidimensional space $\Omega$, one can integrate it successfully with a Markov Chain Monte Carlo method, in particular using Metropolis-Hastings method. Detailed balance and ergodicity are achieved with any well-posed (samplable) integrand. Transition kernel $K(\dot{},\dot{})$ is Harris recurrent and its transition probability is known for every pair $(\mathbf{x},\mathbf{y})$. The value of the desired integral is always finite, even in presence of delta distributions in the integrand. This is given.
In the case of interest, the integrand is of a form $f(\mathbf{x})=\delta_{\mathbf{x}_0}(\mathbf{x})\dot{} g(\mathbf{x}) + h(\mathbf{x})$ and consists of a delta distribution at some unknown location $\mathbf{x}_0\in \Omega$ and some regular (well-posed) non-zero functions $g(\mathbf{x})$ and $h(\mathbf{x})$. This delta distribution cannot be sampled explicitly or using numerical optimization (given). This makes such an integrand unsamplable with random walk.
I mollify (approximate to the identity) this delta distribution using some mollifier (normalized smooth function $\phi_\epsilon(\mathbf{x})=\epsilon^{-1}\phi\left(\frac{\mathbf{x}}{\epsilon}\right)$ with some bandwidth $\epsilon$). This leads to a tempered integrand $f_\epsilon(\mathbf{x})=\phi_\epsilon(\mathbf{x}-\mathbf{x}_0)\dot{} g(\mathbf{x})+h(\mathbf{x})$. During the integration, at every step $n$, I gradually shrink the parameter $\epsilon_n$ to zero in order to achieve $f_{\epsilon_n} \to f$ as $n \to \infty$ in spirit of serial tempering and simulated annealing.
One cannot use parallel or serial tempering here, as the probability of the proposal to descend from a tempered mixture to the original integrand $f$ at the exact location $\mathbf{x}_0$ of the delta distribution is zero.
Thus I have two rather similar questions:

*

*Would the integral converge to the proper value $g(\mathbf{x_0})+\int_{\Omega}{h(\mathbf{x})}$ with such scheme?

*What are the conditions for the asymptotic decrease rate of the sequence $\epsilon_n$ that guarantees the consistency of the MCMC integration? In other words, the rate that allows the integral to converge before parts of the integrand $f_{\epsilon_n}$ become unsamplable?

A: I don't know how committed you are to decreasing epsilon at every step; doing so makes theory a bit harder, at least for me. In any case, as your second question suggests, the answer is that everything should work out fine if you're a little bit careful; checking that you're being careful depends on the values of g,h  and your space.
If you're willing to decrease epsilon by a factor of two at certain steps T(1), T(2), ... then the answers become:
1) Yes, if T(i) grows sufficiently quickly
2) There are many answers, depending on what you know! Bremaud's undergraduate text on Markov chains and such gives a proof that simulated annealing works which should be almost exactly what you want here. Essentially, within each epoch $T(i+1) - T(i)$, you should be able to guarantee mixing of your Markov chain to the extent that your integral is within some error $\epsilon(i)$ of the integral of $f_{\epsilon(i)}$ with probability at least e.g. $1 - i^{-2}$. Furthermore, you should be able to guarantee that the integral of $f_{\epsilon(i)}$ is within $\delta(i)$ of the integral of $f$.
As long as $\epsilon(i)$ and $\delta(i)$ go to 0, and $T(i+1) - T(i)$ is sufficiently large for these conditions to hold, you will have convergence.
Of course, in real life, this requires knowledge of e.g. the spikiness of $f_{\epsilon}$ as well as good information about the convergence of your underlying chain.


text:
Q: how to print stack trace to pages? how to print exception stack trace to web page?
import com.opensymphony.xwork2.ActionSupport;
import java.util.Arrays;

public class ExceptionAction extends ActionSupport
{

 public String execute()
 {
    //
    String errMsg = Arrays.toString(Thread.currentThread().getStackTrace());

    this.addActionError(
                    "Unexcepted error has occurred. \n"
                    +errMsg
                    + "\nPlease try again or report this error to    administrator or support team. \n ");

    return "error";
 }

 /**
 *
 */
 private static final long serialVersionUID = -3754090784536811052L;
}

but i got  a useless msg use above codes, msg is like this:
    [java.lang.Thread.getStackTrace(Thread.java:1479),    com.monitoring.action.ExceptionAction.execute(ExceptionAction.java:11), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39),

A: Here is code to print stack trace to a page
 package test;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        PrintWriter out = response.getWriter();
        try {
            "test".charAt(20);
        } catch (RuntimeException e) {
            out.println("Stack Trace:
");
            e.printStackTrace(out);
            out.println("

Stack Trace (for web display):
");
            out.println(displayErrorForWeb(e));
        }
    }

    public String displayErrorForWeb(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        String stackTrace = sw.toString();
        return stackTrace.replace(System.getProperty("line.separator"), "
\n");
    }

}

Source :http://www.avajava.com/tutorials/lessons/how-do-i-display-a-stack-trace-on-a-web-page.html

A: See documentation
File file = new File("test.log");
PrintStream ps = new PrintStream(file);
try {
    // something
} catch (Exception ex) {
    ex.printStackTrace(ps);
}
ps.close();

See also Difference between printStackTrace() and toString()


text:
Q: Is projection an isometry from the poincare disk to a two-sheeted hyperboloid? Take, for example, the hyperboloid $x^2-y^2-z^2=1$ and the open disk (equipped with the Poincare metric) $x=1, \, y^2+z^2<1$. If we multiply a solution $(1,y,z)$ to the second set of equations by some scalar $s$ to get a solution to the first equation $(s, sy, sz)$, is the resulting map an isometry?
It's intuitive to me that if, given a two-sheeted hyperboloid, you center an open disk equipped with the Poincare metric at one of the hyperboloids vertices (is that what they're called?) such that the radius of the disk is the radius of the asymptotic cone at that point along its axis of symmetry, then performing the projection I described is an isometry of the hyperbolic plane. I haven't thought much about how to prove this, I feel as though I would need to know how to calculate distance on the hyperboloid, and trying to do so with an integral gives an equation that I'm pretty sure isn't solvable analytically.
Is my intuition correct? If so, How would you go about proving it? If not, there is an isometry between these spaces, because they're both models for the hyperbolic plane, right?

A: There are two relevant maps between disk and hyperboloid. The one you describe has the disk at one of the vertices, and the center of projection at the center of symmetry of the hyperboloid. The resulting disk is not the Poincaré disk model, but instead the Beltrami-Klein model:

If you want to project to Poincaré disk model instead, you should place your disk at the plane of symmetry (i.e. at $z=0$) and your center of projection at one of the vertices (i.e. $(0,0,-1)$):

One way to reason about these things is the following: A hyperbolic line is uniquely defined by the two ideal points it's incident with, and a point uniquely defined by two lines intersecting with it. So for both of the above mappings, it is sufficient to show that the set of ideal points is projected in a metric-preserving fashion, and that the set of hyperbolic lines matches. In other words, that the set of hyperbolic geodesics on the hyperboloid maps to straight lines for Beltrami-Klein and to circles orthogonal with the unit circle for Poincaré.
Figures taken from my PhD. thesis Section 2.1.5 Figure 2.5 Page 20. Higher resolution available upon request.

A: picture of a single point in the hyperboloid model, projected to the Beltrami-Klein model and the Poincare disc model

If we think of the projection out of the origin as being an entire plane, we intersect with the hyperboloid in a geodesic. This is pulled back to a line segment in the Beltrami-Klein model (at $z=1$). This is projected vertically to a semicircle on the hemisphere $x^2 + y^2 + z^2 = 1, z \geq 0.$ Stereographic projection around the South Pole $(0,0,-1)$ takes that semicircle to a circular arc in the Poincare disc ($z=0$), which is orthogonal to the equator because the semicircle was orthogonal to the equator, while the equator is mapped to itself. Result in the xy plane depicted below, an entire geodesic arc in the Poincare disc.


text:
Q: Can you find all substrings of a string in faster than O(N^2) time if your constrained about what sub strings your looking for? According this answer (Find all possible substring in fastest way). The fastest way to find all possible substrings of a String is O(N^2). However, is this still true if let's say I have a list of words, and I wan't to see if a certain string x has substrings that are in that list of words. For instance, would creating a trie of the list of words, allow me to optimally ignore certain substrings. Thus making the run time better?

A: Yes, that is what string searching algorithms are for.


text:
Q: How to trigger a local notification at particular time daily in swift 3 I am new to iOS development, but have created the app and I am trying to create a daily notification for specific time like (10AM). Now notification are coming too many if i se my mobile device time to 10AM. I want to trigger a local notification only once at given specific time that is at 10 AM , and I want to repeat this daily. What is the best method to repeat the notification daily ?
Here is my code
func fire(){
    let dateComp:NSDateComponents = NSDateComponents()
    dateComp.hour = 10
    dateComp.minute = 00
    dateComp.timeZone = NSTimeZone.systemTimeZone()
    let calender:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierIndian)!
    let date:NSDate = calender.dateFromComponents(dateComp)!
    let localNotificationSilent = UILocalNotification()
    localNotificationSilent.fireDate = date
    localNotificationSilent.repeatInterval =  NSCalendarUnit.Day
    localNotificationSilent.alertBody = "Started!"
    localNotificationSilent.alertAction = "swipe to hear!"
    localNotificationSilent.timeZone = NSCalendar.currentCalendar().timeZone
   localNotificationSilent.category = "PLAY_CATEGORY"
   UIApplication.sharedApplication().scheduleLocalNotification(localNotificationSilent)
}

A: Working in Swift 3, iOS 10:
UNUserNotificationCenter.current().requestAuthorization(
    options: [.alert, .sound, .badge], completionHandler: {userDidAllow, error in
    //if userDidAllow : do something if you want to
})

//Set notification to trigger 11:30AM everyday
var dateComponents = DateComponents()
dateComponents.hour = 11
dateComponents.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

//Set your content
let content = UNMutableNotificationContent()
content.title = "Your notification title"
content.body = "Your notification body"

let request = UNNotificationRequest(
    identifier: "yourIdentifier", content: content, trigger: trigger
)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

A: your problem is fire date which is not proper
you can create fire date like this way
    let today = Date()
    let calendar = NSCalendar.current
    let components = calendar.dateComponents([.day, .month, .year], from: today)

    var dateComp:DateComponents = DateComponents()
    dateComp.day = components.day
    dateComp.month = components.month
    dateComp.year = components.year
    dateComp.hour = 10
    dateComp.minute = 00
    let date = calendar.date(from: dateComp)

if you want to verify fire date then you can check like this way
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd MM yyyy hh:mm:ss"
    let fireDate = dateFormatter.string(from: date!)
    print("fireDate: \(fireDate)")

Now it's time to set fire date to local notification
localNotificationSilent.fireDate = date
// no need to set time zone Remove bellow line
localNotificationSilent.timeZone = NSCalendar.currentCalendar().timeZone

Notification code
    let localNotificationSilent = UILocalNotification()
    localNotificationSilent.fireDate = date
    localNotificationSilent.repeatInterval = .day
    localNotificationSilent.alertBody = "Started!"
    localNotificationSilent.alertAction = "swipe to hear!"
    localNotificationSilent.category = "PLAY_CATEGORY"
    UIApplication.shared.scheduleLocalNotification(localNotificationSilent)

I hope it will help you.


text:
Q: So confused about this Java Loop I have been trying to get this program to work for ages and every time I try to add a loop that increments the progress counter and refresh the main frame it either just won't display or it will just stay at 0 and every input I enter doesn't affect the program.
public class Progress2
{

    private JPanel mainPanel = new JPanel();

    int progress = 0;
    int prog = 100;
    int count;

    Scanner input = new Scanner(System.in);
    String command = "";

    public Progress2()
    {

        JPanel labelPanel = new JPanel(new GridLayout(0, 11)); // holds the JLabels in a grid
        Label label1 = new Label("0%");
        Label label2 = new Label("10%");
        Label label3 = new Label("20%");
        Label label4 = new Label("30%");
        Label label5 = new Label("40%");
        Label label6 = new Label("50%");
        Label label7 = new Label("60%");
        Label label8 = new Label("70%");
        Label label9 = new Label("80%");
        Label label10 = new Label("90%");
        Label label11 = new Label("100%");

        Label label12 = new Label(prog +"%");

        labelPanel.add(label1);
        labelPanel.add(label2);
        labelPanel.add(label3);
        labelPanel.add(label4);
        labelPanel.add(label5);
        labelPanel.add(label6);
        labelPanel.add(label7);
        labelPanel.add(label8);
        labelPanel.add(label9);
        labelPanel.add(label10);
        labelPanel.add(label11);
        labelPanel.add(label12);

        label1.setForeground(Color.green);
        label2.setForeground(Color.red);
        label3.setForeground(Color.red);
        label4.setForeground(Color.red);
        label5.setForeground(Color.red);
        label6.setForeground(Color.red);
        label7.setForeground(Color.red);
        label8.setForeground(Color.red);
        label9.setForeground(Color.red);
        label10.setForeground(Color.red);
        label11.setForeground(Color.red);

        mainPanel.add(labelPanel, BorderLayout.LINE_START);

        if(progress>=1){
            label2.setForeground(Color.green);
        }

        if(progress>=2){
            label3.setForeground(Color.green);
            prog=-10;
        }

        if(progress>=3){
            label4.setForeground(Color.green);
            prog=-10;
        }

        if(progress>=4){
            label5.setForeground(Color.green);
            prog=-10;
        }

        if(progress>=5){
            label6.setForeground(Color.green);
            prog=-10;
        }

        if(progress>=6){
            label7.setForeground(Color.green);
            prog=-10;
        }

        if(progress>=7){
            label8.setForeground(Color.green);
            prog=-10;
        }

        if(progress>=8){
            label9.setForeground(Color.green);
            prog=-10;
        }

        if(progress>=9){
            label10.setForeground(Color.green);
            prog=-10;
        }

        if(progress>=10){
            label10.setForeground(Color.green);
            prog=-10;
        }

        if(progress>=11){
            label11.setForeground(Color.green);
            prog=-10;
        }

        while(true){
            for(count =0; count<11; count++){
                Scanner scanner = new Scanner(System.in);
                System.out.println("Do you want to increment?");
                String scan = scanner.nextLine();
                progress++;
            }
        }
    }

    public JComponent getComponent()
    {
            return mainPanel;
    }

    private static void createAndShowUI()
    {
         JFrame frame = new JFrame("Progress");
         frame.getContentPane().add(new Progress2().getComponent());
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.pack();
         frame.setLocationRelativeTo(null);
         frame.setVisible(true);
    }

    public static void main(String[] args)
    {

        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
              createAndShowUI();

          }
     });
   }
}

A: I believe you are under the impression that every time the progress variable is updated all those if statements will be tested and the GUI will be updated accordingly. This is not the case. Re-write the loop to be as follows and you will see the intended outcome:
for(count = 0; count < 11; count++) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Do you want to increment? ");
    String scan = scanner.nextLine();
    progress++;
    if(progress>=1){
        label2.setForeground(Color.green);
    }
    if(progress>=2){
        label3.setForeground(Color.green);
        prog=-10;
    }
    if(progress>=3){
        label4.setForeground(Color.green);
        prog=-10;
    }
    if(progress>=4){
        label5.setForeground(Color.green);
        prog=-10;
    }
    if(progress>=5){
        label6.setForeground(Color.green);
        prog=-10;
    }
    if(progress>=6){
        label7.setForeground(Color.green);
        prog=-10;
    }
    if(progress>=7){
        label8.setForeground(Color.green);
        prog=-10;
    }
    if(progress>=8){
        label9.setForeground(Color.green);
        prog=-10;
    }
    if(progress>=9){
        label10.setForeground(Color.green);
        prog=-10;
    }
    if(progress>=10){
        label10.setForeground(Color.green);
        prog=-10;
    }
    if(progress>=11){
        label11.setForeground(Color.green);
        prog=-10;
    }
}

A: Follow the below flow:

*

*Progress2() class initialize panels and labels and add on component in constructor. That is till mainPanel.add(labelPanel, BorderLayout.LINE_START);

*Create a function updateUI()
function void updateUI()
{
        \Get Panel
        \Get labels from panel
        \`for` loop in that function as mentioned by blahfunk above.
}
Learning point here: How to get panel and labels from that panel. To make it easier check if you can declare panel and labels as class attributes for Progress2() class and then you could define class methods to return those values (getters)

*Call updateUI() function after createAndShowUI(); in main() function.

Why the GUI doesn't appear till I press enter eleven times?
This is where code for update is called. frame.getContentPane().add(new Progress2().getComponent()); inside new Progress2() That is constructor for class Progress2()
frame.setVisible(true); is responsible to show UI which is called after above statement.
To see your code in action follow the above workflow for code that should do.


text:
Q: Why use nginx as websocket proxy? So I've been reading up on this whole server set up in which Nginx is used in front of nodejs as a reverse proxy so that it serves the static content while allowing node to do the dynamic stuff. My question is, why would someone want to use the nginx front to reverse proxy to the websocket? If nginx serves the static content (HTML, CSS, JS, media, etc.) then can't the JS file that is served simply connect to the server directly using the ip address and the port that the websocket is listening on in the nodejs server? Why go through nginx to connect to the websocket on the server? Or am I not understanding this situation clearly? Thank you!

A: A WebSocket application keeps a long-running connection open between the client and the server, facilitating the development of real-time applications. The HTTP Upgrade mechanism used to upgrade the connection from HTTP to WebSocket uses the Upgrade and Connection headers. There are some challenges that a reverse proxy server faces in supporting WebSocket. One is that WebSocket is a hop-by-hop protocol, so when a proxy server intercepts an Upgrade request from a client it needs to send its own Upgrade request to the backend server, including the appropriate headers. Also, since WebSocket connections are long lived, as opposed to the typical short-lived connections used by HTTP, the reverse proxy needs to allow these connections to remain open, rather than closing them because they seem to be idle.
NGINX supports WebSocket by allowing a tunnel to be set up between a client and a backend server. For NGINX to send the Upgrade request from the client to the backend server, the Upgrade and Connection headers must be set explicitly, as in this example:
location /wsapp/ {
    proxy_pass http://wsbackend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

Once this is done, NGINX deals with this as a WebSocket connection.
For more details please visit:-
https://www.nginx.com/blog/websocket-nginx/
https://blog.martinfjordvald.com/2013/02/websockets-in-nginx/
Hope this would help!

A: One reason I could think of is that Nginx gives you more flexibility and customizations like load balancing, ratelimiting, etc.