text:
Q: Normal approximation to the pointwise/Hadamard/Schur product of two multivariate Gaussian/normal random variables Let $X \sim \mathcal{N}\left( {{\mu _x},\sigma _x^2} \right)$ and $Y \sim \mathcal{N}\left( {{\mu _y},\sigma _y^2} \right)$  be two univariate and independent Gaussian/normal random variables and let $Z = XY$  be their product.
It is well-known that the probability distribution of $Z$  can be approximated by the normal distribution $\mathcal{N}\left( {{\mu _x}{\mu _y},\mu _x^2\sigma _y^2 + \mu _y^2\sigma _x^2} \right)$  when $\frac{{{\mu _x}}}{{{\sigma _x}}}$  and $\frac{{{\mu _y}}}{{{\sigma _y}}}$  are large. See for instance An approach to distribution of the product of two random variables.
I'm looking for similar results in the multivariate case : $X \sim {\mathcal{N}_d}\left( {{\mu _x},{\Sigma _x}} \right)$ , $Y \sim {\mathcal{N}_d}\left( {{\mu _y},{\Sigma _y}} \right)$  and $Z$  is the pointwise/Hadamard/Schur product of $X$  and $Y$ , i.e. $Z = \left( {{x_1}{y_1},{x_2}{y_2},...,{x_d}{y_d}} \right)$.
More generally, I'm looking for references dealing with the properties of the pointwise/Hadamard/Schur products of multivariate random variables (as a generalization of the scalar product of univariate r.v.s).

A: $\newcommand{\si}{\sigma}
\newcommand{\Si}{\Sigma}
\renewcommand{\c}{\circ}
\newcommand{\tr}{\operatorname{tr}}$
Let $X_1:=X$, $X_2:=Y$, $\mu_1:=\mu_x$, $\mu_2:=\mu_y$, $\Si_1:=\Si_x$, $\Si_2:=\Si_y$, $N:=\mathcal{N}_d$. Let $Y_i:=X_i-\mu_i$. Then $X_i=\mu_i+Y_i$,  $Y_i\sim N(0,\Si_i)$, $Y_1$ and $Y_2$ are independent, and
\begin{equation*}
 X_1\c X_2=\mu_1\c\mu_2+V+Y_1\c Y_2,\quad\text{where}\quad V:=\mu_1\c Y_2+\mu_2\c Y_1
\end{equation*}
and $\c$ denotes the Hadamard product. Next,
\begin{equation*}
 V\sim N(0,\Si),\quad\text{where}\quad \Si:=D(\mu_1)\Si_2 D(\mu_1)+D(\mu_2)\Si_1 D(\mu_2)
\end{equation*}
and $D(\mu)$ is the diagonal matrix whose diagonal entries are the entries of the column matrix $\mu$; we are assuming that the matrix $\Si$ is nonsingular. Hence,
\begin{equation*}
 \Si^{-1/2}(X_1\c X_2-\mu_1\c\mu_2)=Z+\delta,\quad\text{where}\quad \delta:=\Si^{-1/2}(Y_1\c Y_2)
\end{equation*}
and $Z\sim N(0,I)$, a standard normal random vector in $\mathbb R^d$. Further,
\begin{equation*}
 E\|\delta\|^2\le\|\Si^{-1/2}\|^2 E\|Y_1\c Y_2\|^2=\|\Si^{-1}\| \tr(\Si_1\c\Si_2),
\end{equation*}
$\|v\|$ is the Euclidean norm of a vector $v$, and $\|M\|$ and $\tr M$ are the corresponding operator norm and the trace of a matrix $M$, respectively.
Thus, we come to the following conclusion: if $\mu_1$, $\mu_2$, $\Si_1$, $\Si_2$ vary in any such way that the matrix $\Si$ is nonsingular and
$$\|\Si^{-1}\| \tr(\Si_1\c\Si_2)\to0,$$
then
$$X_1\c X_2\approx N(\mu_1\c\mu_2,\Si)$$
in the sense that $\Si^{-1/2}(X_1\c X_2-\mu_1\c\mu_2)$ converges to a standard normal random vector $Z$ in distribution.
In the particular case when $\Si_i=\si_i^2 I$ for some scalars $\si_i>0$, the condition $\|\Si^{-1}\| \tr(\Si_1\c\Si_2)\to0$ becomes
\begin{equation*}
 \min\Big(\frac{\mu_1^2}{\si_1^2}+\frac{\mu_2^2}{\si_2^2}\Big)\to\infty,
\end{equation*}
where $\min v$ denotes the minimum of the entries of a (say, column) matrix $v$.
Further specializing this to the case $d=1$, we have
\begin{equation*}
X_1 X_2\approx N(\mu_1\mu_2,\mu_1^2\si_2^2+\mu_2^2\si_1^2)\quad\text{if}\quad \frac{\mu_1^2}{\si_1^2}+\frac{\mu_2^2}{\si_2^2}\to\infty.
\end{equation*}
Here, as in the paper An approach to distribution of the product of two random variables you cited, the asymptotic variance is $\mu_1^2\si_2^2+\mu_2^2\si_2^2$, not $\mu_1^2\si_2^2+\mu_2^2\si_1^2+\si_1^2\si_2^2$ as you wrote, even though the two values are relatively close to each other under the condition $\frac{\mu_1^2}{\si_1^2}+\frac{\mu_2^2}{\si_2^2}\to\infty$.
However, there are two differences between our conclusion for the special case $d=1$ and the corresponding result in the cited paper: (i) there, the statement is not rigorous, saying that something tends to a "limit" that is in fact varying with $\mu_1$, $\mu_2$, $\si_1$, $\si_2$ and (ii) the condition there for such a "convergence" appears to be that both $\frac{\mu_1}{\si_1}$ and $\frac{\mu_2}{\si_2}$ "increase", whereas here we show that it is enough to have $\frac{\mu_1^2}{\si_1^2}+\frac{\mu_2^2}{\si_2^2}\to\infty$ -- that is, it is enough that at least one of the ratios $\frac{|\mu_1|}{\si_1}$ or $\frac{|\mu_2|}{\si_2}$ go to $\infty$.


text:
Q: insertSubview: AtIndex: does not work I went through the material regarding this issue but still can't figure it out completely.
The main issue is that i am using this method but the view does not show...
The app is built out of two view - the main one (i added it as a subview to the main nib) -
Has of a text field where i write some text.
Has a button that when pressed, the action method loads a second view that has a label with some text in it.
the source code of the first viewController:
#import <UIKit/UIKit.h>

@class TxtRunnerViewController;

@interface Itai_s_text_app_take_2ViewController : UIViewController {
 int sliderSpeed;
 IBOutlet UITextField  *textInput;
 TxtRunnerViewController *trvc;
}

@property (nonatomic, retain) IBOutlet UITextField *textInput;
@property (retain, nonatomic) TxtRunnerViewController *trvc;

- (IBAction)sliderChanged:(id)sender;//speed of text show changed

- (IBAction)textFieldDoneEditing:(id)sender;//dor 'DONE' on keyboard
- (IBAction)backgroundTap:(id)sender;//for handling tapping on background

- (IBAction)textEmButtonPressed:(id)sender;

@end

the .m of the first ViewController:
    #import "Itai_s_text_app_take_2ViewController.h"
    #import "TxtRunnerViewController.h"
@implementation Itai_s_text_app_take_2ViewController
@synthesize textInput;
@synthesize trvc;

- (IBAction)sliderChanged:(id)sender
{
 UISlider *slider = (UISlider *)sender;
 sliderSpeed =  (int)(slider.value + 0.5f);//setting the speed determinned by the usr in slider
 NSLog(@"Slider value is %@", sliderSpeed);
}

- (IBAction)textFieldDoneEditing:(id)sender
{
    [sender resignFirstResponder];
 NSLog(@"our text input  is %@", textInput.text);
}

- (IBAction)backgroundTap:(id)sender
{
 [textInput resignFirstResponder];
}

- (IBAction)textEmButtonPressed:(id)sender
{
 NSLog(@"button pressed");
 if ([textInput.text length]==0)
 {
  NSString *msg = nil;
  msg = @"Write text to transmit";
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Forgot something?"
              message:msg
                delegate:self
             cancelButtonTitle:@"Back"
             otherButtonTitles:nil];

  [alert show];
  [alert release];
  [msg release];
 }
 else { //init
  NSLog(@"HI!");
  if (self.trvc == nil)
  {
   NSLog(@"if accepted");
   TxtRunnerViewController *tr = [[TxtRunnerViewController alloc] initWithNibName:@"TxtRunner"
                       bundle:nil];
   self.trvc = tr;
   [tr release];
  }
  [self.view removeFromSuperview];
  [self.view insertSubview:trvc.view atIndex:0];
  NSLog(@"InsertAtIndex was operated...!");
  //[self.view addSubview:tvc.view];
 }

}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
 // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

 // Release any cached data, images, etc that aren't in use.
 if(self.trvc.view.superview == nil)
  self.trvc = nil;
}

- (void)viewDidUnload {
 // Release any retained subviews of the main view.
 // e.g. self.myOutlet = nil;
}

- (void)dealloc {
 [trvc release];
    [super dealloc];
}

