text:
Q: Jquery scroll to offset target div always I have added a new sticky menu and I want the secondary sub-menu (that has an offset on load) to stay offset when scrolling.
Im a bit of a n00b and Im not getting it.
I am using this link as reference:
Jquery scroll to offset target div on page load
    // Goddamn scroll-to links

    // Get offset height depending on our sweet ass screen width
    if (window.innerWidth < 768) {
            var theOffset = 16;
        } else if ( $(this).is(':first')) {
           //var offset = $('.entry-header').height()  + 30;
        } else {
            var theOffset = $('.subheader').height() + 30;
    }

    $('a[href*=#]:not([href=#])').click(function() {

        //$('.subheader li').removeClass('active');
        //$(this).closest('li').addClass('active');
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
            || location.hostname == this.hostname) {

            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
               if (target.length) {
                 $('html,body').animate({
                     scrollTop: (target.offset().top - theOffset)
                }, 500);
                return false;
            }

        }

    });

and this:

if(window.location.hash) {
         $('html,body').animate({
          scrollTop: $(window.location.hash).offset().top-theOffset
      }, 900, 'swing');
    }

Any help would be appreciated


text:
Q: how to write a loops within a loop in GAMS I have a deterministic model and I want to run my model several times each time changing two parameters Var1 and Var2in order to see how they affect the results.
I can summarize my model like this:
...
equations obj,a,b;

obj...  Ax+By=e=cost;
a...    x+y=l=var1 * z1;
b...    x+y=l=var2 * z2;

solve;
dispaly cost.l;
dispaly y.l;
dispaly x.l;

Where x,y are variables, var1, z1, var2, and  z2 are parameters. I want to try 10 different values for var1 and 10 different values for var2 and have the results.
Could please tell me what is the best way to do so?

A: You can check here how to use loop statement.
In your case you have to define a set i of 10 values and two parameters var1_values(i), var2_values(i).
In your loop you have to include
var1 = var1_values(i);
var2 = var2_values(i);
solve;
*you can also store values to new parameters
display cost.l;
display y.l;
display x.l;

