text:
Q: Can not set correct resolution for external monitor I am using ubuntu 15.04 on my Asus X550L Laptop. Following is my lspci
$ lspci
00:00.0 Host bridge: Intel Corporation Haswell-ULT DRAM Controller (rev 09)
00:02.0 VGA compatible controller: Intel Corporation Haswell-ULT Integrated Graphics Controller (rev 09)
00:03.0 Audio device: Intel Corporation Haswell-ULT HD Audio Controller (rev 09)
00:04.0 Signal processing controller: Intel Corporation Device 0a03 (rev 09)
00:14.0 USB controller: Intel Corporation 8 Series USB xHCI HC (rev 04)
00:16.0 Communication controller: Intel Corporation 8 Series HECI #0 (rev 04)
00:1b.0 Audio device: Intel Corporation 8 Series HD Audio Controller (rev 04)
00:1c.0 PCI bridge: Intel Corporation 8 Series PCI Express Root Port 1 (rev e4)
00:1c.2 PCI bridge: Intel Corporation 8 Series PCI Express Root Port 3 (rev e4)
00:1c.3 PCI bridge: Intel Corporation 8 Series PCI Express Root Port 4 (rev e4)
00:1c.4 PCI bridge: Intel Corporation 8 Series PCI Express Root Port 5 (rev e4)
00:1d.0 USB controller: Intel Corporation 8 Series USB EHCI #1 (rev 04)
00:1f.0 ISA bridge: Intel Corporation 8 Series LPC Controller (rev 04)
00:1f.2 SATA controller: Intel Corporation 8 Series SATA Controller 1 [AHCI mode] (rev 04)
00:1f.3 SMBus: Intel Corporation 8 Series SMBus Controller (rev 04)
00:1f.6 Signal processing controller: Intel Corporation 8 Series Thermal (rev 04)
02:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. Device 5287 (rev 01)
02:00.1 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 12)
03:00.0 Network controller: Qualcomm Atheros QCA9565 / AR9565 Wireless Network Adapter (rev 01)
04:00.0 3D controller: NVIDIA Corporation GF117M [GeForce 610M/710M/820M / GT 620M/625M/630M/720M] (rev a1)

I have two monitors.

*

*Dell 24 inch monitor, with native resolution of 1920X1080, which I can connect to my laptop without any problem and works out of the box.

*Acer X193HQ, which has native resolution of 1366X768, and causing me the problem.

I tried connecting this Acer monitor in Windows 7 without any problem and works at the native resolution 1366X768.
But when I try to connect it in ubuntu I only get options for 2 resolution
1. 1024X768
2. 800X600
I am not able to set the Acer monitor to native resolution but my Dell monitor works fine.
Following is my xrandr
$ xrandr
Screen 0: minimum 8 x 8, current 2390 x 768, maximum 32767 x 32767
eDP1 connected primary 1366x768+0+0 (normal left inverted right x axis y axis) 344mm x 193mm
   1366x768       60.0*+
   1360x768       59.8     60.0
   1024x768       60.0
   800x600        60.3     56.2
   640x480        59.9
DP1 connected 1024x768+1366+0 (normal left inverted right x axis y axis) 0mm x 0mm
   1024x768       60.0*
   800x600        60.3     56.2
HDMI1 disconnected (normal left inverted right x axis y axis)
VIRTUAL1 disconnected (normal left inverted right x axis y axis)

I am using Nouveau display driver. I tried changing it to NVIDIA binary dirver version 340.76, but then I get the black screen on login.
I also tried adding other resolutions for DP1 using following commands
xrandr --newmode "1366x768_60.00"  85.86  1366 1440 1584 1800  768 769 772 795  -HSync +Vsync
xrandr --addmode DP1 1366x768_60.00

These commands successfully added resolution option in display settings (only for a session though) but when I tried to set it, the monitor is again revert back to 1024X768.
Please suggest.

A: You need to make the xrandr commands run on startup.
Unfortunately, a lot of people have trouble making the commands permanent, so that they run on startup, but I'll show you how to do it the easy way:

*

*Create a bash script, xrandr.sh for example, and place your xrandr commands into it. It should look something like this #!/bin/bash
xrandr --newmode "1920x1200_60.00"  193.16  1920 2048 2256 2592  1200 1201 1204 1242  -HSync +Vsync
xrandr --addmode VGA1 1920x1200_60.00
xrandr --output VGA1 --mode 1920x1200_60.00

*Make the script executable with chmod +x xrandr.sh

*Search for "Startup Applications" in the dash, run it, and add the script as a startup application.
The commands will now run every time you log into your account.


text:
Q: Cocoa PDFView only displays PDF on resize How does one get a PDFView to display a PDF without having to resize the window or doing a
scroll to force a redraw.
It's as if a setNeedsDisplay needs to be done, yet that has no effect.
I've the simplest app I can think of to display a PDF using a PDFView.
Basically create a new app in Xcode and change the code to be:
// AppDelegate.h
#import <Cocoa/Cocoa.h>
#import <Quartz/Quartz.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@property (assign) IBOutlet PDFView *pdfView;
@end

and
// AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window = _window;
@synthesize pdfView = _pdfView;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSURL *pdfURL = [[NSBundle mainBundle] URLForResource:@"TestPage" withExtension:@"pdf"];
    PDFDocument *document = [[PDFDocument alloc] initWithURL: pdfURL];
    self.pdfView.document = document;
}
@end

I've noticed the same behaviour in the Apple code example PDFKitLinker2 where one has to either scroll over the PDF or resize the window to get the PDF to display.
Granted I'm new to the world of Cocoa development but I've searched and found no really small examples that show how to display a PDF. What I've produced would seem to be correct yet I have doubts given that even PDFKitLinker2 doesn't seem to be correct.
I've created a Git repo of an Xcode project that demonstrates the issue for those that have time to help and/or comment.
git clone git@bitbucket.org:sotapme/pdfview_open.git

Using Xcode Version 4.3.3 (4E3002) - Latest Lion.
Thanks in advance for any help.

A Solution that works.

I found a solution whereby if I create a sub class of PDFView with an empty implementation and then add that as a custom view and wire it up my existing IBOutlet it works.
Makes no sense at all to me :(
//DPPDFView.h
#import <Quartz/Quartz.h>
@interface DPPDFView : PDFView
@end

and
//DPPDFView.m
#import "DPPDFView.h"
@implementation DPPDFView
@end

Apple's docs do say:

PDFView may be the only class you need to deal with for adding PDF functionality to your application. It lets you display PDF data and allows users to select content, navigate through a document, set zoom level, and copy textual content to the Pasteboard. PDFView also keeps track of page history.
You can subclass PDFView to create a custom PDF viewer.

I leave this question and self answer for those that may pass by with similar questions, hoping that it will be a dim beacon of light for them; Also hoping someone with more Cocoa wisdom will point out the error in my thinking.

A: I figured this is indeed caused by the PDFview needing a setNeedsDisplay after lazyloading has finished actually loading the PDF document.
A hack, but adding the below to your - (void)windowDidLoad method at least displays the document properly without needing a resize.
dispatch_async(dispatch_get_main_queue(), ^{
    [self.myPDFView setNeedsDisplay:YES];
});

A: I found that setting the "Wants Core Animation" flag in the view results in some wonky behaviour.  If you have that set, try adding:
[pdfView setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawOnSetNeedsDisplay];
[pdfView setNeedsDisplay: YES];

to your function that loads the PDFView.

A: It's an hypothesis, but it might be because when you self.pdfView.document = document; the PDFView out of the NIB hasn't been instantiated !
Obj-C doesn't shout at you when you pass messages to the nil object.
To test this hypothesis, you can NSLog() your pdfView to see if it is nil.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invoking jMeter from the command line with 64-bit directive loses the class We were running 32-bit JDK and jMeter 2.6, and were running into heap memory issues when simulating 8000 users spread out over the course of an hour.
We upgraded to 64-bit Java, and jMeter 2.12.
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)

When we run from the command line requesting a 4Gb heap (the server has 32Gb), we receive the message that the initial heap size is too large.
set JVM_ARGS="-Xms4G -Xmx4G -XX:NewSize=512m -XX:MaxNewSize=1G" jmeter.sh

When we add the option -d64 to JVM_ARGS, we no longer receive the error about the heap size, but it no longer finds the class
set JVM_ARGS="-d64 -Xms4G -Xmx4G -XX:NewSize=512m -XX:MaxNewSize=1G" jmeter.sh

Pointing it to the directory seems to have no effect
set JVM_ARGS="-d64 -Xms4G -Xmx4G -XX:NewSize=512m -XX:MaxNewSize=1G -cp mypath" jmeter.sh

A: *

*Looking into jmeter.sh it seems you're trying to run JMeter on Linux or MacOSX. I believe you need to remove set word (or replace it with export)

*Given you have correct java executable in PATH providing -d64 option shouldn't be required. Something like:
 JAVA_HOME=/path/to/64-bit/jdk && export JAVA_HOME
 PATH=$JAVA_HOME/bin:$PATH && export PATH

*You can edit jmeter script and amend the following lines:
HEAP="-Xms512m -Xmx512m"
NEW="-XX:NewSize=128m -XX:MaxNewSize=128m"

"Telling" Jmeter to use Concurrent Mark Sweep (CMS) Garbage Collector can also improve JMeter-side performance greatly. The relevant line is:
-XX:+UseConcMarkSweepGC

See  9 Easy Solutions for a JMeter Load Test "Out of Memory" Failure article for more information on getting the most from your JMeter installation.


text:
Q: $\ X \sim U(0,1) $ find pdf of $\ Y= e^X $ $ X \sim Uni(0,1) $ and $\ Y = e^X $
Find $\ Y $ pdf
So if $\ X $ is uniform then $\ f_x(x) = 1 $ for every $\ 0 \le x \le 1 $
$$\ P\{Y \le y\} = P\{e^X \le y\} = P\{x \le \ln y \} = \ln y $$
What I don't understand is the last part of the equation, could someone explain to me why $\ P\{x \le ln y\} = \ln y $ ?

A: Because $X$ is uniform, so $P(X<a)=a$ for any $a \in [0,1]$. Substitute $a=\ln(y)$.
To see why, the CDF of the uniform distribution will be:
$P(X<a) = \int\limits_0^a f_X(x)dx = \int\limits_0^a dx = (a-0)=a$


text:
Q: Camera2 preview and captured image looks different By default I get a captured image that is rotated by -90deg and I need to rotate it back, but its height is different from the screen's height, so my image doesn't fill the screen.
In landscape mode after photo it only shows the captured image's top-right corner..
I tried all of the samples that are available, but couldn't find the solution.
private void SetUpCameraOutputs(int width, int height)
{
    _manager = (CameraManager)_context.GetSystemService(Context.CameraService);

    string[] cameraIds = _manager.GetCameraIdList();

    _cameraId = cameraIds[0];

    CameraCharacteristics chararc = _manager.GetCameraCharacteristics(cameraIds[i])
    var characteristics = _manager.GetCameraCharacteristics(_cameraId);
    var map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);

    if (_supportedJpegSizes == null && characteristics != null){
        _supportedJpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);
    }

    if (_supportedJpegSizes != null && _supportedJpegSizes.Length > 0){
        _idealPhotoSize = GetOptimalSize(_supportedJpegSizes, 1050, 1400);
    }

    _imageReader = ImageReader.NewInstance(_idealPhotoSize.Width, _idealPhotoSize.Height, ImageFormatType.Jpeg, 1);

    var readerListener = new ImageAvailableListener();

    readerListener.Photo += (sender, buffer) =>
    {
        Photo?.Invoke(this, buffer);
    };

    _flashSupported = HasFLash(characteristics);

    _imageReader.SetOnImageAvailableListener(readerListener, _backgroundHandler);

    _previewSize = GetOptimalSize(map.GetOutputSizes(Class.FromType(typeof(SurfaceTexture))), _idealPhotoSize.Height, _idealPhotoSize.Width);
}