The second View is simply empty (has a label added to it in it's nib file):
    #import
@interface TxtRunnerViewController : UIViewController {

}

@end

It's .m file is the default one, added no code to it.
When i press the button in the first view - it's view disappears but the second view does not appear instead, only a blank white view appears, nothing on it.
Doe

A: The line:
[self.view removeFromSuperview];
Removes the view from its super
then the call
[self.view insertSubview:trvc.view atIndex:0];

Adds trvc to it - but that view has been removed and not visible anymore.
You need to add trvc to the superview.

A: If you push the TxtRunnerViewController it will completely hide the first one, but it still exist in background. (without removeFromSuperview)
TxtRunnerViewController *vw = [[TxtRunnerViewController alloc]initWithNibName:@"TxtRunner" bundle:nil];
[self.view pushViewController:vw.view animated:NO];
[vw release];

To remove the first view it's a bit more difficult. You would need to implement a delegate in RootViewController which will be fired after clicking the done Button of the first view. Then in your RootViewController some code is executed which displays the second view and removes the first view.
For a delegate sample open the Utility Application Sample when creating a new project and figure out how it works or search some examples online.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Difference between custom serialisation and Externalisation? Recently from any source, I came to know that custom serialisation is a process where we can define writeObject(ObjectOutputStream os) and readObject(ObjectInputStream is) in our Serializable class, and these methods will be executed at the time of serialisation and de-serialisation respectively to perform our functionality.
Later on, I came to know that Externalisation is an interface which defines 2 methods:
1- writeExternal()
2- readExternal()
Our class can implement Externalizable and override these methods when we don't want to serialise whole object. These methods will be executed at the time of serialisation and de-serialisation.
I have a doubt that why can't we use custom serialisation by implementing Serializable and defining writeObject(ObjectOutputStream os) and readObject(ObjectInputStream is) methods even to serialise some attributes of an object. Why this externalisation came into the picture.
Thanks,

A: Externalizable was introduced way before Serializable interface during JDK 1.1 days. During that time, the programmer had to write the exact logic how the object shall be serialized, ie, everything that shall occur inside the writeExternal() and readExternal() had to be written explicitly. Serializable was introduced later to get rid of this headache.
But in some cases, using Externalizable has its own advantages as it allows you to define how the class shall be serialized in your own way rather than depending on what is defined underneath the hood by Java language APIs. I think your class may fall under this category.
To answer your question added in the last part, you can achieve selective serialization of members inside a class by marking them as transient.


text:
Q: Connect VirtualBox VM running Ubuntu to VPN I would like to connect my VirtualBox VM running Ubuntu 10.04.4 to a VPN or share the host's VPN connection.  The VM is connected to the internet and issued an IP from my wireless router but it is not sharing the VPN connection that the host has established.  Is there a way to do this.  The host OS is Mac OSX 10.8.5.

A: You could change the networking mode of the VM to use NAT instead of Bridged.  Using NAT should make the VM use the host computer's internet connection, and in turn use the VPN to connect to the internet.


text:
Q: How to Create ImageBrush in C# code In XAML:
    <Rectangle Stroke="Aqua" Opacity="0.7" StrokeThickness="10" Canvas.Left="24" Canvas.Top="22" Height="86" Width="102">
        <Rectangle.Fill>
            <ImageBrush ImageSource="C:\Users\xiaorui.dong\Pictures\profile.jpeg"></ImageBrush>
        </Rectangle.Fill>
    </Rectangle>

XAML works fine, but how to create the above ImageBrush in C# code:
C# should be like this:
Rectangle rectangle = new Rectangle();
rectangle.StrokeThickness = 10;
rectangle.Height = 200;
rectangle.Width = 100;
rectangle.SetValue(Canvas.LeftProperty, 100d);
rectangle.SetValue(Canvas.TopProperty, 100d);
rectangle.Fill = new ImageBrush(new BitmapImage(new Uri(@"C:\Users\xiaorui.dong\Pictures\profile.jpeg")));

A: In c# you can use it like , first thing is remove the fill from XAML then use the same code in c# as you have used it . It must work.
ImageBrush ib = new ImageBrush();

ib.ImageSource = new BitmapImage(new Uri("your path",UriKind.Relative));
rectangle.Fill = ib;

A: This code creates ImageBrush using image "Assets/image.png" which is part of the UWP project. Relative paths are unavailable in UWP version of ImageBrush.
var imageBrush = new ImageBrush();
imageBrush.ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/image.png"));

A: I'm guessing the problem is with locating the image and that the exception you're getting is because you don't provide the UriKind parameter. Try giving UriKind.Relative as a parameter to the Uri:
rectangle.Fill = new ImageBrush(new BitmapImage(
    new Uri(@"C:\Users\xiaorui.dong\Pictures\profile.jpeg", UriKind.Relative)));


text:
Q: How to get total time of differences in user interactions in MySQL I have a mysql table with the following fields:
_id, userId, objectId, timeStamp
I want to calculate the total time an object was interacted with by all users.
I created the query that calculates the time difference between a row and its subsequent row but this doesn't take into consideration the order of actions by a given user.  That query looks like this:
SELECT A._id, A.USERID, A.objectid, A.timeStamp,
    SUBSTRING(A.timeStamp, 12, 2) as hourOfDay,
    TIME_TO_SEC(TIMEDIFF(B.timeStamp, A.timeStamp)) as diff
FROM InteractionsTBL A
INNER JOIN InteractionsTBL B ON B._id = (A._id + 1) and B.USERID = A.USERID
where A.timeStamp > '2012-04-18 1:00:00'
and A.timeStamp < '2012-04-18 23:59:00'
group by hourOfDay, A.objectid
ORDER BY A._id ASC

How do I calculate the sum total of time interaction with an object by all users grouped by the hour of the day and the objectId?

A: I ended up writing a pearl script to go in and calculate this difference after the fact.  I'm not sure if this is possible in real time with SQL.


text:
Q: Create centered patches in each image pixel for 2D image Hi guys I am trying to create patches from a 2D image. I need that these patches must be centered in each pixel image. I am using this code:
#patches for each point in 2D slice
patch_size = 27
pacth_m_size = patch_size//2
for x in range(0, sld_arr_norm.shape[0]):
    for y in range(0, sld_arr_norm.shape[1]):
        if x-pacth_m_size>0: # if all is ok the get the patch
            if y-pacth_m_size>0:
                if x+pacth_m_size<sld_arr_norm.shape[1]:
                    if y+pacth_m_size<sld_arr_norm.shape[1]:
                        x_i = x-pacth_m_size
                        x_s = x+pacth_m_size+1
                        y_i = y-pacth_m_size
                        y_s = y+pacth_m_size+1
                        curr_patch= sld_arr_norm[x_i:x_s, y_i:y_s]
                        assert curr_patch.shape == (patch_size, patch_size)
                        print(curr_patch.shape)
        else:
            x_i = x-pacth_m_size
            x_s = x+pacth_m_size+1
            y_i = y-pacth_m_size
            y_s = y+pacth_m_size+1
            if x-pacth_m_size<0:
                issue_patch = sld_arr_norm[0:x_s, y_i:y_s]
                curr_patch  = np.zeros((patch_size, patch_size))
                star_index  = abs(x-pacth_m_size)
                curr_pacth[star_index:,:]=issue_patch.copy()
            if y-pacth_m_size<0:
                issue_patch = sld_arr_norm[x_i:x_s, 0:y_s]
                curr_patch  = np.zeros((patch_size, patch_size))
                star_index  = abs(y_i)
                curr_pacth[:, star_index:]=issue_patch.copy()
            if y+pacth_m_size>sld_arr_norm.shape[1]:
                issue_patch = sld_arr_norm[x_i:x_s, y_i:y_s]
                curr_patch  = np.zeros((patch_size, patch_size))
                end_index   = abs(y_s-issue_patch.shape[1])
                curr_patch[0:, 0:curr_patch.shape[1]-end_index]=issue_patch.copy() #issue_patch[x_i:x_s, y_i:issue_patch.shape[1]]
            if x+pacth_m_size>sld_arr_norm.shape[0]:
               issue_patch = sld_arr_norm[x_i:x_s, y_i:y_s]
               curr_patch  = np.zeros((patch_size, patch_size))
               end_index   = abs(x_s-issue_patch.shape[0])
               curr_patch[0:arr_zeros.shape[0]-end_index, :]=issue_patch.copy()
            assert curr_patch.shape == (patch_size, patch_size)
            print(curr_patch.shape)

The problems are in the borders of the image I am facing some issues like the patches do not relly to the defined patch size. Do you know any library that permits creating patches in this way?

A: the best way to do this is by first padding the whole image. Then, we can proceed to extract patches without worried about the edges. The code is show bellow:
#Define patch size
patch_size   = 13
pacth_m_size = patch_size//2
#Patch the whole image
sld_arr_norm_pad = np.pad(sld_arr_norm, pacth_m_size, 'wrap')
for x in range(0, sld_arr_norm.shape[0]):
    for y in range(0, sld_arr_norm.shape[1]):
        x_real = x + pacth_m_size
        y_real = y + pacth_m_size

        x_i = x_real - pacth_m_size
        x_s = x_real + pacth_m_size + 1
        y_i = y_real - pacth_m_size
        y_s = y_real + pacth_m_size + 1

        curr_patch = sld_arr_norm_pad[x_i:x_s, y_i:y_s]
        print(curr_patch.shape)
        print((x_i, x_s, y_i, y_s))
        assert curr_patch.shape == (patch_size, patch_size)

Hope this helps others.


text:
Q: Does the lift-json JValue class have the equivalent of the scala.xml.Node.text method? When working with scala xml, I find the Node.text method extremely handy.  It converts all types of objects into a workable string, which can they cast to the data type you expect (and of course, explode for unexpected data).
Does the lift-json JValue class have a similar method?

A: I thinks the closest one to that function is 'values'. It returns the pure value wrapped in JValue.
scala> JInt(1).values
res0: BigInt = 1

scala> JString("1").values
res1: String = 1

scala> JBool(true).values
res2: Boolean = true

scala> JArray(List(JInt(1), JInt(2))).values
res3: List[Any] = List(1, 2)


text:
Q: How to get a JavaScript number as a string using Node-API I'm building a Node.js addon using Node-API.
The logic has been simplified as below,
Use pass js array into the addon and get some filtered array as the output.
Inside the addon, the algorithm will skip any empty strings and false values.
Below is the code snipped of the usage. The whole addon available here: https://replit.com/@dinindu/node-api-addon-compact#addon.c
const addon = require("bindings")("addon.node");

const array = ['0', false, '', {a:'1'}, '2', "str"];
console.log(addon.compact(array)); // expected output: ['0', {a:'1'}, '2', "str"]

// addon.c
#include <assert.h>
#include <node_api.h>
#include <stdlib.h>

#define DECLARE_NAPI_METHOD(name, func) \
  { name, 0, func, 0, 0, 0, napi_default, 0 }

#define DECLARE_WITH_STATUS_CHECK(size, name, func)                       \
  napi_property_descriptor func##_desc = DECLARE_NAPI_METHOD(name, func); \
  status = napi_define_properties(env, exports, size, &func##_desc);      \
  assert(status == napi_ok);

static napi_value compact(napi_env env, napi_callback_info info) {
  size_t argc = 1;
  napi_value args[1];
  napi_get_cb_info(env, info, &argc, args, NULL, NULL);

  uint32_t length;
  napi_get_array_length(env, args[0], &length);

  napi_value output_array;
  napi_create_array_with_length(env, NAPI_AUTO_LENGTH, &output_array);

  uint32_t result_index = 0;
  for (size_t i = 0; i < length; i++) {
    napi_value value;
    napi_get_element(env, args[0], i, &value);

    napi_valuetype type;
    napi_typeof(env, value, &type);

    if (type == napi_boolean) {
      bool result;
      napi_get_value_bool(env, value, &result);
      if (result == false) continue;
    }

    char* str_buffer;
    bool str_found = false;
    if (type == napi_string) {
      size_t str_buffer_size;
      napi_get_value_string_utf8(env, value, NULL, 0, &str_buffer_size);

      str_buffer = (char*)calloc(str_buffer_size + 1, sizeof(char));
      size_t str_result;
      napi_get_value_string_utf8(env, value, str_buffer, str_buffer_size, &str_result);

      str_found = true;
      if (*str_buffer == '\0') {
        free(str_buffer);
        str_found = false;
        continue;
      }
    }

    napi_set_element(env, output_array, result_index, value);
    result_index++;
    if (str_found) free(str_buffer);
  }

  return output_array;
}

static napi_value Init(napi_env env, napi_value exports) {
  napi_status status;
  DECLARE_WITH_STATUS_CHECK(1, "compact", compact)
  return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)

What I don't understand is, the expected output should contain all values except false and ''. But it seems to skip '0' and '2' as well, which means number characters. I tested it by adding another number after it ('01') and then it works.
Why this is happening? Why C is skipping single character numbers? And how can I get my expected output?
Thanks in advance.

A: I got resolved this after digging through Node.js source code and making this change,
I replaced,
napi_get_value_string_utf8(env, value, str_buffer, str_buffer_size, &str_result);

with
napi_get_value_string_utf8(env, value, str_buffer, str_buffer_size + 1, &str_result);

Adding 1 to str_buffer_size simply solves the problem. But I don't understand why, but it fixes my problem anyway.
This helped me to solve this


text:
Q: inserting string from pandas dataframe gives TypeError: not all arguments converted during string formatting Set-up
Using python to access the Shopify API of various shops.
Currently, there's only a need to connect with 1 shop, but more shops will follow in the future so I want to prepare the code for it to be able to handle multiple shops in the future.

Code
import shopify
shop_url = "https://%s:%s@myshopsurl.com/admin/api/%s" % (API_KEY, PASSWORD, API_VERSION)
shopify.ShopifyResource.set_site(shop_url)

which connects correctly to myshopsurl.com.
Defining the shop_url like below also works fine,
shop_url = "https://%s:%s@myshopsurl.com/admin/api/%s" % (keys['API_KEY'][0], keys['PASSWORD'][0], API_VERSION)

where I pull myshopsurl.com's API_KEY and PASSWORD from a prior constructed keys panda dataframe.

Issue
Now, if I want to pull myshopsurl.com's url (i.e. 'myshopsurl.com') from keys like so,
shop_url = "https://%s:%s@" + keys['url'][0] + "/admin/api/%s" % (keys['API_KEY'][0], keys['PASSWORD'][0], API_VERSION)

then I receive a TypeError: not all arguments converted during string formatting.

Question
How do correctly insert myshopsurl.com's url from keys in the shop_url variable?

A: Following @Evan's comment,
shop_url = "https://%s:%s@%s/admin/api/%s" % (keys['API_KEY'][0], keys['PASSWORD'][0], keys['url'][0], API_VERSION)

solves it.


text:
Q: Node.js Mongoose static function not getting called Recently i've been trying to rewrite my node.js express app to be more in line with the mvc principle. I've also been trying to incorporate mongoose. I'm having a problem with calling the static functions on a mongoose model.
userSchema.statics.findDuplicates = function (cb) {
    console.log("Duplicates called");

    this.findOne({ email: this.email }, function(err, result){
        if (err) throw err;
        if (result) {
            cb("A user with this email has already been created.");
        } else {
            cb("");
        }
    });
}

Now the problem is that i'm later exporting a model using this schema, so this is all contained in one file:
module.exports = mongoose.model('User', userSchema);

When i later call this inside a controller, (obviously requiring and initiating the model beforehand):
user.findDuplicates(function(result){

    if (result) {
        res.send("Selle e-mailiga kasutaja on juba loodud.");
        console.log("Duplicates");
    } else {
        user.save();
        res.send("Kasutaja loodud.");
        console.log("User created with password.")
    }
});

It just never gets called. Node tells me it accepted a post, but got a 500 internal server error, and the "Duplicates called" inside findDuplicates does not appear in the console. Something is very wrong here, and i do not know how to fix it.
EDIT: Full controller code:
var express = require('express');
var router = express.Router();

var User = require("../models/user.js");

router.get('/', function(req, res, next) {
    res.render('users',{title: "Lisa kasutaja"});
});

router.post('/', function(req, res, next) {
    var query = req.body;
    var message = "";

    console.log("Post recieved " + JSON.stringify(query));

    if (query.password != query.repeatPassword){
        res.send("Paroolid ei ole võrdsed.");
        console.log("Passwords don't match");
    } else {
        var user = new User({
            firstName: query.firstName,
            lastName: query.lastName,
            telephone: query.telephone,
            email: query.email,
            password: query.password
        });

        console.log("User created");

        user.findDuplicates(function(result){

            if (result) {
                res.send("Selle e-mailiga kasutaja on juba loodud.");
                console.log("Duplicates");
             } else {
                user.save();
                res.send("Kasutaja loodud.");
                console.log("User created with password.")
            }
        });
    }

});

module.exports = router;

A: Your problem resides in the fact that you're calling a static method in an instance of a model, which is not correct. See the difference below:
// if you define a static method
userSchema.statics.findDuplicates = function (cb) {
  // do your stuff
}

// you call it this way
var User = require("../models/user.js");
User.findDuplicates(function (result) {
  // do your stuff
});

// if you define an instance method
userSchema.methods.findDuplicates = function (cb) {
  // do your stuff
};

// you call it this way (on an instance of your model)
var User = require("../models/user.js");
var user = new User({
      firstName: query.firstName,
      lastName: query.lastName,
      telephone: query.telephone,
      email: query.email,
      password: query.password
    });
user.findDuplicates(function (result) {
  // do your stuff
});


text:
Q: Sequelize m:n relation: Access association in beforeHook So in Sequelize I have two models ModelA and ModelB that have many to many relation between them. Then I call instanceA.createModelB() to create instance of ModelB and associate it with instanceA. Now I have a beforeCreate hook on ModelB, like this:
beforeCreate(instance, options) {
  return instance.countA().then(associations => {
     console.log(associations);
  })
}

It returns 0, because the relation between instanceA and instanceB is created only after all hooks were run.
I need to do some checks related to instanceA before I can create instanceB. Can I somewhow access the relation in the hooks, as that would be the best place to perform the checks? I know I can do it everytime before calling instanceA.createModelB() but I call it in many differnt places so I would like to do it in a more centralized way.


text:
Q: CreateWindow return null error I am developing an application using the win32 api, but I have a problem. I wrote code to create a simple window and then create simple button attached to this window and finally create simple menu resource and set it to the window:
#include<Windows.h>
#include"resource.h"

#define DEFAULT_BUTTON_WIDTH 100
#define DEFAULT_BUTTON_HEIGHT 20

HMENU Menu;
HWND Window;
HWND bCreateWall;

void WMCommand(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    if (lParam == (LPARAM)bCreateWall) MessageBox (Window, (LPCWSTR)"You Pressed bCreateWall", (LPCWSTR)"Congrats!", MB_OK);
    else if (wParam == ID_FILE_EXIT) PostQuitMessage(0);
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam){
    switch(msg){
    case WM_DESTROY:PostQuitMessage(0);break;
    case WM_COMMAND: WMCommand (hWnd, msg, wParam, lParam); break;
    }
    return (DefWindowProc(hWnd,msg,wParam,lParam));
}

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevious, LPSTR lpCmdString,int CmdShow)
{
    WNDCLASS wc;
    MSG msg;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wc.hCursor = LoadCursor (NULL, IDC_ARROW);
    wc.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wc.hInstance = hInstance;
    wc.lpfnWndProc = WndProc;
    wc.lpszClassName = (LPCWSTR)"ME";
    wc.lpszMenuName = NULL;
    wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;

    if (!RegisterClass(&wc))
    {
        MessageBox (NULL,(LPCWSTR)"Error: Cannot Register Class", (LPCWSTR)"ERROR!", MB_OK);
        return (0);
    }

    //create window
    Window = CreateWindow((LPCWSTR)"ME",(LPCWSTR) "Map Editor", WS_OVERLAPPEDWINDOW | WS_VISIBLE,0, 0, 640, 480, NULL, NULL, hInstance, NULL);
    if (Window == NULL)
    {
        MessageBox (NULL,(LPCWSTR)"Error: Failed to Create Window", (LPCWSTR)"ERROR!", MB_OK);
        return (0);
    }

    //create button to create wall
    bCreateWall = CreateWindow((LPCWSTR)"BUTTON", (LPCWSTR)"Create Wall", WS_CHILD | WS_VISIBLE, 0, 100, DEFAULT_BUTTON_WIDTH, DEFAULT_BUTTON_HEIGHT, Window,NULL, hInstance, NULL);
    if (bCreateWall== NULL)
    {
        MessageBox (NULL, (LPCWSTR)"Error: Failed to Create Window",(LPCWSTR) "ERROR!", MB_OK);
        return (0);
    }

    Menu = LoadMenu (hInstance, MAKEINTRESOURCE(IDR_MENU));
    SetMenu (Window, Menu);

    while (1)
    {
        if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
        {
            if (msg.message == WM_QUIT) break;
            TranslateMessage(&msg);
            DispatchMessage (&msg);
        }
    }

    return 1;
}

When this runs, the window is blank and the menu and the button aren't added.

the method createWindow return null

What have I done wrong?

A: Firs of all, I would suggest to decide on your code formatting. It looks to me that you have used pieces of code from different sources.
If I were you I would stick with default VS formatting. One liners like this:
if (lParam == (LPARAM)bCreateWall) MessageBox (Window, L"You Pressed bCreateWall", L"Congrats!", MB_OK);
else if (wParam == ID_FILE_EXIT) PostQuitMessage(0);

make the code very difficult to read. Why not to use blocks of code with single line for each code piece:
if(lParam == (LPARAM)bCreateWall)
{
    MessageBox (Window, L"You Pressed bCreateWall", L"Congrats!", MB_OK);
}
else if(wParam == ID_FILE_EXIT)
{
    PostQuitMessage(0);
}

Also, curly brackets are mixed and that does not help analyzing the code. Spacing between delimiters also inconsistent. Be consistent in formatting do not be sloppy; this is a part of the good programming practice.
When you run your app you can see a message box saying something but you see only a garbage characters.
Your problem is that you are compiling project set for using UNICODE characters but all string are ANSI. You merely cast ANSI string to LPWSTR and that is not enough to convert strings.
Your code fails to create button since class named "啂呔乏" you end up with using (LPWSTR)"BUTTON" does not exist.
Either convert all string to generic formatting using _T("string"), TEXT("string") or use only UNICODE strings.
Replace all (LPCWSTR) with L proceeding quoted string: L"string" and try again.


text:
Q: How to make WINE be quiet about MSVCR errors? I downloaded the Python 2.7 MSI installer for Windows and proceeded to install it with Wine. It worked without any problems.
However, running wine python.exe leads to a whole bunch of these errors:

fixme:msvcrt:MSVCRT__sopen : pmode 0x81b6 ignored

The application technically works, but is very hard to use because of these error messages. (They come up multiple times while the program is running.)
Is there a way to tell Wine to ignore these messages?

A: You can have a lot of control on the wine error output, to turn off all the fixme, just run:
WINEDEBUG=fixme-all wine python.exe program

You can read the wine man page to find all the possible options.


text:
Q: Automatic holding page for any sites pointing to my IP I have loads of domains all pointing to my servers IP but because they are just holding domains I haven't configured them in WHM / Apache. Therefore they just get "can't display website" messages when visited.
Is it possible to set up rule (or whatever! (Virtual Host?)) that will point any domains not configured on my server (but pointed to it) to a generic holding page?
I was thinking I could use a VirtualHost like this:
<VirtualHost 123.123.123.123:80>
DocumentRoot /www/path/to/holding/account/
ServerName *
</VirtualHost>

Hope that makes sense!
Thanks

A: Just omit the ServerName directive.
From my /etc/apache2/sites-enabled/000-default - note that only the DocumentRoot directive is needed:
<VirtualHost *:80>
    DocumentRoot /var/www/default

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>


text:
Q: How do we specify the signal frequency while interfacing DAC 0800 with 8086? I am relatively new to Microprocessors and just started with my uni course on the same. My faculty while discussing the question:

gave us the following solution:

What I don't understand here is how he chose the value of FFh to get the required wave frequency of 500Hz. I get it has something to do with the 8086 frequency and the time it takes to run the loop once. But what is the relation exactly? How did the author and my faculty arrive at the value of FFh to get the required frequency?

A: The values 00h and 255 are chosen because the ramp is made to go from 0 to 255 and back to 0. The values are output as fast as possible in a loop.
The CPU just has a clock of 8 MHz, it does not execute 8 million instructions per second, because most instructions take more than 1 clock cycle to execute. The actual cycles how much each CPU instruction takes are found in the CPU manuals.

*

*OUT immed8, accumulator = 10 cycles

*INC reg8 = 3 cycles

*CMP reg, immed = 4 cycles

*JB = 16 cycles if jump taken, 4 cycles if jump not taken

So each loop takes 33 clock cycles.
Which means that the DAC output updates at a rate of 8 MHz / 33 = 242 kHz, which means that a cycle of triangle wave takes 512 updates so the resulting triangle wave frequency is about 473 Hz - close enough to 500 Hz.


text:
Q: Is Rhino the only interpreter with support for sandboxing and serializable continuations? I need (a) sandboxing, and (b) serializeable continuations. I'm exposing server-side game scripting to users, and it is extremely async, thus the callback pattern makes code un-readable and very un-approachable for newbie programmers. A continuation-passing style is an alternative, but has the same drawbacks. Async in the sense that a query to the user may take months to complete.
See http://weaverengine.com/platforms for my full list
Serializeable continuations seem like a very elegant solution, but few interpreters support them.
So far, it seems that my only option is Rhino. I was hoping that NodeJS or PyPy would work, but the evidence so far points to the contrary.
Lua seems to support coroutines, but I can't find any information on whether it supports serializeable continuations. Lua does sandboxing well.
NodeJS has Jefe to offer really nice sandboxing, but nothing so far regarding continuation serialization.
PyPy also hasn't yet refined their sandboxing and serializeable continuation support to the point where they can be used together, from what I understood on the pypy-dev mailing list.
JavaFlow hints that if all classes implement Serializeable, then java continuations could be serialized. But unless I can run an interpreter for a nice dynamic language on top of JavaFlow, I'm not interested.
Is Java and Rhino my only option?
Is there a branch of NodeJS with continuation support? Any reasonably nice, dynamic language that meets these criteria?

A: I'm suprised you did not mention Scheme, as that is the language where continuations where pioneered. SISC for example is a Scheme interpreter running on the JVM that supports serializable continuations. These are used for example in the SISCweb framework.
For sandboxing you could use the builtin security features of the jvm.

A: It should be possible to serialize continuations in Gambit-C.

A: I ended up using Lua 5.1.4 and Pluto. Seems to be a good choice so far.


text:
Q: Visual Studio 2010 Express Limitations What are the limitations of VS2010 C# Express Edition compared with the paid for versions? I was mostly looking into what sort of applications I can build, in VS Express I only have the option of Console, Winform and DLL, etc. I read that you can build services and add - ins for office programs, is this functionality available in Professional/Ultimate etc versions? Thanks.

A: The Express edition does not come with, nor does it grant you permission to distribute, the Microsoft C++ runtime redistributable packages. So the users of the software you build with the Express edition will have to download & run the installers themselves.

A: There's a comparison chart here - You'll need VS Professional to develop Office Plugins.
Although previous version, there is a definitive overview of the VS2008 Express limitations in in this SO Question
Wikipedia also explains the differences.
Edit
The comparison chart link is dead. For 2012:

*

*Visual Studio 2012 (Web Only) comparison is here, and in this Programmer's post

*This SO post addresses the Desktop comparison.


text:
Q: Most efficient way of determining in which range a number is? My application generates a random integer between 0 and 1000.
I have 5 ranges: 0-50, 51-250, 251-500, 501-700, 701-1000. (Note that the range sizes are not equal.)
I will call these ranges: "0","50","250","500","700", respectively (will store those names in my database).
I know that i could do the following:
if ($number > 700 && $number <=1000)
       $num_range='700';

else if...

... and so on.
But is there a more efficient way of doing it?
Thanks a lot in advance. Regards

A: Utilize elseif efficiently:
if($number <= 50)
    $num_range='0';
elseif($number <= 250)
    $num_range='50';
elseif($number <= 500)
    $num_range='250';
elseif($number <= 700)
    $num_range='500';
elseif($number <= 1000)
    $num_range='700';
...

A: $ranges = array(0,50,250,500,700,1000....);
$number = ....;

foreach($ranges as $range){
 if ($number>$range)
     continue;
 else
     return prev($ranges);
}

A: $startPoints = array(700, 500, 250, 50);

$num_range = 0;
foreach ($startPoints as $from) {
    if ($number >= $from) {
        $num_range = $from;
        break;
    }
}

A: $range[0] = range(0, 49);
$range[50] = range(50, 249);
$range[250] = range(250, 499);
....

then do:
foreach($range as $r => $vals){
    if(in_array($number, $vals)){
        echo "Number is in range: $r";
    }
}


text:
Q: Can I change the color of my lips? Playing Mass Effect: Andromeda, I have my character customized to be exactly as I want... except one thing. The lips on my character are a godawful shade of bright pink, and do not match at all with my complexion.
I tried to look for a way to change it in the character creator, but I couldn't find it. I've also searched all over for a console command to fix it and came up with the same result.
So that leads me to this question of how can I change my character's lip color; both during character creation for future reference and after the character has been created?

A: There's not actually a way to change the lip's base color. However, you can choose to apply lipstick to your character and modify the color and opacity to get the exact shade you want to make your character as desired.
From this guide that lists all customization options and settings, these are the only lip settings:

*

*Mouth – Lip Thickness

*Lipstick Color

I can't speak for the shape of the lips (I was a bit disappointed with the small window of variance of a lot of the facial features), but the color should be easy enough to get exactly what you want.
Unfortunately, once you've created your character at the beginning of the game, there is no way to change it without starting a new game. This has been mentioned on multiple sites, such as this one:

BioWare chose not to include a character editor or appearance modifier. What you design at the beginning of the game can't be changed through conventional means.


text:
Q: MySQL - Duplicate entry for key XXX my only entries in table is:
SQL: SELECT * FROM `harmfull_hours` WHERE `date` >= '2014-06-01' LIMIT 0, 30 ;
result: 3
id  date        user_id        number_hours
53  2014-06-01  00239 [->]     60
68  2014-06-01  00728 [->]     44
87  2014-06-01  oi0au1on [->]  54

and when i wanted to add row with this sql query
 INSERT INTO `kadry`.`harmfull_hours` (
   `id` ,
   `date` ,
   `user_id` ,
   `number_hours`
 )
 VALUES (
   NULL , '2014-06-30', '01325', '54'
)

i got this error #1062 - Duplicate entry '01325' for key 'user_id_2'
 i tried to find user_id_2 but in information_schema
CONSTRAINT_CATALOG  CONSTRAINT_SCHEMA   CONSTRAINT_NAME     TABLE_CATALOG   TABLE_SCHEMA    TABLE_NAME          COLUMN_NAME     ORDINAL_POSITION    POSITION_IN_UNIQUE_CONSTRAINT   REFERENCED_TABLE_SCHEMA     REFERENCED_TABLE_NAME   REFERENCED_COLUMN_NAME
def                     kadry [->]          user_id_2           def             kadry [->]      harmfull_hours  user_id         1                   NULL                            NULL                        NULL                        NULL
def                     kadry [->]          user_harm_id        def             kadry [->]      harmfull_hours  user_id         1                   1                               kadry                       users                       id

and i can't find any solution ?


text:
Q: Jquery selecting one out off multiple classes I have a drop down list in which option elements have multiple classes. These classes are dynamically generated and assigned so I don't want to hard code.
  <select class="currency_switcher">
    <option value="#" class="reset default active" data-currencycode="USD">USD</option>
    <option value="#" class="" data-currencycode="EUR">EUR</option>
  </select>

Basically I want to check if whether the selected option has active class. As you can see active is one out of many possible classes assigned to the option. I am doing this on change event:
if($('select.currency_switcher option:selected').attr('class')=="active")
    {
    alert("Hello");
    }

But this returns false even when the current option has active class. So how do I solve this?
Ahmar

A: Check for active class, using hasClass:
if ($(this).children('option:selected').hasClass('active')) {
    alert("Hello");
}


text:
Q: How to determine x, y coordinates when adding text in metafor I'm using the metafor package to create Forest plots in R. I'd like to add text to my plots to create labels using the text() function. I'm wondering what the simplest way is to determine the x,y coordinates of where I want my text to go. Currently I just guess and see how it looks and then edit as necessary. Is there a way to overlay a grid over my plot or something to guide me (and then remove it after)?
Thank you!

A: Start by saving what forest() returns:
x <- forest(res)

And then take a look at x. Among other things, it contains xlim and ylim, which are the x-axis and y-axis limits. Try this:
abline(v=x$xlim)
abline(h=x$ylim)

Also useful:
text(x$xlim[1], x$rows, x$rows, xpd=NA)

I hope this helps.


text:
Q: Cannot compile with boost? Attempting to create a simple WebSocket c++ application, the library I am using relies on boost.
I have attempted to add boost to my project but it refuses to compile, heres my cpp file
#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>

#include <websocketpp/common/thread.hpp>
#include <websocketpp/common/memory.hpp>

#include <cstdlib>
#include <iostream>
#include <map>
#include <string>
#include <sstream>

main()
{
    printf("Hello World\n");
    return 0;
}

I am attemting to compile it with g++ -I. -Iboost_1_58_0 /home/cabox/workspace/main.cpp -o /home/cabox/workspace/bin/exe, but all i get is
In function `__static_initialization_and_destruction_0(int,int)':
main.cpp:(.text+0xfba): undefined reference to`boost::system::generic_category()'

My folder layout is just my Main.cpp file, the boost_1_58_0 & the websocketpp folders all being in the same parent directory, what is it I'm doing wrong?

A: Add
-lboost_system

(see also What is an undefined reference/unresolved external symbol error and how do I fix it?)
Optionally specify the library directory with -L
Make sure it's after the cpps
Undefined reference to boost::system::generic_category despite linking with boost_system


text:
Q: Android Theme style file merge Describe my situation in short, I have a multi themes project with style.xml and style.xml(v21). The only difference of these two versions is that in each theme of v21 version has these two line in addition:
<item name="android:navigationBarColor">?attr/colorPrimaryDark</item>
 <item name="android:statusBarColor">?attr/colorPrimaryDark</item>
And I don't what two maintain two style files since they are too familiar, so is there any way I can merge these two style xml file ,or make the v21 one extends style.xml and when I what to make some modification, I only have to work with style.xml

A: Is this what you mean?
Place this in your "Normal" theme folder
<!--Standard-->
<style name="CommonTheme" parent="Theme.AppCompat.NoActionBar">
    <!--Place all common elements here-->
</style>

<!--Standard-->
<style name="AppTheme" parent="CommonTheme">

</style>

Place this in your V21 folder
<!--V21-->
<style name="AppTheme" parent="CommonTheme">
    <item name="android:navigationBarColor">?attr/colorPrimaryDark</item>
    <item name="android:statusBarColor">?attr/colorPrimaryDark</item>
</style>


text:
Q: Adding constraint on JTextField I am making a GUI, in which I am using a number of JTextfield instances to enter the input from the user. I want to specify that this particular (for example : user name) text field is mandatory to fill. How can I do this?
 JLabel label_2 = new JLabel("User Name");
            label_2.setBounds(23, 167, 126, 21);
            panel_1.add(label_2);

    textField_2 = new JTextField();
            textField_2.setColumns(10);
            textField_2.setBounds(178, 129, 210, 20);
        panel_1.add(textField_2);

A: you can also use JFormattedTextField
http://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.html

A: When the user is done with the textfield, for example when he submits the data, you can validate the textfield to see if it's empty.
For example, if you are using a submit button.
submitButton.addActionLister(new ActionListner(){
    public void actionPerformed(ActionEvent ae){
       if(textField.getText().length() == 0){
            //notify user that mandatory field is empty.
       }

       //other validation checks.
    }
}

OR
You can add a focus listener to the textfields. And every field can have different focus lost implementations depending on the constraint.
 textfield.addFocusListener(new FocusListener(){
           @Override
          public void focusGained(FocusEvent fe) {
             // do whatever want like highlighting the field
          }

          @Override
          public void focusLost(FocusEvent fe) {
              //check for constraint as the user is done with this field.
          }
 });

A: JLabel label_2 = new JLabel("User Name");
label_2.setBounds(23, 167, 126, 21);
panel_1.add(label_2);

textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(178, 129, 210, 20);
panel_1.add(textField_2);

submit.addActionListener(this);

}

  public void actionPerformed(ActionEvent e)
   {
      //check the text field
       if(textField_2.getText().length()==0)
              {
                   //user_name not set
              }
       else
              {
               //user_name is set
              }

   }


text:
Q: Getting id from ImageView and if the getId then compare with with specific ImageView id? I am able the get the id of ImageView by using
ImageView iv = (ImageView)event.getSource();

and storing in the string
String userClickedImage = iv.getId();

but you I can compare with the id that I already gave to ImageView in fxml
In fxml file I  have three Images with three different ids.as can see below
<ImageView fx:id="iv_Rock" fitHeight="100" fitWidth="100"
           onMouseClicked="#selectImage"
           GridPane.columnIndex="0" GridPane.rowIndex="2" >
    <image >
        <Image url="@images/Rock.jpg"  />
    </image>
</ImageView>

and How I compare
iv.getId().equals(iv_Rock)

is not working when I click on rock image it should it give the result but it is not showing me the result.

A: The id property contains a string. For this reason the correct way to compare the id would be
iv.getId().equals("iv_Rock")

Since you seem to inject the ImageView to the controller though, simply comparing the references should also work:
event.getSource() == iv_Rock

You should consider simply using 3 different event handler methods though. This would remove the need of checking the source; Usually it's not a good idea to use the same event handler method for completely unrelated things based on the source.


text:
Q: A question on summation of series...
If $$\frac{\left(1^4+\frac14\right)\left(3^4+\frac14\right)\ldots\left((2n-1)^4+\frac14\right)}{\left(2^4+\frac14\right)\left(4^4+\frac14\right)\ldots\left((2n)^4+\frac14\right)}=\frac1{k_1n^2+k_2n+k_3}$$ then $k_1-k_2+k_3$ is equal to . . . ?

What I  basically tried was simply putting the value of $n$ from $1$ to $3$. By doing so I got $3$ simultaneous equations and hence I calculated the desired answer.
What I want to know is that is there any other elegant way to solve the above problem  because my process is very time consuming ..looking forward to here from my friends thanks in advance......

A: Use the Sophie-Germain identity: $$a^4+4b^4=(a^2+2b^2)^2-(2ab)^2=(a^2-2ab+2b^2)(a^2+2ab+2b^2)$$Using this, we can factor an expression of the form $m^4+\frac{1}{4}$ into $$m^4+4\bigg(\frac{1}{2}\bigg)^4=(m^2-m+\frac{1}{2})(m^2+m+\frac{1}{2})$$Therefore, the LHS of your equation is equal to $$\frac{\displaystyle\prod_{i=1}^{n}\bigg((2i-1)^2-(2i-1)+\frac{1}{2}\bigg)\bigg((2i-1)^2+(2i-1)+\frac{1}{2}\bigg)}{\displaystyle\prod_{i=1}^{n}\bigg((2i)^2-(2i)+\frac{1}{2}\bigg)\bigg((2i)^2+(2i)+\frac{1}{2}\bigg)}$$Note that $$(2i-1)^2+(2i-1)+\dfrac{1}{2}=(2i)^2-4i+1+2i-1+\dfrac{1}{2}=(2i)^2-(2i)+\dfrac{1}{2}$$and $$(2i-2)^2+(2i-2)+\frac{1}{2}=(2i)^2-8i+4+2i-2+\frac{1}{2}=(2i-1)^2-(2i-1)+\frac{1}{2}$$So after cancelling, our expression above is just $$\frac{(2-1)^2-(2-1)+\frac{1}{2}}{(2n)^2+(2n)+\frac{1}{2}}=\frac{1}{8n^2+4n+1}$$and the answer is $8-4+1=5$.


text:
Q: Displaying String/Label in JavaFX I need help figouring out simply how to display a text in my program so that it can display "Stop" in the middle of my polygon shape I've created. What I'm trying to do is create a stop sign. I have already taken care of creating and displaying that stop sign, so now I just need to display "Stop" in t
package application;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
    Pane pane = new Pane();
    Polygon polygon = new Polygon();
    pane.getChildren().add(polygon);
    polygon.setFill(javafx.scene.paint.Color.RED); //sets the color of polygon
    ObservableList<Double> list = polygon.getPoints();

    //create a label to display in the middle of the "stop sign" polygon shape
    //This is what I need most help on
    Label sign = new Label("Stop");
    sign.setAlignment(Pos.CENTER);
    System.out.print(sign);

    final double WIDTH = 200, HEIGHT = 200;
    double centerX = WIDTH / 2, centerY = HEIGHT / 2;
    double radius = Math.min(WIDTH, HEIGHT) * 0.4;

    // Add points to the polygon list
    for (int i = 0; i < 6; i++){
        list.add(centerX + radius * Math.cos(2 * i * Math.PI / 6));
        list.add(centerY - radius * Math.sin(2 * i * Math.PI / 6));
    }

    // Create a scene and place it in the stage
    Scene scene = new Scene(pane, WIDTH, HEIGHT);
    primaryStage.setTitle("ShowPolygon"); //Set the stage title
    primaryStage.setScene(scene); //Place the scene in the stage
    primaryStage.show(); //Display the stage

}

