text:
Q: How to detect if an image contains only white color with C++ We are writing a piece of software which downloads tiles from the internet from WMS servers (these are map servers, and they provide images as map data for various locations on the globe) and then displays them inside a window, using Qt and some OpenGL bindings.
Some of these servers contain data only for specific regions on the planet, and if you request and area outside of what they support it they provide you just a blank white image, which we do not want to use since they occupy extra space. So the question is:
How to identify whether an image contains only 1 color (white), or not.
What we have tried till now is the following:

*

*Create a QImage, loop over every pixel of it, see if it differs from white. This is extremely slow, and since we want this to be a more or less realtime application, this idea sadly does not work.

*Check if the image size is the same as an empty image size, but this also does not work, since it might happen that:

*

*There is another image with the same size which actually contains data

*It might be that tiles which are over an ocean have just one color, a light blue, and we need those tiles.

*Do a "post processing" of the downloaded images and remove them from the scene later, but this looks ugly from the users' perspective that tiles are just appearing and disappearing ...

*Request transparent images from the WMS servers, but due to some OpenGL mishappenings, when rendering, these images appear as black only on some (mostly low-end) video cards.

Any idea, library to use, direction or even code is welcome, and we need a C++ solution, since our app is C++.
Edit for those suggesting to sample pixels only from a few points in the map:
 and
The two images above (yes, the left image contains a very tiny piece of Norway in the corner), would be eliminated if we would assume that the image is entirely white based only sampling a few points, in case none of those points actually touch any color than white. Link to the second image: https://wms.geonorge.no/skwms1/wms.sjokartraster2?LAYERS=all&SRS=EPSG:900913&FORMAT=image/png&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&BBOX=-313086.067812500,9079495.966562500,0.000000000,9392582.034375001&WIDTH=256&HEIGHT=256&TRANSPARENT=false

A: The correct and most reliable way would be to uncompress the PNG bytes and check each pixel in a tight loop.
The most usual source of an image process routine being "slow" is invoking a function call per-pixel.  So if you are calling QImage::pixel in a nested loop for each row/column, it will not have the performance you desire.
Instead, take advantage of the fact that QImage gives you raw image bytes via the scanLine method or the bits method:
Something like this might work:
const int bytes_per_line = qimage.bytesPerLine();

unsigned char white_row[MAX_WIDTH * 4];
memset(white_row, 0xff, sizeof(white_row));

bool allWhite = true;
for (int row = 0; allWhite && (row < height); row++)
{
    unsigned char* row_data = qimage.scanLine(row);
    allWhite = !memcmp(row_data, white_row, bytes_per_line);
}

The above loop terminates pretty fast the moment a non-white pixel is encountered.


text:
Q: How to upgrade OpenGL on Ubuntu? I'm running ubuntu 20.04.5 on an HP EliteBook 850. lspci shows the VGA:
00:02.0 VGA compatible controller: Intel Corporation Haswell-ULT Integrated Graphics Controller (rev 0b)

glxinfo gives:
OpenGL version string: 3.0 Mesa 21.2.6

How can I upgrade OpenGL to at least version 3.2? I followed the procedure described at this link, but afterward glxinfo still shows OpenGL 3.0. Is there a concise guide somewhere describing the correct procedure?
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET Core (Razor page) - how to download a file in a specific folder (of the client) Is it possible to download a file (office document) on client machine indicating a specific folder (e.g.: C:\Projects\Documents)?
Thanks

A: I need to develop a web-application where user can:
- download a document (office document)
- edit/change the document downloaded
- upload the document changed


text:
Q: Specific htaccess redirect I want to remove all numeric fragments of the url on the third position, if the first fragment matches a single string xxxx.
Example:
example.com/xxxx/hello/1

should become
example.com/xxxx/hello

and
example.com/xxxx/hello/1/anything

should become
example.com/xxxx/hello

but
example.com/xxxx/hello
example.com/abcd/hello/anything
example.com/xxxx/hello#12

should be kept unchanged.


text:
Q: localhost not starting after start-all.sh command I recently installed Hadoop, then I start hadoop using start-all.sh command, for the early stages it worked with 0 nodes, can be viewed on localhost:50070.
I tried to fix the LiveNodes = 0, by copy a folder to hadoop repo, but couldn't.
Then I tried to format nodes by hadoop namenode -format command.
Now the problem is localhost also not shows up.
What I did wrong? And how could I revert the operation.


text:
Q: MFRC522 PICC responded with NAK (Porting MFRC522 arduino library[C++] to [C]) First some introducing.
I am trying to make the MFRC522 library for Arduino work on an ATmega328 programmed in C(I am using a 'normal' controller first, to make it work on a raspberry pi in a later state).
I copied the .h and .cpp from the library to my own project and renamed the .c to .cpp. After removing the classes in the .h file, it was time for the .c file. I replaced all the 'byte' statements to 'uint8_t', replaced the 'Serial.print' with printf and did the changes for GPIO and SPI.
The problem.
After some small mistakes I finally got data from a keycard. However it looked like to work, I get an error with reading line 58 from the card. The error is:

MIFARE_READ() failed: A MIFARE PICC responded with NAK.

I added a print statement to the SPI write and read and found out the following difference(on the left the [C] version and on the right the Arduino version): (because of my reputation, the picture can be found in the BitBucket I mentioned at the code part)
Code
The code is pretty long, but i made it available on BitBucket
I hope someone can point me where to look(some [C++] >> [C] different interpretations), because I don't know anymore where to look.
Sander

A: You need to run the PCD_Authenticate function before reads and writes. There are a few pre programmed keys in the linked github library that will authenticate the cards. I was getting this when trying to write to the card because I was using KEY_B and not KEY_A. You can see this Authenticate used in the samples provided on that GitHub page. It should looks something like this.
status = (MFRC522::StatusCode) mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));

From what I can tell the NAK simply means that the wrong key was used or maybe no key.


text:
Q: css issue: extra white space on the right of all my content I'm posting my issue here because I can't find the problem by my own.
I'm building this website: http://www.karlienfabre.be/basmicro , at this time it's possible to scroll horizontally because there is a lot of white space at the right. I do not want this white space, I don't want that you can scroll horizontally.
I think it is something with the section nav
If there is a css-hero who can help me...
Thanks in advance!

A: The problem is with section#twitter slider. It's very wide that's why it expands the body width too. Try this simple fix:
#twitter .container {
    overflow: hidden;
}


text:
Q: php envio via curl nodejs Boa noite, estou a 2 dias tentando enviar dados do curl php para o nodejs
quando eu faço por fora do curl funciona...
mas precisava que fosse deste caminho....
tentativa 1 php:
    {
       $this->ch = curl_init();
     curl_setopt($this->ch,CURLOPT_URL, $url);

  curl_setopt($this->ch,CURLOPT_POST, 1);
  curl_setopt($this->ch,CURLOPT_POSTFIELDS, $data);
  curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($this->ch, CURLOPT_POST, true);

  $result = curl_exec($this->ch);
 return curl_close($this->ch);
 }

tentativa 2:
    $ch = curl_init();
  curl_setopt($ch,CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//curl_setopt($ch, CURLOPT_PORT, 2403);   //<----- Commented out !
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(    //<--- Added this code block
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data))
);
var_dump($data);
$data = curl_exec($ch)|

no nodejs  o metodo post de nenhum jeito traz algum tipo de retorno isso que eu já tentei um pouco de tudo e está me faltando ideias de como fazer ou o que estou fazendo errado kkk queria enviar via post um xml para o nodejs tratar mas nem um envio basico está indo então me sinto frustrado ... 4 dias no problema e mal estou engatinhando nele ...
  app.post('/teste', function (req, res,next) {

//   console.log(util.inspect(req));
//console.log(util.inspect(req, false, null, true /* enable colors */));;
console.log(req.params);
console.log(req.query);

  console.log('receiving data ...');
    console.log('body is ',req.body);
    res.send(req.body);

});

Este método eu consigo pegar os itens e os retornos estão ok:
app.get('/agencia2', function (req, res,next) {

//  console.log(req.params);
//  console.log(req.body);
  console.log(req.query);
  console.log(req.query.id);

   res.send("quase teste");
});

A: no php consigo enviar tudo o que eu preciso e no nodejs eu processo o xml de retorno que não estava processando no php estou apresentando o link que achei a resposta para meus questionamentos bem como o código correspondente.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser')
app.use(bodyParser.json());

app.post('/phpcallback', function(req, res) {
    var content = req.body;
    console.log('message received from php: ' + content.msg);
    //to-do: forward the message to the connected nodes.
    res.end('ok');
});

http.listen(8080, function(){
  var addr = http.address();
  console.log('app listening on ' + addr.address + ':' + addr.port);
});

curl no php:
<?php

$data = array("name" => "Robot", "msg" => "Hi guys, I'm a PHP bot !");
$data_string = json_encode($data);

$ch = curl_init('http://localhost:8080/phpcallback');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);

echo curl_exec($ch)."\n";
curl_close($ch);

?>


text:
Q: How can I show only one MIN date? I am trying to show only the minimal date depends on each projectID, but the result is showing more than one. How can I show only one record?
Select DATEADD(DAY, -(DAY(p.StartDate) - 1), p.StartDate), p.ProjectID
from pm_project p
where ProjectID = 19
group by p.ProjectID, p.StartDate
Having DATEADD(DAY, -(DAY(p.StartDate) - 1), p.StartDate) = MIN(p.StartDate)

A: You should use RANK() to get the minimal date for each ProjectID separately:
SELECT Date, ProjectID FROM (
    Select DATEADD(DAY, -(DAY(p.StartDate) - 1), p.StartDate) AS Date, p.ProjectID,
        RANK() OVER (PARTITION BY p.ProjectID ORDER BY DATEADD(DAY, -(DAY(p.StartDate) - 1), p.StartDate)) AS rank
    from pm_project p
    where ProjectID = 19
    group by p.ProjectID, p.StartDate
    Having DATEADD(DAY, -(DAY(p.StartDate) - 1), p.StartDate) = MIN(p.StartDate)
) ranked
WHERE rank = 1

Here the inner query is your query with an extra rank column, which contains the position of the date in the ordered list of dates for each ProjectID separately. You can read the function quite literraly: rank the lines order by the dates and partitioned by the ProjectID.
From this, you will have to select every field where rank = 1, meaning you select the first (minimal) date for each ProjectID.


