Q: Generic response in retrofit I have 2 calls using retrofit, because the API is poorly design I get difference structure of JSON so I have two different model objects.
what I want to achieve is smaller fetch method and to avoid the duplicate code. I'm trying to use generic class for the pojo but without success.
Thanks,
my models:
   public class GenreResponse {
      @SerializedName("genre") @Expose private Genre genre;
      @SerializedName("sort") @Expose private String sort;
      @SerializedName("page") @Expose private Integer page;
      @SerializedName("limit") @Expose private Integer limit;
      @SerializedName("events") @Expose private List<Movie> events;
      @SerializedName("subGenres") @Expose private List<SubGenre> subGenres = new ArrayList<>();

      public List<SubGenre> getSubGenres() {
        return subGenres;
      }

      public Genre getGenre() {
        return genre;
      }

      public String getSort() {
        return sort;
      }

      public Integer getPage() {
        return page;
      }

      public Integer getLimit() {
        return limit;
      }

      public List<Movie> getEvents() {
        return events;
      }

    }

    public class GeneralSearchResponse {
      @SerializedName("query")   @Expose private String query;
      @SerializedName("sort")    @Expose private String sort;
      @SerializedName("page")    @Expose private String page;
      @SerializedName("limit")   @Expose private Integer limit;
      @SerializedName("amount")  @Expose private Integer amount;
      @SerializedName("events")  @Expose private List<Movie> events;
      @SerializedName("sideNav") @Expose private List<SideNav> sideNavList = new ArrayList<>();

      public List<Movie> getEvents() {
        return events;
      }

      private class SideNav {
        @SerializedName("id")           @Expose private Integer id;
        @SerializedName("name")         @Expose private String name;
        @SerializedName("englishName")  @Expose private String englishName;
        @SerializedName("amount")       @Expose private Integer amount;
        @SerializedName("isKidsEvents") @Expose private Boolean isKidsEvent;
      }
    }

my method:
 private void fetchGenresData(String genreId, int page, final boolean addMore, String sortType) {
    switch (fragmentMode) {
      case MODE_GENRE:
        Observable<GenreResponse> observableGenre = RxUtils.wrapRetrofitCall(
            VODApplication.getInstance()
                .getApi()
                .getGenres(genreType, genreId, page, DEFAULT_PAGE_LIMIT, sortType));

        RxUtils.wrapAsync(observableGenre).subscribe(new Action1<GenreResponse>() {
          @Override public void call(GenreResponse response) {

            if (addMore) {
              mAdapter.remove(mAdapter.getItemCount() - 1);
              mAdapter.addAll(response.getEvents());
            } else {
              // called for the first time.
              mAdapter.setGenres(response.getEvents());
              mSpinnerView.setListener(GenreFragment.this);
              mSpinnerView.initSpinners(response);
            }

            isLoading = false;
          }
        }, new Action1<Throwable>() {
          @Override public void call(Throwable t) {
            ((GenreScreen) getActivity()).getDialog().dismiss();
          }
        });
        break;

      case MODE_SEARCH:
        AppUtils.hideKeyboard(getActivity());

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

                if (addMore) {
                  mAdapter.remove(mAdapter.getItemCount() - 1);
                  mAdapter.addAll(response.body().getEvents());
                } else {
                  // called for the first time.
                  mAdapter.setGenres(response.body().getEvents());
                  mSpinnerView.setListener(GenreFragment.this);
                }

                isLoading = false;
              }

              @Override public void onFailure(Call<GeneralSearchResponse> call, Throwable t) {
                Log.d(TAG, "call: " + t.getMessage());
              }
            });
        break;
    }
  }


Q: Positioning 2 elements (countdown timer and button) in row, side by side - they are not centered I have a problem with one of sections in my HTML code.
My idea is simply: one section made by 1 row, who is divided on 2 columns.
In left column i tried to put countodwn timer, and "submit" button in right column. They have to be side by side, and on equal distance in regards to each other; but there are some problems - they are on unequal distance and i am wondering how to fix it...
Also, when i test how draft of my site looks on mobile, parts of the clock do not stay together - they just move under each other.
Here is a jsfiddle.
What i am doing wrong?

Deadline:

Days

Hours

Minutes

Seconds

<button class="button button1" style="width: 300px; height: 100px;">Submit</button>

And CSS:
  #clockdiv{
    font-family: Open Sans;
    color: #ffffff;
    display: inline-block;
    font-weight: 100;
    text-align: center;
    font-size: 30px;
  }

  #clockdiv > div{
    padding: 0px;
    border-radius: 3px;
    background: #fffff;
    display: inline-block;
  }

  #clockdiv div > span{
    padding: 15px;
    border-radius: 3px;
    background: #000;
    display: inline-block;
    position: relative;

  }

  .smalltext{
    padding-top: 5px;
    font-size: 16px;
    color: #000;
    position: relative;

  }

  .button {
    background-color: #fff;
    border: none;
    color: white;
    text-align: center;
    text-decoration: none;
    font-size: 16px;
    font-family: 'Open Sans';
    margin: 4px 2px;
    -webkit-transition-duration: 0.4s;
    transition-duration: 0.4s;
    cursor: pointer;
  }

  .button1 {
    background-color: white;
    color: #000;
    border: 2px solid #000;

  }

  .button1:hover {
    background-color: #fff;
    color: white;


Q: regex to filter php array by conditional existence of value I have have a php array
    $arr[0] = "something/somethingelse/anotherval";
    $arr[1] = "something/!somevar/anotherval";
    $arr[3] = "something/!notcorrect/anotherval";
    $arr[4] = "something/somethingelse/_MyVal";
    $arr[5] = "something/_MyVal/anotherval";
    $arr[6] = "something/_AnotherNotCorrect/anotherval";

I'm using array_filter to filter the array by certain criteria...
    $f = array_filter(array_keys($arr), function ($k){
    return ( strpos($k, 'something/') !== false ); });

This returns all my vals where the term something/ is matched... I'd like to be able to say IF we encounter a ![something here] or a _[something here] then we need to make sure that the [something here] matches either $afterExcl or $afterUnderscore. If we didn't encounter a ! or _ then just check the strpos($k, 'something/') !== false check...
(notice that the ! and _ portions may or may not be at the end of val string)
I'm assuming this is regex, but I've always struggled to build them.
CLARIFICATION
Thanks. Clarification though, the ! or _ sequence may not be the next directory after something/, it may three or four more steps in. AND, I'll be providing a $afterExcl or $afterUnderscore value which will designate approved values. Basically the client is using ! and _ to denote "regions" ie.
something/images/!Canada
something/videos/tutorials/!Canada or
something/images/!USA or
something/images/!Mexico OR last
something/images/All
then I'd specify
$afterExcl=Canada
My filter would return
something/images/!Canada
something/videos/tutorials/!Canada
something/images/All

A: You can use something like this:
$f = array_filter(array_keys($arr), function ($k){
    return preg_match('~something/(?![_!])~', $k); });

The negative lookahead (?!...) checks if the slash isn't followed by a ! or a _.
Note that preg_match returns 1 if found or 0 if not. If you want to return true or false you can do it with the ternary operator:
return preg_match('~something/(?![_!])~', $k) ? true : false;

an other way:
If you use strpos, I assume that the string you describe as 'something/' is a fixed string $str, in other words you know the length of this strings. Since strpos returns the position $pos in the string of the occurence, you can easily check if at the position $pos + strlen($str) there is either an exclamation mark or an underscore. (you could, for example, extract this next character and check if it is in the array array('!', '_'))


Q: ssis 2008, delete contents from excel im using SSIS for SQL Server 2008.
My SSIS package grabs data from sql and exports it to an excel file. But everytime it does this I want new data on the excel.
The problem right now is, If i execute the package more than one time I will have the old data plus the new one on the excel file. I only want the new data displayed.
On the SSIS, on the Control Flow tab I have an Data Flow task. On the Data Flow tab I have an OLEDB source and an Excel Destination in order to put the data on the excel.
So im thinking on deleting the contents from the excel on the SSIS every time before the data gets inserted on the excel.
The excel file has an image, a title and the column names. I want these data to stay.
But I want the data from the rows deleted.
How can I do this?
Thanks...

A: Ok. What I did was to make a copy of the file and load the data on the new file, and everytime the ssis loads it overwrites the file, so I always have new data..........Thanks!!


Q: google script detect empty cell after edit -- Take 2 This is related to onEdit functionality and a question with the same title found here .
I am not getting the responses they are indicating I might or should when cells go from having values to empty, and those work around solutions did not work as a result. It's as if something has changed since those answers were given or there is different underlying behavior.
Here is a link to spreadsheet with a simple example.
In this example, I have a cell with data validation on it. In context, this cell allows me to pick sales ticket IDs from a list to recall data. After I have recalled the data, if I remove the value from the selection cell with backspace or delete, the onEdit function should be called, a falsy value should exist for "e.value" and I should be able to clear the data it retrieved.  Pretty simple.
== Full Testing Protocal ==
1) When the cell is blank and I pick a value from the list,  I test the e.value property for truthy, i get truthy response, and it completes a function to get data.
2) When the cell is NOT blank and I pick a value from the list,  I test the e.value property for truthy, i get truthy response, and it completes a function to get data.
3) When the cell is NOT blank, and I click into the cell and select backspace or delete to empty the cell. I test the e.value property for truthy and instead of getting a falsy response, I get an object back?!   {old_value=xxxx}.
So, not only do I not get a falsy value, I get an object returned instead that is missing the value item in it??
From looking at the other post, it seems when there is no "value", google has decided to leave the "value" item out of the e object instead of leaving "value" item in the e object  and setting it to null or blank.
I don't know why that was chosen, but that's the way I interpret that.  That said, it seems to me that decision should not have mattered.
If I'm testing for an item in an object and the item doesn't exist, I should get a falsy of some sort, but instead, I'm getting an object returned to me?!
The only way that I know of that might to work around this is to check for variable type to see if an object was returned which is really terribly confusing for those new to programming and shouldn't be required. I will try that shortly, but wanted to get this out first.
I do recall running into this several years ago and not taking the time to try to get a sound answer.
function onEdit(e){
  Logger.log("onEdit running")
  var ss =        SpreadsheetApp.getActiveSpreadsheet();

  if (ss.getRangeByName("sTkt_uniqueID_recall").getA1Notation() == e.range.getA1Notation() ){
    Logger.log("onEdit - sTkt_uniqueID_recall")

    if(e.value){
      Logger.log("recall ID cell has value - get Data")
      Logger.log(e.value)
      //sTkt_getRecallData()

    }else{
      //oE.value should be blank, null or something falsy..
      //instead an object is returned?! {old_value: xxxxxx}
      // and thus is not null and thus it never gets here..
      Logger.log("recall ID cell now empty - clear Data")
      Logger.log(e.value)
      //sTkt_clearForm()
    }
    Logger.log("onEdit fxnComplete")
  }
}