public static void main(String[] args) {
    launch(args);
}

}

A: Just change new Pane() to new StackPane() and add your label to the pane's child list like you do your Polygon.
StackPane is a layout manager that allows you to layer items on top of each other (by default centering the layered items).

A: Replace the Pane with StackPane and add sign to it (after the polygon):
public void start(Stage primaryStage) {
    StackPane pane = new StackPane();
    Polygon polygon = new Polygon();
    polygon.setFill(javafx.scene.paint.Color.RED); //sets the color of polygon
    ObservableList<Double> list = polygon.getPoints();

    //create a label to display in the middle of the "stop sign" polygon shape
    //This is what I need most help on
    Label sign = new Label("STOP");
    //sign.setStyle("-fx-text-fill: white; -fx-font-size: 3em");
    sign.setAlignment(Pos.CENTER);
    System.out.print(sign);

    pane.getChildren().add(polygon);
    pane.getChildren().add(sign);

    final double WIDTH = 200, HEIGHT = 200;
    double centerX = WIDTH / 2, centerY = HEIGHT / 2;
    double radius = Math.min(WIDTH, HEIGHT) * 0.4;

    // Add points to the polygon list
    for (int i = 0; i < 6; i++) {
        list.add(centerX + radius * Math.cos(2 * i * Math.PI / 6));
        list.add(centerY - radius * Math.sin(2 * i * Math.PI / 6));
    }

    // Create a scene and place it in the stage
    Scene scene = new Scene(pane, WIDTH, HEIGHT);
    primaryStage.setTitle("ShowPolygon"); //Set the stage title
    primaryStage.setScene(scene); //Place the scene in the stage
    primaryStage.show(); //Display the stage

}

