text:
Q: The best reporting component for Delphi? We are a team that use Gnostice and RaveReports to view, print, mail and generate PDFs of reports using D2007. D2009 is in the roadmap but as Gnostice don't support D2009 we have to wait. In the past the reports was done in code and then viewed, printed etc.
Now we have started to evaluate the Ravereports designer and make reports with that instead.
But now we hesitate. Nevrona seems to be more or less dead. We haven't managed to buy the source of Ravereports and webmaster@nevrona.com bounce back. Hm...
And they are the default component for Delphi...
There are other report solutions like digital-metaphors and Fast Reports.
I have no doubt that they are both good and competent, but we have to do something.
Anyone know if Codegear is about to abandon Ravereports because of some trouble ?
Comments about digital-metaphors and Fast Reports is appreciated.
We want a good reporting component that can build reports with code and in designtime.
The reportfile should be saved in text, xml is prefered unlike rave-files.
An easy way to set default printer would be nice as the Citrix environment we use sometimes fails with this task.

A: We have used Reportbuilder for several years now, and we think it is awesome. We use it to build reports in our tools, as well to let our customers to build reports by their self. The End user reporting capabilities are the same as the developer. All can be customized where needed in native Delphi code.
I think every thinkable report solution can be build with ReportBuilder.
Beside a great tool they deliver also good support on the product.

A: We use FastReport for last 10 years. Never had any problems.

A: Another thing very interesting : support is very good with Fast Report Team !
Just ask one question and you get your answer very quickly : you can also ask for some improvement and if it don't look stupid they made it.
And then, if you need OLAP solution : you can get Fast Cube and generate report quickly

A: I have been using FastReports for about 10 years.  The current version is very good.  We use it in a number of areas including pdf generation for web reporting, user report design and automatic printing.

A: I would agree with idursun, I have used many reports engines before, but when I used Fast-Report, I haven't look else anymore.
I would add about fast-Reports

*

*FastReport has support for unicode
for Delphi < 2009.

*Development is faster than other
reporting tools,    they were
supporting Delphi 2009    before it's
release date, other    reporting
tools took longer time, and    in
some cases too much time for
Delphi 2009.

*Very flexible, you
can access any report components from
Delphi code, or use any Delphi
function inside your reports.

*If you compare FR with others in
Features/Prices, it has much of
advanced features with lower prices.

*FR file format is XML.

*There's a server edition for web reporting.

*There's .net edition also.

*It has very powerful script engine with more languages(Pascal,Basic, Java & C).

*Has end user-designer tool without extra money(I think you need Standard version or above).

A: I haven't tried digital-metaphors but I have used FastReports for a long time and I haven't even faced any problem related with that product.
Pros:

*

*Very good and functional designer

*Query objects

*Scripting support (allows you to call functions from code)

*Multi language support

*Wide range of exporting options

Cons:

*

*Designer's code editor is buggy

A: I started testing ReportBuilder quite a few years ago but I switched to FastReports a while ago and have been very happy with the change.
One of my requirements was that the reporting engine needed to be just one form of output (producing columnar or similar reports), but my framework needed to be able to output to this engine or an engine to produce filled in PDF forms or reports in Excel format or other kinds of digital reports. The reports have to be instances of a report superclass so that they can be combined and produced together as a package with multiple output types and destinations.
I am not an ace programmer, but I found the job could be done readily.  FastReports fits into this framework and does its job superbly.  I can't say enough about the power and flexibility I have found by using Delphi, Firebird and FastReports.  I am just now starting to explore the possibilities of using its built in pascal scripting to integrate more completely with my main program.
I hope this is helpful.
Jack

A: Slightly different tack, but I use WPTools in its mail merge capacity to generate reports. I switched from a standard reporting system because people found it harder to use, and most reports are wanted in Word so they can be edited (in our app anyway). Not for everyone, but worth a ponder. It supports banding type things, so you can loop nicely, and can feed data from database or static structures.

A: While you haven't explicitly mentioned Bold, I assume you would prefer a Bold aware reporter. If so, then nicely designed "pluggable" data awareness is important. I haven't tried all of the popular products, but I was able to boldify FastReport without too much effort. It's not lacking in any other area so I highly recommend it.


text:
Q: PHP: How to constantly read a file I need to read a file that is changing all the time. the file only and will only ever have one line that changes all the time.
I found the following code that should do what I want here: PHP: How to read a file live that is constantly being written to
But the code does not work, the page just keeps loading, I tried to add a "flush" like one user suggested, but I still cant make it work.
Here's the code
$file='/home/user/youfile.txt';
$lastpos = 0;
while (true) {
    usleep(300000); //0.3 s
    clearstatcache(false, $file);
    $len = filesize($file);
    if ($len < $lastpos) {
        //file deleted or reset
        $lastpos = $len;
    }
    elseif ($len > $lastpos) {
        $f = fopen($file, "rb");
        if ($f === false)
            die();
        fseek($f, $lastpos);
        while (!feof($f)) {
            $buffer = fread($f, 4096);
            echo $buffer;
            flush();
        }
        $lastpos = ftell($f);
        fclose($f);
    }
}

Please could someone have a look and let me know how to fix it.
Thanks in advance.

A: If your file have only one string, and you need to read it on change, use this code:
$file = '/path/to/test.txt';
$last_modify_time = 0;
while (true) {
    sleep(1); // 1 s
    clearstatcache(true, $file);
    $curr_modify_time = filemtime($file);
    if ($last_modify_time < $curr_modify_time) {
        echo file_get_contents($file);
    }

    $last_modify_time = $curr_modify_time;
}

Note:
filemtime() returns last file modification time in seconds, so if you need to check modification more than one time per second, probably you'll need to find other solutions.
Also, you may need to add set_time_limit(0); it depends on your requirements.
Update:
index.html
<!DOCTYPE html>

    <meta charset="UTF-8">

fileupdate.php
<?php
$file = 'test.txt';
$result = array();
clearstatcache(true, $file);

$data['time']    = filemtime($file);
$data['content'] = $_POST['time'] < $data['time']
    ? file_get_contents($file)
    : false;

echo json_encode($data);

A: You might be dealing with 3 drawbacks:

*

*First, the code you already have is holding a $lastpos. Meaning, it will always look for what is added at the end of the file. You are not clear in the OP, but I think this is not what you want. I think your one and only line is continuously changing, but not necessarily changing size. So you might want to remove the line $lastpos = ftell($f);.

*Secondly, in regards to the same, you are check the file size to know if the file has changed. But as I explained, the file might have changed, while the file size stayed equal. Try changing the check of the file size to checking the file last-edit date.

*Third, and probably most importantly: your web browser might be buffering your output until the php script is done running, before it releases the buffered output to the browser. Disable output buffering in both PHP and your web server. Things like gzip/compression by the web server can also be forcing output-buffering effects.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Determining where parameters passed from view to controller originated In my ApplicationController parent class I have an action method called dig which reads parameters via the params[] hash-like structure.  I would like to have any view that builds a link to any controller via link_to helper function with the dig action to call the parent's action first.  I'd like to then be able to determine either what that parameterized information represents (its type), or what created the link (the previous or originating view).
Any ideas on the best way to do this?  Is there a way to pass an object via the link_to and then use its meta data?  If so, would this break the rails paradigm?

A: If you're looking for what called what inside your code, Ruby's caller method is the basis for the stack dump that occurs when an exception occurs. You can tap into that and ask what the calling chain was at any point.
If you want to trace the incoming requests from the browser from an outside site, it becomes a lot more difficult because browsers don't like to reveal the last location any more. If the browser is being redirected around your own site you can use sessions or cookies to trace its movement.

A: I think that to have the originating link what you would need to do is something like this:
request.env['HTTP_REFERER']

This will get the URL where the action was originated, from there you can process the URL to get controller, action and id. Hope this helps!


text:
Q: Dynamic assignment of case class in a class declaration We have two case classes which has different parameters. For Example -
case class OneType(@JsonProperty("column1") column1 : String,
                   @JsonProperty("column2") column2 : Map[String,Any],
                   @JsonProperty("column3") column3 : Seq[String]
                  )

case class AnotherType(@JsonProperty("column1") column1 : String,
                       @JsonProperty("column2") column2 : BigInt,
                       @JsonProperty("column3") column3 : Map[String,String]
                      )

These two case classes will be used to de-serialize incoming JSON messages(by mapping them with the case class). They need to be used in another class declaration. For example -
class JSONDeserialize extends StreamManager(String, Either[Failed, OneType/AnotherType]){
}

How to dynamically assign appropriate case class(here either OneType or AnotherType) into JSONDeserialize  class without having duplicate JSONDeserialize class?

A: I am thinking of 2 ways you can do that.
1- You could Join both case classes in a single case class, like this:
       case class T(
                   @JsonProperty("column1") column1 : Option[String],
                   @JsonProperty("column2") column2 : Option[Map[String,Any]],
                   @JsonProperty("column3") column3 : Option[Seq[String]],
                   @JsonProperty("column4") column4 : Option[String],
                   @JsonProperty("column5") column5 : Option[BigInt],
                   @JsonProperty("column6") column6 : Option[Map[String,String]]
                  )

And you always read the only type T, that have optional fields, with Option, which means the data might not exist, can be None.
2- You could try to read OneType and if it fails read AnotherType.


text:
Q: Showing two fields from two tables I want to get an employee's first name and their department name (based on id_department). This is an example of my data:

How would I accomplish this using MariaDB (shell)?

A: Select FirstName, DepartmentName from Employees e inner join Department d on e.DepartmentId = e.DepartmentId

That's how we do it in SQL server side.
I just read the documentation of MariaDB and found that they have the exact same syntax for join. Given example in their docs:
SELECT * FROM t1 INNER JOIN t2 ON t1.a = t2.b;


text:
Q: Is there a direct way to crop an irregular dimensioned / non rectangular object in image where background area should be transparent I am doing object detection which gives specific polygonal points which I want to crop out from the original image, but apart from the region of interest all the background should be transperent(not just black/white color obtained post bitwise_and operation from ROI). Want to know if it is possible to crop it in that way rather than tweaking the alpha value to decrease the opacity of the background.

A: That can be done by making a white filled mask on a black background in Python/OpenCV using fillPoly() from your polygon points. Then put the mask into the alpha channel of the image.
Input:

import cv2
import numpy as np

# read image
img = cv2.imread("efile.jpg")

points = np.array( [[ [693,67], [23,85], [62,924], [698,918] ]] )

# draw white filled polygon from points on black background as mask
mask = np.zeros_like(img)
cv2.fillPoly(mask, points, (255,255,255))
mask = mask[:,:,0]

# put mask into alpha channel of image
result = img.copy()
result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
result[:,:,3] = mask