but not the equations. You have probably omitted information from solve statement on purpose but you have to specify which model to solve and whether you want to minimize or maximize a variable (in this case probably obj). If you don't specify this, GAMS finds just a feasible solution which will not be unique in your model.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Consolas for listing in Overleaf It's known that the default TT font family is too wide. I would try to use Consolas to list my code instead, since a lot of people are familiar with this programmer-oriented font. At the same time, I'm using Oevrleaf and Overleaf does not have Consolas with it. Overleaf tells me I can add a font. Then I got question 1:
The font that I downloaded is multiple .ttf files. I put the files in the same folder and tried something like
\newcommand\customfont[1]{{\usefont{T1}{Consolas}{m}{Consolas} #1 }}

But the font is not correct.
Question 2: The command above would allow be to use Consolas if it got fixed. But how can I set it to be the default font for lstlisting?


text:
Q: AngularJS Communication between ng-repeat and controller I've just started using AngularJS, and as a project I decided to build a simple app for managing bookmarks. I want to be able to maintain a list of bookmarks and add/remove items. I'm using Django with Django REST framework, and Angular.
So far I've written a service to grab the bookmarks from the database, and I can print them to the console from my controller, but ng-repeat doesn't seem to be seeing them.
Here's my code for the service:
.factory('BookmarkService', ["$http", function ($http) {
    var api_url = "/api/bookmarks/";
    return {
        list: function () {
            return $http.get(api_url).then(function (response) {
                return response.data
             })
        }
    }
}]);

And for the controller:
.controller("ListController",
 ["$scope", "BookmarkService", function ($scope, BookmarkService) {
    $scope.bookmarks = BookmarkService.list();
    console.log($scope.bookmarks);
}]);

And here's the HTML:

    <md-card>
        <md-card-content>

Bookmarks

            <md-list>
                <md-list-item ng-repeat="bookmark in listCtrl.bookmarks">
                    <md-item-content>

{[{ bookmark.name }]} - {[{ bookmark.url }]}
 // used interpolateProvider to allow "{[{" instead of "{{"

                        <md-divider ng-if="!$last"></md-divider>
                    </md-item-content>
                </md-list-item>
            </md-list>
        </md-card-content>
     </md-card>

When I print to the console from the controller I can see a promise object but ng-repeat isn't repeating:
image of promise object
I'd really appreciate if someone could help me to find my mistake and to understand why it is happening. I'm still not entirely comfortable with how all these parts fit together.
Thanks for your time!

A: There's two problems that I see with the code in question.
The first is that using the controller as syntax (ng-controller="ListController as listCtrl") requires properties to be bound to the controller instance and not to the scope if you address them using the controller name.  In your case,
.controller("ListController",
  ["BookmarkService", function (BookmarkService) {
    this.bookmarks = BookmarkService.list();
    console.log(this.bookmarks);
  }]);

The second is that you are assigning a promise to your $scope.bookmarks property.  The repeater is expecting an array of objects to iterate over.  You really want to assign the value resolved by the promise to $scope.bookmarks.
Instead of this
$scope.bookmarks = BookmarkService.list();

Do this
BookmarkService.list().then(function(result){
  this.bookmarks = result;
});

The final version of your controller should look something like this
.controller("ListController",
  ["BookmarkService", function (BookmarkService) {
    this.bookmarks = BookmarkService.list();
    console.log(this.bookmarks);
  }]);

A: This is simple. Ng-repeat is not working with promises. So, you can go with two ways:

*

*BookmarkService.list().then(function(responce){
$scope.bookmarks = responce.data;
});

*Another way is to create own repiter ^)
Ng-repeat doc


text:
Q: Minimum braking distance Suppose we are biking at a constant speed, is the minimum braking distance the same whether we apply the brakes on the front wheel or the back wheel?
I admit this is a homework problem, but I can't think of a reason why there would be a difference...
(Some numbers were given: Distance between the wheels is 1m, the center of mass is exactly between the wheels at 1m of height, the static friction is 1.0, the bike is at a constant speed of 10m/s)
We are currently going through torque, moment of inertia, angular momentum...So I guess we were supposed to use these to solve the problem...
I initially wanted to solve it using the conservation of energy, i.e. the kinetic energy would be converted into heat caused by friction, which actually works, but i guess that's not how I'm supposed to do this problem.

A: The maximum braking force is the maximum possible static friction force between the tire and the road. That force is $F_{max}=\mu_{s}N$ where $\mu_s$ is the coefficient of static friction and $N$ is the portion of the weight of the car that is supported by the tire.
So it depends on which wheel is supporting more of the weight of the vehicle and its occupants and/or has a larger value of $\mu_s$.  Another possible factor may be limitations in the design of the front and rear brakes, but I'm not sure since I have no expertise in this area.
Hope this helps.


text:
Q: Mediawiki custom namespaces id change I am currently working on an internal Mediawiki and we are using a lot of custom written extensions.
Because we did no know better, defined custom namespaces for our own extensions and articles with an id that is smaller than 3000.
For example:
define('NS_bla', 1100);
$wgExtraNamespaces[NS_bla] = "bla";
define('NS_bla_TALK', 1101);
$wgExtraNamespaces[NS_bla_TALK] = "bla Talk";

We did this with several different extensions. Now we read on the official documentation (http://www.mediawiki.org/wiki/Extension_default_namespaces) that custom namespaces should use id's that are 3000+.
Therefore my question: How can we easily change the IDs of the namespaces on the  production instance, without messing up with our current dataset? How could we tackle this problem? I could not find any information on the Mediawiki documentation.
Thank's a lot in advance and
Cheers from Germany,
Fabian

A: To answer the question, you would need to update the page table with the new namespace ID:
http://www.mediawiki.org/wiki/Manual:Using_custom_namespaces#Use_a_database_query
To fit this to your occassion, it would be:
UPDATE page
SET page_namespace = 3000
WHERE page_namespace = 1100

You shouldn't have to replace the page_title since these articles are already in another namespace.
Just please remember to back up your database before trying this.


text:
Q: Why dose the "section size" in a WebAssembly binary module can not be calculated accurately? I found that the attribute "section size" shows in every "Section" is zero. Also there is a comment word "guess" written within a pair of brackets.
In the image Below:-

A: Emscripten produces the binary in one pass, hence it does not yet know section sizes when at the beginning of a section. So it writes zero first and later back-patches the value once the respective section is complete and its size known. You should see a line marked FIXUP later in the output that refers to the same byte offset.


text:
Q: php Warning date() invalid date.timezone value,, we selected UTC timezone for now on server Warning: date(): Invalid date.timezone value 'Asia/Singapore', we selected the timezone 'UTC' for now: in path/file.php on line 14.
i'm having above error when running on the server, while in my code i did not put any timezone.
well the things is, if im running on my local wamp server, there's no error display at all.
below is my code

please advice.
thanks.

A: Try this:
date.timezone = "Asia/Singapore"

Edit:
Let's locate the correct php.ini. Fire this within apache / nginx / whatever web server deamon your using (because the command line version may be different by the one used by it).
<?php
 phpinfo();
?>

What's the .ini in the output? Still the same?
Edit2:
After the php.ini edit, just restart the webserver (apache or nginx.

A: Try to add following line before use of date function.
date_default_timezone_set('America/Los_Angeles');//change zone as per need

A: if you want to ignore the warning, you can put this code at your first line

error_reporting(E_ALL ^ E_WARNING)

about timezone setting:
not only PHP page can be set timezone but also php.ini can be set it.


text:
Q: UNetbootin is stuck in an "Automatic boot in 10 seconds" countdown loop I made a bootable Windows 7 USB using UNetbootin, and when I try to boot from the bootable USB and select the Default boot menu entry, it gets stuck at the UNetbootin boot menu and it keeps repeating an Automatic boot in 10 seconds... message in an endless countdown loop. Selecting Press [Tab] to edit options and editing the options has no effect. When I go back to the boot menu, it keeps repeating the same countdown loop.
I've tried redoing the UNetbootin extraction, but I still have the same issue.

A: The "Automatic boot in 10 seconds..." countdown loop is a UNetbootin problem. If the UNetbootin boot menu does not have an entry for the OS you are trying to boot to under the Default boot menu entry, this is another sign that UNetbootin is not working properly. I know that it's a problem with UNetbootin because I have seen it before, and managed to solve it by reformatting the USB flash drive to remove to bootloader and then making the live USB again with Startup Disk Creator. Startup Disk Creator is capable of making both Ubuntu and non-*buntu bootable live USBs.
This wouldn't solve your problem because you are trying to boot Windows 7, so I suggest that you use the WoeUSB application to make the bootable Windows 7 USB flash drive.
First reformat the USB drive as FAT32 to remove whatever obsolete boot information UNetbootin wrote on the USB flash drive. If your computer detects obsolete boot information on the USB flash drive, it may try to boot an operating system that no longer exists on the USB flash drive, and then UNetbootin will get stuck in a repeating countdown.
Then download WoeUSB and install it. Native UEFI booting is supported for Windows 7 and later images (limited to the FAT filesystem as the target device). WoeUSB is an updated fork of the WinUSB project.
Some third-party installers feature Windows installation images (/sources/install.wim) greater than 4GB making FAT32 as target filesystem impossible. NTFS filesystem support has been added to WoeUSB 3.0.0 and later.
Installation
To install WoeUSB (GUI+CLI) in Ubuntu 14.04/16.04/17.10-20.04:
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt update
sudo apt install woeusb

This will install the WoeUSB graphical interface and the WoeUSB command line tool. WoeUSB supports both UEFI and BIOS for FAT32/NTFS/ExFAT USB flash drives.
To install the WoeUSB command line tool snap package in all currently supported versions of Ubuntu open the terminal and type:
sudo snap install --edge woe-usb
sudo snap connect woe-usb:removable-media

To launch the woe-usb snap package command line tool run the following command:
/snap/bin/woe-usb.woeusb

If you get a permission denied error click the Permissions button on the woe-usb screen in Ubuntu Software and toggle the permissions options from OFF to ON as shown in the below screenshot.

The WoeUSB GUI is easier to use than the WoeUSB command line tool. Click the radio button to the left of where it says From a disk image (iso), browse to the location of the Windows .iso file, under Target device select a USB flash drive, open Disks application and check that the Device name in Disks matches the Target device in WoeUSB (it should be something like /dev/sdX where X is a letter of the alphabet), and click the Install button to install to create a bootable Windows installation media on the USB flash drive.

Windows USB drive from Ubuntu failing repeatedly
WoeUSB Issues

A: Install WoeUSB instead of Unetbootin
WoeUSB is now WoeUSB-ng and a way easy to install, just follow these two commands and you are done:
sudo apt install git p7zip-full python3-pip python3-wxgtk4.0

sudo pip3 install WoeUSB-ng

Now search for WoeUSB in your apps

A: Just reinstall UNetBootIn and it should work fine. I just did that myself. I realize that your question has probably been solved, just putting this here for the other people that may come across this thread.

A: I got stuck with the same error after all windows installations completed(my previous os has gone already) and I used these below steps.
1. Remove the USB first,
2. Restart the system. Now go to the boot settings and enable the safe boot mode on.
I hope it'll work for you too.


text:
Q: Reactjs isomorphic-fetch PATCH how to have the body error? So basically I am sending data with a fetch POST or PATCH method and when I have an error I can see in the network -> response this error:
{
  "Errors": [
   {
     "Code": -201,
     "Message": "Could not get file from link",
     "AssociatedError": "404 Not Found"
   }
 ],
 "Result": null
}

Here is my actual code:
function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  } else {
    var error = new Error(response.statusText);
    error.response = response;
    throw error;
  }
}

export function sendImageUploaded(data, valueMethod, endpoint) {
    return dispatch => {
        dispatch(requestPosts(data));
        return fetch(endpoint, {
            method: valueMethod,
            headers: new Headers({
                            Authorization: Isengard.config.token
                        }),
            body: data
        })
        .then(checkStatus)
        .then(reponse => {
            dispatch(successSent("The output list has been successfully sent!"));
        }).catch(err => {
            console.log('request failed', err);
            dispatch(failSent("Error on sending request: " + err));
        });
    };
};

And I am struggling on having this error message.

A: You already got your response error in "error.response". You only have to resolve that promise.
instead of
.catch(err => {
                console.log('request failed', err);
                dispatch(failSent("Error on sending request: " + err));
});

use
.catch(err => {
        err.response.json().then((json) =>{
           let {Errors,Result} = json;
           dispatch(failSent(Errors)); // You are sending your array of errors here
        });
});


text:
Q: Probability mass function of $ \min(X, Y)$ where $X,Y$ are i.i.d discrete uniform
Let $X$ and $Y$ be two discrete uniform i.i.d random variables distributed over $\{0, 1, 2,\ldots, N\}$. Find the pmf of $Z = \min(X, Y)$.

From what I understand, I have to find the joint $pmf$ first, which is just $1/(N+1)^2$ by independence. Now, I have to find the probability function $P(X_{(1)})$. Is this right? If so, how do I determine $P(X_{(1)})$ for $X_i$ discrete?
From two textbooks I have, I only found $P(X_{(1)} = x_i)$. Is $P(X_{(1)})$ = $P(X_{(1)} = x_i)$ for a generic $x_i$?
Thanks.

A: $P(\min(X,Y) = k) = \sum_{j=k}^N P(X = k)P(Y = j) + \sum_{j=k}^N P(Y = k)P(X = j) - P(Y=k,X=k) $
$= 2\sum_{j=k}^N P(X = k)P(Y = j)-\frac{1}{(N+1)^2}$  by symmetry.
$ = 2\sum_{j=k}^N \frac{1}{N+1}\frac{1}{N+1} = \frac{2(N+1-k)}{(N+1)^2}-\frac{1}{(N+1)^2}$
$ = \frac{2(N+\frac{1}{2}-k)}{(N+1)^2}$

A: $P(Z\le n)=P(X\le n\ or\ Y\le n)=P(X\le n)+P(Y\le n)-P(X\le n \ and\ Y\le n) =\frac{2(n+!)}{N+1}-(\frac{n+1}{N+1})^2$
The last step uses the independence of $X$ and $Y$.
Since the random variables are discrete I am not sure what you would want for a density function.


text:
Q: Aggregation queries on nested array of objects in mongodb I have following collection. each document may be represented as following. there can be multiple customer referees for each document.
{
  _id:objectId(""),
  customerId: "Some Id",
  name: "Customer name",
  customerReferee: [
   {
     status: 'COMPLETED',
     name: "Referee name1"
   },
   {
     status: 'PENDING',
     name: "Referee name2"
   },
  ],
}

I would like to have top 20 documents who has maximum number of 'COMPLETED' customerReferees.

A: *

*$match status condition

*$filter to iterate loop of customerReferee array nad filter by status

*$size to get total elements in above filter result

*$sort by total element that we have added a field customerRefereeSize in descending order

*$skip to start cursor from 0

*$limit to get first 20 elements

db.collection.aggregate([
  { $match: { "customerReferee.status": "COMPLETED" } },
  {
    $addFields: {
      customerRefereeSize: {
        $size: {
          $filter: {
            input: "$customerReferee",
            cond: { $eq: ["$$this.status", "COMPLETED"] }
          }
        }
      }
    }
  },
  { $sort: { customerRefereeSize: -1 } },
  { $skip: 0 },
  { $limit: 20 }
])

Playground


text:
Q: How does this scan camera send data to a computer? I am reading the data sheet of this scan camera (mono version.) My aim is to process the data coming from this camera by programming a simple software (using either CPU or GPU.) I see that it uses a grabber and camera link interface. I assume for this question that the grabber or any other extra HW will not do any processing between the camera and PC.
How does this camera send the data? Does it send 2D frames at a rate or send scanned lines one after each other? If one wants to make his own program, what protocol should be used?
I'm confused because I have made programs communicating through serial protocol before where you set the baudrates, parity etc. and use a library and receive data etc. In this case I'm very confused since I don't know the protocol to be used and I also don't know what the incoming data represents - one scanned line or frame per data sent.

A: I've programmed a few Basler line scan cameras using Camera Link.  Essentially the camera link cable gives you more or less the direct sensor output, and your capture card translates that into PCI/PCIe.  You load in your camera link configuration (which specifies the camera properties like resolution, triggering, etc) and then pixels are streamed to the capture card.
From there what you see depends on the API for the capture card.  These can vary, but for line scan cameras often the interface is programmed to look like a 2D array sensor, so you might configure 1000 lines of 1024 pixels, and get a 2D array of 1024x1000 lines.
Do you actually need to use camera link?  Camera Link is popular in industrial applications in part due to the long cable lengths (don't need to have a PC right next to a big industrial device), but for a lot of applications USB is gradually displacing it. If this is a spectrometer or some scientific device, I would probably use USB if possible.


text:
Q: Error: It was detected that 'sites' has no namespace, but components with no target namespace are not referenceable from schema document I have been working on this "advanced" schema for days with the flu and I cannot figure out why it keeps telling me that "sites" is not found. I re-read the chapter and even created a copy to experiment with (which worked before) and I do not understand. I am trying to import and combine schemas and I am not sure how to get it to work properly... Here are the errors:

Ln 16 Col 84 - cvc-elt.1: Cannot find the declaration of element
  'sites'. 1 Errors [Xerces-J 2.9.1] Validating XML Schema "sites.xsd"
  ... Ln 32 Col 49 - src-resolve.4.1: Error resolving component 'sites'.
  It was detected that 'sites' has no namespace, but components with no
  target namespace are not referenceable from schema document.
If 'sites' is intended to have a namespace, perhaps a prefix needs to
  be provided. If it is intended that 'sites' has no namespace, then an
  'import' without a "namespace" attribute should be added

Here is the schema:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns:cc="http://example.com/weekendfunsnacks/sites/ns"
      targetNamespace="http://example.com/weekendfunsnacks/sites"
      xmlns:sm="http://www.sitemaps.org/schemas/sitemap/0.9/ns"
            elementFormDefault="qualified" attributeFormDefault="unqualified">

 <xs:import namespace="http://www.sitemaps.org/schemas/sitemap/0.9"
             schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" />

   <xs:element name="sites">
      <xs:complexType>
         <xs:sequence>
            <xs:element name="site" maxOccurs="unbounded" minOccurs="0">
               <xs:complexType>
                  <xs:sequence>
                     <xs:element type="xs:string" name="name"/>
                     <xs:element type="xs:byte" name="totalPages" />
                     <xs:element ref="sites"  />
                  </xs:sequence>
               </xs:complexType>
            </xs:element>
         </xs:sequence>
      </xs:complexType>
   </xs:element>
</xs:schema>

And here is the XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<sites xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xs="http://example.com/weekendfunsnacks/sites/ns"
       xsi:schemaLocation="http://example.com/weekendfunsnacks/sites/ns sites.xsd">
    <site>
        <name>Weekend Fun Snacks</name>
        <totalPages>127</totalPages>
    <urlset xmlns:sm="http://www.sitemaps.org/schemas/sitemap/0.9/ns">
         <url>
            <loc>http://example.com/weekendfunsnacks/?cat=58</loc>
         </url>
         <url>
            <loc>http://example.com/weekendfunsnacks/?cat=2</loc>
            <lastmod>2017-12-29T06:03:34+00:00</lastmod>
         </url>
         <url>
            <loc>http://example.com/weekendfunsnacks/?cat=15</loc>
            <lastmod>2017-12-29T05:24:04+00:00</lastmod>
         </url>
         <url>
            <loc>http://example.com/weekendfunsnacks/?cat=93</loc>
         </url>
         <url>
            <loc>http://example.com/weekendfunsnacks/?cat=55</loc>
         </url>
      </urlset>
    </site>
    <site>
        <name>Paleo Snacks</name>
        <totalPages>52</totalPages>
    <urlset xmlns:sm="http://www.sitemaps.org/schemas/sitemap/0.9/ns">
         <url>
            <loc>http://example.com/primalsnacks/?cat=6</loc>
         </url>
         <url>
            <loc>http://example.com/primalsnacks/?cat=18</loc>
            <lastmod>2017-09-19T17:13:19+00:00</lastmod>
         </url>
         <url>
            <loc>http://example.com/primalsnacks/?cat=54</loc>
            <lastmod>2017-09-19T15:24:01+00:00</lastmod>
         </url>
         <url>
            <loc>http://example.com/primalsnacks/?cat=52</loc>
            <lastmod>2017-09-28T21:03:11+00:00</lastmod>
         </url>
         <url>
            <loc>http://example.com/primalsnacks/?cat=201</loc>
            <lastmod>2017-10-06T07:03:26+00:00</lastmod>
         </url>
         <url>
            <loc>http://example.com/primalsnacks/?cat=11</loc>
         </url>
      </urlset>
    </site>
    <site>
        <name>Veg Snacks</name>
        <totalPages>17</totalPages>
     <urlset xmlns:sm="http://www.sitemaps.org/schemas/sitemap/0.9/ns">
         <url>
            <loc>http://example.com/vegsnacks/?cat=102</loc>
         </url>
         <url>
            <loc>http://example.com/vegsnacks/?cat=23</loc>
         </url>
         <url>
            <loc>http://example.com/vegsnacks/?cat=1</loc>
         </url>
         <url>
            <loc>http://example.com/vegsnacks/?cat=55</loc>
            <lastmod>2017-06-12T08:05:32+00:00</lastmod>
         </url>
         <url>
            <loc>http://example.com/vegsnacks/?cat=201</loc>
         </url>
         <url>
            <loc>http://example.com/vegsnacks/?cat=87</loc>
         </url>
      </urlset>
    </site>
</sites>

A: Your XSD has a targetNamespace, so your ref="sites" has to reference that namespace.
Define a namespace prefix, say w:, to be the same as the target namespace, and then use it in the reference: ref="w:sites":
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
             targetNamespace="http://example.com/weekendfunsnacks/sites"
             xmlns:w="http://example.com/weekendfunsnacks/sites"
             elementFormDefault="qualified" attributeFormDefault="unqualified">

  <xs:import namespace="http://www.sitemaps.org/schemas/sitemap/0.9"
             schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" />

  <xs:element name="sites">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="site" maxOccurs="unbounded" minOccurs="0">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="name"/>
              <xs:element type="xs:byte" name="totalPages" />
              <xs:element ref="w:sites"  />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

A: Inside your <xs:schema add xmlns with same value you have for targetNamespace, for your example:
xmlns="http://example.com/weekendfunsnacks/sites"

So result will be like:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:cc="http://example.com/weekendfunsnacks/sites/ns"
  targetNamespace="http://example.com/weekendfunsnacks/sites"
  xmlns="http://example.com/weekendfunsnacks/sites"
  ....


text:
Q: Change popup menu item title android I am new to android development, i m trying to change the popup menu item title. i m using onCreateOptionsMenu() , but its not changing the title. how to achieve this? code included...
MovieDetailsActivity.java
public class MovieDetailsActivity extends AppCompatActivity {
Button magnet;
Button torrent;
private String size720p,size1080p;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.movie_details_activity);
    final Context context = this;

    final Toolbar toolbar = (Toolbar)findViewById(R.id.MyToolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapse_toolbar);
    Bundle bundle = getIntent().getExtras();
    //Extract the data…
    if (bundle != null) {
        String title = bundle.getString("movie_title");
        String screenshot = bundle.getString("screenshot");
        String yts_web = bundle.getString("yts_web");
        String rating = bundle.getString("rating");
        String imdb_url = bundle.getString("imdb_url");
        String mpa_rating = bundle.getString("mpa_rating");
        String runtime = bundle.getString("runtime");
        String genres = bundle.getString("genres");
        String synopsis = bundle.getString("synopsis");
        String poster = bundle.getString("poster");
        final String youtube = bundle.getString("youtube");

        size720p = (String) bundle.getString("size720p");
        final String magnet720p = bundle.getString("magnet720p");
        final String torrent720p = bundle.getString("torrent720p");
        size1080p = bundle.getString("size1080p");
        final String magnet1080p = bundle.getString("magnet1080p");
        final String torrent1080p = bundle.getString("torrent1080p");

        magnet = (Button) findViewById(R.id.magnet);
        magnet.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //Creating the instance of PopupMenu
                Context wrapper = new ContextThemeWrapper(context, R.style.popupMenuStyle);
                PopupMenu popup = new PopupMenu(wrapper, magnet);
                //Inflating the Popup using xml file
                popup.getMenuInflater().inflate(R.menu.popup_dl_quality, popup.getMenu());
                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        if (item.getItemId() == R.id.hd) {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            intent.addCategory(Intent.CATEGORY_BROWSABLE);
                            intent.setData(Uri.parse(magnet720p));
                            startActivity(intent);
                        } else if (item.getItemId() == R.id.full_hd) {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            intent.addCategory(Intent.CATEGORY_BROWSABLE);
                            intent.setData(Uri.parse(magnet1080p));
                            startActivity(intent);
                        }
                        return true;
                    }
                });

                popup.show();//showing popup menu
            }
        });//closing the setOnClickListener method

        torrent = (Button) findViewById(R.id.torrent);
        torrent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //Creating the instance of PopupMenu
                Context wrapper = new ContextThemeWrapper(context, R.style.popupMenuStyle);
                PopupMenu popup = new PopupMenu(wrapper, torrent);
                //Inflating the Popup using xml file
                popup.getMenuInflater().inflate(R.menu.popup_dl_quality, popup.getMenu());

                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        if (item.getItemId() == R.id.hd) {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            intent.addCategory(Intent.CATEGORY_BROWSABLE);
                            intent.setData(Uri.parse(torrent720p));
                            startActivity(intent);
                        } else if (item.getItemId() == R.id.full_hd) {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            intent.addCategory(Intent.CATEGORY_BROWSABLE);
                            intent.setData(Uri.parse(torrent1080p));
                            startActivity(intent);
                        }
                        return true;
                    }
                });

                popup.show();//showing popup menu
            }
        });//closing the setOnClickListener method

        collapsingToolbarLayout.setTitle(title);

        TextView Rating = (TextView)findViewById(R.id.imdb);
        Rating.setText(rating);
        TextView MpaaRating = (TextView)findViewById(R.id.mpaRating);
        MpaaRating.setText(mpa_rating);
        TextView Runtime = (TextView)findViewById(R.id.runtime);
        Runtime.setText(runtime);
        TextView Genres = (TextView)findViewById(R.id.genres);
        Genres.setText(genres);

        ImageView Poster = (ImageView)findViewById(R.id.moviePoster);
        Glide.with(Poster.getContext()).load(poster).placeholder(R.drawable.placeholder).error(R.drawable.ic_img_error).into(Poster);
        ImageView Screenshot = (ImageView)findViewById(R.id.ytThumb);
        Glide.with(Screenshot.getContext()).load(screenshot).into(Screenshot);
        ImageView img = (ImageView)findViewById(R.id.playButton);
        img.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                intent.setData(Uri.parse(youtube));
                startActivity(intent);
            }
        });
    }
}