Javadoc about the StackPane:

StackPane lays out its children in a back-to-front stack. The z-order
  of the children is defined by the order of the children list with the
  0th child being the bottom and last child on top. If a border and/or
  padding have been set, the children will be layed out within those
  insets.
The stackpane will attempt to resize each child to fill its content
  area. If the child could not be sized to fill the stackpane (either
  because it was not resizable or its max size prevented it) then it
  will be aligned within the area using the alignment property, which
  defaults to Pos.CENTER.


text:
Q: Customizing Linkedin Login Button I'm implementing LinkedIn Login into my web app..
I'm using following script as :

to load the LinkedIn Sign In button. This script automatically loads a LinkedIn Sign in button with fix design or image..
but I want to Customize a button with my custom Image of LinkedIn and this button should generate the LinkedIn login event after clicking on it.. that is it should serve above script's purpose
Plz Help

A: Other way to do this:

*

*Place an image that you like:

*Create JS function like this:
function liAuth(){
   IN.User.authorize(function(){
       callback();
   });
}

*Use LinkedIn user data:
IN.API.Profile("me")
   .fields("firstName", "lastName", "headline")
   .result(resultFunction);

A: Yes, it's possible. We're using jQuery, so here is our solution:

A: Under the head tag

             Sign In With LinkedIn