Thanks for the help with this.
EDIT:  Added logs.
Logs when item is in cell...
[19-10-20 15:17:18:071 PDT] onEdit running
[19-10-20 15:17:18:159 PDT] onEdit - sTkt_uniqueID_recall
[19-10-20 15:17:18:160 PDT] recall ID cell has value - get Data
[19-10-20 15:17:18:160 PDT] 1002
[19-10-20 15:17:18:161 PDT] onEdit fxnComplete

Logs when item has been deleted -- it takes wrong path b/c of the object with oldValue in it...
[19-10-20 15:15:25:411 PDT] onEdit running
[19-10-20 15:15:25:509 PDT] onEdit - sTkt_uniqueID_recall
[19-10-20 15:15:25:510 PDT] recall ID cell has value - get Data
[19-10-20 15:15:25:511 PDT] {oldValue=1001.0}
[19-10-20 15:15:25:511 PDT] onEdit fxnComplete

EDIT: Providing the full event object shows this clearly. Should have just done that earlier.  As you can see old value is in there, but there is an object being returned for "value" instead of a falsy (blank or something else)...
[19-10-20 15:54:19:750 PDT] {authMode=LIMITED, range=Range, source=Spreadsheet, oldValue=10/3/2019--6939, user=xxx@xxxxacupuncture.com, value={oldValue=10/3/2019--6939}}

EDIT: I've tested a work around and this is the one I will likely use as it remind me of exactly what is going on AND Im thinking if the issue gets cleaned up or fixed, this work around should still work and I wouldn't need to make any changes in places it may go in.
if(e.value && typeof e.value !== 'object')

A: *

*In your situation, using your shared Spreadsheet, when you delete the value from the cell "C4" of the data validation with the delete button, the event object of e of onEdit(e) has "value":{"oldValue":"deleted value"}.

*

*You want to know about this situation.

If my understanding is correct, how about this answer?
When I had tested this, in your situation, I noticed that the border of cell under the simple trigger is related to this situation.
Preparation 1:
For the explanation, it supposes as follows.

*

*Create new Spreadsheet.

*Put a text of sample to the cell "A1".

*Set a simple trigger of the OnEdit event trigger as the script of function onEdit(e) {Logger.log(JSON.stringify(e))}.

*

*At the explanation, e of the event object is used, when the OnEdit event trigger was fired.

Sample situations 1:

Situation 1A:

When the value of sample of the cell "A1" is deleted by the delete button, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"user":{"nickname":"","email":""}}

Situation 1B:

When the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","user":{"nickname":"","email":""},"value":{"oldValue":"sample"}}

Sample situations 2:
Here, in order to replicate your situation, please set the border to the cell "A1".

Situation 2A:

When the value of sample of the cell "A1", which was surrounded by the border, is deleted by the delete button, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","user":{"nickname":"","email":""},"value":{"oldValue":"sample"}}

Situation 2B:

When the text of sample in the cell "A1", which was surrounded by the border, is deleted by deleting each character using the backspace key, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","user":{"nickname":"","email":""},"value":{"oldValue":"sample"}}

Preparation 2:
For the explanation, it supposes as follows.

*

*Create new Spreadsheet.

*Put a text of sample to the cell "A1".

*Copy and paste the script of function InstallOnEdit(e) {Logger.log(JSON.stringify(e))}.

*

*At the explanation, e of the event object is used, when the OnEdit event trigger was fired.

*Set the installable OnEdit event trigger to the function of InstallOnEdit.
Sample situations 1:

Situation 1A:

When the value of sample of the cell "A1" is deleted by the delete button, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"triggerUid":"###","user":{"nickname":"###","email":"###@gmail.com"}}

Situation 1B:

When the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","triggerUid":"###","user":{"nickname":"###","email":"###@gmail.com"}}

Sample situations 2:
Here, in order to replicate your situation, please set the border to the cell "A1".

Situation 2A:

When the value of sample of the cell "A1", which was surrounded by the border, is deleted by the delete button, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","triggerUid":"###","user":{"nickname":"###","email":"###@gmail.com"}}

Situation 2B:

When the text of sample in the cell "A1", which was surrounded by the border, is deleted by deleting each character using the backspace key, e of the event object returns the following value.
{"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","triggerUid":"###","user":{"nickname":"###","email":"###@gmail.com"}}

Results and discussions:
From above experiment, the following results could be obtained.

*

*Values of the event object depend on the situation with and without the border of cell.

*

*Also above situation can be seen at not only the border, but also the cases that the background color of the cell, the format (font color, size, bold and so on) except for the default font format.

*It seems that when the cell and font are changed from the default settings, the event object returns the values of "Sample situations 2".

*Values of the event object also depend on with and without using the installable event trigger.

*In the case of the cell with the default cell and font under the simple trigger,

*

*When the value of sample of the cell "A1" is deleted by the delete button, e of the event object has no both oldValue and value.

*When the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object has both oldValue and value. And value is {"oldValue":"deleted value"}.

*In the case of the cell with the border under the simple trigger,

*

*When the value of sample of the cell "A1" is deleted by the delete button and also the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object has both oldValue and value. And value is {"oldValue":"deleted value"}.

*In the case of the cell with the default cell and font under the installable trigger,

*

*When the value of sample of the cell "A1" is deleted by the delete button, e of the event object has no both oldValue and value.

*When the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object has oldValue and no value. And oldValue is the deleted value which is not the object.

*In the case of the cell with the border under the installable trigger,

*

*When the value of sample of the cell "A1" is deleted by the delete button and also the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object has oldValue and no value. And oldValue is the deleted value which is not the object.

From above results, I thought that the values (no both oldValue and value) of event object from the default condition of the cell and font might be a bug or the specification. But I had looked for the official document about this. Unfortunately, I couldn't still find it.
About your situation:
Using above results, when your shared Spreadsheet was tested, the cell "C4" is surrounded by the border. And the simple trigger is used. So the situation is the same with above "Sample situations 2" of "Preparation 1". By this, when the value of cell "C4" is deleted by the delete button, "value":{"oldValue":"deleted value"} is returned.
In this case, how about the following method?

*

*When you want to use the simple trigger, I think that the script of the bottom of your question can be used.

*When you can use the installable OnEdit event trigger, you can know whether the value was deleted by checking with and without value in the event object e.

References:

*

*Event Objects

*Simple Triggers

*Installable Triggers


Q: Qt font renders weird on OS X I just started using Qt (using Qt 5 beta 1), and I found that the fonts rendered in OS X 10.6.8 are messed up. I've tried using different fonts, but they all look like the image I've posted below (very thin, pixelated). How can I get the fonts to render correctly?
The code I'm using is simply:
#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QLabel label("The quick brown fox jumps over the lazy dog...");
    label.show();
    return a.exec();
}


Q: MATLAB Fit a line to a histogram I am just wondering, how would I go about fitting a line to histogram, using the z-counts as weights? An example of this is shown below (although this post just discusses overlaying multiple plots), taken from Scatter plot with density in Matlab).
My initial thought is to make an array consisting of each pixel from the density plot, repeated n times to make a scatter plot (n == the number of counts), then do a linear polyfit. This seems awfully redundant though.

A: The other approach is to do a weighted least squares solution.  You need the (x,y) location of each pixel and the number of counts n within each pixel.  Then, I think that you'd do the weighted least-squares this way:
%gather your known data...have x,y, and n all in the same order as each other
A = [x(:) ones(length(x),1)];  %here are the x values from your histogram
b = y(:);  %here are the y-values from your histogram
C = diag(n(:));  %counts from each pixel in your 2D histogram

%Define polynomial coefficients as p = [slope; y_offset];

%usual least-squares solution...written here for reference
% b = A*p;               %remember, p = [slope; y_offset];
% p = inv(A'*A)*(A'*b);  %remember, p = [slope; y_offset];

%We want to apply a weighting matrix, so incorporate the weighting matrix
% A' * b = A' * C * A * p;
p = inv(A' * C * A)*(A' * b);  %remember, p = [slope; y_offset];

The biggest uncertainty for me with this solution is whether the C matrix should be made up of n or n.^2, I can never remember.  Hopefully, someone can correct me in the comments, if needed.

A: If you have the original data, which is a collection of (x,y) points, you simply do a polyfit on the original data:
p = polyfit(x(:),y(:),1);  %linear fit

That will give you a best fit (in the least-squares sense) to the original data, which is what you want.
If you do not have the original data, and you only have the 2D histogram, the approach that you defined (which basically recreates a facsimile of the original data) will give a similar answer as if you did the polyfit on the original data.


Q: Custom image shuffler not working? Basically, what I'm trying to do is shuffle through images using some JavaScript code. All it does is change the display style of the current image to block, and at the same time change the previous one to none.
The HTML code:

The JavaScript code:
var id = ["image1", "image2", "image3"]; //Array with the id's in the document you want
to shuffle through
var i = 0; //Set inital array element
initiateTimer(); //Get the loop going

function initiateTimer() {
if (i > id.length) {
    i = 0;
    initiateTimer();
}
setTimeout(function() { changeElement(); }, 2000); //2000 = 2 seconds
}

function changeElement() {
if (id === 0) {
    document.getElementById(id[2]).style.display = 'none';
    document.getElementById(id[i]).style.display = 'block';
} else {
    document.getElementById(id[i - 1]).style.display = 'none';
    document.getElementById(id[i]).style.display = 'block';
}
i += 1;
initiateTimer();
}