text:
Q: jquery how to skip "a" element if its array value is null Could you please help on how can I achieve not show "a" only if "a1links" value is null.
ie.for the second value on "a1links" array;I dont want "ahref" link to be shown on my html page.
    var a1links = [
        '8li ', '',
'8li ', 'a1link4-',
'a1link5-', 'a1link6-',

...
'+ a1links[j] + imageName + '

but for only values with "null" or '  ' be skipped,The others need to continue as they are.
the complete function is
$.each( images, function( j, imageName ) {

$('

'+ alinks[j] + imageName +'

                                                                                '+ a1links[j] + imageName + '
                                                           '+ a2links[j] + imageName + '

').appendTo('#images');
                                });

thanks a lot for helping.
-------------------------what I tried is below -----------------
this is removing the "a" for all if a1links array is completely empty....
$("input[name='a1links[]']").each(function() {
    var value = $(this).val();
    if (value) {
        a1links.push(value);
    }
});
if (a1links.length === 0) {
  $(".test").hide();
    }

else {
  //send data
}

but I only require this if one of the value on the array is empty.the other array values needs to be read by function and create  of a1links
    $.each( images, function( j, imageName ) {

$('

'+ alinks[j] + imageName +'

                                                                                '+ a1links[j] + imageName + '
                                              '+ a2links[j] + imageName + '

').appendTo('#images');
                                });

A:

let a1links = [
        '8li ', '',
'8li ', 'a1link4-',
'a1link5-', 'a1link6-']

let fragment = document.createDocumentFragment();
a1links.forEach(link => {
 if(link) { // all truthy values
   let a_tag = document.createElement("a")
  a_tag.href = link
  a_tag.innerText = `${link} | `
  fragment.appendChild(a_tag)
 }
})

document.body.appendChild(fragment)

Here's a snippet in javascript to achieve the same


text:
Q: Jboss(Wildfly) server log not able to print MDC key value using %X{key} I have configured %X{key} pattern in standalone.xml file(at path /usr/local/wildfly/standalone/configuration) under logging module as given below.
<formatter name="PATTERN">
   <pattern-formatter pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %X{user-identity} %s%E%n"/>
</formatter>
<formatter name="COLOR-PATTERN">
    <pattern-formatter pattern="%K{level}%d{HH:mm:ss,SSS} %-5p [%c] (%t) %X{user-identity} %s%E%n"/>
 </formatter>

Where user-identity is key which is set in ContainerRequestFilter implementation class like MDC.put("user-identity", "123"). and MDC is Mapped Diagnostic Context in jboss logging.
Same code is working for Development server(i.e. printing user-identity value in server.log file) but not working in QA or Production environment.
Please suggest.

A: I have solved this problem just by configuring %X{key} pattern in standalone-full.xml file(at path /usr/local/wildfly/standalone/configuration) under logging module configuration under PATTERN and COLOR-PATTERN formatter.


text:
Q: Azure DevOps - Incorrect value in System.JobPositionInPhase variable I am using a multi-configuration build pipeline in Azure DevOps to build multiple versions of an application. We use the $(system.jobpositioninphase) variable to set variables for each build. This has worked well for quite a while. Sometime between January 25th and today the builds started failing because the System.JobPositionInPhase variable started returning a value of 1 for all parallel phases.
Here is an example of how we are using the variable: https://stackoverflow.com/a/51091919/264650
I have created an extremely basic build pipeline to verify the issue isn't related to anything else in our pipeline.See the screenshot to see that the pipeline is configured as multi-configuration with a multiplier value of "multiplier". The value of the "multiplier" variable is "phase1,phase3".

The only task simply prints the values of those variables.
But you can see on the phase2 iteration, the variable $(System.JobPositionInPhase) prints "1" instead of 2. I also have release pipelines that use this same pattern, and they are working fine. Only multi-configuration builds seem to be affected.

A: Confirmed to be a bug by Microsoft.
https://developercommunity.visualstudio.com/solutions/500331/view.html


text:
Q: Converting dataframe to dictionary with key and multiple value I have an usecase where I have to read xl file with multiple header columns and values.
I have to convert that into a dictionary, key with multiple values.
The xl header will vary each time, some times 2 columns some to three, and so on.

The sample data frame for an xl file is
      key1    key2
      abc     xyz
      bca     yxz
      cab     zxy

the output should be as...
   {'key1': ['abc','bca','cab'], 'key2': ['xyz','yxz', 'zxy']}

if there is one more column key3, I should able to include that as well in the dictionary

.
import pandas as pd
workbook_loc = "c:\\2020\Book1.xlsx"
df = pd.read_excel(workbook_loc, sheet_name=None)
data_dict = df.to_dict()

but the above script is throwing out  AttributeErro 'dict' object has no attribute.

what is the wrong I am doing?

A: When you specify sheet_name=None it returns a dictionary instead of pandas dataframe. its always good practice to specify a sheet name.
You can try this..
import pandas as pd
workbook_loc = "c:\\2020\Book1.xlsx"
df = pd.read_excel(workbook_loc, index_col=0, sheet_name='Sheet1')
data_dict = {}
for col in df.columns:
    data_dict[col]=[row for row in df[col]]


text:
Q: How can I Troubleshoot the Google Cloudstorage Client? Given the sample code:
import cloudstorage
from django.shortcuts import render

def list_files(request):
  file_list = []
  try:
    bucket_name = my_bucket
    gcs_list_obj = cloudstorage.listbucket('/' + bucket_name, delimiter="/")
    for item in gcs_list_obj:
        file_list.append(item)

  except Exception, e:
    raise e

  return render(request, 'default.htm', {'file_list': file_list,
                                       'bucket_name': bucket_name})

The expectation would be to see a populated array of iterated objects from cloudstorage.listbucket  Instead Django throws an InternalError with the message
5:
What are the common steps for troubleshooting Storage buckets in django?

A: Did you want to add to file_list GCSFileStat objects (and are you handling it correctly in the template) or just the filenames.
If the latter than you can add item.filename instead.

A: After much frustration, it seems there the issue was related to my project NOT having a default bucket.
Navigating to:
https://console.developers.google.com/storage/browser/YOUR_PROJECT.appspot.com/
Then uploading a few files / folders seems to have resolved the issue, and the sample code works as expected.


text:
Q: "return Json(jsonData)" vs "return content (jsonData, "application/json")" I have this code inside an ASP.NET MVC 5 action method, which serializes an object as JSON using Newtonsoft package:
string jsonData = JsonConvert.SerializeObject(result);

And I can return the above JSON using this return statement:
return Json(output, JsonRequestBehavior.AllowGet);

Or using this return statement:
return Content(output, "application/json");

So are there really any differences between the two methods return Json(jsonData) vs return content (jsonData, "application/json") ?
And which one should we use to return the already serialized json object?
Now when I call the action method from Firefox, I will get this json in case I use return Json(output, JsonRequestBehavior.AllowGet);:

while I will get this json (which seems to be the accurate one) when using return Content(output, "application/json");:

It seems the json I will get when using return Content(output, "application/json"); is the accurate one, while using return Json(output, JsonRequestBehavior.AllowGet); will return string that is not be understandable by Firefox?
Thanks


text:
Q: Calling Akka actor from Play controller I have been playing with the distributed worker pattern and I'm running into an issue pushing work from a web request.
The example project has a frontend:
val mediator = DistributedPubSubExtension(context.system).mediator

  def receive = {
    case work =>
      log.info("Frontend received: " + work.toString())
      implicit val timeout = Timeout(5.seconds)
      (mediator ? Send("/user/master/active", work, localAffinity = false)) map {
        case Master.Ack(_) => Ok
      } recover { case _ => NotOk } pipeTo sender
  }

And a WorkProducer:
override def preStart(): Unit =
    scheduler.scheduleOnce(5.seconds, self, Tick)

def receive = {
    case Tick =>
      n += 1
      log.info("Produced work: {}", n)
      val work = Work(nextWorkId(), n)
      frontend ! work
      context.become(waitAccepted(work), discardOld = false)

  }

This all works just fine, when I send directly to the frontend from my Play Framework controller:
def multiply(num: Long) = Action {
    implicit request =>
        implicit val timeout = Timeout(5.seconds)
        val frontend = core.Main.frontend
        frontend ! num
        Ok
  }

The message seems to get lost. The frontend receives the message but it seems the actors down stream do not.
I have modified the play config to use a ClusterActorRefProvider
play {
  akka {
    extensions = ["akka.contrib.pattern.ClusterReceptionistExtension"]
    actor.provider = "akka.cluster.ClusterActorRefProvider"
    remote.netty.tcp.port=0
        }
}

But to no avail.

A: I've been a muppet and haven't sent the correct message, the controller should look like this:
def multiply(num: Long) = Action {
    implicit request =>
        implicit val timeout = Timeout(5.seconds)
        val frontend = core.Main.frontend
        val work = Work(nextWorkId(), num)
        frontend ! work
        Ok
  }


text:
Q: Flood fill function not producing good results I applied the floodfill function in opencv to extract the foreground from the background but some of the objects in the image were not recognized by the algorithm so I would like to know how I can improve my detections and what modifications are necessary.
image = cv2.imread(args["image"])
image = cv2.resize(image, (800, 800))
h,w,chn = image.shape
ratio = image.shape[0] / 800.0
orig = image.copy()

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 75, 200)
# show the original image and the edge detected image
print("STEP 1: Edge Detection")
cv2.imshow("Image", image)
cv2.imshow("Edged", edged)

warped1 = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
T = threshold_local(warped1, 11, offset = 10, method = "gaussian")
warped1 = (warped1 > T).astype("uint8") * 255
print("STEP 3: Apply perspective transform")

seed = (10, 10)

foreground, birdEye = floodFillCustom(image, seed)
cv2.circle(birdEye, seed, 50, (0, 255, 0), -1)
cv2.imshow("originalImg", birdEye)

cv2.circle(birdEye, seed, 100, (0, 255, 0), -1)

cv2.imshow("foreground", foreground)
cv2.imshow("birdEye", birdEye)

gray = cv2.cvtColor(foreground, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
cv2.imwrite("gray.jpg", gray)

threshImg = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY)[1]
h_threshold,w_threshold = threshImg.shape
area = h_threshold*w_threshold

cv2.imshow("threshImg", threshImg)[![enter image description here][1]][1]

The floodFillCustom function is as follows -
def floodFillCustom(originalImage, seed):

    originalImage = np.maximum(originalImage, 10)
    foreground = originalImage.copy()

    cv2.floodFill(foreground, None, seed, (0, 0, 0),
                  loDiff=(10, 10, 10), upDiff=(10, 10, 10))

    return [foreground, originalImage]

A: A little bit late, but here's an alternative solution for segmenting the tools. It involves converting the image to the CMYK color space and extracting the K (Key) component. This component can be thresholded to get a nice binary mask of the tools, the procedure is very straightforward:

*

*Convert the image to the CMYK color space

*Extract the K (Key) component

*Threshold the image via Otsu's thresholding

*Apply some morphology (a closing) to clean up the mask

*(Optional) Get bounding rectangles of all the tools

Let's see the code:
# Imports
import cv2
import numpy as np

# Read image
imagePath = "C://opencvImages//"
inputImage = cv2.imread(imagePath+"DAxhk.jpg")

# Create deep copy for results:
inputImageCopy = inputImage.copy()

# Convert to float and divide by 255:
imgFloat = inputImage.astype(np.float) / 255.

# Calculate channel K:
kChannel = 1 - np.max(imgFloat, axis=2)

# Convert back to uint 8:
kChannel = (255*kChannel).astype(np.uint8)

The first step is to convert the BGR image to CMYK. There's no direct conversion in OpenCV for this, so I applied directly the conversion formula. We can get every color space component from that formula, but we are only interested on the K channel. The conversion is easy, but we need to be careful with the data types. We need to operate on float arrays. After getting the K channel, we convert back the image to an unsigned 8-bit array, this is the resulting image:

Let's threshold this image using Otsu's thresholding method:
# Threshold via Otsu:
_, binaryImage = cv2.threshold(kChannel, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

This yields the following binary image:

Looks very nice! Additionally, we can clean it up a little bit (joining the little gaps) using a morphological closing. Let's apply a rectangular structuring element of size 5 x 5 and use 2 iterations:
# Use a little bit of morphology to clean the mask:
# Set kernel (structuring element) size:
kernelSize = 5
# Set morph operation iterations:
opIterations = 2
# Get the structuring element:
morphKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernelSize, kernelSize))
# Perform closing:
binaryImage = cv2.morphologyEx(binaryImage, cv2.MORPH_CLOSE, morphKernel, None, None, opIterations, cv2.BORDER_REFLECT101)

Which results in this:

Very cool. What follows is optional. We can get the bounding rectangles for every tool by looking for the outer (external) contours:
# Find the contours on the binary image:
contours, hierarchy = cv2.findContours(binaryImage, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Look for the outer bounding boxes (no children):
for _, c in enumerate(contours):

    # Get the contours bounding rectangle:
    boundRect = cv2.boundingRect(c)

    # Get the dimensions of the bounding rectangle:
    rectX = boundRect[0]
    rectY = boundRect[1]
    rectWidth = boundRect[2]
    rectHeight = boundRect[3]

    # Set bounding rectangle:
    color = (0, 0, 255)
    cv2.rectangle( inputImageCopy, (int(rectX), int(rectY)),
                   (int(rectX + rectWidth), int(rectY + rectHeight)), color, 5 )

    cv2.imshow("Bounding Rectangles", inputImageCopy)
    cv2.waitKey(0)

Which produces the final image:


text:
Q: Controlling Access to Class Members class A
{
   private:
           int x;
   public:
           virtual void show()
           {
               cout<<"X: "<<x;
           }
};

class B: public A
{
    public:
           virtual void show()
           {
               cout<<"In class B\n";
               A::show();
           }
};

My question is about accessibility from a member function. In this example, can we say that member function of B (show() of B) can access X in the class A.

A: Since x is declared private in A, nothing in B can directly access it.  Of course, it can be accessed indirectly -- B can call A::show() which can access x.  But B::show() cannot access x, nor can anything else in B.

A: You are not really accessing A.x, you are accessing A.show().
To answer your question, B::show() is not accessing the private member x in A.
The reason for this is, class A can change the function A::show() and do something else, and B can just call A::show().
This is the main point of encapsulation. You can tell A to do things (like show()), but A decides how to do them.

A: *

*A::show() can access any member variables in it's own class, class A.

*Member functions in class B can access any public or protected member variables in class A.
and

*Member functions in class B can access any public of protected member functions in class A.

2 and 3 are possible because the "Most accessible level" of A is defined as public.
Class B: public A

In your code, specifically, the accessibility level of int x; doesn't matter, because it is never directly accessed from class B.


text: Q: Puxar imagens no HTML com Node Js + Express Galera estou começando com o nodejs e tenho uma duvida. Sempre que chamo ima imagem ou até mesmo o bootstrap no meu arquivo eu tenho que usar o sendfile. Sempre que u por um icone ou imagem eu terei que setar a rota no node e depois no arquivo, ou existe uma forma mais prática para isto?


text:
Q: Why I can't override handleMessage method when I initialize a Handler object?
*

*It should be like this :
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
    }
};