Please try this and let me know

A: You can use your own custom html code like this:

<title>LinkedIn JavaScript API</title>

    <input type="button" onclick="onLinkedInLoad()" value="Sign in using LinkedIn account" />

A: method for custom linkedin button

sign in with linkedin

A:         **LinkedIn Customize button onclick function you can call linked in login function**

             //create your customized linkedIn button with css

             // use onLinkedInLoad onclick function in customized button

              Login with LinkedIn

            // ----------------------------LinkedIn Sdk---------------------

            function onLinkedInLoad() {
                IN.UI.Authorize().place();
           // call onLinkedInLogin on click of button
                IN.Event.on(IN, "auth", function () { onLinkedInLogin(); });

                //IN.Event.on(IN, "logout", function () { onLinkedInLogout(); });
            }

            function onLinkedInLogin() {
                //alert('logged in');
           //get all user data from linked in plugin
                IN.API.Raw("/people/~:(id,firstName,lastName,emailAddress)format=json").result(function (data)
             {
                    console.log(data);

                    var profileData = data;
                    LinkedInFName = profileData.firstName;
                    LinkedInLName = profileData.lastName;
                    LinkedInEmail = profileData.emailAddress;
                    LinkedInId = profileData.id;
                    //alert("LinkedInFName : " + LinkedInFName);

                    GetLinkedinLoginDetails(LinkedInEmail, LinkedInId)
                }).error(function (error) {
                    console.log('Error : ' + error);
                });
            }

            function onSuccess(data) {

            }


text:
Q: How to stop Banner Ad loading? Some user intentionally try to click banner ads many times.Due to this we face problem of account suspension or termination. Does anyone know how to stop the ad being loading if it cross some limit(for example 3).
    AdView adView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder()
            .setRequestAgent("android_studio:ad_template").build();

    adView.loadAd(adRequest);
    if(currentbannerclick>3)
    {

       // some code to not load the ad.
    }

A: LinearLayout id=container
AdView       id=adView
    if(currentbannerclick>3)
    container.removeView(adView);

Thank you everyone for your answer.