A: when i === 3 you will have problems
if (i > id.length) {

should become
if (i >= id.length) {

UPDATE: http://jsfiddle.net/HgNuc/


Q: Interesting examples of commutative linear algebraic groups; uniqueness of composition series We define an algebraic group to be solvable if it has a filtration where the successive quotients are abelian. The Lie-Klochin theorem says that every smooth solvable connected group admits an embedding into the Borel subgroup of $GL_n$. But the Borel subgroup o $GL_n$ has a filtration where the successive quotients are $\mathbb{G}_m's$ and $\mathbb{G}_a's$.
Therefore it seems like there are really no examples of abelian linear algebraic groups other than $\mathbb{G}_m's$ and $\mathbb{G}_a's$ or tori and finite abelian groups. Unless the composition factors for a linear algebraic group need not be unique, unlike the case for finite groups.
Are the composition factors for a linear algebraic group unique, and  if not, then what are some more interesting examples of abelian linear algebraic groups?


Q: Cant open a doc file from the browser I have a link using  tag and it is linked to a .doc file in the server. When I click on the link, instead of giving the open, save box, it opens the file in the browser in the binary format. Has anyone encountered this problem? I am using a Weblogic server.

A: As Russ said, sometimes you have to add the Content-Type header to explicitly set the mime type; and sometimes, you also have to add a Content-Disposition header, perhaps to a value like

"attachment; filename=doc1.doc"

If Russ' fix doesn't work for you, try adding this additional header.

A: try setting the MIME Type, possibly to application/msword or application/doc
EDIT:
If the server doesn't know the mime type of the file then it defaults to text/plain and displays the bytes.


Q: Why is Microsoft.PythonTools.Attacher.exe blocking Visual Studio 2010? At least two or three times a day Visual Studio gets stuck (in a deadlock I suspect) and displays the spinning-toilet-bowl-of-death cursor and pops up the dreaded "Microsoft Visual Studio is Busy" notification in the notification area:

It used to be that when this happened Visual Studio would stay like that for hours (and possibly until the end of time itself or a power cut) unless I kicked it to the kerb with an "End Process" in task manager.
More recently I noticed another process always seemed to be lurking about whenever this problem arises - Microsoft.PythonTools.Attacher.exe - which is part of the Python Tools for Visual Studio project:

If I kill that process then Visual Studio manages to free itself from whatever deadly embrace it's got itself into and can continue on its way, and this is what I look out for every time VS does this.
Whilst I do have Python Tools for Visual Studio 1.0 installed, the projects I am working on are plain old ASP.NET MVC3 apps written in C#. I'm not using any Python code or libraries and often I only have one instance of Visual Studio running.
What I also observe is that this process doesn't always start/appear for whole development sessions, and when it does, it seems to start up an random times (i.e. it's not there for the first hour or two and then it magically appears in the process list in task manager), but when it does I know I'm going be in trouble at some point.
Does anyone know why this process seems to randomly start and why it's interfering with Visual Studio in such a dramatic fashion?
I'm running Visual Studio 2010 Premium SP1 on Windows 7 Ultimate x64 SP1.

A: When you do Debug->Attach to Process you'll see that VS displays a list of processes and along with them it displays the types of code that you can debug which are running in those processes.  To get this information VS queries the various installed debug engines.  So when we get queried we go and inspect a bunch of processes to see what's going on.  If it's a 32 bit process life is easy - we can use various APIs to enumerate the modules and try and figure out if there's a Python interpreter in the process.  If it's a 64-bit process life is a little tougher because we're running inside of VS and it's a 32-bit process.  We can't use the APIs from a 32-bit to a 64-bit process so instead we spawn a helper process to do the work.
It sounds like this helper process is somehow becoming a zombie on your system.  It'd be great if you could attach VS to it and send any stack traces back in a bug.  But we should also provide some defense in depth and timeout if the helper process isn't responding.
Finally killing it should generally be safe, it's not doing anything stateful, and we'll start a new one when we need it.
If you never use Debug->Attach to Process for Python debugging there's probably a trivial file update to our .pkgdef file which I could track down and post which would make this problem go away entirely.


Q: How to trigger fresh install instead of update? I'm an android developer and I'll be releasing a new update of my application in the coming days. But the new update is a complete redesign of the app's entire architecture, so I'd like the user to uninstall the previous version of the app before he installs the new version so that all the cached data/already logged in user gets cleared and the user makes a fresh start. I was wondering how I could make this happen? What are my best options? Thanks!

A: If you use sqflite or shared_preferences simply remove all data in the main() function with clear all keys or clear the database. Then you need to write a function that will execute this part of the code once. So basically that's all.
import 'package:shared_preferences/shared_preferences.dart';

void main(List<String> arguments) async {
  bool isDataCleared = false;
  if (isDataCleared == false) {
    final prefs = await SharedPreferences.getInstance();
    prefs.clear();
    isDataCleared = true;
    prefs.setBool('isDataCleared', isDataCleared);
  } else {
    // Do something or continue
  }
}

I hope it will help!

A: You must have made the changes in your code previously for it to trigger an update whenever there is a new release automatically. There is a workaround I can think of though:
You can embed some data in this new release which should be passed to the backend. If this new data is not passed, you should log them out with an error message to update the application.
This approach is because the backend is the only common link between the old and new applications.


Q: Tutorial to create phone book contact in Android SDK Although there are sites out there to help me create a contact, I am still not able to understand how to do it, Can someone give me a pointer/link/suggestion, that teaches me from scratch how to create a phone contact that will eventually show up in phone contacts list. Thank you.

A: While I don't know of any tutorials to show step by step. These links may help:

*

*Using the Contacts API

*ContactManager - Contact Manager


Q: Mongoose Connection I read the quick start from the Mongoose website and I almost copy the code, but I cannot connect the MongoDB using Node.js.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

exports.test = function(req, res) {
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'connection error:'));
  console.log("h1");
  db.once('open', function callback () {
    console.log("h");
  });
  res.render('test');
};

This is my code. The console only prints h1, not h. Where am I wrong?

A: Mongoose connection using Singleton Pattern
Mongoose Connection File - db.js
//Import the mongoose module
const mongoose = require('mongoose');

class Database { // Singleton
  connection = mongoose.connection;

  constructor() {
    try {
      this.connection
      .on('open', console.info.bind(console, 'Database connection: open'))
      .on('close', console.info.bind(console, 'Database connection: close'))
      .on('disconnected', console.info.bind(console, 'Database connection: disconnecting'))
      .on('disconnected', console.info.bind(console, 'Database connection: disconnected'))
      .on('reconnected', console.info.bind(console, 'Database connection: reconnected'))
      .on('fullsetup', console.info.bind(console, 'Database connection: fullsetup'))
      .on('all', console.info.bind(console, 'Database connection: all'))
      .on('error', console.error.bind(console, 'MongoDB connection: error:'));
    } catch (error) {
      console.error(error);
    }
  }

  async connect(username, password, dbname) {
    try {
      await mongoose.connect(
        `mongodb+srv://${username}:${password}@cluster0.2a7nn.mongodb.net/${dbname}?retryWrites=true&w=majority`,
        {
          useNewUrlParser: true,
          useUnifiedTopology: true
        }
      );
    } catch (error) {
      console.error(error);
    }
  }

  async close() {
    try {
      await this.connection.close();
    } catch (error) {
      console.error(error);
    }
  }
}

module.exports = new Database();

call the connection from app.js
const express = require("express"); // Express Server Framework

const Database = require("./utils/db");

const app = express();

Database.connect("username", "password", "dbname");

module.exports = app;

A: When you call mongoose.connect, it will set up a connection with the database.
However, you attach the event listener for open at a much later point in time (when a request is being handled), meaning that the connection is probably already active and the open event has already been called (you just weren't yet listening for it).
You should rearrange your code so that the event handler is as close (in time) to the connect call as possible:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log("h");
});

exports.test = function(req,res) {
  res.render('test');
};

A: I had the same error popping up. Then I found out that I didn't have a mongod running and listening for connections. To do that you just need to open another command prompt (cmd) and run mongod

A:
The safest way to do this, it to "listen for the connect event". This way you don't care how long it takes for the DB to give you a connection.
Once that is done - you should start the server. Also.. config.MONGOOSE is exposed across your app, so you only have one DB connection.
If you want to use mongoose's connection, simply require config in your module, and call config.Mongoose.  Hope this helps out someone!
Here's the code.

var mongoURI;

mongoose.connection.on("open", function(ref) {
  console.log("Connected to mongo server.");
  return start_up();
});

mongoose.connection.on("error", function(err) {
  console.log("Could not connect to mongo server!");
  return console.log(err);
});

mongoURI = "mongodb://localhost/dbanme";

config.MONGOOSE = mongoose.connect(mongoURI);

A: Mongoose's default connection logic is deprecated as of 4.11.0. It is recommended to use the new connection logic:

*

*useMongoClient option

*native promise library

Here is the example from npm module: mongoose-connect-db
// Connection options
const defaultOptions = {
  // Use native promises (in driver)
  promiseLibrary: global.Promise,
  useMongoClient: true,
  // Write concern (Journal Acknowledged)
  w: 1,
  j: true
};

function connect (mongoose, dbURI, options = {}) {
  // Merge options with defaults
  const driverOptions = Object.assign(defaultOptions, options);

  // Use Promise from options (mongoose)
  mongoose.Promise = driverOptions.promiseLibrary;

  // Connect
  mongoose.connect(dbURI, driverOptions);

  // If the Node process ends, close the Mongoose connection
  process.on('SIGINT', () => {
    mongoose.connection.close(() => {
      process.exit(0);
    });
  });

  return mongoose.connection;
}

A: A simple way i make a connection:
const mongoose = require('mongoose')
mongoose.connect(<connection string>);
mongoose.Promise = global.Promise;
mongoose.connection.on("error", error => {
    console.log('Problem connection to the database'+error);
});


Q: Android TV :Show Row Title always How do I get the title of the individual rows to always appear instead of only when it is selected? Like the example here in Youtube app, "Uploads" and "Popular Uploads" should always be seen.

A: I just answered this question here, but the general gist is:

I was able to achieve this affect by calling setExpand(true) as the first line of my onCreateView() in my RowsFragment.
If you want to lock this effect forever, you can override setExpand(...) in your RowsFragment and just call super.setExpand(true). I believe you'll still need the initial call in onCreateView() though.


Q: What is the best data structure to store playing cards held in a player's hand? I'm beginner in java and I'm currently creating a card game like gin rummy for Android.  I want to know what's the best implementation for creating Hand class?  What's the best way where to store the card returned by Deck.dealt()?

*

*Array

*ArrayList

*Vector

*HashSet

*LinkedList

Also, I would appreciate if anyone could provide a gin rummy open source links.

A: I think a good idea would be to use an interface (List if element are ordered, or Set if elements are not ordered. You can use the implementation you prefer, for example:
List<Card> deck = new ArrayList<Card>();

or
Set<Card> deck = new HashSet<Card>();

A: If you really want to understand the nuances between the collection types, here goes.
List isn't technically appropriate except when the game is Bohnanza (which, ahem, is one of the greatest card games of all time, but I'mma let me finish).
List says, among other things, that one hand containing the Ace and King of Clubs, and another hand containing the King and Ace of Clubs, are fundamentally not the same hand. This is a much stronger dependence on order than simply "well, I want to remember the order that the user wants to see their cards in", which is a property that tons of non-List collections have, like LinkedHashSet and Guava's ImmutableSet.
List also implies that there is some particular significance attached to the card that sits in index N.  This is true of no card game I know.
Set isn't generally appropriate for card games -- only the ones that use a single deck of completely unique cards.
To allow duplicates but still have order-independent equality, the type to use is Guava's Multiset.  For example HashMultiset or ImmutableMultiset. Note that most multiset implementations represent multiple "equal" cards by storing just the card and a count, so when iterating over them, duplicates of a card you have in your hand must always appear together. If it's important to let the user freely control the order of cards in her hand, you would need LinkedListMultiset.
Now that lesson time is over.... well, let's be honest. Calling myHand.equals(yourHand), or using an entire hand as a key in a Map is not actually something you're ever going to do... so go ahead and use the ArrayList, you'll be fine. :-)