*However,in my IDE,it must be overrided like this:
    Handler handler = new Handler() {

    @Override
    public void close() {

    }

    @Override
    public void flush() {

    }

    @Override
    public void publish(LogRecord logRecord) {

    }
};

And it seems that the Handler object here doesn't support such method called "handleMessage".
What should I do?

A: That's a name conflict between different Handler classes.
The first Handler you mention seems to be a javax.xml.ws.handler.Handler docs or a android.os.Handler doc, both of which have a handleMessage method to override.
The second Handler seems like it is a java.util.logging.Handler docs that has the methods you mention


text:
Q: 14.10 font issue Since I upgraded from 14,04 to 14,10 I am experiencing the following issue.. Pretty much everywhere the font is distorted. Also, when I type the characters sort of delay appearing on the screen, same thing applies for the text selection. Any clues ?

A: Turn off hinting in the Tweak tool or Appearances. That fixed it 95% for me.
see  https://bugs.launchpad.net/ubuntu/+source/fontconfig/+bug/554935


text:
Q: Is there a such thing as "standard error of random variable?" I am wondering if there is a such thing as "Standard Error" of a random variable? If so, is it simply just the standard deviation of the random variable?

A: As Benjamin Wang commented, the term "standard error" is usually reserved for random samples whose distribution is possibly unknown. Given $n$ independent sampled observations $o_1, \ldots, o_n$ with sample standard deviation $\sigma_o$, the sampled mean value $\bar{o}$ has a so-called "standard error on the mean" given by
$$ \sigma_{\bar{o}} = \frac{\sigma_{o}}{\sqrt{n}} $$
where $\sigma_o$ is the sample standard deviation. See wiki for further details.
For random variables, the appropriate term you are probably looking for is just the standard deviation. This always exists for discrete random variables but may be undefined/infinite for continuous random variables. Classical examples where the standard deviation is undefined are the Cauchy distribution and the Pareto distribution for $\alpha \in (1,2]$.


text:
Q: What does the phrase "Richard of York gave battle in vain" have to do with a rainbow? This question is from the TV game show, "Million Dollar Mind Game" on ABC:

What phrase is "Richard of York gave battle in vain"'s American counterpart?

The contestants gave the final guess: "Moving upstream without a paddle", but the correct answer was "Rainbow".
I still don't get it. Why is the counterpart "Rainbow"?

A: The phrase creates an acronym (initial letters) and also a mnemonic (memory assist device) for the visible spectrum, and so the colours of a rainbow.
The initial letters of 'Richard Of York Gave Battle In Vain' are ROYGBIV (pronounced roy-ge-biv), which correspond to the main colours of the visible spectrum as Red, Orange, Yellow, Green, Blue, Indigo and Violet.
An example of another mnenomic is 'I wish I could determine Pi' - counting the letters gives 1,4,1,5,9,2, and Pi is 3.141592... .


text:
Q: Method in viewWillAppear and viewDidLoad didn't loaded I have created a method to check the status of a server in my viewcontroller, I need to check this, everytime I will open the app.
I call [self checkStatus]; from viewWillAppear and viewDidLoad, but when I open the app, by clicking home button, and I try to open the app again (clicking the app icon in applications) this method is not called. I have a NSLog to view when it is launched or not.
I'm frustrated. Thanks for your help.

A: You can react to app changes using NotificationCenter:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) name:UIApplicationDidBecomeActiveNotification object:nil];

BTW: don't forget to removeObserver when you don't need it!
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];

You can also use UIApplicationWillEnterForegroundNotification etc, depending what do you need.
You should read about app lifecycle on Apple Developer pages :). Read:

*

*AppleDeveloperLink Especially section: "Execution States for Apps" to know more about app lifecycle.

*StackOverflowLink to know more about view lifecycle.

A: iOS is not calling those methods again, but the delegate methods in the AppDelegate. You have to propagate the message to your controllers then.
I hope this will help you: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/


text:
Q: Trying to create multiple data frames while web scraping in R I'm still pretty new to coding and especially web scraping, but here's what I'm trying to do:
I wanna scrape fbRef.com to create a data frame for some of each Premier League teams' match stats.
I know this works for getting the team links:
library(rvest)
page <- "https://fbref.com/en/comps/9/Premier-League-Stats"
scraped_page <- read_html(page)
teamLinks <- scraped_page%>%
   html_nodes("#stats_squads_standard_for a")%>%
   html_attr("href")
teamLinks <- paste0("https://fbref.com/",teamLinks)

I'm also able to create a list of each team's name based on this same info
Team <- scraped_page%>%
   html_nodes('#stats_squads_standard_for .left')%>%
   html_text()%>%
   as.character()

But now I want to create a data frame for each team separately and scrape each team's page for specific stats. I have a for loop to get the stats I need, but I don't know how to separate it or how to name each data frame with the team name.
for (i in 1:length(teamLinks)){
  url <- teamLinks[i]
  scraped_url <- read_html(url)
  Team <- scraped_page%>%
    html_nodes('#stats_squads_standard_for .left')%>%
    html_text()%>%
    as.character()
   df_name <- paste0(Team[i])
   df <- {
    Comp <- scraped_url%>%
      html_nodes(comp)%>%
      html_text()
    Venue <- scraped_url%>%
      html_nodes(venue)%>%
      html_text()
    Result <- scraped_url%>%
      html_nodes(result)%>%
      html_text()
    Goals_For <- scraped_url%>%
      html_nodes(GF)%>%
      html_text()
    Goals_Against <- scraped_url%>%
      html_nodes(GA)%>%
      html_text()
    Opponent <- scraped_url%>%
      html_nodes(Opp)%>%
      html_text()
    xG <- scraped_url%>%
      html_nodes(xg)%>%
      html_text()
    xGA <- scraped_url%>%
      html_nodes(xga)%>%
      html_text()
    Possession <- scraped_url%>%
      html_nodes(poss)%>%
      html_text()
    Formation <- scraped_url%>%
      html_nodes(formation)%>%
      html_text()
    data.frame(Comp,Venue,Goals_For,Goals_Against,
               Opponent,xG,xGA,Possession,Formation)
  }
}

also any help cleaning up that for loop would be much appreciated
these are the values for each html variable as well:
comp <- ".left:nth-child(3) a"
venue <- ".left:nth-child(6)"
result <- "#matchlogs_for .left+ .center"
GF <- "#matchlogs_for .right:nth-child(8)"
GA <- "#matchlogs_for .right:nth-child(9)"
Opp <- ".left:nth-child(10)"
xg <- "#matchlogs_for td.left+ .right"
xga <- "#matchlogs_for .right:nth-child(12)"
poss <- "#matchlogs_for td:nth-child(13)"
formation <- ".left:nth-child(16)"