TakePhoto method:
public void TakePhoto()
{
    if (_context == null || CameraDevice == null) return;

    if (_captureBuilder == null)
        _captureBuilder = CameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);

    _captureBuilder.AddTarget(_imageReader.Surface);

    _captureBuilder.Set(CaptureRequest.ControlAfMode, (int)ControlAFMode.ContinuousPicture);

    var windowManager = _context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
    var rotation = windowManager.DefaultDisplay.Rotation;
    _captureBuilder.Set(CaptureRequest.JpegOrientation, new Integer(Orientations.Get((int)rotation)));

    _previewSession.StopRepeating();
    _previewSession.Capture(_captureBuilder.Build(),
        new CameraCaptureStillPictureSessionCallback
        {
            OnCaptureCompletedAction = session =>
            {
                UnlockFocus();
            }
        }, null);
}

And my OnPhoto method:
private void OnPhoto(object sender, byte[] imgSource)
{
    Android.Graphics.Bitmap bitmap = BitmapFactory.DecodeByteArray(imgSource, 0, imgSource.Length);
    var windowManager = _context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
    var rotation = windowManager.DefaultDisplay.Rotation;
    if (rotation == SurfaceOrientation.Rotation0 || rotation == SurfaceOrientation.Rotation180)
    {
        bitmap = resizeAndRotate(bitmap, bitmap.Width, bitmap.Height); //rotate bitmap by 90
    }

    var SkBitmap = bitmap.ToSKBitmap();

    Application.Current.Properties["bitmap"] = SkBitmap;

    Device.BeginInvokeOnMainThread(() =>
    {
        _currentElement?.PictureTaken();
    });
}

A: while you create bitmap for portrait mode you have to change width and height of bitmap.
so width become height and height become width for portrait image.

int newWidth = oldHeight;
int newHeight = oldWidth;

Bitmap newBitmap  =Bitmap.createScaledBitmap(oldbitmap,newWidth,newHeight,true);

and you are done now the newBitmap is in its real face without stretch.
According to your code just revert the bitmap width and height by using this :
bitmap = resizeAndRotate(bitmap, bitmap.height, bitmap.width);


text:
Q: how to save image and remaining fields (string) of that table at same time in spring java I am trying to develop REST API that used to save data in POSTGRESQL with hibernate.
this REST API basically save the profile of user during registration, that has one image and 4 other String fields like name, gender, job etc.
I successfully saved the image in DB.
Now my problem is to save the image and other fields at the same time, like API hit once that save image and other string fields
code for saving the image is
 @RequestMapping(path="/a",  method = RequestMethod.POST , consumes = MediaType.MULTIPART_FORM_DATA_VALUE)//
   public void Saving(@RequestParam("file") MultipartFile file ) throws Throwable
   {
       EventSpeaker sp=new EventSpeaker();
       sp.setPic(file.getBytes());

       service.savespecker(sp);

   }

A: This is one way to achieve what you are looking for. For example; let's assume your <form> looks like as below.
<form id="form-id">
 <input type="file" name="file"/>
 <input type="text" id="gender"/>
 <input type="text" id="job"/>
</form>

On the controller;
@RestController
public class YourController {

   @RequestMapping(path="/a",  method = RequestMethod.POST , consumes = MediaType.MULTIPART_FORM_DATA_VALUE)//
   public void Saving(@RequestParam("file") MultipartFile file,
                      @ModelAttribute("gender") String gender,
                      @ModelAttribute("job") String job) throws Throwable {
         //your code
   }
}

As you could see, the image file has to be captured as @RequestParam and other text inputs as @ModelAttribute using their ids. Those model attributes are extracted from spring MVC model. If you are using JQuery you will have to add these form inputs to FormData.
A good reference on how @ModelAttribute works can be found here; https://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation


text:
Q: How to best fit image to a fixed ratio? I have a catalog of photographs most of which have aspect ratio of 4:3. There are a handful of odd ones and it is not feasible to crop those to 4:3 without losing important parts of the pictures.
I want to show all of these photographs, including the few odd-size ones, in a bounding box of the same size for every photo. The bounding box is determined by a div of class col-md-4:

    <!- the image here: -->

    <!- other stuff -->

For those images that are already at 4:3, they all show up nicely with the exact same display dimensions, even though the image (file) sizes can be different, eg one can be of 1024x768 and another is 800x600.
For an image that is "too wide", I would like it to be displayed as (where the gray bars represent the background of the bounding area):

For an image that is "too tall", I would like it to be displayed as:

In other words, each odd size image should "choose" its height or width to fit into the bounding box depending on whether it is too tall or too fat. Is this achievable by bootstrap and css?
It may be worthwhile noting that currently, the bounding div has the same width set by bootstrap for every image. The height is determined by the image's aspect ratio. When every photo is at 4:3, then the heights are also all the same. So for odd-size photos, the height has to be locked at 3/4 of the display width.

A: You can use padding-top and absolute positioning (and a bit of magic) to achieve that:

.imagewrapper {
  display: block;
  position: relative;
  background-color: blue;
  border: 1px solid red;
}

.imagewrapper:before {
  content: '';
  display: block;
  width: 100%;
  /* this is AR of 16:9 calculated 9:16*100 = 56.25 */
  padding-top: 56.25%;
}

.imagewrapper img {
  position: absolute;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

If you need another aspect ratio for the container change the padding-top value of .imagewrapper:before. It can be calculated by height / width * 100 (e.g. 9 / 16 * 100 = 56.25 for 16:6 or 4 / 3 * 100 = 133 for 3:4).
How does this work?
The before Element gets 100% width of its parent and a specified percentage-based padding-top value (e.g. 56.25%) which makes it take 56.25% of its width as height which basically makes it a fixed AR box.
The image gets positionied centered inside this box by position absolute, top, left and the transform while its size is contained by height and width auto but max-height and max-width 100%.
You can put this inside roughly anything that changes the width of the outer element and it should work.
Similar behaviour can be achieved using aspect-ratio but this solution works in MSIE and other (legacy) browsers and basically everything from this millennium too.


text:
Q: Zero-inflated Poisson regression Vuong test: Raw, AIC- or BIC-corrected results I'm analyzing count data for a set of ten species and found that for the five species with highest detection rate, the zero-inflated poisson (ZIP) regression fits the data significantly better than the regular poisson regression using glm in R. I found this using the vuong test to compare the two models, using the following code (ZP = zone/phase combination, as the data is separated into before/after phases, control/impact zones)
summary(m2 <- zeroinfl(Squirrel ~ ZP|ZP, data = bact))
summary(p2 <- glm(Squirrel ~ ZP, family = poisson, data = bact))
vuong(p2, m2)

However, for the next five species, the vuong test shows somewhat contradicting results for the fit of the ZIP regression and glm poisson regression. I'm wondering what the difference is between the raw, AIC-corrected BIC-corrected p-values is, and which I should be most concerned about (i.e. which p-value I should pay attention to). For example, the vuong results for sixth most common species is shown below:
Vuong Non-Nested Hypothesis Test-Statistic:
(test-statistic is asymptotically distributed N(0,1) under the
null that the models are indistinguishible)
-------------------------------------------------------------
              Vuong z-statistic             H_A    p-value
Raw                  -0.3378267 model2 > model1    0.36775
AIC-corrected         4.5566296 model1 > model2  2.599e-06
BIC-corrected        19.4932729 model1 > model2 < 2.22e-16

If I use the Raw results, I'd conclude that the ZIP model is not better than the glm poisson model. However, using the AIC- or BIC-corrected results, I'd conclude that the ZIP model is better than the glm poisson model.
What is the difference between these three values, and how should I decide which to use as the result? Thanks!

A: I am convinced that it is incorrect to use the Vuong test -- in any of its forms -- as a test for zero-inflation. I have had a paper "The misuse of the Vuong test for non-nested models to test for zero-inflation" published that explains why.  See http://cybermetrics.wlv.ac.uk/paperdata/misusevuong.pdf.  I have also presented the paper at major statistics conferences and no one disagreed with me.
If you are still working on this, or zero-inflation in general, get in touch if you wish.

A: Great question, with a very un-great answer: it depends.
It depends on whether or not there actually is zero-inflation in the DGP. To say it another way, the vuong test is conditional - not a diagnosis, so there will be much to justify when it comes to your results.
The best explanation I have found is in Desmarais and Harden (2013).
First, what these are:
1) I assume you know what the Vuong test statistic (raw) is, and how it is estimated.
2) The AIC and BIC statistics are corrections on the log-likelihood estimation, because the standard (raw) statistic is biased.
So which is best?
They say this (very basically):
1) If the DGP is not zero-inflated, then the BIC correction will perform the best, followed by the AIC correction, and then by the raw statistic.
2) If the DGP is zero-inflated, then each of the three tests performs similarly well.
Additional:
1) According to Desmarais and Harden, this applies just to Poisson models, and these corrections perform differently when looking at NB models.
2) Part of the reason why BIC corrections fail or succeed is because of the number of observations and (more importantly) the number of (and accuracy of) the covariates included in the inflation equation.
In other words, you'll likely need to make some assumptions about the DGP of your sample, and then choose an appropriate method based on varying the model specifications.
Simple, right?

A: This is a very interesting question I'm also searching for. Unfortunately, I couldn't find an answer yet. That's why I cannot help you with explaining the difference between Raw, AIC and BIC.
However, I can help you with your initial question, which model you should choose.
The AIC- and BIC-corrected tests are based checking model 1 > model 2 while the raw tests model 2 > model 1.
So in your case, the Poisson regression should fit perfectly.


text:
Q: prevent modal dialog from closing - VSTS I want to prevent modal dialog from closing when the 'x' button on upper left corner is clicked.
How can I achieve this?

A: No, you can't.  I can define a global variable to identify whether the modal dialog is closed by click X button or not. (Change the value in button event)


text:
Q: How to pass interface to child component in react using typescript Ok I'm new to using Typescript for react, but I've been programming long enough that this problem makes me feel very dumb...
Literally all I want to do, is define an interface that acts as the type for a property that you pass to a child component.
Like so...
interface Foo {
    bar: string;
}

const Child = ({ foo } : Foo) => {

    console.log(foo)

    return <Text>Hello World</Text>

}

const TestPage = () => {

    const fooObject : Foo = { bar: 'something' }

    return <Child foo={fooObject} />

}

But I keep seeing this error underlining the foo property I pass in inside the return statement on the TestPage component:
Type '{ foo: Foo; }' is not assignable to type 'IntrinsicAttributes & Foo'.
  Property 'foo' does not exist on type 'IntrinsicAttributes & Foo'.

And this error underlining the deconstructed foo property coming in on the child component:
Property 'foo' does not exist on type 'Foo'.

This seems so basic to me, can someone please explain?