# write results
cv2.imwrite("efile_mask.jpg", mask)
cv2.imwrite("efile_transparent.png", result)

# display it
cv2.imshow("efile_mask", mask)
cv2.imshow("efile_transparent", result)
cv2.waitKey(0)

Result:


text:
Q: Changing the default separator in csv created with "gdal_translate -of XYZ" I have 100s of .tiff files, and using the following command:
gdal_translate -of XYZ MCD13A2.t201624.006.global.1km_NDVI.O0.tif MCD13A2.t201624.006.global.1km_NDVI.O0.csv

This generates a .csv file but it is space separated, instead of comma separated.
Does anybody knows why this is happening, or have any solution for converting this space separated file into a comma separated .csv?

A: You can simply use the CSV module :
import csv

with open(ur_infile) as fin, open(ur_outfile, 'w') as fout:
    o=csv.writer(fout)
    for line in fin:
        o.writerow(line.split())

It will automatically read your CSV with space separator and write it with comma (by default).
Also, you could specify delimiter like that :
csv.reader(csvfile, delimiter=' ')
csv.writer(csvfile, delimiter=',')

A: A google search revealed the following approach:
After you are done with the xyz conversion, you can just use the commandline utility sed (suppose you use linux):
sed 's/ /,/g' in.xyz > out.csv
Since you are creating 100s of csv files, you are probably using gdal_translate inside a for loop, so you can just add that additional line right after gdal_translate and you won't even notice anything!
Still, if you want to use @iFlo's method without worrying about out-of-memory problems, you can have a look at this thread.


text:
Q: how to get the current order of all columns (visible or invisible) in dataTables after using colReorder? I have a table populated with dataTabels jquery plugin.
after i use colReorder plugin on it and reorder my columns,
how can i get all my collumns order.
let me explain little more.
if i have all my columns visible it is fairly easy. but when i make some columns disapear with colViz plugin of dataTables it destroy the whole column and its not there for me to get any thing of it.
the problem is that i know that the order is present somewhere in the oTable object, because when you change the order of columns in your table with colReorder in colViz list the order changes and it containes all my columns names.
i searched all three of js files thoroughly. but could not found any thing helpfull.
though i can not use the colVix button names, because they are not present in page and after i click on show/hide columns list they are generated. in addition i can not trigger a click on it because it has a fairly long animation that make it almost impossible to use this cheap tricks on it.
can any one help?
EDIT:
i think it is clear:
i just want a list with titles of my columns visible or hidden especially after using reorder

A: You could use the colVis button clicks  to create array based on checkboxes checked:
$(document).on('click', '.ColVis_Button:not(.ColVis_MasterButton)',function(){
     var colsArray= $('.ColVis_Button :checkbox').map(function(){
      return [[$(this).parent().next('.ColVis_title').text(), this.checked ? 'visibile':'hidden']];
    }).get();
    console.log(colsArray)

});


text:
Q: Width ratio calculation is being applied twice I am attempting to create an overlay which displays a larger version of an image when a thumbnail is clicked on. The problem I am running into is that the width of the image is being scaled down to far.
I am using the following code:
largeImage.addEventListener('load', function() {
    // Resize if Taller
    if (this.height > window.innerHeight) {
        this.ratio = window.innerHeight / this.height;
        this.height = window.innerHeight;
        this.width = this.width * this.ratio;
        console.log('Ratio: ' + this.ratio);
        console.log('Height: ' + this.height);
        console.log('Width: ' + this.width);
    }

    // Resize if Wider
    if (this.width > window.innerWidth) {
        this.ratio = window.innerWidth / this.width;
        this.height = this.height * this.ratio;
        this.width = this.width * this.ratio;
    }
}, false);

The image in question is 1000x1500 and the window.innerHeight and .innerWidth are 430px and 1064px respectively. this.ratio calculates out to 0.2866666666666667 so this.width should calculate to 287. But instead I am getting 82 which is 1000 * 0.2866666666666667 * 0.2866666666666667.
I put in the console.log for diagnostic reasons and this.height and this.ratio are being calculated correctly, but the width is being multiplied by the ratio twice somehow.
Edit: I updated the code to include the entire eventHandler.

A: The width of the image is automatically resized when you resize the height.
So, you resize the height by 0.2866666666666667 (but this also resizes the width) and then you apply 0.2866666666666667 again - that's why you get the ratio applied twice.
You can comment this line - you should get the values as expected in the console:
this.width = this.width * this.ratio;

A: You need to compute the new height and width values ahead of time so neither is skewed by the changing of the other.

function resize() {
  var element = document.getElementById('image');
  var newHeight = element.height * 0.5;
  var newWidth = element.width * 0.5;

  console.log('Original width and height: ', element.width, element.height);

  element.height = newHeight;
  element.width = newWidth;

  console.log('New width and height: ', element.width, element.height);
}

  <button onclick="resize()">Shrink By 50%</button>


text:
Q: How do I pass 2 Parameters to a jQuery.Find function I am trying to pass in 2 parameters to a jQuery.Find() function to get a piece of data. I currently have the following code
$(container).find('[name="cars",' + 'class="selected"]').val()

but its giving me an unrecognized expression error.
Is there a way I can combine the 2 parameters I have into one call?


text:
Q: SAS: create covariance matrix with variables I am working on a project in which we have to do some simulations. I am now at the point I want to use the RandNormal function, to generate multivariate normal data given a vector of means and a covariance matrix. For the covariance matrix, we have to use different parameters, so instead of putting the values in directly, I want to just put the variable name in the matrix (so we do not have to do the calculations by hand).
We get this error:

ERROR: (execution) Character argument should be numeric.

And this is our code. The dataset Simulatie also contains the variables defined in this proc iml.
proc iml;
    use Simulatie;
    read all;
    close Simulatie;

    sigma0sq = 2;
    sigma1sq = 3;
    sigma2sq = 1;
    sigma0 = sqrt(sigma0sq);
    sigma1 = sqrt(sigma1sq);
    sigma2 = sqrt(sigma2sq);
    rhoM = 0.7;
    rhoV = 0.5;
    rhoMsigma0sigma1 = rhoM*sigma0*sigma1;
    rhoVsigma0sigma2 = rhoV*sigma0*sigma2;
    rhoVsigma1sigma2 = rhoV*sigma1*sigma2;

    Mean = {0, 0, 0}; /* population means */

    Cov = {sigma0sq rhoMsigma0sigma1 rhoVsigma0sigma2, /* population covariances */
           rhoMsigma0sigma1 sigma1sq rhoVsigma1sigma2,
           rhoVsigma0sigma2 rhoVsigma1sigma2 sigma2sq};

    N = 185; /* sample size */
    call randseed(123);
    X = RandNormal(N, Mean, Cov); /*x is a nx3 matrix */
    SampleMean = mean(X);
    SampleCov = cov(X);
quit;

We tried putting in for instance
Cov = {3 2 1, 2 4 0,1 0 5};

Which works perfectly nice, but when we change it to variable names, it gets an error.
We did some googling but couldn't find the solution, could anyone help us out :) It seems like such a silly, easy-to-fix error, but we just don't succeed!
Thanks in advance.

A: The reason for your error is explained in the article "How to build a vector from expressions."
The simplest solution is to use the horizontal and vertical concatenation operators to build the matrix:
Cov = (sigma0sq || rhoMsigma0sigma1 || rhoVsigma0sigma2) //
      (rhoMsigma0sigma1 || sigma1sq || rhoVsigma1sigma2) //
      (rhoVsigma0sigma2 || rhoVsigma1sigma2 || sigma2sq);

An alternative is to allocate the 3x3 matrix and then use subscripts to assign each element:
Cov = j(3, 3, .);
Cov[1,1] = sigma0sq;
Cov[1,2] = rhoMsigma0sigma1;
Cov[1,3] = rhoVsigma0sigma2;
Cov[2,2] = sigma1sq;
Cov[2,3] = rhoVsigma1sigma2;
Cov[3,3] = sigma2sq;
/* make symmetric */
Cov[2,1] = Cov[1,2];
Cov[3,1] = Cov[1,3];
Cov[3,2] = Cov[2,3];


text:
Q: Binding properties between viewmodels Lets say I have two views: FileList and Editor.
They both have their own view models, bound using a DependencyProperty.
The view models look somewhat like this:
public class FileVM : INotifyPropertyChanged
{
    public string FileName { get; set; }
}

public class FileListVM : INotifyPropertyChanged
{
    public ObservableCollection<FileVM> Files { get; set; }
    public FileVM SelectedFile { get; set; }
}

public public class EditorVM : INotifyPropertyChanged
{
    string FileName { get; set; }
}

Imagine that they properly implement INotifyPropertyChanged.
Now I don't want FileListVM and EditorVM to know about each other. They could just as easily exist independently. But in one use case I would like to bind FileListVM.SelectedFile.FileName to EditorVM.FileName. Whenever the selected file or the filename changes, so should the filename in the editor. And whenever the editor changes the filename in the editor, so should the name of the selected file.
Now here is my question: how can I do this cleanly? I'm guessing the solution lies somewhere in their parent view model (e.g. MainVM), since that view model is aware of the connection between the two child view models. But I'm not sure if I can connect the two through xaml, and I'd like to avoid writing property changed event handlers if possible.

A: Please look at:
Communicate between View Models in MVVM
I advise to use MVVM frameworks like Galasoft because they have useful functionality and often do life with MVVM easier ;)
If you do not like using them, you can add event SelectedFileChanged in one VM and subscribe it from the other one.


text:
Q: String called from CSV Ajax Call not evaluating with pure string I have the following call from a local CSV called via Ajax, when a dropdown list value is changed.
The CSV is then split into an array on each comma. Then we loop through and grab the correct value.
However, this line refuses to evaluate to true. I have set breakpoints and found that weFoundYou does equal "XXBO2" and options2[find2].toString() does equal "XXBO2" but the if statement will not evaluate.
if (weFoundYou === options2[find2].toString())