public boolean onCreateOptionsMenu(Menu menu) {   // this does nothin
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.popup_dl_quality, menu);
    menu.findItem(R.id.hd).setTitle(size720p);
    menu.findItem(R.id.full_hd).setTitle(size1080p);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
    onBackPressed();
    return true;
}
}

popup_dl_quality.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="jaswinder.yts.app.MovieDetailsActivity"
    app:theme="@style/ToolbarColoredBackArrow">
    <item
        android:id="@+id/hd"
        android:title="720p"/>
    <item
        android:id="@+id/full_hd"
        android:title="1080p"/>
    </menu>

A: @JaswinderSingh Have you passed the String with key value "size720p" and "size1080p" from the previous activity??


text:
Q: Función en AddEventListener se ejecuta sola al cargar la página estoy intentando crear un botón que, al presionarse, cambie la propiedad "contenteditable" de una etiqueta HTML. El tema es que al crear el AddEventListener, no soy capaz de poner una función que creé para cambiar esa propiedad con solo el id de la etiqueta. Ya intenté utilizando "function(){mifuncion()}" seguido del "click". Intenté ejecutar la función entera directamente desde el AddEventListener, y nada. No funciona a menos que la deje tal y como está en el código debajo. Por supuesto, los  con el id "pencil-icon" son íconos de lápiz para editar el texto.

var editter1 = document.getElementsByClassName("edit-1");
var editter2 = document.getElementsByClassName("edit-2");
var editter3 = document.getElementsByClassName("edit-3");
var editter4 = document.getElementsByClassName("edit-4");

function editElement(event, MyElement){
    var ownElement = document.getElementById(MyElement);
    ownElement.setAttribute("contenteditable", "")
};

editter1.addEventListener("click", editElement("own-title"));

        Lorem ipsum
        Lorem ipsum.

Lorem ipsum

¡Hola!

            Lorem ipsum

            Lorem ipsum

            Lorem ipsum

A: Tienes un error en editter1.addEventListener("click", editElement("own-title")); le envías 1 solo parámetro a la funcion mientras que arriba tienes declarados que estas recibiendo dos editElement(event, MyElement).
En la función como event está de primero editElement(event, MyElement), event está recibiendo el parámetro que enviaste que en este caso es own-title mientras que MyElement no está recibiendo nada y con ese es con el que estás trabajando, puedes hacer 2 cosas:
function editElement(MyElement) //Borrarlo

