text:
Q: Pulling "Now Playing" data from html page So I have a shoutcast server that displays info on this page:
http://soundstreamradio.serverroom.net:7424/
I am trying to pull the "Now Playing" data from this page and display it on my website that is playing the stream through a player.
Clicking on the song title and following this link:
http://soundstreamradio.serverroom.net:7424/currentsong?sid=1
Shows the current song in plain text...
So I'm wondering if there is a javascript or php script I can use to scrape this data to display it in my player?
I've tried AJAX but got cross domain errors and YQL gives me an error of "Invalid URL http://soundstreamradio.serverroom.net:7424/currentsong?sid=1: Invalid HTTP destination port"
I was wondering if there was anyone out there with a better idea to solve this issue?
Thank you so much in advance!

A: I would use preg_match() in PHP,
but it's a bit difficult because this page only
shows the artist name, song, then album(I presume?),
and the only way to separate these would be the " " or "-".
Some songs might have a "-" in them.


text:
Q: Progress Indicator can't stop animating when loading from browser back to iOS application In my application l have a link which opens a browser (Safari), when clicking back from browser back to the application the UIActivityIndicatorView can't stop loading or animating although l implemented it to stop animating.. Any help guys...here is my code
func webViewDidStartLoad(_ : UIWebView){

    let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .Alert)

    alert.view.tintColor = UIColor.blackColor()
    let progressIndicator = UIActivityIndicatorView()

    alert.view.addSubview(progressIndicator)

    let views = ["alert" : alert.view, "progressIndicator" : progressIndicator]
    var constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[progressIndicator]-(-50)-|", options: [] , metrics: nil, views: views)
    constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|[progressIndicator]|", options: [], metrics: nil, views: views)
    alert.view.addConstraints(constraints)

    progressIndicator.userInteractionEnabled = false
    progressIndicator.startAnimating()

    self.presentViewController(alert, animated: true, completion:nil)
}

func webViewDidFinishLoad(_ : UIWebView){
    dismissViewControllerAnimated(false, completion: nil)
       progressIndicator.stopAnimating()
}

A: Alert controller can't dismiss because you present view controller with animation and before the animation did complete web view delegate method func webViewDidFinishLoad(_ : UIWebView) is called.
There are 2 Solution for problem
1) Present alert view controller without animation
self.presentViewController(alert, animated: false, completion:nil)
2) Dismiss alert controller after some milliseconds delay
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.alert.dismissViewControllerAnimated(false, completion: nil) self.progressIndicator.stopAnimating() }
Code Snippet
let progressIndicator = UIActivityIndicatorView() let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .Alert)
func webViewDidStartLoad(_ : UIWebView) {

alert.view.tintColor = UIColor.blackColor()
alert.view.addSubview(progressIndicator)

let views = ["alert" : alert.view, "progressIndicator" : progressIndicator]
var constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[progressIndicator]-(-50)-|", options: [] , metrics: nil, views: views)
constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|[progressIndicator]|", options: [], metrics: nil, views: views)
alert.view.addConstraints(constraints)

progressIndicator.userInteractionEnabled = true
progressIndicator.startAnimating()

// If false then 1 solution will work
self.presentViewController(alert, animated: false, completion:nil)
// If true then 2 solution will work
self.presentViewController(alert, animated: true, completion:nil)
}

func webViewDidFinishLoad(_ : UIWebView) {

// 1 Solution
/*self.alert.dismissViewControllerAnimated(false, completion: nil)
self.progressIndicator.stopAnimating()*/

// 2 Solution
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    self.alert.dismissViewControllerAnimated(false, completion: nil)
    self.progressIndicator.stopAnimating()
}
}

A: It look like the you are referencing to the wrong progressIndicator to stopAnimating().
In the above you have a:
let progressIndicator = UIActivityIndicatorView()

This create a new UIActivityIndicatorView() and you start animating it.
But in the webViewDidFinishLoad, there is no way you can get the progressIndicator instance from above. I am suspecting that you are referencing to a IBOutlet or a class variable. Therefore you are telling the wrong UIActivityIndicatorView() to stop.
If it is a class variable, in the above code, you should replace it with this:
let progressIndicator = UIActivityIndicatorView()
progressIndicator = UIActivityIndicatorView()       //replace above with this

If it is a IBOutlet that is link to a UIActivityIndicatorView() in the storyboard, you should just be calling progressIndicator.startAnimating()
without creating a new one. Therefore just remove the let progressIndicator = UIActivityIndicatorView()

A: may be you need to delete UIActivityIndicatorView
progressIndicator.removeFromSuperview()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python: key error for using user input as dict key When I am taking a user input of the num variable, I am getting a key error. But if I assign a value to that variable, then it's working fine. Why am I getting a key error for taking a user input of the key?
f = open("GUTINDEX.ALL", "r", encoding="utf-8")
string = f.read()
f.close()
bookList = string.split('\n\n')
etextDict = {}
x = len(bookList)
for book in bookList:
    etextDict[x] = book
    x -= 1

num = input('Search by ETEXT NO:')
print(etextDict[num])
num=1
print(etextDict[num])

A: The input is read as a string, while on your use case (when working), num is an integer. Just convert the string to integer:
f = open("GUTINDEX.ALL", "r", encoding="utf-8")
string = f.read()
f.close()
bookList = string.split('\n\n')
etextDict = {}
x = len(bookList)
for book in bookList:
    etextDict[x] = book
    x -= 1

num = input('Search by ETEXT NO:')
print(etextDict[int(num)])  # <- changed this line
num=1
print(etextDict[num])

A: This is happening because the user input is a string (str), whereas the actual key in the dictionary is an integer (int). Try converting it to an integer first:
num = int(input('Search by ETEXT NO:'))

As an aside, you don't need to use a dictionary if you're just looking things up by index. A regular list is easier and faster.


text:
Q: change plot axes Any idea how to change X axis to 0-100?
And also delete that 10^-2 and change Y axis to 0-0.025?
Thanks.