Full code:
$('#myoptions').change(function() {

                    csvData2 = $.ajax(
                    {
                                    type: "GET",
                                    url: "data/stats5.csv",
                                    dataType: "text",
                                    success: function (result2)
                        {
                            var options2 = result2.split(",");
                            var selecthidden2 = document.getElementById('myoptions2');
                            var select2 = document.getElementById('myoptions');

                            var selectedText = select2.options[select2.selectedIndex].text;

                            var q = 0;
                            var find = 0;
                            var find2 = 180;

                            while (find < options.length)
                            {
                                if (options[find] == selectedText)
                                {
                                    var weFoundYou = "XX" + options[find - 1];
                                    find++;
                                }
                                else
                                {
                                    find++;
                                }
                            }

                            while (find2 < options2.length)
                            {
                                if (weFoundYou === options2[find2].toString())
                                {
                                    selecthidden2.options[find2] = new Option(options2[find2+1], find2);
                                    find2++;
                                }
                                else
                                {
                                    find2++;
                                }
                            }

                        }
                            });

The annoying thing is that the FIRST if statement evaluates just fine!
if (options[find] == selectedText)

Contents of CSV file example:
XXB01, Somedropdownvalue, XXB02, Somedropdownvalue2

Contents of array:
XXB01, Somedropdownvalue, XXB02, Somedropdownvalue2

A: Do all of the commas in the CSV file have a space after them? If so, try split(', ') (with the space after comma). It may be trying to match a string containing a space in weFoundYou. Also try weFoundYou.toString(), just in case.
Also, find2 starts on 180, so it skips a lot of the array before starting to search. The variable q appears to not be doing anything. Also, to clean up your loops, since you increment regardless of whether you find a match or not, try this:
while (find < options.length) {
    if (options[find] == selectedText) {
        var weFoundYou = "XX" + options[find - 1];
    }
    find++;
}
while (find2 < options2.length) {
    if (weFoundYou === options2[find2].toString()) {
        selecthidden2.options[find2] = new Option(options2[find2+1], find2);
    }
    find2++;
}

}


text:
Q: Determine the domain of $(f\oplus g)$ in terms of the domains of $f$ and $g$ I am having trouble understanding convolution and would like some help with the following:
Let f and g be functions from $X$ to $]-\infty,+\infty]$. Determine the domain of $(f\oplus g)$ in terms of the domains of $f$ and $g$.
I have the following definition
$$(f\oplus g)(z)=\inf_{x+y=z}(f(x)+g(y))$$
however, I am not sure how this may help me. Any suggestion will help me greatly.

A: I'm going to make some assumptions here that you probably should have made somewhat explicit in your question. That is, I will assume that $X$ is a vector space, and that $\mathop{\textrm{dom}} f, \mathop{\textrm{dom}} g\subseteq X$.
What that in mind, the quantity $f(x)+g(z-x)$ is defined only when $x\in\mathop{\textrm{dom}} f$ and $z-x\in\mathop{\textrm{dom}} g$, which means that $z\in\mathop{\textrm{dom}} f+\mathop{\textrm{dom}} g$. That is,
$$\mathop{\textrm{dom}} (f\oplus g) = \mathop{\textrm{dom}} f+\mathop{\textrm{dom}} g = \left\{z\in X \,|\, \exists x\in\mathop{\textrm{dom}} f, y\in\mathop{\textrm{dom}} g ~\text{s.t.}~x+y=z\right\}$$

A: You can rewrite
$$(f \oplus g)(z) = \inf_{x\in \mathbb X} (f(x)+g(z-x))$$
So $(f\oplus g)(z)$ is only defined if $x \in X$ and $z-x \in X$, which is equivalent to $x \in X \cap (z-X)$, where $z-X := \{z-y |y \in X\}$


text:
Q: CommandException: Caught non-retryable exception - aborting rsync After using gsutil for more than 1 year I suddenly have this error:
.....
At destination listing 8350000...
At destination listing 8360000...
CommandException: Caught non-retryable exception - aborting rsync
.....

I tried to locate the files with this sync problem but I am not able to do so. Is there a "skip error" option of is there a way I can have gsutil more verbose?
My command line is like this:
gsutil -V -m rsync -d -r -U -P -C -e -x  -x 'Download/*' /opt/ gs://mybucket1/kraanloos/

I have created a script to split the problem. This gives me more info for a solution

!#/bin/bash
array=(
3ware
AirTime
Amsterdam
BigBag
Download
guide
home
Install
Holding
Multimedia
newsite
Overig
Trak-r
)

for i in "${array[@]}"
do
    echo Processing : $i
    PROCESS="/usr/bin/gsutil -m rsync -d -r -U -P -C -e -x 'Backup/*' /opt/$i/ gs://mybucket1/kraanloos/$i/"
    echo $PROCESS
    $PROCESS
    echo ""
    echo ""
done

A: I've been struggling with the same problem the last few days.  One way to make it super verbose is to put the -D flag before the rsync argument, as in:
gsutil -D rsync ...
By doing that, I found that my problem is due to having # characters in filenames, as in this question.

A: In my case, it was because of a broken link to a directory.
As blambert said, use the -D option to see exactly what file causes the problem.

A: I had struggled with this problem as well. I figured it out now.
you need to re-authenticate your Google Cloud SDK Shell and set a target project again.
It seems like rsync will not show the correct error message.
try cp instead, it will guide you to authentic and set the correct primary project
gsutil cp OBJECT_LOCATION gs://DESTINATION_BUCKET_NAME/

after that, your gsutil rsync should run fine.


text:
Q: Need to ignore "start with" sequence for identity column when comparing schema in oracle db We have an oracle database (18c) on several servers, and need to sync the schema from dev to prod servers. Since it is only the schema that needs to be synced, and not the content of the tables, we do not need to know the next sequence number of primary key columns. (And we certainly do not want to update the prod servers with this sequence number.)
Have tried both SQL Developers Diff Tool and dbForge Schema Compare for Oracle, but they both list tables where only this sequence number is different as tables that need to be updated.
I have not found a setting in SQL Developer Diff Tool that handles this. In dbForge Schema Compare for Oracle they have the Ignore START WITH in sequences, but this seems to not work as I thought, since it still marks tables that are equal except for the sequence number as tables that need an update.
For new tables that only exist in the source db - the sync script will be like this:
CREATE TABLE TEST (
ID NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY(
START WITH 102),
TEXT VARCHAR2(4000 BYTE),
CONSTRAINT TEST_ID_PK PRIMARY KEY (ID))
LOGGING;

We need that script without the (START WITH 102) part in it.
For a table that exist in both source and target db (with no other change than the sequence number) - the sync script will be like this:
ALTER TABLE TEST
  MODIFY(ID GENERATED BY DEFAULT ON NULL AS IDENTITY(
  START WITH 114
  INCREMENT BY 1
  MAXVALUE 9999999999999999999999999999
  MINVALUE 1
  CACHE 20
  NOCYCLE
  NOORDER));

The reality here is that this is a table that does not need an update, and I thought that Ignore START WITH in sequence would handle this, but apparently not.
Anyone out there have a solution for us?

A: Well, I believe it is a very bad idea to use SQL Developer, or any other IDE tool for that matter, to create scripts to be deployed on Production. You are describing a clear case of lacking a real control version software, like GIT or SVN. You shouldn't need to compare between databases unless there is something wrong, but never for creating DDL scripts.
In this specific case, I would use DBMS_METADATA to create the DDLs
Example
SQL> create table t ( c1 number generated by default on null as identity ( start with 1 increment by 1 ) , c2 number ) ;

Table created.

SQL> insert into t values ( null , 1 ) ;

1 row created.

SQL> r
  1* insert into t values ( null , 1 )

1 row created.

SQL> r
  1* insert into t values ( null , 1 )

1 row created.

SQL> r
  1* insert into t values ( null , 1 )

1 row created.

SQL> select * from t ;

        C1         C2
---------- ----------
         1          1
         2          1
         3          1
         4          1

In this case SQL developer shows start with 5, because that is the next value of the identity column. You can use DBMS_METADATA.GET_DDL to get the right DDL without this clause.
SQL> begin
    DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SQLTERMINATOR', true);
    DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'PRETTY', true);
end;
/

PL/SQL procedure successfully completed.

SQL> select dbms_metadata.get_ddl('TABLE','T') from dual

DBMS_METADATA.GET_DDL('TABLE','T')
--------------------------------------------------------------------------------

  CREATE TABLE "SYS"."T"
   (    "C1" NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 99
99999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER  NOCYCLE
  NOKEEP  NOSCALE  NOT NULL ENABLE,
        "C2" NUMBER
   ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
 NOCOMPRESS LOGGING
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "SYSTEM" ;

There are several options to for example not get the storage attributes. I always use this one
SQL> BEGIN
  2       DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SQLTERMINATOR', true);
     DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'PRETTY', true);
  3    4       DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SEGMENT_ATTRIBUTES', true);
     DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'STORAGE', false);
  END;
  /  5    6    7

PL/SQL procedure successfully completed.

SQL> select dbms_metadata.get_ddl('TABLE','T') from dual ;