function editElement(MyElement, event) //Cambiar el orden

CODIGO COMPLETO
let editter1 = document.getElementById("edit-1");
let editter2 = document.getElementsByClassName("edit-2");
let editter3 = document.getElementsByClassName("edit-3");
let editter4 = document.getElementsByClassName("edit-4");

    function editElement(MyElement){
        console.log(event)
        var ownElement = document.getElementById(MyElement);

        ownElement.setAttribute("contentEditable", '')

        //ownElement.setAttribute("contentEditable", 'true') //Otra opción pero es lo mismo, agregando el true

        //otra opción apuntando a la propiedad y cambiando el estado
        //ownElement.contentEditable = 'true'
    };

    editter1.addEventListener('click', () => {
        editElement("prof-sub")
    });

El editter1 lo cambie a getElementById ya que me daba un error al utilizar getElementsByClassName y eso tiene que ver con que getElementById apunta a un elemento definido en el DOM con ese id mientras que con getElementsByClassName devuelves una matriz con los elemento que coinciden con esa clase, tendrías que iterarlos ya que es una matriz pues.
NOTA:

Al utilizar editter1 con getElementById el elemento si contiene
la propiedad addEventListener y si utilizas getElementsByClassName
no la tiene, por lo tanto como lo tenías no iba a capturar el evento click

HTML

            Lorem ipsum
            Lorem ipsum.
            <button type="button" class="fa-sharp fa-solid fa-pencil edit-1" id="edit-1">BOTON</button>

Lorem ipsum

¡Hola!

                Lorem ipsum

                Lorem ipsum

                Lorem ipsum


text:
Q: problem in the if-else condition in scilab I was writing a SSTF disk scheduling algorithm code in SCILAB and during running after displaying first 3 values (41,34,11) correctly its always showing head at -1. Can somebody tell whats the problem in code?
I tried to give a different if condition too but it wasn't also giving correct output.
clear
clf;
seek = 0
x = 8
l = list(176,60,79,92,114,11,34,41)
head = 50
mi = 1
for j = 1:x
    for i=1:x
        if (l(i)~=(-1))then
            if( abs(head - l(i)) < abs(head -l(mi))) then
                mi = i
            end
        end
    end
    seek = seek + abs(head - l(mi))
    head = l(mi)
    h(j) = head
    se(j) = seek
    mprintf('Head is at %i and seek is %i\n',head,seek)
    l(mi) = -1
end

plot(h,se)
scatter(h,se)

A: your problem is that after the first 3 iterations, head=11 is closer to -1 than 60. Replace -1 by%nan (not a number) and a as a result this value won't never taken as the closest to current head. Moreover by using a vector instead of a list you can remove the inner loop my using max
clear
l = [176,60,79,92,114,11,34,41];
head = 50;
seek = 0;
for j = 1:8
    [step,im] = min(abs(head - l));
    seek = seek + step;
    head = l(im);
    mprintf('Head is at %i and seek is %i\n',head,seek);
    l(im) = %nan;
    h(j) = head
    se(j) = seek
end

clf
handle = plot(h,se)
scatter(h,se)

You get the following output:
Head is at 41 and seek is 9
Head is at 34 and seek is 16
Head is at 11 and seek is 39
Head is at 60 and seek is 88
Head is at 79 and seek is 107
Head is at 92 and seek is 120
Head is at 114 and seek is 142
Head is at 176 and seek is 204


text:
Q: Java Spring will not talk to Consul when run as a Docker container I am trying to solve what I believe is a common use case for running micro services.  In this case I am testing consul with a spring cloud application. I am trying to test consul in two different ways.  The first of which is running in a docker container and the other is running on the docker host machine.  I am then attempting to start a spring cloud container that will talk with either consul example.
I have been unable to make the spring cloud application talk to consul when the spring cloud application is run as a docker container.  When the spring cloud application is run with the host networking mode it works as it can resolve the localhost ports, but this is not an acceptable solution if I wish to run multiple instances of the image.
An example of my docker compose file when running both services as containers is shown below. Here I am attempting to set the consul uri in spring cloud through the environment variables, but have been unable to get it to work using a variety of configurations.  If anyone could point to an example of these functions working together that would be immensely helpful.
 consul1:
  image: progrium/consul
  ports:
    - "8400:8400"
    - "8500:8500"
    - "8600:53/udp"
    - "8600:53/tcp"
  environment:
      GOMAXPROCS: 100
      entrypoint: "/bin/consul"
      hostname: consul
      command: agent -log-level=debug -server -config-dir=/config -bootstrap -ui-dir /ui

simpletest:
    build: simpletest
    hostname: simpletest
    environment:
      JAVA_OPTS: "-Xdebug -Xrunjdwp:server=y,transport=dt_socket,suspend=n -Dspring.cloud.consul.host=consul1"
    ports:
     - 39041:7051
     - 39052:7055
#     d2fdockerroot_consul1_1 consul
#    links:
#     - consul1

A: Here you have an example of a brewery system - https://github.com/spring-cloud-samples/brewery. One of the files is a docker-compose file for CONSUL.
https://github.com/spring-cloud-samples/brewery/blob/master/docker-compose-CONSUL.yml
Check out all the application-consul.yaml files that are inside the codebase to see how to set up the Spring Boot apps to talk to consul.
Example: https://github.com/spring-cloud-samples/brewery/blob/master/aggregating/src/main/resources/application-consul.yaml
In case of any issues write here or go to spring-cloud gitter https://gitter.im/spring-cloud/spring-cloud

A: I had exactly the same problem: linking to my consul container was not enough. However, the following did it for me: As stated here, the corresponding consul host and port configuration needs to be placed in bootstrap.yml, not application.yml.
spring:
  cloud:
    consul:
      host: consul
      port: 8500

with the corresponding docker-compose.yml:
version: "2.0"

services:
  consul:
    image: consul:latest
    ports:
      - "8500:8500"
my-service:
    build: path/to/dockerfile
    depends_on:
      - consul
    links:
      - consul:consul


text:
Q: There exists a pair of positive ints $(m,n)$ such that $(m,n$ and $m+n)$ are all perfect squares The only thing I figured to do was just to express these three guys..
$m =a^2$ ,$ n=b^2 $, and $m+n = a^2 + b^2$

A: There are an infinite number of those. Consider the recursive definition of $a_k = k^2 $:
$$x_{k+1} =x_k + 2k + 1$$
or in other words:
$$ (k+1)^2 = k^2 + (2k + 1)$$
You can prove that for every $n$ odd square there's at least one $m$ even square number such that $m+n$ is also a square:
$$n = 2\sqrt m + 1$$
$$m = (\frac{n-1}2)^2$$


text:
Q: MongoDump Failed: error writing data for collection `collection` to disk: error reading collection: EOF [BACKUP COMMAND] mongodump --host 127.0.0.1 -d database --port 27017 --username username --password password --out /output/path/mongodump_DATE_12_00_AM
[ISSUE] Failed: error writing data for collection collection1 to disk: error reading collection: EOF
MongoDB v3.6.5
The Mongo Database and the Node JS application is running in the docker container, Linux Machine. Mongo DB total backup size is 41GB. We are running the backup command on daily basis it is working fine for 10 to 15 days but after that getting above mentioned error intermittently.
[WORKAROUND] = As a workaround, if I stop and start all the NODE application services, application container and MongoDB container then the issue is getting resolved.
For Testing purpose before doing workaround(stop & start container), I ran the mongodump command only for that error collection mongodump --host 127.0.0.1 -d database --port 27017 --username username --password password --collection collection1 --out /output/path/mongodump_DATE_12_00_AM then it is working fine.
So my questions are:

*

*Is this application memory leak issue?

*Or, Is System low memory(RAM) issue? Linux server TOTAL RAM SIZE is: 12GB.

*

*If system low memory issue means it should failed on every time but here it failed after a few days.


text:
Q: Find Percentage of difference between two Videos Using FFMPEG I am working with Video comparison using FFmpeg on Java. I have videos name "video1 and Video2". I can find the difference between two video using FFmpeg.
It shows the result Video with difference. But here I want to find how many percent (IE: 20%) Video1 different from Video2. How to achieve this?

A: If just file comparison, lots of tools can do that.
If video content comparison, you need to scale the 2 videos to the same width & height and calculate SSIM of each pair of frames.  SSIM is short for "Structural similarity", which is a float number between 0 and 1, where 1 stands for totally the same and 0 the opposite.
FFMPEG has a SSIM Filter to do what I just said.  It would give you a text file containing SSIM comparison of all frames.  Then your program can parse this file and get what you want.


text:
Q: Docker Insufficient permissions to set thread priority I'm getting this error when running a multi-threading library on Docker.
Insufficient permissions to set thread priority. Please retry as root.

I have therefore tried to run the image with the -u option, that specifies that the root user with id 0 be used to run /bin/bash:
docker run -u 0 --rm -it img bash

or
docker run -u root --rm -it img bash

The same happens if I run the command instead of bash like
docker run -u root --rm -it img './threading_test'

But actually it does not solve the permissions problem, and still getting the error.
[UPDATE]
Adding the Dockerfile
FROM ubuntu:18.04
MAINTAINER Loreto Parisi loretoparisi@gmail.com
RUN apt-get update && apt-get install -y libcap2-bin
COPY ./src .
CMD ["./y-cruncher"]

I have added the libcap2-bin since command capsh was not installed by default. As suggested the capsh --print capabilities check will return
root@d24d02a2ee8c:/# capsh --print
Current: = cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_sys_nice,cap_mknod,cap_audit_write,cap_setfcap+eip
Bounding set =cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_sys_nice,cap_mknod,cap_audit_write,cap_setfcap
Securebits: 00/0x0/1'b0
 secure-noroot: no (unlocked)
 secure-no-suid-fixup: no (unlocked)
 secure-keep-caps: no (unlocked)
uid=0(root)
gid=0(root)
groups=

The run command was docker run --rm -it --cap-add=sys_nice y-cruncher since I have set CMD ["./y-cruncher"] in the Dockerfile by defaults.

A: In general you need to give the container CAP_SYS_NICE capability to be able to set the priorities.

y-cruncher needs to run with root user otherwise the error message will be raised

A test before giving CAP_SYS_NICE capability:
Launching y-cruncher...
================================================================
Insufficient permissions to set thread priority. Please retry as root.
Further messages for this warning will be suppressed.
Checking processor/OS features...
Required Features:
    x64, ABM, BMI1, BMI2, ADX,
    SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2,
    AVX, FMA3, AVX2