\begin{figure}
\resizebox{\linewidth}{!}{

    \begin{tikzpicture}
    \begin{axis}
    \addplot [ybar interval, mark=no] plot coordinates
    {(0,0.0043973941368078175) (0.1,0.006677524429967427)  (0.2,0.016938110749185668)
         (0.3,0.02280130293159609)  (0.4,0.0250814332247557)  (0.5,0.016042345276872965) (0.6,0.006758957654723126)  (0.7,0.0038273615635179142)  (0.8,0.0028501628664495127)  (0.9,0.0018729641693811076)  (1,0.0018729641693811076)};
    \end{axis}
    \end{tikzpicture}
}
\caption{users' average charge levels at start of charge \cite{hu2019modeling}}
\label{fig:1}
\end{figure}

A: Please have a look at the comments in the code.
% used PGFPlots v1.16
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[
        % don't scale y ticks ...
        scaled y ticks=false,
        % ... and format them properly
        yticklabel style={
            /pgf/number format/.cd,
                fixed,
                fixed zerofill,
                precision=3,
        },
    ]
        \addplot [
            ybar interval,
        % changed `coordinates` to a `table` because then ...
        ] table [
            % ... it is easy to manipulate the values
            x expr=\thisrow{x}*100,
        ] {
            x   y
            0.0 0.0043973941368078175
            0.1 0.006677524429967427
            0.2 0.016938110749185668
            0.3 0.02280130293159609
            0.4 0.0250814332247557
            0.5 0.016042345276872965
            0.6 0.006758957654723126
            0.7 0.0038273615635179142
            0.8 0.0028501628664495127
            0.9 0.0018729641693811076
            1.0 0.0018729641693811076
        };
    \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Reading any file as binary in C++? How might I read any file type as binary in C++? So far, I've been able to read .txt files in binary using std::bitset like so:
std::ifstream myfile;
myfile.open("example.txt", std::ios::binary);
while (getline (myfile, line) ) {
    for (std::size_t i = 0; i<line.size(); ++i) {
        std::bitset<8> a = std::bitset<8>(line[i]); //convert every character to binary, save it in a

        std::cout<<((char)std::bitset<8>(a).to_ulong())<<'\n';
    }
}

In the first line, how might I read a file like sound.mp3 or word.docx as a binary file? I understand that in they really just are binary files, but how can I read them as such?
Thanks!

A: By casting from a block of memory of chars to binary, you can read a file as binary.
std::streampos size;
char * memblock;

std::ifstream myfile ("sound.mp3", std::ios::in|std::ios::binary|std::ios::ate);
//ios::ate puts the reader at the end of the file
if (file.is_open())
{
    size = myfile.tellg();
    memblockChar = new char [size];
    myfile.seekg (0, std::ios::beg);
    myfile.read (memblockChar, size);
    myfile.close();

    for (int i = 0; i<size; i++) {
        std::cout << (((std::bitset<8>)memblockChar[i]).to_ulong()) << '\n';
    }
    delete[] memblockChar;
}
else std::cout<<"Unable to open file"<<std::endl;

This could be used in a main method, or anywhere else.


text:
Q: Excel Pivot Grouping Excel 2013, Windows 10.  Can someone describe the simple act of viewing what data values are included in an existing, renamed grouping?
For example, imagine an Excel sheet containing SKUs and sales of grocery items. So, "apples" are in the data as SKU "1111" with sales of $10.  Oranges are there as "2222" with sales of $20. Some joker first grouped all the apples and oranges into one field, and renamed it "Fruit" using a custom label. Now all I can see is "Fruit" sales of $30.  How do I see whether SKU 3333 ("Bananas") is included in the "Fruit" grouping?
What I want to do is open the sheet and somehow confirm that "Fruit" is a custom name of a grouping containing only SKUs "1111" and "2222".  Can someone advise how I do this before I go completely 3333?
I apologize if this is obvious, duplicate, not a question, uncouth, inappropriate for this forum, not a member of the Group of Seventeen, or some other offense to the rules.  But it's driving me nuts!

A: Just drag the old ungrouped field into the PivotTable alongside the new grouping, and you can see all the items that make it up.


text:
Q: Is it possible to peform thermodynamic work by harvesting entanglement from the vacuum? I have already asked two questions on this topic:
1. What happens to the vacuum when entanglement is harvested? [closed]
and
2. Does entanglement harvesting require cooling the environment to sufficiently low temperatures?
I wonder whether it is at least in theory possible to harvest the entanglement from the vacuum and then use it to perform thermodynamic work, because I read in papers that quantum coherence can be used to perform work [1,2,3]. I have done some research into this topic, however I found that it requires energy to harvest entanglement [4,5]. (The two papers show different costs - not sure about that). The key question is does it require more or less energy to harvest entanglement than can be gained. As expected The harvested entanglement falls off with the distance [6]. However for the application of thermodynamic work gain it is not required to maintain entanglement over large distance.
All in all this idea seems too obvious and it is unlikely that people haven't thought about this yet. So I am guessing there are some complications with this idea. Anyway, I hope someone can clarify my doubt.

Papers on thermodynamic work gain from entanglement
[1] https://www.science.org/doi/10.1126/science.1078955
[2] https://arxiv.org/abs/1207.6872
[3] https://arxiv.org/abs/1009.1630
Papers on entanglement extraction cost
[4] https://quantum-journal.org/papers/q-2019-07-15-165
[5] https://www.nature.com/articles/s41467-018-06153-w
Harvested entanglement falls off with distance
[6] https://arxiv.org/abs/quant-ph/0212044


text:
Q: Tensorflow: Gradient Calculation from Input to Output I would like to calculate the gradients of the output of a neural network with respect to the input. I have the following tensors:
Input: (num_timesteps, features)

Output: (num_timesteps, 1)

For the gradients from the inputs to the entire output vector I can use the following:
tf.gradients(Output, Input)

Since I would like to compute the gradients for every single timesample I would like to calculate
tf.gradients(Output[i], Input)

for every i.
What is the best way to do that?

A: First up, I suppose you mean the gradient of Output with respect to the Input.
Now, the result of both of these calls:

*

*dO = tf.gradients(Output, Input)

*dO_i = tf.gradients(Output[i], Input) (for any valid i)

will be a list with a single element - a tensor with the same shape as Input, namely a [num_timesteps, features] matrix. Also, if you sum all matrices dO_i (over all valid i) is exactly the matrix dO.
With this in mind, back to your question. In many cases, individual rows from the Input are independent, meaning that Output[i] is calculated only from Input[i] and doesn't know other inputs (typical case: batch processing without batchnorm). If that is your case, then dO is going to give you all individual components dO_i at once.
This is because each dO_i matrix is going to look like this:
[[  0.   0.   0.]
 [  0.   0.   0.]
 ...
 [  0.   0.   0.]
 [ xxx  xxx  xxx]     <- i-th row
 [  0.   0.   0.]
 ...
 [  0.   0.   0.]]

All rows are going to be 0, except for the i-th one. So just by computing one matrix dO, you can easily get every dO_i. This is very efficient.
However, if that's not your case and all Output[i] depend on all inputs, there's no way to extract individual dO_i just from their sum. You have no other choice other than calculate each gradient separately: just iterate over i and execute tf.gradients.


text:
Q: Is it possible to override a single domain name using dnsmasq? I have a server application that I'm running two instances of, production and development, namely:
prod.example.com (10.0.0.1)
dev.example.com (10.0.0.2)

A third-party has written a client application which has been hardcoded to point to prod.example.com. But, I want those requests to go to the dev.example.com server and I don't have access to the third-party source code.
I do have access (temporarily) to the LAN that the client and server are running on so I can use dnsmasq to resolve prod.example.com to 10.0.0.2, at which point my work here is done and the client application will be (unknowingly) talking to the development server (or so I thought).
I've gotten as far as adding the following config to dnsmasq.conf..
address=/prod.example.com/10.0.0.2

..which does work, but it has the side-effect of preventing all other domains from resolving.
How can I have my cake and eat it?

A: Add this line to /etc/dnsmasq.conf:
addn-hosts=/etc/dnsmasq.hosts

Then insert your domain names into /etc/dnsmasq.hosts:
10.0.0.1  prod.example.com.
10.0.0.2  dev.example.com.

Don't forget the period at the end of the domain name. It marks it as a TLD, not a local hostname.
As always after configuration changes, restart dnsmasq:
sudo service dnsmasq restart


text:
Q: Extract regex groups from text with bash and output to file I need to scan a log file and extract the relevant parts from it to another file.
The log format is:
   [hh:mm:ss] Header
   [hh:mm:ss] irrelevant text
   [hh:mm:ss] irrelevant text
   [hh:mm:ss]Error text
   [hh:mm:ss] some details
   [hh:mm:ss] end_error;
   [hh:mm:ss] irrelevant text
   [hh:mm:ss] Warning text
   [hh:mm:ss] some details
   [hh:mm:ss] end_warning;
   [hh:mm:ss] irrelevant text
   [hh:mm:ss] irrelevant text
   [hh:mm:ss]Error text
   [hh:mm:ss] some details
   [hh:mm:ss] end_error;

I need to get all occurrences of Error and Warning and capture the following text:
[hh:mm:ss]Error text
[hh:mm:ss] some details
[hh:mm:ss] end_error;
[hh:mm:ss] Warning text
[hh:mm:ss] some details
[hh:mm:ss] end_warning;
[hh:mm:ss]Error text
[hh:mm:ss] some details
[hh:mm:ss] end_error;

What is the simplest way to achieve this on bash?

A: $ awk '/^(Error|Warning)/{f=1} f; /;/{f=0}' file
Error text
end_error;
Warning text
end_warning;

Your original input file showed Error and Warning at the start of each line so my script above has a start-of-line anchor (^) in it. Using your latest posted sample input file and desired output you'd need:
$ awk '
   /^[[:space:]]*\[[^]]+\][[:space:]]*(Error|Warning)/ { found=1 }
   found { sub(/^[[:space:]]+/,""); print }
   /;/ { found=0 }
' file
[hh:mm:ss]Error text
[hh:mm:ss] some details
[hh:mm:ss] end_error;
[hh:mm:ss] Warning text
[hh:mm:ss] some details
[hh:mm:ss] end_warning;
[hh:mm:ss]Error text
[hh:mm:ss] some details
[hh:mm:ss] end_error;

The complexity of the regexp is to avoid false matches if the words Error or Warning appear elsewhere in your input file.

A: Using GNU sed range operator with -n and -r option to suppress default printing and enabling extended regular expression respectively. p flag prints the line that matches the condition.
$ sed -nr '/^(Error|Warning)/,/;/p' file
Error text
end_error;
Warning text
end_warning;

You can do the same in awk too. But using Ed's approach is almost always recommended.
$ awk '/^(Error|Warning)/,/;/' file
Error text
end_error;
Warning text
end_warning;

A: Try:
cat file | awk '/^(Error|Warning)/,/;$/ { print $0 }' > output

This will pipe the file through awk, awk will print lines starting with Error or Warning up to the first line ending with ;, the result will be saved on output


text:
Q: Fast Conversion to Big INT I have a huge number of large databases (300+!) that vary in size from teeny tiny to absolutely massive (120 GB+) in size.  I've already determined a way to generate scripts to decide what indexes, foreign keys, primary keys, and default constraints need to be removed in order to convert a known set of columns from int to bigint data types.
The problem we're running into is on the larger databases, we're hitting 2-3 days runtime on this query, which isn't acceptable in production. Is there a method to make these conversions that is faster than the current drop-change-rebuild process?

A: I had a similar conversion of a key column from int to bigint that involved hundreds of tables, some over 100GB.  I used an approach like the one below, which accomplished the migration a couple of hours against the large client databases. If the database is in the FULL recovery model, make sure sufficient transaction log space exists and/or perform log backups during the migration to avoid filling the log.
1) Drop referencing foreign keys on tables to be modified and schemabound objects
2) Optionally, drop all non-clustered indexes (including non-clustered primary key and non-clustered unique constraint indexes) on tables to be modified to reduce disk space requirements during the migration.
3) For each table, create new table using SELECT...INTO with an explicit CAST of the column to bigint, with ISNULL to coerce a NOT NULL column when necessary. Drop original table and rename new table to original name.
4) Recreate clustered indexes/constraints, non-clustered indexes/constraints, followed by other constraints and objects.


text:
Q: Fingerprint reader espresso test I am trying to make espresso test for fingerprint reading. It is possible for emulator test with such
Runtime.getRuntime().exec("adb -e emu finger touch 1");
However this same code is not working on real devices.
What is the way to do fingerprint reader on espresso test for real devices?

A: I'm sorry but, as far as I know, this is not possible with real devices.


text:
Q: Preserve Document IDs while copying document from one site collection to another Can we preserve the document ID assigned to a document while moving it from one document library in one site collection to another document library in other site collection?
I searched for some answers but they all suggest that the ID is preserved in MOVE operation but not in COPY.
I want to preserve the ID in COPY action.
Is this possible?

A: No.
The document-ID is only maintained when using the Content and Structure page '/_layouts/15/sitemanager.aspx?Source={WebUrl}_layouts/15/settings.aspx'. Or when you create custom (Visual Studio) solution and using code.
Using 'Send to', 'Copy' or 'Move' from the ribbon will in all cases generate a new Document-ID in SP2013.

A: It should be possible. Please see this link.
Answer from link:

According to your description, my understanding is that you want to
  preserve the Document ID when moving the documents across site
  collections.
Per my knowledge, the document id will be preserved when the document
  has been moved from one Site Collection to another Site Collection.
During move operations, SharePoint Server 2010 keeps the document ID.
  During copy operations SharePoint Server 2010 assigns a new document
  ID. You can control this by setting a Boolean operator on the
  PersistID column.

A: Documents can be sent across sites, site collections or even across SharePoint farms using a send to connection which you can configure in central admin.   Copying a document using a send to connection will preserve most metadata including the Document ID however it will update metadata such as Modified By and Modified Date.
Note that copying a document in Explorer View will always create a new Document ID unless you have implemented your own code to handle the process.
Copy a file to another library or Send To location.