DBMS_METADATA.GET_DDL('TABLE','T')
--------------------------------------------------------------------------------

  CREATE TABLE "SYS"."T"
   (    "C1" NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 99
99999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER  NOCYCLE
  NOKEEP  NOSCALE  NOT NULL ENABLE,
        "C2" NUMBER
   ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
 NOCOMPRESS LOGGING
  TABLESPACE "SYSTEM" ;

SQL>

For comparison purposes, you might want to have a look into DBMS_COMPARISON
https://docs.oracle.com/database/121/ARPLS/d_comparison.htm#ARPLS868


text:
Q: Does adding outputs from processing tools in a list save them as layers? import processing

layers = qgis.utils.iface.legendInterface().layers()

supply=[]
sub="supply"
for layer in layers:
    if sub in layer.name():
supply.append(processing.runalg("qgis:fixeddistancebuffer",layer,55,10,False,None))

demand=[]
substring="demand"
for layer in layers:
    if substring in layer.name():
        demand.append(processing.runalg("qgis:fixeddistancebuffer",layer,55,10,False,None))

finalints=[]

for s in supply:
    for d in demand:
        intersections_1=[]
        intersections_1.append((processing.runalg("qgis:intersection",s,d,None)))
    finalints.append((intersections_1))
    del(intersections_1)
print(finalints)

Does this save the obtained output files as layers in the list? If so, how can I add the layers saved in the list onto my map? Also, am not able to get intersections of the layers stored in such lists with output as "Unable to run algorithm".

A: You have intersection alg in double brackets, maybe thats the reason. Is there more output when you run it other than "Unable to run algorithm"?
To load layers:
for layer in finalints:
    QgsProject.instance().addMapLayer(layer)


text:
Q: Foodb api fetch react native Hello I am a beginner in mobile app development. I am doing project in react native.In my app I need to fetch the food details from foodb website using API. I tried in postman to get response but I am getting error.

Error:
  {
    "error": "food_name is missing, api_key is missing"
}

Kindly guide me to resolve this problem. Thanks in Advance

A: You have to add parameter as query parameters:
curl -X GET 'https://foodb.ca/api/v1/foodreport/food?food_name=Angelicaa&api_key=d9b6cec3eb561db6f920a0797ba49f3e'


text:
Q: How to use substitute function with query function in google spreadsheet I am trying to use substitute function inside a query function but not able to find the correct syntax to do that. My use case is as follows.
I have two columns Name and Salary. Values in these columns have comas ',' in them. I want to import these two columns to a new spreadsheet but replace comas in "Salary" column with empty string and retain comas in "Name" column. I also want to apply value function to "Salary" column after removing comas to do number formatting.
I tried with the following code but it is replacing comas in both the columns. I want a code which can apply the substitute function only to a subset of columns.
Code:
=arrayformula(SUBSTITUTE(QUERY(IMPORTRANGE(Address,"Sheet1!A2:B5"),"Select *"),",",""))

Result:
Converted v/s Expected Result
Note :
I have almost 10 columns to import and comas should be removed from 3 of them.

A: Based on your suggestions, I was able to achieve the objective by treating columns separately. Below is the code.
=QUERY({IMPORTRANGE(Address,"Sheet1!A3:A5"),arrayformula(VALUE(SUBSTITUTE(IMPORTRANGE(Address,"Sheet1!B3:B5"),",","")))},"Select * where Col2 is not null")

Basically, two IMPORTRANGE functions side by side for each column.
The same query on the actual data with 10 columns will look like this.
=QUERY({IMPORTRANGE(Address,"Sheet1!A3:C"),arrayformula(VALUE(SUBSTITUTE(IMPORTRANGE(Address,"Sheet1!D3:H"),",",""))),IMPORTRANGE(Address,"Sheet1!I3:J")},"Select * where Col2 is not null")

I used 3 IMPORTRANGE functions so that I can format the columns D to H by removing comas and changing them to number.

A: My suggestion is to use 2 formulas and more space in your sheets.
Formula #1: get the data and replace commas:
=arrayformula(SUBSTITUTE(IMPORTRANGE(Address,"Sheet1!A2:B5"),",",""))
Formula #2: to convert text into numbers:
=arrayformula (range_of_text_to_convert * 1)
Notes:

*

*using 2 formulas will need extra space, but will speed up formulas (importrange is slow)

*the second formula uses math operation (*1) which is the same as value formula.

A: Try this. I treats the columns separately.
=arrayformula(QUERY({Sheet1!A2:A5,SUBSTITUTE(Sheet1!B2:B5,",","")},"Select *"))

A: Thanks to Ed Nelson, I was able to figure out this:
=arrayformula(QUERY({'Accepted Connections'!A:R,SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE('Accepted Connections'!A:R,"AIF®",""),"APA",""),"APMA®",""),"ASA",""),"C(k)P®",""),"C(k)PS",""),"CAIA",""),"CBA",""),"CBI",""),"CCIM",""),"","")},"Select *"))

That removed all the text I didn't need in specific columns.


text:
Q: Event detection on opaque pixels in JButton I have a class extending JButton that I am trying to apply a .png image to.
The image is irregular in shape, and is surrounded by transparent pixels. I have overridden the paintComponent() method in the JButton to apply my buffered image to the button. Right now, the image is the only thing being drawn, which is what I want.
However, the button is still detecting events in the rectangle around it. Is there a way to limit detection to only the area containing opaque pixels (or rather to not detect events on the transparent pixels)?
Code for button class is below.
public class DrawButton extends JButton{

    private BufferedImage bi;

    public DrawButton(BufferedImage bi){
        setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
        this.bi = bi;
    }

    @Override
    protected void paintComponent(Graphics g){
        g.drawImage(bi, 0, 0, null);
        g.dispose();
    }
}

A: Well I would suggest using a MouseAdapter, and override mouseClicked(..). In mouseClicked check if pixel is alpha at point of click if it is do nothing, if not do something.

*

*Always call super.paintComponent(..) as first call in overriden paintComponent method, but because, especially with buttons, this will redraw the JButton background call setContentAreaFilled(false) on JButton instance to stop this. You may also want setBorderPainted(false) too.

Here is a small example I made (adapted from here):

if click on smiley:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class TransparentButton {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                final JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                MyButton button = null;

                try {
                    button = new MyButton(scaleImage(100, 100, ImageIO.read(new URL("http://2.bp.blogspot.com/-eRryNji1gQU/UCIPw0tY5bI/AAAAAAAASt0/qAvERbom5N4/s1600/original_smiley_face.png"))));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                button.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent me) {
                        super.mouseClicked(me);
                        MyButton mb = ((MyButton) me.getSource());
                        if (!isAlpha(mb.getIconImage(), me.getX(), me.getY())) {
                            JOptionPane.showMessageDialog(frame, "You clicked the smiley");
                        }
                    }

                    private boolean isAlpha(BufferedImage bufImg, int posX, int posY) {
                        int alpha = (bufImg.getRGB(posX, posY) >> 24) & 0xFF;
                        return alpha == 0;
                    }
                });

                frame.add(button);

                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    public static BufferedImage scaleImage(int w, int h, Image img) throws Exception {
        BufferedImage bi;
        bi = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
        Graphics2D g2d = (Graphics2D) bi.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
        g2d.drawImage(img, 0, 0, w, h, null);
        return bi;
    }
}

class MyButton extends JButton {

    BufferedImage icon;

    MyButton(BufferedImage bi) {
        this.icon = ((BufferedImage) bi);
        setContentAreaFilled(false);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(icon.getWidth(), icon.getHeight());
    }

    public BufferedImage getIconImage() {
        return icon;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(icon, 0, 0, this);
    }
}


text:
Q: MS SQL Bridge Table Constraints Greetings -
I have a table of Articles and a table of Categories.
An Article can be used in many Categories, so I have created a table of ArticleCategories like this:

*

*BridgeID int (PK)

*ArticleID int

*CategoryID int
Now, I want to create constraints/relationships such that the ArticleID-CategoryID combinations are unique AND that the IDs must exist in the respective primary key tables (Articles and Categories).
I have tried using both VS2008 Server Explorer and Enterprise Manager (SQL-2005) to create the FK relationships, but the results always prevent Duplicate ArticleIDs in the bridge table, even though the CategoryID is different.
I am pretty sure I am doing something obviously wrong, but I appear to have a mental block at this point.
Can anyone tell me please how should this be done?
Greaty appreciated!

A: Don't use a BridgeId column.
Make a composite primary key (aka compound key) from your ArticleId and CateogryId, that will ensure each combination is unique.
Make each column a foreign key to the corresponding table, and that completes your set of constraints.

A: Ok first you do a unique index on ArticleID, CategoryID.
Then you set up a foreign key constraint on articleID linking it back to the Article table. and then do the same for CategoryID and Catgory table.
Your description sounds like you are creating the PK on the Bridge table and the FK on the other table which is why it wouldn't work.

A: Expanding on HLGEM's solution you would have something like:
Create Table ArticleCategories
(
    Id int not null Primary Key Clustered
    , ArticleId int not null
    , CategoryId int not null
    , Constraint UK_ArticleCategories_Unique ( ArticleId, CategoryId )
    , Constraint FK_ArticleCategories_Articles
        Foreign Key ( ArticleId )
        References Articles( Id )
    , Constraint FK_ArticleCategories_Categories
        Foreign Key ( CategoryId )
        References Categories( Id )
)


text:
Q: Appending php array for desired row outputs I am building a friends list of logged in user verified by session id. I have code that query's, results, and loops perfectly. BUT, it is posting an integer (maybe the id#?), (as this is my unique identifying condition of the select query) AND what I want is to output the (users) table rows of "firstname" and "lastname" instead of the user-id!
Sounds simple enough, yet, I lack the knowledge to make it work! So, here I am inquiry from the world of coders for help! Any assistance would be greatly appreciated!
Here is my code:
// Get Friend Array
$sql = "SELECT * FROM users
        INNER JOIN friends
        ON users.id = friends.id
        WHERE (friends.user1='$u' OR friends.user2='$u' AND friends.accepted='1')";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
        array_push($my_friends, $row["user2"]);
        array_push($my_friends, $row["user1"]);
        }

        //remove your id from array
        $my_friends = array_diff($my_friends, array($u));
        //reset the key values
        $my_friends = array_values($my_friends);
        mysqli_free_result($query);
        // Loop through $my_friends array and build results
        foreach($my_friends as $friends => $v2);
        $friends .= '   ';
}

Here is my html code:

        <?php
            echo "
$friends
";
        ?>

It is the last line of code
$friends .= '   ';that I'm trying to workout. How the syntax of that line should be to add ($row["users.firstname"] and $row["users.lastname"]) and somehow not list the user "$id #" that is joining the two tables of (users) and (friends) in the select query!
It may be that I need a different array altogether for what I want, and If you know of the right way to do this, please inform me of how to do it...Thank you all!

A: What I understood that you are missing User's id in row. This issue is because php array can not have two keys with same name.
Change you query little bit like below
$sql = "SELECT *, friends.id as friendsID FROM users
        INNER JOIN friends
        ON users.id = friends.id
        WHERE (friends.user1='$u' OR friends.user2='$u' AND friends.accepted='1')";

Now you will have id' as User Id andfriendsID` as Friend's ID


