text:
Q: Compare two similar Postgres databases for differences I occasionally download publicly available data sets in the form of Postgres dBs.   These datasets are updated/modified/expanded over time by the repository host.
Is there a Postgres command or tool (ideally FOSS) that can show the differences between an OLD and NEW Postgres database ?  (A working assumption is that 95% of the entries are unchanged and that the tables and relationships also do not change).

A: For schema comparisons, pgadmin4 has a Schema Diff feature (in beta as of 26 Jun 2020).  https://www.pgadmin.org/

A: There is also:

*

*PgDiff

*and the tool I'm working on Postgres Compare which is free while in beta

A: Have a look at the Stack Overflow Q & A, How to check difference between two databases in PostgreSQL?; in particular Another PostgreSQL Diff Tool (apgdiff) (schema comparison only). Apgdiff is recommended by Alexander Kuznetsov - a published database book author and bit of a guru.
Maybe also look at Liquibase or Compare Database Table Data.
There are also commercial products - e.g. Altova Database Differencing with DiffDog

A: If you need something fairly quick and dirty to compare schemas, I wrote this gist to help compare a running schema to a "latest" schema -- something maybe hosted in SCM. It's working fairly well for a ~50 tables project:
Assuming a database mydb, and a canonical database file defined in a file tables.sql, here is a way to tell if an operational schema differs from the canonical one:
pg_dump -U postgres -a mydb > mydbdata.sql
psql -U postgres -c "drop database mydbcanonical"
psql -U postgres -c "create database mydbcanonical"
psql -U postgres -d mydbcanonical -f tables.sql
psql -U postgres -d mydbcanonical -f mydbdata.sql

The gist is to see if the operational database's data will load cleanly into the canonical schema. These commands depend on the admin to visually parse the output of the last command where the data is loaded into the test database for errors. If there are no errors of concern, the schema is compliant.


text:
Q: Update a cloned project without removing it I am new in Ubuntu! I cloned a project from github in my (~\Desktop) Ubuntu directory. If the developer updated his project, how do I update the cloned one in my computer without having to remove it every time?
Thank you.

A: If you are not making your own local changes, this should work every time:
cd ~/Desktop/<project directory>
git pull

If you are making local changes, there is a little more to it.

If I were making local changes, but not contributing them back to the repo, then I would update my local version something like this:
(assuming I am working only on master branch)
first commit all your local changes.  This doesn't upload the to the repository.  You need to 'push' to do that.  It just saves them in a local commit.
git add -A
git -m"commit all my local changes before updating"

then download everything on origin (the remote version of the branch will be in origin/master while your local version is in master)
git fetch

I wouldn't use pull, since I'd want to keep all my local changes after the server changes in most cases.  I'd rebase like this:
# tag what you have in case anything goes wrong
git tag local-changes-number-1 #or whatever tag name

# replay your local changes overtop of the newer version and
# hope there are no conflicts
git rebase origin/master

and if anything goes wrong in the rebas git rebase --abort and come back to stackoverflow to find out how to resolve it

A: You're most likely looking for git pull.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The image contains cross-origin data I'm totally new to JS, but as I have ML background I wanted to explore ML5. I'm trying to do Image classification from https://github.com/CodingTrain/website/tree/master/Courses/beginner_ml5/02_image_classification
I'm getting below error when want to use prediction. I would be grateful for suggestions.
error

A: The error you have suggest that you are using an image that is served by a server different from the server that is rendering your frontend page. It is the CORS issue.
To solve it, your server needs to allow your frontend to retrieve images. It means that there should be in the header of the response serving your image the following entry
Access-Control-Allow-Origin: "*" ( not recommended because allowing everything)

or to be more specific
Access-Control-Allow-Origin: "url of your frontend" (ex: localhost:4200, website.com)

and in your image on the frontend, you need to set the attribute crossorigin="anonymous" in your img or canvas or video tag.
If the allow-origin fails to be in the server response, there is nothing one can do to process that image, because the error will be thrown no matter what. A similar question was considered here


text:
Q: Change format and data of datetime X-axis in a line chart with d3 Javascript library I have to create a Line chart using D3 and dimple library with JavaScript. The Y-axis represent the measure of a pyranometer (Example: 530) and the X-axis represent the instant of time of this measure (last 24hours). (Example: Tue Dec 31 17:40:00 CET 2013)
This chart is a dinamic chart. I take the data of a database and I refresh the chart every 5 minut.
I have this problem: There are so many data in the X-axis and i can't watch nothing in the x-axis. This is a picture of my chart:

I need to reorganize the data of X-axis. I only have to put a tick every 4 hour. The x-axis have to be like this:

So, I have to change the format of the X-axis and only put a tick every 4 hours of the last 24 hours. Moreover, I have to put the day below.
Do you have any idea of How could I do this?
This is the code of my chart:
var svg = dimple.newSvg("#container", 500, 500);
var myChart = new dimple.chart(svg, data2);
var x = myChart.addCategoryAxis("x", "time");
x.addOrderRule(Date);
var y1 = myChart.addMeasureAxis("y", "Piranometro");
var piranometro = myChart.addSeries("Piranom.", dimple.plot.line,[x,y1]);
myChart.draw();

Thanks in advance

A: Try using
myChart.addTimeAxis()

instead of
myChart.addCategoryAxis()

Here is an advanced time axis example (both x and y are time axis):
Advanced Time Axis Sample
Documentation on addTimeAxis():
Dimple  addTimeAxis() function
Related question:
Dimple Time Format Juggling
For displaying days below the hour axis, you can utilize second time axis.
Hope all this will help you find solution that fits your need.


text:
Q: Is unsigned long long fixed to an int(4 byte) range, if so, why is it 8 bytes in memory? Edit: Stupid question, I overlooked the format identifiers.
I had a program grab the size of a few unsigned types and their maximum value. This brought an anomaly to my attention, the fact that even thought unsigned long long is 8 bytes, it's range seems to be fixed to a 4 byte range. (char is a guaranteed 8-bit byte)
Question
I understand that unsigned long long is only defined by the standards to be at least large enough to hold an int (or rather >= long int >= int transitively). However, why is it using 8 bytes of memory instead of being the same size as int if it's limited to the range of 4 bytes too?
unsigned char:             255         1*sizeof(char)
unsigned short:            65535       2*sizeof(char)
unsigned short int:        65535       2*sizeof(char)
unsigned int:              4294967295  4*sizeof(char)
unsigned long int:         4294967295  4*sizeof(char)
unsigned long long int:    4294967295  8*sizeof(char)  //range[0..18446744073709551615]
unsigned long:             4294967295  4*sizeof(char)
unsigned long long:        4294967295  8*sizeof(char)  //range[0..18446744073709551615]

Here is the source I used:
#include <iostream>
#include <cstdio>

int main(void){

    std::cout << "Type sizes: (multiples of char)"<< std::endl << "char: " << sizeof(char) << std::endl <<\
    "short: " << sizeof() << std::endl <<\
    "short int: " << sizeof(short int) << std::endl << std::endl <<\
    "int: " << sizeof(int) << std::endl <<\
    "long int: " << sizeof(long int) << std::endl <<\
    "long long int: " << sizeof(long long int) << std::endl << std::endl <<\
    "long: " << sizeof(long) << std::endl <<\
    "long long: " << sizeof(long long) << std::endl << std::endl <<\
    "float: " << sizeof(float) << std::endl <<\
    "double: " << sizeof(double) << std::endl;

    unsigned char c = -1;
    unsigned short s1 = -1;
    unsigned short int s2 = -1;

    unsigned int i = -1;
    unsigned long int i1 = -1;
    unsigned long long int i2 = -1;

    unsigned long l = -1;
    unsigned long long l1 = -1;

    printf("\
            \nUnsigned Max:     \n\
            \nchar:             %u\
            \nshort:            %u\
            \nshort int:        %u\
            \nint:              %u\
            \nlong int:         %u\
            \nlong long int:    %u\
            \nlong:             %u\
            \nlong long:        %u\
            ", c, s1, s2, i, i1, i2, l, l1);

    return 0;
}

A: You're using the wrong flag for printf, the values are actually alright but printf isn't displaying them correctly. Try %llu for unsigned long long.
More info on printf (flags): http://www.cplusplus.com/reference/cstdio/printf/


text:
Q: Adding web facet to project without creating EAR I am trying to convert a java project to a dynamic web project programmatically by adding the required project facets.
Here is my code:
IProjectFacet JAVA_FACET    = ProjectFacetsManager.getProjectFacet("jst.java");
IProjectFacet WEB_FACET     = ProjectFacetsManager.getProjectFacet("jst.web");

iFacetedProject.installProjectFacet(JAVA_FACET.getVersion("5.0"), null, monitor);
iFacetedProject.installProjectFacet(WEB_FACET.getVersion("2.4"), null, monitor);

The facets get added correctly and the IDE recognizes the project as a web project.
The problem I am seeing is that adding the facets also creates an EAR project which I don't want.
Is there a way to suppress creating an EAR and just adding the facets to my project?

A: In order to avoid the creation of ear you can try this:
IProjectFacet JAVA_FACET = ProjectFacetsManager.getProjectFacet("jst.java");
IProjectFacet WEB_FACET = ProjectFacetsManager.getProjectFacet("jst.web");

iFacetedProject.installProjectFacet(JAVA_FACET.getVersion("5.0"), null, monitor);

IDataModel aFacetInstallDataModel = DataModelFactory.createDataModel(new WebFacetInstallDataModelProvider());
aFacetInstallDataModel.setBooleanProperty(IJ2EEModuleFacetInstallDataModelProperties.ADD_TO_EAR, false);

iFacetedProject.installProjectFacet(WEB_FACET.getVersion("2.4"), aFacetInstallDataModel, monitor);

In the same way, you are able to pass throw the same function a customize ear...


text:
Q: How to pass ManagedObjectContext to TabBarViewControllers After reading quite a couple of questions in stackoverflow, I still can't find an answer at the moment.
I have trouble passing ManagedObjectContext from appdelegate to my tabbarcontroller view.
in my appdelegate.m  I have this
#import "memoView.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    memoView *mView = (memoView *)navigationController.topViewController;
    mView.ObjectContext =[self managedObjectContext];
}

in memoView.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"NoteLog" inManagedObjectContext:[self ObjectContext]];
    [fetchRequest setEntity:entity];
    NSError *error;
    self.memoInfo = [ObjectContext executeFetchRequest:fetchRequest error:&error];
    //self.title = @"Memo";
    [fetchRequest release];

}

error reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'NoteLog''
I'm not sure what I have done wrong, I'm relative new to core data.
Any comments are appreciated.

A: I ran into this at one point and solved like this:
YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
self. ObjectContext = appDelegate.ManagedObjectContect;