A: const Child = ({ foo } : Foo) => {

This means that the entire props object is a Foo. It does not mean that foo is a Foo. You want:
const Child = ({ foo }: { foo: Foo }) => {

Or giving it a named type:
interface ChildProps {
  foo: Foo
}

const Child = ({ foo }: ChildProps) => {


text:
Q: SQL Server 2012 : how do I join 2 case when clauses into 1 column? I need some assistance with a query. I have a table with the following info:
enter image description here
I need to allocate a point system for every call, calls less than 1 min, calls between 1 and 5 min , calls between 5 and 10 min and lastly calls over 10 min
Currently my query looks like this:
Select distinct convert (date,AIV.PSEndTime,102) as TRXDATE
,AIV.Username
,AIV.FirstName+' '+AIV.LastName as Agent_Name
,AIV.ITypeDisplayValue
,convert (datetime,AIV.PSBeginTime,120) as PSBeginTime
,convert (datetime,AIV.PSEndTime,120) as PSEndTime
,convert(CHAR(8),DATEADD(second,AIV.Talking,0),108) as [Talking]
,CASE WHEN AIV.Talking <='60' THEN 1 ELSE 0 end as Less_than_1min
,CASE WHEN AIV.Talking between '61' and '300' THEN 1 ELSE 0 end as Between_1_and_5_min
,CASE WHEN AIV.Talking between '301' and '600' THEN 1 ELSE 0 end as Between_5_and_10_min
,CASE WHEN AIV.Talking >='601' THEN 1 ELSE 0 END as More_than_10min

 From AgentInteractionsView as AIV WITH (NOLOCK)

 WHere UserName in ('TomE','MicDe','JulCa')
and AIV.PSBeginTime > '2017-08-01'
and AIV.PSEndTime < '2017-09-01'
group by
convert (date,AIV.PSEndTime,102)
    ,AIV.Username
,AIV.FirstName+' '+AIV.LastName
,AIV.ITypeDisplayValue,AIV.DIDisplayValue
,convert (datetime,(DATEADD(hour,2,AIV.PSBeginTime)),120)
,convert (datetime,(DATEADD(hour,2,AIV.PSEndTime)),120)
,convert(CHAR(8),DATEADD(second,AIV.Talking,0),108)
,AIV.Talking

And this actually worked however I noticed that when the Column "talking" was Null it would not give me a result so I added a new query:
,CASE WHEN AIV.Talking <='60' THEN 1 ELSE 0 end as Less_than_1min
,CASE WHEN AIV.Talking = null THEN 1 ELSE 0 end as Less_than_1min

Hoping that these would result in a single column, but of course it gave me 2 columns with the same heading.
I want to join these two queries into 1 column, for example
,CASE WHEN AIV.Talking = null THEN 1
ELSE (CASE WHEN AIV.Talking <='60' THEN 1 ELSE 0) end
as Less_than_1min

am I missing something ( obviously) or am I expecting too much from SQL :)

A: As I mentioned in my comment, you can use ISNULL or COALESCE to handle a NULL value, example code:
DECLARE @time   TIME;
SET     @time = NULL;

SELECT CASE WHEN COALESCE(@time,'00:00:01') <= '00:01:00' THEN 1 ELSE 0 END AS Test_Time;

The above code returns a 1, as does:
DECLARE @time   TIME;
SET     @time = '00:00:01';

SELECT CASE WHEN COALESCE(@time,'00:00:01') <= '00:01:00' THEN 1 ELSE 0 END AS Test_Time;

And the below returns a 0:
DECLARE @time   TIME;
SET     @time = '00:02:01';

SELECT CASE WHEN COALESCE(@time,'00:00:01') <= '00:01:00' THEN 1 ELSE 0 END AS Test_Time;

As does:
DECLARE @time   TIME;
SET     @time = NULL;

SELECT CASE WHEN @time <= '00:01:00' THEN 1 ELSE 0 END AS Test_Time;

As the value is NULL, it cannot evaluate, so returns false.
So when using COALESCE, I just make sure that what I set the value to be if it is NULL fits in with the CASE expression logic, to return what I require.

A: Thanks for the assistance I was able to figure out what I was doing wrong.
As the Time is and Integer Showing the number of Seconds I came to this solution :)
Select CASE WHEN AIV.Talking <='60' THEN 1 ELSE 0 end as Less_than_1min
,CASE WHEN AIV.Talking between '61' and '300' THEN 1 ELSE 0 end as Between_1_and_5_min ,
CASE WHEN AIV.Talking between '301' and '600' THEN 1 ELSE 0 end as Between_5_and_10_min
,CASE WHEN AIV.Talking >='601' THEN 1 ELSE 0 END as More_than_10min

I really hope that this helps someone else in future :)


text:
Q: Find Non Duplicate Values in Two Tables I want to create a procedure that checks the data in 'Table1' against the data in 'Table2'. I have used this query to perform the procedure.
$sq_query = 'SELECT * FROM Table1 WHERE NOT EXISTS (SELECT * FROM Table2 WHERE Table1.name = Table2.name)';
$result = mysqli_query($conn, $sq_query);
if (!$result) {
    die ('SQL Error: ' . mysqli_error($conn));
}

BTW, I want to find out any name which isn't in 'Table2' but is in 'Table1'. I have been unsuccessful in locating missing files so far.

A: You can try using left join
SELECT * FROM table1 left join
Table2 on Table1.name = Table2.name
where Table2.name is null


text:
Q: HDD Partitions Management My Acer E5 511 has HDD with five basic partitions as will be seen from enclosed image.  After upgrading to Windows 10, the recovery partition of the size of more than 16 GB is lying empty.  It is not visible  under "My PC" and presumably is hidden.  My question is can I use it for storing data and if yes how?
[1

A: You may want to check that the recovery partition is really empty first (or at least, that it has no recovery image that you may want to preserve, which should at least occupy around 3GB of the partition).
To do that, you can assign a drive letter to the partition with diskpart:

Make sure you pick the correct recovery partition (since you have two) when enter select volume N.
Once you've confirmed that, you can remove the drive letter with remove all and delete the partition with delete volume. Then you may either create a new partition with the space released or extend your My Documents (D:) to the end of the disk with Disk Management. Just right click on either the Unallocated space or My Documents (D:) and you'll see your available options.


text:
Q: Extending CookieAuthenticationProvider OnValidateIdentity im trying to logout my users when they are dasabled or banned. my approarch was to extend CookieAuthenticationOptins in Startup.Auth.vb. According to many examples i found my Privider looks like this
app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
        .AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        .LoginPath = New PathString("/Account/Login"),
        .Provider = New CookieAuthenticationProvider() With { _
        .OnValidateIdentity = Function(ctx)
                                  Dim ret = Task.Run(Function()
                                                         Dim userManager As UserManager(Of ApplicationUser) = New UserManager(Of ApplicationUser)(New UserStore(Of ApplicationUser)(New DatabaseContext()))
                                                         Dim currentUser = userManager.FindById(ctx.Identity.GetUserId())
                                                         If Not IsNothing(currentUser) Then
                                                             If currentUser.isBanned Or currentUser.isDeleted Then
                                                                 ctx.RejectIdentity()
                                                             End If
                                                         End If
                                                         Return Task.FromResult(0)
                                                     End Function)
                                  Return ret
                              End Function
        }})

unfortunately this results in an endless loading of the page without an error.
EDIT:
i added Return Task.FromResult(0), but my user is still logged in


text:
Q: Reading lines in text file I'm trying to make a mini maze game. I have a text file which includes # for walls and whitespaces for grass. I'm having an issue reading the file and the lines atm. I tried using different methods but im not really familiar with reading files and how to read lines.
public class Map {

   private Scanner m;
   private Image wall,grass;
   private int lines;
   private char Map[][];

public Map(){

    ImageIcon img = new ImageIcon("/Users/parischrysanthou/Downloads/handpainted_wall2.jpg");
    wall = img.getImage();

    img = new ImageIcon(("/Users/parischrysanthou/Downloads/grass20.png"));
    grass = img.getImage();

    openFile();
    readFile();
    closeFile();
}

public int getLines() { return lines; }

public Image getGrass(){
    return grass;
}

public Image getWall() {
    return wall;
}

public char getMap(int x, int y){
    char index = Map[x][y];
    return index;
}

public void openFile(){
    try {
        File f = new File("/Users/parischrysanthou/Downloads/maze21-2.txt");
        Scanner m = new Scanner(f);
        while (m.hasNextLine()) {
            m.nextLine();
            lines++;
        }
        Map = new char [lines][lines];

    }
    catch(Exception e){
        System.out.println("Error loading file");
    }
}
public void readFile() {
    m = new Scanner("/Users/parischrysanthou/Downloads/maze21-2.txt");
    while (m.hasNextLine()) {
        for (int i = 0; i < lines; i++) {
            String s = m.nextLine();
            for (int j = 0; j < lines; j++) {
                Map[i][j] = s.charAt(j);

            }
        }
    }
}
public void closeFile(){
    m.close();
    }
}

Apparently my file is read as a string instead of reading the contents.I tried using BufferedReader but im unable to use hasNextLine. Any help is appreciated.
Edit: Sample of text file http://unload.io/rJ3OYFcpx.clean


text:
Q: How to change background color of specific md-tab based on label in angular 1 How to change the background color of specific md-tab based on the label in angular 1.
I have tried .md-tab:first-child {background: green; } this works based on id ,I have to give background color of tab based on the label and it's Id is not constant.

UPDATE

code
<md-tab  id="tab1" label="Followup" ui-sref="app.ccc-patientDetails.followup">

        </md-tab>
        <md-tab id="tab2" label="Symptoms" ui-sref="app.ccc-patientDetails.symptoms">

        </md-tab>
        <md-tab id="tab3"  label="Survey" ui-sref="app.ccc-patientDetails.survey" ng-if="ctrl.model.showSurvey">

        </md-tab>

css
.md-tab:first-child {background: green; }


text:
Q: Extend PackageManager Implementing SharedPreferences I Need Access to PackageManager and SharedPreferences from a plane Java Class (No Activity).
I tried extend the Class PackageManager and implement the Interface SharedPreferences like following:
public abstract class TestClass extends PackageManager implements SharedPreferences {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Do code here

}

Isn't now my class not something like sharedPreferences?
Now I don't Need to create a new Object of the Class SharedPreferences? But wait. I'm implementing an Interface and not a class? Can I really create a Instance of an Interface? I don't think so. I think the whole Interface-Story are a real big interrogation mark for me.
How can I get Access to SharedPreferences in my plain class?
public abstract class TestClass extends PackageManager implements SharedPreferences {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    this.getSharedPreferences(...); // Doesn't work
}

What i'm doing wrong, how does it really work? It would be really nice if someone can explain my issue in simple words. Thanks in advance :)
Update
I don't have Access to an activity-context! Sorry, forgot to say that. The plane Java class is called from my appWidget Long time before one of my activities are getting created.

A: If you want SharedPreferences in a non-activity class, you can use Context for that.
Like:
public class MyClass{
    public MyClass(Context context){
        SharedPreferences sPrefs = context.getSharedPreferences("MyPrefs", null);
    }
}

You don't need to extend PackageManager, implement SharedPreferences etc.
You can also access PackageManager using Context:
context.getPackageManager();

When you create object of this class, yo would need to pass context like:
MyClass myClass = new MyClass(this);

Hope this helps.


text:
Q: ORA-00906: missing left parenthesis (FK) alter table booking
add constraint fk_customer_id
foreign key customer_id
references customer (customer_id);