A: You can identify if Ad is clicked using Activity life-cycle callbacks. you can then find out how much time user clicked your Ad and call adView.loadAd(adRequest); only if the user clicked your Ad less than your threshold.

A: You can attach an AdListener to your AdView and increase your click counter in the onAdLoaded or onAdOpened methods. More info here: https://developers.google.com/android/reference/com/google/android/gms/ads/AdListener#public-methods

A: This should work:
private void loadAd() {
    // This is a one element array because it needs to be declared final
    // TODO: you should probably load the default value from somewhere because of activity restarts
    final int[] currentBannerClick = {0};

    final AdView adView = (AdView) findViewById(R.id.adView);
    adView.setAdListener(new AdListener() {
        @Override
        public void onAdOpened() {
            super.onAdOpened();
            currentBannerClick[0]++;
            if (currentBannerClick[0] > 3) {
                adView.setVisibility(View.INVISIBLE);
                adView.destroy();
            }

            // TODO: save currentBannerClick[0] somewhere, see previous TODO comment
        }
    });

    if (currentBannerClick[0] <= 3) {
        AdRequest adRequest = new AdRequest.Builder().addTestDevice(YOUR_DEVICE_ID).build();
        adView.setVisibility(View.VISIBLE);
        adView.loadAd(adRequest);
    } else {
        adView.setVisibility(View.INVISIBLE);
    }
}

A: You can also limit number of Ads displayed for user in AdMob System. You can set limit of 3 ads per user per minut, hour or day.


text:
Q: Showing Existence of Antiderivative for Complex-Valued Function I am asked to show that for $z\in \mathbb{C} \setminus \{0,1\}$, there exists an analytic (single-valued) function, $F(z)$ on $\mathbb{C} \setminus \{0,1\}$, such that $F'=f$, where $$f(z) = \frac{(1-2z)\cos(2\pi z)}{z^2 (1-z)^2}$$
I know that if $$\int_{\gamma} f(z) dz =0$$ for all closed contours, $\gamma$, then $f$ has an antiderivative. Furthermore, in the case of the given function above, $f(z)$, I know that Res$(f,0)=$ Res$(f,1)=0$, so using the Residue Theorem I know that for any simple closed contour, $\gamma$, we have $$\int_{\gamma} f(z) dz =0$$
However, to ensure that $f$ has an antiderivative, I need to show that this is true for all closed $\gamma$, not just simple closed $\gamma$. How can I go about finishing this last step of the proof?

A: The Residue theorem states that for any (rectifiable) closed curve $\gamma$ in $\mathbb{C} \setminus \{0,1\}$:
$$
\int _{\gamma }f(z)\,dz=2\pi i \bigl( \operatorname {I} (\gamma ,0)\operatorname {Res} (f,0) + \operatorname {I} (\gamma ,1)\operatorname {Res} (f,1) \bigr)
$$
and that is zero for the given function $f$ because both residues are zero (as you already calculated).
Alternatively you could use that
$$
 f(z) = \frac{\cos(2 \pi z)}{z^2} - \frac{\cos(2 \pi (z-1))}{(z-1)^2}
$$
and show that $\frac{\cos(2 \pi z)}{z^2}$ has an antiderivative in $\mathbb{C} \backslash \{0\}$.

A: Here is an alternative solution. Write
$$ g(z) = f(z) - \left( \frac{1}{z^2} - \frac{1}{(z-1)^2} \right). $$
Then $g$ has removable singularities at both $z=0$ and $z=1$, and so, $g$ extends to a holomorphic function on $\mathbb{C}$. In particular, $g$ has an antiderivative, say $G(z)$. Then
$$ f(z) = g(z) + \frac{1}{z^2} - \frac{1}{(z-1)^2} $$
has an antideriviative
$$ G(z) - \frac{1}{z} + \frac{1}{z-1}. $$

A: The function $f$ is holomorphic on $\mathbb{C} \backslash \{0,1\}$ because $f$ is the quotient of holomorphic functions.  Since $f$ is holomorphic in this set, it has a primitive $F$ there so that $F^\prime=f$.  Or is the question to find $F$?
UPDATE
This answer is not complete.  Leaving it here for a while because the comment from @Martin R was helpful.


text:
Q: url structure is not working well in magento site with categories and sub categories we used following format under " age" menu in [Current Demo URL][2]
code  : [PASTEBIN DEMO][3]
**"shop by age "**is main category and all other are sub category.
but urls are generating like as in the image

shop-by-age/shop-by-age/shop-by-age/shop-by-age/0-6-months.html

click on 0-6 months for 3 or 4 times
please help me to find solution.
thanks in advance

A: The way the links are generated in this menu is wrong.
The href attribute is using relative path whereas it should use absolute path.
Adding slashes at the beginning of the href attributes will fix it.
Your final code should look like this:

0-6 Months

6 Months and above

1 Year and above

2 Years and above

3 Years and above

4 Years and above

5 Years and above

6 Years and above

7 Years and above

8 Years and above

10 Years and above


text:
Q: Getting count from two joined tables I have 4 tables, each with a one-to-many relationship:
client -< inspection -< car -< issue

and I'm trying to select the name and the address of a client along with the count of the inspections and the count of the issues.
Here is what I have so far: http://sqlfiddle.com/#!5/e62ba/29/0
In the example above the result for client._id = 1 should be:
 client_name    client_address   Inspection count   Issue count
 "John"         "1 Main street"  2                  3

and for client._id = 2 it should be:
 client_name    client_address   Inspection count   Issue count
 "Jane"         "1 Wall street"  0                  0

Is it possible to achieve this result in one query, or do I have to use a subquery for issue count?

A: You can do this using count(distinct):
SELECT c.client_name, c.client_address,
       COUNT(DISTINCT i._id) AS "Inspection count",
       COUNT(DISTINCT iss._id) AS "Issue count"
FROM client c LEFT JOIN
     inspection i
     ON c._id = i.client_id LEFT JOIN
     (car ca INNER JOIN
      issue iss
      ON iss.car_id = ca._id
     )
     ON ca.inspection_id = i._id
WHERE c._id = 1;


text:
Q: In a SpringBoot project with MVC REST API is returning 406 response I am working on a SpringBoot project, that uses the regular MVC mechanism to expose the REST APIs.
In one particular GET API, I am getting 406 HTTP Response.
Here is how my Controller method looks:
    @GetMapping(path = "/analysis/detail/{analysisId}")
    public ResponseEntity<AnalysisDetailResponse> getAnalysisDetails(
            @PathVariable @NotNull Long analysisId) throws BusinessException {
        AnalysisDetailResponse analysisDetailResponse = analysisService.getAnalysisDetailsByAnalysisId(analysisId);
//        return ResponseEntity.ok(analysisService.getAnalysisDetailsByAnalysisId(analysisId));
        return ResponseEntity.ok(analysisDetailResponse);
    }

The AnalysisDetailResponse is created using Lombok (which is working flawlessly in case of other APIs)
@Builder
@ToString
public class AnalysisDetailResponse {

    @NotNull
    private Long id;

    @NotNull
    private AnalysisStatus state;

    private String failedSummary;

    @NotNull
    @NotEmpty
    @Valid
    private List<PostDetail> posts;

    @Builder
    @ToString
    private static class PostDetail {

        @NotNull
        private Long id;

        @NotNull
        private float score;

        @NotNull
        private String body;

        private List<String> childBodyList;
    }
}

I've verified the contents of the entire Response object and it seems to be perfect. However, the response is always 406.
I need the response in JSON format, hence, explicit mentioning of the response type isn't really necessary IMO.
Nevertheless, I tried adding the below content to the @GetMapping annotation, but found no luck:
produces = MediaType.APPLICATION_JSON_VALUE

A majority of relevant posts are suggesting to add the jackson-mapper-asl and jackson-core-asl libraries. I tried it, but that didn't make any difference
Please note, it's just this particular API that's causing issues. There are other APIs defined in the same Controller that are working fine.
Kindly suggest....
Update:
I am trying to hit the API using Postman and I did try adding the Accept Header parameter explicitly. No luck with it

A: Was able to get this working eventually by updating the Response object class's definition.
Lombok was been used and I had applied the @Data annotation to the Response class as well as the static inner class. The motive was to club multiple Lombok annotations into one
Replacing the @Data annotation with a more verbose set including @NoArgsConstructor, @AllArgsConstructor, @Getter, @Setter resolved the issue.
So, one or more of these Lombok annotations was the real culprit in this scenario:
@ToString, @EqualsAndHashCode, @RequiredArgsConstructor


text:
Q: How is Elon Musk's Tesla surviving in space? I'm sorry I have to ask this question but I need evidence for a friend.  My answer to her that I trust people who specialize in the field to know better than me is 'BS' to her.
So to begin...
My friend believes the earth is flat.
She believes NASA is fake.
And now she thinks the Elon Musk Falcon Heavy launch wasn't real (well maybe the launch in the Earth's atmosphere) but the car in space was completely fake.
She wants me to research and provide evidence that it was real and a car can exist in space.
I know I know, many people say it's not worth the time but I truly care for  this person and have to see this through.  Plus if we're not trying to educate the world aren't we kind of being hypocritical? Yes? Haha ok here we go...
So the main point I'd need to have scientific evidence of is can the car exist in space.
Her points...

*

*a car would be destroyed in a vacuum

*elon says "you know it's real because it looks so fake"

*outgassing

*the car goes from a room into space

*did you see the photo of it from launch

*you know how much money it takes to "launch" something into space

*you think he just did that to have it "orbit for 1 billion years" that is literally so dumb it's incomprehensible

*engineering teams never see the satellites launch 'they just build them'

*look at the car - put the image in a photoshop editor - it's worse than avatar special effects

*you think there are just cameras fixed to some car that's literally just cruising around space and there's not debris next to it from the
rocket and there are no shots of the camera attachment from one side
of the car to the other

*uber has 6000 engineers, they don't know any of what uber is actually doing, they all do pieces of it, that isn't even a valid
argument, there's only a portion of every business that knows
anything, you think they send a brief to 6000 employees that they are
going to do a launch

*next piece of evidence https://www.livescience.com/61690-why-spacex-roadster-looks-fake.html
everyone thinks it looks fake, even elon, and his excuse is "the
colors are more crisp in space", and then people just believe that??

*you need to watch the footage again and wonder why there are articles upon articles explaining why "it looks fake", when you don't
think yourself it does

*I said I trust experts and asked who she trusts which she responded...no one, but that's why i ask questions, to myself
included, "do i think this looks real?" no, why?, "because of X Y and
Z", okay why is x this, research look, ask, repeat, always

*i expect this from you too - outgassing, photo editor images, see what has been previously launched

*look to see where the cameras are in the different angles

*instead of me asking you to research why it's fake, you can instead tell me what you researched to show you it's real, i will listen - i
did this - your turn

*i don't want any of the "trusting people" "watched it live" bull that's not evidence, I'll wait

*

*https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19690026573.pdf

*you can't lose 1 billion a year, stock dropped 8.63% just last night, and then be spending millions to randomly launch a car into
space. It doesn't make sense - it's a distraction to justify his lack
of use with tax payer money

Have a field day ladies & gents ;) and if you could provide resources to anything that would possibly help educate and validate your answer I'd be moooore than appreciated.