thank you in advance!

A: You could create a list before the loop and save each dataframe into that list, as in:
TeamList <- list()

for (i in 1:length(teamLinks)){

  # [...] your scraping code that leads to a "df"

  TeamList[[i]] <- df

}

Then name the TeamList's dataframes based on each team, and then convert the list of dataframes into multiple dataframes with list2env():
names(TeamList) <- Team

list2env(TeamList, envir=.GlobalEnv)


text:
Q: Program fails to count the beverages and total number of persons I'm beginner of c sharp language. I need help to compile this program it does not count the beverages and total number of persons
using System;
using System.Collections.Generic;
using System.Text;

namespace survey
{
    class Program
    {
        static void Main(string[] args)
        {
            int choice = 0 , coffee = 0, tea = 0, coke = 0, juice = 0, person = 0;
            while (choice != -1)
            {
                Console.WriteLine("\n SURVEY ON BEVERAGES ");
                Console.WriteLine("======================== ");
                Console.WriteLine("\n1. COFFEE\n2. TEA\n3. COKE\n4. ORANGE JUICE\n5. PLEASE ENTER -1 TO EXIT\n ");
                Console.Write(" CHOOSE YOUR FAVORITE BEVERAGES FROM THE LIST : ");
                choice = Convert.ToInt16(Console.ReadLine());
            }

            switch (choice)
            {
                case 1:
                    coffee++;
                    break;
                case 2:
                    tea++;
                    break;
                case 3:
                    coke++;
                    break;
                case 4:
                    juice++;
                    break;
            }
            person++;
            if (choice == -1)
            {
                Console.WriteLine("\n\nThe total number of people surveyed is {0}",person);
                Console.WriteLine(" The results are as follows:\n");
                Console.WriteLine("Beverage of choice and votes.\n");

                Console.WriteLine("Coffee = {0}",coffee);
                Console.WriteLine("Tea = {0}",tea);
                Console.WriteLine("Coke = {0}",coke);
                Console.WriteLine("Orange juice = {0}",juice);
            }

        }

    }

}

A: You need to iterate the different beverand choices, count them and then exit the loop printing the result. Try this code:
using System;
using System.Collections.Generic;
using System.Text;

namespace survey
{
    class Program
    {
        static void Main(string[] args)
        {
            int choice = 0 , coffee = 0, tea = 0, coke = 0, juice = 0, person = 0;
            while (choice != -1)
            {
                Console.WriteLine("\n SURVEY ON BEVERAGES ");
                Console.WriteLine("======================== ");
                Console.WriteLine("\n1. COFFEE\n2. TEA\n3. COKE\n4. ORANGE JUICE\n5. PLEASE ENTER -1 TO EXIT\n ");
                Console.Write(" CHOOSE YOUR FAVORITE BEVERAGES FROM THE LIST : ");
                choice = Convert.ToInt16(Console.ReadLine());

                switch (choice)
                {
                    case 1:
                        coffee++;
                        break;
                    case 2:
                        tea++;
                        break;
                    case 3:
                        coke++;
                        break;
                    case 4:
                        juice++;
                        break;
                }
                person++;
            }

            Console.WriteLine("\n\nThe total number of people surveyed is {0}",person);
            Console.WriteLine(" The results are as follows:\n");
            Console.WriteLine("Beverage of choice and votes.\n");

            Console.WriteLine("Coffee = {0}",coffee);
            Console.WriteLine("Tea = {0}",tea);
            Console.WriteLine("Coke = {0}",coke);
            Console.WriteLine("Orange juice = {0}",juice);

        }

    }

}

A: I believe your issue is that you have a while loop that continues until the choice value is -1. Then when it is -1, you run the switch statement on choice which is -1. The way you can fix this is by putting the switch statement inside your while loop

A: As you write Case outside of the while loop, this problem raised. You can solve the problem by including Case inside While loop. Here is my code after the modification. You can try this one.
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;

        namespace survey
        {
            class Program
            {
                static void Main(string[] args)
                {
                    int choice = 0, coffee = 0, tea = 0, coke = 0, juice = 0, person = 0;
                    while (choice != -1)
                    {
                        Console.WriteLine("\n SURVEY ON BEVERAGES ");
                        Console.WriteLine("======================== ");
                        Console.WriteLine("\n1. COFFEE\n2. TEA\n3. COKE\n4. ORANGE JUICE\n5. PLEASE ENTER -1 TO EXIT\n ");
                        Console.Write(" CHOOSE YOUR FAVORITE BEVERAGES FROM THE LIST : ");
                        choice = Convert.ToInt16(Console.ReadLine());

                        switch (choice)
                        {
                            case 1:
                                coffee++;
                                break;
                            case 2:
                                tea++;
                                break;
                            case 3:
                                coke++;
                                break;
                            case 4:
                                juice++;
                                break;
                        }
                        person++;
                    }

                    if (choice == -1)
                    {
                        Console.WriteLine("\n\nThe total number of people surveyed is {0}", person);
                        Console.WriteLine(" The results are as follows:\n");
                        Console.WriteLine("Beverage of choice and votes.\n");

                        Console.WriteLine("Coffee = {0}", coffee);
                        Console.WriteLine("Tea = {0}", tea);
                        Console.WriteLine("Coke = {0}", coke);
                        Console.WriteLine("Orange juice = {0}", juice);
                    }

                }

            }

        }


text:
Q: How to get Salesforce upsertResults count in OnComplete phase in Batch component on Mule In the mule flow, I have iterated upsertResults and add it into arraylist in the process phase, but sometimes its not showing exact result because its based on batch size it keep on changing I think. And also I couldn't access flowvars in Oncomplete phase. Hereby I added my mule configuration code,
<batch:job name="Student-Application-Upsert-Batch" max-failed-records="-1">
    <batch:threading-profile poolExhaustedAction="WAIT"/>
    <batch:input>
        <data-mapper:transform doc:name="CSV To List<Account>" config-ref="CSV_To_List_Account_" stream="true"/>
    </batch:input>
    <batch:process-records>
        <batch:step name="Upsert-Account">
            <batch:commit  doc:name="Batch Commit" streaming="true">
                <sfdc:upsert config-ref="Salesforce__Basic_authentication" externalIdFieldName="Email_Address_Key__c" type="Account" doc:name="Upsert Account">
                    <sfdc:objects ref="#[payload]"/>
                </sfdc:upsert>
                <foreach   doc:name="For Each Result Record" >
                    <choice doc:name="Choice">
                        <when expression="#[payload.success == 'true']">
                            <set-variable variableName="Success" value="#[SuccessResult.add(message.payload)]" doc:name="Success Records"/>
                        </when>
                        <otherwise>
                            <set-variable variableName="Failure" value="#[FailureResult.add(message.payload)]" doc:name="Failure Records"/>
                        </otherwise>
                    </choice>
                </foreach>
                <logger message="#####------------->Failures: #[flowVars.FailureResult.size()]" level="INFO" doc:name="Log Failure Records"/>
                <logger message="#####------------->Success: #[flowVars.SuccessResult.size()]" level="INFO" doc:name="Log Success Records"/>
                <object-to-string-transformer doc:name="Object to String"/>
                <file:outbound-endpoint path="${MULE.PROCESSED_FILES}" outputPattern="#[flowVars.UpsertLogName]" connector-ref="LogFileWritter" responseTimeout="10000" doc:name="Upsert Results Log File"/>
            </batch:commit>
        </batch:step>
        <batch:step name="Log-Failures" accept-policy="ONLY_FAILURES">
            <logger message="Record with the following payload has failed. Payload:: #[message.payload], Loading Phase: #[failureExceptionForStep], Inside Failure the exception is :- #[getStepExceptions()]" level="INFO" doc:name="Log Failure"/>
            <!-- <foreach collection="#[payload]" doc:name="For Each">
                <logger message="For earch resultset row Payload is #[message.payload], counter is #[flowVars['counter']]" level="INFO" doc:name="Logger"/>
            </foreach>-->
            <object-to-string-transformer doc:name="Object to String"/>
            <file:outbound-endpoint path="${MULE.FAILURE_LOGS}" outputPattern="OnlyFailures_#[message.inboundProperties.originalFilename].txt"  responseTimeout="10000" doc:name="File" connector-ref="LogFileWritter"/>
        </batch:step>
    </batch:process-records>
    <batch:on-complete>
        <logger message="Batch Failed Records: #[payload.failedRecords]" level="INFO" doc:name="Logger"/>
        <logger message="#####------------->Failures: #[flowVars.FailureResult.size()]" level="INFO" doc:name="Failure Size Logger"/>
        <logger message="Number of failed Records: #[payload.failedRecords] " level="INFO" doc:name="Failed Records" />
        <logger level="INFO" doc:name="Logger" message=" Number of loadedRecord: #[payload.loadedRecords]"/>
         <logger message="Number of successful Records: #[flowVars.SuccessResult.size()]"    level="INFO" doc:name="Successful Records" />
         <logger message="ElapsedTime #[payload.getElapsedTimeInMillis()]" level="INFO" doc:name="Elapsed Time" />
     </batch:on-complete>
</batch:job>

A: You can see flowVars in the on complete but the actions you toke over them inside the steps will probably not get propagated as inside each step you're working with a copy of the message. FYI record vars won't do either as you can't see them in the on complete.
I think the best option you have here is to use object store or custom code like a java bean to store the values you want to access in on complete. Be careful with concurrency as the writing of that value in the last step can be potentially run by several threads and it's up to you to synchronise them (Object store won't help you with that either I think) .
HTH.


text:
Q: About Time and the Big Bang In a TV ducumentary, I heard that time started with Big Bang, and it is meaningless to talk of "before". This was given without any further explanation, in the peculiar, irritating style of documentaries.
Now I wonder if this fact may be motivated by the means of motion. Time, afaik, is necessarily measured (or even defined) by motion.
"Prior" to Big Bang, no motion, no time.
Is that correct?
NOTE: I have a degree in mathematics (BSc), but almost no knowledge of modern physics, so treat me as a layman when talking about it.

A: The Universe we see around us today including the space was once concentrated to a size smaller than an atom. This infinitely dense object may have had a past before that state but no information would make it from that past into our universe so we may as well say that time began at the big bang.