text:
Q: How do I add a window from the resources as a child window? I am creating a windows using win32:
HWND mainWnd = CreateWindow(...);

Now I can add gui elements as children of mainWnd. However this soon becomes a bit tedious and I want to use the designer built into Visual Studio to help me.
I noticed that under Add Resource there is a Dialog entry. Among the dialogs IDD_FORMVIEW seems the most general so I added one of these. Next I added gui elements to it using the designer.
Now I want to use this as a child of my mainWnd. How do I do this?
I found some examples using DialogBox, but I do not want a separate dialog, I want this window as a child of my mainWnd.

A: The designer in Visual Studio is appropriate for creating dialog boxes, not arbitrary windows.
That being said, there are a couple of approaches (in increasing order of difficulty):

*

*Make your main window a dialog.  Petzold's book has an example of using a dialog as the main window of the program.  (If I recall correctly, it's the calculator example.)

*Create the dialog and, before you show it, change its style to WS_CHILD, change its extended style to WS_EX_CONTROLPARENT, and parent it to your main window.  For all the navigation stuff to work, you'll have to add IsDialogMessage calls in your message pump.  This is do-able, but it's likely hard to get everything working well.

*A mixture of 1 and 2 where you create one dialog for your main window, then create a second dialog for the content (with DS_CONTROL), and put the second dialog in the first.  I've never tried this approach myself, but it seems like it should work.

*Write your own code to parse the dialog resource and create the child windows, which is basically re-doing a lot of the work that CreateDialog does for you.
Given your desire to use the GUI to design the UI, I suspect only the first solution is simple enough that you would be interested.

A: Use the CreateDialog API to create the window from the resource. If you do not want it to look like a dialog then remove the titlebar style from the resource properties.

A: To use a dialog created from a dialog resource template you have to specify the DS_CONTROL window style in the template.
Read more about dialog boxes here.
Dialog resources are explained here


text:
Q: Infinite subset in compact metric space Let $X$ be a compact metric space and $A$ be an infinite subset of $X$. Then $A$ contains a Cauchy sequence.
My attempt: Since $X$ is a metric space, then $X$ is a limit point compact. Then $A$ has a limit point, say $x$. Then there exists a sequence $x_n$ in $A$ that converges in $A.$ Hence, $x_n$ is a Cauchy sequence. Is that right?

A: As it stands the conclusion is trivial: for a non-empty set we can always use a constant sequence with value in $A$.
The intended conclusion is more along the lines of
There is a sequence $(a_n)_n$ with all $a_n \in A$ so that all terms are distinct which is a Cauchy sequence.
For that we can indeed use the limit point compactness or ,even better, the sequential compactness of $X$.


text:
Q: Export SharePoint 2013 list big data to Excel I have a SharePoint list with 13879 items, so when I am trying to export the list to Excel, data doesn't export.
It is blank sheet and looks like this. (where column1, column2... are SharePoint list column names).

Also list view threshold is increased to 15000.
Here is an image of list settings showing list view threshold:


text:
Q: What is the need of staging folder in Cordova 3.5.0 iOS application? We are working on a hybrid iOS application. Previously we were using Cordova 3.2.0 version. Recently we are under the process of upgrading our Cordova version to 3.5.0. After creating a new project with Cordova 3.5.0 and opening it with Xcode 5.1.1, we can see a new folder named "Staging" in the Xcode project structure (it's pretty strange for us).
In the root folder of project, there is no staging folder found. Below is the screenshot.

But after opening it with Xcode, the "www" folder and the "config.xml" are coming under staging directory instead of the root directory. Also, I can see two sets of www folder and config.xml file. The www folder & config.xml file which comes under root folder appears in red color (that may be because I have taken only the my_cordova_project --> platform --> ios directory and copied it to some other place. I am planning to commit only the ios folder to my versioning tool). I have simply deleted those two references.

Could someone please explain me if this is an issue. Can I get the old Xcode project structure with Cordova 3.5.0 also? Please let me know in case of any clarifications.

A: Sorry, I did not understand your question. Staging is simply a link folder to the ios-proj/www folder, and you can edit your code normally modifying the original.
In a multi-platform project "cordova platform add " will create a different project for each platform, in this case your editing should be done in the common code and sync sources through "cordova build" that will copy and compile code.
A similar question about the staging purpose:
Purpose of Staging folder in PhoneGap 3.4? Only changes to index.html in this folder get recognized?

A: I had the same problem understanding the relation of /www and /platforms/ios/www. I realized the former should contain the source common to all platforms and the latter should hold platform specific modifications. The Staging folder appearing in the Xcode project is a link to the latter folder. Modifying the content on the former folder and running the app seemed to have no effect - no modifications were seen.
The thing I was missing was that after the modifications I would still need to do the build on command line:
cordova build ios

After that the modifications in the common folder are copied to the platform specific folder(s) and running the project in Xcode shows the modified content.

A: You should sudo cordova build after making any changes, before you build/run in XCode.
This will cause Cordova to update the /staging folder with a "staged" (i.e. assembled for production) version of your assets that has some Cordova magic like device-specific plugins. Compare /staging to /www and you'll notice some additional files in the former.


text:
Q: Using Excel.Region.get_Range() within a range, gives unexpected behavior I am trying to access a range, within another range, in Excel C#, and getting unexpected behavior. In the first range, Cell[1,1].Value, gives the value of the first cell, in the range, as expected. However, in the "subrange", Cell[1,1].Value, does not give the value of the first cell in the subrange. Instead, it jumps down a few rows.
Microsoft documentation
namespace RangeRange
{
    class RangeRange
    {
        private Excel.Application excelApp = new Excel.Application();
        private Excel.Workbook workbook;
        private Excel.Worksheet worksheet;

        public int Load(string filepath)
        {
            workbook = excelApp.Workbooks.Open(filepath);
            worksheet = (Excel.Worksheet)workbook.Sheets[1];

            return 0;
        }

        public int Close()
        {
            // Shut down excel.exe
            workbook.Close();
            excelApp.Quit();

            return 0;
        }

        public int Process()
        {
            Excel.Range data_range = worksheet.UsedRange.Cells;
            int rows = data_range.Rows.Count;
            int cols = data_range.Columns.Count;

            // Get the range containing rows 3 through N.
            Excel.Range c1 = worksheet.Cells[3, 1];
            Excel.Range c2 = worksheet.Cells[rows, cols];
            Excel.Range range1 = (Excel.Range)worksheet.get_Range(c1, c2);

            string value1 = range1.Cells[1, 1].Value;

            Console.WriteLine(value1);

            ProcessRange(range1);

            return 0;
        }

        private int ProcessRange(Excel.Range my_range)
        {
            // Get a range, containing all rows, within my_range.
            int rows = my_range.Rows.Count;
            int cols = my_range.Columns.Count;

            Excel.Range c1 = my_range.Cells[1, 1];
            Excel.Range c2 = my_range.Cells[rows, cols];
            Excel.Range range2 = (Excel.Range)my_range.get_Range(c1, c2);

            string value2 = range2.Cells[1, 1].Value;

            Console.WriteLine(value2);

            return 0;
        }
    }
}

My input data is:

The output is:

A: I was able to get it working, by getting the Worksheet from the range that was passed in, and then setting the desired "subrange", to a range on the Worksheet.
    private int ProcessRange(Excel.Range my_range)
    {
        // Get a range, containing all rows, within my_range.
        int rows = my_range.Rows.Count;
        int cols = my_range.Columns.Count;
        Excel.Range c1 = my_range.Cells[1, 1];
        Excel.Range c2 = my_range.Cells[rows, cols];

        Excel.Worksheet ws = my_range.Worksheet;
        Excel.Range range2 = (Excel.Range)ws.Range[c1, c2];

        string value2 = range2.Cells[1, 1].Value;

        Console.WriteLine(value2);

        return 0;
    }


text:
Q: an image response contains http status code 200 means it fetched to client browser? I am conducting a load testing using Jmeter to ensure massive of concurrent users able to request the image file from the server.
I have few question on the response code of the image(.png).

*

*If the http status code is 200, does it mean the image fully fetched to the client from the server?

*The response code is 200, image will still loading on the browser? or fully loaded?

A: HTTP is stateful protocol, therefore JMeter sends requests and has to wait for a response. If you getting http status code 200 it normally means that the request is completed successfully, so given your request is well-formed it should mean that the image is fully transferred.
However in some cases you may receive HTTP status code 200 which means that request has completed successfully on transport level, but in the response body you will get an error instead of the image. That's why I would recommend using MD5Hex Assertion which will automatically fail your HTTP Request sampler if image will be different from the expected one.

*

*In the "Advanced" tab of your HTTP Request sampler tick "Save response as MD5 hash" box

*Add ND5 Assertion as a child of the HTTP Request and put your image's MD5 checksum into the input field

*That's it, HTTP Request sampler will be failed if downloaded image MD5 checksum is different from the provided one

See How to Use JMeter Assertions in Three Easy Steps article for more information on conditionally setting pass/fail criteria on JMeter tests

A: Following are the answers to your questions:
If the HTTP status code is 200, does it mean the image fully fetched to the client from the server?
Yes. Once you receive the HTTP Response Code, it does mean that complete transfer of the response from Server to Client is done. Please go through TCP/IP model. Data is divided into small TCP packets by Server and Client will combine all of them to form the data (responsibility of Transport Layer). Add screenshot of Wireshark tool to highlight this behaviour.
The response code is 200, image will still loading on the browser? or fully loaded?
Image is fully received by the client (JMeter). But JMeter does not render the output on GUI, not just images any HTTP response. So, the response times of any HTTP requests doesn't include page rendering time, which is a major factor we should consider. if JMeter tells the HTTP response time is x seconds, then from actual end-user perspective, it is x+browser rendering time.
Wireshark image:


text:
Q: In Grails, how do I apply an inList constraint from a 3rd party data source? Let's say I have the following model:
class Product {
    String name
    String price
    String currency

    static constraints = {
        currency inList: ['USD', 'EUR']
}

Now we have a new requirement that inList constraint for currency must be pulled from a service:
class CurrencyService {
    def getAvailableCurrencies = {
        ...
    }
}

How do I make this work? I tried:
class Product {
    def currencyService
    ...

    static constraints = {
        currency inList: currencyService.getAvailableCurrencies()
    }
}

But I can't access the currencyService instance in the static constraints context. I also tried using static currencyService, but this likewise does not work. Any ideas?

A: As dmahapatro mentioned above, you could use a custom validator which uses your service:
static constraints = {
    currency validator: { value, obj ->
        if (!(value in obj.currencyService.getAvailableCurrencies()))
            return ['invalid.currency']
    }
}


text:
Q: Complex Database Design: columns or data For an existing database we are considering to improve part of the database design.
25 tables have very similar structures, about 90% identical columns & data types. And fairly frequent changes to the tables, for example we may need to add 2 new columns to 7 of these 25 tables. A few months later the 2 new columns may be required in 5 further tables, etc. We also get questions like how many rows in these tables have IsActive (see example below) = TRUE. This currently means creating 25 SQL statements and the statements are much more complex than this simple example. It just feels wrong to query 25 tables and then combine the results.
One option we discussed would be to store all data in a master table. However in total this would mean having quite a wide table and quite a lot of NULL values.
A further idea we discussed is to keep the 25 tables and create a master view, which combines these tables. The view would however need a lot of manuall maintenance and the update could get forgotten & the view would still work.
In database design one of the main concepts is: "For maximum flexibility, data is stored in columns, not in column names.", which leads us to the main question. Does anyone have experience in storing columns in a table? The columns actually contain filter criteria for business logic.
Here is an example:
Table 1: Business Rule 1
CustomerID (int) | IsPremiumCust (bool) | HasCreditCard (bool) | IsActive (bool) | OrderThreshold (int)

Table 2: Business Rule 2
CustomerID (int) | IsPremiumCust (bool) | HasCreditCard (bool) | IsActive (bool) | Discount (int)

further 23 tables like these. All with more columns than in this examples.
Suggestion: Criteria table
Criteria ID | Criteria       | Data Type
1           | IsPremiumCust  | bool
2           | HasCreditCard  | bool
3           | IsActive       | bool
4           | OrderThreshold | int
5           | Discount       | int

Suggestion: Business Rule table
Business Rule ID | Name
     1           | Business Rule 1
     2           | Business Rule 2

Suggestion: Intersection table
CustomerID | Business Rule ID | Criteria ID | Criteria Value
------------------------------------------------------------
      1    |      1           |       1     | TRUE
      2    |      2           |       1     | FALSE

I know this doesn't really work, as the Criteria Value field could have different data types. However I hope someone might have had a similar situation and can think of a full solution for this question.
This would allow us to add criteria without having to keep changing many table structures.

A: It sounds like you should have one table that has the core fields from your 25 common tables, with an additional field for the type of record that corresponds to the current existing table names. Then, you want one or a few supplemental tables that use the primary key for you new core table and also store just the additional fields needed by each type of record. If you find yourself with a new set of columns that only apply to a handful of existing tables, that's fine. You only need records for those records from the core table in your new supplemental table. And when those columns expand to include more of your original tables, adding records to the supplemental table is easy. You can still build a master view from this, if you need it.

A: I think reply to you question is good property inheritance tree for end entity. If tree will be optimized for problem domain you will be have efficient database scheme without null values. Problem with quantity of sql statements you can close by suitable ORM.


text:
Q: Autoscroll to bottom of page then top and repeat I have created a dashboard which echos out all the rows but I want an auto scroll which will slowly scroll down the bottom of the page and then scroll slowly back to the top and repeat. I have googled this and can't get a working code. I have been looking for jQuery codes but anything will do.
Because the page will adjust all the time it cant have fixed height scroll.
Not sure if you need more information but if you do I will update this question.
Regards
Gambit

A: You could use something like this.
//run instantly and then goes after (setTimeout interval)

    $("html, body").animate({ scrollTop: $(document).height() }, 4000);
    setTimeout(function() {
       $('html, body').animate({scrollTop:0}, 4000);
    },4000);
  var scrolltopbottom =  setInterval(function(){
         // 4000 - it will take 4 secound in total from the top of the page to the bottom
    $("html, body").animate({ scrollTop: $(document).height() }, 4000);
    setTimeout(function() {
       $('html, body').animate({scrollTop:0}, 4000);
    },4000);

    },8000);

//Use this to stop the scroller -> clearInterval(scrolltopbottom);

Example:
http://jsfiddle.net/NaP8D/11/

A: you should try this for better result

//run instantly and then goes after (setTimeout interval)

$("html, body").animate({ scrollTop: $(document).height() }, 4000);

setTimeout(function() {
   $('html, body').animate({scrollTop:0}, 4000);
},4000);

setInterval(function(){
     // 4000 - it will take 4 secound in total from the top of the page to the bottom
$("html, body").animate({ scrollTop: $(document).height() }, 4000);
setTimeout(function() {
   $('html, body').animate({scrollTop:0}, 4000);
},4000);

},8000);

$('html, body').mouseover(function(e) {
$(this).stop(true);

    }).mouseout(function() {
         $(this).stop(false);
    });

Text text
Text text
    Text text

    Text text
    Text text
    Text text
    Text text

    Text text
    Text textv
    Text text
    Text text

    Text text
    Text textText text
     Text textText text Text textText text
      Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

             Text textText text Text textText text Text textText text Text textText text Text textText text

http://jsfiddle.net/neelu/gvvnd0tt/8/

A: Here, this should work good, just change 5000 to the time in ms to adjust the speed.
http://jsfiddle.net/BDc6S/3/
function scrollDown(el) {
    el.animate({
        scrollTop: el[0].scrollHeight
    }, 5000, function() {
        scrollUp(el)
    });
};

function scrollUp(el) {
    el.animate({
        scrollTop: 0
    }, 5000, function() {
        scrollDown(el);
    });
};

scrollDown($("html,body"));

A: function doSomething() {
  $(document).scrollTop($(document).height());
}
setInterval(doSomething, 5000);

This will scroll to bottom of the page every 5 seconds. This will be useful, if you have auto load content based on user scroll like facebook.


text:
Q: Replace non matching characters regex I'm trying to create a regex which does a replace of every characters which is not within a search pattern.
p.e.
Input
whatever text text and more text
test 2 12000 text and more text
text and text
text 3 text more text
1-2000 and more text

search pattern:
let @/ = '^test \zs2 \d\d\d\d\d\s.*\n\(.*\n\)\{-}text 3\ze'

(matching from just before '2' till just after '3')
I want to replace all other characters outside the matching with the character _.
expected output
________________________________
_____2 text and more text
text and text
text 3_______________
_____________

I use this regex which works fine but does not work if there are multiple lines in search pattern:
exe "%s/\\(@/\\)\\zs\\|./\\=submatch(1)!=''?'':'_'/g"

How can I make it work also with multiple lines in search pattern?

A: Modyfing alpha bravo's solution and adapting to vim:
:%s/\(2\_.*3\)*[^\r\n]/\1_/g

Should do the trick.
The key here is \_.  which matches any character including newlines.
Which is the equivalent to /s in PCRE

A: Use this pattern (2.*3)*[^\r\n] with gs options and replace with $1_
Demo


text:
Q: Use qplot to draw only one subset of data I have a list named d like this:
V1 is an integer set from 0 - 50
V2 is a real set from 1500 - 1800
V3 is an integer set from 1 - 50
In total, the list contains 5100 objects
Now I would like to plot the histogram of V2, with V1 = a certain number (0, 1 or 10, etc.)
I tried different ways:
factor(d$V1)
qplot(V2, data=d, V1 = 1)        --> not successful
d.subset <- subset(d, d$V1 = 1)  --> not successful

I really get crazy with this. Check the characteristics of d$V1 but found nothing strange. Anyone could help me out?
is.factor(d$V1)

[1] TRUE

str(d$V1)  Factor w/ 51 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...

levels(d$V1)
[1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" "14" "15" "16" "17" "18" "19"
[20] "20" "21" "22" "23" "24" "25" "26" "27" "28" "29" "30" "31" "32" "33" "34" "35" "36" "37""38"
[39] "39" "40" "41" "42" "43" "44" "45" "46" "47" "48" "49" "50" "51"

A: Change the line:
d.subset <- subset(d, d$V1 = 1)

to
d.subset <- subset(d, V1 == 1)

Notice the double equals (==) to denote the logical operator. = is used for assignment and doesn't subset the data frame.
Finally, you might mean to put the 1 in quotes if you want to get the "1" level of the factor (which might not be the same as the numeric 1).
d.subset <- subset(d, V1 == "1")


text:
Q: How to join a Slack channel as a Real Time Messaging bot user? channels.join is not allowed for bot users.  I would like my RTM-using bot to listen to channels other than the one listed in the bot integration page.
I don't see a way to change the channels in the bot integration page:

Is this just a limitation of bots or am I missing something fundamental here?

A: I had the same issue and wasnt sure why my bot was only listening to certain channels.
Your bot will need to be invited to each channel by a user. Run this command within the required channel in the Slack app to do so
/invite @<your_bot_name>

Once in the channel they should then be able to listen to events.

A: This is still a limitation of bots as of May 2017 because of a bug that it introduces-- see paulhammod's answer at https://github.com/slackapi/node-slack-sdk/issues/26. The correct way to add a bot is the the slash command /invite @<bot.user> <channel_name> as @MattGifford pointed out.
However, @nafg introduced an interesting workaround. If you generate a personal API_TOKEN for your account, then you can use it to invite a bot.
For instance, in python one could run:
import slackclient
 sc = slackclient.SlackClient(<PERSONAL_API_TOKEN>)
 sc.api_call('channels.invite', channel=<channel_id>, user=<user_id>)

This will invite the bot to the channel. If you wanted to automate inviting your bot to new channels, you can look at event listeners in the API found at https://api.slack.com/rtm
As long as you allow your API_TOKEN to be used for that purpose, it seems that it would work as needed, albeit less convenient.

A: I haven't actually tried this but I would expect that you can first call channels.join on behalf of an actual user (e.g., yourself), then call channels.invite as that user to add the bot to that channel. I expect that is allowed, and it would then allow the bot to interact with that channel. This way you can automate everything.


text:
Q: How to remove every {element} after the 3rd one? I've got a list of objects that I need to trim down on special occasions using jQuery. For intents and purposes, let's say it looks like this:

stuff

stuff

stuff

stuff

stuff

Is there a simple way (with jQuery, pure JS if necessary I suppose) to remove 'every' .child after the third one?
Note: the .one, .two .three is not necessarily in numerical order.

A: Yes, using the :gt selector:
$("#container > .child:gt(2)").remove();

...which means "select all .child elements that are immediate children of #container and are at index 2 or higher (indexes start at 0).
Or if you don't like using jQuery's extended selectors (because they can't be passed through to the browser's own selector engine), you can use .filter to filter the children:
$("#container > .child").filter(function(index) {
    return index > 2;
}).remove();

If they're the only children, you can use .children instead of the > .child part of that selector:
$("#container").children().filter(function(index) {
    return index > 2;
}).remove();

A: Use :gt() selector and .remove()
$(document).ready(function(){
$('#container .child:gt(2)').remove();
});

DEMO VIEW

A: $('.child').gt(2).remove();

here gt means greaterthan


text:
Q: the equation $y^2=4x+4y$ changes to the form $y^2=4x$ if the origin shifted to (without rotating the axis) the equation $y^2=4x+4y$ changes to the form $y^2=4x$ if the origin shifted to (without rotating the axis)
$A:(1,2)$
$B:(-1,2)$
$C:(-1,-2)$
$D:(1,-2)$

A: Being the lazy person I am, I just plugged in A, B, C, and D to get a feel for the problem. Then, we can take some values for $y^2=4x+4y$.
$x = -1, y = 2$
$x = 0, y = 4$
$x = 1, y \approx 4.82$
As you can see, when $x = -1$, $y = 2$. The answer choice is B.
-FruDe

A: Hint:
$y^2=4x+4y$ is equivalent to $(y-2)^2=4(x+1)$.

A: Fill in the blanks to by completing the square.
$y^2=4x+4y$
$y^2-4y=4x$
$y^2-4x+\color{blue}{?}=4x+\color{blue}{?}$
$(y-\color{green}{?})^2=4(x-\color{red}{?})$
$(y')^2=4x'$ where $(x',y')=(0,0)$ when $(x,y)=(\color{red}{?},\color{green}{?})$.


text:
Q: No print output from openpyxl modules I'm new in coding - trying to figure it out as working on an actual code.
I want to go through all the column titles in the first row, find the one that says "Status" and get the column letter for it.
Supposedly afterwards I will go through all the rows in the spreadsheet and create a new file with rows that only have a certain keyword in the "Status" column.
My Frankenstein is not giving me any errors, but I can't get a printed output for the column letter.
temp_value variable was created with an intention to hold that column letter and use it in some loops/calculations later in the code.
I appreciate your time and hope you might help me out.
P.S. I actively browse through openpyxl official guidelines, but not much luck. I assume my main problem here is inability to plan my code structure - open to any ideas and advise here :)
    import openpyxl
    from openpyxl import Workbook
    from openpyxl.utils import get_column_letter

    wb = openpyxl.load_workbook("myfile.xlsx")
    sheet = wb.active
    temp_data = str()

    #TODO: Find "Status" column to sift through only what we need later

    print("Reading through column titles...")

    for column in range (1, 10):
        column_letter = get_column_letter(column)
        if sheet[column_letter+str(column)].value == "Status":
            temp_data = column_letter

    print(temp_data)

A: In your description you are stating of looping through the columns titles of the first row. The code "sheet[column_letter+str(column)].value will generate A1,B2,C3...
import openpyxl
from openpyxl import Workbook
from openpyxl.utils import get_column_letter

wb = openpyxl.load_workbook("myfile.xlsx")
sheet = wb.active
temp_data = str()

# TODO: Find "Status" column to sift through only what we need later

print("Reading through column titles...")

for column in range(1, 10):
    column_letter = get_column_letter(column)
    if sheet[column_letter + '1'].value == "Status":
        temp_data = column_letter

print(temp_data)

A: You'll rarely actually need get_column_letter in your own code:
for cell in ws[1]:
   if cell.value == "Status":
       print(cell.column_letter)


text:
Q: ReactiveX JS and TypeScript - How to unsubscribe? I've been attempting to implement a new rxjs Observable in an Angular 2 component using TypeScript. I have created a service, MyService that returns an observable in one of its methods, e.g.,
export class MyService {

    getMyObs(){
        return new Observable(observer => {
            observer.next(42);
        });
    }
}

Then in my Angular 2 component I subscribe to this observable in OnInit, e.g.,
export class MyComponent implements OnInit {
obs: any;

constructor(private myService: MyService){};

    ngOnInit {
        this.obs = myService.getMyObs().subscribe(data => {
            // Do stuff here...
        });
    }
}

The RxJs documentation talks about unsubscribing from your observable such that your observable knows to no longer emit messages to your observer. Therefore, I figured I should be unsubscribing from the observable when my component gets destroyed, something like
export class MyComponent implements OnInit, OnDestroy {
obs: any;

constructor(private myService: MyService){};

    ngOnInit {
        this.obs = myService.getMyObs().subscribe(data => {
            // Do stuff here...
        });
    }

    ngOnDestroy {
        this.obs.unsubscribe();
    }
}

Whilst this makes sense to me, the typescript compiler throws (and indeed the application throws) saying there is no unsubscribe method. There appears to be no such method described in the type definition files. How do I correctly unsubscribe from an observable using TypeScript?

A: You need add unsubscribe method to your Observable., Disposing Observable Executions
return new Observable(observer => {
  observer.next(42);

  return () => {
    console.log('unsubscribe')
  }
});

A: You can find the definition of the unsubscribe method in the Subscription.d.ts (class Subscription) of the Rxjs module.
As a matter of fact, you unsubscribe a subscription and not an observable.

A: First create Subscription as follow.
private obs: Subscription = new Subscription();

Then assign to observable.
this.obs = myService.getMyObs().subscribe(data => {
       if(data !== null){
        this.obs.unsubscribe()
         }
    });


text:
Q: How to run Google Assistant library (on AIY kit), upon startup of Raspberry Pi? We set up a voice kit using Raspberry Pi (using "the MagPi essentials AIY Projects" manual).  We are able to enable Google Assistant using the command "src/assistant_library_demo.py" in the dev terminal, after Raspberry Pi starts up.  We would like to embed the voice kit in a stuffed animal with a portable power supply (i.e., used to charge cell phone on the go).  But when the portable power supply is charged, the Raspberry Pi resets.  That requires us to go back into the Raspberry Pi, open the dev terminal, and run the Google Assistant file.
My question: Is it possible to run a startup script that automatically runs Google Assistant upon Raspberry Pi starting up?  How to do this?

A: I ended up creating a crontab job after a 10 second wait. Starting right at boot didn't give it enough time for the internet to connect fully.
In terminal type:
crontab -e

Choose an option if it asks how you want to open/edit the file. Then at the bottom put:
@reboot sleep 10 && /home/pi/pathtofile > /home/pi/cronlog 2>&1

Save the file and reboot or pull the cable out and plug it back in. The cronlog helped me troubleshoot this whole process and get feedback on why it didn't work.

A: Take a look at this page. It tells you how to set up a service which will run automatically.
If the link has gone bad, here is a short explanation of it:
Create a file called my_assistant.service in the src directory, and put in the following code
[Unit]
Description=My awesome assistant app

[Service]
Environment=XDG_RUNTIME_DIR=/run/user/1000
ExecStart=/bin/bash -c 'python3 -u src/my_assistant.py'
WorkingDirectory=/home/pi/AIY-projects-python
Restart=always
User=pi

[Install]
WantedBy=multi-user.target

Where the file says src/my_assistant.py, replace my_assistant with your program's filename. Now go to the folder that file the .sevice file is in, and run the command sudo mv my_assistant.service /lib/systemd/system/. This code moves the file to the services folder. Now you can run the following commands to change the service:
Enable the service- sudo systemctl enable my_assistant.service
Disable it- sudo systemctl disable my_assistant.service
Start it (just runs it once, enabling makes it run on startup)- sudo service my_assistant start
Stop it- sudo service my_assistant stop
See the logs, when the program was started and if an error occurred- sudo service my_assistant status


text:
Q: How do I detect if a value has been added to array slot? (java) I am a beginner programmer and i've gotten stuck.
I've set up an array here which has worked how I want it to.
Although now I need a way to check the very last slot (data[5]) to see if any value has been placed within it since there is no guarantee in my code that each array slot will be assigned a value.
Below is my working array setup:
public final int[] data;

//Constructor
public MyArrayList() {
    this.data = new int[6];

}

And here is what I've tried:
if(data[5] == null){
        data[5] = value;
        truth = true;

    } else {

        truth = false;
    }

Note that this code is trying to detect if anything is in there, and place another value in if it can see there hasn't been any code written there.
Any help appreciated :)

A: int is a primitive type in Java, so it will never be null. If you want to keep track of how much of the array you've "used", you can add a second field to the class to keep up with it.
public class MyArrayList {

  private final int[] data;
  private int index;

  public MyArrayList() {
    data = new int[6];
    index = 0;
  }

  ...

}

Then whenever you "push" something new to the list, you put it at the index position and increment index. If index is ever equal to the length of the list, then you've exhausted the space you allocated.

A: Use the Integer class instead of the primitive type. It allows to assign a value  or a null value. With this you can apply the logic that you described.
data = new Integer[6];

if (data[5] == null)
    data[5] = value;


text:
Q: Bash if filename exists I have a script that I call from another script with a specific filename as second argument.
script1 </var/tmp/outputfile>

within script1, I want to add a logic to find if the filename after /var/tmp is 'outputfile' if, yes I need to add some logic, if not other logic.
Following code is not working in the script1.sh.
#!/bin/sh

if [ $# -ne 1 ]; then
    echo "Invalid usage"
    echo "Usage: $0 <logfile>"
    exit 1
fi

if [[ $1 == *"outputfile" ]]; then
    echo "Found it"
else
    echo "Search fail"
fi

Note that input always includes the full path where the file is generated. I just need to search for the filename that is at the end of the input string ($1). I tried many ways. It is not working in the script.
If I try similar logic directly in the shell it is working fine. Can someone tell me what should I add in the script.
[root@mgmt:~]$echo $file
/var/tmp/output
[root@mgmt:~]$if [[ $file == *"output" ]] ; then echo "ok";  else echo "fail";fi
ok


text:
Q: Want to make a detailview just like Pinterest I've been struggling with a view in xcode this whole weekend but still can't get it as I want. I want to do a detailview like Pinterest (see link below) but can't find out how to do it, is it a tableview with custom cells, collectionview or something else.. Which way's the easiest way to build it? Would be so grateful if someone got some good inputs for me..
Have a great upcoming week!!
Pinterest DeatilView
EDIT: This is what I got at the moment.. But feels like there should be an easier way to..
#import "ViewController.h"

enum TableSectionSelected
{
kUIMainContentSection = 0,
kUISecondSection,
kUIActivateSection
};

@interface ViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];

self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
self.imageView.image = [UIImage imageNamed:@"fotolia_54424692.jpg"];
}

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 3;
}

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch (section) {
    case 0:
        return 2;
        break;
    default:
        return 1;
        break;
   }
 }

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath     *)indexPath
{
NSIndexPath *firstCell = [NSIndexPath indexPathForRow:0 inSection:0];

if ([firstCell isEqual:indexPath]) {
    return 500;
 }

 return 44;
 }

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:    (NSIndexPath    *)indexPath
 {
 static NSString *CellIdentifier = @"Cell";
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier            forIndexPath:indexPath];