text:
Q: How to migrate from REST to GDAA Api without losing files? UPDATE:
The question below resulted from a bug in my code (scanning the wrong directory tree), rendering the question irrelevant (and exposing my stupidity in the process). Even if it deserves deletion, I decided to keep it, since the answer (Cheryl Simon's) is correct, valuable and substitutes GDAA's documentation.
THE ORIGINAL QUESTION STARTS HERE:
The app, I've been running for awhile under the DRIVE scope of the REST Api created numerous folders / files in Google Drive.
Now, when building a new version, I switched to the GDAA Api , but none of the files/folders can be found under the FILE scope of the GDAA. It has always been my understanding, that the FILE scope has access to the Drive objects created by the app. Needles to say I did not modify the SHA1 / PackageName combination in the Developer Console.

A: File scope access is based on the developer console project.  If the same developer console project is used for your app using the REST api and the GDAA app, then you should be able to access files from either.


text:
Q: Need to replace only display cable or entire display? I have a Dell n5110. On startup I hear 8 beeps, the monitor shows only black screen. I pressed the 'D' key and the monitor flashed in different colors.
It happened me this a couple of times ago but I managed somehow to make it work. Now it works only with external monitor.
I red some articles on web and understood that if the monitor shows colors (on pressing D) the display is fine, it is just the cable.
My question is: how can I be sure that the display is fine and I only need to replace the display cable?
Or is there any other fix or details I am missing?

A: Eight beeps means a display failure.
Since the external monitor works, you know it's not a fault with the video card.
When holding down the D key and Powering the notebook on gets
solid colors on the screen, this means that the LCD is good and the problem
is with the video cable.
But as even this method does not work any more, the problem can be anything
at all. Maybe a repair-man could do better.


text:
Q: Server 2012 R2 Remote Desktop Services - IE11 Scrolling getting stuck Recently, a number of our remote desktop users on 2012 R2, have been finding IE 11 occassionaly gets into a state whereby they can't scroll up or down on a page they have been working on.
Mouse wheel doesn't work, arrow keys don't work, and while you can click on the vertical scrollbar and it darkens (to indicate it has been clicked on), when dragging it up and down it doesn't move.
Refreshing the page, or sometimes duplicating the tab, seems to resolve the issue.
Is anyone aware of any recent updates that may have introduced this issue? We aren't clear on when the issue started, so we don't know how far back to check on our updates that have been installed.


text:
Q: QHE from Kubo's formula I'm following David Tong's lectures on the Quantum Hall Effect, in which he rederives the TKNN formula using the Kubo formula.
The notes are a understandably hand-wavy with notation, so let me provide some preliminaries.
Preliminaries.
Consider a single particle Hamiltonian $H$ on a 2d torus of length $L$ in each direction. Attach a square lattice to the 2d torus, with unit cell of length $a$ so that $L=Na$, so that the Hamiltonian $H$ is translationally invariant under the lattice.
We then know from Bloch's theorem that there exist Bloch states $\psi_{k\alpha}=|k \alpha\rangle$ which diagonalize $H$ where $k \in \text{Brillouin Zone}$. Therefore, at zero temperature, the Kubo formula tells us that
$$
\sigma_{xy}= \frac{1}{iL^2}\sum_{E_{k\alpha} <E_F <E_{k'\alpha'}} \frac{\langle k\alpha|J_x|k'\alpha'\rangle\langle k'\alpha'|J_y|k\alpha\rangle-\text{c.c.}}{(E_{k'\alpha'}-E_{k\alpha})^2}
$$
where the summation is over $k,\alpha,k',\alpha'$ such that $|k\alpha\rangle$ are filled band states and $|k'\alpha'\rangle$ are unfilled. This follows from the fact that the many-body Hamiltonian $H^\text{sq}$ is just the non-interacting sum of the single particle Hamiltonians $H$. Notice that by definition, the current of a gauge-invariant Hamiltonian $H[A]$ is defined as,
$J=-\partial H[A]/\partial A$. Also notice that by gauge invariance, we have
$$
H_k[A] \equiv e^{ik\hat{r}} H[A] e^{-ik\hat{r}} = H[A+k]
$$
where I use the hat notation to indicate that $\hat{r}$ is the position operator. Therefore,
$$
J=- \left. \frac{\partial}{\partial p} \right|_{p=0} H_p[A]
$$
Substituting this back into the Kubo formula, we can focus on the term
$$
-\langle k\alpha|J_x|k'\alpha'\rangle=  \langle k\alpha|  \left(\left. \frac{\partial}{\partial p} \right|_{p=0} H_p \right)|k'\alpha'\rangle
$$
Where I have dropped the $A$ for simplicity.
Question. To prove the TKNN formula, we need that
$$
\langle k\alpha|J_x|k'\alpha'\rangle= (E_{k'\alpha'}-E_{k\alpha})\langle \psi_{k\alpha}|\left.\frac{\partial}{\partial p_x}\right|_{p=k'}\psi_{p\alpha'}\rangle
$$
However, I can't understand why. Indeed, ignoring the fact that $p$ can be arbitrarily small, while $k'$ can only be in the BZ, we still have
\begin{align}
J_x &= i[\hat{x},H] \\
\langle k\alpha|J_x|k'\alpha'\rangle &= (E_{k'\alpha'}-E_{k\alpha}) \langle k\alpha|i\hat{x}|k'\alpha'\rangle
\end{align}
Now if the Bloch states were just plane waves $|k\alpha\rangle \propto e^{ikx}$, then the statement holds since $i\hat{x}\mapsto \partial_{k_x}$ in momentum space. However, in general, what we have is that $|k\alpha\rangle = e^{ikr} u_{k\alpha}(r)$ for some lattice periodic $u_{k\alpha}$, and so I don't quite understand why the statement is true.

A: I don't think the equation you're trying to prove is correct - or at least, it's not exactly what you want. I would instead do the following.
Let $H_p \equiv e^{-i p \hat{r}}He^{i p \hat{r}}$, opposite your convention. We have
$$\langle k \alpha |  J_x | k' \alpha' \rangle = \frac{\partial}{\partial p_x} \langle k \alpha |  H_p | k' \alpha' \rangle |_{p=0}.$$
Now focus on the matrix element $\langle k \alpha |  H_p | k' \alpha' \rangle$. First, it is zero unless $k = k'$. (See the addendum below.) Second, $| k \alpha \rangle \propto e^{i k \hat{r}} | u_{k\alpha} \rangle$, where $| u_{k\alpha } \rangle$ is the cell periodic function. All together,
$$ \langle k \alpha |  H_p | k' \alpha' \rangle = \delta_{kk'}
\langle u_{k \alpha}| H_{p+k} | u_{k \alpha'} \rangle$$
Implicit in the equation above is the fact that on the left hand side, the inner product is an integral over the whole sample, whereas on the right hand side it is an integral over one unit cell.
At this point, we have
$$\langle k \alpha |  J_x | k' \alpha' \rangle = \frac{\partial}{\partial p_x} \langle u_{k \alpha}| H_{p+k} | u_{k \alpha'} \rangle|_{p=0} \delta_{k k'} \\
=\langle u_{k \alpha}| \left(\frac{\partial}{\partial k_x} H_{k} \right) | u_{k \alpha'} \rangle \delta_{k k'}.
$$
Now we can follow Tong's notes to get
$$\langle k \alpha |  J_x | k' \alpha' \rangle =
\langle u_{k \alpha}| \left(\frac{\partial}{\partial k_x} H_{k} \right) | u_{k \alpha'} \rangle \delta_{k k'} \\
= \left[ \langle u_{k \alpha}| \left(\frac{\partial}{\partial k_x} H_{k}  | u_{k \alpha'} \rangle \right)  -
\langle u_{k \alpha}|  H_{k}  \left(\frac{\partial}{\partial k_x}| u_{k \beta} \rangle \right) \right] \delta_{k k'} \\
= (E_{k \alpha} - E_{k \alpha '}) \langle u_{k \alpha} |\left(\frac{\partial}{\partial k_x}| u_{k \alpha'} \rangle \right) \delta_{kk'}
$$
This final equality is the correct version of what you want.
Addendum
The idea behind $\langle k \alpha |  H_p | k' \alpha' \rangle = 0$ if $k \ne k'$ is that $H_p$ carries zero crystal momentum, so it cannot connect states with distinct crystal momentum. Formally:
Let $T_R$ denote the operator which translates by lattice vector $R$. Write
$$\langle k \alpha |  H_p | k' \alpha' \rangle =
(\langle k \alpha | T_R^{\dagger}) (T_R  H_p T_R^{\dagger}) (T_R | k' \alpha' \rangle).$$
Since $| k \alpha \rangle $ has crystal momentum $k$, $T_R| k \alpha \rangle = e^{-ikR}| k \alpha \rangle$. We also have
$$ T_R H_p T_R^{\dagger} = (T_R e^{-ip\hat{r}} T_R^{\dagger}) (T_R H T_R^{\dagger}) (T_R e^{ip\hat{r}} T_R^{\dagger})
\\
= e^{-ip(\hat{r} - R)} H e^{ip(\hat{r} - R)} \\
= H_p
$$
The second line above follows from the fact that $H$ is invariant under lattice translations and from $T_R\hat{r}T_R^{\dagger} = \hat{r} - R$, which is essentially the definition of translation. (You could alternatively use the BCH formula.)
Hence for all lattice vectors $R$,
$$ \langle k \alpha |  H_p | k' \alpha' \rangle  = e^{i(k-k')R}\langle k \alpha |  H_p | k' \alpha' \rangle  $$
which for $k \ne k'$ (modulo reciprocal lattice vectors) implies $\langle k \alpha |  H_p | k' \alpha' \rangle = 0$.


text:
Q: wrong values insertion in database i have written a programme to insert the values in database. i had taken name, phone, address and email, but only name and phone are inserted in database. in the columns of address and email again name and phone are being inserted.
here's my code.
edit_phone=(EditText)findViewById(R.id.phone);
        edit_name=(EditText)findViewById(R.id.name);
        edit_email=(EditText)findViewById(R.id.email);
        edit_add=(EditText)findViewById(R.id.addr);
        String name1=edit_name.getText().toString();
        String mobile_no1=edit_phone.getText().toString();
        String email1=edit_name.getText().toString();
        String addr1=edit_phone.getText().toString();
        db.execSQL("insert into register values('"+name1+"','"+mobile_no1+"','"+email1+"','"+addr1+"')");
        edit_phone.setText(" ");
        edit_name.setText(" ");
        edit_email.setText(" ");
        edit_add.setText(" ");
        db.close();

A: Change
    String email1=edit_name.getText().toString();
    String addr1=edit_phone.getText().toString();

To
    String email1=edit_email.getText().toString();
    String addr1=edit_add.getText().toString();

A: Here's where your problem lies:
String email1=edit_name.getText().toString();
String addr1=edit_phone.getText().toString();

You're storing the name in the email variable, and the phone in the address variable.


text:
Q: how to execute immediate sql string to shows result direcly? I'm trying to execute sql string be executed like this image1

but. when I execute immediate my sql string, it doesn't return to any output like the first one.
how can I make it return the output without pass the output into a variable? please help

A: Since you are in 12c, try DBMS_SQL.RETURN_RESULT using a REFCURSOR over any dynamic query.
DECLARE
     sqlstring   VARCHAR2(2000);
     cur         SYS_REFCURSOR;
     tab_name    VARCHAR2(100) := 'YOUR_TAB_NAME';
     col_name    VARCHAR2(32)  := 'COL_NAME';
     n           INT := 5;
     m           INT := 10;
BEGIN
     sqlstring :=   'SELECT '||col_name||',col1,col2,col3 FROM ' || tab_name
               || ' OFFSET ' || n || ' ROWS FETCH NEXT '
                             || m || ' ROWS ONLY ';
     OPEN cur FOR sqlstring;
     dbms_sql.return_result(cur);
END;
/


text:
Q: Could not load package intervention/image in http://packagist.org I don't know why, but I have this error when I try to install intervention/image in Laravel:
[RuntimeException] Could not load package intervention/image in http://packagist.org: [UnexpectedValueException] Could not parse version constraint 4.x.x: Invalid version string "4.x.x"

A: I resolved that by updating composer itself first.
composer self-update


text:
Q: Alternatives to geolocation for detecting users location My website needs to detect the users country so I can then hone the content to this country.
Previously I tried geolocation but I think this had a negative affect on SEO and also led to a delay when the user first loaded the site.
I'm looking to detect country in another way e.g. perhaps via information available in the users browser if possible.
Has anyone detected the user location successfully without using geolocation?

A: One alternative would be to use the user's IP address, but this can be unreliable:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=325


text:
Q: php notice array to string conversion I have an error with my function.
Notice: Array to string conversion in....
Just I wanna check array availability & return if have. I have searched but, I can't do.
Here is my function:
function if_array_exists($array,$value) {
    if(isset($array[$value]) || array_key_exists($value,$array)) {
        $result=array();
        $result[0]=$value;
        return $result;
    } else {
        return '<!--- no array named as '.$value.' value in ---!>';
    }
}

A: If you check to see if it's an actual array first, that should prevent the notice (because it will skip directly to the else.
function if_array_exists($array,$value) {
    if(is_array($array) && (isset($array[$value]) || array_key_exists($value,$array))) {
        $result=array();
        $result[0]=$value;
        return $result;
     } else {
        return '<!--- no array named as '.$value.' value in ---!>';
    }
}


text:
Q: setVisibilty to visible from gone not updated in real time I'm trying a simple act of changing a layout visibility from 'gone' to 'visible'.
the flow is quite simple, clicking on a 'fab' will change the visibilty of a specific layout (in this case: 'threeVal_layout') from gone to visible.
For some reason, the code is working when running without debugging(which means the layout does change to visible), but once I use debug mode the layout is not updated after the code is executed, only after I return to the screen and click on the fab one more time.
I do see the error attached in the image inside View.class, once I step in the 'setVisiblty' function.
my code:
public class SubmitStringsActivity extends AppCompatActivity{
RandomFunctions randomFunc = new RandomFunctions();
EditText firstVal,secVal,thirdVal;
TextInputLayout firstVal_layout,secVal_layout;
public static TextInputLayout threeVal_layout;
FloatingActionButton btn_go,btn_add;
Integer minValOpt= 0;
String firstChoErr,secChoErr,strResult;
public static String[] choicesArr = new String[2];    //Initialize array for 2 since minimum options is 2

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_strings);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    /*First Value*/
    firstVal = findViewById(R.id.firstVal);
    firstVal_layout = findViewById(R.id.firstVal_layout);
    /*Second Value*/
    secVal = findViewById(R.id.secVal);
    secVal_layout = findViewById(R.id.secVal_layout);
    /*Third Value*/
    thirdVal = findViewById(R.id.thirdVal);
    threeVal_layout = findViewById(R.id.threeVal_layout);

    btn_add = findViewById(R.id.fab_add);
    btn_add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            threeVal_layout.setVisibility(View.VISIBLE);
            threeVal_layout.invalidate();
            RandomFunctions.addChoiceOption();
        }
    });         btn_go = findViewById(R.id.button);
    btn_go.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(), DisplayResultActivity.class);
            // Clean any errors
            firstVal.setError(null);
            // minVal_layout.setErrorEnabled(false);
            secVal_layout.setError(null);
            // maxVal_layout.setErrorEnabled(false);
            //       _End_
            if (firstVal.getText().toString().equals("")) {
                firstChoErr= getString(R.string.emptyChoiceStr);   /**Get the error string from the res*/
                firstVal_layout.setError(firstChoErr);    /**Set error in case minimum value is empty*/
                return;
            }
             else if (secVal.getText().toString().equals("")){
                secChoErr= getString(R.string.emptyChoiceStr);
                secVal_layout.setError(secChoErr);    /**Set error in case maximum value is empty*/
                return;
            }

            else  {
                /** Called when the user taps the Go button */

                    choicesArr[0] = (firstVal.getText().toString());
                    choicesArr[1] = (secVal.getText().toString());
                    int resVal = randomFunc.calculateNums(minValOpt, choicesArr.length-1); //Send minimum and maximum values to random function
                    strResult = choicesArr[resVal];
                    intent.putExtra("intValName", strResult);
                    startActivity(intent);
                    //finish();
                    }
        }
    }

    );
}

}
XML:
<LinearLayout
    android:id="@+id/linearStringLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="56dp"
    android:background="@color/mainBackGroundHalf1"
    android:gravity="center"
    android:orientation="vertical"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/firstVal_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:gravity="center"
        app:layout_constraintEnd_toEndOf="@+id/linearStringLayout"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/linearStringLayout">

        <EditText
            android:id="@+id/firstVal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="8dp"
            android:backgroundTint="@color/inputText"
            android:ems="10"
            android:hint="@string/firstString"
            android:imeOptions="actionDone"
            android:inputType="text"
            android:maxLength="9"
            android:selectAllOnFocus="false"
            android:singleLine="true"
            android:textAlignment="center"
            android:textAppearance="@android:style/TextAppearance.Material"
            android:textColorHint="@color/inputText"
            app:layout_constraintBottom_toBottomOf="@+id/linearStringLayout"
            app:layout_constraintHorizontal_bias="0.502"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent" />

    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/secVal_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:gravity="center"
        app:layout_constraintEnd_toEndOf="@+id/linearStringLayout"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/firstVal_layout">

        <EditText
            android:id="@+id/secVal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:backgroundTint="@color/inputText"
            android:ems="10"
            android:hint="@string/secondString"
            android:inputType="text"
            android:maxLength="9"
            android:selectAllOnFocus="false"
            android:singleLine="true"
            android:textAlignment="center"
            android:textAppearance="@android:style/TextAppearance.Material"
            android:textColorHint="@color/inputText" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/threeVal_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:gravity="center"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="@+id/linearStringLayout"
        app:layout_constraintEnd_toEndOf="@+id/linearStringLayout"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/secVal_layout">

        <EditText
            android:id="@+id/thirdVal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="8dp"
            android:backgroundTint="@color/inputText"
            android:ems="10"
            android:hint="@string/threeString"
            android:imeOptions="actionDone"
            android:inputType="text"
            android:maxLength="9"
            android:selectAllOnFocus="false"
            android:singleLine="true"
            android:textAlignment="center"
            android:textAppearance="@android:style/TextAppearance.Material"
            android:textColorHint="@color/inputText"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="@+id/linearLayout"
            app:layout_constraintHorizontal_bias="0.502"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent" />

    </android.support.design.widget.TextInputLayout>