text:
Q: What is the best practice to create an ASP.NET portal and modules? Recently, our development team was approached by a representative from one of the departments at our institution looking for a web based solution to help out with their workflow. A few weeks later, another person from that department approached us concerning another solution for a completely different workflow process. Then after that ... yet another request from the same department from a different person.
During our requirements gathering for the various requests, we noticed that there was some common ground between core aspects of the requests. Between the projects some of the users were shared and some where not, some users roles changed between processes, 2 of the apps accessed the same data, 2 of them accessed client data. The individual requests are far from trivial.
Now, we are currently considering creating some sort of portal for this department. The portal would serve as the main entry point to the various modules/ tools that we would make available form them. In addition to that there will be a core database that stores the common data between the applications, and then module specific data would reside in their respective databases.
My question is, what would be the best way develop such a portal in an asp.net, IIS 6, MSSQL 2005 environment. I was thinking to have one app pool created in IIS to be used for all the modules and the portal. Create the portal and each module as separate web apps, and the deploy modules to sub folders underneath the portal app. The portal would just need to serve links to the various modules available. Does this make sense or is there a better way? I know SharePoint would be a good solution if we had the resources to purchase and setup a SharePoint, but we don't.

A:
I was thinking to have one app pool
  created in IIS to be used for all the
  modules

Maybe. I'm not saying it's bad - it's just a very low level bit of detail and it sounds like you've got much bigger fish to fry.
I haven't used DonNetNuke, I've know of one company that uses the multi-tenancey modules it has.  If the system is workflow intensive you might want to look into workflow systems - K2 BlackPearl is fairly well established in the Microsoft influenced market.  If tyou haven't discovered it already (and you're not going to use something like DNN) then the Microsoft Enterprise Libraries are a must-have (see: MS Patterns & Practices and CodePlex).
Other points to consider:

*

*You want to have a good framework in place that handles all the (truly) common stuff (Logging, etc).

*Keeping the different dept's areas seperate is wise; a project for each of those plus a project for the portal would be my approach.  Framework would be seperate again.

*Model the data - even if it's on a whiteboard.  Understanding the data (what's shared, what's not, where it comes from and who uses it) is pretty important.

*When looking at re-use: remember to apoply it at the right level.  Just because you write a specific UI doesn't mean you have to wriete specific BL and/or DAL for it.

*Use abstraction and Dependency Injection to keep layers apart (particularly the BL and DAL).

*Use the Interface Segregation Principle to keep verticla parts of the system seperate.

A:
" I know SharePoint would be a good
  solution if we had the resources to
  purchase and setup a SharePoint, but
  we don't."

If you mean Sharepoint services, depending on the version you need and what you already have, there might not be any purchase involved. Also check DotNetNuke as @balexandre mentioned.
Above said, if you are going the custom route, I'd focus more on library reuse than deployment aspects to share the core. Having the main site + the 2 app folders is good, but don't make that get you into cross-app calls if simpler library calls would work for your scenarios.
Don't access the core database directly from the 2 apps. Use business level operations to access the data, and define a very clear boundary / with very simple operations. The boundary is very important, if you try to model the 3 projects at a low level at the same time it will only mean unnecessary complexity / both during the analysis and in the resulting product. When thinking on the 3 projects at the same time, keep it hight level as should be the operations involved at the boundary. This is the way it'll actually work, if you later on get other apps/projects - otherwise you'll find yourself with very though decisions with 5+ products of information and a very big headache.

A: I would say a simple thing so you don't have any headaches creating something that exists...
for ASP.NET portal and modules use DotNetNuke
it's Open source, so you already have all the code... build upon it!


text:
Q: Left Align an ordered list's numbers How can I left align the numbers of an ordered listed so instead of being aligned at the . like image below, they are aligned at the number.

a

b

c

d

e

f

g

h

i

j

k

l

I want the numbers aligned the other way so that 9 is aligned with the 1 in 10.

A: It's kind of a weird thing to do. But here is how you can accomplish it.

ol {
  list-style-position: inside;
}
li{
  position: relative;
}
li p {
  position: absolute;
  left: 30px;
  margin: 0;
  top: 0;
}

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1


text:
Q: vaadin plugin for eclipse build failure on compile theme Iam getting a build failure every time i try to compile my themes. The compilation seems to work. Iam just wondering about the console log which is saying(in extracts):
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.503 s
[INFO] Finished at: 2017-01-19T17:15:48+01:00
[INFO] Final Memory: 19M/303M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.vaadin:vaadin-maven-plugin:7.6.6:compile-theme (default-cli) on project admintool: Compiling theme "VAADIN/themes/nxo-fr" failed:  Command [[
[ERROR] /bin/sh -c /opt/jdk/jdk1.8.0_91/jre/bin/java -classpath /home/cia/dev/projects/trunk/trunk/admintool/src/main/webapp:/home/cia/dev/projects/trunk/trunk/admintool/target/classes:/home/cia/dev/projects/trunk/trunk/admintool/src/main/java:/home/cia/dev/projects/trunk/trunk/admintool/src/main/resources:/home/cia/.m2/repository/com/sharis/bl/admintool-widgetset/7.6.7/admintool-widgetset-7.6.7.jar:/home/cia/.m2/repository/com/vaadin/vaadin-server/7.6.7/vaadin-server-7.6.7.jar:/home/cia/.m2/repository/com/vaadin/vaadin-sass-compiler/0.9.13/vaadin-sass-compiler-0.9.13.jar:/home/cia/.m2/repository/org/w3c/css/sac/1.3/sac-....................................................................1.5.10.jar com.vaadin.sass.SassCompiler /home/cia/dev/projects/trunk/trunk/admintool/src/main/webapp/VAADIN/themes/nxo-fr/styles.scss /home/cia/dev/projects/trunk/trunk/admintool/src/main/webapp/VAADIN/themes/nxo-fr/styles.css
[ERROR] ]] failed with status 2
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

A: I found the issue. The styles.scss file was missing in my older theme folders like runo etc.
So in each theme folder there must be a styles.scss for proper compilation.

A: Try to use a theme name which has no hyphens in it.
"VAADIN/themes/nxo-fr"


text:
Q: Latex verbatim:how to show the file directoy created by tree command? I want to insert a file directory diagram created by tree command using verbatim enviroment. But in the output document, only file names are kept, and the connection lines are disapeared.
\documentclass{article}
\usepackage{fancyvrb}
\begin{document}

\begin{Verbatim}
 .
 ├── app
 ├── bakery
 ├── build
 ├── CHANGELOG.md
 ├── composer.json
 ├── composer.lock
 ├── docker
 ├── sponsors
 ├── STYLE-GUIDE.md
 └── webserver-configs

 \end{Verbatim}

 \end{document}

I have tried using fancyvrb package by setting showtabs true, but the connection lines are still not printed in the document.
Is there any way?

A: The problem is that these unicode characters are not included in the default mono font. If you use an unicode-capable engine, such as xelatex, and a font which contains them, e.g. DejaVu Sans Mono, the will be visible in the document:
% !TeX TS-program = xelatex

\documentclass{article}
\usepackage{fancyvrb}

\usepackage{fontspec}
\setmonofont{DejaVu Sans Mono}

\begin{document}

\begin{Verbatim}
 .
 ├── app
 ├── bakery
 ├── build
 ├── CHANGELOG.md
 ├── composer.json
 ├── composer.lock
 ├── docker
 ├── sponsors
 ├── STYLE-GUIDE.md
 └── webserver-configs

 \end{Verbatim}

 \end{document}

If you prefer pdflatex, the pmboxdraw package can be used:
\documentclass{article}
\usepackage{fancyvrb}

\usepackage[utf8]{inputenc}
\usepackage{pmboxdraw}

\begin{document}

\begin{Verbatim}
 .
 ├── app
 ├── bakery
 ├── build
 ├── CHANGELOG.md
 ├── composer.json
 ├── composer.lock
 ├── docker
 ├── sponsors
 ├── STYLE-GUIDE.md
 └── webserver-configs

 \end{Verbatim}

 \end{document}


text:
Q: Searching in a time range I am currently using a formula that matches certain criteria from one sheet to another and returns a value. The problem I am having is that it will only return a true value if the time is exactly the same on both sheets. I need it to look a the time on the first sheet and check if it matches the time on the second sheet plus or minus say 10 minutes. Here's the code I am using.  FYI (Sheet1, 1=Date, 2=Time, 3=RefNo)(Sheet2, 1=Date, 2=Time, 3=RefNo, 4=RefNo)
If UCase(Worksheets("Sheet1").Cells(i, 1).Value) = UCase(Worksheets("Sheet2").Cells(j, 1).Value) Then
If UCase(Worksheets("Sheet1").Cells(i, 2).Value) = UCase(Worksheets("Sheet2").Cells(j, 2).Value) Then
If UCase(Worksheets("Sheet1").Cells(i, 3).Value) = UCase(Worksheets("Sheet2").Cells(j, 4).Value) Or UCase(Worksheets("Sheet1").Cells(i, 4).Value) = UCase(Worksheets("Sheet2").Cells(j, 4).Value) Then
Worksheets("Workings").Cells(i, 1).Value = UCase(Worksheets("Sheet2").Cells(j, 12).Value)
Worksheets("Workings").Cells(i, 2).Value = UCase(Worksheets("Sheet2").Cells(j, 9).Value)

I cannot find a reference to this problem on any forum and am completely stumped, I am sure there is a simple solution.

A: Assuming VBA, that the cells are in a date/time format & that i is their address;
Abs(DateDiff("N", Worksheets("Workings").Cells(i, 1).Value, Worksheets("Sheet2").Cells(i, 1).Value))

Will return a positive integer representing the number of minutes difference between the 2 times.
I created a blank workbook and;
Worksheets("Sheet1").Cells(1, 2).Value = "15:00:00"
Worksheets("Sheet1").Cells(2, 2).Value = "15:00:00"
Worksheets("Sheet1").Cells(3, 2).Value = "15:00:00"

Worksheets("Sheet2").Cells(1, 2).Value = "15:05:00"
Worksheets("Sheet2").Cells(2, 2).Value = "15:59:00"
Worksheets("Sheet2").Cells(3, 2).Value = "15:00:00"

For i = 1 To 3
    If (Abs(DateDiff("N", Worksheets("Sheet1").Cells(i, 2).Value, Worksheets("Sheet2").Cells(i, 2).Value)) < 10) Then
        Worksheets("Sheet2").Cells(i, 3) = "in range"
    End If
Next

Works for me, I see on sheet2;
15:05   in range
15:59
15:00   in range


text:
Q: cancel touch event during touchesMoved I need to cancel a touch event during touchesMoved so that underlying uiviews can receive the events. See comments below:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

    for (UITouch *touch in touches)
    {

        if (touch.view == self.touchOverlay) {
            CGPoint touchLocation = [touch locationInView:touch.view];

            //perform checks on touch location and trip sensor if circumstances are met

            if (self.touchSensorTripped) {
                self.touchOverlay.userInteractionEnabled = NO;
                //NEED TO CANCEL THE TOUCH HERE SO THAT VIEWS UNDERNEATH CAN RECEIVE THE TOUCH EVENTS
            }

        }

    }
}