what is the problem, can somebody help?

A: Try parens around the field name
alter table booking
add constraint fk_customer_id
foreign key (customer_id)
references customer (customer_id);

A: You need brackets around the source field name, and around the entire constraint as part of the alter table add (..your addition here...) syntax
alter table booking add
(
   constraint fk_customer_id
   foreign key (customer_id )
   references customer (customer_id)
);

Revise that - the outer brackets are only required if adding more than one item, so give the correct answer to andraemc but be aware of the possible need for outer brackets. I always stick 'em in to keep the style consistent, and so I don't ever forget to!


text:
Q: Using fetch for a POST request to add data to JSON server database Trying to add something new to my fake database using JSON server.
The problem is that when I run the function the input information is not added. However a id in my database is created but no body content.
My code:
// newName + newNumber are values from user input
 const contactObject = {
        name: newName,
        number: newNumber,
        date: new Date().toISOString(),
        id: persons.length + 1,
      }
      console.log(JSON.stringify(contactObject))

      fetch('http://localhost:3001/phonebook', {
        method: 'POST',
        body: JSON.stringify(contactObject),
      })

The console log from above shows {"name":"test","number":"12345","date":"2020-10-29T01:50:17.345Z","id":9}
My JSON database shows
// hardcoded data
 {
      "name": "Mary Poppendieck",
      "number": "39-23-6423122",
      "id": 4
    },
// data from running my create new function
    {
      "id": 5
    }

I expected data would include name, number, data, ID. But instead only get an ID.
Not sure what i'm doing here as its my first time doing any CRUD operations.

A: Need to add the following to my functionality.
 headers: {
          "Content-type": "application/json; charset=UTF-8"
        }

Full code:
fetch('http://localhost:3001/phonebook', {
        method: 'POST',
        body: JSON.stringify(contactObject),
        headers: {
          "Content-type": "application/json; charset=UTF-8"
        }
      })


text:
Q: External Login Account vs. Native Login Account I am brand new to Visual Studio 2012 and MVC 4, and I've been working with the SimpleMembershipProvider via the WebMatrix.WebData library.
I'd like to integrate Facebook as an external login source down the road, but it's not a requirement as of right now. However, to get a decent feel for what it would take, I've been following the tutorial and guide found here - http://www.asp.net/mvc/tutorials/mvc-4/using-oauth-providers-with-mvc.
My question :
If a user has already been created using :
WebSecurity.CreateUserAndAccount(model.Email, model.Password);
WebSecurity.Login(model.Email, model.Password);

Can they be "upgraded" to an oAuthMemebership account in the future, if they choose to use their Facebook credentials instead of the email and password they created when first signing up?
I couldn't find a clear answer to this question in the guide, or elsewhere, so I'm hoping someone can clarify how that process may work.

A: The SimpleMembership setup allows for a local and multiple OAuth logins all sharing the same UserProfile - so a single user can login with either a local password, or FacebOogLiveWitter.
(I should state, that I'm assuming in this answer that the OAuth provider does not send back a matching piece of information for a local account. If they do then the principles of actually performing the merge are the same, but the complexity and steps are vastly reduced.)
The OAuth registration process will refuse the user if they use an existing user name, rather than try and merge two accounts. Therefore this isn't simple, you'll have to build the functionality yourself. The process is complex as there are many directions the user can approach this from (so you could simplify by only supporting one or two), and you need to enforce security as well in case someone tries to merge into an account they don't own.
I will assume you are comfortable with the link you've posted, and you've followed the Facebook help at (for example) Facebook Login and The Login Flow for Web (without JavaScript SDK) so you have a working test application.
Your general process has to have multiple user journey approaches to make sense to a user:

*

*for a logged in user (with a local account)

*

*let them login to facebook and associate the accounts

*let them merge an existing account on your site which uses a facebook login

*for a logged-in user (with a facebook account)

*

*let them create a local account

*let them merge an existing local account on your site

*for a non logged in user who tries to register a local account

*

*let them merge this new account with a facebook login that is already registered, and do that as part of the registration process

*for a non logged in user who tries to register (or log in for the first time with) a facebook account

*

*let them link this with an existing local account as part of the registration process

etc.
ASK PERMISSION
(You can skip this if the OAuth provider has sent back a matching identifying piece of information, such as an email address).
You should enforce confirmation security, usually through email confirmation sent to the target account of the merge. Otherwise:

*

*someone can login to your site with facebook for the first time

*during that process say they "own" the email address or username of a local account (remember, facebook won't necessarily confirm what their email is for you)

*and therefore gain access to the existing local account

So, once the merge "request" is made, you need to ask for permission to proceed from the target account of the merge.
The MVC 4 AccountController
I will use Facebook as our OAuth example. To compare what happens when you register a user on your local authentication framework vs. OAuth:

*

*Local: creates an entry in webpages_Membership and an entry with the same UserId in UserProfile (assuming you are using the default tables for the MVC 4 application template)

*OAuth: creates an entry in webpages_OAuthMembership and an entry with the same UserId in UserProfile

Now let's look at what happens when a user signs in using Facebook for the first time:

*

*They click on Login using Facebook (or whatever your button says)

*they get taken to facebook to login

*they succeed (let's assume that, and ignore the failure case)

*they then get sent, invisibly to them, to /Account/ExternalLoginCallback

*OAuthWebSecurity.SerializeProviderUserId is called, passing the OAuth details to that Action

*They get redirected to /Account/ExternalLoginConfirmation and asked to provide a username for their new presence on your site

*If that user name is available then UserProfile and webpages_OAuthMembership entries are created

This process is your chance to "join" the accounts by matching some unique piece of information. As long as you end up with the same UserId in UserProfile, webpages_Membership and webpages_OAuthMembership you should be ok. So we have to intercept the process at the point of /Account/ExternalLoginConfirmation.
If the OAuth provider has sent back a matching identifying piece of information, such as an email address, this becomes simple, test for this in the ExternalLoginConfirmation action, and auto-merge using a similar process to the one outlined below.
However, I think you can't/shouldn't assume that the user uses the same email address for your site and OAuth, (nor should you for many reasons). Also, probably in the T&Cs for something like FacebOogLiveWitter it stops you asking for the email of their account anyway, and if they don't currently they might in future.
So instead, you could link the accounts based on alternatives, like username or email address, or phone number. Either way you are going to need them to input some identifying piece of information that is unique against an account, and will pull back the target account.
Wrapping up
So to put this all together: In the first part of this answer I outlined how you will need to consider multiple user journeys to merge accounts. I will use the example 4.1.
Your process will need to:
(Assumption - when a user first registers with a local account, you ask them for an email address and validate it or assume it is valid)

*

*Let the user login with facebook for the first time

*at Account/ExternalLoginConfirmation ask them if they want to

*

*Create a new account with you

*Use their facebook login to access an existing account

*Assuming the latter, then you log a request in a new table (maybe "MergeAccountRequests") with:

*

*The facebook account UserId

*The target merge local account UserId

*An authorisation code to use in the email you need to send
(From this point on, if they login without confirming that merge, they will have to get sent to a page to ask them to confirm, rather than create objects in other db tables which you have to worry about later)

*You then send an email to the address of the target merge (local) account asking for permission to complete the merge (a standard confirmation email, with a link)

*When they click on that link, or enter the code you sent them (you could use SMS as well as email) then you need to merge the two accounts

*

*Choose the "new" and "target accounts (in this case "new" is the facebook account as you don't have data associated with it yet)

*Delete the UserProfile of the "new" account

*Change the UserId of the "new" account webpages_OAuthMembership table to the same as the "target" account

*Log the user out (so there are no complications depending on which account they are currently logged in with)

*Display a message to the user telling them the merge is almost complete and that they can now log in with either account to confirm and complete the merge

Rather than send them to a login page, i would give them the login options alongside the confirmation message.


text:
Q: Mongoose: How to populate sub properties from within a schema's virtual properties I have a mongodb schema defined using mongoose and I have some sub documents nested over multiple levels. I want to be able to access these (populated) subdocuments within another schema's virtual properties but I can't seem to do so. I seem to be able to access the documents at the first level of nesting but not further down.
Here's an example of my schemas:

const SchemaA = {
   name: {type: string}
   items: [
     {
      schemaB: {
       type: schema.type.ObjectId,
       ref: "B"
      }
     }
   ]
}

const SchemaB = {
   name: {type: string}
   schemaC: {
       type: schema.type.ObjectId,
       ref: "C"
      }
}

const SchemaC = {
   types: [{label: {type: String}}]
}

What I want to be able to do is access the SchemaC.types from inside a virtual property on SchemaA.
Here's what I want to achieve:

SchemaA.virtual("types").get(function(){
   return this.items.map(item => {
       return {name: item.schemaB.name, types: item.schemaB.SchemaC.types}
   })
})

From the above item.schemaB seems to populate just fine but item.schemaB.SchemaC seems to just be the objectId of schemaC.
I'm not sure if this is even possible, to be honest, but I can't seem to find a definitive answer anywhere online so I'm hoping someone on here can help. Thanks!

A: So in mongoose you need to use the populate method.
 .populate({
    path: 'schemaB',
    populate: {
      path: 'schemaC'
    }
  });

mongoose populate


text:
Q: Reference has not compile-time usages I've been watching over the architecture view of our solution created by ReSharper, when I noticed some of the project references has no compile-time usages, does that mean I can change assemblies at runtime?

A: In simple terms, no compile-time usage means that your code will compile even if you remove the reference. You cannot directly derive anything regarding runtime from this statement. It might even be that your application runs perfectly fine if you just remove this reference. It might also be that your reference is somewhat obfuscated and the compiler doesn't know it. This could be because the reference is implementing interfaces that you compile against or you are looking for it manually at runtime (see Florians answer). You could probably also hide it with reflection if you really wanted to. But that would also need to load the assembly manually at runtime.
At compile-time, the compiler will link the new binaries to the corresponding code in the referenced assemblies. This will allow automatically loading the assembly at runtime. It will also copy const values to your assembly.
You can definitely change the referenced assembly between compile- and runtime, although you should tread very carefully. If method signatures changed, compile-time references will break.
At runtime, referenced assemblies will be loaded once you try to interact with them. Once an assembly is loaded, it cannot be unloaded directly. You can only unload AppDomains. So if you want to change assemblies at runtime, look into AppDomains.
So what could be an intended use of those non-compile-time references? The most common architecture that uses this was mentioned by Florian in the other answer: Plugins. Also other dependencies where you want to separate your code from the actual implementation via interfaces. Your project references without compile-time dependencies are then only used to deliver the implementation to the actual application. Otherwise you would need to add this to your delivery and debugging process, which can be a pain depending on your project.


text:
Q: Counting created objects over 2 different classes leads to problems I want to count created objects. If I do this with one class it is easy, but I want count objects from 2 different classes with 2 different counters interacting with each other.
Simplified example:
template <class Obj>
class Counter1
{
    private:
        static int total1;
    public:
        Counter1(){++total1;}
        .. destuctor, copy constructor ..
       static int getCounter1() {return total1;}
       static void setCounter1(int var) {total1 = var;}
};
template<class Obj> int Counter1<Obj>::total1(0);

template <class Obj>
class Counter2
{
    private:
        static int total2;
    public:
        Counter2(){++total2;}
        .. destuctor, copy constructor ..
       static int getCounter2() {return total2;}
       static void setCounter2(int var) {total2 = var;}
};
template<class Obj> int Counter2<Obj>::total2(0);

class Test1 : private Counter1<Test1>
{
 .. some code ..
};
Test1::Test1() : Counter1()
{
   int tmp_var;
   tmp_var = Counter2<int>::getCounter2();
}

Sadly tmp_var never gets a valid number. Or in other words, it stays at zero and doesn't increase. What am I doing wrong?
_________________EDIT__________________
Here a more detailed example as requested:
template <class Obj>
class Counter1
{
    private:
        static int total1;

    public:
        Counter1() {++total1;}
        Counter1(const Counter1& countObj) {if(this != &countObj) {++total1;}}
        ~Counter1() {--total1;}

        static int getCounter1() {return total1;}
        static void setCounter1(int var){total1 = var;}
};
template <class Obj> int Counter1<Obj>::total1(0);

template <class Obj>
class Counter2
{
    private:
        static int total2;

    public:
        Counter2() {++total2;}
        Counter2(const Counter2& countObj) {if(this != &countObj) {++total2;}}
        ~Counter2() {--total2;}

        static int getCounter2() {return total2;}
        static void setCounter2(int var){total2 = var;}
};
template <class Obj> int Counter2<Obj>::total2(0);

/* Memory are with a static Size with variable object Size allocator */
class Class1 : private Counter2<Class1>
{
    public:
        Class1();

        .. some methods ..

    private:
       .. some members ..
    };

/* Constructor */
Class1::Class1() : Counter2()
{
    const int varTotal1 = Counter1<int>::getCounter1();
    const int varTotal2 = getCounter2()-1;

    .. some code ..
}

.. some methods ..

class Class2 : private Counter1<Class2>
{
    public:
        Class1 _PoolsObj[TASKS_PER_PROCESS];

        Class2();
};

Class2::Class2() : Counter1()
{
    _PoolsObj[TASKS_PER_PROCESS] = {};

    /* Reset the task counter */
    Counter2<int>::setCounter2(0);
}

static Class2 class_pool[64];

I have two problems:
 1) Counter2<int>::setCounter2(0); doesn't work
 2) const int varTotal1 = Counter1<int>::getCounter1(); Is always 0

A: Following your new sample, the following is my opinion.
First of all, do not forget that each instance of the template has its own static variable. It is not like other standard classes. That is what is playing a trick on you.
The reason
const int varTotal1 = Counter1<int>::getCounter1();

is always 0 is the instance of the template counter1 is inherited by class2.  But you are asking the counter1's  getCounter1() from class1 to give you the count or the value of total1.  Class1 does not know about getCounter1(). Note that when instantiating the class using the following line of code in your sample code total1 of counter1 is incremented rightly as you are instantiating Class2 and Class2 knows about getCounter1() and if you happen to include getCounter1() in Class2 you can see the total1 value.
static Class2 class_pool[64];

As to the following code as far as I can tell it works.
Counter2<int>::setCounter2(0);

As a final note, if I were you I will have only one template say counter. Use that as you do normally to control count of created objects for each class. If you want to see the count of one class from another class why not create a third utility shared class where you can store the counts of the objects. Or you can use mixin to combine the classes as required (using inheritance and composition), but may be this is an overkill.
By the way, your code is not complete you missed to define
 TASKS_PER_PROCESS  in
  _PoolsObj[TASKS_PER_PROCESS] = {};
   I added the following to just compile your code ..
   #define TASKS_PER_PROCESS 10

A: I figured out, what I was doing wrong and I made some major improvements.
1) Thanks to the comment of @tobi303 I could remove one counter and only use one for different objects.
2) I had a semantical error inside of my code. _PoolsObj[TASKS_PER_PROCESS] = {}; is completly wrong. I wanted to initalize all array elements with 0, but this only called the constructor a fifth time and set the forth (TASK_PER_PROCESS) element to 0. I now placed the initialize list after the variable declaration to ensure proper creation.
3)
public:
        Class1 _PoolsObj[TASKS_PER_PROCESS];