A: Store them in an ArrayList.
Cards in a hand are in a certain order, not in an unordered pile.  This ordering is preserved in a List over a Set.
ArrayList also gives you the opportunity to select a specific card by index, which will be helpful as you implement the game.
Keep in mind that as long as you design your Hand class properly, you can always change this data structure easily at any point in the future.  As long as you keep this in mind with any class you design, you can always change it if you realize you need something different.

A: Well, a HashSet is faster(as far as I know), but if you want to make a card game, then maybe you will wish to sort the cards. That is why I would suggest using a List. If you are a beginner, then maybe the best thing would be to use an ArrayList. It's easy to use and understand. At least this is what I would do. If you want to learn more, I suggest reading about each one's unique properties so that you can decide for yourself. And yes, like greuze said before, you should use an interface for more flexibility.

A: Firstly, use of Vector is discouraged in the latest versions of Java, so you can probably ignore that one.
Secondly, as you'll know if you're read the Javadoc on those remaining classes, they all have advantages or disadvantages. Some have an order, some can take duplicate values, some cannot and so on. Therefore I think the best approach is to write some pseudo-code for your application which is not based on a specific class (just write things like 'add Card to Hand', 'remove card from Hand'). Once you have some of this pseudo code you will be able to see your requirements more clearly; will you want to keep the cards in the hand in a specific order? will you want to be able to retrieve cards from the hand by a key?
Then, your choice will be clearer.

A: Keeping the deck in a List makes sense as it does maintain order. I tend to default to using Lists.newArrayList() to create a List. Lists is part of Guava. I strongly recommend using and getting to know Guava since it has many useful offerings.
It would make sense to be able to keep the hand in some data structure that could be sorted easily in order to make it easier to compare hands. OTOH, IIRC, gin rummy hands aren't all that large.


Q: Using nonce or hash values in content-security-policy for inline styles I am adding content-security-policy settings for my web app and would like to be strict about inline scripts and inline styles.  I have inline scripts working properly but am having trouble with inline styles.  For background, my web app uses Elixir/Phoenix on the back end and includes React components on the front end.
Nonce for Inline Scripts - Works
I have just a smattering of inline scripts to get the React components bootstrapped.  Per CSP guidelines, I'm using nonce values to handle these inline scripts.  Specifically, I generate a new nonce value server side on each page load and include it in the content-security-policy header and also inject it into a nonce attribute in the script tags using server side rendering.  This works fine.
Nonce for Inline Styles - Doesn't Work
Inlines styles are another story.  Inlines styles are pretty common in React.  My hope was that I could use a similar nonce approach for this, but so far I have not been able to get it to work.  Nonce values are listed in the style-src page at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src so it seems like this should work, though that section of the doc references scripts so maybe not.  I have tried injecting a nonce attribute into the generated HTML, but this does not work.  I continue to receive the normal error messages.

Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self' 'nonce-my-long-ugly-random-nonce-value'". Either the 'unsafe-inline' keyword, a hash ('sha256-specific-hash'), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.

I've been searching for a while and have yet to find any hint that nonce values work for inline styles, other than what I mention above.  Can anyone confirm that nonce values work for inline styles?
If they don't work, it seems like using hashes is my next best bet.  I can get hashes to work, by looking at each error message like the one above and adding the hash to the content-security-policy header.  That is not a very scalable solution though, and if I have to go that route I'd like to know if anyone has come up with a way to automate generating the hashes without having to manually navigate everywhere in the app and look at the error message to get the hash.
Any help you can provide is appreciated.
Thanks.
Justin

A: After looking at Content Security Policy allow inline style without unsafe-inline it appears this isn't supported, perhaps because the spec seems to imply that it is referring only to inline styles in a <style> tag, similar how the spec refers to inline scripts in a <script> tag.
Assuming that is correct, it looks like I'll have to go the hash route or add 'unsafe-inline' just for style-src.


Q: Finding optimal linear transformation for intersection of convex polytopes I previously posted this on MathSE and am now trying here.

I have the following situation, as shown in the following diagram:

*

*$W=\{w_i\}_{i=1..|W|}$ is a set of vertices (show in diagram in blue) located within a regular simplex and having coordinates $\in \mathbb{R}^n$ .  In the diagram, an example $W$ is depicted by three vertices $w_1$, $w_2$, and $w_3$.  Some vertices of $w_i$ may be convex combinations of others.

*$A=\{a_i\}_{i=1..|A|}$ (orange) and $B=\{b_i\}_{i=1..|B|}$ (green) are sets of vertices located within the convex hull of $W$.  Examples are shown in the diagram, indicated by $a_1$, $a_2$, $a_3$ and $b_1$, $b_2$, $b_3$.
The coordinates of the vertices $A$ and $B$ are held fixed in terms of the coefficients associated with $\{w_i\}$ (vertices of $W$), but naturally vary with $W$.

*The convex hulls of $W$, $A$ and $B$ are all guaranteed to include the origin (indicated by the red $+$).