Currently the underlying views do not receive touch events until the touch ENDS, which is too late. I need them to start receiving the touchesMoved events immediately once the overlay view is disabled, while the touches are still moving. What can I insert where the comment is above to do this?

A: I just did some simple messing around with a test app, and found that calling
[[self superview]touchesMoved:touches withEvent:event]; seemed to work for a straightforward view hierarchy, if that's what you have.  The superview's touchesMoved was definitely called before the view touchesEnded. Calling the superviews touchesMoved prematurely in this way didn't cause it to be called again afterwards


text:
Q: Symfony service FileUploader not autowiring I've followed the Symfony 5.2 tutorial to add a FileUploader as a service (https://symfony.com/doc/current/controller/upload_file.html).
So this is my service.yaml
parameters:
  targetDirectory: '%kernel.project_dir%/public/uploads/'
  previews_video: '%kernel.project_dir%/public/uploads/previews'
  brochures_directory: '%kernel.project_dir%/public/uploads/brochures'
services:
  App\Service\FileUploader:
      arguments:
          $targetDirectory: '%previews_video%'

And this is my FileUploader.php
<?php

namespace App\Service;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\String\Slugger\SluggerInterface;

class FileUploader
{
    private $targetDirectory;
    private $slugger;

    public function __construct($targetDirectory, SluggerInterface $slugger)
    {
        $this->targetDirectory = $targetDirectory;
        $this->slugger = $slugger;
    }

    public function upload(UploadedFile $file)
    {
        $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
        $safeFilename = $this->slugger->slug($originalFilename);
        $fileName = $safeFilename.'-'.uniqid().'.'.$file->guessExtension();

        try {
            $file->move($this->getTargetDirectory(), $fileName);
        } catch (FileException $e) {
            // ... handle exception if something happens during file upload
        }

        return $fileName;
    }

    public function getTargetDirectory()
    {
        return $this->targetDirectory;
    }
}

But I'm having this common error :

Cannot resolve argument $fileUploader of "App\Controller\VideoController::edit()": Cannot autowire service "App\Service\FileUploader": argument "$targetDirectory" of method "__construct()" has no type-hint, you should configure its value explicitly.

Called by this controller :
 /**
 * @Route("/{id}/edit", name="video_edit", methods={"GET","POST"})
 * @param Request $request
 * @param Video $video
 * @param FileUploader $fileUploader
 * @return Response
 */
public function edit(Request $request, Video $video, FileUploader $fileUploader): Response
{...}

How do I fix this ? I trying by remove the string type, adding the string type, removing the $ from the targetDirectory parameters in services.yaml... Struggling with that for hours now...

A: Take a look at my working services.yaml. I've changed the namespace

App\Service

to

App\Services

And I also added the service declaration at the end of the file.
Looks like the order of the lines in services matter. First, I've added the declaration at the top of the services part, but the autowiring is declared after, guess the error was here...
# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    previews_directory: '%kernel.project_dir%/public/uploads/previews'
services:
  #i've added my service here at first...
    app.menu_builder:
        class: App\Menu\MenuBuilder
        arguments: ["@knp_menu.factory"]
        tags:
            - { name: knp_menu.menu_builder, method: createMainMenu, alias: main }
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'
            - '../src/Tests/'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller/'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones

    App\Services\FileUploader:
        arguments:
            $targetDirectory: '%previews_directory%'

A: You should have autowiring configuration added to your services file:
parameters:
  targetDirectory: '%kernel.project_dir%/public/uploads/'
  previews_video: '%kernel.project_dir%/public/uploads/previews'
  brochures_directory: '%kernel.project_dir%/public/uploads/brochures'
services:
  # To add:
  _defaults:
      autowire: true
      autoconfigure: true
  # You service
  App\Service\FileUploader:
      arguments:
          $targetDirectory: '%previews_video%'

A: Add a type-hint string for $targetDirectory in the contructor
public function __construct(string $targetDirectory, SluggerInterface $slugger)
{
    $this->targetDirectory = $targetDirectory;
    $this->slugger = $slugger;
}

A: I had the same issue.
It was related to the indentation of that specific service. I wasn't getting any indentation error but also the auto wiring wasn't working.
What i did was to add 4 spaces as indentation
    App\Service\FileUploader:
        arguments:
            $targetDirectory: '%TEAM_LOGO_DIRECTORY%'

A: Yes I got the problem too and I managed to solve it by replacing indentation by spaces in the services.yaml file, I added all of these properties at the same root and then I did that and it works for me:
services:
    App\Services\FileUploader: #(added 4 spaces, NOT 1 tab)
        arguments: #(added 8 spaces, NOT 2 tabs)
            $targetDirectory: '%cats_directory%' #(added 12 spaces, NOT 3 tabs)

If you struggle you (and other people who got this problem) can try this solution. I don't guarantee it will work 100%.


text:
Q: How to delete multiple Items from QTreeWidget, QListWidget or QListView I have a list of QTreeWidget items indexes:
indexesToDelete=[1, 3, 5 ,7]

Now if I do:
for itemIndex in indexesToDelete:
    myTree.takeTopLevelItem(itemIndex) # deletes an item from Tree

the things get really nasty. With every for itemIndex in indexesToDelete iteration an Item deleted and Tree Item's indexes are changed even while for loop is still going... Needless to say that only the very first for loop iteration deletes a correct List Item. All other list items are removed improperly.
Question: How to delete List Items by their indexes correctly?

A: An idea is to remove by item instead of constantly changing index numbers.
First build a list of items to be removed. Then iterate the items in a Tree comparing each against the ones stored in a items-to-be-removed list . Delete if True.
QListWidget()
myListWidget=QtGui.QListWidget()

for i in range(10):
    item=QtGui.QtGui.QListWidgetItem()
    myListWidget.addItem(item)

indexToRemove=[2,4,6]

itemsToRemove=[]
for index in indexToRemove:
    item=myListWidget.item(index)
    if item: itemsToRemove.append(item)

for i in range(myListWidget.count()):
    listItem = myListWidget.item(i)
    if not listItem: continue
    if not listItem in itemsToRemove: continue
    itemRow=myListWidget.row(listItem)
    if itemRow:
        myListWidget.takeItem(itemRow)

QTreeWidget()
myTreeWidget=QtGui.QTreeWidget()

for i in range(10):
    item=QtGui.QtGui.QTreeWidgetItem()
    myTreeWidget.addTopLevelItem(item)

indexToRemove=[2,4,6]

itemsToRemove=[]
for index in indexToRemove:
    item=myTreeWidget.topLevelItem(index)
    if item: itemsToRemove.append(item)

for i in range(myTreeWidget.topLevelItemCount()):
    listItem=myTreeWidget.topLevelItem(i)
    if not listItem: continue
    if not listItem in itemsToRemove: continue
    itemIndex=myTreeWidget.indexOfTopLevelItem(listItem)
    if not itemIndex: continue
    myTreeWidget.takeTopLevelItem(itemIndex)

A: So I would like to start by pointing out that you aren't actually deleting by a QModelIndex but rather by an integer which you have associated to a specific item (or rows of items). If you actually had QModelIndexs for each item you wanted to delete, you would find that after the first deletion, all of the indexes would return False when you queried index.isValid(). This should make a lot of sense, obviously when you delete an item, all indexes become invalid (as you have found).
In short, Qt is supposed to help stop you doing exactly what you have attempted to do!
The only reliable solution is to delete based on a list of items. You can look up the item index from the item at each iteration of your deletion loop if you want (and delete by index), but you cannot store a list of indexes and expect deletion to work correctly.


text:
Q: can a mobile application developed for io6 work correctly on ios7 and ios8? Could you please indicate us if an Mobile Application developed for iOS6 can work correctly (without any adaptation) on iOS 7 and 8 or there will always be any functional and display issues and therefore it will be necessary to redevelop this Mobile Application for iOS 7 and 8.

A: Your iOS6 application might run correctly without any problem.
It might also show some visual problems (iOS6 did not cater for the new iphone6/6+ formats or even 3x retina displays), or could fail (crashes) because it's using deprecated functionalities. As suggested, the best you can do is test your application with those newer iOS versions, there's no straight answer to that question.
If your application is not already on the AppStore, but you have its source code and would like to submit it at some point in the future, it will most likely need to be reworked because the submission process will check for compliance with newer i-devices.


text:
Q: Is there any examples of how to implement full-screen advertisement for android? Is there any examples of how to implement full-screen advertisement for android using AdMob?
I have researched and found these tutorials:

*

*Getting Started with House Ads

*Google AdMob Ads Android Advanced
EDIT - added some related questions:

*

*In the tutorials it looks like you have to use Android 4.0 to get the interstitial house ads to work. Is it not possible in earlier versions?

A: Please see the AdMob Interstitial documentation for how to add interstitials to your Android app.  Please note, however, that you need to be whitelisted for interstitial ads to get interstitial ads from AdMob.  Right now you will only be able to see the test interstitial ad, or a house ad interstitial that you traffic to your app.
EDIT:
The Google AdMob SDK v4.3.1 requires that you set your android build target to android-13 (Android 3.2) or higher.  You can still get ads on devices all the way down to Android 1.5 (android-3) by setting the minSdkVersion="3" in your manifest.


text:
Q: SSMS 2012 hanging when opening multiple query windows or files I recently upgraded from 2005 to 2012 (about 10 months).  When I first started using SSMS2012 it worked great was able to open multiple windows in a particular database.  For about that last 2-3 months SSMS hangs when I try to open more than 1 query window or open a file.  It is random but happens a majority of the time.  I have been able to interrupt the hang a few times.  When I interrupt it I get the login screen and it sits there trying to log in apparently unsuccessfully.  If I cancel the login and try it again with the same entries it connects just fine and things are great, but I have to do this for every window and I cannot often break into that screen before it stops responding.
I have searched extensively and have not found an answer to this problem.  It only appears to be happening to a particular instance.  The instance does not show any signs of issues, has been rebooted and configuration checked for inconsistencies, etc.  I am at a loss.  If anyone has experienced this and has been able to resolve it I would appreciate a response.
Again this is a fresh install of 2012 standard with 2005 imported databases.  All indications show that it is working fine.  compatibility level for a majority of the databases are still 90, until I can clear them for 11 with the software they house.  I have a test environment with the restored versions on a different server and no issues result from that instance - I can open up multiples without incident.  My belief is it is something with that particular instance, but I am not sure where else to look.
Thank you in advance.


text:
Q: Spring returned page is empty I requested a page which was supposed to be populated with objects for a user, but the returned page was empty.
The controller for the request
    @RequestMapping(value = "/main/user/testing", method = RequestMethod.GET)
    public String getRecords(@RequestParam("userId") Integer userId, ModelMap

        model) {
     if(userId !=null)

     {
           UserEntity user = userService.getUserByID(userId);

         model.addAttribute("setter", user);
     }

  return "/main/user/testing";
 }