A: I'd personally implement a Singleton for my CoreData Stack. - But in a slightly safer manner like here.
The singleton pattern is basically an excuse for a "global variable". Although if implemented correctly and used wisely one of the most powerful patterns there are. Simply speaking, what it does is: It creates an object of a class IF it doesn't exist yet and stores it in a static variable of that object's class. And since a class variable's content is the same amongst all the instances of that class (obviously), the next time you try to allocate an instance of the class it checks whether it was allocated before, and if it was returns the old instance.
Thus, you can basically "allocate" from anywhere and however often you want and you'll always get the same object back.
People tend to then call that singleton class something along the lines of "DataManager" or similar.

A: Where do you put following code? I guess mView is nil when you assigning mView.ObjectContext:
#import "memoView.h"
memoView *mView = (memoView *)navigationController.topViewController;
mView.ObjectContext =[self managedObjectContext];


text:
Q: Maintain strokeWidth while scaling in fabric js Note: I have refereed SO question, but it is not useful for my case, because
1) I am trying to maintain previous border but as of now its recalculate border while scaling.
I have added below code to stop increasing border automatically while scaling the object. Now the issue is I have added a 5px border to object but when scaling the object then it is not maintaining the border which I added earlier.
canvas.on('object:scaling', (e) => {
  var o = e.target;
  if (!o.strokeWidthUnscaled && o.strokeWidth) {
    o.strokeWidthUnscaled = o.strokeWidth;
  }

  if (o.strokeWidthUnscaled) {
    o.strokeWidth = o.strokeWidthUnscaled / o.scaleX;
  }
});

Now what I want is to prevent increasing of border while scaling the object. Border should remain as it was earlier.
Here is snippet / Codepen

var canvas = new fabric.Canvas('canvas1');

$('.add_shape').click(function() {
  var cur_value = $(this).attr('data-rel');
  if (cur_value != '') {
    switch (cur_value) {
      case 'rectangle':
        var rect = new fabric.Rect({
          left: 50,
          top: 50,
          fill: '#aaa',
          width: 50,
          height: 50,
          opacity: 1,
          stroke: '#000',
          strokeWidth: 1
        });
        canvas.add(rect);
        canvas.setActiveObject(rect);
        break;
      case 'circle':
        var circle = new fabric.Circle({
          left: 50,
          top: 50,
          fill: '#aaa',
          radius: 50,
          opacity: 1,
          stroke: '#000',
          strokeWidth: 1
        });
        canvas.add(circle);
        canvas.setActiveObject(circle);
        break;
    }
  }
});

canvas.on('object:scaling', (e) => {
  var o = e.target;
  if (!o.strokeWidthUnscaled && o.strokeWidth) {
    o.strokeWidthUnscaled = o.strokeWidth;
  }
  if (o.strokeWidthUnscaled) {
    o.strokeWidth = o.strokeWidthUnscaled / o.scaleX;
  }
});

/* Control the border  */
$('#control_border').change(function() {
  var cur_value = parseInt($(this).val());
  var activeObj = canvas.getActiveObject();
  if (activeObj == undefined) {
    alert('Please select the Object');
    return false;
  }
  activeObj.set({
    strokeWidth: cur_value
  });
  canvas.renderAll();
});
button {
  max-resolution: 10px;
  height: 30px;
}

div {
  margin: 10px
}

  <button class="add_shape" data-rel="circle">Add Circle</button>

  <button class="add_shape" data-rel="rectangle">Add Rectangle</button>

  Border
  <input id="control_border" type="range" min="0" max="10" step="1" value="0" />

<canvas id="canvas1" width="600" height="300" style="border:1px solid #000000;"></canvas>

Steps
1) Add Rectangle
2) Apply the border (lets say 5)
3) Scale that object
Now you can see the applied border is gone. So how to resolve that?
Update
I have tried below option but its not working, basically i am trying to maintain strokeWidth/Border for objects like rectangle, circle, triangle, line, polygon
What i have tried so far:
//1st try
canvas.on('object:scaling', (e) => {
    var o = e.target;
    o.strokeWidth = o.strokeWidth / ((o.scaleX + o.scaleY) / 2);
    var activeObject = canvas.getActiveObject();
    activeObject.set('strokeWidth',o.strokeWidth);
});

//2nd try
canvas.on('object:scaling', (e) => {
    if (!o.strokeWidthUnscaled && o.strokeWidth) {
        o.strokeWidthUnscaled = o.strokeWidth;
    }
    if (o.strokeWidthUnscaled) {
        o.strokeWidth = o.strokeWidthUnscaled / o.scaleX;
    }
});

//3rd try
fabric.Object.prototype._renderStroke = function(ctx) {
    if (!this.stroke || this.strokeWidth === 0) {
        return;
    }
    if (this.shadow && !this.shadow.affectStroke) {
        this._removeShadow(ctx);
    }
    ctx.save();
    ctx.scale(1 / this.scaleX, 1 / this.scaleY);
    this._setLineDash(ctx, this.strokeDashArray, this._renderDashedStroke);
    this._applyPatternGradientTransform(ctx, this.stroke);
    ctx.stroke();
    ctx.restore();
};

Questions i have refereed:
https://github.com/kangax/fabric.js/issues/66
Unable to maintain thickness of strokeWidth while resizing in case of Groups in Fabricjs
Fabricjs How to scale object but keep the border (stroke) width fixed
Resize a fabricjs rect to maintain border size
https://github.com/kangax/fabric.js/issues/2012
But not able to found solution.

A: Set strokeWidth to strokeWidthUnscaled for first time then set @ at scalling, for caching make it false only when scalling after modified change it.
object.strokeWidth = object.strokeWidthUnscaled/((object.scaleX+object.scaleY)/2);

And for selecting new stroke width, do this
var newStrokeWidth = cur_value / ((activeObj.scaleX + activeObj.scaleY) / 2)
activeObj.set({
  strokeWidth: newStrokeWidth,
  strokeWidthUnscaled : cur_value
});

Example

var canvas = new fabric.Canvas('canvas1');
var globalStrokeWidth = 1;

$('.add_shape').click(function() {
  var cur_value = $(this).attr('data-rel');
  if (cur_value != '') {
    switch (cur_value) {
      case 'rectangle':
        var rect = new fabric.Rect({
          left: 50,
          top: 50,
          fill: '#aaa',
          width: 50,
          height: 50,
          opacity: 1,
          stroke: '#000',
          strokeWidth: globalStrokeWidth
        });
        canvas.add(rect);
        canvas.setActiveObject(rect);
        break;
      case 'circle':
        var circle = new fabric.Circle({
          left: 50,
          top: 50,
          fill: '#aaa',
          radius: 50,
          opacity: 1,
          stroke: '#000',
          strokeWidth: globalStrokeWidth
        });
        canvas.add(circle);
        canvas.setActiveObject(circle);
        break;
    }
  }
});

canvas.on('object:scaling', (e) => {
  var o = e.target;
  if (!o.strokeWidthUnscaled && o.strokeWidth) {
    o.strokeWidthUnscaled = o.strokeWidth;
  }
  if (o.strokeWidthUnscaled) {
    if(o.objectCaching) o.objectCaching = false;
    o.strokeWidth = o.strokeWidthUnscaled / ((o.scaleX + o.scaleY) / 2);
  }
});

canvas.on('object:modified', (e) => {
  var o = e.target;
  if(!o.objectCaching) o.objectCaching = true;
  canvas.renderAll();
});

/* Control the border  */
$('#control_border').change(function() {
  var cur_value = parseInt($(this).val());
  globalStrokeWidth = cur_value;
  var activeObj = canvas.getActiveObject();
  if (activeObj == undefined) {
    alert('Please select the Object');
    return false;
  }
  var newStrokeWidth = cur_value / ((activeObj.scaleX + activeObj.scaleY) / 2)
  activeObj.set({
    strokeWidth: newStrokeWidth,
    strokeWidthUnscaled : cur_value
  });
  activeObj.setCoords();
  canvas.renderAll();
});
button {
  max-resolution: 10px;
  height: 30px;
}

div {
  margin: 10px
}

  <button class="add_shape" data-rel="circle">Add Circle</button>

  <button class="add_shape" data-rel="rectangle">Add Rectangle</button>

  Border
  <input id="control_border" type="range" min="0" max="10" step="1" value="0" />

<canvas id="canvas1" width="600" height="300" style="border:1px solid #000000;"></canvas>

A: While working on this issue, I've noticed that after resizing an object value of width and height doesn't change, it only changes scaleX and scaleY.
To maintain the stroke width, you need to reset scaleX and scalyY to 1 and also update width and height with new values.

For rectangle:

var currObj = canvas.getActiveObject();
if (currObj.type === 'rect') {
  var newWidth = currObj.width * currObj.scaleX,
      newHeight = currObj.height * currObj.scaleY;

    currObj.set({
      'width': newWidth,
      'height': newHeight,
      scaleX: 1,
      scaleY: 1
    });
}

For Ellipse:

var currObj = canvas.getActiveObject();
if (currObj.type === 'ellipse') {
  var newRX = currObj.rx * currObj.scaleX,
      newRY = currObj.ry * currObj.scaleY;

  currObj.set({
    'rx': newRX,
    'ry': newRY,
    scaleX: 1,
    scaleY: 1
    });
}

Don't forget to call canvas.renderAll() later;

http://jsfiddle.net/eLoamgrq/5/

A: This has become much easier as of Fabric.js version 2.7.0. There is now a strokeUniform property that when enabled, prevents the stroke width from being affected by the object's scale values.
obj.set('strokeUniform', true);

https://github.com/fabricjs/fabric.js/pull/5546

var canvas = new fabric.Canvas('canvas1');

$('.add_shape').click(function() {
  var cur_value = $(this).attr('data-rel');
  if (cur_value != '') {
    switch (cur_value) {
      case 'rectangle':
        var rect = new fabric.Rect({
          left: 50,
          top: 50,
          fill: '#aaa',
          width: 50,
          height: 50,
          opacity: 1,
          stroke: '#000',
          strokeWidth: 1,
          noScaleCache: false,
          strokeUniform: true,
        });
        canvas.add(rect);
        canvas.setActiveObject(rect);
        break;
      case 'circle':
        var circle = new fabric.Circle({
          left: 50,
          top: 50,
          fill: '#aaa',
          radius: 50,
          opacity: 1,
          stroke: '#000',
          strokeWidth: 1,
          noScaleCache: false,
          strokeUniform: true
        });
        canvas.add(circle);
        canvas.setActiveObject(circle);
        break;
    }
  }
});

/* Control the border  */
$('#control_border').change(function() {
  var cur_value = parseInt($(this).val());
  var activeObj = canvas.getActiveObject();
  if (activeObj == undefined) {
    alert('Please select the Object');
    return false;
  }
  activeObj.set({
    strokeWidth: cur_value
  });
  canvas.renderAll();
});
button {
  max-resolution: 10px;
  height: 30px;
}

div {
  margin: 10px
}

  <button class="add_shape" data-rel="circle">Add Circle</button>
  <button class="add_shape" data-rel="rectangle">Add Rectangle</button>
  Border
  <input id="control_border" type="range" min="0" max="10" step="1" value="0" />

