text:
Q: JspException: Error reading the child resources of parent folder "/warrants/" I am getting the following error message when I try to login to the member section of my OpenCMS website./
javax.servlet.ServletException: javax.servlet.jsp.JspException: Error reading the child resources of parent folder "/warrants/".
I am very new to java and cant understand whats the issue.. Can anyone please help..
Best Regards,
Anz

A: I have to reference some source code even though you said you are new to java.
ERR_READ_RESOURCES_1 is the error message that you are seeing. That means you don't have permission to access the folder content.
Source code
/**
         * Reads all resources below the given path matching the filter criteria,
         * including the full tree below the path only in case the readTree
         * parameter is true.

         *
         * @param context the current request context
         * @param parent the parent path to read the resources from
         * @param filter the filter
         * @param readTree true to read all subresources
         *
         * @return a list of {@link CmsResource} objects matching the filter criteria
         *
         * @throws CmsSecurityException if the user has insufficient permission for the given resource (read is required)
         * @throws CmsException if something goes wrong
         *
         */
        public List readResources(CmsRequestContext context,
                CmsResource parent, CmsResourceFilter filter,
                boolean readTree) throws CmsException, CmsSecurityException {

            List result = null;
            CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
            try {
                // check the access permissions
                checkPermissions(dbc, parent, CmsPermissionSet.ACCESS_READ,
                        true, CmsResourceFilter.ALL);
                result = m_driverManager.readResources(dbc, parent, filter,
                        readTree);
            } catch (Exception e) {
                dbc.report(null, Messages.get().container(
                        Messages.ERR_READ_RESOURCES_1,
                        context.removeSiteRoot(parent.getRootPath())), e);
            } finally {
                dbc.clear();
            }
            return result;
        }


text:
Q: R Markdown - Automated Chunks? I am trying to automate chunk creation in an R markdown document. I am using the iris dataset just for this question. With this dataset there are 3 chunks, but my goal is to be able to create a document with a variable number of chunks. What I have so far is in two files - Parent.Rmd and Child.Rmd. The contents of these two files is shown below. The 3 headers are giving me what I expect. The problem is with the print(a) statement in the Child.Rmd file. It only prints the same data.frame each time, the data.frame for the last species, virginica. How do I fix this? Am I on the right track or should I be tackling this problem in another way?
Your help is appreciated. Thank you.
Paul
Parent.Rmd

---
title: "Parent"
output: pdf_document
---

```{r setup, echo=FALSE}
library(knitr)
```

```{r include=FALSE}
out = NULL
for (i in as.character(unique(iris$Species)))
{
  a <- iris[iris$Species == i, ]
  out = c(out, knit_expand(file = "Child.rmd"))
}
```

`r paste(knit(text = out), collapse = '\n')`

Child.Rmd
*********

#### Species = {{i}}

```{r echo=FALSE}
print(a)
```

A: You could perhaps do the subsetting in Child.Rmd
#### Species = {{i}}

```{r echo=FALSE}
a <- head(iris[iris$Species == "{{i}}", ])
print(a)
```

redpajama_set_name: RedPajamaStackExchange


text:
Q: Give drive permission to service account in Google Developer Console I'm trying to create a Google service account which has access to a Drive folder so I can use google-spreadsheets to read and write to files in the folder. During development I created a service account under my unmanaged Google account. The user account has owner access. In order to be allowed access I needed to change the document sharing settings to public (with link access). For development this is no issue, but of course in production I do not want my data to be publicly accessible.
How do I make sure the service account has access to the document while it is not publicly shared (shared within organisation is preferred)? Setting it to organisation access only, the api gives me a 403 (Forbidden) code.

A: Service accounts are dummy users.   You can take the service account email address and share a folder on your personal drive account with the service account.  Give it write access and it will be able to read and write to this folder.
Just remember that when uploading to this folder you will need to have the service account grant your personal user access to the file or your going to have files on your drive account that you dont own and cant access.


text:
Q: Swift uses the wrong equality function to determine if an array contains an object I have a class A which conforms to Equatable and a class B which inherits from A. I defined == for each of these classes.
When comparing two B objects, the correct == function is used to determine the equality. When checking to see whether an array of B contains an object B, the == defined for A will be called.
//: Playground - noun: a place where people can play

class A: Equatable {
    var id: Int

    init(id: Int) {
        self.id = id
    }
}

class B: A {
}

func ==(lhs: A, rhs: A) -> Bool {
    print("Comparing using A's ==")
    return false
}

func ==(lhs: B, rhs: B) -> Bool {
    print("Comparing using B's ==")
    return lhs.id == rhs.id
}

let b1 = B(id: 1)
let b2 = B(id: 2)

let array: [B] = [b1, b2] // an array explicitly defined as containing B objects

print("\((b2 == b2))")
print("\(array.index(of: b2))")
print("\(array.contains(b2))")

Output:
Comparing using B's ==
true
Comparing using A's ==
Comparing using A's ==
nil
Comparing using A's ==
Comparing using A's ==
false

Why is this happening?
EDIT: SOLVED!
As Hamish commented below, this is because B will rely on A's == in certain cases, for more, see here, point #2: == overload for custom class is not always called
To work around this I did the following: I defined a method called isEqualTo(object:) that is called from A's ==. That method is overridden from B.
This is probably a little bit more inefficient because of the overhead of going through another few method calls, but it works good enough for the data I am dealing with.
//: Playground - noun: a place where people can play

class A: Equatable {
    var id: Int

    init(id: Int) {
        self.id = id
    }

    // define an isEqualTo method which takes another A instance
    // this will be called from A's ==
    func isEqualTo(object: A) -> Bool {
        return self == object
    }
}

class B: A {

    // override the isEqualTo: method
    override func isEqualTo(object: A) -> Bool {

        // if we are actually dealing with an object of type B, cast it
        // first, then call B's ==
        if let bObject = object as? B {
            return self == bObject
        }

        // fallback to A's  ==
        return super.isEqualTo(object: object)
    }
}

func ==(lhs: A, rhs: A) -> Bool {
    print("Comparing using A's ==")
    // use a designated, overridable method to determine equality
    return lhs.isEqualTo(object: rhs)
}

func ==(lhs: B, rhs: B) -> Bool {
    print("Comparing using B's ==")
    return lhs.id == rhs.id
}

let b1 = B(id: 1)
let b2 = B(id: 2)

let array: [B] = [b1, b2]

print("\((b2 == b2))")
print("\(array.index(of: b2))")
print("\(array.contains(b2))")

Output:
Comparing using B's ==
true
Comparing using A's ==
Comparing using B's ==
Comparing using A's ==
Comparing using B's ==
Optional(1)
Comparing using A's ==
Comparing using B's ==
Comparing using A's ==
Comparing using B's ==
true


text:
Q: swf chart not displayed in chrome I want to display the Chart of swf type. It is displayed proeprly in firefox and ie but in chrome it is not displayed. In chrome the chart will be displayed after a click on the chart div. Data for chart is loaded properly but will be displayed only on click.
my code is:
<?php
 $link = "/flash/Chart.swf?theXml=".urlencode(url_for('@chartCompare?series='.$seriesName.'&id='.$seriesId.'&source='.$sourceName,true));
?>

<div style="margin-top:10px; margin-bottom:10px">
 <object style="z-index:-1" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="560" height="180" id="Chart" align="middle" >
  <param name="allowScriptAccess" value="sameDomain" />
  <param name="allowFullScreen" value="false" />
  <PARAM NAME="WMODE" VALUE="transparent">
  <param name="movie" value="<?php  echo $link; ?>" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" />
  <embed src="<?php echo $link; ?>" wmode="transparent" quality="high" bgcolor="#ffffff" width="560" height="180" name="Chart" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
 </object>
</div>

Anybody have any idea? ...Thanks in advance.

A: Try removing param movie, worked for me.  It's kind of a hack but you just turn off that line if chrome (or can try !IE since firefox probably doesn't need it either).
Others have had luck with swfobject loading: http://www.adobe.com/devnet/flashplayer/articles/swfobject.html