//    cell.textLabel.text = [NSString stringWithFormat:@"%@", indexPath];

if (indexPath.section == 0 && indexPath.row == 0) {

}

switch (indexPath.section) {
    case kUIMainContentSection:
        if (indexPath.row == 0) {
            [cell.contentView addSubview:self.imageView];
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 320, 260,   30)];
            titleLabel.text = @"Orange Juice";
            [cell.contentView addSubview:titleLabel];
            UILabel *detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 370, 260, 44)];
            detailLabel.numberOfLines = 0;
            detailLabel.text = @"Lorem ipsum dolor sit er elit lamet, consectetaur cillium   adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolo";
            [detailLabel sizeToFit];
            [cell.contentView addSubview:detailLabel];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

        } else if (indexPath.row == 1) {
            cell.textLabel.text = @"Hitta Hit";
            cell.imageView.image = [UIImage imageNamed:@"fotolia_54424692.jpg"];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleDefault;

        }
        break;
    case kUISecondSection:
        cell.textLabel.text = @"Joe & The Juice";
        cell.imageView.image = [UIImage imageNamed:@"fotolia_54424692.jpg"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;

        break;
    case kUIActivateSection:
        cell.textLabel.text = @"Activate";
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.imageView.image = nil;
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        break;
    default:
        break;
}