Parsing Core -> Handle Mappings...
    Cores:  0-3
Parsing NUMA -> Core Mappings...
    Node  0:  0-3
y-cruncher v0.7.7 Build 9499                ( www.numberworld.org )
Copyright 2008-2020 Alexander J. Yee      ( a-yee@u.northwestern.edu )

A test after giving CAP_SYS_NICE capability with: --cap-add=sys_nice ubuntu:latest
Launching y-cruncher...
================================================================
Checking processor/OS features...
Required Features:
    x64, ABM, BMI1, BMI2, ADX,
    SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2,
    AVX, FMA3, AVX2
Parsing Core -> Handle Mappings...
    Cores:  0-3
Parsing NUMA -> Core Mappings...
    Node  0:  0-3
y-cruncher v0.7.7 Build 9499                ( www.numberworld.org )
Copyright 2008-2020 Alexander J. Yee      ( a-yee@u.northwestern.edu )

It may worth mentioning to ensure that the kernel itself has the required capability enabled using capsh --print however CAP_SYS_NICE should be exist on the host by default

A: It looks like an app issue. Non docker execution has the same problem:
$ id
uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
$ ./y-cruncher-static/y-cruncher | grep 'Insufficient'
Insufficient permissions to set thread priority. Please retry as root.

Docker execution:
$ docker run --rm -v $PWD/y-cruncher-static:/y-cruncher-static --privileged --security-opt seccomp=unconfined -ti ubuntu bash -c "/y-cruncher-static/y-cruncher | grep 'Insufficient'"
Insufficient permissions to set thread priority. Please retry as root.

Debug info:
$ capsh --print
Current: = cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,35,36+ep
Bounding set =cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,35,36
Securebits: 00/0x0/1'b0
 secure-noroot: no (unlocked)
 secure-no-suid-fixup: no (unlocked)
 secure-keep-caps: no (unlocked)
uid=0(root)
gid=0(root)
groups=0(root)
$ uname -a
Linux dockerhost 3.10.0-862.14.4.el7.x86_64 #1 SMP Wed Sep 26 15:12:11 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux


text:
Q: leaflet .bindLabel using geojson feature I am new to leaflet and I'd like to add labels to my point map features derived from geojson format.
I am getting the error: TypeError: layer.bindLabel is not a function in this script https://jsfiddle.net/gfiske/ksx600sn/35/  (uncomment line 129)
Can anyone suggest a workaround or a better approach?
thanks.
geojsonLayer = L.geoJson(geojson, {

style: function(feature) {
    return {
      color: feature.properties.GPSUserColor
    };
  },
  pointToLayer: function(feature, latlng) {
    return new L.CircleMarker(latlng, {
      radius: 7,
      fillOpacity: 0.75
    });
  },
  onEachFeature: function(feature, layer) {
    layer.bindPopup(feature.properties.MAP_LABEL);
    layer.bindLabel(feature.properties.MAP_LABEL);
    }
});

A: From the documentation for Leaflet.label:

NOTE: starting with Leaflet 1.0, L.Label is added to Leaflet core as L.Tooltip and this plugin is deprecrated.

You should use bindTooltip instead:
onEachFeature: function(feature, layer) {
  layer.bindPopup(feature.properties.MAP_LABEL);
  layer.bindTooltip(feature.properties.MAP_LABEL);
}


text:
Q: Authenticating in Play without using routes I've followed this tutorial for authentication and it works:
http://www.playframework.com/documentation/2.2.x/JavaGuide4
But I was wondering if there was another way to do it so that the user can't just go to myapp.com/login and get the login screen even if they're already logged in. Is there a way to do this so I can go to the login screen but still have myapp.com as the route?

A: This is easy. Just have the controller method for route "/" display the login page instead of your landing page when the user is not logged in.
Say / routes to Application.index() and it has a function isLoggedIn() to check login status, you could do something like this:
public static index() {

    if (isLoggedIn()) {
        return ok (index.render());
    }
    else {
        return ok (login.render());
    }
}


text:
Q: Setting Qt 5.7 OpenGL version on Mac El Capitan (OSX 10.11) I am trying to set the OpenGL version for my QOpenGLWidget to 3.3 using the following code.
QSurfaceFormat defaultFormat;
defaultFormat.setProfile(QSurfaceFormat::CoreProfile);
defaultFormat.setVersion(3, 3);
defaultFormat.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
QSurfaceFormat::setDefaultFormat(defaultFormat);
QApplication a(argc, argv);

The problem is when I later call glGetString(GL_VERSION) I get

4.1 INTEL-10.14.73

as output. Should this be happening? It seems I can either use 2.1 or 4.1, and Qt won't allow me to use anything in between.

A: Yes, that is normal. And perfectly valid.
With the exception of the 3.2 core profile break, every higher OpenGL version is backwards compatible with a lower one. As such, if you ask for 3.3, an implementation is free to give you 4.1, since 4.1 does everything that 3.3 does.
Indeed, if you ask for 2.1, an implementation is allowed to give you 4.1 compatibility profile, since that is backwards compatible with 2.1. Now on MacOSX, you won't get that, because Apple doesn't expose any compatibility profiles. But they could have.


text:
Q: Kendo Dataviz charts - Adding a shape as a point on a bar chart I've got a chart with 2 series - one is a line series, and another is a bar series.
I need to add a marker to a point on the chart as a 3rd series but can't find a way of doing it. Current code:
  $("#lowerDayschart").kendoChart({
                width: "200px",
                height: "190px",
                title: {
                    text: "Title"
                },
                legend: {
                    position: "bottom"
                },
                seriesDefaults: {
                    type: "column"
                },
                series: [
                        {
                            name: "My Name",
                            data: [1, 2, 3, 4, 4, 4, 5, 5, 5, 5, 4, 4, 4, 4, 3, 2, 1],
                            gap: 0,
                            spacing: 0,
                            type: "column",
                            YAxisType: 'primary'
                        }, {
                            data: [1, 2, 3, 4, 4, 4, 5, 5, 5, 5, 4, 4, 4, 4, 3, 2, 1],
                            gap: 0,
                            spacing: 0,
                            type: "line",
                            markers: {
                                visible: false
                            },
                            YAxisType: 'secondary'
                        }],
                valueAxis: {
                    line: {
                        visible: false
                    }
                },
                categoryAxis: {
                    categories: ["-8", "", "", "", "", "", "", "", "0", "", "", "", "", "", "", "", "8"],
                    majorGridLines: {
                        visible: false
                    }
                },
                tooltip: {
                    visible: true,
                    format: "{0}"
                }
            });

Chart at the moment:

Chart as I'd like it:


text:
Q: Microsoft Windows server monitoring tools I'm more of a developer then an IT guy and I was wondering if there are any existing Microsof tools for monitoring servers and potentially SQL Server.
We have access to MSDN so anything created by Microsoft would be preferred.

A: You should check out a product called SCOM from microsoft.  Depending on if you have a virtual environment or not the pricing is pretty respectable these days.

A: Have a look at the System Center products, specifically Operations Manager.  It's available to download via MSDN, depending on your subscription level, however I don't know to what extent you'll be able to use it in production since MSDN only provides for single user testing purposes.


text:
Q: Retrieve code from PHP Bluemix Application In my bluemix space I have a php application running.
I want to make some change to the code of this application.
But I don't have the code locally.
In my commandshell I can connect to my bluemix space with the Cloud Foundry command line interface.
If I use the command cf apps, I see the application.
Can anybody tell me how I retreive the code from this application?

A: There is a Cloud Foundry CLI plugin, which allows you to download your application after it has staged.
I have been using it and it works like a charm.


text:
Q: GWT: execution stops when adding a Composite widget to RootPanel I have an abstract class extending Composite (AbstractWhiteBoard). Then I have a concrete class extending AbstractWhiteBoard. When I instantiate the concrete class and try to add it to the RootPanel, the program simply stops executing. There is no error or any output to direct me to a log file. I have no idea what is going wrong.
Here is my abstract class:
public abstract class AbstractWhiteBoard extends Composite {
     /*
      * FIELDS
      */
     protected HorizontalPanel WhiteBoardWrapperPanel;

     public AbstractWhiteBoard( ) {
          WhiteBoardWrapperPanel = new HorizontalPanel();
          WhiteBoardWrapperPanel.setStyleName("WhiteBoard-Wrapper");
          initWidget(WhiteBoardWrapperPanel);
     }

     /*
      * ABSTRACT PUBLIC METHODS
      */
     abstract public void addNotecard( Notecard nc );
     abstract public void addPostit( Postit postit );

     /*
      * ABSTRACT PROTECTED HELPER METHODS
      */
     abstract protected void registerDragDropControllers();
 }

And here is my concrete implementation class:
public class ConcreteWhiteBoard extends AbstractWhiteBoard {

/*
 * CONTSTRUCTORS
 */
public ConcreteWhiteBoard() {
    super();
}

/*
 * PUBLIC METHOD OVERRIDES
 */
@Override
public void addNotecard(Notecard nc) {
    // TODO Auto-generated method stub

}

@Override
public void addPostit(Postit postit) {
    // TODO Auto-generated method stub

}

/*
 * PRIVATE HELPER METHOD OVERRIDES
 */
@Override
protected void registerDragDropControllers() {
    // TODO Auto-generated method stub
}
}

So, what is happening, is I have this code:
AbstractWhiteBoard wb = new ConcreteWhiteBoard();
RootPanel.get().add(wb);
Window.alert("wb added!");

But after I add wb to the RootPanel, execution stops. The alert statement never even gets called. There is no error and I don't see anything in the log.
Is there something wrong with having an abstract class that extends Composite? Or is it something entirely different that I am just not seeing? any help is greatly appreciated!