A: First of all, the burden of proof is on her, not you. She's the one who's going against consensus, so she's the one who actually needs to prove her points with evidence. But she probably won't listen to that, so let's refute her points, one by one, as concisely as possible:

*

*A car wouldn't actually be destroyed in a vacuum, especially not a convertible. The only way a vacuum would destroy an object is if it contained some pressurized gas and was dependent on atmospheric pressure to keep itself from blowing apart. Since we're dealing with a convertible electric car here (so no gas tank or air intake for the engine, either), there's no air anywhere except the tires. The tires are built to withstand substantial pressure anyway, and atmospheric pressure is only 15 psi. So if the tires were 15 psi below their absolute maximum rated pressure, then there's no reason they'd explode.

*Irrelevant. Elon Musk says stupid things.

*Outgassing is a process that occurs slowly, especially in cold environments. When I used to do a lot of vacuum testing, the only way you could make outgassing happen at any reasonable rate is by "baking out" the chamber at several hundred degrees, waiting a few days, and then coming back. In the cold vacuum of space, its effects are negligible over short time periods.

*That "room" was a capsule. If it wasn't in there, it would have been damaged by atmospheric friction on the way up. On top of that, the car's asymmetric shape would have messed up the rocket's aerodynamics in an unpredictable way, so it was easier and safer all around to place it in a capsule.

*Not sure what's being asked here.

*It takes a lot of money. Elon Musk also has a lot of money. He makes money through marketing stunts that make investors want to give him more money. This was one of those stunts.

*It was part marketing stunt, part "because he could." It's the same reason people climb Mount Everest, and they don't usually get much flak for that.

*As someone who is friends with a bunch of aerospace engineers, they absolutely do see the things that they built launch. That's most of the reason they're in the field they're in.

*No it isn't. You're just not used to photos where there's no atmosphere.

*The rocket staging was carefully planned so that debris would not hit anything. On top of that, anything that's jettisoned in the atmosphere is immediately slowed down by aerodynamic drag, to the point where it's not in any danger of hitting the car. As far as the camera attachment, there are several shots where you can see it. It's actually visible in the reflection from the door in the livestream at the moment.

*

*Yes, companies are big. But company-wide memos are also a thing.

*Photos in the absence of atmosphere really do look different. It's the same reason photos taken underwater look different.

*Just because it looks fake doesn't mean it is fake. Space is a strange place, after all.

*[Nothing to refute, seems to be the transcript of a conversation]

*See above.

*There are plenty of shots from the livestream, many of which are at different angles, and many of which show the different camera arms. There appear to be three cameras; one is built into the passenger seat, one is suspended on an arm off to the side, and one is suspended on an arm off to the front. The arm to the front is brilliantly lit up by this shot:

*

*Burden of proof is on her. That's how logic works. Extraordinary claims require extraordinary evidence.

*Everything I've laid down here is either basic physics that you can get from any textbook, or common sense.

*Microscopic etching only destroys things after a very long time, much longer than the timespan of the video. (Hence the word "microscopic".) Same with radiation damage - it's a worry when you want to build a space station that will last 20 years, but not when you're putting a car in space with some cameras until people stop watching.

*This is part marketing stunt. You have to spend money to make (people give you) money; and as long as he can keep convincing investors to give him money, then it really doesn't matter how much money his companies lose. You should definitely ask for a source on that "taxpayer money" claim.


text:
Q: MongoDB C# 2.0 Driver Multiple Unwinds I'm trying out Mongo for the first time and am having an issue where I have:
public class A
{
    public int ID {get;set;}
    .
    .
    .
    public List<B> Bs { get; set; }
}

public class B
{
    public int ID { get; set; }
    .
    .
    .
    public List<C> Cs { get; set; }
}

public class C
{
    public string Name { get; set; }
    public double Amount { get; set; }
}

and I want get back the top 10 C's with the highest Summed Amounts when I group C by name.  So for example, John Smith could be in several B's within a single A and could also be in B's among several different A's
I can accomplish this within in the Mongo Shell by running:
db.As.aggregate(
  {$unwind: "$Bs"},
  {$unwind: "$Bs.Cs"},
  {$group: { _id: "$Bs.Cs.Name", total: {$sum: "$Bs.Cs.Amount"}}},
  {$sort: {total: -1}},
  {$limit: 10}
);

But I cant figure out how to do this within my C# app using the MongoDB 2.0 driver.  Could somebody point me in the right direction?
Also, I'm a SQL Server guy and am very used to using sprocs, should I put this particular aggregate in a stored javascript on the server and just call it from my C# app?  If so, how do you call stored javascript with the 2.0 driver?
Thanks!

A: Unfortunately not all MongoDB queries can be written with LINQ. Anyway you can implement it through aggregation:
var collection = database.GetCollection<A>("As");
var result = await collection
      .Aggregate()
      .Unwind(x => x.Bs)
      .Unwind(x => x["Bs.Cs"])
      .Group(new BsonDocument {{"_id", "$Bs.Cs.Name"}, {"total", new BsonDocument("$sum", "$Bs.Cs.Amount")}})
      .Sort(new BsonDocument("total", -1))
      .Limit(10)
      .ToListAsync();


text:
Q: difference between hasmany belongsTo , namedQuery belongsTo and hasmany instantiation grails domain In grails, I have two domain classes Question and QuestionOption.One question have many options.Each option has a question.
I went through 4 different scenario.
These scenarios has combination of instantiation-namedQuery , belongsTo-namedQuery , instantiation-hasMany and  belongsTo-hasMany.
Scenario 1:

class Question
{
  String quesText
  static constraints={}
  static namedQueries={
    getAllQuestionOptions{question->
      return QuestionOption.findAllWhere(question:question)
    }
  }
}

class QuestionOption
{
  String optionText
  Question question
  static constraints={}
}

.
Scenario 2:
class Question
{
  String quesText
  static constraints={}
  static namedQueries={
    getAllQuestionOptions{question->
      return QuestionOption.findAllWhere(question:question)
    }
  }
}

class QuestionOption
{
  String optionText
  static constraints={}
  static belongsTo=[question:Question]
}

.
Scenario 3:
class Question
{
  String quesText
  static constraints={}
  static hasMany=[questionOption:QuestionOption]
}

class QuestionOption
{
  String optionText
  Question question
  static constraints={}
}

.
Scenario 4:
class Question
{
  String quesText
  static constraints={}
  static hasMany=[questionOption:QuestionOption]
}

class QuestionOption
{
  String optionText
  static constraints={}
  static belongsTo=[question:Question]
}

I used all these scenarios with mysql and all resulted with same schema
mysql> desc question;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| version     | bigint(20)   | NO   |     | NULL    |                |
| ques_text   | varchar(255) | NO   |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> desc question_option;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| version     | bigint(20)   | NO   |     | NULL    |                |
| option_text | varchar(255) | NO   |     | NULL    |                |
| question_id | bigint(20)   | NO   | MUL | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

What is difference between using these scenarios in the terms of cascading , unidirectional-bidirectional and aggregation-composition?
Bidirectional means when both entity knows about each other.Unidirectional means first entity know about second but reverse is not true.
To understand cascading I referred this: http://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/ .
Please help

A: belongsTo and hasMany associations in Grails effect the cascading behavior when it relates to updating/deleting instances. It has no effect on the named queries or querying in general.


text:
Q: How does lambda function works in rails with an example from paperclip gem I had a problem with the Paperclip gem where the default_url doesn't load after it fingerprinted in production environment, my code was like this:
class User

# Attachments to Paperclip - Profile pic
  has_attached_file :profilepic_attachment,
                    :styles => {
                      thumb: '100x100#',
                      square: '500x500#'
                    },
                    :default_url => ActionController::Base.helpers.asset_path("missing/default_user.png"),
                    :preserve_files => true
  validates_attachment_content_type :profilepic_attachment, content_type: /\Aimage\/.*\Z/

end

Note that when I do rails c in production and print out ActionController::Base.helpers.asset_path("missing/default_user.png"). The fingerprinted version (correct version) is printed out.
 default_user-fb34158daae99f297ad672c43bb1a4d3917d8e272b5f2254aa055392aa2faa94.png.
However, when I inspect it from browser, the original /assets/missing/default_user.png appeared.
I struggled for long time until I came across this post, which tells me to change

:default_url => ActionController::Base.helpers.asset_path("missing/default_user.png"),

to

:default_url => lambda { |image| ActionController::Base.helpers.asset_path("missing/default_user.png") },

I wasn't sure what happened, but then it works. I then wonder what lambda function is for and when is it used in rails? also, it passed in a variable |image| but seems it wasn't use in the code. Why is that?
Thanks!


text:
Q: Using Docker on Android Would it be possible to build a Docker app on Android? I noticed there aren't any right now, but the kernel is based on the Linux kernel, after all. If there's a way to do this without rooting, all the better!
Some reasons I could see for not being able to do this are that while Android is based on the Linux kernel, it's likely highly modified, and that Android is usually based on ARM, not x86 like most desktops & laptops currently running Docker. I don't know if Docker needs to be on x86/amd64, but I can't imagine it helps. Also, the Boot2Docker VM created on Windows & Macs, because they're not Linux and so can't natively handle Docker, is based on TinyCore Linux, yet it takes up 20GB, more than any but the latest, biggest Androids. I imagine there's a reason for this huge size. Nevertheless, perhaps if necessary someone could port this distro to Android.
Is there anything else I'm missing? Is it inherently possible to create a Docker app for Android (or, for that matter, iOS or Windows Phone)? If not, why not? If so, does anyone know of any progress?

A: Android apps already run as containers on top of linux, similar to docker, using cgroups/namespaces. To run docker on android, it needs to support docker's highlevel API. There is some discussion on the web, but most of it indicates the aufs file system as a blocker that needs an alternative.
Docker supports alternative file systems but using an alternative platform necessitates different images than the normal 64-bit user base, similar to when using Docker on 32-bit. Here is a good introduction to running Docker on ARM devices that covers a lot of what is involved. It was written before the alternative file systems were introduced but does talk about them near the end.


text:
Q: A question on bounded operator $\|T_A x\|\leq K\|x\|$ We consider an operator $T_A:H\rightarrow H$, where $H$ is an Hilbert Space and $A$ is its associated $N\times N$ matrix. $T_A$ is said "bounded" if there exists a constant $K>0$ such that
$$\|T_A x\|\leq K\|x\|$$
for each $x\in H$. From this, can we infer that, if $y\in\mathbb R^N$, $$K_1|y|^2\leq Ay\cdot y\leq K_2 |y|^2?$$
Here $0<K_1<K_2$. I think that the consequence of this kind should be possible because $\|T_A\|\leq K$ but... in what way?


text:
Q: Is there a required context for presentViewController? My iOS app has a welcome screen (not to be confused with the default view). The view controller downloads and parses an XML file using NSXMLParser. When it completes it's task it makes a button visible, which when clicked calls "presentViewController" which takes the user into the actual app. This worked fine.
I then decided that I would just like the the app to automatically transition, and so I removed the button altogether and moved the call to presentViewController into the "parserDidEndDocument" delegate method. The method gets called but nothing happens. I suspect it has something to do with the context, but when I log "self" it prints an instance of the welcome view controller. What am I doing wrong? How should I fix this?