This is of course not the nice way, so I included a getter function and set the array to private.
4) My problems were cause by this two lines of code:
Counter1<int>::getCounter1();
Counter2<int>::setCounter2(0);

The type should not be int, it should be the class name:
Counter1<Class2>::getCounter();
Counter2<Class1>::setCounter(0);

I think I set and get a counter for int and not for my classes.
Here my fixed code just for completion:
template <class Obj>
class Counter
{
    private:
        static int total;

    public:
        Counter() {++total;}
        Counter(const Counter& countObj) {if(this != &countObj) {++total;}}
        ~Counter() {--total;}

        static int getCounter() {return total;}
        static void setCounter(int var){total = var;}
};
template <class Obj> int Counter<Obj>::total(0);

class Class1 : private Counter<Class1>
{
    private:
        int member;

    public:
        int getMember();
        Class1();
};

class Class2 : private Counter<Class2>
{
    private:
        Class1 _PoolsObj[TASKS_PER_PROCESS] = {};
    public:
        Class1 getPool(int index);
        Class2();
};

Class1::Class1()
{
    const int varTotal1 = Counter<Class2>::getCounter()-1;
    const int varTotal2 = getCounter()-1;

    std::cout<<"varTotal1: "<<varTotal1<<std::endl;
    std::cout<<"varTotal2: "<<varTotal2<<std::endl;
}

int Class1::getMember()
{
    return member;
}

Class2::Class2()
{
    std::cout<<"Class2 Constructor"<<std::endl<<std::endl;

    /* Reset the task counter */
    Counter<Class1>::setCounter(0);
}

Class1 Class2::getPool(int index)
{
    return _PoolsObj[index];
}

static Class2 class_pool[64];


text:
Q: x86 architecture specifications I want to write an IBM-PC compatible emualtor with C++ as an educational project, and in order to correctly emulate the 8086 processor need information on how it works.
Some examples for the information I would need:

*

*How is the code structured (size of single instructions, how are they unpacked, etc.)

*Exact workings of the registers