</LinearLayout>


text:
Q: Reading a external XML file using __XPath(${__P(fileName)} I have a situation where in I am trying to read a node value of an external XML. I am using BeanShell sampler to read the fileName (passed via command line) and using setProperty method setting the value of the parsed node:
${__setProperty(variable_name,${__XPath(${__P(fileName)},/Allocations/item/@name)})}

Though the above method retrieves the value of the node I intended to receive, there is a error thrown:

2013/03/19 19:32:59 ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: `` D:\myProject\Jmeter Tests\allocate.xml      ;'' Token Parsing Error: Lexical error at line 2, column 3.  Encountered: "\" (92), after : ""

My xml file looks something like this:
<?xml version="1.0" encoding="UTF-8"?>
<Allocations>
    <item name="CAR" />
</Allocations>

Kindly advice if I am doing some error while reading.

A: Very strange because looks you are doing everything correct.
I've reproduced your scenario step-by-step but works fine for me.
Try to use e.g. Debug Sampler / Debug PostProcessor to monitor your jmeter properties and ensure that fileName normally set from command-line and doesn't contain any extra symbols.


text:
Q: Knockout textbox bound to numeric field I've implemented a form using KnockOutJs but I realize that the textboxes that bind to numeric fields have a default value of '0' (Zero). Is there a way of making the textbox empty by default rather than defaulting to '0' (Zero)?

A: You can just set default textbox value to empty string when define the observable property:
self.myObservableField = ko.observable("");


text:
Q: AdMob Interstitial Landscape-only Orientation I have an [Android, Java] game which runs in landscape orientation and shows AdMob interstitial ads.
I noticed that the ads we displaying in the orientation in which the device was when the app was launched.  For example when using a tablet if the device was held in portrait mode when the app was initially launched but then rotated to landscape (so that the app could be used as it's forced into landscape), the ads would still show in portrait orientation.
I should point out that my app uses the following in the manifest...
<activity
    android:configChanges="keyboardHidden|orientation|screenSize|screenLayout"
    android:screenOrientation="locked"...

The reason for this is that I have a splash theme which I want to show immediately upon launch.  If I lock the app here to landscape (android:screenOrientation="landscape"), there is a noticeable pause before the app actually launches if the device's orientation is portrait... ie, it needs to rotate to landscape.  I found this solution elsewhere on SO.
In onCreate, I use the following to change the orientation...
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

So, everything works as expected... launch, splash shown immediately, apps' orientation changes and loads.
I did some research and learned that I should implement onConfigurationChanged and load a new ad when the rotation had changed, which is what I did...
@Override
public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);

    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        loadInterstitial(); // This is a just my own method which calls the static .load() method and carries a few additional tasks
    }
}

With this in place, all ads apart from the initial one are indeed shown in landscape mode.  This makes sense as I'm loading a new ad when the old one is dismissed.  So if for some reason the current ad is shown in portrait and is dismissed, a new one is requested.  The app then rotates back to its correct orientation (landscape), which triggers the onConfigurationChanged callback which requests a new ad (now a landscape ad as long as the device is now physically in a landscape orientation).
However, what I can't understand is why my initial ad is still loaded in portrait mode.  Here is what I think should happen and what actually does happen...

*

*Tablet held in portrait mode

*App lauched

*Splashscreen shown in portrait mode

*onCreate requests landscape orientation

*Ad is loaded (app still in portrait so portrait ad loaded)

*App (still showing splashscreen), rotates to correct orientation (landscape)... device is rotated to match (now held in landscape so app can be used)