A: take a look at the uncaught exception handler in gwt. if a runtime exception occurs it is called. Think of it as a global try catch around your code.
But if your code is inside your entrypoint on module load make sure to set the uncaught exception handler and call the next function within a timer (so that the uncaught exception handler is active.
For a quick example take a look here:
http://code.google.com/p/mgwt/source/browse/src/main/java/com/googlecode/mgwt/examples/showcase/client/ShowCaseEntryPoint.java?repo=showcase
In web mode you can turn on emulated stack (and get meaningful stacktraces). YOu need to add this to your gwt.xml file (only for debug purposes because it is quite slow):
<set-property name="compiler.emulatedStack" value="true" />

<set-configuration-property name="compiler.emulatedStack.recordLineNumbers" value="true" />
<set-configuration-property name="compiler.emulatedStack.recordFileNames" value="true" />

A: So, this is one of those times that you feel like the most retarded developers of all time. What happened is that I was running several async calls all at the same time and I tried to refer to an object that was returned by one of those calls before it was actually created. Dunce cap on me, I got confused with async threads.
Major thanks to Daniel. Your input lead me straight to the problem!


text:
Q: Multidex app still over 64K method limit I'm facing a weird issue with multidex. I've had my app multidexed for a long time, but lately I can't build it anymore. It started after configuring Kotlin in the project.
The 'run' option in Android Studio works: the app runs successfully in my device. However, if I try the "Build APK" option or run gradlew assembleDebug, the build fails with the usual exception:
Error:The number of method references in a .dex file cannot exceed 64K.
Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html
Error:com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

However, multidex worked correctly before adding Kotlin. I can checkout the commit just before adding Kotlin, build the apk and check there's 3 .dex files, with a method count over 100k total.
Some key details:

*

*Gradle 4.1, with Gradle plugin 3.0.1

*Build-tools version 26.0.2

*Kotlin version 1.2.0

After proguarding, the app does not need multidex, but I don't really want to proguard for debug compilation, and besides, this should be working.
Here's the complete build.gradle script:
buildscript {
    repositories {
        mavenCentral()
    }
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'idea'

repositories {
    mavenCentral()
    jcenter()
    maven { url "https://maven.google.com" }
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    maven { url 'https://jitpack.io' }
}

idea {
    module {
        downloadJavadoc = true
        downloadSources = true
    }
}

// read keystore for app signing
def keystorePropertiesFile = rootProject.file("keystore.properties")
def keystoreProperties = null
if (keystorePropertiesFile.exists()) {
    keystoreProperties = new Properties()
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

def getDate() {
    def date = new Date()
    def formattedDate = date.format('yyyy.MM.dd')
    return formattedDate
}

def getCustomProguardFiles() {
    return fileTree(dir: "proguard", include: ["*.pro"]).asList().toArray()
}

android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        applicationId "my.app.id"
        multiDexEnabled true

        manifestPlaceholders = [
                'appAuthRedirectScheme': 'my.app.id'
        ]

        //TODO do not put this into release
        resValue "string", "google_client_id", google_appId + ".apps.googleusercontent.com"
        resValue "string", "google_auth_redirect_uri", "com.googleusercontent.apps." + google_appId + ":/oauth2redirect"
    }

    dexOptions {

    }

    dexOptions {
        javaMaxHeapSize "2g"
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties != null ? keystoreProperties['keyAlias'] : null
            keyPassword keystoreProperties != null ? keystoreProperties['keyPassword'] : null
            storeFile keystoreProperties != null ? file(keystoreProperties['storeFile']) : null
            storePassword keystoreProperties != null ? keystoreProperties['storePassword'] : null
        }
    }

    lintOptions {
        abortOnError false
        checkReleaseBuilds false
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt')
            proguardFiles getCustomProguardFiles()
            testProguardFiles getDefaultProguardFile('proguard-android.txt')
            testProguardFiles getCustomProguardFiles()
            signingConfig signingConfigs.release
        }
        debug {
            debuggable true
            minifyEnabled false
        }
    }

    flavorDimensions "buildType"

    productFlavors {
        develop {
            applicationIdSuffix ""
            dimension "buildType"
        }
        product {
            dimension "buildType"
        }
        ci {
            dimension "buildType"
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.all {
            outputFileName = "${variant.name}-${variant.versionName}.apk"
        }
    }
    compileOptions.incremental = false
}

dependencies {

    /********** DEBUGGING **********/
    // Chrome debug bridge
    compile 'com.facebook.stetho:stetho:1.5.0'
    compile 'com.facebook.stetho:stetho-okhttp3:1.5.0'

    // Memory leak debugging
    //  1.5.2 held back because of a bug with gradle 3.0
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
    androidTestCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'

    /********** SUPPORT **********/
    // Multidex support
    compile 'com.android.support:multidex:1.0.2'

    // Support libs
    compile "com.android.support:appcompat-v7:$libVersions.android.support"
    compile "com.android.support:cardview-v7:$libVersions.android.support"
    compile "com.android.support:customtabs:$libVersions.android.support"
    compile "com.android.support:design:$libVersions.android.support"
    compile "com.android.support:gridlayout-v7:$libVersions.android.support"
    compile "com.android.support:palette-v7:$libVersions.android.support"
    compile "com.android.support:preference-v7:$libVersions.android.support"
    compile "com.android.support:recyclerview-v7:$libVersions.android.support"
    compile "com.android.support:support-annotations:$libVersions.android.support"
    compile "com.android.support:support-v4:$libVersions.android.support"
    compile "com.android.support:support-v13:$libVersions.android.support"

    // Testing dependencies
    //  Made explicit to avoid conflicts with other testing libs
    androidTestCompile "com.android.support:appcompat-v7:$libVersions.android.support"
    androidTestCompile "com.android.support:design:$libVersions.android.support"
    androidTestCompile "com.android.support:recyclerview-v7:$libVersions.android.support"
    androidTestCompile "com.android.support:support-annotations:$libVersions.android.support"
    androidTestCompile "com.android.support:support-v4:$libVersions.android.support"

    /********** TESTING **********/
    // JUnit
    testCompile 'junit:junit:4.12'

    // Mockito
    testCompile "org.mockito:mockito-core:2.8.47"

    // Support testing
    androidTestCompile 'com.android.support.test.espresso:espresso-contrib:3.0.0'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:3.0.0'
    androidTestCompile 'com.android.support.test:rules:1.0.0'
    androidTestCompile 'com.android.support.test:runner:1.0.0'

    /********** UTILITIES **********/
    // HTML parsing
    compile 'org.jsoup:jsoup:1.10.2'

    // Event bus
    compile 'org.greenrobot:eventbus:3.0.0'

    // FHIR
    compile 'ca.uhn.hapi.fhir:hapi-fhir-android:3.1.0'
    compile 'ca.uhn.hapi.fhir:hapi-fhir-structures-dstu3:3.1.0'

    // Jobs
    compile 'com.evernote:android-job:1.1.11'

    // JSON serializing-deserializing
    compile 'com.google.code.gson:gson:2.8.1'

    // JWT validation
    compile 'com.nimbusds:nimbus-jose-jwt:4.41.1'

    // Lang utilities
    //  Used for Levenshtein distance, etc
    compile 'org.apache.commons:commons-lang3:3.6'
    compile 'org.apache.commons:commons-text:1.1'

    // OpenID authentication
    compile 'net.openid:appauth:0.7.0'

    // QR code scanning
    compile 'com.google.zxing:core:3.3.0'
    compile 'com.journeyapps:zxing-android-embedded:3.5.0@aar'

    // Play Services (for Firebase InstanceID)
    compile 'com.google.android.gms:play-services-auth:11.6.0'

    // Recurrence processing
    compile 'org.dmfs:lib-recur:0.10'

    // REST services
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-scalars:2.1.0'

    // SQLite ORM
    compile 'com.j256.ormlite:ormlite-android:5.0'

    // Time and date handling
    compile 'com.fatboyindustrial.gson-jodatime-serialisers:gson-jodatime-serialisers:1.6.0'
    compile 'joda-time:joda-time:2.9.7'

    // View/resource binding
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    compile 'com.jakewharton:butterknife:8.8.1'

    /********** VIEWS AND VIEW UTILITIES **********/
    // About page with libraries
    compile('com.mikepenz:aboutlibraries:5.2.5@aar') {
        transitive = true
    }

    // Calendar views
    compile 'com.roomorama:caldroid:3.0.1'
    compile 'com.squareup:android-times-square:1.6.4@aar'

    // Circular progress "pie" view
    //  Used for pill picker
    compile 'com.github.filippudak.progresspieview:library:1.0.4'

    // Dialogs with material style
    compile 'com.github.javiersantos:MaterialStyledDialogs:2.0'

    // Floating Action Button
    compile 'com.getbase:floatingactionbutton:1.9.0'

    // GIF ImageView
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.3'

    // Icons
    compile 'com.mikepenz:community-material-typeface:1.9.32.2@aar'
    compile 'com.mikepenz:google-material-typeface:2.1.2.1@aar'
    compile 'com.mikepenz:iconics-core:2.7.1@aar'

    // Image loading
    compile 'com.squareup.picasso:picasso:2.5.2'

    // Intro slides
    compile 'com.heinrichreimersoftware:material-intro:1.5.8'

    // Material style utilities
    compile('com.mikepenz:materialize:0.2.7@aar') {
        transitive = true
    }

    // Picker DialogFragments
    compile 'com.code-troopers.betterpickers:library:3.1.0'

    // Round image view
    compile 'com.makeramen:roundedimageview:1.5.0'

    // Tab strip
    compile 'com.astuetz:pagerslidingtabstrip:1.0.1'

    // Sliding left drawer
    compile('com.mikepenz:materialdrawer:4.4.1@aar') {
        transitive = true
    }

    // Recyclerview adapters
    compile('com.mikepenz:fastadapter:2.1.5@aar') {
        transitive = true
    }
    compile 'com.mikepenz:fastadapter-commons:2.1.0@aar'
    compile 'com.mikepenz:fastadapter-extensions:2.1.0@aar'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // Schedule step-by-step building
    compile 'com.stepstone.stepper:material-stepper:3.3.0'
    compile 'com.wdullaer:materialdatetimepicker:3.2.2'
    compile 'com.shawnlin:number-picker:2.4.4'
}

apply plugin: 'com.google.gms.google-services'

And the build.gradle of the project:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = '1.2.0'
    repositories {
        jcenter()
        maven { url "https://maven.google.com" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:3.0.0'
    }
    ext {
        libVersions = [
                android: [
                        support: '25.4.0'
                ]
        ]
    }
}

A: It turned out to be a problem with the way I was including HAPI-FHIR. It's a really big library with tons of dependencies, and it probably was collapsing the main dexfile.
In the end, I solved it by replacing:
// FHIR
compile 'ca.uhn.hapi.fhir:hapi-fhir-android:3.1.0'
compile 'ca.uhn.hapi.fhir:hapi-fhir-structures-dstu3:3.1.0'

with:
// FHIR
compile 'ca.uhn.hapi.fhir:hapi-fhir-base:3.1.0@jar'
compile 'ca.uhn.hapi.fhir:hapi-fhir-utilities:3.1.0@jar'
compile 'ca.uhn.hapi.fhir:hapi-fhir-structures-dstu3:3.1.0@jar'
compile 'commons-io:commons-io:2.5'
compile 'org.slf4j:slf4j-api:1.7.25@jar'