A: Try dispatching it to the main thread.  Async objects like NSXmlParser work on separate threads, but UIKit updates must be done on the main thread.
dispatch_async(dispatch_get_main_queue(), ^{
    [self presentViewController]; //Or whatever
});


text:
Q: command-line: Force installation of a downloaded Windows-10 update "wuauclt.exe /updatenow" % was run as administrator

Windows Update indicates that 19.03 download status indicates 100%.
What command-line instruction can "move the needle" and initiate the installation of the the newly downloaded v19.03?

A: This is only a comment but I don't have enough rep for it to appear directly under your question.
Have you tried the Windows Update Standalone Installer?
Just type "wusa /h" for a list of commands.


text:
Q: Ruby: Is there an opposite of include? for Ruby Arrays? I've got the following logic in my code:
if !@players.include?(p.name)
  ...
end

@players is an array.  Is there a method so I can avoid the !?
Ideally, this snippet would be:
if @players.does_not_include?(p.name)
  ...
end

A: module Enumerable
  def does_not_include?(item)
    !include?(item)
  end
end

Ok, but seriously, the unless works fine.

A: Use unless:
unless @players.include?(p.name) do
  ...
end

A: if @players.exclude?(p.name)
    ...
end

ActiveSupport adds the exclude? method to Array, Hash, and String.  This is not pure Ruby, but is used by a LOT of rubyists.
Source: Active Support Core Extensions (Rails Guides)

A: If your objection to the !-operator is primarily that it needs to be put in front of your check and this breaks your typing flow, then there is the .! method. You just put it after the check to invert the boolean:
if @players.include?(p.name).!

A: Can you use:
unless @players.include?(p.name) do
...
end

unless is opposite of if, or you may use reject.
You can reject the not-required elements:
@players.reject{|x| x==p.name}

after the getting the results you can do your implementation.

A: Looking at Ruby only:
TL;DR
Use none? passing it a block with == for the comparison:
[1, 2].include?(1)
  #=> true
[1, 2].none? { |n| 1 == n  }
  #=> false

Array#include? accepts one argument and uses == to check against each element in the array:
player = [1, 2, 3]
player.include?(1)
 #=> true

Enumerable#none? can also accept one argument in which case it uses === for the comparison. To get the opposing behaviour to include? we omit the parameter and pass it a block using == for the comparison.
player.none? { |n| 7 == n }
 #=> true
!player.include?(7)    #notice the '!'
 #=> true

In the above example we can actually use:
player.none?(7)
 #=> true

That's because Integer#== and Integer#=== are equivalent. But consider:
player.include?(Integer)
 #=> false
player.none?(Integer)
 #=> false

none? returns false because Integer === 1 #=> true. But really a legit notinclude? method should return true. So as we did before:
player.none? { |e| Integer == e  }
 #=> true

A: How about the following:
unless @players.include?(p.name)
  ....
end

A: Here you go:
unless @players.include?(p.name)
  ...
end

You might have a look at the Ruby Style Guide for more info on similar techniques.

A: Try this, it's pure Ruby so there's no need to add any peripheral frameworks
if @players.include?(p.name) == false do
  ...
end

I was struggling with a similar logic for a few days, and after checking several forums and Q&A boards to little avail it turns out the solution was actually pretty simple.

A: Using unless is fine for statements with single include? clauses but, for example, when you need to check the inclusion of something in one Array but not in another, the use of include? with exclude? is much friendlier.
if @players.include? && @spectators.exclude? do
  ....
end

But as dizzy42 says above, the use of exclude? requires ActiveSupport

A: Try something like this:
@players.include?(p.name) ? false : true

A: I was looking up on this for myself, found this, and then a solution. People are using confusing methods and some methods that don't work in certain situations or not at all.
I know it's too late now, considering this was posted 6 years ago, but hopefully future visitors find this (and hopefully, it can clean up their, and your, code.)
Simple solution:
if not @players.include?(p.name) do
  ....
end

A: It's not a single method, but chaining count and zero works:
[1, 2, 3].count(1).zero? # => false
[1, 2, 3].count(4).zero? # => true

It also works with strings:
"hello".count("l").zero? # => false
"hello".count("q").zero? # => true


text:
Q: How could I unit test a function which uses SqlKata? How could I unit test a function which uses SqlKata?
I am using the QueryFactory to create and execute queries and as I can see there is neither interface for it, nor any of the methods are virtual. Meaning, I can not mock the results and behavior of the QueryFactory, Query and the the methods like Where, Select, WhereIn, etc.
So, if I have a method which uses SqlKata I have no idea how to mock the SqlKata dependencies. Ergo, I can not test it. Hope someone knows how to mock the SqlKata and could share that knowledge, hence the question.
May there be any reasons that low level ORMs are not supposed to be mocked? And as a result the SqlKata developers did not put interfaces/virtual members in the library.


text: Q: how can I insert, updatek select, delete datata among three tables and pivote table where many to many ternary relationship exists? for example We have 5 sales men, 1000 customers, 5 airlines listed. Now, suppose salesman 1 has sold 5 ticket to 2 customer of three airlines, again same customer has bought 15 ticket of five airlines from 3 salesmen. So it is definitely going to be a ternary many to many relationship in pivote sales table. Now How can entry and retrieve those sales from a single form where all data with relationship would be listed in all four  respective table in the background? Thank you


text:
Q: Rails 3.2 friendly url routing by date I want to implement blog\news application with ability to:

*

*show all posts at root: example.com/

*show all posts answering some year: example.com/2012/

*show all posts answering some year and month: example.com/2012/07/

*show some post by its date and slug: example.com/2012/07/slug-of-the-post
So I have created a mockup for routes.rb file:
# GET /?page=1
root :to => "posts#index"

match "/posts" => redirect("/")
match "/posts/" => redirect("/")

# Get /posts/2012/?page=1
match "/posts/:year", :to => "posts#index",
  :constraints => { :year => /\d{4}/ }

# Get /posts/2012/07/?page=1
match "/posts/:year/:month", :to => "posts#index",
  :constraints => { :year => /\d{4}/, :month => /\d{1,2}/ }

# Get /posts/2012/07/slug-of-the-post
match "/posts/:year/:month/:slug", :to => "posts#show", :as => :post,
  :constraints => { :year => /\d{4}/, :month => /\d{1,2}/, :slug => /[a-z0-9\-]+/ }

So I should work with params in index action and just get post by slug in show action (checking whether date is corect is an option):
# GET /posts?page=1
def index
  #render :text => "posts#index

#{params.to_s}"
  @posts = Post.order('created_at DESC').page(params[:page])
  # sould be more complicated in future
end

# GET /posts/2012/07/19/slug
def show
  #render :text => "posts#show

#{params.to_s}"
  @post = Post.find_by_slug(params[:slug])
end

Also I have to implement to_param for my model:
def to_param
  "#{created_at.year}/#{created_at.month}/#{slug}"
end

This is all I have learned from all night long searching in api/guides/SO.
But the problem is strange things keep happenning for me as new to rails:

*

*When I go to localhost/, the app breaks and says that it had invoked show action but first object in database had been recieved as :year (sic!):
No route matches {:controller=>"posts", :action=>"show", :year=>#<Post id: 12, slug: "*", title: "*", content: "*", created_at: "2012-07-19 15:25:38", updated_at: "2012-07-19 15:25:38">}

*When I go to localhost/posts/2012/07/cut-test same thing happens:
No route matches {:controller=>"posts", :action=>"show", :year=>#<Post id: 12, slug: "*", title: "*", content: "*", created_at: "2012-07-19 15:25:38", updated_at: "2012-07-19 15:25:38">}

I feel that there is something very easy that I haven't made, but I can't find what is it.
Anyway, this post will be helpful when it is solved, because there are solutions only for just slugs in url without date and similar but not useful questions.

A: The problem was in post's path helper usage as post_path(post), because first parameter must be year since I use :as => :post in parametrized match in routes.rb.
Nevertheless, to make the entire solution clear here are some actions needed to make that all work proper:

*

*You must add proper path helpers names for each match, e.g.
# Get /posts/2012/07/slug-of-the-post
match "/posts/:year/:month/:slug", <...>,
  :as => :post_date

Now you can use post_date_path("2012","12","end-of-the-world-is-near") in views.
Same for posts_path, posts_year_path("2012"), posts_month_path("2012","12") if properly named.
I advice not to use neither :as => :post in that match nor creating to_param in model file as it can break something you don't expect (as active_admin for me).

*Controller file posts-controller.rb should be filled with posts that needed extraction and checking of date's correctness before slug. Nevertheless in this state it is OK and breaks nothing.

*Model file posts.rb should be filled with year and month extraciton in proper format, e.g.:
def year
  created_at.year
end

def month
  created_at.strftime("%m")
end

There is no to_param method really needed as I've noticed already.

A: Is this your full routes.rb file?  Sounds like you might have a preceding resources :posts entry, which basically matches /posts/:id.  Also, there's nothing I can see from the routes file you posted that could be causing a redirect from the root path to posts, so it must be something else in there.


text:
Q: Issues understanding Google App Engine key I'm looking at the GAE example for datastoring here, and among other things this confused me a bit.
def guestbook_key(guestbook_name=DEFAULT_GUESTBOOK_NAME):
    """Constructs a Datastore key for a Guestbook entity with guestbook_name."""
    return ndb.Key('Guestbook', guestbook_name)

I understand why we need the key, but why is 'Guestbook' necessary? Is it so you can query for all 'Guestbook' objects in the datastore? But if you need to search a datastore for a type of object why isn't there a query(type(Greeting)? Concidering that that is the ndb.model that you are putting in?
Additionally, if you are feeling generous, why in creating the object you are storing, do you have to set parent?
greeting = Greeting(parent=guestbook_key(guestbook_name))

A: That's what a key is: a path consisting of pairs of kind and ID. The key is what identifies what kind it is.
I don't understand your second question. You don't have to set a parent, but if you want to set one, you can only do it when creating the entity.

A: First: GAE Datastore is one big distributed database used by all GAE apps concurrently. To distinguish entities GAE uses system-wide keys. A key is composed of:

*

*Your application name (implicitly set, not visible via API)

*Namespace, set via Namespace API (if not set in code, then an empty namespace is used).

*Kind of entity. This is just a string and has nothing to do with types at database level. Datastore is schema-less so there are no types. However, language based APIs (Java JDO/JPA/objectify, Python NDB) map this to classes/objects.

*Parent keys (afaik, serialised inside key). This is used to establish entity groups (defining scope of transactions).

*A particular entity identifier: name (string) or ID (long). They are unique within namespace and kind (and parent key if defined) - see this for more info on ID uniqueness.

See Key methods (java) to see what data is actually stored within the key.
Second: It seems that GAE Python API does not allow you to query Datastore without defining classes that map to entity kind (I don't use GAE Python, so I might be wrong). Java does have a low-level API that you can use without mapping to classes.
Third: You are not required to define a parent to an entity. Defining a parent is a way to define entity groups, which are important when using transactions. See ancestor paths and
transactions.


text:
Q: How to control the z-index on this specific suggestion box I'm trying to make this suggestion box be on top.

I can't get the z-index to work properly. Any suggestions on how to edit the CSS to make it overlap the next content block?
Site URL: https://shop.cph.dk/thejourneyison

A: .class {
    position:absolute
          *or*
    position:relative
    padding: 0px;
    z-index: 10000;
}