*Detailed information on what the single instructions do (For example the default description for the CMP command "Compares ... and ... and sets the flags" isn't enough for me)
I have already searched around for a few hours, but the information I got was more aimed at people trying to learn x86 assembly, and wasn't detailed enough
Maybe you can help me?

A: You may want to go straight to the source:
http://download.intel.com/design/intarch/manuals/24319101.pdf

A: sandpile.org is a nice place if you need information about the encoding format of x86 opcodes. All the info is organized in tables for easy look-up.

A: You could look at the Intel architecture manuals:
http://www.intel.com/products/processor/manuals/
(note: Otavio's link is better as it goes to an older manual)
Of course, these include specifications for a lot of instructions and features that didn't exist in the 8086, but you should be able to skip over the new stuff.
You may also want to look at Bochs to check things or get some ideas.
Finally, unless you're already quite confident, I would recommend starting with a simpler (RISC) instruction set, such as one of the MIPS architectures. Instruction decoding and addressing modes are considerably less complex in a typical RISC architecture than they are in a typical CISC architecture.

A: The art of assembly language, by Randall Hyde. It has a couple of sections on how the processor works, for example:
Chapter Three: System Organization

*

*3.0 Chapter Overview

*3.1 The Basic System Components

*3.1.1 The System Bus

*3.1.1.1 The Data Bus

*3.1.1.2 The Address Bus

*3.1.1.3 The Control Bus

*3.1.2 The Memory Subsystem

*3.1.3 The I/O Subsystem

*3.2 System Timing

*3.2.1 The System Clock

*3.2.2 Memory Access and the System Clock

*3.2.3 Wait States

*3.2.4 Cache Memory

*3.3 The 886, 8286, 8486, and 8686 "Hypothetical" Processors

*3.3.1 CPU Registers

*3.3.2 The Arithmetic & Logical Unit

*3.3.3 The Bus Interface Unit

*3.3.4 The Control Unit and Instruction Sets

*3.3.5 The x86 Instruction Set

*3.3.6 Addressing Modes on the x86

*3.3.7 Encoding x86 Instructions

*3.3.8 Step-by-Step Instruction Execution

*3.3.9 The Differences Between the x86 Processors

*3.3.10 The 886 Processor

*3.3.11 The 8286 Processor

*3.3.12 The 8486 Processor

*3.3.12.1 The 8486 Pipeline

*3.3.12.2 Stalls in a Pipeline

*3.3.12.3 Cache, the Prefetch Queue, and the 8486

*3.3.12.4 Hazards on the 8486

*3.3.13 The 8686 Processor

*3.4 I/O (Input/Output)

*3.5 Interrupts and Polled I/O


text:
Q: Form action call to insert data to database in Framework 1 I am learning Framework1 and tried to do a simple ColdFusion program to insert data into database after submitting a form.
My simple form person.cfm is in views/main
<form name = "savePerson" action="#buildurl('person')#" method="post">

In the form action I put controller person.cfc
I have person.cfc in controllers folder with code in the component
<cffunction name="person">
  <cfif isDefined("rc.savePerson")>
    <cfset variables.services.person.savePerson()>
  </cfif>
</cffunction

and SQL insert statement in person.cfc with function name = savePerson in the services folder.
Application.cfc has code
 function setupApplication() {

    var bf = new framework.ioc( "services" );

    setBeanFactory( bf );

 }

When I submit the form I get the error below

Original exception in onRequest
The action person.person failed.
Element SERVICES.PERSON is undefined in a Java object of type class [Ljava.lang.String; referenced as ''
(Expression)

but there is a person.cfc in controllers, services. I don't know if I need a beans folder.
My question is what should I write for form action and how Framework1 will call the file in services folder to run insert statement via controller?

A: I have a feeling you might be missing get/set to the Person Service. Also make sure you've got the service declared in the beans.xml.cfm
controllers/person.cfc
<cffunction name="setPersonService" access="public" output="false">
    <cfargument name="personService" type="any" required="true" />
    <cfset variables.personService = arguments.personService />
</cffunction>
<cffunction name="getPersonService" access="public" returntype="any" output="false">
    <cfreturn variables.personService />
</cffunction>

assets/config/beans.xml.cfm
<bean id="personService" class="myapp.services.Person" singleton="true">
</bean>

Edit: Oh I just realised this question was answered on the FW/1 groups


text:
Q: How to change style of DIV element in view from controller? I have the following div in my view:

    REVIEW:

    <%:ViewData["Review"]%>

    <input name="submit" id="submit" type="submit" value="OK"/>

How can I set DIV visibility to visible inside of controller when a certain button is clicked?
This is a code fragment in my controller:
public ActionResult Index(EsafeModel model,string submit, string create)
{
   if (button.Equals("Create"))
   {
      ViewData["Review"] = ESafeData.CreateReview(eSafe);
   }
   else if (button.Equals("OK"))
   {
      if (ESafeData.Create(eSafe))
      {
         ViewData["Message"] = "E-Safe data created!!!";
      }
   }
}

A: You can't do this directly as div is on client side and the controller is server side.
What you can do is have a property in your model which is bound to view .This can have the value of visibility attribute for div and then you can assign it using server tags to div
Below is a sample code snippet
 <div id="elementid" style="visibility:'<%=Model.Visible %>'"/>

On the click of button you can return the same view and model but this time model will have Visible ="hidden"


text:
Q: tikz - relative coordinates of a second position I'm drawing a kind of sequence diagram but I don't want to calculate every position.
I want to use relative coordinates. With the command coodinate I set the first coordinate (0.25,14.25) as a, but I want to select a second coordinate (0.25,14.75).
Is there a way to do this?
%Actor
\draw[dashed] (0.25,15) -- (0.25,0)  node[above=15] {User};
\draw[dashed] (6,15) -- (6,0)  node[above=15] {HMI};
\draw[dashed] (12,15) -- (12,0) node[above=15] {Server1};
\draw[dashed] (18,15) -- (18,0) node[above=15] {Server2};
%
%Blocks
\begin{scriptsize}
\draw[line width=5pt] (0.25,14.25) -- (0.25,14.75)  node[midway, right] {Test} coordinate (a);
\end{scriptsize}
%
%Arrows
\begin{scope}[>=latex]
\draw[->,black] (a) -- (6,14);
\end{scope}

A: You can do this using the calc library (See Section 13.5 Coordinate Calculations of the pgf manual):
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}

\begin{tikzpicture}
  \coordinate (a) at (2,2);
  \coordinate (b) at (0,-2);
  \node[draw=red] at (a) {a};
  \node[draw=red] at (b) {b};
  \draw[help lines] (-1,-3) grid (3,3);
  \draw ($ (a) + (0,1) $) -- ($ (b) + (0,1) $);
\end{tikzpicture}
\end{document}

A: I think you have it a bit confused. Your coordinate (a) (which is an empty node) is really (0.25,14.75), at the end of the path.
To have a  "marker" for the start and end of the path you can do:
    %Blocks
    \begin{scriptsize}
        \draw[line width=5pt] (0.25,14.25) coordinate(b) --
             (0.25,14.75)  node[midway, right] {Test} coordinate (a);
    \end{scriptsize}
    %
    %Arrows
    \begin{scope}[>=latex]
        \draw[->,black] (a) -- ++(1,0) node {a};
        \draw[->,black] (b) -- ++(1,0) node {b};
    \end{scope}

and you'll have (partial graph):

In general, you can have node on whichever part of the path, with the pos key; if you add
        \draw[line width=5pt] (0.25,14.25) coordinate(b) --
           (0.25,14.75)  node[midway, right] {Test}
           coordinate (a)  coordinate[pos=0.5](c);

and
       \draw[->,black] (c) -- ++(2,0) node {c};

you have:

Notice also that the midway keys is really another way of saying pos=0.5.

A: First Answer: Use the package tikz-uml, it offers also support for sequence diagrams. See perso.ensta-paristech.fr/~kielbasi/tikzuml; the sequence diagrams are documented here.
Second Answer: If you want to do it yourself using the tikz commands directly, I suggest to

*

*use commands for constants, like \xUser and \xHmi for the horizontal positions of the time lines

*use nodes for actors and actions and name them

*define styles for the parameters of the nodes.
Then it will be easy to adjust and extend the diagram. Here is an example how you can do it.

\documentclass[border=3pt]{standalone}
\usepackage{tikz}
\tikzset
  {actor/.style={font=\ttfamily},
   action/.style 2 args= % first arg is length in mm, second arg is label
     {minimum width=3mm,minimum height=#1mm,inner sep=0pt,
      draw,fill=blue!30,anchor=north,label={right:\scriptsize#2}
     },
   message/.style={-stealth,font=\scriptsize\bfseries},
   timeline/.style={dashed}
  }
\begin{document}
\begin{tikzpicture}[x=1mm,y=1mm]
  % horizontal position of actors (in mm)
  \newcommand\xUser{0}
  \newcommand\xHmi{20}
  \newcommand\xSa {40}
  \newcommand\xSb {60}
  % actors
  \node[actor] (user-0) at (\xUser,0) {User};
  \node[actor] (hmi-0)  at (\xHmi ,0) {HMI};
  \node[actor] (s1-0)   at (\xSa  ,0) {Server1};
  \node[actor] (s2-0)   at (\xSb  ,0) {Server2};
  % time lines
  \newcommand\yTimeMax{-65}
  \draw[timeline] (user-0) -- +(0,\yTimeMax); % example for relative positioning
  \draw[timeline] (hmi-0)  -- +(0,\yTimeMax);
  \draw[timeline] (s1-0)   -- +(0,\yTimeMax);
  \draw[timeline] (s2-0)   -- +(0,\yTimeMax);
  % actions (first arg is length in mm, second arg is label)
  \node[action={10}{$A_1$}] (user-1) at (\xUser,-10) {};
  \node[action={ 5}{$A_2$}] (hmi-1)  at (\xHmi ,-20) {};
  \node[action={15}{$A_3$}] (s1-1)   at (\xSa  ,-25) {};
  \node[action={10}{$A_4$}] (user-2) at (\xUser,-50) {};
  % messages
  \draw[message] (user-1.south east) -- node[above]{a} (hmi-1.north west);
  \draw[message] (hmi-1.south east)  -- node[above]{b} (s1-1.north west);
  \draw[message] (s1-1.south west)   -- node[above]{c} (user-2.north east);
\end{tikzpicture}
\end{document}


text:
Q: In PostgreSQL, do PL/pgSQL and SQL have different CREATE FUNCTION commands? In PostgreSQL document, the commands to create a PL/pgSQL function and to create a SQL function seem very similar but with differences:

Functions written in PL/pgSQL are defined to the server by executing
  CREATE FUNCTION commands. Such a command would normally look like,
  say,
CREATE FUNCTION somefunc(integer, text) RETURNS integer
AS 'function body text'
LANGUAGE plpgsql;

The function body is simply a string literal so far as  CREATE
  FUNCTION  is concerned. It is often helpful to use dollar quoting (see
  Section 4.1.2.4) to write the function body, rather than the normal
  single quote syntax. Without dollar quoting, any single quotes or
  backslashes in the function body must be escaped by doubling them.
  Almost all the examples in this chapter use dollar-quoted literals for
  their function bodies. PL/pgSQL is a block-structured language. The
  complete text of a function body must be a block. A block is defined
  as:
[ <<label>> ]
[ DECLARE
    declarations ]
BEGIN
    statements
END [ label ];

In the list of SQL commands:
CREATE [ OR REPLACE ] FUNCTION
    name ( [ [ argmode ] [ argname ] argtype [ { DEFAULT |
 = } default_expr ] [, ...] ] )
    [ RETURNS rettype
      | RETURNS TABLE ( column_name column_type [, ...] ) ]
  { LANGUAGE lang_name
    | TRANSFORM { FOR TYPE type_name } [, ... ]
    | WINDOW
    | IMMUTABLE | STABLE | VOLATILE | [ NOT ] LEAKPROOF
    | CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT
    | [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER
    | PARALLEL { UNSAFE | RESTRICTED | SAFE }
    | COST execution_cost
    | ROWS result_rows
    | SET configuration_parameter { TO value | = value | FROM
 CURRENT }
    | AS 'definition'
    | AS 'obj_file', 'link_symbol'
  } ...
    [ WITH ( attribute [, ...] ) ]

For example, we can specify a language

*

*by LANGUAGE ... at the end in the PL/pgSQL command and

*by LANGUAGE lang_name in the SQL command.
Are they really two different commands? Or are they  the same command?
Thanks.

A: The cited definition of CREATE FUNCTION is common for all languages:

lang_name
The name of the language that the function is implemented in. It can be sql, c, internal, or the name of a user-defined procedural language, e.g. plpgsql.


text:
Q: How to run a command on a linked docker container? I am using docker-compose with:

*

*an existing (python) app running inside a docker container.

*another (ruby) command-line app running in a docker container.

How do I 'connect' those two containers so that the python container can call the command-line app in the ruby container? (and pass arguments via stdin/stdout)

A: Options are available, but not great. If you're using a recent version of Docker Compose then both containers will be in the same Docker network and can communicate, so you could install sshd in the destination container and make ssh calls from the source container.
Alternatively, use Docker in Docker with the source container, so you can run docker exec inside the source and execute commands on the target container.
It's low-level communication though, and raising it to a service call or message passing would be better, if changing your apps is feasible.


text:
Q: Can I mock a generic (template) private method using MockK in Kotlin? I would like to mock the following function:
private fun <T> updateItemInDb(id: Long, column: String, data: T)
which is invoked in the following way by my class:
updateItemInDb(it, DB_POS, i), where it is a Long, DB_POS is String and i is an Int.
I want the function to just run without doing anything. I tried the following in my unit test:
1) every { adapter["updateItemInDb"](any<Long>(), any<String>(), any<Int>()) } just Runs
This gives me a type mismatch error: required MockKStubScope<Unit>, found MockKStubScope<Any?>
2) every { adapter["updateItemInDb"](any<Long>(), any<String>(), any<Int>()) } answers { }
This fails at runtime with io.mockk.MockKException: can't find function updateItemInDb(-1078155520644112829, -d008fa83c4f49c0, 843241211) for dynamic call

A: Now yes. Generic private functions was fixed since 1.7.16


text:
Q: Accessing variable from library to use in component I have this bit of code right here:
                    <Chart // this Component has the value I want
                          style={[styles.chart]}
                          data={this.props.daily}
                          verticalGridStep={6}
                          type="line"
                          showDataPoint={true}
                          color={['white']}
                          gridColor={'white'}
                          dataPointColor={['white']}
                          dataPointFillColor={['white']}
                          axisLabelColor={'white'}
                          axisColor={'white'}
                          chartTitle={'Weekly View'}
                          tightBounds
                          yAxisShortLabel
                          animationDuration={0}
                       />
                  <Popover // I want to use it in here
                     isVisible={this.state.isVisible}
                     fromRect={{x: 197.14285714285714-20, y: 10, width: 0, height: 0}}
                     onClose={this.closePopover}
                     placement={'bottom'}
                     key={i}
                    >
                     <Text>Value</Text>
                    </Popover>

The goal is to set this popover in the exact location of the plotted dots form that chart, I found the area in the code for the library that has the coordinates of the dots in an array:
var multipleDataPoints = dataPoints.map( (dataPointSet, index) => {
                        console.log(dataPointSet)                 //HERE
                        let totalDataSet = dataPointSet.map((d, i) => {
                            return (
                                        <Circle key={i} {...d} onPress={()=> console.log("\N\N\NYOYOYO")}>
                                            <Text>What</Text>
                                        </Circle>
                            );
                        });
                        return totalDataSet;
                    });

What I was wondering, is there a way to access that variable from the library so I can use it in the <Popover> component in the index file so I can set the location of it relative to the plotted dots?


text:
Q: Error: the declared type of navigation property is not compatible with the result This error just makes no sense to me.  I've read the various answers on here and other places - nothing is clicking for me.

the declared type of navigation property 'Invoice.LineItems' is not compatible with the result of the specified navigation

I have two tables: Invoices and LineItems.
In their simplest form they look like:
Invoices
InvoiceID
LineItems
InvoiceID
Name
QTY
and the entities:
Public Class Invoice
    <Key>
    Public Property InvoiceID As Int64

    Public Overridable Property LineItems As List(Of LineItem) = New List(Of LineItem)
End Class

Public Class LineItem
    <Key>
    Public Property InvoiceID As Int64

    Public Property Name As String

    Public Property QTY As Int32 = 0
End Class

When attempting to fetch Invoices with their associated LineItems, I get the error above.
Using database As PosDatabase = New PosDatabase
    Dim invoices As List(Of Invoice) = database.Invoices _
        .Include("LineItems") _
        .ToList()
End Using

This is EF 6.2.0
Any help in resolving the issue would be much appreciated.

A: The exception is caused by the improper model mapping.
The FK InvoiceID property of the LineItem is marked as PK, thus effectively making the relationship 1 to 0..1, i.e. changing the expected multiplicity of the relationship represented by the LineItems collection navigation property from Many to One.
I guess this is just a mapping mistake, the actual PK of the LineItem should be different - either own identity column like LineItemID or composite PK on (InvoiceID, Name).
So simply map the correct PK (with data annotations or fluent API) of the LineItem and the problem will be solved. In my test I did it with
modelBuilder.Entity<LineItem>()
    .HasKey(e => new { e.InvoiceID, e.Name });


text:
Q: Comparison matchers fail on mixed numeric types In vanilla Scala the following assertions pass
assert(1D > 0F)
assert(1F > 0)
assert(1L > 0)
assert(1 > 0.toShort)
assert(1.toShort > 0.toChar)

however similar matchers in ScalaTest fail
1D shouldBe > (0F)
1F shouldBe > (0)
1L shouldBe > (0)
1 shouldBe > (0.toShort)
1.toShort shouldBe > (0.toChar)

A workaround is to make both sides the same type, for example
1D shouldBe > (0D)

Why does it work in Scala, but not in Scalatest, or what is it about the signature of >
def >[T : Ordering] (right: T): ResultOfGreaterThanComparison[T]

that makes it fail?

A: Vanilla Scala works due to automatic type conversion i.e. 0F is cast to 0D which is a common practise in many languages.
More interesting question is why shouldBe does not work. De-sugaring the implicits yields
new AnyShouldWrapper[Double](leftSideValue = 1D,
                             pos = ???,
                             prettifier = ???)
  .shouldBe(new ResultOfGreaterThanComparison[Double](right = 0D))

new AnyShouldWrapper[Double](leftSideValue = 1D,
                             pos = ???,
                             prettifier = ???)
  .shouldBe(new ResultOfGreaterThanComparison[Float](right = 0F))

which leads to overloaded implementations of shouldBe. The former case goes here and the latter here.
After looking at the source code, it seems that the only reason 1D shouldBe > (0F) actually compiles is to support array comparison with shouldBe keyword.


text:
Q: hierarchy problems changing paragraph style from css I want to change paragraph style  from CSS using hover on different element without default  style overwriting it.
HTML:

AAAA

BBBB

CSS:
.a {
    color: red;
}
p {
    color: green;
    text-align: center;
}

.a:hover ~ .b {
    background-color: blue;
    color: orange;
}

I want to change color of font BBBB to orange, when hovering over AAAA. The hovering happens, BBBB style fonts gets command for changing background-color and font color, but font color is overwritten by default paragraph P style.
I am not able to change much of the html hierarchy. What can I do from CSS only?

A: your css is working fine!
Just select the
 inside of your class="b"
Like this:
.a:hover ~ .b p {
    color: orange;
}

.a {
    color: red;
}
p {
    color: green;
    text-align: center;
}

.a:hover ~ .b {
    background-color: blue;
    color: orange;
}

.a:hover ~ .b p {
    color: orange;
}

AAAA

BBBB


text:
Q: How to arrange divs by css floats? I have six divs and want to arange them in two rows and three columns
#topLeft {float:left;} //ok
#topMiddle {float:left;} //ok
#topRight {float:right;} //ok
#bottomLeft {}
#bottomMiddle {}
#bottomRight {}

In the second row I tried many combinations with floats and clears - without success.

A: Add clear: left; float: left; to #bottomLeft and float: left; to the last two.
Here's a fiddle: http://jsfiddle.net/5nGUe/2/


text:
Q: Uncaught ReferenceError: __VUE_HMR_RUNTIME__ is not defined I am trying to add vue.js to a project with webpack, when I run I get an error 'Uncaught ReferenceError: VUE_HMR_RUNTIME is not defined' in console.
App.vue
<template>

{{text}}

</template>

index.js
import Vue from 'vue/dist/vue.runtime.common';
import App from "./App.vue";

new Vue({
    el: '#app',
    render: h => h(App)
})

vue-loader installed

A: just update your vue-loader. in recent weeks, it updates fast! from v16 back to v15.


text:
Q: How to share link to Google Drive file via Google+? I'm trying to share a Google+ post from Android with DeepLinkId attached. This deeplink should lead to Google Drive file.
I've managed to share a file from Google Drive (I've got DriveFile.resourceId) and it's clear to how to share Google+ post with deeplink.
But how to attach Drive file link, which is also should become shared to person who opens deep link?


text:
Q: SpriteKit Detect Ranges I am making small/mid RTS game, I have the following need:
I want Enemy Players to Attack allies and vice versa when they are in each attack range.
My question is: what would be a better approach finding if enemy units are in attack range of allied or vice versa of course ?
What have I tried:
For now I tried to add SKNodes with SKPhysicsBodies for each unit Node.
I can see that FPS are going down when the contact happens... I guess it wasn't the best way to know detect whether enemies are in range.
I guess my alternative is to run some Nested Loop within Update method and check if there are enemy units within the Radius.
I am not sure if it is the best approach, however with this approach I may play with some parameters and maybe optimize the routine for my own needs.
I would like to know if there is some better alternatives.

A: Look into GamePlayKit,
It may have some things you want.
Otherwise I would just use the Euclidiean Distance Formula https://math.stackexchange.com/questions/139600/euclidean-manhattan-distance without the square root,  and use this value based on  squads, not individual troops.  (So if a group of 4 soldiers is attacking an enemy of 5 soldiers, only 1 distance check is done).
The reason why you do not square root, is because you should know the squared allowable distance.  If an enemy 10 pixels away attracts soldiers, then use 100.
The best way to treat your soldiers like squads,  add them all to an SKNode  (sub class to add better functionality),  then you just need to compare those squad SKNodes
If you want to reduce the number of checks you make,  consider turning your play area into a grid (Like a chess board).  Since you know the size of your tiles, you could easily check to see if the units are close enough to warrant a distance check.  E.G.  You have a unit at a1, and an enemy at i9, then you know just by tile distance that the units are too far apart to attack each other


text:
Q: N people in a circle randomly throw ball at each other - Expected number of balls on the ground Suppose there are N people standing in a circle and each one of them has a ball in their hand. When the referee says throw, they are supposed to throw the ball at random towards another person in the circle and at the same time supposed to catch the first incoming ball. If a person receives >1 ball, those fall on the ground. Question is what is the expected number of balls that will fall on the ground?
This question has appeared in one of my past interviews. Currently my take on this is (although it doesn't seem correct):
So can I assume $X$ to follow $\operatorname{binomial}(N-1, p)$ where $p = \frac{1}{N-1}$? In that case, $$\mathbb{E}(X) = \frac{N-1}{N-1} = 1.$$ So the expected number of balls on the ground for person $i$ $\mathbb{E}(X-1) = 0$? That makes the overall expectation $0N = 0$?


text:
Q: How to take a snapshot of a directory on Linux as it was at a particular point in time? I have a directory containing a lot of result log files (directory size ~ 4GB), and a set of processes running that keep on writing to these files.
To be able to correctly analyze the results at a later time, I want to copy the whole directory to an archive destination, and I cannot stop the processes.
I want a copy of the directory as it was at a particular point of time. As the size directory is huge (which means it takes about 40 seconds to copy) and some of the files are being written to, a normal cp -r does NOT give me a snapshot at a particular point in time, rather a snapshot of files spread over some 40 seconds. This is not good enough.
Is there a way to get an exclusive lock on the directory and all its components while copying?

A: LVM (Logical Volume Manager) supports snapshots. Since all Linux distribution has LVM builtin, it is the easiest for you. The only downside is you need to recreate your file system.
Here is a good tutorial http://rhcelinuxguide.wordpress.com/2006/06/03/what-is-a-logical-volume-manager-lvm-snapshot-and-how-do-i-use-it/

A: If cp is taking too long to provide the results you need, you're most probably not going to be satisfied with other options. Unix copy is about as basic as it gets for I/O overhead.
However, if you retarded the I/O processes buy leveraging another management process between the disk and the files as they were changing, the overhead may not matter. What I mean is, you could run the process in a VM (if this is possible), try snapshots with rsync, or even subversion.
The only other thing I can think of is maybe piping the log output to a symbolic link and updating the links to a secondary location with a batch file.
For instance:
file.log -> /mnt/disk1/logarea/file.log
file.log -> /mnt/disk/logarea2/file.log
So that you can update the symbolic link instantly, and the output pipes to the new location.
You might even be able to write a batch file to update the link, count to 45 seconds, and then switch it back - thus isolating the data you need.
Just thoughts, good luck.

A: A different way of doing it would be to use Logrotate to archive the logs every week/day/hour, then you essentially have snapshots at that interval.

A: Some filesystems provide snapshot facilities.  Creating a filesystem (on an unused area of drive, or in a dedicated data file [loopback]) using one of these filesystems and then mounting that where your logs are written would allow you to snapshot the logs filesystem.
Filesystems known to support snapshots:

*

*ZFS (fuse based)

*FreeBSD's FFS

*LFS (Log Structured Filesystem)

*XFS

There are probably more, but those are the ones I can think of off the top of my head.
Snapshots don't copy the data, rather the freeze the data at a particular moment in time and create a virtual filesystem containing that data that can be mounted and used like any other filesystem (albeit read-only).  The original filesystem continues to function as if nothing had happened.

A: Frankly, for what you're asking for the only thing that has worked for me is ZFS-FUSE.  There is also a native ZFS for Linux but it's not really usable yet.


text:
Q: Google Maps iOS SDK Map Will Not Appear My map on GMSMapView appears tan in color and never appears. I have tried every suggestion on the internet, including:
Triple checking my API Keys and setting them as follows (note: GooglePlaces does work):
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
    FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
    GMSPlacesClient.provideAPIKey("MY KEY")
    GMSServices.provideAPIKey("MY KEY")
    LocationService.sharedLocation.startUpdatingLocation()
    return true
}

I have enabled the iOS SDK:

I have added the SDK to the credentials:

I have also triple checked that the bundle ID is correct (again, GooglePlaces does work).
Below is my implementation code which I got from the Google website.
Inside the viewDidLoad I call:
private func initializeMap() {
    let camera = GMSCameraPosition.camera(
        withLatitude: (currentLocation?.coordinate.latitude)!,
           longitude: (currentLocation?.coordinate.longitude)!,
                zoom: zoomLevel
    )
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    mapView.isMyLocationEnabled = true
    mapView.delegate = self
    self.view = mapView
}

And yet the map does not appear. Any other thoughts?

A: In my case the problem was I didn't enabled the Maps SDK for iOS in Google Cloud Platform since the instructions of the Getting Started page didn't say anything about this.
So I enabled this going to the Apis & Services page (make sure you have the correct project selected), clicking ENABLE APIS AND SERVICES, then selecting "Maps SDK for iOS" and finally clicking ENABLE.
If the problem is your user doesn't have access to this API you can grant it following this instructions: https://cloud.google.com/endpoints/docs/openapi/enable-api

A: I found the answer to my question myself. I was using GoogleMaps as a shared pod between my SDK and app (just as I was doing this for GooglePlaces). For some reason unbeknownst, likely a bug in Google API, this prevents it from working. When I moved the pod to my app only, it works.


text:
Q: How to prove the equivalence of two definitions of hypercharge? Before introducing top bottom and charm quarks,Strong Hypercharge is defined in the following two ways---
$1.\,\,\,Y=B+S$ where $Y,B,S$ are the hypercharge, baryon number and strangeness respectively.
$2.\,\,\,SU(3)$ can be decomposed into its maximal subgroup---$SU(2) \times U(1)$.Let in a basis, $SU(2)$ generators be the first three Gell-Mann matrices $\lambda_1,\lambda_2,\lambda_3$ and $U(1)$ generator be the 8th Gell-Mann matrix $\lambda_8$. Hypercharge is often defined as the U(1) quantum number, just like isospin is the $SU(2)$ quantum number. Therefore hypercharge is the eigenvalue of $\lambda_8$.
How can we get from 2 to 1 or the reverse, i.e. how are these definitions equivalent?

A: You can construct representations of $\text{SU}(3)$ from tensor products of the standard and dual actions of its complexified Lie algebra $\mathfrak{su}(3)\otimes\mathbb{C}\simeq\mathfrak{sl}(3,\mathbb{C})$ on $\mathbb{C}^3$, corresponding to the number of quarks and antiquarks respectively, which we will call the $(p,q)$ representations. (All I mean by complexification is taking complex linear combinations of the generators of $\text{SU}(3)$ so we can define ladder operators. The isomorphism to $\mathfrak{sl}(3,\mathbb{C})$ is a standard result that you can ignore if you don't know it). These end up giving us the decuplet, the different octets and singlets when combined with spin and requiring symmetry under permutations. These are representations of a flavor symmetry (that is broken by mass).
Like you said, $\mathfrak{sl}(3,\mathbb{C})$ contains some $\mathfrak{sl}(2,\mathbb{C})\oplus \mathbb{C}$ subalgebra. It is made up of a spin algebra $\mathfrak{sl}(2,\mathbb{C})\simeq\mathfrak{su} (2)\otimes\mathbb{C}) $ which mixes up and down quarks and under which the strange quark is a singlet, and a hypercharge algebra, as $\mathbb{C}\simeq\mathfrak{u}(1)\otimes\mathbb{C}$, and these algebras commute with eachother. And like ACuriousMind commented, you have to choose a basis and therefore define what a strange quark is (and so the notion of strangeness) for the formula to make sense.
We take a basis as
$$ I_3=\frac{1}{2}\lambda_3,\quad I_\pm = \frac{\lambda_1\pm i\lambda_2}{2},\quad Y=\frac{\lambda_8}{\sqrt{3}}$$
$$ u = \pmatrix{1\\0\\0}\quad d = \pmatrix{0\\1\\0}\quad s = \pmatrix{0\\0\\1}$$
where we have that $[Y,I_3]=0=[Y,I_\pm]$ as needed. We are of course omitting mention of the other ladder operators in $\mathfrak{sl}(3,\mathbb{C})$ that mix the strange quark with the others.
Using the explicit form of these matrices, we see that the strange quark has zero isospin, the up and down quark have $\pm\frac{1}{2}$ isospin respectively. The strange quark has hypercharge $-\frac{2}{3}$, and the up and down quark have hypercharge $\frac{1}{3}$. This is reversed for the antiparticles in the dual representation, since the action of a Lie algebra element $\lambda$ on some $\overline{q}\in\left(\mathbb{C}^3\right)^\ast$ is
$$ \lambda (\overline{q})=-\lambda^t\cdot \overline{q}$$
where $\cdot$ represents the regular matrix multiplication. You can calculate the charges of the tensor products by the usual operators $F = f\otimes 1 \otimes\ldots\otimes 1+\ldots$, etc, where each $f$ that is tensored is the single particle operator. Then the hypercharge of a vector in some representation is then given by
$$Y=\frac{n_u+n_d-2n_s}{3}-\frac{n_\overline{u}+n_\overline{d}-2n_\overline{s}}{3}$$
Now define the baryon number as $B=\frac{p-q}{3}=\frac{1}{3}\left(n_u+n_d+n_s-n_\overline{u}-n_\overline{d}-n_\overline{s}\right)$, and the strangeness as $S=-(n_s-n_\overline{s})$, and your result follows.
You can also get the charges of the quarks as $Q = I_3 + \frac{Y}{2}$. This just relates the $\text{SU}(3)$ flavor symmetry charges to the electric charge under which the quarks couple to the electromagnetic field.


text:
Q: SP.SOD.executeOrDelayUntilScriptLoaded not executing callback when script loads Don't have a lot of experience using the SP.SOD system, so I'm wondering what I'm doing wrong here...
I have a lot of functionality I am tying to a button I am rendering through the CSR framework.  That functionality is dependent on a few other scripts, and indeed some of that functionality I want to break out into another file so I can reuse it somewhere else.
I have my rendering override file set up like this:
var MYNS = MYNS || {};

MYNS.PromotedFieldRenderer = (function () {
    function renderDisplay(ctx) {
        var renderHtml;
        if (ctx.CurrentFieldValue && ctx.CurrentFieldValue === 'Yes') {
            renderHtml = 'Yes';
        } else {
            renderHtml = '<input type="button" class="ms-ButtonHeightWidth" value="Promote" onclick="MYNS.PromoteFromButton();"/>';
        }
        return renderHtml;
    }
    function renderReadOnly(ctx) {
        var renderHtml = 'No';
        if (ctx.CurrentFieldValue && ctx.CurrentFieldValue === '1') {
            renderHtml = 'Yes';
        }
        return renderHtml;
    }
    return {
        render: function () {
            SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
                Templates: {
                    Fields: {
                        Promoted: {
                            DisplayForm: renderDisplay,
                            EditForm: renderReadOnly,
                            NewForm: renderReadOnly
                        }
                    }
                }
            });
        }
    };
})();