cell.layer.cornerRadius = 3.0;
cell.layer.borderColor = [UIColor colorWithHue:0.0 saturation:0.0 brightness:0.0 alpha:0.1].CGColor;
cell.layer.borderWidth = 0.5;

return cell;
 }

 - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
if (section == kUISecondSection) {
    return @"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu,   sed do eiusmod tempor incididunt ut labore et dolo";
} else {
    return @"";
}
}

@end

A: They are using UICollectionViews and the new transitioning APIs.
Here is an actual blog post by them going over some of the layouts at a high level:
https://medium.com/@Pinterest_Engineering/behind-the-pins-building-pinterest-3-0-for-ios-100f57f6940
Here is a UICollectionView layout someone made to recreate their main layout:
https://github.com/chiahsien/CHTCollectionViewWaterfallLayout


text:
Q: ExtJS 4.1 Call One Controller From Another Note: I'm a total ignoramus regarding javascript.
I've broken my ExtJS 4.1 MVC app out into several controllers like:
/app/controller/Auth
    |          |Quiz
    |          |Result
    |          |Blah...
    |model/...

I want to respond to an "event", not a DOM Event, rather a Ext.form.action.Submit.success event by calling functions in both my Auth and Quiz controllers. The summarized code for the first part is here:
// File: app/controller/Auth.js
attemptLogin : function() {
    var form = Ext.ComponentQuery.query('#loginpanel')[0].form;
    if (form.isValid()) {
        form.submit({
        success : function(form, action) {
            // THIS IS THE FUNCTION FROM THE CURRENT CONTROLLER
            Assessor.controller.Auth.prototype.finishLogin();
            // THIS IS THE FUNCTION FROM THE OTHER CONTROLLER
            Assessor.controller.Quiz.prototype.setupAssessment();
        },

This works but feels wrong. Is there a proper way to do this? It seems like I should fire a unique event that is listened to by both controllers, but I can't understand how to do that with Ext.Event. Any guidance?
Thanks! I'm really grateful for all the great ideas and advice.

A: It  makes sense to me to fire a custom event from the form and simply listen to it in both your controllers, like what you said here:

It seems like I should fire a unique event that is listened to by both
  controllers

// File: app/controller/Auth.js
attemptLogin : function() {
    var form = Ext.ComponentQuery.down('#loginpanel').form;
    if (form.isValid()) {
        form.submit({
        success : function(form, action) {
            // fire the event from the form panel
            form.owner.fireEvent('loginsuccess', form.owner);
        },

Then in each of your controllers you can listen to it with Controller#control, like this:
Ext.define('YourApp.controller.Auth', {
    extend: 'Ext.app.Controller',

    init: function() {
        var me = this;

        me.control({

            '#loginpanel': {

                loginsuccess: me.someHandler

            }
        });
    },

    someHandler: function(form) {
        //whatever needs to be done
        console.log(form);
    }
}

And then add the same thing to your Quiz controller:
Ext.define('YourApp.controller.Quiz', {
    extend: 'Ext.app.Controller',

    init: function() {
        var me = this;

        me.control({

            '#loginpanel': {

                loginsuccess: me.someOtherHandler

            }
        });
    },

    someOtherHandler: function(form) {
        //whatever needs to be done
        console.log(form);
    }
}

I've used this approach successfully in 4.1.0 and 4.1.1

A: It really should be
Assessor.controller.Auth.prototype.finishLogin.apply(this, arguments)

or something along these lines (in order to have a correct this reference that points to the 'owner' of the method, the controller object)
However, why do you use this unorthodox way to call the current controller's method. Just set the scope for the success callback, then call this.finishLogin().
form.submit({
    success : function(form, action) {
        // THIS IS THE FUNCTION FROM THE CURRENT CONTROLLER
        this.finishLogin();
        ...
    },
    scope: this
});

Also, you can retrieve another controller instance using Controller#getController.
this.getController('Assessor.controller.quiz').setupAssignment();

Then, if your controller methods are not depending on each other, you could make them both listen to the same event.
Another solution is to fire a custom event once the login is finished. You could do that on the application object
this.application.fireEvent('logincomplete');

and in your controller's init method:
this.application.mon('logincomplete', this.setupAssignment, this);

Please note that you cannot listen to those events via Controller#control - see Alexander Tokarev's blog post for a patch to Ext to achieve this.

A: There is no standard way to fire events between controllers, but it's possible with some custom hacks. See my recent blog post.

A: I have also been looking for this and all you need is Asanda.app.getController('quiz').setupAssignment();, where Asanda is the name of your app

A: You should use a MessageBus if you have to send events between controllers:
Ext.define('MyApp.utils.MessageBus', {
        extend : 'Ext.util.Observable'
});

store the message bus in a global var
MsgBus = Ext.create('MyApp.utils.MessageBus');

Where you have to send events:
MsgBus.fireEvent('eventName',eventArg_1,eventArg_2);

Where you have to receive events:
MsgBus.on('eventName', functionHandler,scope); //scope is not mandatory
...
functionHandler:function(eventArg_1,eventArg_2){
...
//do whatever you want
...
}


text:
Q: How do I obtain the Jackson ObjectMapper in use by Spring 4.1? Spring 4.1 instantiates a Jackson ObjectMapper instance. I have reason to want to @Autowire that instance into one of my controllers: The controller does some minor JSON parsing of its own using Jackson, but the ObjectMapper it uses should be the one and same instance that Spring itself is using. How do I go about accomplishing that?
Note that I'm not asking how to custom configure the ObjectMapper in use by Spring; I'm happy with the defaults. I just want to fish the instance used by Spring out so that I can re-use the existing instance in my own code.

A: I have debugged into source code of Spring Boot and found that only when we launch the whole context Jackson2ObjectMapperBuilder will contain the config we put in application.yml.
This means, if we want to generate an ObjectMapper in a Spring Boot test, with JUnit 5, we have to:
@ExtendWith(SpringExtension.class)
@SpringBootTest
class SomeTest {
    @Autowired
    private Jackson2ObjectMapperBuilder builder;
    ...

    @Test
    void testObjectMapper() {
        ObjectMapper mapper = builder.build();

    }

We cannot only make @SpringBootTest(classes = Jackson2ObjectMapperBuilder.class) to generate this builder.
When we bootRun we don't have this problem.
The configuration is set in Jackson2ObjectMapperBuilderCustomizerConfiguration#customize(Jackson2ObjectMapperBuilder builder) method.

A: If you're using Spring Boot with Jackson on your classpath and default implementation for JSON parsing in your REST controller, then this should work:
@Autowired
private ObjectMapper jacksonObjectMapper;

A: As was said by others, you can't @Autowired it in directly into your controller.
@Emerson Farrugia's suggestion to create a new instance using
Jackson2ObjectMapperBuilder.json().build()

also didn't work for me because the obtained instance was not following the spring.jackson.* configuration properties, which I needed it to.

The solution I found was to obtain the ObjectMapper from Spring's MappingJackson2HttpMessageConverter which is injectable.
So I autowired it:
@Autowired
private MappingJackson2HttpMessageConverter springMvcJacksonConverter;

and then get the ObjectMapper from it like this:
ObjectMapper objectMapper = springMvcJacksonConverter.getObjectMapper();

This instance behaves exactly as Spring MVC's own message conversion - it probably is the same instance anyway.

A: If you take a look at MappingJackson2HttpMessageConverter, you'll see that it creates a new ObjectMapper, but doesn't expose it as a bean. There's a getter, but the only way I've fished it out in the past is when I created the MappingJackson2HttpMessageConverter myself, e.g.
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        MappingJackson2HttpMessageConverter jacksonMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jacksonMessageConverter.getObjectMapper();

        objectMapper.registerModule(new JodaModule());
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);

        converters.add(jacksonMessageConverter);
    }
}

If you're working with Spring Boot, there's a section in the manual dedicated to working with the ObjectMapper If you create a default Jackson2ObjectMapperBuilder @Bean, you should be able to autowire that same ObjectMapper instance in your controller.

A: The ObjectMapper is created by Jackson2ObjectMapperBuilder, and you can inject the builder using:
@Autowired
private Jackson2ObjectMapperBuilder mapperBuilder;

Then use mapperBuilder.build() to build an ObjectMapper instance, and this instance can use configurations in application.properties. Official doc here.

A: When you try to @Autowire the MappingJackson2HttpMessageConverter it gives you:
No qualifying bean of type 'org.springframework.http.converter.json.MappingJackson2HttpMessageConverter' available: expected single matching bean but found 4: mappingJackson2HttpMessageConverter,jacksonHttpMessageConverter,halJacksonHttpMessageConverter,alpsJsonHttpMessageConverter.
This is not a big issue, you can just change your variable name to one of the above to  get that instance:
@Autowired
    private MappingJackson2HttpMessageConverter halJacksonHttpMessageConverter;

A: An Update for Spring 4.3:

*

*As of Spring 4.3, classes with a single constructor can omit the @Autowired annotation

*Consequently, if you add a constructor which takes an ObjectMapper parameter it will be autowired with the Jackson ObjectMapper instance without needing to use the annotation @Autowired

A: A two-stepper if you will;

*

*At your @SpringBootApplication class, add:
@Bean
public ObjectMapper mapper() {
  return new ObjectMapper();
}

*Anywhere you wish to use ObjectMapper:
@Autowired
ObjectMapper mapper;

Peace!


text:
Q: Cannot find spark image built with docker-image-tool locally I am trying to build spark image to use with Kubernetes (minikube locally) (following https://spark.apache.org/docs/latest/running-on-kubernetes.html, https://itnext.io/running-spark-job-on-kubernetes-minikube-958cadaddd55 and https://learn.microsoft.com/en-us/azure/aks/spark-job).
I want to build it for local docker repo and I am using following command ./bin/docker-image-tool.sh -m -t v2 build to build it for minikube. This build succeeds, but after that I can't find the image with docker image ps. The spark-submit fails with cryptic Error: Could not find or load main class org.apache.spark.launcher.Main, which doesn't tell anything, but it seems reasonable to be linked with image missing in the docker registry.
All build steps seem to succeed with no issue, so I am bit lost at what went wrong.
Build output:
Sending build context to Docker daemon  1.193GB
Step 1/15 : FROM openjdk:8-jdk-slim
 ---> 6b2212023a6e
Step 2/15 : ARG spark_jars=jars
 ---> Using cache
 ---> 2407ea1f6efa
Step 3/15 : ARG img_path=kubernetes/dockerfiles
 ---> Using cache
 ---> db7404f15dfd
Step 4/15 : ARG k8s_tests=kubernetes/tests
 ---> Using cache
 ---> 8dc19efc9230
Step 5/15 : RUN set -ex &&     apt-get update &&     ln -s /lib /lib64 &&     apt install -y bash tini libc6 libpam-modules libnss3 &&     mkdir -p /opt/spark &&     mkdir -p /opt/spark/work-dir &&     touch /opt/spark/RELEASE &&     rm /bin/sh &&     ln -sv /bin/bash /bin/sh &&     echo "auth required pam_wheel.so use_uid" >> /etc/pam.d/su &&     chgrp root /etc/passwd && chmod ug+rw /etc/passwd &&     rm -rf /var/cache/apt/*
 ---> Using cache
 ---> 5884173cd551
Step 6/15 : COPY ${spark_jars} /opt/spark/jars
 ---> Using cache
 ---> ff058e0c80e7
Step 7/15 : COPY bin /opt/spark/bin
 ---> Using cache
 ---> d158732d730c
Step 8/15 : COPY sbin /opt/spark/sbin
 ---> Using cache
 ---> 896cd481cdbc
Step 9/15 : COPY ${img_path}/spark/entrypoint.sh /opt/
 ---> Using cache
 ---> 1d108a1e1df4
Step 10/15 : COPY examples /opt/spark/examples
 ---> Using cache
 ---> 3a7680f04b03
Step 11/15 : COPY ${k8s_tests} /opt/spark/tests
 ---> Using cache
 ---> 2cd76b303d3e
Step 12/15 : COPY data /opt/spark/data
 ---> Using cache
 ---> 8221e20aac95
Step 13/15 : ENV SPARK_HOME /opt/spark
 ---> Using cache
 ---> ecb9bee32447
Step 14/15 : WORKDIR /opt/spark/work-dir
 ---> Using cache
 ---> 6bfafec8d0bb
Step 15/15 : ENTRYPOINT [ "/opt/entrypoint.sh" ]
 ---> Using cache
 ---> 110ccecb98db
Successfully built 110ccecb98db
Successfully tagged spark:v2
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.
Sending build context to Docker daemon  1.193GB
Step 1/9 : ARG base_img
Step 2/9 : FROM $base_img
 ---> 110ccecb98db
Step 3/9 : WORKDIR /
 ---> Using cache
 ---> 7d82c43a71b8
Step 4/9 : RUN mkdir ${SPARK_HOME}/python
 ---> Using cache
 ---> a06db167de65
Step 5/9 : RUN apt install -y python python-pip &&     apt install -y python3 python3-pip &&     rm -r /usr/lib/python*/ensurepip &&     pip install --upgrade pip setuptools &&     rm -r /root/.cache && rm -rf /var/cache/apt/*
 ---> Using cache
 ---> 2789da56886a
Step 6/9 : COPY python/lib ${SPARK_HOME}/python/lib
 ---> Using cache
 ---> 17ad5567580c
Step 7/9 : ENV PYTHONPATH ${SPARK_HOME}/python/lib/pyspark.zip:${SPARK_HOME}/python/lib/py4j-*.zip
 ---> Using cache
 ---> 01f0ee91d6a6
Step 8/9 : WORKDIR /opt/spark/work-dir
 ---> Using cache
 ---> 95b4885abc7e
Step 9/9 : ENTRYPOINT [ "/opt/entrypoint.sh" ]
 ---> Using cache
 ---> 2bb9c23681e8
Successfully built 2bb9c23681e8
Successfully tagged spark-py:v2
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.
Sending build context to Docker daemon  1.193GB
Step 1/9 : ARG base_img
Step 2/9 : FROM $base_img
 ---> 110ccecb98db
Step 3/9 : WORKDIR /
 ---> Using cache
 ---> 7d82c43a71b8
Step 4/9 : RUN mkdir ${SPARK_HOME}/R
 ---> Using cache
 ---> c49d10da5c74
Step 5/9 : RUN apt install -y r-base r-base-dev && rm -rf /var/cache/apt/*
 ---> Using cache
 ---> d693ef1ab12c
Step 6/9 : COPY R ${SPARK_HOME}/R
 ---> Using cache
 ---> 50ca4b703501
Step 7/9 : ENV R_HOME /usr/lib/R
 ---> Using cache
 ---> cba4fbc51e7c
Step 8/9 : WORKDIR /opt/spark/work-dir
 ---> Using cache
 ---> 449edacaae16
Step 9/9 : ENTRYPOINT [ "/opt/entrypoint.sh" ]
 ---> Using cache
 ---> a84c327a2b9d
Successfully built a84c327a2b9d
Successfully tagged spark-r:v2
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.

A: I have missed these as well. But this should be OK
You see the lines
Successfully tagged spark:v2
Successfully tagged spark-py:v2
Successfully tagged spark-r:v2

so your build has succeeded, and the Docker images for JVM-, Python- and R-based jobs to be used for Spark jobs on Kubernetes were created.
You will not see these images when you list the images on the host (the system minikube runs on):
$ docker image ls | egrep "spark-k8s-2.4.5|minikube"
gcr.io/k8s-minikube/kicbase                                          v0.0.18                                         a776c544501a        6 weeks ago         1.08GB

You should see these images when you list the images in minikube:
$ minikube ssh
Last login: Thu Apr  8 15:55:10 2021 from 192.168.49.1
docker@minikube:~$ docker image ls
REPOSITORY                                TAG               IMAGE ID       CREATED         SIZE
spark-r                                   spark-k8s-2.4.5   21836f5f1e0c   23 hours ago    1.1GB
spark-py                                  spark-k8s-2.4.5   1a042cd867f7   23 hours ago    1.05GB
spark                                     spark-k8s-2.4.5   07a9a8459c4c   23 hours ago    552MB
openjdk                                   8-jdk-slim        76fad6e75a0f   9 days ago      288MB
k8s.gcr.io/kube-proxy                     v1.20.2           43154ddb57a8   2 months ago    118MB
k8s.gcr.io/kube-apiserver                 v1.20.2           a8c2fdb8bf76   2 months ago    122MB
k8s.gcr.io/kube-controller-manager        v1.20.2           a27166429d98   2 months ago    116MB
k8s.gcr.io/kube-scheduler                 v1.20.2           ed2c44fbdd78   2 months ago    46.4MB
kubernetesui/dashboard                    v2.1.0            9a07b5b4bfac   3 months ago    226MB
gcr.io/k8s-minikube/storage-provisioner   v4                85069258b98a   4 months ago    29.7MB
k8s.gcr.io/etcd                           3.4.13-0          0369cf4303ff   7 months ago    253MB
k8s.gcr.io/coredns                        1.7.0             bfe3a36ebd25   9 months ago    45.2MB
kubernetesui/metrics-scraper              v1.0.4            86262685d9ab   12 months ago   36.9MB
k8s.gcr.io/pause                          3.2               80d28bedfe5d   13 months ago   683kB
k8s.gcr.io/echoserver                     1.4               a90209bb39e3   4 years ago     140MB

This is the effect of using
docker-image-tool.sh -m

-m instructs docker-image-tool.sh to "use minikube's Docker daemon".
Likewise docker ps on the host will look like this: It will show minikube
$ docker ps
CONTAINER ID        IMAGE                                 COMMAND                  CREATED             STATUS                  PORTS                                                                                NAMES
3cb659bf50d7        gcr.io/k8s-minikube/kicbase:v0.0.18   "/usr/local/bin/entr…"   8 days ago          Up 56 minutes           127.0.0.1:32782->22/tcp, 127.0.0.1:32781->2376/tcp, 127.0.0.1:32780->5000/tcp, 127.0.0.1:32779->8443/tcp, 127.0.0.1:32778->32443/tcp   minikube

O the other hand you should see various Kubernetes services in minikube like this:
$ minikube ssh
Last login: Fri Apr  9 06:59:08 2021 from 192.168.49.1
docker@minikube:~$ docker ps | head -n 5
CONTAINER ID   IMAGE                  COMMAND                  CREATED          STATUS          PORTS     NAMES
43b8fa28c0f0   9a07b5b4bfac           "/dashboard --insecu…"   56 minutes ago   Up 56 minutes             k8s_kubernetes-dashboard_kubernetes-dashboard-968bcb79-hnqcg_kubernetes-dashboard_90252423-eb5d-4e53-800a-3aa40cbcd4b6_9
3cc6d85f88ce   85069258b98a           "/storage-provisioner"   56 minutes ago   Up 56 minutes             k8s_storage-provisioner_storage-provisioner_kube-system_ca8a31c4-1ca2-4284-b9d4-4a1068d46876_15
cf48ca7b8e2e   bfe3a36ebd25           "/coredns -conf /etc…"   57 minutes ago   Up 57 minutes             k8s_coredns_coredns-74ff55c5b-xtkgf_kube-system_d24f114f-d3f9-4a45-bd2a-fa954a42686e_7
0ce17fa229df   a90209bb39e3           "nginx -g 'daemon of…"   57 minutes ago   Up 57 minutes             k8s_echoserver_hello-minikube-6ddfcc9757-vwkh8_default_08c3f2ee-c0ed-4778-9aa9-5d65890cb18c_7

As for the error message I don't think that it's related to the "missing" image.
It could be anything, like invalid class name, the class is not the jar, dependency problems (for example in the jar file containing the job), mixed Spark versions etc.


text:
Q: How to use fortran to read irregular lines I have a text file formatted like this:
1  2
3  4  5
6  7

and so on for many lines.
I run this fortran program:
i=1
tt=1
do while(.true.)
  read(unit=1,*,IOSTAT=status) lon(i,tt),lat(i,tt),h(i,tt)
  i=i+1
  if(status/=0)exit
enddo

I want to assign three numbers in the same line to lon, lat, h. However, because the first line doesn't have the third element , the program will read the first element in the second line (i.e., 3 to h(i,tt)), and that's not what I want. I want to set h(i,tt) to the missing value in some lines
How can I do this?

A: For your specific example, you can try something like this:
program test

  integer :: status, i, tt
  character(len=100) :: line
  integer :: lon(3, 1), lat(3, 1), h(3, 1)

  lon(:, :) = 0
  lat(:, :) = 0
  h(:, :) = 0

  open(unit=1, file='data.txt')
  i=1
  tt=1
  do

     read(1, '(A100)', iostat=status) line
     if(status/=0) exit

     read(line, *, iostat=status) lon(i, tt), lat(i, tt), h(i, tt)

     if(status/=0) then
        read(line, *) lon(i, tt), lat(i, tt)
        h(i, tt) = 1  ! default value
     end if

     i = i + 1

  end do

  print *, 'lon=', lon
  print *, 'lat=', lat
  print *, 'h=', h

end program test

which returns
lon=           1           3           6
lat=           2           4           7
h=           1           5           1


text:
Q: Compiled C Program Wont Run Under My uid But Will Run As Root System: RHEL8   4.18.0-372.19.1.el8_6.x86_64
Selinux: Enabled
FIPS:    Enabled
Program:
#include <stdio.h>

int main( void )
{
  fprintf( stdout, "Running test Program...\r\n" );
}

Compile:
gcc test.c -o test
Run Program:
./test
-bash: ./test: Operation not permitted
It doesn't work.
List Directory:
$ ls -l
total 24
-rwx------. 1 dev dev 18088 Aug  9 13:01 test
-rw-r--r--. 1 dev dev    95 Aug  9 13:00 test.c
List File Attributes:
-------------------- ./test.c
-------------------- ./test
Mounted Partition:
There is -> no <-  "noexec"  set.
Run as root:
sudo ./test
Running test Program...
It works running as root.
What am I missing here?
I have read, write, and execute permission for this file.

A: Try to change the owner (chown) or the permissions (chmod) of the executable and/or the directory it is in. Maybe something is wrong with it.


text:
Q: Verify order of mock calls I need to test if one objects calls other object methods in right order.
Unfortunately it looks like  Mockito use some kind of grouping for calls with the same parameters. I prepared example which illustrates this behavior.
public class TestInOrder {

@Test
public void test() {
    Foo foo = new Foo();
    Bar mockBar = mock(Bar.class);
    foo.run(mockBar);

    InOrder order = Mockito.inOrder(mockBar);
    order.verify(mockBar).A();
    order.verify(mockBar).B();
    order.verify(mockBar).B();
    order.verify(mockBar).A();
    order.verify(mockBar).B();
    }
}

class Foo {

void run(Bar mockBar) {
    mockBar.A();
    mockBar.B();
    mockBar.B();
    mockBar.A();
    mockBar.B();
}

}

class Bar {
public void A() {
}

public void B() {
}
}

The result is:
    org.mockito.exceptions.verification.VerificationInOrderFailure:
Verification in order failure:
bar.B();
Wanted 1 time:
-> at com.goeuro.pi.provider.busfor.TestInOrder.test(TestInOrder.java:19)
But was 3 times. Undesired invocation:
-> at com.goeuro.pi.provider.busfor.Foo.run(TestInOrder.java:32)

I don't understand why I get this error. Order of calls in test is the same as in method.

A: The issue is that you expect one invocation on each mock. Instead Mockito will count all the invocation on certain mock and will fail when 2 in a row will happen.
This is the implementation for verify method in InOrderImpl class.
public <T> T verify(T mock) {
    return this.verify(mock, VerificationModeFactory.times(1));
}

As you can see, it tells mockito to expect exact one invocation on method.
From JavaDoc:

Allows verifying exact number of invocations.

Use VerificationMode to tell Mockito how to verify you mock. This should help:
InOrder order = Mockito.inOrder(mockBar);
order.verify(mockBar).A();
order.verify(mockBar, times(2)).B();
order.verify(mockBar).A();
order.verify(mockBar).B();


text:
Q: Browser (Extension Script) Module not found: Error: Can't resolve 'fs' I am requiring a module (chinese-tokenizer) that uses fs. Webpack prompts an error that fs is not found. All solutions that I found online suggest to use target: 'node', however my application is meant for the 'web'.
Is there a way to avoid this error while still have the module work?

A: The issue probably happened because you are using Webpack 5. Traditionally, Webpack used to polyfill the core Node.js modules when the bundle was being created for browser/web. But that is no longer the case.
To address this, essentially, you will have to tell Webpack to polyfill this module. There are multiple options to do this.
First, you can use node-polyfill-webpack-plugin that takes cares of bundling any core Node.js module that Webpack encounters.
In you Webpack configuration, webpack.config.js file, just add this plugin:
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")

module.exports = {
  // Other config...
  plugins: [
    new NodePolyfillPlugin()
  ]
};

Second, you can write your own configuration to tell Webpack about this module:
// webpack.config.js
module.exports = {
  // Other configuration
  resolve: {
    fallback: {
      fs: require.resolve('fs')
    }
  }
};

Third, instead of using actual module, you can provide your own mocked implementation. This is what you should use as bundling actual fs modules doesn't make any sense for browser code and probably there will be transitive dependencies of fs modules that Webpack may fail to bundle. See this link for more details.
Also, make sure that you are not using the loadFile function provided by the  chinese-tokenizer module. That is the only function using the Node's fs module.


text:
Q: Minecraft 1.12 - execute entity when clicked on while empty handed I've seen this done before, and even though I am highly proficient in commands, it seems this is the only thing I can't quite figure out.
When I click on an empty armor stand while my hands are empty, I want it to execute a command on the clicked-on entity.  For example, I click on an entity (armor stand, villager, etc.) and lightning is summoned at the entity, or it tags the nearest sheep with a test tag.

A: To check hitting on a specific spot, you can put a "deactivated" mob at that location. To least affect the environment and have the same size as a player/standard mob, I recommend a skeleton:
/summon skeleton ~ ~ ~ {NoAI:1,NoGravity:1,Silent:1,ActiveEffects:{Id:14,Amplifier:1,Duration:2147483647,ShowParticles:0}}

To also make it not collide with the player, you can assign it to the same team as the player and then do:
/scoreboard teams option <team name> collisionRule pushOtherTeams

But if you are already using teams otherwise in your map, that might conflict with it.