<canvas id="canvas1" width="600" height="300" style="border:1px solid #000000;"></canvas>

A: In object:scaling, I commented out the calculation based on scale. Since the unscaled was = 1 and it was divided by scaling it always resulted in the border equaling a fraction (rather than staying put).

var canvas = new fabric.Canvas('canvas1');

$('.add_shape').click(function() {
  var cur_value = $(this).attr('data-rel');
  if (cur_value != '') {
    switch (cur_value) {
      case 'rectangle':
        var rect = new fabric.Rect({
          left: 50,
          top: 50,
          fill: '#aaa',
          width: 50,
          height: 50,
          opacity: 1,
          stroke: '#000',
          strokeWidth: 1
        });
        canvas.add(rect);
        canvas.setActiveObject(rect);
        break;
      case 'circle':
        var circle = new fabric.Circle({
          left: 50,
          top: 50,
          fill: '#aaa',
          radius: 50,
          opacity: 1,
          stroke: '#000',
          strokeWidth: 1
        });
        canvas.add(circle);
        canvas.setActiveObject(circle);
        break;
    }
  }
});

canvas.on('object:scaling', (e) => {
  var o = e.target;
  if (!o.strokeWidthUnscaled && o.strokeWidth) {
    o.strokeWidthUnscaled = o.strokeWidth;
  }
  if (o.strokeWidthUnscaled) {
    //o.strokeWidth = o.strokeWidthUnscaled / o.scaleX;
  }
});

/* Control the border  */
$('#control_border').change(function() {
  var cur_value = parseInt($(this).val());
  var activeObj = canvas.getActiveObject();
  if (activeObj == undefined) {
    alert('Please select the Object');
    return false;
  }
  activeObj.set({
    strokeWidth: cur_value
  });
  canvas.renderAll();
});
button {
  max-resolution: 10px;
  height: 30px;
}

div {
  margin: 10px
}

  <button class="add_shape" data-rel="circle">Add Circle</button>

  <button class="add_shape" data-rel="rectangle">Add Rectangle</button>

  Border
  <input id="control_border" type="range" min="0" max="10" step="1" value="0" />

<canvas id="canvas1" width="600" height="300" style="border:1px solid #000000;"></canvas>