RegisterModuleInit(SPClientTemplates.Utility.ReplaceUrlTokens('~sitelayouts/path/to/js/PromotedFieldRenderer.js'), MYNS.PromotedFieldRenderer.render);
MYNS.PromotedFieldRenderer.render();

SP.SOD.registerSod('jquery-3.4.1.min.js', '/sites/mysite/_layouts/15/path/to/js/jquery-3.4.1.min.js');
SP.SOD.registerSod('docx.js', '/sites/mysite/_layouts/15/path/to/js/docx.js');
SP.SOD.registerSod('My-Utils.js', '/sites/mysite/_layouts/15/path/to/js/My-Utils.js');
SP.SOD.registerSod('DoPromotionStuff.js', '/sites/mysite/_layouts/15/path/to/js/DoPromotionStuff.js');

SP.SOD.registerSodDep('DoPromotionStuff.js', 'jquery-3.4.1.min.js');
SP.SOD.registerSodDep('DoPromotionStuff.js', 'docx.js');
SP.SOD.registerSodDep('DoPromotionStuff.js', 'My-Utils.js');

MYNS.PromoteFromButton = function promoteFromButton() {
    SP.SOD.executeOrDelayUntilScriptLoaded(function() {
        var itemID = GetUrlKeyValue('ID');

        // MYNS.PromoteItem is in DoPromotionStuff.js
        MYNS.PromoteItem(itemID);
    }, 'DoPromotionStuff.js');
    SP.SOD.executeFunc('DoPromotionStuff.js', null, null);
};