commons-io and slf4j are runtime dependencies of HAPI, and when using @jar those dependencies aren't downloaded, so they need to be explicitly declared.
Note: this particular configuration is only valid for my use case, as HAPI has more runtime dependencies, which would need to be added manually as well in case they're needed.


text:
Q: How to copy a file from local machine to a storage account using Terraform I have created a storage account and created a file share in it too using Terraform. I want to copy some files from my local machine to that storage account using Terraform. Is that possible? If yes, then how?
Here is my code-
provider "azurerm" {
  # whilst the `version` attribute is optional, we recommend pinning to a given version of the Provider
  version = "=2.0.0"
  subscription_id = "xxx-xxxx-xxxx-xxxx"
  tenant_id = "xxxxx-xxxxx-xxxx-xxxx"
  features {}
}
resource "azurerm_resource_group" "example" {
  name     = "azuretest"
  location = "West Europe"
}
resource "azurerm_storage_account" "example" {
  name                     = "asdfghjklteststorage"
  resource_group_name      = azurerm_resource_group.example.name
  location                 = azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

resource "azurerm_storage_share" "example" {
  name                 = "sharename"
  storage_account_name = azurerm_storage_account.example.name
  quota                = 50

  acl {
    id = "xxx-xxx-xxx-xxx"

    access_policy {
      permissions = "rwdl"
      start       = "2020-05-10T09:38:21.0000000Z"
      expiry      = "2020-07-02T10:38:21.0000000Z"
    }
  }
}
resource "null_resource" "uploadfile" {

  provisioner "local-exec" {

  command = <<-EOT
  $storageAcct = Get-AzStorageAccount -ResourceGroupName "${azurerm_resource_group.example.name}" -Name "${azurerm_storage_account.example.name}"
   Set-AzStorageFileContent `
   -Context $storageAcct.Context `
   -ShareName "${azurerm_storage_share.example.name}" `
   -Source "C:\Users\xxx\xxx\xxx\Untitled.png" `
   -Path "Untitled.png"

  EOT

  interpreter = ["PowerShell", "-Command"]
  }
}

A: You could use local-exec provisioner invokes a local executable after a resource is created. See upload a file to Azure file share with PowerShell.
For example,
    resource "azurerm_storage_share" "example" {
      name                 = "sharename"
      storage_account_name = azurerm_storage_account.example.name
      quota                = 50

      acl {
        id = "xxxxxxxxxxxxxxx"

        access_policy {
          permissions = "rwdl"
          start       = "2020-05-10T09:38:21.0000000Z"
          expiry      = "2020-07-02T10:38:21.0000000Z"
        }
      }
    }

    resource "null_resource" "uploadfile" {

      provisioner "local-exec" {

      command = <<-EOT
      $storageAcct = Get-AzStorageAccount -ResourceGroupName "${azurerm_resource_group.example.name}" -Name "${azurerm_storage_account.example.name}"
       Set-AzStorageFileContent `
       -Context $storageAcct.Context `
       -ShareName "${azurerm_storage_share.example.name}" `
       -Source "C:\Users\xxx\terraform\test.txt" `
       -Path "test.txt"

      EOT

      interpreter = ["PowerShell", "-Command"]
      }

}

Result

For more information, you could read this blog.

A: For anyone coming from Google, it's worth pointing out you that in early 2022 should now be able to use azurerm_storage_share_file. This worked great for me to upload a single file. To upload multiple files it looks like you will require multiple resources
https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/storage_share_file
resource "azurerm_storage_share_file" "example" {
  name             = "test.txt"
  storage_share_id = azurerm_storage_share.example.id
  source           = "${path.root}/TestFiles/test.txt"
}


text:
Q: Background service is freezing/lagging android app I have been developing an android application in which there is a service and I want to run it for ever.
I am using a broadcast receiver to get screen on-off intents inside oncreate of service and using an alarm manager  which starts the service itself after every 25 seconds inside onstartcommand and also performing my other operations in onstartcommand. I have put all the code in onstartcommand inside an thread. But the problem is once the service in running for some hours in background and I reopen the app the app starts lagging and becomes very slow. Before starting the service the app works very fine.
The Brief of my code is as follows -
public class MyService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    AlarmManager alarmManagerMain;
    BroadcastReceiver receiver;
    Thread t;
    Thread thread;

        @Override
    public void onCreate()  {
        super.onCreate();
        t = new Thread(() -> {
            HandleReceiver();
        });
        t.start();
        CreateNotificationChannel();
        startNotification();
    }

    private void HandleReceiver() {
        try {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(Intent.ACTION_SCREEN_ON);
            intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
            receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if(intent.getAction().equals(Intent.ACTION_SCREEN_ON))
                    {
                        // ...
                        // My Code
                        // ...
                        // Starting Service to call onStartCommand
                        Intent serviceIntent = new Intent(context, MyService.class);
                        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                        {
                            startForegroundService(serviceIntent);
                        }
                        else
                        {
                            startService(serviceIntent);
                        }
                    }
                    else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
                    {
                        // ...
                        // My Code
                        // ...
                    }
                }
            };
            MyService.this.registerReceiver(receiver, intentFilter);
        }
        catch (Exception ignore) { }
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        Runnable runnable = () -> {
            if(allowNotificationAndAlerts)
            {
                // My Code
            }
            // This function is to start the service even after the system kills it
            startAlarm();
        };
        thread = new Thread(runnable);
        thread.start();
        return super.onStartCommand(intent, flags, startId);
    }

    private void startAlarm()
    {
        AlarmManager alarmManager = (AlarmManager) MyService.this.getSystemService(Service.ALARM_SERVICE);
        Intent myIntent = new Intent(MyService.this, MyBroadCastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(MyService.this, 1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, 25);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }
    }

    @Override
    public void onDestroy() {
        stopForeground(false);
        unregisterReceiver(receiver);
        super.onDestroy();
    }
}

My questions are -

*

*How can I optimize the service as to run it for ever in background without causing the lag in app

*Is there any way to get screen on off intents by system or anything else instead of running the service with broadcast receiver

A: I got the answer
I was able to solve it by removing "android:process=:remote" line from service in manifest and changing shared preferences to database the issue was maybe because shared preferences are not process safe


text:
Q: Excel Table Columns without Data, or Schema I'm trying to load the rows of a table into a typed collection. I'm familiar with the "BuildList" samples that rely on getting row data into a string array. However, this isn't very reliable if a user inserts a column or rearranges the column position in a table. So I want to get a list of columns and their ordinal positions of the table.
What is the best way to do this? The /Rows call doesn't bring back column names, and /Columns is good, but it also brings back all the data for all columns. Is there a way to bring back Columns but with no data or some other call to describe the table schema (although I don't expect to get data types).
Update
I'm using the sample app from here: https://github.com/microsoftgraph/aspnet-donations-rest-sample/blob/master/Microsoft-Graph-ASPNET-Excel-Donations/ExcelAPIHelper.cs. Specifically, the BuildList method used hard coded stringarray references (lines 108-112). This is very fragile and will break if the user rearranges the columns in the excel file, or inserts an extra column.
I want to get the list of columns from a table without the data. The List Columns Method (i.e. table('MyTable')/columns) returns all of the data values for each column as well). See ref: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/table_list_columns. ) I hope that is clearer.

A: I found that you can use OData query parameters and just pull back the names and index of the columns with $select=name,index.
https://graph.microsoft.com/beta/drives/omitted/items/omitted/workbook/worksheets('Sheet2')/tables('Table2')/Columns?$select=name,index

and the resulting json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#drives('omitted')/items('omitted')/workbook/worksheets('Sheet2')/tables('Table2')/columns(name)",
"value": [
    {
        "@odata.id": "/drives('omitted')/items('omitted')/workbook/worksheets(%27%7B00000000-0001-0000-0100-000000000000%7D%27)/tables(%272%27)/columns(%279%27)",
        "id": "9",
        "name": "Date"
    },
    {
        "@odata.id": "/drives('omitted')/items('omitted')/workbook/worksheets(%27%7B00000000-0001-0000-0100-000000000000%7D%27)/tables(%272%27)/columns(%2710%27)",
        "id": "10",
        "name": "Time"
    },
    {
        "@odata.id": "/drives('omitted')/items('omitted')/workbook/worksheets(%27%7B00000000-0001-0000-0100-000000000000%7D%27)/tables(%272%27)/columns(%2711%27)",
        "id": "11",
        "name": "Rink"
    }
}


text:
Q: Warning: validation was turned on but an org.xml.sax.ErrorHandler Any idea why this error is happening and how to fix it? I'm getting this error when trying to parse/load a config file:
Error
Warning: validation was turned on but an org.xml.sax.ErrorHandler was not
set, which is probably not what is desired.  Parser will use a default
ErrorHandler to print the first 10 errors.  Please call
the 'setErrorHandler' method to fix this.
Error: URI=null Line=3: Document root element "persistence", must match DOCTYPE root "null".
Error: URI=null Line=3: Document is invalid: no grammar found.
null
[]
null

Main code
public static void main(String[] args) throws ConfigurationException {
        config = new XMLPropertiesConfiguration(new File("META-INF/vamola.xml"));
        System.out.println(config.getString("persitence-unit.provider"));
        System.out.println(config.getList("persistence-unit.properties.name"));

    }

XML FILE
<?xml version="1.0"?>
<persistence version="1.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="dbBank" transaction-type="RESOURCE_LOCAL">
        <provider>oracle.toplink.essentials.PersistenceProvider</provider>

        <class>br.ufg.inf.server.Account</class>
        <class>br.ufg.inf.server.UserBank</class>

        <properties>
            <property name="toplink.jdbc.user" value="derby" />
            <property name="toplink.jdbc.password" value="senha" />
            <property name="toplink.jdbc.url" value="jdbc:derby://192.168.80.125:1527/db/master/dbBank;create=true"/>
            <property name="toplink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver" />
            <property name="toplink.ddl-generation" value="create-tables" />
            <property name="toplink.logging.level" value="OFF" />
            <property name="toplink.target-database" value="Derby" />
        </properties>
    </persistence-unit>
</persistence>

A: If your parsing an XML document with validation turned on, you need to specify either a DTD or an XML schema in a DOCTYPE at the start of your XML document.  Your parser is basically complaining that it doesn't know how to validate your document because no grammer has been specified to validate the mark up.
You already have an XML schema, so you probably want:
<!DOCTYPE schema PUBLIC "http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

If you want to turn off validation, you need something like:
spf.setValidating(false);  (Where spf is a SaxParserFactory)