A: If your object is inside a group, strokeUniform property does not work. In that case you can reduce the scaling of the inner object and update its width and height property on scaling. Example:
object.on('scaling', function() {

    object.item(0).set('scaleX', 1/object.scaleX);
    object.item(0).set('scaleY', 1/object.scaleY);
    var newobjwidth = Math.round(object.width * object.scaleX);
    var newobjheight = Math.round(object.height * object.scaleY);
    object.item(0).set('width', newobjwidth);
    object.item(0).set('height', newobjheight);
    object.item(0).setCoords();

}

If your object is blurry delete it and add it again after scaling.


text:
Q: R Propensity score matching with million row data I ran PMS (nearest) using MatchIt package with 2 million row data.
However, it took more than a day and was not stopped normally.
Is there any substitution methods that can handle PMS with large data?
Hopefully.. somebody knows.


text:
Q: XML field checkboxes with SQL I am trying to create list of article to choose from (multiple select checkbox), but so far I am not able to do so, or find a solution on net. So far I just have this:
 <field name="title" type="sql" default="10" label="Select an article" query="SELECT id AS value, title FROM #__content" ></field>

It is not much at all, but it is working. The problem is, that I am getting a list, where I can click on one article, and that is it. How can I create checkboxes from this?

A: Your custom.php file in regards to the link I provided in the comments could look something like this:
<?php

defined('_JEXEC') or die('Restricted access');

class JFormFieldCustom extends JFormField {

    protected $type = 'Custom';

    protected function getInput() {

        $db = JFactory::getDbo();

        $query = $db->getQuery(true);
        $query->select($db->quoteName('*'));
         ->from($db->quoteName('#__content'));
        $db->setQuery($query);
        $rows = $db->loadObjectList();
        $result = array();

        foreach ($rows as $row) {
            $result['id'] = $row->id;
        }

        return $result;
    }

}
?>

Please bare in mind that this was a quick mockup and I haven't tested it so let me know if it works and I can make any adjustments if need be after :)

A: You must create your own field or you can use this I created.
https://github.com/3ehrang/joomlaFields


text:
Q: What's the best strategy to monitor S3 bucket for missing a new file in the last x hours? I have a use case where some process puts a file every 6 hours to an S3 bucket. This bucket has already thousands of files in it and I wanted to generate an sns alert or something if no new file is added in the last 7 hours.  what would be a reasonable approach?
Thanks

A: There are a few potential approaches:

*

*Check the bucket every few minuter

*Keep track of the last new file

*Use an Amazon CloudWatch Alarm

Check the bucket every few minutes
Configure Amazon CloudWatch Events to trigger an AWS Lambda function every few minutes (depending upon how quickly you want it reported), which obtains a listing of the bucket and check the timestamp that the last object was added. If it is more than 7 hours, send the alert.
This approach is very simple but is doing a lot of work every few minutes, including during the 7 hours after an object was added. Plus, if you have lots of objects, this can consume a lot of Lambda time and API calls.
Keep track of the last new file

*

*Configure an Event on the Amazon S3 bucket to trigger an AWS Lambda function whenever a new file is added to the bucket. Store the current time in a DynamoDB table (or, if you really want to save costs, store it in the Systems Manager Parameter Store or an S3 object in another bucket). This will update the date whenever a new file is added.

*Configure Amazon CloudWatch Events to trigger an AWS Lambda function every few minutes (depending upon how quickly you want it reported) that checks the "last updated date" in DynamoDB (or where ever it was stored). If it is more than 7 hours, trigger an alert.

While this approach has more components, it is actually a simpler solution because it never has to look through the list of objects in S3. Instead, it just remembers when the last object was added.
You could come up with an even smarter method that, instead of checking every few minutes, schedules an alert function in 7 hours time. Whenever a new file is added, it changes the schedule to put it 7 hours away again. It's like constantly delaying a dentist appointment. :)
Use an Amazon CloudWatch Alarm
This is a simpler method that uses a CloudWatch Alarm to trigger the notification.

*

*Configure the S3 bucket to trigger a Lambda function whenever an object is added. The Lambda function sends a Custom Metric to Amazon CloudWatch.

*Create a CloudWatch Alarm to trigger a notification whenever the SUM of the Custom Metric is zero for the past 6 hours. Also configure it to trigger if the Alarm enters the INSUFFICIENT_DATA state, so that it correctly triggers when no data is sent (which is more likely than a metric of zero since the Lambda function won't send data when no objects are created).

The only downside is that the alarm period only has a few options. It can be set for 6 hours, but I don't think it can be set for 7 hours.
How to alert
As to how to alert somebody, sending a message to an Amazon SNS topic is a good idea. People could subscribe via Email, SMS and various other methods.

A: The Amazon CloudWatch Alarm method described by @John Rotenstein is definitely the simplest option for most use cases and works well. Just one thing to be aware of: CloudWatch Alarms has a 24hr limit per metric (EvaluationPeriods * Period must be <= 86400s). Therefore, if you expect your bucket to receive files less than once per day then you'll need to use a different method.


text:
Q: Installing xgboost==0.6a2 on Mac Mojave I have tried all possible solution I can find on web to install  xgboost==0.6a2
I have MacOS Mojave 10.14.4
I am trying in virtualenv having python 3.6
Here is result of pip command
pip install xgboost==0.6a2
Collecting xgboost==0.6a2
  Using cached https://files.pythonhosted.org/packages/34/85/456a1a8c762f646671043e446a59efbce02b5f408f522c4ef8793e860c5e/xgboost-0.6a2.tar.gz
    ERROR: Complete output from command python setup.py egg_info:
    ERROR: rm -f -rf build build_plugin lib bin *~ */*~ */*/*~ */*/*/*~ */*.o */*/*.o */*/*/*.o xgboost
    clang-omp++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/learner.o src/learner.cc >build/learner.d
    /bin/sh: clang-omp++: command not found
    make: *** [build/learner.o] Error 127
    make: *** Waiting for unfinished jobs....
    clang-omp++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/logging.o src/logging.cc >build/logging.d
    /bin/sh: clang-omp++: command not found
    make: *** [build/logging.o] Error 127
    -----------------------------
    Building multi-thread xgboost failed
    Start to build single-thread xgboost
    rm -f -rf build build_plugin lib bin *~ */*~ */*/*~ */*/*/*~ */*.o */*/*.o */*/*/*.o xgboost
    clang-omp++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/learner.o src/learner.cc >build/learner.d
    /bin/sh: clang-omp++: command not found
    make: *** [build/learner.o] Error 127
    make: *** Waiting for unfinished jobs....
    clang-omp++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/logging.o src/logging.cc >build/logging.d
    /bin/sh: clang-omp++: command not found
    make: *** [build/logging.o] Error 127
    Successfully build single-thread xgboost
    If you want multi-threaded version
    See additional instructions in doc/build.md
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/8s/jbryfvkn68jg4d2p2mncgqqw0000gq/T/pip-install-bp2gsdf9/xgboost/setup.py", line 29, in <module>
        LIB_PATH = libpath['find_lib_path']()
      File "/private/var/folders/8s/jbryfvkn68jg4d2p2mncgqqw0000gq/T/pip-install-bp2gsdf9/xgboost/xgboost/libpath.py", line 45, in find_lib_path
        'List of candidates:\n' + ('\n'.join(dll_path)))
    XGBoostLibraryNotFound: Cannot find XGBoost Libarary in the candicate path, did you install compilers and run build.sh in root path?
    List of candidates:
    /private/var/folders/8s/jbryfvkn68jg4d2p2mncgqqw0000gq/T/pip-install-bp2gsdf9/xgboost/xgboost/libxgboost.so
    /private/var/folders/8s/jbryfvkn68jg4d2p2mncgqqw0000gq/T/pip-install-bp2gsdf9/xgboost/xgboost/../../lib/libxgboost.so
    /private/var/folders/8s/jbryfvkn68jg4d2p2mncgqqw0000gq/T/pip-install-bp2gsdf9/xgboost/xgboost/./lib/libxgboost.so
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/8s/jbryfvkn68jg4d2p2mncgqqw0000gq/T/pip-install-bp2gsdf9/xgboost/

I downloaded xgboost and tried to install from source
python setup.py install
rm -f -rf build build_plugin lib bin *~ */*~ */*/*~ */*/*/*~ */*.o */*/*.o */*/*/*.o xgboost
clang-omp++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/learner.o src/learner.cc >build/learner.d
/bin/sh: clang-omp++: command not found
make: *** [build/learner.o] Error 127
make: *** Waiting for unfinished jobs....
clang-omp++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/logging.o src/logging.cc >build/logging.d
/bin/sh: clang-omp++: command not found
make: *** [build/logging.o] Error 127
-----------------------------
Building multi-thread xgboost failed
Start to build single-thread xgboost
rm -f -rf build build_plugin lib bin *~ */*~ */*/*~ */*/*/*~ */*.o */*/*.o */*/*/*.o xgboost
clang-omp++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/learner.o src/learner.cc >build/learner.d
/bin/sh: clang-omp++: command not found
make: *** [build/learner.o] Error 127
make: *** Waiting for unfinished jobs....
clang-omp++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/logging.o src/logging.cc >build/logging.d
/bin/sh: clang-omp++: command not found
make: *** [build/logging.o] Error 127
Successfully build single-thread xgboost
If you want multi-threaded version
See additional instructions in doc/build.md
Traceback (most recent call last):
  File "setup.py", line 29, in <module>
    LIB_PATH = libpath['find_lib_path']()
  File "xgboost/libpath.py", line 45, in find_lib_path
    'List of candidates:\n' + ('\n'.join(dll_path)))
XGBoostLibraryNotFound: Cannot find XGBoost Libarary in the candicate path, did you install compilers and run build.sh in root path?
List of candidates:
/Users/karim/Documents/software/xgboost-0.6a2/xgboost/libxgboost.so
/Users/karim/Documents/software/xgboost-0.6a2/xgboost/../../lib/libxgboost.so
/Users/karim/Documents/software/xgboost-0.6a2/xgboost/./lib/libxgboost.so

I also tried to install gcc5 by

brew install gcc@5

Which gives

Error: gcc@5 5.5.0_2 is already installed

When I type gcc -v it gives

Configured with: --prefix=/Library/Developer/CommandLineTools/usr
  --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1
  Apple LLVM version 10.0.1 (clang-1001.0.46.4) Target:
  x86_64-apple-darwin18.5.0 Thread model: posix InstalledDir:
  /Library/Developer/CommandLineTools/usr/bin

Are there any specific steps to be followed on Mac to configure it?
Any help highly appreciated.

A: I think having
ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/8s/jbryfvkn68jg4d2p2mncgqqw0000gq/T/pip-install-bp2gsdf9/xgboost/

mean that your setuptools are out of date. You can fix it by doing :
pip install --upgrade setuptools


text:
Q: Honeycomb like view with fragment and listview We are developing an app that in one point, we need a screen like Honeycomb Gmail application :
http://www.cnx-software.com/wp-content/uploads/2011/02/android_3.0_honeycomb_gmail_app_fragments_700px.png
We are trying to use fragments and includes a listview to show our items.
We did exactly the same thing on this link : http://www.vogella.com/articles/Android/article.html#fragments_tutorial
But in any way we did not able to view different layouts,
what i mean is that, the only thing that we can show on the right fragment a single textview.
but we need a listview there, that we can view a thumbnail,some explanations and this needs to be clickable.
anyone to help?

A: Should work.  I think you want to instantiate a ListFragment that, upon the user selecting a row, instantiates another ListFragment.

A: Maybe read this article aswell.
Below is an example for a layout xml file that has two fragments next to each other with an even width.
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >
    <fragment
        class="package.of.fragmentA"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:id="@+id/fragmentA"
        />
    <fragment
        class="package.of.fragmentB"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:id="@+id/fragmentB"
        />
</LinearLayout>

In the case of the GMail application the class fragmentA would be a ListFragment and fragmentB would be a normal fragment class with a custom layout file.


text:
Q: How do I make \dots more compact? Or are there alternatives? How would I go about making \dots more compact? I prefer the dots to be closer together to save horizontal space in long equations.
Alternatively, is there another inherently more compact macro than \dots? Would be preferable as regular \dots could still be used in other contexts.

A: Here it is another option: expanding ellipsis package to work also in math mode, apart from adding two more dimensions (\ellipsisbeforegap and \ellipsisaftergap, if set to zero it has the same behaviour as in ellipsis package).
\documentclass{scrartcl}

\usepackage{mathtools}
\usepackage{ellipsis}

\makeatletter
\renewcommand*{\mathellipsis}{%
  \mathinner{%
    \kern\ellipsisbeforegap%
    {\ldotp}\kern\ellipsisgap%
    {\ldotp}\kern\ellipsisgap%
    {\ldotp}\kern\ellipsisaftergap%
  }%
}
\renewcommand*{\dotsb@}{%
  \mathinner{%
    \kern\ellipsisbeforegap%
    {\cdotp}\kern\ellipsisgap%
    {\cdotp}\kern\ellipsisgap%
    {\cdotp}\kern\ellipsisaftergap%
  }%
}
\renewcommand*{\@cdots}{%
  \mathinner{%
    \kern\ellipsisbeforegap%
    {\cdotp}\kern\ellipsisgap%
    {\cdotp}\kern\ellipsisgap%
    {\cdotp}\kern\ellipsisaftergap%
  }%
}
\renewcommand*{\ellipsis@default}{%
  \ellipsis@before
  \kern\ellipsisbeforegap
  .\kern\ellipsisgap
  .\kern\ellipsisgap
  .\kern\ellipsisgap
  \ellipsis@after\relax}
\renewcommand*{\ellipsis@centered}{%
  \ellipsis@before
  \kern\ellipsisbeforegap
  .\kern\ellipsisgap
  .\kern\ellipsisgap
  .\kern\ellipsisaftergap
  \ellipsis@after\relax}
\AtBeginDocument{%
  \DeclareRobustCommand*{\dots}{%
    \ifmmode\@xp\mdots@\else\@xp\textellipsis\fi}}
\def\ellipsisgap{.1em}
\def\ellipsisbeforegap{.05em}
\def\ellipsisaftergap{.05em}
\makeatother

\begin{document}

a \dots\ b

a\dots b

\[ a + \dots + b \]

\end{document}

Also, this question of mine might be interesting in case you want to configure the spacing after the dots for diferent glyphs (e.g., !, ?, ,, ;, etc.).

A: Or with kerning:
% arara: pdflatex

\documentclass{article}
\newcommand*{\myDots}{\ifmmode\mathellipsis\else.\kern-0.13em.\kern-0.13em.\fi} % touching at \kern-0.1725em

\begin{document}
\myDots

\dots

$\myDots$

$\dots$
\end{document}

If you want to have different kerning for the math-version, you can just replace \mathellipsis by something else.
Update: for full control over math- and text-mode, you can use the following command: \newcommand{\myDots}{\ifmmode\mathinner{\ldotp\kern-0.2em\ldotp\kern-0.2em\ldotp}\else.\kern-0.13em.\kern-0.13em.\fi}

A second possibility (just for text-mode) would be the package ellipsis:
% arara: pdflatex

\documentclass{article}
\usepackage{ellipsis}
\renewcommand{\ellipsisgap}{0.01em}

\begin{document}
\dots $\dots$
\end{document}

A: How about this?
\documentclass{article}
\newcommand\mydots{\hbox to 1em{.\hss.\hss.}}
\begin{document}

Hello\dots

Hello again\mydots

\end{document}

Or if you prefer to keep it all "clean" LaTeX commands:
\newcommand\mydots{\makebox[1em][c]{.\hfil.\hfil.}}

A further consideration would be whether you care about maths mode or not.  The standard \dots command carefully checks whether we are in maths or not and does the right thing.   If you want to worry about this, then you would need this:
\newcommand\mydots{\ifmmode\ldots\else\makebox[1em][c]{.\hfil.\hfil.}\fi}

In order to change the spacing of the dots with this solution, you change the overall width of the ellipsis.  In the above examples I've made it 1em wide, and the the \hss or the \hfil commands expand as needed to make the dots evenly spaced.
If your ellipsis is ever followed by more text, then there is another consideration: whether you want any built-in space after the ellipsis (as pointed out in the comments).  The original \dots command has a small amount of space after it, but my suggested replacement above does not.  For example

To fix this you can either add a thin space after it by hand or amend the definition to:
\newcommand\mydots{\ifmmode\ldots\else\makebox[1em][c]{.\hfil.\hfil.}\thinspace\fi}


text:
Q: how to prevent normal-user from opening port In linux,since normal-user can open ports above 1024- does any one know how to prevent normal-user from opening any port on the system.

A: All the common security extensions for Linux like SELinux, grsecurity, AppArmor or Tomoyo enable you to forbid normal users to bind to any UDP or TCP socket or to specify which sockets they can bind to.

A: I don't think you can disallow users to bind to a port, but you can firewall them. Iptables has "owner" support, that might give you the options you need.


text:
Q: please prove that$E_3=\{\sum_{n=1}^{\infty}{({d_{n}\over 10^{n!}})}\mid d_{n}\in\{4,7\}\}$ contains no algebraic numbers I have a question from my professor:
Given
$$E_3=\left\{\sum_{n=1}^\infty \left({d_n\over 10^{n!}}\right) \mid d_n \in\{4,7\}\right\},$$
please prove $E_3$ is compact, perfect (hence uncountable) and nowhere-dense, and prove it contains no algebraic numbers.
I have proved that the set is compact, perfect and nowhere-dense, but still have no idea how to prove $E_{3}$ contains no algebraic numbers. Can someone tell me how to prove it? any hints?


text:
Q: Is there any way to vectorize a rolling cross-correlation in python based on my example? Let's suppose I have two arrays that represent pixels in pictures.
I want to build an array of tensordot products of pixels of a smaller picture with a bigger picture as it "scans" the latter. By "scanning" I mean iteration over rows and columns while creating overlays with the original picture.
For instance, a 2x2 picture can be overlaid on top of 3x3 in four different ways, so I want to produce a four-element array that contains tensordot products of matching pixels.
Tensordot is calculated by multiplying a[i,j] with b[i,j] element-wise and summing the terms.
Please examine this code:
import numpy as np

a = np.array([[0,1,2],
              [3,4,5],
              [6,7,8]])

b = np.array([[0,1],
              [2,3]])

shape_diff = (a.shape[0] - b.shape[0] + 1,
              a.shape[1] - b.shape[1] + 1)

def compute_pixel(x,y):
    sub_matrix = a[x : x + b.shape[0],
                   y : y + b.shape[1]]
    return np.tensordot(sub_matrix, b, axes=2)

def process():
    arr = np.zeros(shape_diff)
    for i in range(shape_diff[0]):
        for j in range(shape_diff[1]):
            arr[i,j]=compute_pixel(i,j)
    return arr

print(process())

Computing a single pixel is very easy, all I need is the starting location coordinates within a. From there I match the size of the b and do a tensordot product.
However, because I need to do this all over again for each x and y location as I'm iterating over rows and columns I've had to use a loop, which is of course suboptimal.
In the next piece of code I have tried to utilize a handy feature of tensordot, which also accepts tensors as arguments. In order words I can feed an array of arrays for different combinations of a, while keeping the b the same.
Although in order to create an array of said combination, I couldn't think of anything better than using another loop, which kind of sounds silly in this case.
def try_vector():
    tensor = np.zeros(shape_diff + b.shape)
    for i in range(shape_diff[0]):
        for j in range(shape_diff[1]):
            tensor[i,j]=a[i: i + b.shape[0],
                          j: j + b.shape[1]]

    return np.tensordot(tensor, b, axes=2)

print(try_vector())

Note: tensor size is the sum of two tuples, which in this case gives (2, 2, 2, 2)
Yet regardless, even if I produced such array, it would be prohibitively large in size to be of any practical use. For doing this for a 1000x1000 picture, could probably consume all the available memory.
So, is there any other ways to avoid loops in this problem?

A: In [111]: process()
Out[111]:
array([[19., 25.],
       [37., 43.]])

tensordot with 2 is the same as element multiply and sum:
In [116]: np.tensordot(a[0:2,0:2],b, axes=2)
Out[116]: array(19)
In [126]: (a[0:2,0:2]*b).sum()
Out[126]: 19

A lower-memory way of generating your tensor is:
In [121]: np.lib.stride_tricks.sliding_window_view(a,(2,2))
Out[121]:
array([[[[0, 1],
         [3, 4]],

        [[1, 2],
         [4, 5]]],

       [[[3, 4],
         [6, 7]],

        [[4, 5],
         [7, 8]]]])

We can do a broadcasted multiply, and sum on the last 2 axes:
In [129]: (Out[121]*b).sum((2,3))
Out[129]:
array([[19, 25],
       [37, 43]])


text:
Q: How do I know if a file has been closed if I open it using subprocess.Popen? I am opening files using the following commands in python :
file = os.path.normpath(file_path)
phandler = subprocess.Popen(['open', '-W', file])

I am polling
is_opened = phandler.poll() == None

to see if the process has been terminated. It is working if the process is terminated using cmd+Q. However, this is not working if I close the file using cmd+w. What is the foolproof way to make sure that the file is not open anymore.
PS. From phandler, I can also get the process Id using phandler.pid if needed.
If there is no other way to do this, I might have to use a library like watchdog, which is a wrapper over iNotify, but it will be preferable if I can achieve this using a library like psutils.

A: Is what you're looking for something like this:
from __future__ import print_function  # If in Python 2.x, import print function from Python 3.x

import os
import subprocess
import time

import psutil

def get_proc_status(pid):
    """Get the status of the process which has the specified process id."""

    proc_status = None
    try:
        proc_status = psutil.Process(pid).status()
    except psutil.NoSuchProcess as no_proc_exc:
        print(no_proc_exc)
    except psutil.ZombieProcess as zombie_proc_exc:
        # For Python 3.0+ in Linux (and MacOS?).
        print(zombie_proc_exc)
    return proc_status

def open_file(app, file_path):
    """Open the specified file with the specified app, and wait for the file to be closed. """

    my_file = os.path.normpath(file_path)
    # phandler = subprocess.Popen(['open', '-W', my_file])
    # Must be for Macs. Doesn't work in Windows or Linux.
    phandler = subprocess.Popen([app, my_file])
    pid = phandler.pid

    pstatus = get_proc_status(pid)
    while pstatus is not None and pstatus != "zombie":
        # The allowed set of statuses might differ on your system.
        print("subprocess %s, current process status: %s." % (pid, pstatus))
        time.sleep(1)  # Wait 1 second.
        pstatus = get_proc_status(pid)
        # Get process status to check in 'while' clause at start of next loop iteration.

    if os.name == 'posix' and pstatus == "zombie":   # Handle zombie processes in Linux (and MacOS?).
        print("subprocess %s, near-final process status: %s." % (pid, pstatus))
        phandler.communicate()

    pstatus = get_proc_status(pid)
    print("subprocess %s, final process status: %s.\n" % (pid, pstatus))

open_file(r"Evince\bin\Evince.exe", "fuzzed_file.pdf")
open_file(r"Evince\bin\Evince.exe", "unfuzzed_file.pdf")

According to Python: Non-Blocking + Non defunct process and how to kill (or avoid) zombie processes with subprocess module, it seems that the communicate() call is needed to handle "zombie" processes in Linux (and also, I think, in MacOS).
(See StackOverflow's Tag Info for zombie-process tag.)
This generates output such as:
subprocess 6844, current process status: running.
subprocess 6844, current process status: running.
subprocess 6844, current process status: running.
subprocess 6844, current process status: running.
psutil.NoSuchProcess no process found with pid 6844
psutil.NoSuchProcess no process found with pid 6844
subprocess 6844, final process status: None.

subprocess 5460, current process status: running.
subprocess 5460, current process status: running.
subprocess 5460, current process status: running.
subprocess 5460, current process status: running.
subprocess 5460, current process status: running.
subprocess 5460, current process status: running.
psutil.NoSuchProcess no process found with pid 5460
psutil.NoSuchProcess no process found with pid 5460
subprocess 5460, final process status: None.


text:
Q: iAd bottom UITableViewController not showing ads I have a UISplitViewController and I have the MasterViewController with a UITableViewController.
I want to add an iAd at the bottom of the view. I think I have achieved this, but there are no ad's showing.
self.adBannerView = [[ADBannerView alloc] initWithFrame:CGRectZero];
self.adBannerView.frame = CGRectMake(0, self.view.frame.size.height - 50, 320, 50);
[self.view addSubview:self.adBannerView];

//set proper bottom inset depending on your banner height
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 50, 0);

adBannerView.delegate = self;

I have implemented the delegate methods:
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
    if (!_bannerIsVisible)
    {
        // If banner isn't part of view hierarchy, add it
        if (adBannerView.superview == nil)
        {
            [self.view addSubview:adBannerView];
        }

        [UIView beginAnimations:@"animateAdBannerOn" context:NULL];

        // Assumes the banner view is just off the bottom of the screen.
        // banner.frame = CGRectOffset(banner.frame, 0, -banner.frame.size.height);

        [UIView commitAnimations];

        _bannerIsVisible = YES;
    }
}

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
    NSLog(@"Failed to retrieve ad MLEFT");
    NSLog(@"MLEFT Error :%@",error);
    if (_bannerIsVisible)
    {
        [UIView beginAnimations:@"animateAdBannerOff" context:NULL];

        // Assumes the banner view is placed at the bottom of the screen.
        // banner.frame = CGRectOffset(banner.frame, 0, banner.frame.size.height);

        [UIView commitAnimations];

        _bannerIsVisible = NO;
    }

}

But the ad is not showing. Also not after a few hours waiting. In another view, the ad is loaded.
What am I missing here?

A: *

*Make sure you have added iAd.framework in **Build Phases => Link Binary With Libraries.

*In case you are using storyboard, check if ADBannerView is not behind any other view. (I suggest try to put at 0,0 position in front of all views for testing)


text:
Q: Series of Legendre Polynomials and Harmonic numbers. $\sum_{n=1}^{\infty} P_n (z) \frac{H(n)}{n+k}$ I would like to compute sums of the type
\begin{equation}
\sum_{n=1}^{\infty} P_n (z) \frac{H(n)}{n+k}
\end{equation}
where $P_n(z)$ are Legendre polynomials, $H(n)$ are harmonic numbers and $k = 0, 1, 2, 3...$, a positive integer.
I've tried using the integral representation for $H(n)$ and then the generator function for legendre polynomials. Moreover, I tried using the integral representation for legendre polynomials, but it seems that nothing works...
Any suggestion?


text:
Q: Changing variable name in Spyder or Notepad++ I'm working with Spyder (for Python) and I'm looking for a way to change a variable name in the entire code. I know the replace-text-function, but this changes also text, where my variable name is only part of it. I know this function from Matlab, is there something like this in Spyder or alternatively in Notepad++?
So if I like to change the name of my variable "data", it should replace everything, where data is used (also expressions like data.append), but should not change things like "datanew", which is another variable

A: (Spyder maintainer here) The technical term for this kind of operation is refactoring, and I'm sorry to tell you but Spyder doesn't have support for it as of November/2017.

A: Not sure to well understand your needs, but I guess you want (using Notepad++):

*

*Ctrl+H

*Find what: \bdata\b

*Replace with: new_name

*check Match case

*check Wrap around

*check Regular expression

*Replace all
Explanation:
\b      : word boundary, make sure we don't have a word character before
data    : literally "data"
\b      : word boundary, make sure we don't have a word character after

Learn more on wordboundary
In order to keep "data", you could use negative lookaround:
(?<!["'])\bdata\b(?!["'])

A: You can replace it with following regex in Notepad++
(?:"(?:\\.|[^\"])*")\K|(?:\bdata\b)

but there ist one handicap - it gives a match for the emptystring behind every closing " too.
So you can use it in 3 steps

*

*replace (?:"(?:\\.|[^\"])*")\K|(?:\bdata\b) with a_string_you_dont_use

*replace "a_string_you_dont_use with "

*replace a_string_you_dont_use with your new variablename
tested with: regex101
Maybe someone can improve the regex so that you can do it in one step. The first part matches everyhing inside ""and drops the match with \K but it leaves an empty match. The second part matches the variable itself.
The regex takes care of " and \" but not of ' so if you use it you have to extend the regex.


text:
Q: "Service_References" namespace emerges for WCF references I have a project which references 5-7 of my own WCF services and I have encountered a very annoying problem.
When I update service references, sometimes they create additional namespace, but sometimes don't.
For example, I add reference to my SomeWcfService in my MyMvcProject.
It will automatically generate a namespace
MyMvcProject.SomeWcfService.SomeDataContract

After an hour of work, I need to update it. I click Update reference and Visual Studio creates an updated code...but in namespace
MyMvcProject.Service_Reference.SomeWcfService.SomeDataContract

You can imagine how annoying it is - all using statements break and I get 50+ compile errors which take a lot of time to be fixed. I have found a solution - update references again and again until it creates a necessary namespace, but it is not a solution.
Why does it happen? There should be a reason - it can't just be a random. And how to solve this?

A: I don't know what is causing it but a solution would be to drop all your service references and just call the services directly via the runtime generated proxy returned from ChannelFactory<T>.CreateChannel();
There is no reason I can think of to prefer the use of system generated service references over this method, especially as you say you own and control all the services anyway.
The code generation behind service references is complex and fickle and, while ultimately deterministic, is certainly unpredictable and adds another layer of stuff that can go wrong to your client application.


text:
Q: Paypal Website Payments Pro transaction not getting listed in the Sandbox account I have created a simple PHP App for requesting(nvp format) paypal to accept payment from my customers through on-site payment with credit-card, even though when I test it with dummy cards & I get success message in the response, the transaction is not getting listed in my sandbox account "Recent Activity" page or "View all transactions" or "Payments Received".
My Payment type is sale and I am calling "DoDirectPayment" method.
I have already enabled "Payment Pro" for my sandbox account & also the account is "Verified", still transaction entry not getting listed.
Can somebody guide me with a detailed explanation about the issue that might be causing this ?
I am using this as my reference.
https://github.com/GeorgeOld/Paypal-NVP-PHP-code-examples


text:
Q: Why passing &error instead of error in Cocoa programming? In Cocoa programming, when dealing with NSError, why we are passing &error to a message instead of error?
NSError *error;
if (![managedObject.managedObjectContext save:&error])
   //Code

A: When you call the method, you aren't giving it a pointer to an NSError, you're giving it a place to pass a pointer to an NSError back to you.
I often write
NSError *error = nil;

which makes it a bit more obvious that there nothing (interesting) in error when you call -save:.  It's just a place you've set aside for the address in memory of an NSError object.  If the method encounters an error, it creates an NSError object and writes the address of the object in error to pass it back to you.

A: NSError's fields are not settable. its interface is opaque and immutable. therefore, if you were to alloc/init an error, the client could not populate it. thus, the approach is to return a new error (if applicable), also saving you from allocs in every case.
since the return type is already specified by the method, and the error is optional, it makes sense to take this approach to returning the error in idiomatic c syntax.
iow, the client may neither mutate what you pass nor return the error using :(NSError *)outError, so the "out parameter" form :(NSError**)outError is applied.

A: The save method takes a pointer to a pointer.  There's a good explanation on Cocoa Tutorial: Using NSError to Great Effect

Passing Pointers to Pointers
Using the NSError class in the above
  example is quite simple. I just pass
  it in and if the call failed for
  whatever reason I have an NSError
  object to explain what the problem
  was. But how does the other side of
  that call work?
The first part of this is to
  understand the concept of passing a
  pointer to a pointer rather than a
  pointer to an object. Normally when a
  message is sent, a pointer to the
  object is being passed in the message.
  This is denoted with the single
  asterisk(*) in the method signature
  such as
-(void)appendString:(NSString*)newString
  This is different then passing a
  pointer to a pointer. First, that type
  of argument is denoted with two
  asterisk(**) such as:
-(BOOL)save:(NSError**)error Second, the other difference is this allows
  the receiving method to control what
  the pointer (that the pointer is
  pointing to) is referencing. This is
  arguably one of the more confusing
  parts of pointer programming but once
  you get it, it is a very powerful
  tool. To put it another way, by
  passing a pointer to the pointer, the
  receiving method can decide what your
  variable's value is. As you can see in
  my code above, I initialized the error
  variable to nil. However, if the save
  call fails, that variable will no
  longer be nil but will reference an
  actual NSError object which I can than
  interrogate.
If you wish to understand how this
  works, I would suggest the double
  indirection wikipedia article as a
  great starting point.

A: It's the address-of operator; it produces a pointer pointing to the referent. In this case, error is an NSError *,it takes an address to it and may modify error through that pointer to indicate the error that occurred.


text:
Q: How do I change background color of storyboard in xcode 4.6.2 I am working with storyboards in xcode 4.6.2 I simply want to change the background color of the storyboard. Usually I would think (and according to tutorials) I just go to the inspector on the right and there's a drop down to change the background color. However it's not showing up. Instead I see too areas, "simulated metrics" which shows drop down for size, orientation, status bar, top bar and bottom bar and "view controller" which shows title, initial scene check box layout check box which offers wants full screen, hides bottom bar and resize options and transition and presentation style check boxes.
Any one know why I don't see anything for changing background color etc.. am I missing something here? Any help would be greatly appreciated.

A: You are most probably clicking on the view controller which is showing those properties that can be adjusted in the view controller itself. This can be found out on the left of the storyboard or Interface Builder.

A view is not the same as view controller. A view controller manages a set of views, as mentioned in the View Controller Programming Guide for iOS.
Try to click on the view of the view controller and you should be able to modify the background color of the view:

A: Select the view under the view controller in the storyboard panel. Then go to the Attributes Inspector. Backgorund is about the 4th item down.


text:
Q: Properly Create and Serve PDF Blob via HTML5 File and URL APIs Ok, Let's say I have document data stored somewhere, let's arbitrarily take this pdf.
Issue #1.  What I want to do is make an AJAX call to this URL (because I need to pass some authentication headers and it is cross domain).  Then take the returned data, create a blob url for it, append an iFrame to the DOM, and direct the src to the blob url.
Currently my code looks like this:
$.ajax({
  url:'http://www.grida.no/climate/ipcc_tar/wg1/pdf/tar-01.pdf'
}).done(function(data){
   var file = new Blob([data], {type:'application/pdf'}),
       url = URL.createObjectURL(file),
       _iFrame = document.createElement('iframe');
      _iFrame.setAttribute('src', url);
      _iFrame.setAttribute('style', 'visibility:hidden;');
      $('#someDiv').append(_iFrame);
});

Unfortunately, I am getting a 'Failed to Render PDF' in the iFrame.
Issue #2.  I'd like this to result in a file download prompt.  Not sure how to guarantee this given that PDF's will naturally just display in the iFrame.

A: jQuery.ajax does not currently support blobs, see this bug report #7248 which is closed as wontfix.
However it's easy to do XHR for blobs without jQuery:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.grida.no/climate/ipcc_tar/wg1/pdf/tar-01.pdf', true);
xhr.responseType = 'blob';

xhr.onload = function(e) {
  if (this.status == 200) {
    // Note: .response instead of .responseText
    var blob = new Blob([this.response], {type: 'application/pdf'}),
        url = URL.createObjectURL(blob),
        _iFrame = document.createElement('iframe');

    _iFrame.setAttribute('src', url);
    _iFrame.setAttribute('style', 'visibility:hidden;');
    $('#someDiv').append(_iFrame)
  }
};

xhr.send();

Shamelessly copied from HTML5rocks.
If jQuery did support the Blob type, it could be as simple as:
$.ajax({
  url:'http://www.grida.no/climate/ipcc_tar/wg1/pdf/tar-01.pdf',
  dataType:'blob'
})...

A: I have used @Ciantic answer to adapt my answer. I have avoided using iframe obj and the user can download the file directly from the page.
var link = 'http://www.grida.no/climate/ipcc_tar/wg1/pdf/tar-01.pdf';
$("body").addClass("loading"); // adding the loading spinner class

var xhr = new XMLHttpRequest();
xhr.open('GET',link,true);
xhr.responseType = 'blob';

        xhr.onload = function(e){
                 if (this.status == 200) {
                    var a = document.createElement('a');
                    var url = window.URL.createObjectURL(new Blob([this.response], {type: 'application/pdf'}));
                    a.href = url;
                    a.download = 'report.pdf';
                    a.click();
                    window.URL.revokeObjectURL(url);
                    $('body').removeClass("loading"); //removing the loading spinner class
                  }else{
                      $('body').removeClass("loading") //removing the loading spinner class
                      console.log(this.status);
                      alert('Download failed...!  Please Try again!!!');
                  }
            };
            xhr.send();

A: var src_url = your url here;
var contentDisposition = 'AlwaysInline';
var src_new = src_url.replace(/(ContentDisposition=).*?(&)/, '$1' + contentDisposition + '$2');

By doing this you will be able to view pdf instead of downloading it,
Header ContentDisposition should be 'AlwaysInline' then only it displays your file instead of downloading it.


text:
Q: Reset Safari from command line I accidentally navigated to one of those sites that pops up a dialog telling me that my computer is infected. Upon clicking the OK button, that dialog reappears, ad infinitum.
I cannot close the tab or otherwise interact with Safari while the dialog is up. No matter how many times I Quit or Force Quit (and no matter how many times I tell Safari "Do Not Re-open Windows") the previously-open set of tabs always reopens and this dialog pops to the fore.
How can I delete the state of things while Safari is closed?

A: Disconnect your computer from the internet (disable wlan)
Then delete browser history (Safari/Preferences/Privacy: remove all website data)

A: I created a script, DeleteSafariTabs.command, and made it executable so I can just double-click the script.
This method leaves your history and bookmarks intact, and reliably deletes the previously open tabs.
# Most apple apps (if not all) have a file inside of
# ~/Saved Application State/ so by deleting that we
# get rid of the state of open windows Safari is using.
rm -rf ~/Library/Saved\ Application\ State/com.apple.Safari.savedState

# There is also some information about the previous
# session here so we delete this as well.
rm ~/Library/Safari/LastSession.plist

You can make the file executable by typing in chmod +x, pressing the space bar, and dragging in DeleteSafariTabs.command from Finder into the Terminal window.

A: From http://seanscus.blogspot.com/2012/08/completely-reset-safari.html
Open a terminal and enter the following commands to fully wipe out all of your old Safari settings:
mv ~/Library/Safari ~/Desktop/Safari-`date +%Y%m%d%H%M%S`; \
rm -Rf ~/Library/Caches/Apple\ -\ Safari\ -\ Safari\ Extensions\ Gallery; \
rm -Rf ~/Library/Caches/Metadata/Safari; \
rm -Rf ~/Library/Caches/com.apple.Safari; \
rm -Rf ~/Library/Caches/com.apple.WebKit.PluginProcess; \
rm -Rf ~/Library/Cookies/Cookies.binarycookies; \
rm -Rf ~/Library/Preferences/Apple\ -\ Safari\ -\ Safari\ Extensions\ Gallery; \
rm -Rf ~/Library/Preferences/com.apple.Safari.LSSharedFileList.plist; \
rm -Rf ~/Library/Preferences/com.apple.Safari.RSS.plist; \
rm -Rf ~/Library/Preferences/com.apple.Safari.plist; \
rm -Rf ~/Library/Preferences/com.apple.WebFoundation.plist; \
rm -Rf ~/Library/Preferences/com.apple.WebKit.PluginHost.plist; \
rm -Rf ~/Library/Preferences/com.apple.WebKit.PluginProcess.plist; \
rm -Rf ~/Library/PubSub/Database; \
rm -Rf ~/Library/Saved\ Application\ State/com.apple.Safari.savedState

A: Oh, my! Just press and hold Shift when launching Safari from the dock.
But you have got in answers above exactly what you have asked for)

A: Quit Safari>Click on GO in finder> go to Folder> ~/Library/> rename folder named Safari to Safari1.
Reopen Safari, it will start new and a new Safari Folder will be created in Library.
Bring back some files like Bookmark etc one at a time.

A: For those that are really looking for an easy answer, disconnect from local network (Wifi/ ethernet).  Open Safari and then force quit it to loose the cache.  Then restart safari (it'll try to connect to the suspicious phishing pages but has no cached version. Go to menu -> safari -> reset safari and hit okay on popup to delete all history/ cache/ cookies etc

A: @Iskra 's answer nails it, The below steps works even there's no Safari in the dock.
1 - Open terminal
2 - Issue killall Safari
3 - Go to the list of apps (Four fingers swipe-inwards)
4 - Shift + Click Safari

A: Safari stores its window state in /Users/USERNAME/Library/Saved Application State/com.apple.Safari.savedState. If you close Safari, then rename that folder, the next time you open Safari it'll open with a blank slate.
Alternatively, you could temporarily disable the saved state feature across the board by going into the General pane of System Preferences and ticking the "Close windows when quitting an appellation" checkbox. If you open Safari after doing that, it'll also open with a blank slate. Remember to untick it afterward if you want to turn the saved state feature back on.

A: To reset a highjacked Safari:

*

*Click Go

*select Go to folder

*type in: ~/Library/Cookies

*hit Go

*Send all the frenkin cookies to the
trash

*Close folder

*Launch Safari

*You are Welcome!!!

Pass it on

A: I just typed google website on a word sheet, clicked on the link then go to preferences and change the home page back.

A: I find it most useful to create a .bash_alias file and add it to your .bash_profile.
Add this alias to .bash_alias and any other useful command line scripts.
alias resetsafari='rm -rf ~/Library/Saved\ Application\ State/com.apple.Safari.savedState; rm ~/Library/Safari/LastSession.plist

You will need to source .bash_profile again to refresh the aliases.
In the event you forget your saved aliases, just type alias into Terminal to see all current aliases.(This is a modification of the code someone posted above, modified into an alias form.)


text:
Q: Remove Nth node from end of the list I was trying to understand from the following code why head is getting returned. I suppose it returns null. Could someone explain me about it ?
public ListNode removeNthFromEnd(ListNode head, int n) {
    if(head == null)
        return null;

    ListNode fast = head;
    ListNode slow = head;

    for(int i=0; i<n; i++){
        fast = fast.next;
    }

    //if remove the first node
    if(fast == null){
        head = head.next;
        return head;
    }

    while(fast.next != null){
        fast = fast.next;
        slow = slow.next;
    }

    slow.next = slow.next.next;

    return head;
}

A: I think there is a better way of removing the nth element from the end of the list. You can use a stack. Put the elements in the stack till you reach the end. Then, start popping till the nth element from the end. Then, the next of the popped element (nth) is the next. Also, the previous of the nth element in the stack peek. All you need to do it to set the next of prev as the next. You need to consider removing the head and tail of the list as edge cases. Also, you need to consider the empty list. I hope it helps.
import java.util.Stack;

public class RemoveNthNodeFromLL {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || (head.next == null)) return null;
        Stack<ListNode> s = new Stack<>();
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            prev = curr;
            s.push(prev);
            curr = curr.next;
        }
        for (int i = 1; i <= n - 1; i++) {
            s.pop();
        }
        ListNode toBeRemoved = s.pop();
        ListNode next = toBeRemoved.next;
        if (s.isEmpty()) {
            // Removing the head
            head = head.next;
        } else {
            prev = s.peek();
            prev.next = next;
        }
        return head;
    }

    public static void main(String[] args) {
        RemoveNthNodeFromLL r = new RemoveNthNodeFromLL();
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        System.out.println(r.removeNthFromEnd(head, 2));
    }

}


text:
Q: Rails error Uninitialized constant importing csv This is my first time importing a csv file to my rails app.
I have the code below in /lib/tasks/import.rake
    require 'csv'
        CSV.foreach("lib/articles.csv", headers: true, encoding: "ISO8859-1") do |row|
            Article.new(title: row["Title"], body: row["Body"], user: User.find(1))
    end

When I run rake import:articles
I get this error:
     NameError: uninitialized constant Article
    /Users/justinMgrant/code/hrsurvival/lib/tasks/import.rake:8:in `block in <top (required)>'
    /Users/justinMgrant/code/hrsurvival/lib/tasks/import.rake:7:in `<top (required)>'
    /Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:658:in `block in run_tasks_blocks'
    /Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:658:in `each'
    /Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:658:in `run_tasks_blocks'
    /Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/application.rb:452:in `run_tasks_blocks'
    /Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:453:in `load_tasks'
    /Users/justinMgrant/code/hrsurvival/Rakefile:6:in `<top (required)>'
    (See full trace by running task with --trace)

Any idea what I'm doing wrong?

A: The problem is that you're not actually defining your task in your rakefile. This should work for you to be able to run rake import:articles.
namespace :import do

  desc 'An optional description for what the task does'
  task :articles => :environment do
    # your code goes here
  end

end

rake import:articles is saying to look for a task called articles within a namespace called import, which is why the namespace is necessary for what you're currently trying.
And as @max mentioned, utilizing task :articles => :environment is what tells the task to run in the context of your Rails environment, which would make your Articles model and any other model available to you in that task.


text:
Q: ZIO [Declarative] Transactional Management I spent a lot of time figuring out transactions on my otherwise well running ZIO+HTTP4S+Doobie-project.
How can I have proper [declarative] transaction management? Something like Spring @Transactional.
I read this very good post from-transactional-to-type-safe-reasonable-transactions, but ironically have exactly the alleged Spring challenge of getting confused how/where the transactions are precisely handled :)
Also tried tranzactio, even a entered a question under issues, where my PR (on my fork) seems to indicate individual transact calls are grouped in a single transaction?!
And here in bootzooka which is on the ZIO references list, I don't understand why the Resource is 'used' only once in main, and then transact is called around the logic. Well, I understand why it works, but I don't see any 'Strategy' or anything else letting me handle when an error in the first ZIO-effekt would let me control what happens to the second flatmapped effect...
Or how to assure there will be a single transaction happening for a HTTP4S-request.
Or an error handler, that got a @RequiresNew to actually store information about the error somewhere in the databse, even when all the previous logic is correctly rolled back.
I wouldn't mind helping others by writing up something about this, but I clearly have more to learn. About Doobie and ZLayers and so forth.
If there is something I am clearly missing here, please let me know :-)


text:
Q: Collection.toArray() method, detail about it Why would not it work?
List<String> lista = new ArrayList<>();
        lista.add("Lol");
        lista.add("ball");
        String [] array = (String[])lista.toArray();

It throws a RunTimeException (ClassCastException), I am aware that there is another method for the purpose of returning the object contained in the List, however what is happening behind the scenes? I mean I am casting an array of Objects which actually is an array of Strings to an Array of Strings. So it should compile, but it does not.
Thanks in advance.

A: That version of toArray() returns Object[]. You can't cast an Object array into a String array even if all the objects in it are Strings.
You can use the lista.toArray(new String[lista.size()]); version to get the actual type correctly.

A: List.toArray()
returns an Object[], because of type erasure. At runtime your list does not know if it has String objects. From there you can see where that error is coming from.
You cannot type cast an Object[] into a String[]

A: Array of objects is not array of Strings and can't be cast to one.
Check this.

A: use toArray(T[] a) instead.
Ie.
List<String> lista = new ArrayList<String>();
    lista.add("Lol");
    lista.add("ball");
    String [] array = lista.toArray(new string[1]);

This insures that toArray returns an array of type String[]
As others have noted, toArray() returns an array of type Object[], and the cast from Object[] to String[] is illegal.

A: List lista = new ArrayList<>(); --->  List lista = new ArrayList();

A: There are two toArray() versions.You can use another one!


text:
Q: Is the standard definition of $i$ enough to uniquely describe it? Ahlfors states "From elementary algebra the reader is acquainted with the imaginary unit $i$ with the property $i^2 = -1$." (Complex Analysis, Lars Ahlfors, page 1)
Kreyszig (Advanced Engineering Mathematics) first defines complex numbers "as an ordered pair $(x,y)$", where $x, y \in \mathbb{R}$. He then defines the imaginary unit $i$ as $(0,1)$. Following this, he defines the addition and multiplication of complex numbers, and uses the definition of multiplication to arrive at $i^2 = -1$. (pages 652, 653)
Professor Paul Dawkins's online notes use both of the above approaches.
Various other places like MathWorld use similar definitions.
But these definitions only narrow down $i$ to two possible values (which are opposite in sign: $z_1$ and $-z_1$). So, when $i$ is used in an expression or in the representation of a complex number, how does one determine which one of the two values it actually is? Also, the sign of the imaginary part of the complex number will change if one person is using one of the two values given by the definition of $i$ and someone else is using the other one. This ambiguity will also affect the uniqueness of the complex plane.
Keeping the above points in mind, are there additional qualifications that help in narrowing it down to one value?
Or is it impossible to further narrow it down, and so we say that - we are using one of the square roots of -1 and representing that root as $i$, and we will all use $i$ to mean this same root, although we can't really define which one it is?

A: The map $$f:\mathbb{C}\rightarrow\mathbb{C}: a+bi\mapsto a-bi$$ (conjugation) is an automorphism of $\mathbb{C}$: if $P$ is a true statement about complex numbers using $+$ and $\times$, then "$f(P)$" is also true, where $f(P)$ is the statement gotten by replacing $z$ with $f(z)$ for every complex number $z$ in $P$. E.g. "$i^3=-1$" is true, and $f($"$i^3=-1$") = "$(-1)^3=-1$" is also true.
So using addition and multiplication alone there is no way to distinguish $i$ from $-i$. That said, there are other operations on $\mathbb{C}$ which "add structure" - e.g. the "imaginary part" function $\mathfrak{Im}: a+bi\mapsto b$ (since we have $\mathfrak{Im}(i)=1$ but $\mathfrak{Im}(-i)=-1$).

Making this a bit more palatable (hopefully!):
We shouldn't really talk about $\mathbb{C}$ as if it were unique. Rather, we should talk about "algebraic closures of $\mathbb{R}$" (which is itself a bit wrong - reall really, we should talk about "algebraic closures of Dedekind-complete ordered fields"). The point is that any two such objects are isomorphic, and that means that when you're holding your version of $\mathbb{C}$ and I'm holding my version of $\mathbb{C}$ we'll never disagree about how they behave - even if they're quite different, or if they're the same except with $i$ and $-i$ "flipped."
The ordered-pairs-of-reals approach describes one way of producing a "version of $\mathbb{C}$."

Ultimately, thinking along these lines will take us to model theory (an area of logic that looks at the problem of what objects/functions/relations/etc. are "definable" in given contexts) and category theory (which can be thought of as studying "purely structural" behavior).


text:
Q: Flutter [ERROR:flutter/runtime/dart_vm_initializer.cc(39)] PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: ) I want to set up a Google login with Flutter.
In Firebase I have the SHA's for both debug and realease.
When I start the app I get the button and it lets me enter the email, but when I press enter I get this error:

E/flutter (24342): [ERROR:flutter/runtime/dart_vm_initializer.cc(39)] Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null, null)

I have tried other published solutions but I still get this error.  I have tried both on the emulator and on the physical device.
The file google-services.json is inside the app folder.
dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  google_sign_in: ^5.3.3
  provider: ^6.0.3
  firebase: ^9.0.3
  firebase_core: ^1.17.1
  firebase_auth: ^3.3.19
  firebase_database: ^9.0.15

I try to run the app locally on an emulator.
in many of the solutions I see that the app is uploaded to google. is it not possible to test it locally?


text:
Q: Put many columns in group by clause in Oracle SQL In Oracle 11g database, Suppose we have table, CUSTOMER and PAYMENT as follows
Customer
CUSTOMER_ID | CUSTOMER_NAME | CUSTOMER_AGE | CUSTOMER_CREATION_DATE
--------------------------------------------------------------------
001                     John             30              1 Jan 2017
002                     Jack             10              2 Jan 2017
003                      Jim             50              3 Jan 2017

Payment
CUSTOMER_ID | PAYMENT_ID | PAYMENT_AMOUNT |
-------------------------------------------
001                   900            100.00
001                   901            200.00
001                   902            300.00
003                   903            999.00

We want to write an SQL to get all columns from table CUSTOMER together with the sum of all payment of each customer. There are many possible ways to do this but I would like to ask which one of the following is better.
Solution 1
SELECT C.CUSTOMER_ID
, MAX(C.CUSTOMER_NAME) CUSTOMER_NAME
, MAX(C.CUSTOMER_AGE) CUSTOMER_AGE
, MAX(C.CUSTOMER_CREATION_DATE) CUSTOMER_CREATION_DATE
, SUM(P.PAYMENT_AMOUNT) TOTAL_PAYMENT_AMOUNT
FROM CUSTOMER C
JOIN PAYMENT P ON (P.CUSTOMER_ID = C.CUSTOMER_ID)
GROUP BY C.CUSTOMER_ID;

Solution 2
SELECT C.CUSTOMER_ID
, C.CUSTOMER_NAME
, C.CUSTOMER_AGE
, C.CUSTOMER_CREATION_DATE
, SUM(P.PAYMENT_AMOUNT) PAYMENT_AMOUNT
FROM CUSTOMER C
JOIN PAYMENT P ON (P.CUSTOMER_ID = C.CUSTOMER_ID)
GROUP BY C.CUSTOMER_ID, C.CUSTOMER_NAME, C.CUSTOMER_AGE, C.CUSTOMER_CREATION_DATE

Please notice in Solution 1 that I use MAX not because I actually want the max results, but I because I want "ONE" row from the columns which I know are equal for all rows with the same CUSTOMER_ID
While in solution 2, I avoid putting the misleading MAX in SELECT part by putting the columns in GROUP BY part instead.
With my current knowledge, I prefer Solution 1 because it is more important to comprehend the logic in GROUP BY part than in the SELECT part. I would put only a set of unique keys to express the intention of the query, so the application can infer the expected number of rows. But I don't know about the performance.
I ask this question because I am reviewing a code change of a big SQL that put 50 columns in the GROUP BY clause because the editor want avoid the MAX function in SELECT part. I know we can refactor the query in someway to avoid putting the irrelevant columns in both GROUP BY and SELECT part, but please discard that option because it will affect the application logic and require more time to do the test.

Update
I have just done the test on my big query in both versions as everyone suggested. The query is complex, it has 69 lines involving more than 20 tables and the execution plan is more than 190 lines, so I think this is not the place to show it.
My production data is quite small now, it has about 4000 customers and the query was run against the whole database. Only table CUSTOMER and a few reference table has TABLE ACCESS FULL in the execution plan, the others tables have access by indexes. The execution plans for both versions have a little bit difference in join algorithm (HASH GROUP BY vs SORT AGGREGATE) on some part.
Both versions use about 13 minutes, no significant difference.
I also have done the test on the simplified versions similar to the SQL in the question. Both version has exactly the same execution plan and elapse time.
With the current information, I think the most reasonable answer is that it is unpredictable unless test to decide the quality of both versions as the optimizer will do the job. I will very appreciate if anyone could give any information to convince or reject this idea.

A: Another option is
SELECT C.CUSTOMER_ID
, C.CUSTOMER_NAME
, C.CUSTOMER_AGE
, C.CUSTOMER_CREATION_DATE
, P.PAYMENT_AMOUNT
FROM CUSTOMER C
JOIN (
 SELECT CUSTOMER_ID, SUM(PAYMENT_AMOUNT) PAYMENT_AMOUNT
 FROM PAYMENT
 GROUP BY CUSTOMER_ID
) P ON (P.CUSTOMER_ID = C.CUSTOMER_ID)

To  decide which one of three is better just test them and see the execution plans.

A: Neither. Do the sum on payment, then join the results.
select C.*, p.total_payment -- c.* gets all columns from table alias c without typing them all out
from Customer C
left join -- I've used left in case you want to include customers with no orders
(
select customer_id, sum(payment_amount) as total_payment
from Payment
group by customer_id
) p
on p.customer_id = c.customer_id

A: Solution 1 is costly.
Even though optimizer could avoid the unecessary sorting,
at some point you will be forced to add indexes/constraints
over irrelevant columns to improve performance.
Not a good practice in the long term.
Solution 2 is the Oracle way.
Oracle documentation states that:

GROUP BY clause must contain only aggregates or grouping columns

Oracle engineers had valid reasons to do that,
however this does not apply to other RDBMS where you
can simply put GROUP BY c.customerID and all will be fine.
For the sake of code readability a --comment would be cheaper.
In general, not embracing any platform principles would have a cost:
more code, weird code, memory, disk space, performance, etc.

A: In Solution 1 the query will repeat the MAX function for each column. I don't know exactly how the MAX function works but I assume that it sorts all elements on the column than pick the first (best case scenario). It is kind of a time bomb, when your table gets bigger this query will get worst very fast. So if you consern about performance you should pick the solution 2. It looks messier but will be better for the application.


text:
Q: SOLR - how to index database partly? I have a postgresql database. In table, which i need to index, i have about 20 million rows. When i want to index them all in one attempt(smth like "select * from table_name"), i have Java OutOfMemory error, even, if i`ll give to JVM more memory.
Is there any option in SOLR to index a table part by part(e.g. execute sql for first 1000000 rows, then index it, then execute sql for second million)?
Now i am using sql query with LIMIT. But, everytime, when solr has indexed it, i need manually start it again.
UPDATE: Ok, 1.4 is out now. No OutOfMemory Exceptions, seems, Apache had done very big work on DIH. Also, now we can pass parameters through request, and use them in our SQL selects. Wow!

A: See the bit about "cursors" here, that might well help.
http://jdbc.postgresql.org/documentation/83/query.html

A: Do you have autoCommit, batchSize configured? If you do, it might be this bug, try updating to trunk.

A: Have you looked at using SolrJ as a client?   While DIH is great, the tight coupling between Solr and your Database means that it can be hard to manipulate your data and work around issues.
With a SolrJ client, you could then iterate in batches that you control over your database, and then turnaround and dump then directly into Solr.  Also, using SolrJ new binary java stream format instead of XML means that indexing your 20 million rows should go fairly quickly.
DIH is great, until you end up in issues like this!


text:
Q: Angular CLI ejected App - pass parameters I'm currently using @angular/cli@1.0.0-beta.32.3. I used the new eject feature to edit the webpack config. Now I'm confused how I'm able to pass parameters to my build.
For example: How would I do a
ng build --prod or ng test --code-coverage?
How would I do those things with npm scripts.

A: After ejecting, angular-cli disables the use of your ng-commands. It does however give you a basic setup for doing it yourself.
If you look into your package.json, you find the following:
"scripts": {
    "ng": "ng",
    "start": "webpack-dev-server --port=4200",
    "build": "webpack",
    "test": "karma start ./karma.conf.js",
    "lint": "ng lint",
    "e2e": "protractor ./protractor.conf.js",
    "prepree2e": "npm start",
    "pree2e": "webdriver-manager update --standalone false --gecko false --quiet"
}

These are what the angular-cli folk have determined to be the minimum needed scripts to build your project from now on. They are run from your command-line, preceded by npm run or yarn run, depending on your preference.
So when you want to run a webpack build, in stead of running ng build, like you used to, you now run npm run build.
To build for production in webpack, you want to add a line to those scripts:
"scripts": {
    "ng": "ng",
    "start": "webpack-dev-server --port=4200",
    "build": "webpack",
    "build:prod": "webpack -p",                        <-- add this line
    "test": "karma start ./karma.conf.js",
    "lint": "ng lint",
    "e2e": "protractor ./protractor.conf.js",
    "prepree2e": "npm start",
    "pree2e": "webdriver-manager update --standalone false --gecko false --quiet"
}

Now when you want to run a production build, just type npm run build:prod and webpack will run in production mode.
If you ejected with --prod, the above will not mean much will change, since I think webpack.config.js will automatically be put in production mode.
Some more info on what webpack -p does exactly, see https://webpack.js.org/guides/production-build/


text:
Q: I am trying to convert the blank values of my csv file to the mean of the columns but it is giving "could not convert string to float: '-' " error import pandas as pd
import numpy as np
from sklearn.preprocessing import Imputer
data = pd.read_csv("austin_weather.csv")
data = data.drop(['Events', 'Date'], axis = 1)
X = data.iloc[:, :-1].values
Y = data.iloc[:, 18].values
data = data.replace('T', 0.0)
imputer = Imputer(missing_values="-", strategy="mean", axis = 0)
imputer.fit(X[:])

the imputer function is not able to convert the "-" blank value to the mean of the respective column

A: For the depreciated class sklearn.preprocessing.Imputer parameter missing_values is either string NaN or a number.
So you can first replace all - values with np.nan: X.replace('-', np.nan) and then call imputer.


text:
Q: project.assests.json is being written to wrong directory I am new to Azure DevOps and trying to build a Visual Studio solution with many projects.  During the NuGet restore which is running in an azure pipeline, the project.assests.json file is being written to the wrong directory.  The solution is set to Release configuration but the json file is being written to the Debug directory. The following is the output of the NuGet restore:
2022-10-18T20:33:28.9371401Z Writing assets file to disk. Path: E:\2020ProdBuild1_work\271\s\squirrel.windows\build\obj\Debug\Squirrel\project.assets.json
The NuGet commands are:
- task: NuGetCommand@2
  displayName: "Restore NuGet.config"
  inputs:
    command: 'restore'
    restoreSolution: '$(solution)'
    configuration: 'Release'
    feedsToUse: 'select'
    nugetConfigPath: 'NuGet.config'

How do I change the directory where the json file is being written?


text:
Q: How can I make the Login Activity start automatically when the authentication fails? package com.example.madclassproj;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

In the Main Activity I get the response either ( 0-FAIL Cannot identify token … ) if the authentication fails or ( 0-OK Hello Leonidas ) if it is successful. I need the another activity (Login Activity) to be automatically started if the authentication is failed.
 public class MainActivity extends AppCompatActivity {
        TextView textView;
        String server_url = "http://mad.mywork.gr/authenticate.php?t=XYZ";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            textView = (TextView)findViewById(R.id.textView);

            final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

            StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    textView.setText(response);
                    requestQueue.stop();

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    textView.setText("Something went wrong.");
                    error.printStackTrace();
                    requestQueue.stop();
                                }
            });
            requestQueue.add(stringRequest);

        }

    }

A: public class MainActivity extends AppCompatActivity {
        TextView textView;
        String server_url = "http://mad.mywork.gr/authenticate.php?t=XYZ";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            textView = (TextView)findViewById(R.id.textView);

            final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

            StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    textView.setText(response);
                    requestQueue.stop();

                    if(!response.equals("0-OK Hello Leonidas")) {
                        startActivity(new Intent(this, LoginActivity.class));
                        finish();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    textView.setText("Something went wrong.");
                    error.printStackTrace();
                    requestQueue.stop();
                                }
            });
            requestQueue.add(stringRequest);

        }

    }