The model for the parent and the associated children that is to be retrieved
UserEntity
   public class UserEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "user_id")
    private Integer userId;

    @Column(name = "name")
    private String name;

        @ManyToOne(cascade={CascadeType.ALL})
        @JoinColumn(name="checker_id")
        private UserEntity checker;

        @OneToMany(mappedBy="checker", orphanRemoval=true, cascade = CascadeType.ALL)
        private Set<UserEntity> setters = new HashSet<UserEntity>();

        @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="setter")
        private Set<Module> sModule = new HashSet<Module>();

        @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="checker")
        private Set<Module> cModule = new HashSet<Module>();

Module
    public class Module implements Serializable{

  @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      @Column(name = "module_id")
      private Integer moduleId;

  @Column(name = "module_code")
      private String moduleCode;

  @Column(name = "module_name")
      private String moduleName;

So when at the controller I use the user id as the parameter I want it to return with the modules associated with the user.
The page itself is returned but all it has is the table headers ad no values from the database.
Requested page

                    User Id
                    Name
            Module Code
            Module Name

       <c:forEach items="${setter}" var="obj" >
        <c:forEach items="${obj.sModule}" var="module" >

                <c:out value="${obj.userId}" escapeXml="true" />
                <c:out value="${obj.name}" escapeXml="true" />

                <c:out value="${module.moduleCode}" escapeXml="true" />
                <c:out value="${module.moduleName}" escapeXml="true" />

            </c:forEach>
        </c:forEach>

Is there a reason why this is happening?

A: Does the c:foreach work on a single object? You are returning exactly one user. Either get rid of the loop in your template or wrap the user entity in a list and put that list into the setter variable.


text:
Q: Pass in a parameter to model in codeingiter Currently in my model I am hardcoding in 'XYZ'. This works cause I get the correct number of XYZ buildings but there 50 other buildings that also need. It doesn't make sense for me to hardcode all buildings.
How do I pass this the building as a parameter.
My view file looks like this:

Buildings

Total work requests

      <?php foreach ($buildings as $bldg){?>

            <?php echo $bldg['Building_Code'];?>

                60% Complete

            <?php echo $countBuildings; ?>

      <?php } ?>

My controller looks like this:

$data["countBuildings"]= $this->Buildings_model->getBldgCount('XYZ');
$this->load->view('main/header');
$this->load->view('main/body', $data);
$this->load->view('main/footer');

My model looks like this:

public function getBldgCount($queryBuilding){
  $this->db->select('*');
  $this->db->where('Building_Code', $queryBuilding);
  $this->db->from('work_requests');
  $count = $this->db->count_all_results();
  return $count;
}

A: Hope this will help you :
the best approach is to use custom helper because you need to count all 50 type of buildings
Create helper with name custom_helper.php and place it helpers folder and autoload with autoload.php
$autoload['helper'] = array('custom');

custom_helper.php should be like this :
function count_building_by_code($building_code)
{
    $ci = & get_instance();
    /* Omit this line if you autoload model in autoload.php*/
    $ci->load->model('Buildings_model');
    $count = $ci->Buildings_model->getBldgCount($building_code);
    return $count;
}

The model code :
public function getBldgCount($building_code)
    {
        if ($building_code)
        {
            $this->db->where('Building_Code',$building_code);
            return $this->db->count_all_results('work_requests');
        }
    }

The View :
<?php foreach ($buildings as $bldg){?>

            <?php echo $bldg['Building_Code'];?>

                60% Complete

            <?php echo count_building_by_code($bldg['Building_Code']); ?>

      <?php } ?>

For more : https://www.codeigniter.com/user_guide/general/helpers.html

A: You need to change the approach.
There is no need to have the building code hard coded. You even don't need to pass the building code.
You need to use group by in your query such that it returns all the building with count. Your model function will be something like below:
public function getBldgCount(){
    $this->db->select('Building_Code, COUNT(id) as total');
    $this->db->group_by('Building_Code');
    $this->db->get('work_requests');
}

A: You need to change the approach.
There is no need to have the building code hard coded. You don't even need to pass the building code.
You need to use group by in your query such that it returns all the building with count.
public function getBldgCount(){
    $this->db->select('Building_Code, COUNT(id) as total');
    $this->db->group_by('Building_Code');
    $this->db->get('work_requests');
}

A: In your controller, you have to set the array value in $data of buildings counts.
In controller replace:
$data["countBuildings"]= $this->Buildings_model->getBldgCount('XYZ');
$this->load->view('main/header');
$this->load->view('main/body', $data);
$this->load->view('main/footer');

With:
foreach($data['buildings'] as $k=>$v){
    $data["buildingcount"][$k]["count"] = $this->Buildings_model->getBldgCount($v);
}

$this->load->view('main/header');
$this->load->view('main/body', $data);
$this->load->view('main/footer');

You have to update as needed the view code to accommodate the new buildings counts data.
Updated View:

Buildings

Total work requests

      <?php foreach ($buildings as $bk=>$bldg){?>

            <?php echo $bldg['Building_Code'];?>

                60% Complete

            <?php echo $buildingcount[$bk]['count']; ?>

      <?php } ?>


text:
Q: How to stop random links from opening with react-router? I am new to React and practicing with an online website for repairing appliances. I have used react-router and created all my routes in a separate file.
I have a problem though, I can open any link from the address bar like:
http://localhost:3000/<randomword>

I only want routes to be opened that I have declared in my routes component while if I type http://localhost:3000/something, I get an empty page with my header and footer in it.
here are my codes:
Index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from "react-router-dom";
import Routes from './Routes';
import './index.css';

const App = () => {
    return(
        <BrowserRouter>
            <Routes />
        </BrowserRouter>
        )
    }

ReactDOM.render(<App/>,document.getElementById('root'));

App.js:
import React, {Component} from 'react';
import { Route, BrowserRouter } from 'react-router-dom';
import Layout from './Containers/Layout';
import LandingPage from './Containers/Pages/LandingPage';
import About from './Containers/Pages/About';
import Cities from './Containers/Pages/Cities';
import Discount from './Containers/Pages/Discount';

class Routes extends Component {
    render(){
        return (

                <Layout>
                    <BrowserRouter>
                        <Route path="/" render={props => <LandingPage {...props} />} exact component={LandingPage}/>
                        <Route path="/About" component={About}/>
                        <Route path="/Cities" component={Cities}/>
                        <Route path="/Discount" component={Discount}/>
                    </BrowserRouter>
                </Layout>

    );
}
};

export default Routes;

Layout.js:
import React, { Component } from 'react';
import Header from "./Layouts/Header";
import Footer from './Layouts/Footer';
import './Layout.css';

export default class Layout extends Component {
    constructor(){
        super();
        this.state= {

        }
    }
    render() {
        return (

                        {this.props.children}

);
        }
}

Can someone help me figure out how I should stop random random pages to be opened from addressbar?

A: Just want to start by saying I'm completely self-taught with React so I apologize if this answer is incorrect. However, in my experience with react-router I always have a Switch inside of my BrowserRouter. So your Routes class in app.js should something like this:
class Routes extends Component {
    render(){
        return (

                <Layout>
                    <BrowserRouter>
                        <Switch>
                            <Route path="/" render={props => <LandingPage {...props} />} exact component={LandingPage}/>
                            <Route path="/About" component={About}/>
                            <Route path="/Cities" component={Cities}/>
                            <Route path="/Discount" component={Discount}/>
                        </Switch>
                    </BrowserRouter>
                </Layout>

        );
    }
};

Just be sure you don't forget to update your imports to
import { Switch, Route, BrowserRouter } from 'react-router-dom';

A: import {  Redirect } from "react-router-dom"
<Route path="/not-found" component={notFound-Component} />
<Redirect to="/not-found" />

This will always redirect you to 404 component if route is not present just make a 404 component and u should add the redirect at the end after all routes are defined


text:
Q: Clamping inrush current in a lighting circuit I use a relay to switch on/off lighting circuits with lots of LEDs. The relay switches the mains supply so must run happily with 110/220/240 Vac. The relay I'm using is rated for an 800 A inrush current, which is the highest spec that I can find in its class and is sufficient to protect it from inrush damage with most LED lighting circuits, e.g. when the steady state current is less than say 10 A. So far, so good.
My problem: I would like to increase the maximum load, e.g. from 10 A to 15 A.
I think this means somehow clamping the inrush current, rather than simply using a bigger relay. I would prefer not to use a thermistor, because of the high temperatures these generate.
Is there a different (and cost-effective) solution?

A: You could use  a combo NTC and relay approach.  The NTC is in series for a short period of time, and then the relay is engaged to bypass the NTC.
TDK has an appnote on a simple RC timer based circuit.

simulate this circuit – Schematic created using CircuitLab

A: Have you measured the actual inrush of you LED power supplies?
Good ones have soft start and don't inrush a lot. Also 800A inrush for 10A of steady state load is 80x, which is unreasonable. Where did you find that spec?
Standard magnetic breaker (curve C, IIRC) trip at 5x their current, for comparison so there something suspicious in your data
The obvious solution of course would be simply to… use more than one relay. Split the load between two contacts and put the coils in parallel. For optimum result if possible stagger the turn on to reduce the inrush on the network (you don't want to pop a fuse)


text:
Q: String matching query in flutterfire firestore I am trying to get all records having a particular email value. Here email1 is user provided.
I have tried :
QuerySnapshot userList = await  users!.where('email', '>=', email1).where('email', '<=', email1).get(); \\ gives syntax error

users!.where("email", isGreaterThan: email1).get(); \\ returns all records

users!.where("email", isGreaterThan: email1).where("email", isLessThan: email1).get(); \\ returns no record

users!.where('email', arrayContainsAny: [email1]).get() \\ returns no record

Any help in this regard would be appreciated.

A: I think you're looking for isEqualTo:
users!.where("email", isEqualTo: email1).get();


text:
Q: User form is taking to long to execute I have this UserForm and  it's taking to long to look up. Is there any         way that I can reduce that time?
Here is the userform's textbox code where I put what I am looking for:
Private Sub TXTBUSCAART_Change()
     Application.ScreenUpdating = False

     Sheets("CONCAT").Select
     Range("A2").Select
     LSTART.Clear

     While ActiveCell.Value <> ""
         M = InStr(1, ActiveCell.Value, UCase(TXTBUSCAART.Text))

         If M > 0 Then
             LSTART.ColumnCount = 9
             LSTART.AddItem

             LSTART.List(LSTART.ListCount - 1, 0) = ActiveCell.Value
             ActiveCell.Offset(0, 2).Select
             LSTART.List(LSTART.ListCount - 1, 1) = ActiveCell.Value
             ActiveCell.Offset(0, -1).Select
             LSTART.List(LSTART.ListCount - 1, 2) = ActiveCell.Value
             ActiveCell.Offset(0, 2).Select
             LSTART.List(LSTART.ListCount - 1, 3) = ActiveCell.Value
             ActiveCell.Offset(0, 2).Select
             LSTART.List(LSTART.ListCount - 1, 4) = ActiveCell.Value
             ActiveCell.Offset(0, -1).Select
             LSTART.List(LSTART.ListCount - 1, 5) = ActiveCell.Value
             ActiveCell.Offset(0, 3).Select
             LSTART.List(LSTART.ListCount - 1, 6) = ActiveCell.Value
             ActiveCell.Offset(0, 1).Select
             LSTART.List(LSTART.ListCount - 1, 7) = ActiveCell.Value
             ActiveCell.Offset(0, -2).Select
             LSTART.List(LSTART.ListCount - 1, 8) = ActiveCell.Value
             ActiveCell.Offset(0, -6).Select
         End If

         ActiveCell.Offset(1, 0).Select
     Wend

     Sheets("REMITO").Select
     Range("A1").Select

     Application.ScreenUpdating = False
 End Sub

A: It should be a lot faster to put the data into an array and loop through that - something like this (I think I got the columns right):
Private Sub TXTBUSCAART_Change()
    Dim rowCount As Long, itemCount As Long, counter As Long, n As Long
    Dim dataSheet As Worksheet
    Dim dataIn, dataOut()

    LSTART.Clear
    LSTART.ColumnCount = 9

    Set dataSheet = Sheets("CONCAT")
    With dataSheet

        rowCount = .Cells(.Rows.Count, "A").End(xlUp).Row
        itemCount = Application.WorksheetFunction.CountIf(.Range("A2:A" & rowCount), "*" & TXTBUSCAART.Text & "*")

        If itemCount > 0 Then
            ReDim dataOut(1 To itemCount, 1 To 9)
            dataIn = .Range("A2:I" & rowCount).Value
            counter = 1

            For n = 1 To UBound(dataIn)
                M = InStr(1, dataIn(1, 1), UCase(TXTBUSCAART.Text))
                If M > 0 Then
                    dataOut(counter, 1) = dataIn(n, 1)
                    dataOut(counter, 2) = dataIn(n, 3)
                    dataOut(counter, 3) = dataIn(n, 2)
                    dataOut(counter, 4) = dataIn(n, 4)
                    dataOut(counter, 5) = dataIn(n, 6)
                    dataOut(counter, 6) = dataIn(n, 5)
                    dataOut(counter, 7) = dataIn(n, 8)
                    dataOut(counter, 8) = dataIn(n, 9)
                    dataOut(counter, 9) = dataIn(n, 7)
                    counter = counter + 1
                End If
            Next

        LSTART.List = dataOut

        End If
    End With

End Sub

A: You don't need to select each cell before setting its value.  You can do it simply by referencing the cell object itself.  Using the Cells shortcut function, if you don't ask for a specific property, the cell's value is returned by default.
So for the loop portion, you might gain some speed doing this (especially if that when loop goes around many times):
 LSTART.List(LSTART.ListCount - 1, 0) = Cells(1, 2)
 LSTART.List(LSTART.ListCount - 1, 1) = Cells(1, 4)
 LSTART.List(LSTART.ListCount - 1, 2) = Cells(1, 3)
 LSTART.List(LSTART.ListCount - 1, 3) = Cells(1, 5)
 LSTART.List(LSTART.ListCount - 1, 4) = Cells(1, 7)
 LSTART.List(LSTART.ListCount - 1, 5) = Cells(1, 6)
 LSTART.List(LSTART.ListCount - 1, 6) = Cells(1, 9)
 LSTART.List(LSTART.ListCount - 1, 7) = Cells(1, 10)
 LSTART.List(LSTART.ListCount - 1, 8) = Cells(1, 8)

Double check my math - I just added and subtracted your offsets to generate this example code.


text:
Q: RxJava Single.error inside a map or flatMap I haave this
private Single<Integer>(){

    Single.just(1,2,3).map{
      it
    }.onErrorResumeNext {
     Single.error(UserException("400", errorMessage))
    }
}

Now, I want to insert an extra object in my exception.
Single.just(1,2,3).map{
//anything
}.onErrorResumeNext {
  moreInformation.map{
     Single.error(UserException("400", errorMessage + it.message))
  }
}

I have an error, that I need return an Single<Integer> and not an Single<UserExepction>

A: I think you want onErrorReturn
Flowable.just(1, 2, 3).map { x -> x }.onErrorReturn { 1 }


text:
Q: porting multi-module Android Intellij Project to Android Studio I have an android project in Intellij IDEA using the classical format that I want to port to Android Studio using gradle.
My project consists of multiple modules with dependencies between them:
/root
  module1/
  module2/
  appModule/

module1 and module2 are library modules. appModule is the actual android app and is currently using both module1 and module2 as dependencies.
How do I achieve this with gradle?
I currently have a gradle file for each module but im having trouble int the appModule/build.gradle making it refer to the other modules. Im guessing I need a build.gradle in the root directory?

A: The root build.gradle file is optional.
what you need is having a settings.gradle file in your root project and specify all module and then in your appModule' s build.gradle file, add:
dependencies {
  compile project(':module1')
  // others modules goes here...
}


text:
Q: Gradle rename maven dependency package (HttpComponents, Android) Using and Choosing way to make HTTP(S) requests on Android is a long-time pain.
Although Google wants us to use HttpURLConnection, there are those who prefer to use HttpClient instead.
There is this library, https://code.google.com/p/httpclientandroidlib/ with packaging script.
I'd rather use something more integrated with Android build environment.
Is there possibility to use Gradle to repackage Maven dependency (whole tree, including httpclient, httpcomponents, httpmime, ...) in the same way httpclientandroidlib does?
The best scenario would be to have gradle download,repackage and link those libraries in the same transparent way.
gradle:
dependencies {
    compile 'org.apache.httpcomponents:httpclient:4.2.3'
    compile 'org.apache.httpcomponents:httpmime:4.2.3'
}

A: Simple repackaging from org.apache.http to some other namespace has a drawback of rendering HttpClient incompatible with 3rd party libraries compiled against the stock APIs. There are plans to create a re-spin of HttpClient 4.3 specifically for Android fully compatible with 4.0 BETA1 APIs and with most of 4.3 features back-ported to it. It is a shame really that the way of mitigating the damage of Android's fork of HttpClient appears to be by creating yet another fork. Thank you Google.
NEW INFO
Apache HttpComponents created spin of HttpClient library for Android only, which is available here: https://hc.apache.org/httpcomponents-client-4.3.x/android-port.html


text:
Q: two or more data types in declaration specifiers error in header file I am an OS developer and I would like to compile the following (it's in the file cpu.h) with my gcc crosscompiler(ver= 4.5.4)
#ifndef X86_64_CPU_H
#define X86_64_CPU_H
#include<stdint.h>
typedef struct
{
    // manually secured registers
    uint64_t   rax;
    uint64_t   rbx;
    uint64_t   rcx;
    uint64_t   rdx;
    uint64_t   rsi;
    uint64_t   rdi;
    uint64_t   rbp;
    uint64_t   r8;
    uint64_t   r9;
    uint64_t   r10;
    uint64_t   r11;
    uint64_t   r12;
    uint64_t   r13;
    uint64_t   r14;
    uint64_t   r15;

    uint64_t   intr;
    uint64_t   error;

    // secured by cpu
    uint64_t   rip;
    uint64_t   cs;
    uint64_t   rflags;
    uint64_t   rsp;
    uint64_t   ss;
} cpu_state;
...
#endif

but unfortunally it says:

HAL/x86_64/cpu.h:4:1: error: two or more data types in declaration specifiers

What am I doing wrong?

A: Usually, that error is when a missing semicolon after the struct declaration. I don't see one here, however it is possible the next struct is missing its semi colon.
typdef struct{

...

} next_struct <- missing ;


text:
Q: Mongodb Primary shard cluster down just wanted to understand a scenario where if primary shard cluster down.
so i have a setup of Mongo database where i have 4 shards running in replicaset.
shard-1 == Server 1 (Primary), shard-1 Server 2 (Secondary), shard-1 - Server 3 (Secondary)
shard-2 == Server 4 (Primary), shard-2 - Server 5(Secondary), shard-2 - Server 6(Secondary)
shard-3 == Server 7 (Primary), shard-3 - Server 8(Secondary), shard-3 - Server 9(Secondary)

i have single database and single collection, so assuming that is distributed across all 3 shards as chunks and balancer is doing it's job right?
so in such case if shard-1(cluster) goes down, will traffic movement will be normal or will be hampered.

A: I guess you mix sharding and replication.
What do you mean by "if shard-1(cluster) goes down"? This means you lose 3 servers at once! Is this a probable situation you like investigate? Then I would say, you did a poor design of your cluster.
Sharding needs to be enabled on database level and on collection level. Based on the information you provided, no answer can be given.

A: well i was just making a scenario where complete cluster might go down, let's say, i have a cluster in single DC and that DC is down, so i might be in a situation where complete cluster is unavailable, other 2 cluster's are in different DC and so they are up and running well.
ok, let's try another way, If the primary replica set member of a primary shard goes down, elections will be held, the new primary will be announced and everything is back to normal right?.
but only in case if cluster have another available nodes, what if the complete cluster goes down?.
what is the use case of other 2 sharded cluster?.
or do i have wrong understanding of sharding?.
also, yes i have enabled sharding on my DB and collection both.

A: ok, why i was coming this way, let me tell you my actual problem here, i have 4 shards and all in replicaset.
when i check sh.status(), i saw below output
autosplit:
Currently enabled: yes
balancer:
Currently enabled:  yes
Currently running:  yes
Failed balancer rounds in last 5 attempts:  0
Migration Results for the last 24 hours:
7641 : Failed with error 'aborted', from MCA2 to MCA4
databases:
{  "_id" : "MCA",  "primary" : "MCA2",  "partitioned" : true,  "version" : {  "uuid" : UUID("xxxxxxxxxxxx"),  "lastMod" : 1 } }
xxxxxxx
shard key: { "xxxxx" : "hashed" }
unique: false
balancing: true
chunks:
MCA     1658
MCA2    1692
MCA3    1675
MCA4    1670
so my simple question is if this Primary MCA2 shard goes down, what will happen, will collection(xxxxxx) is inaccessible by application or what?
also, as per terminology, i have 3 nodes cluster so anyone can go down and other becomes primary for traffic serve, so as long as any of the node is alive in my primary shard is alive and can server traffic to application right?.
if yes then let's say complete replicaset is down of primary shard MCA2, what now?
if no, then what will happen.
changed the actual value of collection and shard key for security reason to (xxxxxxx)