A: The exception says that an ErrorHandler wasn't set. This means that the parser uses its built-in error handler, which simply writes messages to the console. If you actually want to validate, you need to create an ErrorHandler implementation and attach it to the DocumentBuilder.
For more information, read this: http://www.kdgregory.com/index.php?page=xml.parsing (error handlers are about 1/3 of the way down).
Or, as other responses have suggested, you can just turn validation off.

A: The XML document defines the default namespace http://java.sun.com/xml/ns/persistence and includes a url, where the schema can be found (xsi:schemaLocation attribute, first value is the namespace, second the url or path).
Please double-check if this url is accessible at the time you parse it. An alternative is to download the schema, put it on the file system and modify the xsi:schemaLocation value.


text:
Q: bubble a record to the top of mySQL query based on record number How do I get a query to bubble a specific record to the top of the results based on a PK?
I've got a list of product classes based on a department Primary Key. My product has a class already associated with it but I want to provide the user to with the other classes available for that product only I want it's current class to be the top result.
Does this make sense?

A: This will make row 123 be the first of the result:
SELECT ... ORDER BY (key_col = 123) DESC

If key_col is 123 the result of the comparison is 1, otherwise it is 0. If you ORDER in descending order, 1 comes first.

A: A more flexible solution to this is to add a weight column to your table. Depending on recordnumber, or an artificial primary key (especially one that is autogenerated on insert) will lead to problems later on, especially if you copy data between database servers.
Add a new column that allows you to specify a weight to a record, and then order by the weight column as a second column in your ORDER BY statement. The values in the weight column don't need to matter, as long as they're numeric and allow things to be ordered the way you want them.

A: My general approach to this sort of functionality is to use a CASE .. WHEN statement, which will work similarly to @AndreKR's answer above, but is a little more flexible in that it can be more granular than just a boolean comparison.
It'd look similar to this (this is how it'd look in MS SQL, but from looking at the documentation, it appears that it's similar in mySQL):
SELECT fields
FROM table
ORDER BY
  CASE
    WHEN val = 123 THEN 0
    WHEN val < 200 THEN 1
    WHEN val < 400 THEN 2
    ELSE 3
  END
asc


text:
Q: Do I need to use a before "few" in this case and why? or why not? I always do a grammar mistake with a. I would like to improve my understanding for a special case of using a. For example,
Most values are 0 or very close to 0, while a few of them are -1.
Here, I think I do not need to use a before few. However, I do not know why?
Could you help, me please?

A:
Most values are 0 or very close to 0, while a few of them are -1.

A before few should be better in the sentence above. There are still some values which are -1, aren't there? So, to emphasize the fact that there are such values, we need to use a. More examples:

Most of my friends are students but a few of them are not. (some of my friends are actually not students)
I have few friends. (not using a I emphasize the fact that I have almost no friends - their number is insufficient, I feel lonely and unhappy)


text:
Q: how to get the value of multidimensional array pass from jquery and ajax? I send a multidimensional array from ajax.js to test1.php. But then I do not know how to retrieve the multidimensional array in my test1.php. I have found lots of examples but they did not work for me.
ajax.js
answers = {};
answers[0] = {};
answers[0]['question_id'] = '12';
answers[0]['answer_id'] = '32';

$.ajax({
    type: "POST",
    url: 'test1.php',
    data: {answers: answers},
    //dataType: "json",

    error: function(jqXHR, textStatus, errorThrown){
        alert(errorThrown);
    },
    success: function(data){
        alert('success!');
    }
});

test1.php
$a=$_POST['answers'][0]['answer_id'];
echo "$a"; //display nothing, I wish to display '32' here

Appreciate for any helps. Thanks!
Update: I included library and Ajax.js does give me an alert 'success'. So this is not the library problem. Thanks again for any helps!

A: try this -
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
answers = {};
answers[0] = {};
answers[0]['question_id'] = '12';
answers[0]['answer_id'] = '32';

$.ajax({
    type: "POST",
    url: 'test1.php',
    data: {answers: answers},
    //dataType: "json",

    error: function(jqXHR, textStatus, errorThrown){
        alert(errorThrown);
    },
    success: function(data){
        alert('success!');
    }
});
</script>

test1.php
<?php
$a=$_POST['answers'][0]['answer_id'];
echo "$a hello"; //display nothing, I wish to display '32' here


text:
Q: Magento 2: How to get certification of Magento 2? Anyone used to get certification of Magento 2.
May you show me how to get certification of Magento 2 ?

A: 1. Before appearing for the exam we need to prepare the for the exam

*

*Examination Syllabus Details

*

*AD0-E700 Adobe Certified Expert Magento Commerce Business Practitioner (previously - Magento 2 Certified Solution Specialist)

*AD0-E702 Adobe Certified Professional - Magento Commerce Developer (previously Magento 2 Certified Associate Developer)

*AD0-E701 Adobe Certified Expert - Magento Commerce Front-End Developer (previously Magento 2 Certified Professional Front End Developer)

*AD0-E703 Adobe Certified Expert - Magento Commerce Developer (previously Magento 2 Certified Professional Developer)

*AD0-E705 Adobe Certified Expert - Magento Commerce JavaScript Developer (previously Magento 2 Certified Professional JavaScript Developer)

*AD0-E706 Adobe Certified Expert - Magento Commerce Cloud Developer (previously Magento 2 Certified Professional Cloud Developer)

*AD0-E707 Adobe Certified Expert Magento Commerce Order Management Developer (previously Magento 2 Certified Order Management Developer)

*AD0-E704 Adobe Certified Master Magento Commerce Architect (previously Magento 2 Certified Professional Developer Plus)

*Premium ($$) Study Materials and Mock Tests (By Swift Otter)

*

*AD0-E700 Adobe Certified Expert Magento Commerce Business Practitioner (previously - Magento 2 Certified Solution Specialist)

*AD0-E702 Adobe Certified Professional - Magento Commerce Developer(previously Magento 2 Certified Associate Developer)

*AD0-E701 Adobe Certified Expert - Magento Commerce Front-End Developer (previously Magento 2 Certified Professional Front End Developer)

*AD0-E703 Adobe Certified Expert - Magento Commerce Developer (previously Magento 2 Certified Professional Developer)

*AD0-E705 Adobe Certified Expert - Magento Commerce JavaScript Developer (previously Magento 2 Certified Professional JavaScript Developer)

*AD0-E706 Adobe Certified Expert - Magento Commerce Cloud Developer (previously Magento 2 Certified Professional Cloud Developer)

*AD0-E704 Adobe Certified Master Magento Commerce Architect (previously Magento 2 Certified Professional Developer Plus)

*Free / Open Source Materials

*

*AD0-E706 Adobe Certified Expert - Magento Commerce Cloud Developer (previously Magento 2 Certified Professional Cloud Developer)

*

*Magento Cloud Notes

*Cloud Developer Mock Questions

*AD0-E704 Adobe Certified Master Magento Commerce Architect (previously Magento 2 Certified Professional Developer Plus)

*

*Magento Developer Plus Study Notes

*AD0-E702 Adobe Certified Professional - Magento Commerce Developer (previously Magento 2 Certified Associate Developer)

*

*Associate Developer Study Notes

*AD0-E703 Adobe Certified Expert - Magento Commerce Developer (previously Magento 2 Certified Professional Developer)

*

*magento-lucknow/certification-notes

*magento-notes/magento2-exam-notes

*df2k2/m2cert

*Decimadigital Mock Questions

*colinmurphy/magento-exam-notes (Outdated)

*AD0-E701 Adobe Certified Expert - Magento Commerce Front-End Developer (previously Magento 2 Certified Professional Front End Developer)

*

*Frontend Developer Training Material by FishEye

*Frontend Developer Mock Questions

*Other Paid Magento Training Materials

*

*Magento trainings on the Adobe Digital Learning Platform

*Magemastery

*Magento training by Yireo

*M.academy

*Mage2TV
2. Exam Vouchers

*

*Exam Voucher (Get 50% discount on your first purchase using Holiday22 coupon code. The promo is valid till December 31, 2022)

A: You can register for Magento 2 Certified Solution Specialist (Beta) exam.
Registration begins August 4 2017. Test dates for this Beta exam will be August 14-25.
More Info on registration and certification is available at:
https://u.magento.com/certification

A: You can check details from magento site. magento certifications link
Magento Certifications for Developer
1. Adobe Certified Expert-Magento Commerce Order Management Developer
2. Adobe Certified Expert-Magento Commerce Developer
3.
Adobe Certified Expert-Magento Commerce Business Practitioner
4. Adobe Certified Professional—Magento Commerce Developer
5. Adobe Certified Master Magento Commerce Architect
6.
Adobe Certified Expert-Magento Commerce Front-End Developer
7.
Adobe Certified Expert-Magento Commerce JavaScript Developer
6.
Adobe Certified Expert Magento Commerce Cloud Developer

A: MAGENTO 2 CERTIFIED SOLUTION SPECIALIST (BETA EXAM) is from August 14th to August 25th, 2017

*

*This Beta exam will be limited to 200 registrants.

*exam at a discounted rate of $130

*150 Multiple Choice items/180 minutes to complete the exam

*All questions are valid for Magento Community Edition (2.0.x/2.1.x) and Magento Enterprise Edition (2..0.x/2.1.x).
Register fast as this Beta exam will be limited to 200 registrants.
Link : https://u.magento.com/certification-magento2-solution-specialist-1

A: MAGENTO 2 CERTIFIED SOLUTION SPECIALIST exam is available now please check below link
https://u.magento.com/certified-magento2-solution-specialist
You can also find study guide for Magento 2 exam from this link

A: Developer Certification is released.
https://u.magento.com/magento-2-certified-professional-developer
Solution specialist certification also available
https://u.magento.com/certified-magento2-solution-specialist

A: i would like to recommand you this all-in-one blog post:
https://firebearstudio.com/blog/how-to-pass-the-magento-2-certification.html
it's a very good starting point to get a clear and concise overview of the official Magento Certification program with few pointers to good materials on internet (blogs, youtube channels, alternative options for training courses ..) to start your preparation.
also have a look at the official Magento certification directory and try to get touch with those who already get certified in order to get feedback, hints, advises and some encouragement.
and last but not least START with the official devdocs.

A: I purchased Magento Certification Voucher (After Magento Purchase by Adobe ) from below link.
https://market.xvoucher.com/adobe
and you will get mail after successfully place voucher order.In that mail step by step info to book exam date on below site
https://auth.services.adobe.com/en_US/index.html/