*onConfigurationChanged triggers and re-loads ad (should now load landscape ad, but doesn't seem to)

*Ad loaded above shows (in portrait mode)

It's extremely frustrating.  If I remove 'lock' from my manifest then the ads are OK (even the initial one)...  (See edit), but then I have the horrible dead-time on app cold start when a rotation is required.
It seems that even though the orientation has changed, AdMob still uses the 'locked' orientation from the manifest and still think it's in portrait mode.
I've looked all over but can't find a solution.
Help appreciated.  Any code in Java please not Kotlin.
Edit
Above I wrote:

If I remove 'lock' from my manifest then the ads are OK (even the initial one).

This is incorrect.  I meant to say that "if I change 'locked' to 'landscape'" rather than simply "If I remove 'lock'"


text:
Q: Access Request object from REST Is it possible to access the Request object in a REST method under JAX-RS?
I just found out
@Context Request request;

A: On JAX-RS you must annotate a Request parameter with @Context:
 @GET
 public Response foo(@Context Request request) {

 }

Optionally you can also inject:

*

*UriInfo

*HttpHeaders

*SecurityContext

*HttpServletRequest

A: To elaborate on @dfa's answer for alternatives, I find this to be simpler than specifying the variable on each resource method signature:
public class MyResource {

  @Context
  private HttpServletRequest httpRequest;

  @GET
  public Response foo() {
    httpRequest.getContentType(); //or whatever else you want to do with it
  }
}


text:
Q: Is Geralt's Amnesia because I didn't import a Witcher 1 save file? In the opening scene of the game, you meet the Crinfrid Reavers. Dialog with them implies that Geralt met them previously. Geralt claims to have amnesia.
Is this because I did not import a save-file from witcher 1 (and thus the game doesn't know how I "would" have treated them?) or does Geralt truly have amnesia? Did they appear in Witcher 1 at all?

A: Little late to the party, but about the Reavers, its a pretty significant reference if you read the books/short stories. Its the first reference in TW2 to Geralt's relationship to Yennefer (one of the Reavers called her Connifer or some such). The Reavers are in the short story, "Limit of Possibility," which is heavily referenced later in the game. I don't want to spoil it too much but just know that you (Geralt) was a friend of a Golden Dragon (which was also referenced in TW1).
I wouldn't call the Reavers in the short story background characters. They and their leader, Boholt really caused a lot of trouble for Geralt and Yennefer. Theres also kinda a major story and game spoiler related to the Golden Dragon I don't want to ruin.

A: Cinfrid Reavers appeared only in one short story, as far as I can remember, and even there as background characters. Don't know what's their role in the game, but most people familiar with Sapkowski's writing probably wouldn't even remember them. Think of it as a wink to the people 'in the know'.
I don't remember them in the first game.

A: Geralt's amnesia started in the beginning of the first game, it has nothing to do with save files. Geralt doesn't remember most of what happened to him in Sapkovsky's books.
As far as I remember there was no Crinfrid Reavers in the first game.


text:
Q: Endeca "did you mean" navigation How to provide Did you mean suggestions in endeca

A: Firstly you need the -dym flag enabled on your dgraph (this should be set in AppConfig.xml)
Then you need to extract the dym values in your application code, using the following code:
queryResult.getNavigation().getESearchReports().getDYMSUggestions();
This will return a list of ESearchDYMSUggestion objects each of which has a term which can be displayed to the user.
I am sure that you can find a good example of this on the Endeca Support portal.

A: Nty parameter sets the Did You Mean feature for record search in the navigation query.
Java setter method ENEQuery.setNavERecSearchDidYouMean()
Reference: http://docs.oracle.com/cd/E51277_01/Mdex.650/pdf/DevGuide.pdf
For code example refer http://ourownjava.com/endeca/oracle-endeca-extract-tokens-navigation-query-result/


text:
Q: Ruby - Error when trying to parse HTML page using JSON.load(), error 795 or 757 I'm trying to parse a page using JSON.load(), but unfortunately I always get the same error JSON::ParserError: 795: unexpected token at '{"...
It actually works when I don't do the loop. If I set a constant for {page}, let's say 1, it does work. In the loop, it fails.
I assume, there is an error because of the two "{" as I get two Hashes, one for page 1 and one for page 2. Am I right?
Here is my code:
@dl_page = []
(1..2).each do |page|
  puts "Loading page #{page}..."
  @dl_page << [ `(curl --url "https://angel.co/video?page=#{page}&sort=joined" -H "X-Requested-With: XMLHttpRequest")` ]
  @result = "#{@dl_page.join}"
end

html = JSON.load(@result)["html"]

Many thanks for your help!

A: In your code @result looks like: "{"html": "<...>"}{"html": "<...>"}". It is not valid JSON.
If you need to concatenate html from both requests:
@dl_page = (1..2).map do |page|
  puts "Loading page #{page}..."
  `(curl --url "https://angel.co/video?page=#{page}&sort=joined" -H "X-Requested-With: XMLHttpRequest")`
end

@result = "[#{@dl_page.join(',')}]"

html = JSON.load(@result)
# => [{"html": "<...>"}, {"html": "<...>"}]

A: What went wrong
First, let's look at what's happening in your code. Here's your loop:
@dl_page = []
(1..2).each do |page|
  @dl_page << [ `(curl --url "https://angel.co/video?page=#{page}&sort=joined" -H "X-Requested-With: XMLHttpRequest")` ]
  @result = "#{@dl_page.join}"
end

Let's assume that your curl command returns a valid JSON object like {"html":"foo"} the first time and {"html":"bar"} the second. Let's unroll your loop:
@dl_page = []

# First iteration

@dl_page << [ '{"html":"foo"}' ]
# => [ [ '{"html":"foo"}' ] ]

@result = @dl_page.join
# => '{"html":"foo"}'

Note that because you appended an array ([ '{"html":"foo"}' ]) to @dl_page with the << operator, @dl_page is now an array with a single element, which itself is an array with a single element. That's probably not what you want. What you probably want is to just append the JSON string itself to the array, i.e. @dl_page << '{"html":"foo"}'.
Note also that I replaced "#{@dl_page.join}" with @dl_page.join. "#{foo}" is never necessary. #{...} is for string interpolation, and you're not interpolating anything here Array#join returns a string, so the above is exactly equivalent to @result = @dl_page.join.
The docs for Array#join are a little vague, but as it turns out [ [ '{"html":"foo"}' ] ].join just returns '{"html":"foo"}'.
As you discovered, if you stop at this point and use JSON.load it works, because @result is a valid JSON object. Let's find out why, after the second iteration, that's no longer the case:
# Second iteration

@dl_page << [ '{"html":"bar"}' ]
# => [ [ '{"html":"foo"}' ], [ '{"html":"bar"}' ] ]

@result = @dl_page.join
# => '{"html":"foo"}{"html":"bar"}'

Now @dl_page is an array with two elements, each of which is itself an array with one element. When you call @dl_page.join, the result is two JSON objects mashed up against one another. Obviously that's not valid, so JSON.load fails.
How to fix it
You have a few superficial problems, like appending an array to @dl_page instead of just a single element, and doing @result = ...inside the loop when really you only need to do it once, after the loop. Those are issues worth fixing.
The real problem here, however, is that you're trying to turn two JSON strings into one JSON string and then parse it, when you should be parsing each JSON string separately:
@result = []

(1..2).each do |page|
  json = `curl --url "https://angel.co/video?page=#{page}&sort=joined" -H "X-Requested-With: XMLHttpRequest"`
  @result << JSON.parse(json)
end

Assuming, again, that the curl system call returns {"html":"foo"} the first time and {"html":"bar"} the second, now the value of @result will be an array with two elements, each of which is a Ruby hash:
p @result
# => [ { "html" => "foo" }, { "html" => "bar" } ]

If you just wanted the values of the "html" key, you could instead do this:
@result = []
(1..2).each do |page|
  json = `(curl --url "https://angel.co/video?page=#{page}&sort=joined" -H "X-Requested-With: XMLHttpRequest")`
  @result << JSON.parse(json)["html"]
end

Now the value of @result will be an array with two strings in it:
p @result
# => ["foo", "bar"]

We can still do better, however. It's usually the case in Ruby that if you create an empty object outside of a loop and then, inside the loop, add things to that object, you should use Enumerable#map or Enumerable#reduce instead:
@result = (1..2).map do |page|
  json = `curl --url "https://angel.co/video?page=#{page}&sort=joined" -H "X-Requested-With: XMLHttpRequest"`
  JSON.parse(json)["html"]
end

p @result
# => ["foo", "bar"]


text:
Q: What can I turn off on windows XP to free up memory without breaking everything I seem to have a lot of services that start up on windows, many of which I have no use of (to my knowledge). are there any services which are on by default which I won't really miss and which will free up my system so it works a bit better.
This question is specific to XP, I have a vista laptop which I will ask the same question for.

A: Try BlackViper for some good configurations of varying levels for most Windows OSs. For example, XP SP3 is here.
Also, try using the Autoruns tool from Sysinternals to get rid of Adobe and QuickTime startup apps.
Then, uninstall all apps you don't use. Really - do you use that Noughts-and-crosses game all that often?
Finally, use lightweight equivalents of big apps - Foxit Reader instead of Adobe Reader.


text:
Q: Managing old computer accounts in AD We have a moderately sized AD installation with approx 1000 employees and maybe 1800 valid computer accounts (servers, PCs, virtuals).  Because we replace desktop hardware on a 3-4 yr cycle, cleaning up old computer accounts is a necessary task that usually get's put off.  We currently have 3200 accounts!).  We have a robust process in place for identifying unused user accounts and disabling/deleting them, but nothing in place for computer accounts.
We know about tools like oldcomp, powershell, etc and we even have a windows batch script which uses dsquery and dsrm to handle this, but we've not actually production-alized anything.
My question is simple - What process do you use to clean up these accounts?

A: PowerShell + dsquery. Really. Very short pipeline, runs fast. Use DSQuery to generate a list of computer accounts that haven't logged in in $days, run it through whatever exception list we have going, then send the output through dsrm. Works a treat, and we can even create a log-file showing which machines got deleted when.

A: My first initial thought would be - to not put disabling computer accounts on the back burner, if that then raises concerns later. Simply make it a procedure to disable computer accounts (and move them a Unused Comps OU for example).
Furthermore we still do check AD and apart from powershell, we use ADtidy, a simple but very effective tool ( http://www.cjwdev.co.uk/Software/ADTidy/Info.html)
We run this manually but we have a reminder in our shared calendar -so that this task gets done on a regular basis (every 4 months is ok for us)


text:
Q: select series from transposed pandas dataframe With a dataframe, called mrna as follows:
id      Cell_1  Cell_2  Cell_3
CDH3    8.006   5.183   10.144
ERBB2   9.799   12.355  8.571
...

How can I select the ERBB2 row as a pandas series (if I don't know its index)?
I tried:
mrna.iloc['ERBB2'] but that only takes a integer, and doesn't map to string
I also tried:
mrna_t = mrna.transpose()
mrna_t['ERBB2']

but I get KeyError: 'ERBB2'

A: Pass a boolean condition to generate a boolean mask, this mask is used against the index and will return just the rows where the condition is met:
In [116]:
df[df['id']=='ERBB2']

Out[116]:
      id  Cell_1  Cell_2  Cell_3
1  ERBB2   9.799  12.355   8.571

Output from boolean condition:
In [117]:
df['id']=='ERBB2'

Out[117]:
0    False
1     True
Name: id, dtype: bool

As for your error: mrna_t['ERBB2'] will attempt to look for a column with that name which doesn't exist hence the KeyError
If it was your index then you could just do:
df.loc['ERBB2']

To select index values matching the passed label, it's worth checking the docs, including the section on index selection by position and label

A: Just figured it out.  I just reset the index labels then transposed.  This allowed me to index by "ERBB2".
mrna.set_index('id').T


text:
Q: Who is this character laying on Qyburn's table? In the 5th season, we see this scene:

 https://vine.co/v/eW9bUtEBJO6

As displayed in the picture:

But, it appears to me that this has not yet been re-visited and I'm still clueless as to who he is, and what he actually had tied onto the bed.

A: That person is Ser Gregor Clegane, aka The Mountain (or as in the books, Ser Robert Strong). After his duel with Prince Oberyn Martell, Gregor was struck with a poisoned spear which was slowly killing him. Qyburn starts using certain magical and medical arts on him, converting him into this:

According to Show Wikia about the event:

A moribund Gregor Clegane is being experimented on by Qyburn at his
  laboratory in the dungeons below the Red Keep. Queen Cersei visits
  Qyburn and asks him about the state of his work, while glancing at
  Gregor's covered body, and Qyburn assures her it is going very well,
  though there is still a way to go. Then, Gregor suddenly spasms, and
  Qyburn gently shushes him and tells him to go easy.

It is not clear exactly what Qyburn did to Gregor to make him come back from the dead but when Jaime asked what Qyburn did in season 6, Qyburn only replied:

A number of things

Since he is already a part of Season 5 & 6, I'd say that his story line has been revisited over and over again. It is not like they left his story dangling there like Gendry's.


text:
Q: Vagrant xenial64 NFS synced dir 'preserve permissions' failure on bcrypt build Looking for help on what extra configuration I can set to allow my ubuntu virtualbox vm to write into the NFS synced project directory on my OSX host. I've set the explicit sudoers for vagrant in macOS so it shouldn't have any issues modifying the host if needed.
End goal is to be able to operate the app's build and dev runtime within ubuntu, while editing the files on the macOS host and the ubuntu box will detect changes and rebuild with gulp as appropriate.
Currently getting an error on npm install for bcrypt when it tries to preserve permissions, but I'm also not sure if this is the root cuase of the full fail.
Cross posted: https://groups.google.com/forum/#!topic/vagrant-up/LS_eFJhZAwQ
Vagrantfile:
Vagrant.configure(2) do |config|
  config.vm.box = "ubuntu/xenial64"
  config.vm.provider "virtualbox" do |v|
    v.memory = "3072"
    v.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/v-root", "1"]
  end

  config.vm.define "dev", primary: true do |dev|
    dev.vm.hostname = "proteus.dev"
    dev.vm.network "private_network", ip: "192.168.10.10"
    dev.vm.synced_folder '.', '/home/ubuntu/src/proteus', nfs: true, mount_options:['nolock,vers=3,udp,noatime,actimeo=1']
    # also tried 'rw' and other linux__mount_options
  end
end

Error output:
$ npm install bcrypt

> bcrypt@1.0.2 install /home/ubuntu/src/proteus/node_modules/bcrypt
> node-pre-gyp install --fallback-to-build

node-pre-gyp ERR! Tried to download(404): https://github.com/kelektiv/node.bcrypt.js/releases/download/v1.0.2/bcrypt_lib-v1.0.2-node-v48-linux-x64.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for bcrypt@1.0.2 and node@6.11.0 (node-v48 ABI) (falling back to source compile with node-gyp)
make: Entering directory '/home/ubuntu/src/proteus/node_modules/bcrypt/build'
  CXX(target) Release/obj.target/bcrypt_lib/src/blowfish.o
  CXX(target) Release/obj.target/bcrypt_lib/src/bcrypt.o
  CXX(target) Release/obj.target/bcrypt_lib/src/bcrypt_node.o
  SOLINK_MODULE(target) Release/obj.target/bcrypt_lib.node
  COPY Release/bcrypt_lib.node
cp: preserving permissions for 'Release/bcrypt_lib.node': Operation not permitted
bcrypt_lib.target.mk:134: recipe for target 'Release/bcrypt_lib.node' failed
make: *** [Release/bcrypt_lib.node] Error 1
make: Leaving directory '/home/ubuntu/src/proteus/node_modules/bcrypt/build'
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/lib/node_modules/node-gyp/lib/build.js:258:23)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:191:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
gyp ERR! System Linux 4.4.0-83-generic
gyp ERR! command "/usr/bin/nodejs" "/usr/lib/node_modules/node-gyp/bin/node-gyp.js" "build" "--fallback-to-build" "--module=/home/ubuntu/src/proteus/node_modules/bcrypt/lib/binding/bcrypt_lib.node" "--module_name=bcrypt_lib" "--module_path=/home/ubuntu/src/proteus/node_modules/bcrypt/lib/binding"
gyp ERR! cwd /home/ubuntu/src/proteus/node_modules/bcrypt
gyp ERR! node -v v6.11.0
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/bin/nodejs /usr/lib/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --module=/home/ubuntu/src/proteus/node_modules/bcrypt/lib/binding/bcrypt_lib.node --module_name=bcrypt_lib --module_path=/home/ubuntu/src/proteus/node_modules/bcrypt/lib/binding' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/home/ubuntu/src/proteus/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at emitTwo (events.js:106:13)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:191:7)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:891:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
node-pre-gyp ERR! System Linux 4.4.0-83-generic
node-pre-gyp ERR! command "/usr/bin/nodejs" "/home/ubuntu/src/proteus/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /home/ubuntu/src/proteus/node_modules/bcrypt
node-pre-gyp ERR! node -v v6.11.0
node-pre-gyp ERR! node-pre-gyp -v v0.6.32
node-pre-gyp ERR! not ok
Failed to execute '/usr/bin/nodejs /usr/lib/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --module=/home/ubuntu/src/proteus/node_modules/bcrypt/lib/binding/bcrypt_lib.node --module_name=bcrypt_lib --module_path=/home/ubuntu/src/proteus/node_modules/bcrypt/lib/binding' (1)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm ERR! Linux 4.4.0-83-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "bcrypt"
npm ERR! node v6.11.0
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE

A: I had a simular problem once. Try to empty your /etc/exports in your MacOS.
I don't have mount_options or setextradata.
I would first try to isolate the problem, first to see why cp didn't work (without npm stuff).
It could be that it's macOS problem that I still have https://github.com/mitchellh/vagrant/issues/8061
Good luck!


text:
Q: bash array with space in element I have a text log file
$ cat aaa
673                  20160405 root "/path_to/gis/20160401/20160301_placement_map_org.dbf" ""
673                  20160405 root "/path_to/gis/20160401/20160310_20160401ent_map_org.dbf" ""
790890               20170201 jle  "/path_to/gis/20160401/Pina (Asc) 20160401 Rapid Report.kmz" ""
5883710              20160406 dho  "/path_to/gis/20160401/20160401_Pina_Asc_Rapid_Report_Minesouth.pdf" ""
673                  20160405 dho  "/path_to/gis/20160401/20160310_20160401 placement map org.dbf" ""

Now I have this script output just the full path of the files:
#!/bin/bash

function nodatechk() {
    arr=("$@")
    for ((i=3;i<${#arr[@]};i+=5));
    do
      echo "${i}" "${arr[i]}"
    done
}

r=( $(grep gis aaa) )

nodatechk "${r[@]}"

The output is break because of the 3rd line (and 5th line) have a space in the element, although it has double quote.
How can I fix this? (BTW I know I can use awk or cut to print out columns, but in this case I just want use grep.) Thanks.

A: The problem has its roots in this line:
 r=( $(grep gis aaa) )

As you will immediately see if you try:
 printf '<%s>\n' $(grep gis aaa)

Which splits on the characters inside "$IFS" (space, tab, newline by default).
And exposes the values from the file to globbing. Which will transform some *, ? and […] (which ones will depend on the list of files on your pwd and the condition of several shell options).
One (not recommended) solution is to change IFS to the split character and disable globbing for the split:
 IFS=$'\n'; set -f; r=( $(grep gis aaa) )

But a simpler solution is to use what the shell already provide:
readarray -t r <(grep gis aaa)

That will split on newlines (assuming there are no newlines in the pathnames).
Then, to avoid splitting each line again to get each part which could expose the line to whitespace splitting and globbing, lets remove the leading and trailing parts of the lines.
If from each line we remove everything from the beginning up to the "/ (double quote and slash) and everything from the " (double quote and space) to the end, we will get a clean pathname:
 #!/bin/bash

 function nodatechk() {
    for l do
        l="/${l#*\"/}"                # Remove leading text up to `"/`
        l=${l%\" *}                   # Remove trailing text from `" `
        printf '%s\n' "$l"
    done
 }

 readarray -t r < <(grep gis aaa)

 nodatechk "${r[@]}"

A: A grep-only solution is
grep gis aaa | grep -o '^[^"]*"[^"]*"' | grep -o '"[^"]*"$'

The first grep is the same as what you have in the question.
Obviously, it selects lines that contain gis (anywhere in the line).
The second grep,
grep -o '^[^"]*"[^"]*"'

matches everything up through (and including)
the first quoted string on the line (i.e., columns 1 through 4),
and, because of the -o option, outputs only those words.
The third grep,
grep -o '"[^"]*"$'

matches the last word quoted string on the line
(which, at this point, is column 4 from the original line)
and outputs only that string.

P.S. If your file has one tab between each pair of columns,
and the values don't contain tabs, the simple way to get the fourth column is
awk -F'\t' '/gis/ { print $4 }' aaa

A: I read this post and I solved the problem by using 'eval'. So changed this line:
r=( $(grep gis aaa) )
to
eval r="( $(grep gis aaa) )"


text:
Q: Prevent click if it is child element Would it be a bad idea to use a boolean to determine if child element was clicked or not? Is there any better method?
Note: I don't want to use jquery for this.
See code below:
<!DOCTYPE html>

<title></title>

Added new version:
In this version I am using addEventListener instead.
var hbWindow = window,
    hbDocument = document,
    hbIdBox = hbDocument.getElementById('box'),
    hbIdContainer = hbDocument.getElementById('container');

hbWindow.onload = function () {

function inOrOut(e){
    if (!e) e = hbWindow.event;
    if((e.target || e.srcElement).id == 'container') {
        alert('you\'re outside!');
    } else {
        alert('you\'re inside!');
    }
}

hbIdContainer.addEventListener('click', inOrOut, false);

}

A: If you wish to know what invoked the click, check event.target. On IE6-8 you would check the window.event.srcElement property.
if ( document.body.addEventListener ) {
  document.body.addEventListener("click", alertMe, false);
} else if ( document.body.attachEvent ) {
  document.body.attachEvent("onclick", alertMe);
}

function alertMe(event) {
  console.log( event.target || window.event.srcElement.nodeName );
}

So while we're attaching the event to the document.body, we can determine by the target (or in some cases the srcElement) which child triggered the click.
Demo: http://jsbin.com/oxuzek/7/edit