I threw a breakpoint on the MYNS.PromotedFieldRenderer.render() line, and SP.SOD came up in the console (as did SPClientTemplates.Utility), so I'm pretty sure the SOD system is loaded and available even at the early stage registering rendering overrides, and no errors are shown in the console when the file loads.
However, when I click my button, nothing happens.  If I throw a breakpoint on the SP.SOD.executeFunc() line, it gets hit, but none of the dependency scripts load, and a breakpoint set in the callback never gets hit.
Any thoughts on what is going on here?
I read some other answers that said to explicitly load sp.js and sp.runtime.js, but this isn't some custom page where that might be missing, this is part of a regular SharePoint list item display form, and I can see that those files get loaded normally like regular OOB SharePoint behavior, so I don't think it's that.
(MDS is dis -abled on the site if that makes a difference.)

UPDATE
I have updated my code sample.  Apparently there was a problem with ReplaceUrlTokens not working as I expected, so the SOD registrations were not happening correctly.  After changing to the hardcoded URLs in the SOD registrations, SP.SOD.executeFunc() did correctly trigger the loading of all four script files in the correct order.
I also found this article and this article that both say pretty much the same thing - that you need to use both SP.SOD.executeFunc and SP.SOD.executeOrDelayUntilScriptLoaded in conjunction in order to get things to work.  executeFunc will trigger the script loading if it is not loaded already, but the callback function you can add there is executed immediately while the script loading is async, so you can't use it to call a function in the script you are waiting to load, so you use executeOrDelayUntilScriptLoaded to queue the function you want to run once the script finally loads.
I updated my code example to reflect that change as well, but that's still not working.  As I said, executeFunc does trigger the scripts to load, but the function I'm trying to queue with executeOrDelayUntilScriptLoaded never runs.


text:
Q: Popup form changing textbox value only once I have an asp page which calling another popup page on button click event. and few values are returned from the popup page by following code.
       function ShowSelfpopup() {var customizeParamGL = 'status:no;help:no;dialogWidth:600px;dialogHeight:550px;scrolling=no';

        var FunctionID = document.getElementById("ctl00_contPlcHdrMasterHolder_LstxtHidFUNCTION_ID").value;
        window.showModalDialog('corBrmBlockIssuAndMaintFindUI.aspx?Function_Id=' + FunctionID + '', window, customizeParamGL);
        debugger;
        if (XYZ_PID != '') {
            debugger;
            document.getElementById("ctl00_contPlcHdrMasterHolder_LsddlProductID99").value = XYZ_PID;
            document.getElementById("ctl00_contPlcHdrMasterHolder_LstxtStartNo").value = XYZ_SN;
            document.getElementById("ctl00_contPlcHdrMasterHolder_LstxtEndNo").value = XYZ_EN;
            document.getElementById("ctl00_contPlcHdrMasterHolder_lstxthide").value = XYZ_BP;

            aspnetForm.submit();
            return true;

        }
        else {
            return false;
        }

    }

Now I have a Text changed event method for LstxtEndNo. Which is firing only first time I am getting data from the popup form. next time I'm calling the popup form and getting data as i confirmed by debugging. but its neither changing values in the textbox nor firing text changed event.

A: For Javascript Dont use Textchange event instead onchange
<head runat="server">
<title>

</title>
   <script>
       function AlertTest()
       {
           alert('hELLO');
       }
   </script>
</head>
<body>
<form id="form1" runat="server">
    <ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">           </ajax:ToolkitScriptManager>
    <div>

            <asp:TextBox ID="Button1" runat="server" Text="Button" onchange="AlertTest()" />
    </div>
</form>
</body>

Try this with your example


text:
Q: How to include a .txt file content inside the Latex file How to include a .txt file contents inside a Latex file so that the generated PDF from the Latex file should record the contents of the .txt file
\verbatiminput{../../foo.txt} is not working. Doing so causes the compiler break at that line in .tex file.
Please show me a way how I can include a .txt file inside Latex so that my generated PDF file has the contents of the .txt file

A: one can use \usepackage{listings}.
And when you want to input your file use.
\lstinputlisting[caption=myfile.txt]{file.txt}.
\documentclass[draft,a4paper]{article}

\begin{filecontents*}{file.txt}
first line
second line
third line
\end{filecontents*}
\usepackage{listings}

\begin{document}

\textbf{Title}

\lstinputlisting[caption=myfile.txt]{file.txt}

 that's it.

\end{document}