text:
Q: Indenting ListView items Android I am trying to indent listView row by certain factor. For this, I used view.layout() and view.setX() method but they don't work or result in forceclose. Is there a way to achieve this result. Here is my code:
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View newRowView = convertView;
    ViewHolder viewHolder;

    if(newRowView == null)
    {

    LayoutInflater inflator = (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    newRowView = inflator.inflate(R.layout.list_view_images, parent,false);

    //newRowView.layout(100*(position/list.size()), 0, 0, 0); // not working

    newRowView.setX(100*(position/list.size())); // causing force close

    viewHolder = new ViewHolder();

    viewHolder.appIcon = (ImageView) newRowView.findViewById(R.id.imageView1);

    viewHolder.appName = (TextView) newRowView.findViewById(R.id.textView1);

    viewHolder.appName.setText(names.get(position));

    newRowView.setTag(viewHolder);

}

list_view_images.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>

I am trying to indent the list in semi circular fashion.
What can I do achieve required results?
Regards

A: Update your getView() method as follows:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View newRowView = convertView;
    ViewHolder viewHolder;

    if (newRowView == null) {

        LayoutInflater inflator = (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        newRowView = inflator.inflate(R.layout.list_view_images, parent, false);

        viewHolder = new ViewHolder();
        viewHolder.innerContainer = (LinearLayout) newRowView.findViewById(R.id.innerContainer);
        viewHolder.appIcon = (ImageView) newRowView.findViewById(R.id.imageView1);
        viewHolder.appName = (TextView) newRowView.findViewById(R.id.textView1);
        viewHolder.appName.setText(list.get(position));
        newRowView.setTag(viewHolder);
    }
    else {
        viewHolder = (ViewHolder) newRowView.getTag();
    }

    float shiftRight = 100 * ((position * 1.0f) / list.size());
    viewHolder.innerContainer.setPadding((int) shiftRight, 0, 0, 0);

    //...
    //...

    return newRowView;
}

Update your XML layout as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/innerContainer"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

    </LinearLayout>

</LinearLayout>

Update your ViewHolder to contain another field as following:
public LinearLayout innerContainer;

Explanation: Basically, we put your original XML layout inside a LinearLayout that acts as an outer container. The we assign padding to the innerContainer (original layout) with respect to the outer layout


text:
Q: Open vbp file with text editor I have a vbp file that I would like to open with a computer without vb.  I don't need to run the file, but I would just like to look at the source code.  Is it possible to do this with a text editor?

A: .vbp files are Visual Basic project files; they don't contain any VB source code.
That being said, you can certainly open source code files in something like Notepad or Wordpad, or some other text editor equivalent. The source code is just plain text.
In Notepad and Wordpad, just open them up and use File -> Open or Ctrl+O. (Set the file type filter to All Types (*.*) or All Documents (*.*).)

A: Yes; it's a plain-text file.
Note that the VBP file is the project file; it references the other files, but does not contain source code.
However, the actual source files (.frm, .bas, etc) are also plain-text.


text:
Q: How to get selected value of dropdownlist in edititemtemplate - datagridview? I've created a DropDownList in a DataGrid EditItemTemplate. (Manually)
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
                        DataSourceID="SqlDataSource1" DataTextField="nazwa" DataValueField="nazwa"
                        SelectedValue='<%# Bind("nazwa") %>'>
                    </asp:DropDownList>
                    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                        ConnectionString="<%$ ConnectionStrings:baza_pismConnectionString1 %>"
                        SelectCommand="SELECT [nazwa] FROM [podmioty]"></asp:SqlDataSource>
</EditItemTemplate>

how can I get the selected value from the dropdownlist in the code behind?

A: I guess you want to find the value of dropdown during editing, this code will do
    protected void gridview1_RowEditing(object sender, GridViewEditEventArgs e)
        {
GridViewRow row = gridview1.Rows[e.RowIndex];

            DropDownList ddl = row.FindControl("DropDownList1") as DropDownList;
        var value=ddl.SelectedValue;
            //now do whatever with that value
        }


text:
Q: Hyperlinks in bibtex bibliography I am using BibTex to write the bibliography of my document. I also want that when I cite some of my references an hyperlink appears in the pdf so as when one click it it will redirect to the bibliography item that corresponds.
The problem is that with my actual setting next to the bibliography entries a series of numbers appers which redirect to every page where I have a reference of that particular entry. For example:
[9] John C. Strikwerda. Finite Difference Schemes and Partial Differential Equations. Society for Industrial and Applied Mathematics, Philadelphia, 2004. 16, 19, 20
Notice the numbers 16,19, 20 at the end. Those are in fact references to the pages where I referenced that particular book. I would like them to disappear. The references in the pages appear as [9] where the number 9 is a reference to the bibliography entry. This is my desired setup.
A sample to reproduce my issue:
\documentclass[a4paper,11pt,twoside]{book}

\usepackage[pagebackref=true]{hyperref}
\hypersetup{
    colorlinks=true,
    linkcolor=blue,
    citecolor=green,
    filecolor=magenta,
    urlcolor=blue
}

\begin{document}
 %citation
 An interesting book \cite{vnewmann}

 % biblio
 \bibliographystyle{plain}
 \bibliography{trashbib}

\end{document}

With the trashbib.bib file as follows
@article{vnewmann,
   author={{V}on{N}ewmann, {J}. and {R}ichtmyer, {R}. {D}.},
   title={{A} {M}ethod for the {N}umerical {C}alculation of {H}ydrodynamic {S}hocks},
   journal={{J}ournal of {A}pplied {P}hysics},
   volume={21},
   year = 1950,
   pages = {232-237}
 }

Anyone knows how to get rid of the numbers (with references to the text) next to the bibliography items while keeping the references to the bibbliography in the text?

A: Those numbers are called 'back references'. Remove the [pagebackref=true] bit, and they'll go away.


text: Q: Make beamer accessible (visual impairment)? I wanted to know if it is possible to include "Speaker notes" in the beamer slides. I want to make a presentation accessible and use the speaker notes to also add detailed descriptions of the figures, tables and so on.


text:
Q: Where Do I Insert my DJI Windows SDK App Key I created my app key as per the Readme, but I do not know where to add it.  I am also getting the errors below. I have not connected a drone yet because I do not own a compatible model.

Error Output

A: The information to add the app key is in DJI's WSDK API documentation under: method RegisterApp.  You can find an example in DJI's Github WSDK Sample App here: DJISDKManager


text:
Q: How to convert this curl request to Http post request for file upload in java? Following is my curl request:
curl -X POST --data-urlencode 'data1@/Users/Documents/file.csv' http://localhost:8000/predict

Following is my equivalent Java implementation.
String filePath = inputFilePath;
        String url = inputUrl;
        File file = new File(filePath);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost uploadFile = new HttpPost(inputUrl);
        uploadFile.addHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        FileBody fileBody = new FileBody(new File(inputFilePath));

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("data1", fileBody)
                .build();

        uploadFile.setEntity(reqEntity);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(uploadFile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

I am trying to invoke my R Rest API endpoint from my Java HTTP post.
#* @post /predict
mypredict <- function(data1) {
  print(data1)

}

(1) Is my equivalent Java HTTP Post request correct?
(2) I am able to invoke the R rest endpoint using my curl command. But for some reason when i sent the POST request through my Java code, i see that data1 is not being passed as part of post request. I see this error in R.
<simpleError in print(data1): argument "data1" is missing, with no default>

I feel my Java equivalent curl implementation is wrong. Can someone help?

A: You specify content-type application/x-www-form-urlencoded (as curl does for this case) but supply an actual body (entity) that corresponds to multipart/form-data which is radically different. Instead use URLEncodedFormEntity containing (for your case) one NameValuePair something like this:
byte[] contents = Files.readAllBytes (new File(filepath).toPath());
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("data1", new String(contents,charset));
uploadFile.setEntity(new UrlEncodedFormEntity (list));

And you don't need addHeader("content-type",...) because setting the entity automatically supplies the content-type header (and content-length).


text:
Q: Show window in OS X >= 10.10 (plugin template)? There are a lot of similar questions but they appear to be too old - nothing happens, beginSheet:... methods undeclared and etc. I need something like the following (but for window in OS X):
//just created class with option "also create xib"
MyViewController *vc = [[MyViewController alloc] initWithNibName:@"..." bundle:nil];
[self.navigationController pushViewController:controller animated:NO];

So for example I create NSWindowController with xib via the similar way and run [NSApp beginSheet:...] but it falls down on any from beginSheet:... methods. But this example is even described in apple documentation.
What I'm doing wrong? Is it because of I use plugin template downloaded via Alcatraz which doesn't have any window from the beginning but should show it on menu item click?

A: You incorrectly used subclass of NSViewController, namely "MyViewController". What you need is a subclass of NSWindowController. As a sheet you can only use NSWindow (not NSView). If you are trying to run window modally (this means having dependant window) make sure there is existing window displayed.
The case when there is no window you can achieve with creating new subclass of NSWindowController with a XIB. Then instantiate like this:
    @interface SomeClass {
      CustomWindowController *customWindowController;
    }

    - (IBAction)createNewWindow:(id)sender {
      customWindowController = [[CustomWindowController alloc] initWithWindowNibName:@"NameOfXib"];
      [customWindowController showWindow:nil];
    }

More info about sheets: Using Application-Modal Dialogs


text:
Q: How to make a macro ignore tables? I have the following code that deletes the paragraph following any entirely bold paragraphs (i.e. deletes blank lines following subheadings), but this has caused an issue with the part of my macro that converts text to tables, in that it deletes the content following a table header when the table has bold headers. Is there a way I can get this code to ignore tables?
Dim para As Paragraph
Dim searchRange As Range

Set searchRange = Selection.Range
searchRange.End = ActiveDocument.Content.End

For Each para In searchRange.Paragraphs
    If para.Range.Font.Bold = True Then para.Next.Range.Delete
Next para

A: You can utilize the Information property of the Range.
Try something like:
Dim para As Paragraph
Dim searchRange As Range

Set searchRange = Selection.Range
searchRange.End = ActiveDocument.Content.End

For Each para In searchRange.Paragraphs
    If para.Range.Font.Bold = True And Not para.Range.Information(wdWithInTable) Then para.Range.Next.Delete
Next para


text:
Q: How to set checkbox as checked by testing array result against another array? I wanted to display checkbox as checked by testing one array from query result and another one also from a query result, but I can't seem to get it...
Here's what I've come up with so far:
first query:
$getbficiaryres = mysqli_query($link, "
SELECT
    a.`id`,
    b.`id` as `bfryid`, b.`bficiaryname`,
    c.`notes` as `bfrynotes`
FROM
    `activity` a, `beneficiary` b, `bficiarynotes` c, `actbficiary_link` d
WHERE
    a.`id` = c.`activity_id` AND
    a.`id` = d.`activity_id` AND
    b.`id` = c.`beneficiary_id` AND
    b.`id` = d.`beneficiary_id` AND
    a.`id` = '".$edit."'");

$getbficiaryrow = mysqli_fetch_array($getbficiaryres);

first query result:
id  bfryid  bficiaryname bfrynotes
1   2       xxx          xxx notes
1   4       yyy          yyy notes

second query:
$bficiaryres = mysqli_query($link, "SELECT `id`, `bficiaryname` FROM `beneficiary`");

second query result:
id  bficiaryname
1   aaa
2   xxx
3   bbb
4   yyy

php codes:
$i = 0;
while($bficiaryrow = mysqli_fetch_array($bficiaryres)){
    if($bficiaryrow['id'] == $getbficiaryrow['bfryid']){
        echo '

                    <input type="checkbox" name="pmanfaat['.$i.']" value="'.$getbficiaryrow['bfryid'].'" checked />'.$getbficiaryrow['bfryname'].'

<textarea name="ketpmanfaat['.$i.']" class="form-control">'.$getbficiaryrow['bfrynotes'].'</textarea>

';

    }else{
        echo '

                    <input type="checkbox" name="pmanfaat['.$i.']" value="'.$bficiaryrow['id'].'" />'.$bficiaryrow['bficiaryname'].'

<textarea name="ketpmanfaat['.$i.']" class="form-control"></textarea>

';
    }
    $i++;
}

The result that I'm expecting was to get two checkboxes xxx (id no 2)and yyy (id no 4) set as checked, but the only thing that was checked is the xxx.
How do I loop properly to get all the arrays tested?
I hope my question is clear enough.
My head' about to blow... Any help is really appreciated.
Thank you.

A: A better way to do this, than my comment, is to populate both arrays with you data and then follow something on the lines of code given below.
Let's suppose you build two arrays as given in example. Then iterate over the first array and search the value in second array. If a match is found, you display the checked checkbox and do nothing otherwise
$arr1 = array("xxx", "yyy");
$arr2 = array("aaa", "xxx", "bbb", "yyy");

foreach ($arr1 as $key => $val){
    if (in_array($val, $arr2)){
        echo("checked: ".$val."
");
    }
}

A: Thank you @mynawaz, although I'm still struggling after that, I really appreciate your trying to help. I've had learn more about arrays. Still a loong way to go for me... just keep moving forward :D
After a week or so, I finally understand, what I need is another mysql query to get the paired result using LEFT JOIN. This post helps me understand it better: answers from one of stackoverflow
thx so


text:
Q: Smoothly Updating Bitmap Just to add a surprise factor to my game, I have decided to invert the background colors randomly. When the player collects, let's say, 21 golden bacon strips the background changes. By modifying the bitmap's pixels, I have done this through the following code:
public void invert() {
    int length = BackBitmap.getWidth() * BackBitmap.getHeight();
    int[] array = new int[length];
    BackBitmap.getPixels(array, 0, BackBitmap.getWidth(), 0, 0, BackBitmap.getWidth(), BackBitmap.getHeight());
    int[] array2 = new int[length];
    int a2 = 0;

    for(int col = 0; col < BackBitmap.getHeight(); col++){
        for (int row = 0; row < BackBitmap.getWidth();row++){
            array2[a2] = BackBitmap.getPixel(row,col);
            a2++;
        }
    }

    for (int i=0;i<length;i++){
        array[i] = 0xFFFFFF - array2[i];
        }
    BackBitmap = BackBitmap.copy(Bitmap.Config.ARGB_8888, true);
    BackBitmap.setPixels(array, 0, BackBitmap.getWidth(), 0, 0, BackBitmap.getWidth(), BackBitmap.getHeight());
}

However once the colors are inverted, the game encounters major lag. To my surprise I thought this way of updating bitmap would be the most effective - memory-wise. What would be the right way to approach this error?

A: public void invert() {
    int length = BackBitmap.getWidth() * BackBitmap.getHeight();
    int[] array = new int[length];
    int[] array2 = new int[length];
    BackBitmap.getPixels(array2, 0, BackBitmap.getWidth(), 0, 0, BackBitmap.getWidth(), BackBitmap.getHeight());

    for (int i=0;i<length;i++){
        array[i] = 0xFFFFFF - array2[i];
    }
    BackBitmap = BackBitmap.copy(Bitmap.Config.ARGB_8888, true);
    BackBitmap.setPixels(array, 0, BackBitmap.getWidth(), 0, 0, BackBitmap.getWidth(), BackBitmap.getHeight());
}

This is how I would write it.  You were writing to array and then rewriting it without using it.
This may not reduce lag significantly but it may help to a degree.


text:
Q: Woocommerce search result showing all products of the shop Recently, I got a website developed in WooCommerce by a developing company. Due to his unnecessary money demand, I need to take back my website from him and I did't noticed that product search isn't working.
The issue is whenever I start typing in the search bar, by live search I am getting the product name. But when I search the name of the product or anything and hit enter immediately the search result takes me to the shop page where all products are shown. None of the related products show up. I followed some solution like
I just copied it to function.php, the situation is same.
function wp_search_filter($query) {
$url = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if ( (strpos($url,'post_type=product') !== false) && is_search() ) {
    $query->set('post_type', 'product');
}
return $query;
}

add_filter('pre_get_posts','wp_search_filter');

A: You may find the solution on this webpage
https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query
When I have time I will try to create a better explanation,
I would recommend you work with a custom var or using some custom taxonomies as Key, because using this.
function wp_search_filter($query) {
 $url = 'https://' . $_SERVER['SERVER_NAME'] .
$_SERVER['REQUEST_URI'];
if ( (strpos($url,'post_type=product') !== false) && is_search() ) {
$query->set('post_type', 'product');
}
return $query;
}

add_filter('pre_get_posts','wp_search_filter');

let give a Example, You would search for a shirt, and the bone product has "shirt" word in description this wp_search will get the bone as well, it happed in a project of mine.


text:
Q: problem with Context "getApplicationContext()' on a null object reference" I made nonActivity class, and I use there other nonActivity Database class. When I call method from 1st class I have Error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Here is a fragment of my code of both classes:
DataBase.java
 public DataBase(Context context) {
        super(context, DATABASE_NAME, null, TABLE_VERSION);
   }

and ObliczPodatki.java
public class ObliczPodatki extends Application
.
.
.
myDb = new DataBase(this.getApplicationContext());

and the full error message:
Process: com.example.nadgraniav01, PID: 11274
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
        at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:116)
        at com.example.nadgraniav01.ObliczPodatki.obliczPodatki(ObliczPodatki.java:43)
        at com.example.nadgraniav01.DodajNadgranieActivity$2.onClick(DodajNadgranieActivity.java:99)
        at android.view.View.performClick(View.java:6669)
        at android.view.View.performClickInternal(View.java:6638)
        at android.view.View.access$3100(View.java:789)
        at android.view.View$PerformClick.run(View.java:26145)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6863)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

if I use this instead of this.getApplicationContext() I am getting following erroe
Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference

A: Try this then:
 @Override
 public void onCreate() {
  super.onCreate()
  SQLiteHandler db = new SQLiteHandler(getApplicationContext());
  ....rest of db calls..
}

A: Use:
 myDb = new DataBase(getApplicationContext());

Or,
 myDb = new DataBase(Activityname.this);

A: getApplicationContext is not the context that you should use,
Use this instead
myDb = new DataBase(this);

A: You have to initialise myDb variable in onCreate() method of ObliczPodatki class.
   myDb = new DataBase(getApplicationContext());


text:
Q: Jenkins is not automatically building new tags Using multibranch pipelines. I know Jenkins will not build a tag if the tagged commit has already been built: jenkins trigger build if new tag is released
But Jenkins is not even building tags for new commits for me.
I tried doing this:
# create a NEW commit
git commit -am 'new commit'
# tag after creating this commit
git tag testtag01
# push the tag
git push origin testtag01

The tag is discovered but it doesn't do anything. I should be triggering a new build which happens if a new branch is created or if a commit to a remote branch is pushed.


text:
Q: Why does using theme() in ggplot deletes my beforehand specified labs() command? It seems to be the case that as soon as I call theme() in ggplot2 my previous labs() for the same plot gets deleted/overwritten. I surfed for 5 hours now and I do not see the solution. Does anyone see the reason why this happens? You would save my week.
This is my code:
#creating variables and store them in new data frame

rel_pred <- fitted(rel)
rel_resid <- residuals(rel)
data1 <- data.frame(rel_resid, rel_pred)`

#plot the data

plot1 <- ggplot(data1, aes(x=rel_pred,y=rel_resid)) +
geom_point() +
geom_hline(yintercept=0, colour='red') #so far so good, everything works

plot1 + labs(y="Residuals", x="Fitted Values SF-12 MCS", caption="Figure
1. Residuals vs. fitted Values Model 1") #when I run this, it perfectly
adds labels

Here comes the problem: as soon as I run theme() with whatever elements in there, it will make my previous labels disappear.
plot1 + theme(panel.background = element_rect(fill='transparent'),
plot.background = element_rect(fill='transparent'),
panel.border = element_blank(),
axis.line = element_line(colour="black", size=1),
axis.title.x = element_text(colour='black',size=6),
axis.title.y = element_text(colour='black', size=6),
plot.caption = element_text('Figure 1. Residuals vs. fitted Values Model
1')
)

A: As Richard said, you forgot to "update" plot1 as the result of adding labels to the original plot.
Here:
plot1 <- ggplot(data1, aes(x=rel_pred,y=rel_resid)) +
geom_point() +
geom_hline(yintercept=0, colour='red') #so far so good, everything works

plot1 + labs(y="Residuals", x="Fitted Values SF-12 MCS", caption="Figure
1. Residuals vs. fitted Values Model 1") #when I run this, it perfectly
adds labels

Try instead
plot1 <- ggplot(data1, aes(x=rel_pred,y=rel_resid)) +
geom_point() +
geom_hline(yintercept=0, colour='red') #so far so good, everything works

plot1 <-  plot1 + labs(y="Residuals", x="Fitted Values SF-12 MCS", caption="Figure
1. Residuals vs. fitted Values Model 1") # no output now, it will save the result as plot1

and then
plot1 + theme(panel.background = element_rect(fill='transparent'),
plot.background = element_rect(fill='transparent'),
panel.border = element_blank(),
axis.line = element_line(colour="black", size=1),
axis.title.x = element_text(colour='black',size=6),
axis.title.y = element_text(colour='black', size=6),
plot.caption = element_text('Figure 1. Residuals vs. fitted Values Model
1')
)

will work as expected


text:
Q: Spring SPEL : setRemoteDirecotoryExpression issue I'm trying to set the remote directory for my SFTP server using Java Spring's SPEL language. Basically I'm trying to append two strings together as my remote directory path, but for some reason I'm still trying to figure out, it does not work.
Here's what I do :
ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
Expression exp = EXPRESSION_PARSER.parseExpression("headers['path']"); //which contains the 2nd part of the path to my dir
String fullFilePath = this.remoteDir; //which has the 1st part of the path to my directory
SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());
handler.setRemoteDirectoryExpressionString(this.remoteDir.concat("/").concat(exp.getValue().toString()));
handler.setAutoCreateDirectory(true);

There is seemingly something wrong with the exp.getValue()method, because I get the following exception whenever that line is not commented :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SFTPConfig' defined in file [/Users/psdev/PrediSurge/backend/file-service/target/classes/com/predisurge/planopsuite/microservices/fileservice/sftp/SFTPConfig.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handler' defined in class path resource [com/predisurge/planopsuite/microservices/fileservice/sftp/SFTPConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.messaging.MessageHandler]: Circular reference involving containing bean 'SFTPConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'handler' threw exception; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:584) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at com.predisurge.planopsuite.microservices.fileservice.FileServiceApplication.main(FileServiceApplication.java:26) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_241]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_241]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_241]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.2.RELEASE.jar:2.1.2.RELEASE]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handler' defined in class path resource [com/predisurge/planopsuite/microservices/fileservice/sftp/SFTPConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.messaging.MessageHandler]: Circular reference involving containing bean 'SFTPConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'handler' threw exception; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.resolveTargetBeanFromMethodWithBeanAnnotation(AbstractMethodAnnotationPostProcessor.java:464) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.postProcess(AbstractMethodAnnotationPostProcessor.java:146) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.processAnnotationTypeOnMethod(MessagingAnnotationPostProcessor.java:190) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.lambda$postProcessAfterInitialization$0(MessagingAnnotationPostProcessor.java:163) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:589) ~[spring-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.postProcessAfterInitialization(MessagingAnnotationPostProcessor.java:144) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:434) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1749) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 20 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.messaging.MessageHandler]: Circular reference involving containing bean 'SFTPConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'handler' threw exception; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 38 common frames omitted
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:213) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:91) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:53) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:89) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:109) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:138) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at com.predisurge.planopsuite.microservices.fileservice.sftp.SFTPConfig.handler(SFTPConfig.java:101) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_241]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_241]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_241]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 39 common frames omitted

I'm not new to Java Spring but I've never used SPEL before, so I'm very unsure what's wrong.
Any help would be appreciated.

A: handler.setRemoteDirectoryExpressionString(this.remoteDir.concat("/").concat(exp.getValue().toString()));
The expression has to be evaluated at runtime against a messagee, you are evaluating the expression during configuration time against nothing.
Use
"'" + this.remoteDir + "/' + headers['path']"

so the headers['path'] is evaluated against the message sent to the handler.

A: The EL expression "headers['path']" probably refers to a map, containing key "path". By default spring expression parser has no information about external variables. You should create an instance of StandardEvaluationContext, register the variable "headers" there and use this context, when getting expression value:
ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();

// create context and register variable "headers"
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("headers",headers);

Expression exp = EXPRESSION_PARSER.parseExpression("headers['path']");
String fullFilePath = this.remoteDir;
SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());

// use context, when getting evaluated value
 handler.setRemoteDirectoryExpressionString(this.remoteDir.concat("/").concat(exp.getValue(context).toString()));
        handler.setAutoCreateDirectory(true);

Here is a reference for using variables in spring EL.


text:
Q: Jquery Taphold not working on dragdealerjs slider I am adding a series of divs with dragdealerjs functionality. The problem is I need to be able to tap and hold the ".handle" div inorder to expose a slider/drawer below it. I have simplified my code down to get to the root of the problem. I am appending the ".innerGroup" div to the ".groups" div.
HTML:

Javascript:
This code doesn't work,
$(document).on('taphold', '.handle', function() {
 alert('Tapped');
});

This code does work though,
$(document).on('click', '.handle', function() {
 alert('Tapped');
});

I know there are several other similar answers to this one here but I fear that drag dealer may be complicating the issue. I also think the problem is related to adding the innerGroup after the DOM has loaded. Thanks in advance.

A: The error here is that drag dealer actually takes control of the taphold event. To work around  you need to take a two stage check with a 750 millisecond time out (same as a standard taphold) and put the distance the slider can move as .49-.51 (or something similar ). If anyone wants the code leave a comment here and ill post what I come up with.
Happy coding


text:
Q: Core Data - database not found when Updating App on App Store We have an app currently up on the app Store. Recently we put up a new version that now uses a preloaded Core Data database.
When a user does a fresh install of the new version, there is no problem.
When a user updates from a previous version, there is an issue. The app appears blank and it's as if it can't find the Core Data database.
I thought there was only migration issues when changing Core Data model. Is there also migration issues I should look out for when updated an existing app from using no Core data to using Core Data?
Any advice would be greatly appreciated.
Thanks


text:
Q: Service and Thread I want to build an application that start a Service. This Service can run also if the APP is closed.
So I'm building this code on the OnCreate method of my BLEActivity.java:
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ble);
        startService(new Intent(this, BlePowerService.class));
}

Now I want that this service shoudl to start every 5 minutes also if the APP is closed.
The correct way to do this, is to create a Thread into BlePowerService ?
So I'm building this:
public class BlePowerService extends Service {
    public DbLayer db;
    Setting settingApp;
    List<ScanFilter> filters;
    String[] stringSequence = new String[] {CHARACTERISTIC_FORZA_STRING};
    BluetoothAdapter mBluetoothAdapter;
    BluetoothGatt mGatt;
    BluetoothDevice currDevice;
    static final long SCAN_PERIOD = 1000;
    BluetoothLeScanner mLEScanner;
    Handler mHandler;
    int ReadQueueIndex;
    List<BluetoothGattCharacteristic> ReadQueue;
    ScanSettings settings;
    int id = 1000;
    boolean valore;
    //String UuID = "f0001132-0451-4000-b000-000000000000";
    String LOG_CODE = "NOTIFSRV";
    int NOTIFICATION_GREEN = 1;
    int NOTIFICATION_RED = 2;
    int START_HOUR = 7;
    int RANGE_HOURS_WEIGHT = 13;
    int START_NOTIFY = 9;
    int END_NOTIFY = 21;
    public static String PAR_NOTIFICATION_EXERCISEID = "parNotificationExerciseId";
    String NEW_ACTIVITY_START = "NAS";
    String OPEN_ACTIVITY_START = "OAS";

    public BlePowerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler();

        Context sharedContext = null;
        try {
            sharedContext = this.createPackageContext(
                    "com.eresult.diabesitycare.devicesensor",
                    Context.CONTEXT_INCLUDE_CODE);
            if (sharedContext == null) {
                return;
            }
            db=new DbLayer(sharedContext);
            db.open();

        } catch (Exception e) {
            String error = e.getMessage();
          //  Log.d(LOG_CODE,"DB error : " + error);
            return;
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            //RECUPERO LE IMPOSTAZIONI SETTATE DALL'UTENTE
            settingApp = db.fetchSetting();
            mTimer = new Timer();
            mTimer.schedule(timerTask, 2500, 1 * 60 * 1000);
        } catch (Exception e) {
           // Log.e("POWER_SERVICE", e.getMessage());
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private Timer mTimer;

    TimerTask timerTask = new TimerTask() {

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void run() {
            //LEGGO TUTTI I DATI DAL SENSORE FINCHE CI SONO VALORI
            valore = true;
            int conta = 0;
            while(valore){
                conta++;
                Log.v("CICLO WHILE", conta+"");
                if (currDevice != null) {
                    GattClientCallback gattClientCallback = new GattClientCallback();
                    mGatt = currDevice.connectGatt(getBaseContext(), false, gattClientCallback);
                    scanLeDevice(false);// will stop after first device detection
                }else{
                    //provo a ricollegarmi al dispositivo probabile, abbia perso la connessione con esso
                    scanLeDevice(true);
                }
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }
    };

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void connectToDevice(BluetoothDevice device) {
        //VERIFICO SE IL DEVICE è QUELLO CHE VOGLIO IO
        if (mGatt == null && settingApp != null
                && device.getAddress().equals(settingApp.getAddressBleSX())) {
            currDevice = device;
            GattClientCallback gattClientCallback = new GattClientCallback();
            mGatt = currDevice.connectGatt(getBaseContext(), false, gattClientCallback);
            scanLeDevice(false);// will stop after first device detection
        }
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi,
                                     byte[] scanRecord) {
                    Handler h = new Handler(getApplicationContext().getMainLooper());
                    // Although you need to pass an appropriate context
                   //TO DO
                }
            };

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void scanLeDevice(final boolean enable) {
        //TO DO
    }

    private ScanCallback mScanCallback = new ScanCallback() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
           //TODO
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private class GattClientCallback extends BluetoothGattCallback {

        @SuppressLint("LongLogTag")
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            try{
                //TODO
            }catch(Exception e){
                Log.e("ON_CONNECTION_STATE_CHANGE", e.getMessage());
            }
        }

        public void disconnectGattServer() {
            valore = false;
            if (mGatt != null) {
                mGatt.disconnect();
                mGatt.close();
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);
        //TODO
        }

        private void ReadCharacteristics(int index) {
            mGatt.readCharacteristic(ReadQueue.get(index));
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
          //  Log.i("INFO", "Characteristic changed, " + characteristic.getUuid().toString());
            readCharacteristic(characteristic);
        }

        private void enableCharacteristicNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
           //TODO
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            //TODO
        }
    }
}


text:
Q: HTML file structure's affect on website URL I currently have a simple website, hosted on github pages with a file structured in hierarchical directories as shown below:
/foobar.com
 /css
 /js
 /images
 /html
      /news
           /news_content
                fizz.html
                buzz.html
           news.html
       about.html
       contact.html
 index.html

However, when I am on the buzz webpage for example, this has resulted in the URL to become:
https://foobar.com/html/news/news_content/buzz.html
Is there a way to change this URL so that it doesn't show all the folder directories and instead, just the file itself i.e. https://foobar.com/buzz.html as I don't want to separate all the individual HTML files into separate folders?

A: Yes, you can change the URL to be more user-friendly by using server-side URL rewriting or client-side JavaScript.
For server-side URL rewriting, you'll need to use a web server such as Apache or Nginx and configure it to rewrite the URLs. You can find more information on how to do this for Apache or Nginx by searching for "URL rewriting" on their websites or forums.
For client-side URL rewriting, you can use JavaScript to manipulate the URL shown in the browser's address bar. However, this method may not be ideal for search engines or users who have JavaScript disabled.
If you are using GitHub Pages to host your website, you might be able to achieve URL rewriting by using Jekyll. Jekyll is a static site generator that supports URL rewriting and can be used in combination with GitHub Pages to host your website. You can find more information on how to do this by searching for "Jekyll URL rewriting."

A: How a URL is resolved to a resource depends on the HTTP server and/or the server side programming language you are using.
Github Pages provides no features that allow anything other than a direct reflection of the directory layout in the URL.
The closest you could come would be to write a program that transformed the input (the file structure you want to work with) into the file structure that Github Pages will express as the URLs you desire (and then run it as a build step that takes the pages out of your working branch and into your gh-pages branch; possibly you could use actions to do this).


text:
Q: Problems sampling D3D11 depth buffer I'm getting everything ready in a little DirectX 11.0 project of mine for a deferred rendering pipeline. However, I've been having quite a lot of trouble with sampling the depth buffer from within a pixel shader.
First I define the depth texture and its shader resource view:
    D3D11_TEXTURE2D_DESC depthTexDesc;
    ZeroMemory(&depthTexDesc, sizeof(depthTexDesc));
    depthTexDesc.Width = nWidth;
    depthTexDesc.Height = nHeight;
    depthTexDesc.Format = DXGI_FORMAT_R32_TYPELESS;
    depthTexDesc.Usage = D3D11_USAGE_DEFAULT;
    depthTexDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
    depthTexDesc.MipLevels = 1;
    depthTexDesc.ArraySize = 1;
    depthTexDesc.SampleDesc.Count = 1;
    depthTexDesc.SampleDesc.Quality = 0;
    depthTexDesc.CPUAccessFlags = 0;
    depthTexDesc.MiscFlags = 0;

    hresult = d3dDevice_->CreateTexture2D(&depthTexDesc, nullptr, &depthTexture_);

    D3D11_DEPTH_STENCIL_VIEW_DESC DSVDesc;
    ZeroMemory(&DSVDesc, sizeof(DSVDesc));
    DSVDesc.Format = DXGI_FORMAT_D32_FLOAT;
    DSVDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    DSVDesc.Texture2D.MipSlice = 0;

    hresult = d3dDevice_->CreateDepthStencilView(depthTexture_, &DSVDesc, &depthView_);

    D3D11_SHADER_RESOURCE_VIEW_DESC gbDepthTexDesc;
    ZeroMemory(&gbDepthTexDesc, sizeof(gbDepthTexDesc));
    gbDepthTexDesc.Format = DXGI_FORMAT_R32_FLOAT;
    gbDepthTexDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    gbDepthTexDesc.Texture2D.MipLevels = 1;
    gbDepthTexDesc.Texture2D.MostDetailedMip = -1;

    d3dDevice_->CreateShaderResourceView(depthTexture_, &gbDepthTexDesc, &gbDepthView_);

Here's the relevant part of my rendering function:
    float clearColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
    d3dContext_->ClearRenderTargetView(backBufferTarget_, clearColor);
    d3dContext_->ClearDepthStencilView(depthView_, D3D11_CLEAR_DEPTH, 1.0f, 0);

    // GBuffer packing pass (in the future): /////////////////////////////////////////

    d3dContext_->OMSetRenderTargets(1, &backBufferTarget_, depthView_);

    unsigned int nStride = sizeof(Vertex);
    unsigned int nOffset = 0;

    d3dContext_->IASetInputLayout(inputLayout_);
    d3dContext_->IASetVertexBuffers(0, 1, &vertexBuffer_, &nStride, &nOffset);
    d3dContext_->IASetIndexBuffer(indexBuffer_, DXGI_FORMAT_R32_UINT, 0);
    d3dContext_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    d3dContext_->VSSetShader(firstVS_, 0, 0);
    d3dContext_->PSSetShader(firstPS_, 0, 0);

    d3dContext_->DrawIndexed(nIndexCount_, 0, 0);

    d3dContext_->OMSetRenderTargets(1, &backBufferTarget_, nullptr);

    d3dContext_->VSSetShader(secondVS_, 0, 0);
    d3dContext_->PSSetShader(secondPS_, 0, 0);
    d3dContext_->PSGetShaderResources(0, 1, &gbDepthView_);
    d3dContext_->PSSetSamplers(0, 1, &colorMapSampler_);

    d3dContext_->DrawIndexed(nIndexCount_, 0, 0);

    swapChain_->Present(0, 0);

In this temporary implementation, firstVS_ and secondVS_ are identical, and their only function is to do all the transforms and pass on the data to the PSs.
And finally, here are firstPS_ and secondPS_:
// firstPS_
float4 main(PS_Input frag) : SV_TARGET
{
    return float4(1.0f, 1.0f, 1.0f, 1.0f);
}

// secondPS_
Texture2D<float> depthMap_ : register(t0);
SamplerState colorSampler_ : register(s0);

float4 main(PS_Input frag) : SV_TARGET
{
    float4 psOut;
    psOut.xyz = depthMap_.Sample(colorSampler_, frag.tex0).xxx;
    psOut.w = 1.0f;
    return psOut;
}

So, my actual questions:
1) All this code compiles without any issues, but when I sample the depth buffer, it just turns out black. I read this could be caused by having your depth & stencil view bound by D3D11DeviceContext::OMSetRenderTargets() at the time you want to sample the depth buffer. I fixed that, but the buffer is still black. I checked the graphics debugger, with no success. So, is my depth buffer not getting written correctly, or am I sampling the wrong way? firstPS_ works fine.
2) Speaking of sampling, the book I'm using just says "we'll be using a point sampler," but I have no idea what is exactly meant. Now I'm just using a standard texture map sampler, but is there something else I should sample with?
3) Also, the book uses the SamplerState.Gather() function in secondPS_, but when I tried that it complained that "the expression could not be mapped to pixel shader instruction set." Is Gather() an error in the book, or is it my GPU (D3D feature level 11.0) who doesn't understand what that is? Is Sample() good enough for what I want to do? The original use of Gather() was in the context of creating a silhouette around objects in the depth buffer.
4) I tried to get secondVS_ to draw nothing but a full-screen quad, but FXC complained about my use of SV_VertexID as "invalid," saying that my type should be integral, even though it already was. I read somewhere that SV_VertexID can only be used by the first VS in a pipeline. Is that the problem here? How do I solve this in this particular case? In my current inefficient solution, is the problem being caused by the UVs?

A: 1) You've called PSGetShaderResources instead of PSSetShaderResources. Also, MostDetailedMip should be 0 not -1.
2) A "point sampler" is just a texture sampler with the FILTER field set to something like D3D11_FILTER_MIN_MAG_MIP_POINT.
3) Gather is a function on the Texture2D not the SamplerState as you stated.
4) You get this error if you compile using vs_4_0, try vs_5_0.


text:
Q: I need to filter my data and create a subset from a dataframe based on a range values of latitude and longitude I have the following data (in a bigger extent):
How will I be able to filter my data based on a range of latitude, longitude simultaneusly say for lati >= 52.46 and <= 52.50 and for longitude >= -1.87 and <= -1.92

A: The following code should work.
If you get the error object of type 'closure' is not subsettable that's because you need to rename your latitude column.
#create a reproducible data.frame
df = read.table(text ='ID    Lat    Long
1     124   76
2     234   53
3     229   11
4     268   22
5     150   44
6     190   34
7     211   87
8     152   21
9     300   98
10    186   19', header = TRUE)

#subset the data.frame
df_sub = subset(df, Lat >= 150 & Lat <= 299 & Long >= 22 & Long <= 97)

#output
> df_sub
ID Lat Long
2  2 234   53
4  4 268   22
5  5 150   44
6  6 190   34
7  7 211   87

A: I think you should create another column with a boolean value, setting it to 1 if the corresponding row passed the condition or 0 if it didn't.
then use the VLOOKUP function to filter only those rows wich passed the condition (having the new column value = 1)

A: Assuming you stored your data in a data frame df, and range 1 through 4 are your latitude and longitude limits-
df_sub <- df[df$latitude >= range1 & df$latitude <= range2 &
             df$longitude >= range3 & df$longitude <= range4,]


text:
Q: Background downloading even if the phone gets locked I am trying to implement an application for iPhone that should simply download some content out of the web. This download is quite big, so I implemented the download as a background task to give the user the chance to do some other stuff with his phone while downloading. My problem is that if the user pushes the lock button (or if auto lock kicks in) the applicationWillResignActive: in the AppDelegate is called and after about ten seconds the download is aborted because the phone does not enter background and just stays inactive.
My question is what am I doing wrong? How can I ensure that the download is continued, even if the phone is locked?
Thanks in advance.

A: You need to surround the downloading code with background task block like this:
UIApplication* app = [UIApplication sharedApplication];
        UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
            //here you need to finish what you are doing evven if you've not finished yet, otherwise your app will be killed
            [app endBackgroundTask:bgTask];
        }];

        //here comes your downloading code

        [app endBackgroundTask:bgTask];

This will give you 10 minutes(according to some other posts) to execute code in background...


text:
Q: Layout Animation is blank Nothing comes to the screen. The individual pngs render fine. what is wrong?
<ImageButton
  android:id="@+id/btn_loading"
  android:src="@drawable/loading_animation"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />

And next is the file "loading_animation.xml" :
 <?xml version="1.0" encoding="utf-8"?>
    <animation-list xmlns:android="http://schemas.android.com/apk/res/android"
        android:oneshot="false"
         android:repeatMode="repeat" >
        <item android:drawable="@drawable/load0" android:duration="20" />
        <item android:drawable="@drawable/load1" android:duration="20" />
        <item android:drawable="@drawable/load2" android:duration="20" />
        <item android:drawable="@drawable/load3" android:duration="20" />
        <item android:drawable="@drawable/load4" android:duration="20" />
        <item android:drawable="@drawable/load5" android:duration="20" />
        <item android:drawable="@drawable/load6" android:duration="20" />
        <item android:drawable="@drawable/load7" android:duration="20" />
        <item android:drawable="@drawable/load8" android:duration="20" />
    </animation-list>

A: You have to start the animation
Use the following code in your java code
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;

public class Main extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myxml);

        ImageView animation = (ImageView) findViewById(R.id.btn_loading);

        animation.setBackgroundResource(R.drawable.loading_animation);

        AnimationRoutine animationRoutine = new AnimationRoutine();

        Timer t = new Timer(false);

        t.schedule(animationRoutine, 100);

    }

    private class AnimationRoutine extends TimerTask {

        AnimationRoutine() {
        }

        public void run() {

            ImageView img = (ImageView) findViewById(R.id.btn_loading);

            AnimationDrawable frameAnimation = (AnimationDrawable) img
                    .getBackground();

            frameAnimation.start();

        }

    }

}


text:
Q: How does PyTorch module do the back prop While following the instructions on extending PyTorch - adding a module, I noticed while extending Module, we don't really have to implement the backward function. The only thing we need is to apply the Function instance in the forward function and PyTorch can automatically call the backward one in the Function instance when doing the back prop. This seems like magic to me as we didn't even register the Function instance we used. I looked into the source code but didn't find anything related. Could anyone kindly point me out a place that all those actually happened?

A: Maybe I'm not correct, but I have different kind of view.
The backward function is defined and be called by forward function.
For example:
#!/usr/bin/env python
# encoding: utf-8

###############################################################
# Parametrized example
# --------------------
#
# This implements a layer with learnable weights.
#
# It implements the Cross-correlation with a learnable kernel.
#
# In deep learning literature, it's confusingly referred to as
# Convolution.
#
# The backward computes the gradients wrt the input and gradients wrt the
# filter.
#
# **Implementation:**
#
# *Please Note that the implementation serves as an illustration, and we
# did not verify it's correctness*

import torch
from torch.autograd import Function
from torch.autograd import Variable

from scipy.signal import convolve2d, correlate2d
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter

class ScipyConv2dFunction(Function):
    @staticmethod
    def forward(ctx, input, filter):
        result = correlate2d(input.numpy(), filter.numpy(), mode='valid')
        ctx.save_for_backward(input, filter)
        return input.new(result)

    @staticmethod
    def backward(ctx, grad_output):
        input, filter = ctx.saved_tensors
        grad_output = grad_output.data
        grad_input = convolve2d(grad_output.numpy(), filter.t().numpy(), mode='full')
        grad_filter = convolve2d(input.numpy(), grad_output.numpy(), mode='valid')

        return Variable(grad_output.new(grad_input)), \
            Variable(grad_output.new(grad_filter))

class ScipyConv2d(Module):

    def __init__(self, kh, kw):
        super(ScipyConv2d, self).__init__()
        self.filter = Parameter(torch.randn(kh, kw))

    def forward(self, input):
        return ScipyConv2dFunction.apply(input, self.filter)

###############################################################
# **Example usage:**

module = ScipyConv2d(3, 3)
print(list(module.parameters()))
input = Variable(torch.randn(10, 10), requires_grad=True)
output = module(input)
print(output)
output.backward(torch.randn(8, 8))
print(input.grad)

In this example, backward function is defined by ScipyConv2dFunction function.
And ScipyConv2dFunction is called by forward function.
Am I correct?

A: Not having to implement backward() is the reason PyTorch or any other DL framework is so valuable. In fact, implementing backward() should only be done in very specific cases where you need to mess with the network's gradient (or when you create a custom Function that can't be expressed using PyTorch's built-in functions).
PyTorch computes backward gradients using a computational graph which keeps track of what operations have been done during your forward pass. Any operation done on a Variable implicitly get registered here. Then it's a matter of traversing the graph backward from the variable where it was called, and applying derivative chain rule to compute the gradients.
PyTorch's About page has a nice visualization of the graph and how it generally works. I'd also recommend looking up compute graphs and autograd mechanism on Google if you want more details.
EDIT: The source code where all this happens would be in the C part of PyTorch's codebase, where the actual graph is implemented. After some digging around, I found this:
/// Evaluates the function on the given inputs and returns the result of the
/// function call.
variable_list operator()(const variable_list& inputs) {
    profiler::RecordFunction rec(this);
    if (jit::tracer::isTracingVar(inputs)) {
        return traced_apply(inputs);
    }
    return apply(inputs);
}

So in each Function, PyTorch first checks if its inputs needs tracing, and performs trace_apply() as implemented here. You can see the node being created and appended to the graph:
// Insert a CppOp in the trace.
auto& graph = state->graph;
std::vector<VariableFlags> var_flags;
for(auto & input: inputs) {
    var_flags.push_back(VariableFlags::of(input));
}
auto* this_node = graph->createCppOp(get_shared_ptr(), std::move(var_flags));
// ...
for (auto& input: inputs) {
    this_node->addInput(tracer::getValueTrace(state, input));
}
graph->appendNode(this_node);

My best guess here is that every Function object registers itself and its inputs (if needed) upon execution. Every non-functional calls (eg. variable.dot()) simply defers to the corresponding function, so this still applies.
NOTE: I don't take part in PyTorch's development and is in no way an expert on its architecture. Any corrections or addition would be welcomed.


text:
Q: (user error) OverlayFS - files deleted in current merged dir (mountpoint) reappear when merged dir remounted as lower On Debian Stretch (running as root) this the current behaviour:
# Create base directory
mkdir base
touch base/example

# Create merge, upper and work directories for 2 layers
mkdir layer1 layer1.upper layer1.work
mkdir layer2 layer2.upper layer2.work

# Mount layer1 as the merged directory using layer1.upper as the true upper layer,
# with base as a lower layer and layer1.work as the necessary work directory
mount -t overlay overlay -o lowerdir=$(pwd)/base,upperdir=$(pwd)/layer1.upper,workdir=$(pwd)/layer1.work layer1
ls layer1 # should show example as expected
ls layer1.upper # shows no file (this is expected behaviour, it should only show files written on layer1)
rm layer1/example
ls layer1 # should show no files
ls layer1.upper # should show a special character device called "example", this is the "whiteout" file

# unmount, and remount with layer2 being the new upper layer and using layer1.upper directory as the top level lower layer.
umount layer1
mount -t overlay overlay -o lowerdir=$(pwd)/base:$(pwd)/layer1.upper,upperdir=$(pwd)/layer2.upper,workdir=$(pwd)/layer2.work layer2
ls layer2 # now shows example again as if it was never deleted

Is this a bug? Or is this a limitation/expected behaviour?
If expected, any suggestions on a quick and easy workaround?
FWIW it works as desired under auFS, so one workaround is to install aufs-dkms and continue to use auFS... I may do that regardless, but I would really like clarity on whether this is a bug or expected behaviour.

[update] I was doing it wrong, please see (the now corrected) answer!

A: I've decided that this is a bug. As such, I've lodged a bug report with Debian:
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=896646
Oops! Turns out I was doing it wrong! As noted in response to the Debian bug:

overlayfs is behaving as documented.  The documentation
  (filesystems/overlayfs.txt) says: "The specified lower directories will
  be stacked beginning from the rightmost one and going left.  In the
  above example lower1 will be the top, lower2 the middle and lower3 the
  bottom layer."
In your example this means that "layer1.upper" is the lowest layer, and
  its whiteout is overridden by the file in "base" which is on top of it.
   I think you just need to swap the order of these directories in the
  mount options.

I had read that doc, but missed the "right to left" bit!
I can confirm, that when done correctly (i.e. swapped the order so it is right to left) it works as expected.


text:
Q: MATLAB QUESTIONS on logical indexing and cell2struct function First Question:
Hello there!
I am trying to assign this vector

v(mod(v,2)~=0)=0

The operations is supposed to replace odd numbers in a vector with 0. I am trying to assign this vector to result variable in a function.
something goes wrong when I try this
 function
 function [result1,result2] = myfunction(v)
 v(mod(v,2)==0)= 0;
result1 = v;

v(mod(v,2)~=0) = 0;
result2 = v;
return

QUESTION 2:
I am trying to figure out an alternative way to express the the function cell2struct in for-loop format
for example,
if we have a cell array with 2 dimensions containing food labels. Their names, caloric count and price, each in one column. Can we write a function that's can transfer the information in cells to a struct that contain each of the fields above?
Thanks

A: Question #1
You are setting all even numbers to 0, but then you are using this mutated result to search for odd numbers and setting them to 0.  This will probably not give you what you intended as you are using a modified copy of the original vector, so it would be prudent that you keep a copy of the vector before doing each operation.
function [result1,result2] = myfunction(v)
vcopy = v; %// Make a copy
vcopy(mod(vcopy,2)==0)= 0; %// Find even numbers and set to 0
result1 = vcopy;

vcopy = v; %// Make another copy
vcopy(mod(vcopy,2)~=0) = 0; %// Find odd numbers and set them to 0.
result2 = vcopy;
return

Question #2
Yup.  If you have a list of field names stored in f and their corresponding entities for each field stored in c, simply use a loop like so:
function [s] = my_cell2struct(c, f)
for idx = 1 : numel(f)
    s.(f{idx}) = c{idx};
end

The above code does no error checking, so you need to make sure that the total number of elements in c matches those of f.  Also, c and f must be cell arrays.  Notice that s wasn't declared at all in the function.  Also, using the dot operator combined with enclosing brackets and a string that goes inside the enclosing brackets allows you to dynamically create field names on the fly.  As such, for each string in f, we access the corresponding value stored in c, and we create a field name that contains this value.
Here's a reproducible example from the MathWorks documentation:
c = {'tree',37.4,'birch'};
f = {'category','height','name'};
s = cell2struct(c, f, 2)

s =

    category: 'tree'
      height: 37.4000
        name: 'birch'

Notice that I use cell2struct here from native MATLAB to produce the above structure.  Doing the above for loop which is wrapped in a function called my_cell2struct, we get:
c = {'tree',37.4,'birch'};
f = {'category','height','name'};
s =  my_cell2struct(c, f)

s =

    category: 'tree'
      height: 37.4000
        name: 'birch'


text: Q: Can the cavity method be used to analyze graphs with loops which are short? In statistical physics, the cavity method can be regarded as a generalization of the Bethe-Peierls iterative method in tree-like graphs to the case of graphs with loops that are not too short. I would like to know whether there is some similar method in statistical physics that can be used to analyze the percolation on graphs with loops that are short, such as square lattices.


text:
Q: What is correct way to change user's email? When a user updates their email address we are seeing that their old email address becomes unavailable to register. This is undesirable.
It appears this is based on the user_login and user_nicename are not updated with user_email.
To fix this we are planning to:
$wpdb->update($wpdb->users, array('user_login' => $new_user_login, 'user_nicename' => $user_nicename), array('ID' => $user_id));

This must be a common issue other people are seeing. So I just wanted to ask, is this the correct way to fix this?

A: There is nothing in plain vanilla WordPress that would result in what you described.
It would seem that your problem stems from customizing your process (either by plugin or by your own customization) to populate the user_login with the user's email address to avoid having both a username and email.  If it's a custom process that you put in place yourself, then the issue is a result of not thinking through all of the possible issues based on circumventing the core WP process.
When doing something like this, the problem is when the user changes their email address, you also have to account for their username changing.  Both email and username must be unique values (display name does not need to be unique).  If the user changes their email but the user_login value is their previous email, the validation for unique username will return an error when trying to register the previous email.
It's not a good idea to simply populate the username with the email address.  WP intentionally does not have a built in process for changing usernames, and so you have to circumvent that process with a direct db update.  Any time you try to do something to "workaround" a core part of WP, you need to ask yourself two questions:

*

*Is this a good idea?

*Do I really need to do it this way?

If you simply MUST do away with username altogether, a better method is to come up with a way to create a username value from the email address (like extracting the first part) rather than having it be the actual email. BUT... then you still need an additional process during validation to make sure that your autopopulated pseudo username results in a unique value (like if "john" already exists, add "1" to it).


text:
Q: Why does the D2010 debugger make some things much slower? I've got a special combo box with a very long list of items (a few thousand) that has to be calculated when you open it.  When I was testing something, I was horrified to find that it took about a minute to open.  So I hooked the program (same build, same options) up to Sampling Profiler to see what was taking so long, and it only took about 5 seconds to open.  I tried running it directly from Windows, and this time it only took 2-3 seconds, which is what I expected.
So why does the exact same EXE crunch the numbers more than 25 times slower when the Delphi debugger is hooked up to it?  It's not anything obvious like conditional breakpoints being evaluated.  It seems that just the presence of the debugger is slowing it to a crawl.  Does anyone know why?

A: Repost: Is it producing a lot of debug output (OutputDebugString)? Anything showing up in the event log?


text:
Q: Limiting selected rows in SQL Server In the query below I want to retrieve @MaximumRecords rows, so that no ProjectId will have rows left out beyond @MaximumRecords.
For example if @MaximumRecords=100, and ProjectId=7 has records at rows number 99-102, I wish to retrieve only rows with ProjectId=1 to ProjectId=6 (The query will run again later starting at ProjectId=7). How do I do that?
SELECT TOP (@MaximumRecords)
    t1.ProjectId,
    t1.Row2,
    t2.Row3
FROM Table1 t1
    JOIN Table2 t2 ON t1.ProjectId = t2.ProjectId
ORDER BY
    t1.ProjectId ASC
WHERE
    t1.ProjectId > @InitialProjectId

A: I worked up a solution using the Sales.SalesOrderHeader and Sales.SalesOrderDetail tables in the AdventureWorks2008R2 database using the technique to get a running total described here.
The basic idea is to get the running total of the count for each SalesOrderID (ProjectID in your case) and then select all of the data for each SalesOrderID where the running total of the count is less than @MaximumRecords. You would then need to capture the maximum ID in the data returned and use that value in the next run of your query.
This task gets a little easier with SQL Server 2012 which is also described in the link given above.
Here it is...
USE AdventureWorks2008R2

IF OBJECT_ID('tempdb..#Test', 'U') IS NOT NULL DROP TABLE #Test;

DECLARE @MaximumRecords INT
DECLARE @InitialSalesOrderID INT

SET @MaximumRecords = 500
SET @InitialSalesOrderID = 43663

SELECT a.SalesOrderID, COUNT(*) AS 'Count'
INTO #Test
FROM Sales.SalesOrderHeader a
INNER JOIN Sales.SalesOrderDetail b ON a.SalesOrderID = b.SalesOrderID
WHERE a.SalesOrderID > @InitialSalesOrderID
GROUP BY a.SalesOrderID

SELECT * FROM Sales.SalesOrderHeader a
INNER JOIN Sales.SalesOrderDetail b ON a.SalesOrderID = b.SalesOrderID
WHERE a.SalesOrderID IN (
SELECT
    a.SalesOrderID
FROM
    #Test a
WHERE (
     SELECT
        SUM(Count)
     FROM
        #Test b
     WHERE
        b.SalesOrderID <= a.SalesOrderID
    ) < @MaximumRecords
)

Noel


text:
Q: How to install HAXM by enabling VT-X in BIOS? This is my problem
http://gyazo.com/3086025522327b4d8a15069f32c65a5c
and these are my bios settings
http://gyazo.com/8ecee9b665ed9058e64205ead1647b30
does any one of you know why this error is appering on my screen because my settings are good. And Hyper-V is disabled

A: I got the same problem.I will tell you how to solve it. Do u use avast antivirus? If yes then you have to disable Hardware assisted virtualization in Settings->trobleshooting tab of avast. If no then download this software from the link below.It will tell you whether the VT-x is enable or not. http://crystalmark.info/software/CrystalCPUID/index-e.html


text:
Q: How to convert substring to datetime I have a date time value extracted from textbox (datepicker) which is a range of time however i use sub string to further divide the time range to admissionDT and dischargeDT.However i cannot convert the substring into DateTime as i wanted to insert them into the database.The error displayed was  String was not recognized as a valid DateTime.
string admissionDischargeDT = adDT.Text;
string admissionDT = admissionDischargeDT.Substring(0,17);
string dischargeDT = admissionDischargeDT.Substring(18,17);

DateTime admissionDTinput = DateTime.ParseExact(admissionDT,"dd-mm-yyyy hh:mm tt",System.Globalization.CultureInfo.InvariantCulture);
DateTime dischargeDTinput = Convert.ToDateTime(dischargeDT);

Below are the codes for the datepicker found in the aspx.

        Admission Date & Time

        <asp:TextBox ID="adDT" type="text" runat="server" class="form-control daterange-time" value=""></asp:TextBox>

A: In a comment you say:

The value is 12/28/2016 12:00 am

But your format string is:
"dd-mm-yyyy hh:mm tt"

That doesn't match the input.  It sounds like the format you want is:
"MM/dd/yyyy hh:mm tt"

*

*You were using - instead of /

*You were using minutes instead of months

*Your day/month values were transposed (there is no 28th month)


text:
Q: Getting started in creating simple bootable C program Could someone guide me on what path/steps to take to create a simple bootable hello world program? I have the basic knowledge of C/C++.
My aim is to create a very simple OS.
I would like as much relevant links to references and samples as possible.

A: See this.  It's a tutorial for a very basic boot loader.  It doesn't have much to do with C/C++, but it has some really good information on the basic building blocks of a bootloader.
If you're really curious about the building blocks, there are more in-depth resources in the form of textbooks.  This tutorial, for instance, doesn't explain why the boot loader must end with 55 AA.  In addition, it's relatively narrow.

A: You want to build a statically linked binary (no ld.so involved), and you start it by jumping to its entry point. The entry point is usually the start of the .text section.  Maye run objdump --section-headers image on it to find out its adress.
If you're trying to run on an embedded device, check out how the kernel of an embedded OS is built and booted.  For example, see how U-Boot brings up  an Ångström linux based system.


text:
Q: How is jQuery UI adding elements to my DOM I have a login.php file

then flush that login.php to the output html file
        switch ($temp) {
            case 'php':
                ob_start();
                include_once($file);
                $content = @ob_get_contents();
                ob_end_clean();
                break;

However, when I check that login.html page which come from the login.php
there's

as you can see the div of login.php got inserted the ui-tabs ui-widget....etc from jquery ui elements..  who did that? which file insert those into the div?  It's not in any javascript files, css style sheet. but who?

A: These classes are added by the Jquery UI CSS framework. These the default classes added to the top container of each widget.
http://jqueryui.com/docs/Theming/API
http://code.jquery.com/ui/1.9.0-rc.1/jquery-ui.js
Hope this helps.
Thanks
aks

A: well this are the classes which is dynamically added by jquery UI related to functionality you have used.


text:
Q: counting rows and joining tables I have two tables, post and post_vote. The post table stores an id.
And the post_vote table stores the id of the post to which the vote belongs, the name of the user, and the type of the vote (upvote/downvote).
There are other columns in each table and other tables but those are irrelevant.
My problem:
How can I get a table that has the info from the post table, joined with the count of upvotes and downvotes from the post_vote table next to the post they belong to in a row?
Example:
post:
+---------------------+
| post_id | title |...|
| 1       | ...   |...|
| 2       | ...   |...|
+---------------------+

post_vote:
+---------------------------------+
| post_id | voter_name | vote_type|
| 1       | user1      | UPVOTE   |
| 2       | user2      | DOWNVOTE |
+---------------------------------+

desired result from a query:
+--------------------------------------------+
| post_id | title | ... | upvotes | downvotes|
| 1       | ...   | ... | 1       | 0        |
| 2       | ...   | ... | 0       | 1        |
+--------------------------------------------+

A: Join post to a query that uses conditional aggregation in post_vote to count the votes:
select p.*, v.upvotes, v.downvotes
from post p
left join (
  select post_id,
    sum(vote_type = 'UPVOTE') upvotes,
    sum(vote_type = 'DOWNVOTE') downvotes
  from post_vote
  group by post_id
) v on v.post_id = p.post_id

A: Try this one out
SELECT post.post_id, post.title, post.(...), (SELECT COUNT(vote_type) AS 'upvotes' FROM post_vote WHERE vote_type = 'upvote'), (SELECT COUNT(vote_type) AS 'downvotes' FROM post_vote WHERE vote_type = 'downvote') FROM post INNER JOIN post_vote ON post.post_id = post_vote.post_id


text:
Q: Set Windows 10 password grace period / timeout I'm using Windows 10 as a member of the Administrators group.
I've set up my group policy for UAC such that Windows prompts for credentials whenever something requires elevated access.
On more than once occasion, I've needed elevated access repeatedly in a short time interval. For example: when experimenting with setting up shared internet connections, (re)moving files on a protected drive, etc. In many situations, these actions are not part of a bulk operation, so an "All as administrator" option is not available. On these occasions, I have to type my PIN every 2 seconds, sometimes dozens of times.
On Linux, as a sudoer using sudo, there is a configurable timeout period such that after typing your password, you can use sudo for a short while without having to re-type the password every time.
So, I'm looking for the Windows analog for that mechanism. Does such a concept exist in the Windows world? Or am I trying too hard to make Windows behave like Linux and am I just approaching the problem "all wrong"?
Googling grace period or pin timeout and similar terms have not proven very fruitful...

A: Windows doesn't have such an option to completely disable
User Account Control (UAC).
Microsoft made this annoying on purpose and by design, in order to
discourage you from doing elevation too frequently.
Linux took rather the approach that people know what they are doing
(and if they don't then it's their fault).
I can think of these possibilities:

*

*Work in a Command Prompt (cmd) or PowerShell that is Run as Administrator.
Windows Explorer will not work in Admin mode, so if you need this then you
should use some
alternative file manager
that can be run in elevated mode.

*Temporarily
Enable or Disable User Account Control (UAC) in Windows.

*Use the built-in Administrator account. However, there is a good
security reason why this account is disabled.

A: At it's most simple you can elevate an hta hosting a folderview.
Call it folder.hta.
<html>
<body>
<iframe src="file:///c:/" width="100%" height="99%">
</body>
</html>

This is explorer like but you can't go up a folder only down.
Note the initial folder is expressed as an HTML path not a Windows path.


text:
Q: Query Does not return results Sqlite try {
    Class.forName("org.sqlite.JDBC");

    Connection connit  = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//ProjectData.sqlite");

    String query1= "insert into email (subject,message) values(?,?)";
    PreparedStatement pst=connit.prepareStatement(query1);
    pst.setString(1, subject.getText());

    pst.setString(2, message.getText());

    JOptionPane.showMessageDialog(null, "Message Sent");
    pst.executeQuery();
    pst.close();
    connit.close();
} catch (Exception e) {
    e.printStackTrace();
}

Hey guys, I know it's probably a very silly mistake but I can't seem to find it. As you all can understand I want to send some data over to my table. Please help. The error is Squery Does not return results.


text:
Q: Can't launch the selenium remote driver in docker container I am trying to dockerize my crawler with using selenium and I use the following docker-compose.yml:
version: "3"
services:
  chrome:
    image: selenium/node-chrome:4.1.1-20220121
    shm_size: 2gb
    depends_on:
      - selenium-hub
    environment:
      - HUB_HOST=selenium-hub
      - HUB_PORT=4444

  selenium-hub:
    image: selenium/hub:4.1.1-20220121
    container_name: selenium-hub
    ports:
      - "4444:4444"

  crawler:
    build: .
    depends_on:
      - chrome

After that, I am trying to open web browser session executing the following python script:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

cap = DesiredCapabilities.CHROME
driver = webdriver.Remote(command_executor='http://selenium-hub:4444/wd/hub', desired_capabilities=cap)

I am not sure why it will trigger the following MaxRetryError:
raise MaxRetryError(_pool, url, error or ResponseError(cause))

urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='selenium-hub', port=4444): Max retries exceeded with url: /wd/hub/session (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f569421cdd0>: Failed to establish a new connection: [Errno 111] Connection refused'))

I have done some research and I found that some people faced the same problem but their solution are not workable for me (eg. python jupyter notebook in docker container connection to selenium/standalone-chrome). Also I think I am using the same network since I am using the docker compose to create the image with both my crawler, selenium-hub and chrome and contain it together.
May I know how do I fix this problem? Thanks a lot for your help.


text:
Q: Add new items on top of list view Because android automatically moves new items to the bottom of list view I want that to be reversed. In any case my condition is met, I want to add new items on top of list view.
I have seen this post here but I don't know how to add that to my code, here it is:
if(condition){
listView = (ListView) findViewById(R.id.ListView1);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            this, R.layout.list_b_text, R.id.list_content, ArrayofName);
    listView.setAdapter(adapter);
}

A: Just simply add every item at position 0 of your ArrayList so when you call listView.notifyDataSetChanged(); it will show latest items on top.
for (Object obj : objectList) {
    ArrayofName.add (0, obj); // this adds new items at top of ArrayList
}

objectList is basically an ArrayList or List of Object or String (whatever is your case). If you want to add items one by one, remove for loop. This loop actually iterates every item of objectList and adds it in your ArrayList at top position.