*The intersection of the convex hulls of $A$ and $B$, called by $A \cap B$, is indicated in grey.  Call this region, as a function of the vertices $W$, by $C(W)=Conv(A(W)) \cap Conv(B(W))$.
I need to maximize a convex function $f$ over the intersection region:
$$\max_{W,x\in C(W)} f(x)$$
It is important to note again that some of the vertices of $w_i$ may be convex combinations of others.  In fact, increasing the intersection between the convex hulls of $A$ and $B$ can involve projecting onto subspaces where they overlap (orthogonally to subspaces in which they differ).
Finding a global minimum does not seem possible using standard optimization techniques, since (at least in the way I've been able to state it), it involves a quadratic equality constraint.  I'm wondering if there is some special structure, or some combination of optimization and enumeration,  I can exploit to find the solution.
Some ideas:
1) Is it possible to prove something special about the optimal $W$ vertices, such as that they will map onto (a subset of) the vertices of underlying regular simplex?  In this case, I could enumerate all possible such $W$ (I'm dealing with low dimensional objects).
2) Because $f$ is convex, for any given $W$ it will be maximized at one of the extreme points of $C(W)$.   Is there any way to split the set of possible $W$s into a finite set of regions $\{\Omega_1, \dots, \Omega_m\}$, where in each case the set $\{Ep(C(W)) : W \in \Omega_i\}$ (where $Ep$ indicates the extreme points of a convex set) will be convex?
3) Perhaps the polar duality can be used here?  For convex polytopes $P_1$ and $P_2$, I know that $P_1 \cap P_2 = ConvHull( P_1° \cup P_2°)°$, where $P°$ indicates the polar polytope of $P$.  There is also duality between the vertices and faces of a polytope and its polar dual. Maybe the set of possible vertices of the intersections be associated with the faces of $(A° \cup B°)$ under linear transformation $T$ which represents remapping the vertices of $W$?  One difficulty is that, IIRC, the polar of a polytope transformed by linear transformation $T$ (call this $PT$), is $P°T^{-1}$.  As I suggested, the set of $W$ may not be linearly independent, leading to a singular $T$.  (Actually, I'm not sure if this relationship even holds for non-convex polytopes -- such as $P_1° \cup P_2°$ -- or whether things get weird).
In any case, any other relevant literature / ideas here would be greatly appreciated!


Q: Connecting noodles probability question I don't know how to solve this. You have 100 noodles in your soup bowl. Being blindfolded, you are told to take two ends of some noodles (each end of any noodle has the same probability of being chosen) in your bowl and connect them. You continue until there are no free ends. The number of loops formed by the noodles this way is stochastic. Calculate the expected number of circles.

A: Let's do it in a more general case.
Let the expected number of loops from $n$ noodles be $E(n)$.
Obviously, $E(1)=1$.
For $n>1$, if you pick up two ends, the possibility for those two ends belongs to the same noodle will be $\frac{1}{2n-1}$. Then you have one loop now and there are $n-1$ noodles to keep on going. Otherwise you get no loop and still have $n-1$ noodles to go(The two you pick before are now connected as one). Hence $E(n)=E(n-1)+\frac{1}{2n-1}$
Inductively you may expect that $E(n) = 1+\frac{1}{3}+\frac{1}{5}+...+\frac{1}{2n-1}$.

A: The accepted answer is correct, but I think should be more carefully detailed.
$E(1) = 1$
Pick up two ends. They either belong to the Same Noodle ($S$) or they don't ($\bar{S}$). The $S$ event can be used to "compute expectations by conditioning" in the same spirit of this question. So:
$$E(n) = E(n | S)p(S) + E(n | \bar{S}) p(\bar{S})$$
Now $p(S) = \frac{1}{2n-1}$ and $p(\bar{S}) = 1-\frac{1}{2n-1}$. Now the trick is that $E(n|S) = E(n-1)+1$ (i.e. if you picked the two ends from the same noodle you've added one loop to the bowl, leaving $n-1$ noodles) and $E(n|\bar{S}) = E(n-1)$ (i.e if you've picked two ends from different noodles you didn't increase the number of loops).
$$E(n) = E(n | S)p(S) + E(n| \bar{S}) p(\bar{S}) = \\
= \left[E(n-1)+1\right]\frac{1}{2n-1} + E(n-1)\left[1-\frac{1}{2n-1}\right] = \\
= E(n-1) + \frac{1}{2n-1}$$


Q: Diferenças entre Natural Join e Inner Join Que características diferenciam uma consulta realizada com o uso de Natural Join de outra com o uso de Inner Join? Existe alguma questão relacionada a desempenho ou qualquer outra condição que me leve a escolher uma em detrimento da outra?
Para o exemplo abaixo, teríamos as seguintes consultas:
select livro.nome_livro, editora.nome_editora from livro natural join editora

ou
select livro.nome_livro, editora.nome_editora from livro
inner join editora on editora.codigo_editora = livro.codigo_editora

A: O NATURAL JOIN é só um facilitador. Ele não é mais rápido ou faz nada melhor, ele apenas permite uma sintaxe mais curta se a junção é simples, o seu exemplo ilustra bem isto. Ambos fazem exatamente a mesma coisa da mesma forma mas a primeira é mais fácil de escrever.
O nome é assim porque esta é a forma mais natural de fazer um INNER JOIN simples.
Como dá para perceber não é possível produzir resultados com expressões mais complexas usando a forma natural.
Se o * for usado para pegar os campos nas tabelas com NATURAL JOIN as colunas de mesmo nome não serão mostradas repetidas no resultado.
Artigo da Wikipedia.
Coloquei no GitHub para referência futura.


Q: SELECT UPDATE SQL Not Working I have 2 forms
First Form has
Public Class frmMain

Friend strBillIDNumber As String
Friend strBillPassword As String
Friend ds As New DataSet
Friend cnn As OleDbConnection
Friend sql As String
Friend adptr As OleDbDataAdapter
Dim attempt As Integer = 1

Private Sub btnSign_Click(sender As Object, e As EventArgs) Handles btnSign.Click

    Dim connectionString As String
    connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\UsersDB.accdb;"
    sql = "Select ID, LASTNAME, FIRSTNAME, LOGINSTATUS from TblUser"
    cnn = New OleDbConnection(connectionString)
    Try
        cnn.Open()
        adptr = New OleDbDataAdapter(sql, cnn)
        adptr.Fill(ds)

        For i = 0 To ds.Tables(0).Rows.Count - 1

            If ds.Tables(0).Rows(i).Item(0) = txtID.Text Then
                MessageBox.Show("UserName Matched")
                If ds.Tables(0).Rows(i).Item(1) = txtPassword.Text Then
                    MessageBox.Show("Password Matched")

                    If txtPassword.Text = "admin" Then
                        MessageBox.Show("You are now Logged In as Admin.")
                        frmFaculty.Show()
                        Me.Hide()
                    Else
                        frmStudent.lblSI.Text = ds.Tables(0).Rows(i).Item(0)
                        frmStudent.lblLN.Text = ds.Tables(0).Rows(i).Item(1)
                        frmStudent.lblFN.Text = ds.Tables(0).Rows(i).Item(2)
                        frmStudent.lblLS.Text = ds.Tables(0).Rows(i).Item(3)
                        MessageBox.Show("You are now Logged In.")
                        frmStudent.Show()
                        Me.Hide()
                    End If
                Else
                    MessageBox.Show("Invalid Password.")
                    MessageBox.Show("Please Try Again." & vbNewLine & "ATTEMPT: " & attempt & " out of 3")
                    attempt = attempt + 1
                End If
            End If

        Next

        adptr.Dispose()
        cnn.Close()
    Catch ex As Exception
        MessageBox.Show("Please Try Again!")
    End Try

    'log-in attempt 3x fail'
    If attempt > 3 Then
        MessageBox.Show("You have exceeded the number of login attempt." & vbNewLine & "Please Contact the Administrator.")
    End If
End Sub

And my Second Form Has
Imports System.Data.OleDb

Public Class frmStudent
Dim TimeInHold As String
Private Sub loginBTN_Click(sender As Object, e As EventArgs) Handles loginBTN.Click

    Dim cnn2 As New OleDbConnection
    Dim Command As OleDbCommand
    Dim i As Integer
    Dim sql2 As String
    Dim status As String

    Try
        cnn2 = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\AuditDB.mdb;")
        cnn2.Open()

        sql2 = "INSERT INTO Audit ([ID],[TIMEIN]) VALUES('" & frmMain.txtID.Text & "','" & DateTime.Now & "')"

        Command = New OleDbCommand(sql2, cnn2)
        i = Command.ExecuteNonQuery

    Catch ex As Exception
        cnn2.Close()

    End Try

    MessageBox.Show("You have successfully Signed in." & vbNewLine & " Please Don't Forget to Logout.")
    frmMain.cnn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\UsersDB.accdb;")
    frmMain.cnn.Open()
    frmMain.adptr = New OleDbDataAdapter(frmMain.sql, frmMain.cnn)
    frmMain.adptr.Fill(frmMain.ds)
    If frmMain.ds.Tables(0).Rows(i).Item(0) = lblSI.Text Then
        frmMain.sql = "UPDATE TblUser SET LOGINSTATUS = 'SignedIn'"

        frmMain.cnn.Close()
    End If
    Me.Close()
    frmMain.Show()
    frmMain.txtID.Text = String.Empty
    frmMain.txtPassword.Text = String.Empty
End Sub

I can't get my SELECT and UPDATE sql statement to work that will get the data set from form 1.  And when the button is clicked, it will update the field "LoginStatus" to a value of "Signed In".
P.S. I'm creating a time-in, time-out monitoring system that will determine if the user is an admin or a student and will redirect them to their corresponding forms.  Student form will have sign in and sign out buttons, and will record their time in and time out.  When sign in is clicked, it will be grayed out.
Please Help..

A: If frmMain.ds.Tables(0).Rows(i).Item(0) = lblSI.Text Then
    frmMain.sql = "UPDATE TblUser SET LOGINSTATUS = 'SignedIn'"

    frmMain.cnn.Close()
End If

It seems that the UPDATE statement doesn't get executed.
I don't see ExecuteNonQuery for it.
ps: The UPDATE statement is to update all records in the table. Look out!
ps2: I'm not familiar with the VB(.net) :)

A: I think you are missing executeNonQuery in second form and is there only one user then query is fine if more than one consider using " Where Clause" eg.
sql= "UPDATE TblUser SET LOGINSTATUS = 'SignedIn' where ID =" <provide id>

if that doesn't solve your problem then feel free to ask more.
Regards.


Q: problems with my /etc/profile I am a rookie in ubuntu, I tried to install java but I think it was installed yet (I didn't check it before, sorry), now an error pops up appears in my screen every time I log in
/etc/profile: line 28: $'E[200~': order not found

Could anybody help me please?

A: Line 28 of your /etc/profile has that character string in it, and the shell couldn't understand it. Look at the line with
sed -n -e '28p' /etc/profile | \
  od -bc

and delete the funny characters with your favorite editor.


Q: Gatsby Dynamic Image I have a problem: this is my Heroes component
const Hero = styled.div`
display: flex;
flex-direction: column;
justify-content: flex-end;
background: linear-gradient(to top, #1f1f21 1%, #1f1f21 1%,rgba(25, 26, 27, 0) 100%) , url(${props => props.bgdesktop}) no-repeat top center;
height: 100vh;
background-size: cover;
@media (max-width:1024px) {
background: linear-gradient(to top, #1f1f21 1%, #1f1f21 1%,rgba(25, 26,
27, 0) 100%) , url(${props => props.bgtablet}) no-repeat center top;
}
@media (max-width:480px) {
background:linear-gradient(to top, rgba(31, 31, 33, 1) 2%, rgba(31, 31,33, 1) 5%,rgba(25, 26, 27, 0) 100%)  , url(${props => props.bgmobile}) no-repeat center top;
    }
`
class Heroes extends React.Component {
constructor(props) {
    super(props);
...
render() {
    return (
<Hero
bgdesktop={this.props.bgdesktop}
bgtablet={this.props.bgtablet}
bgmobile={this.props.bgmobile}/>
)}}

Then I added this component to 'pages/Hero.js':
export default props => {
const hero = props.location.href
? heroCards.find(h => h.name === props.location.href.substring(28))
: heroCards[0]
return (
<Layout>
<Heroes
        bgdesktop={require(`./../images/BG/${hero.name}_Desktop.jpg`)}
        bgtablet={require(`./../images/BG/${hero.name}_Tablet.jpg`)}
        bgmobile={require(`./../images/BG/${hero.name}_Mobile.jpg`)}
      />
</Layout>
)
}

Now, clicking on different buttons on the Home page, I'm redirected different pages that take different bg depending on 'name' included in heroes.js (located in costants folder). It works on local but not on production and the problem is gatsby that doesn't allow that '{require(./../images/BG/${hero.name}_Desktop.jpg)}'. How can I solve this problem?

A: I don't think you need require for this.
Why not use the prop you pass and bake that into a string literal that you insert into the component (without require and outside of the return)?
const mobilePath = `./../images/BG/${props.bgmobile}_Mobile.jpg`;
const desktopPath = `./../images/BG/${props.bgdesktop}_Desktop.jpg`;

return(
  <Heroes mobile={mobilePath} desktop={desktopPath} />
)

EDIT: the substring part could be added in either <Heroes> before passing  the prop. Or by filtering the prop in <Hero> and passing that variable instead of the prop


Q: Vector Calculus - Evaluating $\nabla \times \mathbf{E} = -\frac{1}{c} \partial_t \mathbf{B}$ For the life of me, I cannot remember how to solve equations similar to the cross product equations in Maxwell's equations. I haven't used vector calculus of this level in quite some time and could use some help with it. Given a specific electric field inbetween two perfect conductors (the inner conductor has an outer radius $a$ and the outer conductor has an inner radius $b$,
\begin{equation}
\mathbf{E}(\mathbf{r},t)
=
\dfrac{E_0}{2\pi} \dfrac{\hat{\mathbf{x}} x +\hat{\mathbf{y}}y}{x^2 + y^2} \cos\left(\omega\left(\frac{z}{c}-t\right)\right),
\end{equation}
how would you use the equation
$\nabla \times \mathbf{E} = -\frac{1}{c} \partial_t \mathbf{B}$
to solve for the magnetic field? (If there is an easier alternative way to do this, I'm open to learning that method, as well.)
Note: The notation $\partial_t$ is simply shorthand for $\partial/\partial t$.

EDIT: The coaxial cable is along the $z$-axis.
Thanks!


Q: Recursion time complexity I am looking for help in understanding what the Time/Space complexity of my solution, for finding permutations of an array, is. I know that because I am using an Array.forEach method that my time complexity includes O(n), however since I am also using recursion I do not know how the time complexity changes. The recursion seems to me to be in O(n) time complexity as well. Does that make the overall time complexity of the algorithm O(n^2)? And for space complexity is that 0(n) as well? since each recursion call returns a bigger memory array? Thanks in advance.
  function getPermutations(array) {
      if (array.length <= 1){
        return array.length === 0 ? array : [array];
      }

      let lastNum = array[array.length - 1]
      let arrayWithoutLastNum = array.slice(0, array.length - 1);
      let permutations = getPermutations(arrayWithoutLastNum);

      let memory = []
      permutations.forEach(element => {
        for(let i = 0; i <= element.length; i++){
          let elementCopy = element.slice(0);
          elementCopy.splice(i, 0, lastNum)
          memory.push(elementCopy)
        }
      })

      return memory
    }


Q: Symmetries of a Square $U_{24}$ and $\mathbb Z_{8}$ proving or disproving an Isomorphism The question is as follows.
Consider the following three groups: $\mathbb Z_{8}$, $U_{24}$ and the group of symmetries of the square. For each pair, determine if the two groups are
isomorphic. If they are isomorphic, give and explicit isomorphism and
if they are not, explain why they are not.
Firstly i want to list the elements of the symmetries of a square.
I, $R_{90}$,$R_{180}$,$R_{270}$,H,V,$D_{1}$,$D_{2}$
For clarity (R= Rotation, H= flip horizontal axis V= Vertical D= Diagonal)
i have labeled each corner of my square as each entry of this matrix $$A=\begin{pmatrix} 1 & 2 \\ 4& 3\end{pmatrix}$$
$$R_{90}=\begin{pmatrix} 1 & 2& 3 & 4 \\ 2 & 3 & 4 & 1\end{pmatrix},$$
$$R_{180}=\begin{pmatrix} 1 & 2& 3 & 4 \\ 3 & 4 & 1 & 2\end{pmatrix},$$
$$R_{270}=\begin{pmatrix} 1 & 2& 3 & 4 \\ 4 &1 & 2 & 3\end{pmatrix},$$
$$H=\begin{pmatrix} 1 & 2& 3 & 4 \\ 4&3 & 3 & 1\end{pmatrix}$$
$$V=\begin{pmatrix} 1 & 2& 3 & 4 \\ 2& 1 & 4 & 3\end{pmatrix}$$
$$D_{1}=\begin{pmatrix} 1 & 2& 3 & 4 \\ 1& 4 & 3 & 2\end{pmatrix}$$
$$D_{2}=\begin{pmatrix} 1 & 2& 3 & 4 \\ 3& 2 & 1 & 4\end{pmatrix}$$
Now im fairly lost about $\mathbb Z_{8}$ because i think there will be elements in here without inverse's. Preferably id like to understand what this means exactly? as well as how i should be making it look.
Next is $U_{24}$
$$\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|} \hline a & x & 1 & 3 & 5 & 7 & 9&11&13&15&17&19&21&23 \\ \hline 1 & 1\cdot x & 1 & 3 & 5 & 7 & 9&11&13&15&17&19&21&23 \\ \hline 3 & 3\cdot x & 3 & 9 & 15 & 21&3&9&15&21&3&9&15&21 \\ \hline 5 & 5\cdot x & 5 & 15 & 1 & 11&21&7&17&3&13&23&9&19 \\ \hline 7 & 7\cdot x \\  \hline 9 & 9\cdot x \\ \hline
\hline 11 & 11\cdot x  \\ \hline
\hline 13 & 13\cdot x  \\ \hline
\hline 15 & 15\cdot x \\ \hline
\hline 17 &17\cdot x  \\ \hline
\hline 19 & 19\cdot x  \\ \hline
\hline 21 & 21\cdot x \\ \hline
\hline 23 & 23\cdot x \\ \hline \end{array}$$
i got this far and decided this was way too much work and its not what im supposed to be doing, clearly there is no isomorphism between the symmetries of a square and $U_{24}$  is there some easier way to prove this?
Edit
So there are a couple things that are pointed out below as incorrect, firstly this is way too much work. secondly gcd(12,3) = 3 not 1 so 3, 9, 12, 15 should not be in the table leaving only 8 elements.
As well as pointed out below $\mathbb Z_{8}$ is the integers on addition mod 8 not multiplication.

A: Easy way: show that an abelian group cannot be isomorphic to a nonabelian group.
Observe that $Z_8$ and $U(24)$ are abelian, and check that the dihedral group is nonabelian, which can be done in general by simply finding any two elements that do not commute.
Next, show that if a group is cyclic of even order, it has a unique element of order two.
Observe that $Z_8$ is cyclic of order $8$. Find two elements in $U(24)$ of order two, i.e. such that the equation $n^2\equiv1~(24)$ is satisfied but $n\ne1$. The solution $n=-1\equiv23$ is obvious, so you only need one more. So keep adding $24$ to $1$ until you hit a perfect square (it doesn't take long!).


Q: I need to delete an element in an array everytime a user press , but when is being output after deletion I got long number like ; 124352919 int main ()
{
    int a[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75};

    char ans;
    int i = 0;
    int pos = 0;

    cout<<"Press y to generate number"<<"\n";
    cin >> ans;

    while(ans=='y'||ans=='Y')
    {
        cout<<"\n\nEnter position to Delete number :: ";
        cin>>pos;

        --pos;

        for(i=pos;i<=size-1;i++)
        {
            a[i]=a[i+1];
            cout<<" "<<a[i]<<" ";
        }
        cout<<"\nNew Array is :: \n\n";

        for(i=0;i<size-1;i++)
        {

        }

        cout<<"Press y to generate number"<<"\n";
        cin >> ans;

    }

    cout << "\n\n";

//I need to delete an element in the array ,for example ; if I input position 67 ,it deletes position 67 but when the array is being after deletion , I got 1312123131 at the end

A: You can't delete an element from an array, but you can delete a vector element like this:
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> nums = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75 };

    char ans;
    int pos = 0;

    cout << "Press y to generate number: ";
    cin >> ans;

    while (ans == 'y' || ans == 'Y')
    {
        cout << "\n\nEnter position to Delete number: ";
        cin >> pos;

        --pos;

        nums.erase(nums.begin() + pos);
        cout << "\nNew Array is:\n\n";

        for (const auto& element : nums)
        {
            std::cout << element << '\n';
        }

        cout << "Press y to generate number" << "\n";
        cin >> ans;
    }
}


Q: Python MultiProcessing I'm using Python Python Multiprocessing for a RabbitMQ Consumers.
On Application Start I create 4 WorkerProcesses.
def start_workers(num=4):
    for i in xrange(num):
        process = WorkerProcess()
        process.start()

Below you find my WorkerClass.
The Logic works so far, I create 4 parallel Consumer Processes.
But the Problem is after a Process got killed. I want to create a new Process. The Problem  in the Logic below is that the new Process is created as child process from the old one and after a while the memory runs out of space.
Is there any possibility with Python Multiprocessing to start a new process and kill the old one correctly?
class WorkerProcess(multiprocessing.Process):

def ___init__(self):
    app.logger.info('%s: Starting new Thread!', self.name)
    super(multiprocessing.Process, self).__init__()

def shutdown(self):
    process = WorkerProcess()
    process.start()
    return True

def kill(self):
    start_workers(1)
    self.terminate()

def run(self):
    try:
        # Connect to RabbitMQ
        credentials = pika.PlainCredentials(app.config.get('RABBIT_USER'), app.config.get('RABBIT_PASS'))
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=app.config.get('RABBITMQ_SERVER'), port=5672, credentials=credentials))
        channel = connection.channel()

        # Declare the Queue
        channel.queue_declare(queue='screenshotlayer',
                              auto_delete=False,
                              durable=True)

        app.logger.info('%s: Start to consume from RabbitMQ.', self.name)
        channel.basic_qos(prefetch_count=1)
        channel.basic_consume(callback, queue='screenshotlayer')
        channel.start_consuming()
        app.logger.info('%s: Thread is going to sleep!', self.name)

        # do what channel.start_consuming() does but with stoppping signal
        #while self.stop_working.is_set():
        #    channel.transport.connection.process_data_events()

        channel.stop_consuming()
        connection.close()
    except Exception as e:
               self.shutdown()
    return 0

Thank You

A: In the main process, keep track of your subprocesses (in a list) and loop over them with .join(timeout=50) (https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.join).
Then check is he is alive (https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.is_alive).
If he is not, replace him with a fresh one.
def start_workers(n):
    wks = []
    for _ in range(n):
        wks.append(WorkerProcess())
        wks[-1].start()
    while True:
        #Remove all terminated process
        wks = [p for p in wks if p.is_alive()]

        #Start new process
        for i in range(n-len(wks)):
            wks.append(WorkerProcess())
            wks[-1].start()

A: I would not handle the process pool management myself. Instead, I would use the ProcessPoolExecutor from the concurrent.future module.
No need to inherit the WorkerProcess to inherit the Process class. Just write your actual code in the class and then submit it to a process pool executor. The executor would have a pool of processes always ready to execute your tasks.
This way you can keep things simple and less headache for you.
You can read more about in my blog post here: http://masnun.com/2016/03/29/python-a-quick-introduction-to-the-concurrent-futures-module.html
Example Code:
from concurrent.futures import ProcessPoolExecutor
from time import sleep

def return_after_5_secs(message):
    sleep(5)
    return message

pool = ProcessPoolExecutor(3)

future = pool.submit(return_after_5_secs, ("hello"))
print(future.done())
sleep(5)
print(future.done())
print("Result: " + future.result())


Q: OutputDebugString error I use:
OutputDebugString(L"My error");

in Visual Studio 2010, but instead of displaying "My error", I get just an "ERROR" in the window.

How do I fix this issue?

A: Since you're explicitly passing an UNICODE string, I'd suggest you also explicitly call OutputDebugStringW().
Otherwise, if the UNICODE preprocessor symbol is not defined in your compilation unit, the ANSI version of the function (OutputDebugStringA()) would end up being called with an UNICODE string, which it does not support, and it should result in a compilation error.
EDIT: You cannot use OutputDebugString() to write a string in your application's status bar. OutputDebugString() only sends the string you pass to the debugger.
You have to use the appropriate API to write text to the status bar instead. In your case, wxStatusBar::SetStatusText() should do the trick.


Q: Why does FPS go down if canvas is larger than 255x220? I've found a wierd phenomenon with HTML5 canvas. I was getting a lower than expected framerate, but only in Firefox, and only on one computer (but not on another I tested). The wierd thing is, if I reduce the canvas size to be 255x250 or less, Firefox performs similar to other browsers. If I add one more pixel in width, the FPS falls rapidly to a third.
I've made a jsPerf to demonstrate the problem: http://jsperf.com/critical-canvas-size
(Make sure that the grey rectangle is on screen. I let the tests fail if not, because I found it changes the results if you scroll away accidentally.)
All four test cases are pretty similar with most browsers on most systems, but on this one PC with Firefox 17, I see the following:

The PC in question is running an older Red Hat Linux, and I guess it probably doesn't have hardware accelleration support (from the OS side).
So, what could be the cause for this? Is there anything I can do in my code to circumvent the issue? (I've been thinking about using several small canvasses instead of one large one, for example.)

Edit:
Here is a standalone html file that exibits the problem, and one that doesn't. The only difference is the width of the canvas, 251 vs. 250. (You can comment out the spinner animation, it is just to make the problem visible. Also please excuse the accuracy of the FPS timer, its implementation is very simple.)
The 250px version gets about 60 FPS, in fact it seems to be capped. You can increase the numIterations variable to make the frame function draw a multiple amount of tiles. I can get up to numIterations = 100, or 120000 tiles/sec, while still having a decent framerate. However, the 251px version gives me even for numIterations = 1 a framerate below 20, or less than 1000 tiles/sec.

A: This makes sense because drawing to the canvas and clearing the canvas are expensive methods; if you have a smaller canvas and call clearRect on it every animation step then it will perform better than a larger canvas running the exact same code. The best thing to do is optimise your draw method to only clear what changed each frame. Once you do that you will notice a performance boost; this article will help with other areas in which you can increase performance.
I'm developing with canvas too and have found that WebKit based browsers, in general, handle canvas operations quicker than Gecko in most cases.

A: I actually see similar behavior.  I believe it is when you cross the 65776 pixel barrier -> not 65536 as you would expect.
I don't yet know why this is the case, but it is likely some kind of internal data structure or data type issue (possibly its using a hash and needs to grow the table at that point) inside your browser.  Your test is actually invalid on my chrome browser - it does not exhibit the same performance drop.
I wrote some test cases
http://jsperf.com/pixel-count-matters/2
and
http://jsperf.com/magic-canvas/2
Hope this helps!


Q: React Actions using RxJS for parallel async calls I am having an existing action that calls the api with list of IDs as querystring parameter and fetches the thumbnail response for the passed IDs. In some cases, count of IDs can be 150-200 records. Hence, I am working on making this APIs call batch based and run in parallel using forkJoin and subscribe methods of RxJs. I'm facing following 3 issues regarding the implementation.

*

*I am able to get the batch based response in next method of subscribe. However, the action invoked in this function along with response is not getting invoked.

*maxParallelQueries dont seems to be working as intended. All the fetchThumbnailObservables() are executed at once and not in the batches of 3 as set as constant/

*How to handle return of observable so that mergeMap do not give syntax error . Argument of type '({ payload }: IAction) => void' is not assignable to parameter of type '(value: IAction, index: number) => ObservableInput<any>'. Type 'void' is not assignable to type 'ObservableInput<any>'.ts(2345)
Here is my current code looks like. Any help would be great on this.
const getThumbnails: Epic<IAction, IAction, IStoreState> = (action$, state$) =>
    action$.ofType(ActionTypes.AssetActions.DATA.FETCH_THUMBNAILS).pipe(
        mergeMap( ({ payload }) => {

            const assetIds = Object.keys(payload);
            const meta = payload;

            const batchSize = 10;
            const maxParallelQueries = 3;

            const fetchThumbnailObservables : Observable<IThumbnailResponse>[] = [];

            for (let count = 0; count < assetIds.length; count += batchSize) {
                fetchThumbnailObservables.push(AssetDataService.fetchThumbnailData(assetIds.slice(count, count + batchSize)));
            }

             forkJoin(fetchThumbnailObservables)
            .pipe(mergeMap(fetchThumbnailObservable => fetchThumbnailObservable, maxParallelQueries)) // Issue 1 :  maxParallelQueries limit is not working
            .subscribe({
                complete: () => { },
                error: () => { },
                next: (response) => {
                     // Issue 2 :  below action dont seems to be getting invoked
                    actions.AssetActions.receivedThumbnailsAction(response, meta)
                },
             });

            // Issue 3 :  How to handle return of observable
            // Added below code for prevennting error raised by mergeMap( ({ payload }) => {
            return new Observable<any>();
        }),
        catchError((error) => of(actions.Common.errorOccured({ error })))
    );
    ```

A: I do not know Epics, but I think I can give you some hints about how to address this problem.
Let's start from the fact that you have an array of ids, assetIds, and you want to make an http call for each id with a controlled level of concurrency, maxParallelQueries.
In this case from function and mergeMap operator are yor friends.
What you need to do is
// from function transform an array of values, in this case, to a stream of values
from(assetIds).pipe(
  mergeMap(id => {
    // do whatever you need to do and eventually return an Observable
    return AssetDataService.fetchThumbnailData(id)
  }, maxParallelQueries) // the second parameter of mergeMap is the concurrency
)

In this way you should be able to invoke the http calls keeping the limit of concurrency you have established

A:

*

*I am able to get the batch based response in next method of subscribe. However, the action invoked in this function along with response is not getting invoked.

You mustn't call an action imperatively in redux-observable. Instead you need to queue them.
actions.AssetActions.receivedThumbnailsAction(response, meta) would return an plain object of the shape {type: "MY_ACTION", payload: ...} instead of dispatching an action. You rather want to return that object wrapped inside an observable inside mergeMap in order to add the next action to the queue. (see solution below)

*maxParallelQueries dont seems to be working as intended. All the fetchThumbnailObservables() are executed at once and not in the batches of 3 as set as constant/

First guess: What is the return type of AssetDataService.fetchThumbnailData(assetIds.slice(count, count + batchSize))? If it is of type Promise then maxParallelQueries has no effect because promises are eager and start immediately when created thus before mergeMap has the chance to control the request. So make sure that fetchThumbnailData returns an observable. Use defer rather than from if you need to convert a Promise to an Observable to make sure that a promise is not being fired prematurely inside fetchThumbnailData.
Second guess: forkJoin is firing all the request so mergeMap doesn't even have the chance to restrict the number of parallel queries. I'm surprised that typescript doesn't warn you here about the incorrect return type in mergeMap(fetchThumbnailObservable => fetchThumbnailObservable, ...). My solution below replaces forJoin with from and should enable your maxParallelQueries.

*How to handle return of observable so that mergeMap do not give syntax error . Argument of type '({ payload }: IAction) => void' is not assignable to parameter of type '(value: IAction, index: number) => ObservableInput'. Type 'void' is not assignable to type 'ObservableInput'.ts(2345)

This is not a syntax error. In an epic you have either the option to return an empty observable return empty() if no subsequent actions are intended or dispatch another action by returning an observable of type IAction. Here my (untested) attempt to meet your requirements:
const getThumbnails: Epic<IAction, IAction, IStoreState> = (action$, state$) =>
  action$.ofType(ActionTypes.AssetActions.DATA.FETCH_THUMBNAILS).pipe(
    mergeMap( ({ payload }) => {

      const assetIds = Object.keys(payload);
      const meta = payload;

      const batchSize = 10;
      const maxParallelQueries = 3;

      const fetchThumbnailObservables : Observable<IThumbnailResponse>[] = [];

      for (let count = 0; count < assetIds.length; count += batchSize) {
        fetchThumbnailObservables.push(
          AssetDataService.fetchThumbnailData(
             assetIds.slice(count, count + batchSize)
          )
        );
      }

      return from(fetchThumbnailObservables)
        .pipe(
          mergeMap(
            fetchThumbnailObservable => fetchThumbnailObservable,
            maxParallelQueries
          ),
          map((response) =>
            // dispatch action for each response
            actions.AssetActions.receivedThumbnailsAction(response, meta)
          ),
          // catch error early so epic continue on error
          catchError((error) => of(actions.Common.errorOccured({ error })))
        );
    })
  );

Please notice that I moved catchError closer to the request (inside the inner forkJoin Observable) so that the epic does not get terminated when an error occurs. Error Handling - redux observable This is so because when catchError is active it replaces the failed observable with the one that is returned by catchError. And I assume you don't want to replace the whole epic in case of an error?
And one thing: redux-observable handles the subscriptions for you so won't need to call .subscribe or .unsubscribe anywhere in your application. You just need to care a about the lifecycle of observables. Most important to know here is when does an observable start, what happens to it when it completes, when does it complete or what happens when an observable throws.


Q: Stream compaction and transform based on the index in CUDA I have an array of float that I would like to perform a stram compaction operation on, like what is presented here: Parallel Prefix Sum (Scan) with CUDA, and then apply a transform based on the value and the address or the original element.
For example, I have an array with the values {10,-1, -10, 2}, and I want to return all the elements with an absolute value greater than 5, and apply a transform taking the value and its address in the array.
The result here would be {transform(10,0),transform(-10,2)}.
I'm trying to use thrust with this, but this code will run often on large arrays, so ideally it wouldn't use buffers and multiple traversals of the array.
Is it possible to do what I'd like to do without allocating a secondary array and doing multiple traversals? If yes, does such code exist in the wild? Or at least does anybody have any pointers to which functions of thrust or any other library I could compose to reach my goal?

A: Yes, it's possible in thrust with a single thrust algorithm call (I assume that is what you mean by "without ... doing multiple traversals") and without "allocating a secondary array".
One approach would be to pass the data array plus an index/"address" array (via thrust::counting_iterator, which avoids the allocation) to a thrust::transform_iterator which creates your "transform" operation (combined with an appropriate functor).
You would then pass the above transform iterator to an appropriate thrust stream compaction algorithm to select the values you want.
Here's a possible approach:
$ cat t1044.cu
#include <thrust/device_vector.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/copy.h>
#include <math.h>

#include <iostream>

__host__ __device__ int my_transform(int data, int idx){
  return (data - idx);  //put whatever transform you want here
}

struct my_transform_func : public thrust::unary_function<thrust::tuple<int, int>, int>
{

  __host__ __device__
  int operator()(thrust::tuple<int, int> &t){
    return my_transform(thrust::get<0>(t), thrust::get<1>(t));
    }
};

struct my_test_func
{
  __host__ __device__
  bool operator()(int data){
    return (abs(data) > 5);
    }
};

int main(){

  int data[] = {10,-1,-10,2};
  int dsize = sizeof(data)/sizeof(int);

  thrust::device_vector<int> d_data(data, data+dsize);
  thrust::device_vector<int> d_result(dsize);
  int rsize = thrust::copy_if(thrust::make_transform_iterator(thrust::make_zip_iterator(thrust::make_tuple(d_data.begin(), thrust::counting_iterator<int>(0))), my_transform_func()), thrust::make_transform_iterator(thrust::make_zip_iterator(thrust::make_tuple(d_data.end(), thrust::counting_iterator<int>(dsize))), my_transform_func()), d_data.begin(), d_result.begin(), my_test_func()) - d_result.begin();
  thrust::copy_n(d_result.begin(), rsize, std::ostream_iterator<int>(std::cout, ","));
  std::cout << std::endl;
  return 0;
}
$ nvcc -o t1044 t1044.cu
$ ./t1044
10,-12,
$

Some possible criticisms of this approach:

*

*It would appear to be loading the d_data elements twice (once for the transform operation, once for the stencil).  However, it's possible that the CUDA optimizing compiler would recognize the redundant load in the thread code that ultimately gets generated, and optimize it out.

*It would appear that we are performing the transform operation on every data element, whether we intend to save it or not in the result.  Once again, it's possible that the thrust copy_if implementation may actually defer the data loading operation until after the stencil decision is made.  If that were the case, its possible that the transform only gets done on an as-needed basis.  Even if it is done always, this may be an insignificant issue, since many thrust operations tend to be load/store or memory bandwidth bound, not compute bound.  However an interesting alternate approach could be to use the adaptation created by @m.s. here which creates a transform applied to the output iterator step, which would presumably limit the transform operation to only be performed on the data elements that are actually being saved in the result, although I have not inspected that closely either.

*As mentioned in the comment below, this approach does allocate temporary storage (thrust does so under the hood, as part of the copy_if operation) and of course I'm explicitly allocating O(n) storage for the result.  I suspect the thrust allocation (a single cudaMalloc) is probably also for O(n) storage.  While it may be possible to do all the things asked for (parallel prefix sum, stream compaction, data transformation) with absolutely no extra storage of any kind (so perhaps the request is for an in-place operation), I think that crafting an algorithm that way is likely to have significant negative performance implications, if it is doable at all (it's not clear to me a parallel prefix sum can be realized with absolutely no additional storage of any kind, let alone coupling that with a stream compaction i.e. data movement in parallel).  Since thrust frees all such temporary storage it uses, there can't be much of a storage concern associated with frequent use of this method.  The only remaining concern (I guess) is performance. If the performance is a concern, then the time overhead associated with the temporary allocations should be mostly eliminated by coupling the above algorithm with a thrust custom allocator (also see here), which would allocate the maximum needed storage buffer once, then re-use that buffer each time the above algorithm is used.


Q: block command line not found I am trying to follow this answer on OS X 11.x
block return from any to 192.0.2.2

The console displays :

-bash: block: command not found

So, I tried to install it using brew:
brew install block

However, I got another error .

*

*How to install this firewall utility?

A: On recent versions of OS X, pf is installed and running by default.  The linked question is referring to changing the pf configuration, not installing a new utility.  Modifying a firewall on a production system is not something which should be done without reading the documentation (man pf.conf , man pfctl).
To add that block line (or experiment with other configuration changes), you would add it to the configuration file /etc/pf.conf with your preferred editor, and then reload the firewall configuration with
$ sudo pfctl -f /etc/pf.conf


Q: MongoDB and Spring Data performance Issue I am using MongoDB with Spring Data for creating our prototype application. The save operation is very fast but for listing the results the performance is very poor even when their are just 3 to 4 records persisted. Another amazing part is the the performance deteriorates with each consecutive list operation.
Just to give an idea here is the single json which is not the largest in the world.
    {
    "enquiryId": "574feac25215eae3e2e1434b",
    "enquiryName": "Mineral Shipment",
    "dateOfEnquiry": null,
    "requiredFrom": 1465324200000,
    "requiredTo": 1483036200000,
    "source": {
      "locationId": null,
      "area": {
        "pincode": null,
        "area": null,
        "city": {
          "cityId": null,
          "cityName": "Panjim",
          "state": {
            "stateId": null,
            "stateName": " Goa 403001",
            "country": {
              "countryId": null,
              "countryName": " India"
            }
          }
        }
      }
    },
    "destination": {
      "locationId": null,
      "area": {
        "pincode": null,
        "area": null,
        "city": {
          "cityId": null,
          "cityName": "Ludhiana",
          "state": {
            "stateId": null,
            "stateName": " Punjab 141001",
            "country": {
              "countryId": null,
              "countryName": " India"
            }
          }
        }
      }
    },
    "shipment": {
      "shipmentId": null,
      "enquiryId": null,
      "shipmentName": "Mineral Shipment",
      "valueOfGoods": null,
      "categories": [
        {
          "categoryId": null,
          "categoryName": "Hazardous,Flammable",
          "subCategories": null,
          "shipmentId": null
        }
      ],
      "modes": [
        {
          "modeId": null,
          "modeName": "WATER",
          "modeDescription": null,
          "shipmentId": null
        }
      ],
      "items": [
        {
          "itemId": null,
          "itemName": "Coal",
          "shape": null,
          "form": null,
          "dimension": null,
          "weight": null,
          "quantity": null,
          "shipmentId": null
        },
        {
          "itemId": null,
          "itemName": "Nickel",
          "shape": null,
          "form": null,
          "dimension": null,
          "weight": null,
          "quantity": null,
          "shipmentId": null
        }
      ]
    },
    "transportEnquiries": [
      {
        "transportEnquiryId": null,
        "transport": {
          "transportId": null,
          "name": "Flat Bed",
          "mode": {
            "modeId": null,
            "modeName": "WATER",
            "modeDescription": "The two world wars gave a great impetus to the development of air transport in almost all the countries of the world",
            "shipmentId": null
          },
          "type": {
            "typeId": null,
            "name": "LWH",
            "modeId": null,
            "illustrationURL": null
          },
          "desc": "Description of Flat Bed"
        }
      }
    ],
    "storageEnquiries": [],
    "packagingEnquiries": null,
    "insuranceEnquiries": null,
    "documentationEnquiry": null,
    "trackingToolRequired": null,
    "customerSupportRequired": null,
    "insuranceRequired": null,
    "storageRequired": null,
    "documentationRequired": null,
    "published": false,
    "userId": null
  }

And here is the Spring Service
    public class EnquiryManagementService implements IEnquiryManagementService{

    @Autowired
    private EnquiryRepository enquiryRepository;

    public Enquiry createEnquiry(Enquiry enquiry) {
        Enquiry enquiryObj = (Enquiry)enquiry;
        Enquiry e = enquiryRepository.save(enquiryObj);
        return e;
    }

    @Override
    public List<Enquiry> listEnquiry(int start) {
         long startTime = System.currentTimeMillis();
         Page<Enquiry> enquiries = enquiryRepository.findAll(new PageRequest(start,10));
         long endTime = System.currentTimeMillis();
         System.out.println("Time Taken = "+(endTime-startTime));
         return enquiries.getContent();
    }

}

Here are the results of the times taken in processing the findAll() 4 times consequtively without adding any more records. There are only 4 records in the system and you can see the time taken is 10.7 sec, 25.7 sec, 41.9 sec, and 58.5 sec. Each request takes a lifetime of its own to complete.

*

*Time Taken = 10768

*Time Taken = 25785

*Time Taken = 41921

*Time Taken = 58530

Given below is the configuration of my system
- Intel Core i3 2330M @2.2 GHz
- 2 GB RAM
- 64 bit Windows 7
- MongoDB version locally installed on my system : 3.2
- At the time of executing this query CPU utilization 50% and memory 80%
Ideally this operation must happen in less than half a second or at max a second. Any kind of help would be great.


Q: How to get data from website's dd tag via VBA I am trying to get data from a website, but I cannot get this part of my VBA code to work.
I have tried to look here, e.g. Excel VBA to find dd & dt tag but I could not find the answer.
This is the HTML code I am trying to get data from:

Folkbokföring

Gatuadress

Postnummer

Postort

Kommun

Län

Örebro (18)

Särskild adress

Gatuadress

Poste Restante

Postadress

701 00 Örebro

I am trying to retrieve the class="UpplysningTableSecondTd" data.
Neither of the below is working, and I have tried different things.
Set All_dd = oHDoc.getElementsByClassName("rapport__list m-b-25").getElementsByClassName("UpplysningTableSecondTd")(0).innerText
Set All_dd = oHDoc.getElementsById("show7").getElementsByTag("UpplysningTableSecondTd")

Thanks.

A: I managed to solve it.
Debug.Print oHDoc.getElementsByClassName("UpplysningTableSecondTd").Item(0).innerText
Debug.Print oHDoc.getElementsByClassName("UpplysningTableSecondTd").Item(1).innerText


Q: XSSFCell Style seems to be slow I'm currently using apache POI to automatically tranfers data from xls file to xlsm file after some process. I have strong executing time constraint and the setters on XSSFCellStyle is very time consuming.
In fact i have files with thousands of cell to transfert and method on boder (SetBorder & SetBorder color) take 3 ms to 5 ms to execution each on 1 cell. In my context 1300 thousands it takes 30 sec to execute.
In a graph on JProfiler, we can see the most time spend on these methods is in state "waiting".
Is it normal for you or not ?
Thanks a lot!!

A: in for example org.apache.poi.xssf.model.StylesTable.putStyle( XSSFCellStyle ) they try to find the xfs twice.
It uses an ArrayList.
The more cells, the slower this operation is.
If you can, try to avoid a lot of dates.


Q: Iterating through my fonts list to display them more efficiently Answer located here: Setting multiple different Typefaces to the TextViews in a ListView
I have 20 fonts in a list that changes a TextView based on the user's selection. I want to keep adding more custom fonts, but it's getting very tedious doing this manually for each addition. In the following use case, the user presses a button that opens a menu (not shown). I want to display these buttons in their respective fonts, by setting a typeface to each TextView in the menu:
Typeface Aclonica = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Aclonica.ttf");
TextView fontMenuAclonica = (TextView) this.view.findViewById(R.id.fontMenuAclonica);
fontMenuAclonica.setTypeface(Aclonica);

Typeface Arimo = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Arimo-Regular.ttf");
TextView fontMenuArimo = (TextView) this.view.findViewById(R.id.fontMenuArminoRegular);
fontMenuArimo.setTypeface(Arimo);

Is there a more efficient way to do this than by repeating this code over and over again? Can't I just have one base implementation of the code and list of values for the Typeface name, TextView name, and font name?
Typeface typefaceName = Typeface.createFromAsset(getActivity().getAssets(), "fonts/font.ttf");
TextView textViewName = (TextView) this.view.findViewById(R.id.resourceId);
textViewName.setTypeface(typefaceName);

Update: I suppose it's more efficient to set up a ListView:
    ListView fontsListView = (ListView) this.view.findViewById(R.id.MenuLayout);
    penis
    String[] fonts = new String[]{
            "Aclonica",
            "Amino-Regular"

    };
    ArrayList<String> planetList = new ArrayList<String>();
    planetList.addAll(Arrays.<String>asList(Arrays.toString(fonts)));
    for( int i = 0; i <= fonts.length - 1; i++) {
        planetList[i].setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/" + fonts[i] + ".ttf"));
    }

Here is the XML:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
android:id="@+id/rowTextView"
android:textSize="20sp"
android:gravity="center_horizontal"
android:padding="10dp"
android:typeface="sans"
android:fontFamily="sans-serif-light" />

How do I iterate through the TextViews that are created so that I can programmatically set their Typefaces?