text:
Q: Interpreting the Joint Distribution of $(X , X \mid Y)$ This is perhaps too much of a general question, but perhaps someone can give me some insight.
Suppose that $X$ and $Y$ are random variables. Now, I'm interested in the joint distribution
of $(X, X \mid Y)$.
I know that
$$P(X, X \mid Y) = P([X \mid Y] \mid X) P(X) = P(X \mid [X \mid Y])P(X \mid Y)
$$
Is it true then that $P(X, X \mid Y) = X P(X)$? What can one say about this joint distribution?
If necessary, assume that $X$ and $Y$ are continuous and that $P(X \mid Y) = f(x\mid y)$ is the conditional density function.


text:
Q: Am I doing right this variable substitution in this differential equation? I have this differential equation: $2x(1+\sqrt{x^2-y})dx - \sqrt{x^2 - y}dy = 0$. I'm trying to switch from $(x,y)$ to $(x,u=\sqrt{x^2-y})$. So let $u = \sqrt{x^2 - y}$. Then $y = x^2 - u^2$ and $\dfrac{dy}{dx} = 2x - 2u\dfrac{du}{dx}$ and $dy = 2xdx - 2udu$. But I'm not sure if I'm doing this substitution right. If it is right, then the equation gets solved pretty easily after this but the fact that $u$ is a function of $x$ and $y$ confuses me.

A: $$2x(1+\sqrt{x^2-y})dx - \sqrt{x^2 - y}dy = 0$$
$$(1+\sqrt{x^2-y})dx^2 - \sqrt{x^2 - y}dy = 0$$
$$dx^2+\sqrt{x^2-y})d(x^2 - y) = 0$$
$$dx^2+\sqrt{u}du = 0$$
I used $u=x^2-y$ but your substitution works fine too. The DE is separable. Integrate. Your substitution and calculation looks good. For $u=\sqrt {x^2-y}$
$$2xdx+\sqrt{x^2-y})d(x^2 - y) = 0$$
$$2xdx+udu^2 = 0$$
Note that $du^2=2udu$:
$$2xdx+2u^2du = 0$$
$$xdx+u^2du = 0$$
Integrate.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to deal with booleans in NSMutableArrays? Can someone tell me why my application crashes here ?
and why it does not crash when i replace the YES objects with NSString values ?
all i want to do is to store boolean data into array and to modify these data later,
can someone please tell me how to do this ?
- (void)viewDidLoad {
    [super viewDidLoad];
    NSMutableArray* arr = [[NSMutableArray alloc] initWithObjects:YES, YES, YES, YES, nil];
    NSLog([arr objectAtIndex:1]);
}

A: YES and NO are BOOLs, which is not an Objective-C class. Foundation containers can only store Objective-C objects.
You need to wrap them in an NSNumber, like:
NSNumber* yesObj = [NSNumber numberWithBool:YES];
NSMutableArray* arr = [[NSMutableArray alloc] initWithObjects:
                                               yesObj, yesObj, yesObj, yesObj, nil];
NSLog(@"%d", [[arr objectAtIndex:1] boolValue]);

The reason why it accepts NSString is because an NSString is a kind of Objective-C class.


text:
Q: Give a grid column with text content 100% width I have a ListBox that uses the following template:
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="64" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="100" />
    </Grid.ColumnDefinitions>

    <Image Source="{Binding Property3}" Grid.Column="0" HorizontalAlignment="Left" Height="64" Width="64"/>
    <TextBlock Grid.Column="1" Text="{Binding Property1}"/>
    <TextBlock Grid.Column="2" Text="{Binding Property2}" HorizontalAlignment="Right"/>
</Grid>

The problem I'm having is with the middle column. The length of the text in the middle column determines the grid's width. What's the best way to make the grid extend to 100% of the page's width without using exact values for width? Or is this impossible? I tried quite a number of suggestions from here (Ex. setting HorizontalContentAlignment on the ListBox) to no avail.
EDIT: Here's the full page, minimal code to highlight the problem:
<phone:PhoneApplicationPage
x:Class="FoursquareDemo.SandboxPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">
<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="ItemTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="64" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="100" />
                </Grid.ColumnDefinitions>

                <Image Source="{Binding Property3}" Grid.Column="0" HorizontalAlignment="Left" Height="64" Width="64"/>
                <TextBlock Grid.Column="1" Text="{Binding Property1}"/>
                <TextBlock Grid.Column="2" Text="{Binding Property2}" HorizontalAlignment="Right"/>
            </Grid>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

<ListBox x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource SampleDataSource}}" ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding Collection}" />

A: Found the solution:
ListBoxItems do not expand to the full width of the ListBox. It's better to use a LongListSelector in this case. It seems like overkill, but it gets the job done.

A: There are 2 ways you could approach the problem.
1) Set the Margin of the Grid to Margin = "0,0,0,0"
This basically sets the offset of the Grid to 0 for "Left, Top, Right, Bottom"
2)If the above does not work, check the parent Grid. And set the Margin of the Parent Grid to the same as mentioned. It is ok if you change the values of Top and Bottom according to your design. However, if you wish to have the length of the Grid to take up the entire Width, make sure you set the left and right margin values to 0.


text:
Q: Why chrome devtools only show failed request instead of 400, 500, or 401? I'm using latest chrome at the moment (chrome 81), but in chrome dev tool catch http request and only show (failed) on request failed. I tested in Firefox with same case and received status code is 500.
Anyone has idea to show specific status code in chrome again (In chrome version < 70 the status code show in normal, like Firefox)?

Thanks!


text:
Q: Display Slug instead of Name Im trying to display the slug instead of the name of on a product single meta.  This is the code which is displaying the current category name with a link to the category.  Id like to do the same but use the slug as instead :
<?php

global $post, $product;

    $cat_count = sizeof( get_the_terms( $post->ID, 'product_cat' ) );

    ?>

        <?php echo $product->get_categories( ', ', '' . _n( 'Location:', 'Locations:', $cat_counts, 'woocommerce' ) . ' ', '' ); ?>

        <?php do_action( 'woocommerce_product_meta_end' ); ?>

Thank you

A: From your code, it looks like product_cat is a custom taxonomy. get_the_terms returns an array you can get the slug from. For instance...
$terms_array = get_the_terms($post->ID, 'procuct_cat');
$term_slug = $terms_array['your index']->slug;


text:
Q: MVVM User Control Dependency Hell It seems like a straight forward task, i want to pass in a public property value from a MVVM View, but i keep getting the "a 'binding' cannot be set on the property of type . a 'binding' can only be set on a dependencyproperty of a dependencyobject" error.
I am iterate over an observable collection and rendering the item, and i would like to move some Template code into a User control. How the heck can i solve this????
<local:xIPAddressControl UserControlIPAddressText="{Binding Path=IPAddress, RelativeSource={RelativeSource Mode=Self}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

UserControl
public partial class xIPAddressControl : UserControl
{
    public xIPAddressControl()
    {
        this.InitializeComponent();
    }

    public string UserControlIPAddressText
    {
        get { return this.xIPAddressTextBlock.Text; }
        set { this.xIPAddressTextBlock.Text = value; }
    }
}

A: You are defining the UserControlIPAddressText as a CLR property, but it needs to be registered with the Dependency Property System.
DependencyProperty UserControlIPAddressTextProperty = DependencyProperty.Register("UserControlIPADdressText", typeof(string), null);

A: As stated in comments, your property needs to be a DependencyProperty to use a Binding on it.
Here is what your code should look like:
        public static readonly DependencyProperty UserControlIPAddressTextProperty=
            DependencyProperty.Register("UserControlIPAddressText",
                                        typeof(string),
                                        typeof(xIPAddressControl));

       public string UserControlIPAddressText
       {
           get { return (string)GetValue(UserControlIPAddressTextProperty); }
           set { SetValue(UserControlIPAddressTextProperty, value); }
       }

A: Crazy thing, I was trying to set the User control incorrectly. It needs to be the following.
//this.DataContext = this;

LayoutRoot.DataContext = this;

Tutorial is here.


text:
Q: Indentation in Eclipse I am trying to indent my code in eclipse .
List<TestDB> list=session.createCriteria(TestDB.class).add(Restrictions.eq("testCase",testCase)).list();

I type my code as above and when I save my code the line is indented as follows :-
List<TestDB> list = session.createCriteria(TestDB.class)
        .add(Restrictions.eq("testCase", testCase)).list();

I tried this from SO :-
 How do I disable auto-indent in Eclipse Helios (Java)?
But it is did not help . Can anyone please help me with the indentation ?

A: Window -> Preferences -> Java -> Editor -> Save Actions -> Deactivate Perform the selected actions on save.
Also right click your project, select Properties and check the same setting here.


text:
Q: Access objects stored in list I´m not sure if I have done everything correctly but I want to access objects that I stored in a list. Here is the code:
# Obstcale class
class obstacle(object):

    def __init__(self, obstacleImg, obstacleX, obstacleY, obstacelX_change):
        self.obstacleImg = pygame.image.load("rock.png")
        self.obstacleX = random.randint(600, 700)
        self.obstacleY = random.randint(0, ScreenHeight - 64)
        self.obstacleX_change = -0.3

    def spawn_obstacle(self, x, y):
        screen.blit(self.obstacleImg, (x, y))
while running:

    if count < 1299:
        count += 1
    else:
        obstacle_number += 1
        obstacle_list.append(obstacle)
        count = 0
        print(obstacle_list[obstacle_number-1])

With the print function I want to print out every new object created by accessing the List but everything i get is this:
<class '__main__.obstacle'>
<class '__main__.obstacle'>
<class '__main__.obstacle'>
<class '__main__.obstacle'>
<class '__main__.obstacle'>
<class '__main__.obstacle'>

A: Create actual instances of your class.  Defining a __repr__ (debug representation) to make a meaningful display of the instance helps, too.  Below is your code modified into a minimal, reproducible example creating a short list of Obstacles:
import random

ScreenHeight = 600

class Obstacle(object):

    def __init__(self): # removed unused parameters
        self.obstacleImg = 'rock.png' # pygame.image.load("rock.png")
        self.obstacleX = random.randint(600, 700)
        self.obstacleY = random.randint(0, ScreenHeight - 64)
        self.obstacleX_change = -0.3

    def __repr__(self):
        return f'Obstacle(image={self.obstacleImg!r}, X={self.obstacleX}, Y={self.obstacleY}, change={self.obstacleX_change})'

obstacle_list = []
while len(obstacle_list) < 5:
    obstacle = Obstacle()  # call the class to create an instance
    obstacle_list.append(obstacle)
    print(obstacle)

Obstacle(image='rock.png', X=650, Y=62, change=-0.3)
Obstacle(image='rock.png', X=677, Y=8, change=-0.3)
Obstacle(image='rock.png', X=625, Y=370, change=-0.3)
Obstacle(image='rock.png', X=642, Y=536, change=-0.3)
Obstacle(image='rock.png', X=688, Y=311, change=-0.3)


text:
Q: Executing gcloud command in Jenkins pipeline I'm trying to run the gcloud command in a Jenkins declarative pipeline just like in the following example:
pipeline {
    agent any

   stages {
      stage('Run gcloud version') {

         steps {
            sh 'gcloud --version'
         }
      }
   }
}

I downloaded the "GCloud SDK Plugin" and configured it like this (in "Global Tool Configuration" for Jenkins):

but when I try to build the pipeline using the above Jenkinsfile, I'm getting a 'gcloud: not found' error in the pipeline.

A: I was able to run the command using the following Jenkinsfile:
pipeline {
   agent any

stages {
    stage('Run gcloud') {

        steps {
            withEnv(['GCLOUD_PATH=/var/jenkins_home/google-cloud-sdk/bin']) {
                sh '$GCLOUD_PATH/gcloud --version'
            }

         }
      }
   }
}

Note: I'm running Jenkins in kubernetes, so first I had to install the gcloud sdk in the Jenkins pod

A: I am running Jenkins 2.176.2 in containers and the GCloud plugin was not able to install the SDK in the slave (agents) containers.
I used the docker file to install it when deploying the agents:
RUN echo "deb http://packages.cloud.google.com/apt cloud-sdk-stretch main" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list \
    && curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add - \
    && apt-get update -y && apt-get install google-cloud-sdk -y \
    && PATH=$PATH:/root/google-cloud-sdk/bin


text:
Q: How do I commit changes to a submodule but not its parent? I have made a repository A original.
Then I made repository B original.
I add A original to B original as A submodule.
I make changes to the A submodule in B original, but I do not want to push the changes from A submodule to A original.
Is it possible to push changes to the A submodule without having to push them to the A original? And then would it be possible to merge updates from A original, into A submodule?
Is submodules a bad idea for this, and what is the more appropriate way??

A: A submodule is a Git repository.
A Git repository is little more1 than a collection of commits.  This means that if you want something to stick around, you must put it into a commit.2
The superproject—the Git repository that's using a second Git repository, thus turning the second Git repository into the submodule in question—is its own separate Git repository.  In this case, A original is your superproject.  It has commits and for something to stick around, you must put it into a commit.  But when A original refers to some submodule, all it does here is store a Git hash ID.  This hash ID is the "true name" of some particular commit in the submodule Git repository.3

Is it possible to push changes to the [submodule Git repository] without having to push them to the [superproject]?

This question is a bit malformed, because we don't actually push changes.  What git push pushes are commits.  Commits are not changes: they are snapshots.  Still, the concept is sound: you make some change, then you commit it, i.e., make a new snapshot by taking the changed sources and turning them into a snapshot.
If you make new commits in some repository—whatever "kind" of repository that may be: superproject, submodule, or standalone—and you want those commits to be available to other people, you not only can push them, you often must push them.  The only other way to make them available to other people is to give other people fetch/pull access to your own computer.  That tends to be a big job, which is why we mostly fob it off on hosting providers like GitHub or Bitbucket.
The tricky bit with a submodule is that if you do make changes to the submodule Git repository, you should then:

*

*make one or more new commits;

*deliver those commits somewhere that other people can see them (e.g., git push them to your hosting provider);

*go back into your superproject repository and use the Git tools there to make a new snapshot: one which says use the new submodule commit.

You can include other changes in this superproject snapshot as well, but the key change is that this new commit in the superproject says to use the new commit in the submodule.

And then would it be possible to merge updates from [the superproject], into [the submodule]?

No: the superproject has no updates to the submodule.  The superproject is a separate Git repository.  All it does is refer to some particular commits in the submodule.  Since the superproject merely says "go get commit H from submodule X" (for some commit hash ID H), there is literally nothing to merge.
The submodule is a collection of commits.  As long as it includes a commit with hash ID H, that's all the superproject needs; all the superproject can say is "get me hash H", or "get me hash I", or "get me hash J", or whatever.
Each repository is a Git repository:

*

*The submodule is a Git repository: a collection of commits (plus whatever minor other stuff it has).  It only "knows" that it's a submodule because the superproject itself cloned it and because the superproject Git keeps entering the submodule and commanding it: check out commit _____ (fill in the blank with some raw hash ID).

*The superproject is a Git repository: a collection of commits (plus whatever other minor stuff it has).  It only "knows" that it's a superproject because it has a commit that says clone the submodule if necessary, then check out commit _____ (fill in the blank with some raw hash ID).  The cloning instructions are in a file named .gitmodules; these may also get copied to your .git/config.  The rest—the hash ID, and the path where the clone goes—are in each commit in the superproject.
That's really all there is to submodules.  Well, OK, there's a whole bunch of interaction, mostly coded up in git submodule, that results from the above, but that's the essence of a superproject/submodule pair.  Note that a submodule Git repository can itself be a superproject, i.e., it can have its own submodules.  All it has to do is list some Git repository to clone, and some commit hash ID to check out.

1How much more, depends on the type of repository: a --bare repository is the collection of commits plus the names database (branch names, tag names, and the like); a non-bare repository also provides a working tree.  The working tree isn't in the repository, but it's where you see your files, so that can be pretty important.  Just keep in mind that while Git provided a directory (or folder, if you prefer that term) to work in, that folder (directory) is not actually in the repository, it's just next to it.
2Things you put in your working tree will generally stick around too—with a lot of caveats—but since they're next to, not in, the repository, no other Git clone will be able to see them.
3Branch names are a sort of changeable alias for a commit: they'll let you find a commit, but someone can change the branch name later, so that you find a different commit.  The superproject Git insists on finding the right commit, so it doesn't hold a branch name, which might change: it holds a hash ID, which cannot change.


text:
Q: Install asp.net3 When I install ASP.NET 3 I get the following error: "use the role management tool". I enabled .NET 3.0 through the role management tool, and am still getting the error so am not able to proceed with the install. Can anyone help?

A: Please use clearer writing next time and proper punctuation. Are you trying to enable ASP.NET in IIS?
If so, try
aspnet_regiis.exe -i

in %WINDIR%\microsoft.net\framework\v2.0.50727

A: From the question I see that you don't know the environment, so I care to explain:
ASP.NET is a Microsoft technology to build Web Pages
.NET is the Microsoft Framework
there are 2 versions of ASP.NET, the Classic (normally called just ASP.NET) and the Model View Controler called ASP.NET MVC
.NET has more versions, since 1.0 to the brand new 4.0
As I understand, you installed the .NET Framework 3.0 (by the way, install the 3.5 SP1 and you have all you need to create not only 2.0, 3.0 or 3.5 applications)
all you need to do is verify if your application on IIS is pointed to .NET 2.0 and not 1.0 and you should have all it takes to run it.

added
if order to understand all of this you should have a read at Scott Hanselman Blog

How to set an IIS Application or AppPool to use ASP.NET 3.5 rather than 2.0


text:
Q: find key value in object I have the following object(Json):
 let object = {
"statusCode": 200,
"body": [{
        "id": "3",
        "externalId": "yehudakala4",
        "status": "active",
        "createdAt": "2018-11-14T08:36:50.967Z",
        "updatedAt": "2018-11-14T08:36:50.967Z",
        "firstName": "yehu",
        "lastName": "da",
        "email": "ye@g.com"
    }
],
"headers": {
    "x-powered-by": "Express",
    "access-control-allow-origin": "*",
    "content-type": "application/json; charset=utf-8",
    "content-length": "189",
    "etag": "W/\"bd-Emx3/KChQLzf9+6bgFSHXPQgDTM\"",
    "date": "<<Masked>>",
    "connection": "close"
},
"request": {
    "uri": {
        "protocol": "http:",
        "slashes": true,
        "auth": null,
        "host": "user-management-service.dev.local:4202",
        "port": "4202",
        "hostname": "user-management-service.dev.local",
        "hash": null,
        "search": "?username=yehudakala4",
        "query": "username=yehudakala4",
        "pathname": "/v1/users",
        "path": "/v1/users?username=yehudakala4",
        "href": "http://user-management-service.dev.local:4202/v1/users?username=yehudakala4"
    },
    "method": "GET",
    "headers": {
        "Content-Type": "application/json",
        "accept": "application/json",
        "content-length": 2
    }
}

}
given the following function:
let key = "protocol";
let value = "http:";
let x;
let res = false;
let findValue = function findValue(obj, key, value) {

for(let localKey in obj){
    if(obj.hasOwnProperty(localKey)){
        //console.log(localKey)
        if(localKey === key){
            res = obj[localKey] === value;
            return res;
        }
        else
        {
            let val = obj[localKey];
            if(typeof val === 'object')
                x = findValue(val, key, value);
                if (typeof x === 'boolean') {
                    return x;
                }
            }
        }
    }
}

let rs = findValue(object, key, value)
console.log(rs);

there are two problems with this approach:

*

*if the key does not exist in object, then the function returns undefine

*if key appears more than one time, it check only for the first time

my goal is too check any occurrence of key and if the value of one of them does not match return false, if all match return true.
second, if key does not exist return false.

A: I changed your function to get all values for a given key by including a Set as context in the recursion.
Then you check the set for a single value that equals your value.
See updated snippet.
Finally, as a side note, Object.keys will make your code leaner, as you won't have to check for hasOwnProperty.

let findValues = function(obj, key, found) {
  for (let localKey in obj) {
    if (obj.hasOwnProperty(localKey)) {
      let val = obj[localKey];
      //console.log(localKey)
      if (localKey === key) {
        found.add(val)
      } else {
        if (typeof val === 'object') {
          findValues(val, key, found)
        }
      }
    }
  }
}

function uniqueValue(obj, key, value) {
  let found = new Set()
  findValues(object, key, found)
  return found.size === 1 && found.has(value);
}

let object = {
  "statusCode": 200,
  "body": [{
    "id": "3",
    "externalId": "yehudakala4",
    "status": "active",
    "createdAt": "2018-11-14T08:36:50.967Z",
    "updatedAt": "2018-11-14T08:36:50.967Z",
    "firstName": "yehu",
    "lastName": "da",
    "email": "ye@g.com"
  }],
  "headers": {
    "x-powered-by": "Express",
    "access-control-allow-origin": "*",
    "content-type": "application/json; charset=utf-8",
    "content-length": "189",
    "etag": "W/\"bd-Emx3/KChQLzf9+6bgFSHXPQgDTM\"",
    "date": "<<Masked>>",
    "connection": "close"
  },
  "request": {
    "uri": {
      "protocol": "http:",
      "slashes": true,
      "auth": null,
      "host": "user-management-service.dev.local:4202",
      "port": "4202",
      "hostname": "user-management-service.dev.local",
      "hash": null,
      "search": "?username=yehudakala4",
      "query": "username=yehudakala4",
      "pathname": "/v1/users",
      "path": "/v1/users?username=yehudakala4",
      "href": "http://user-management-service.dev.local:4202/v1/users?username=yehudakala4"
    },
    "method": "GET",
    "headers": {
      "Content-Type": "application/json",
      "accept": "application/json",
      "content-length": 2
    }
  }
}

let key = "protocol";
let value = "http:";

console.log(uniqueValue(object, key, value));

A: You can make a simple recursive function for this problem. Which will find and validate the value of the property. The below mention function in snippet will :

*

*return true if the property is found and all its occurrences have same value.

*return false if the property is not found or all its occurrences do not match.

This function currently supports only object, i.e it recursively check for the property only in objects and not inside arrays, we can further extend it to support arrays also.

let object1 = { auth : "ok", response : { auth : "ok" }, check : { check1 : { check2 : {auth : "no"} } } };
let object2 = { auth : "ok", response : { auth : "ok" }, check : { check1 : { check2 : {auth : "ok"} } } };

function findAndValidateKey(obj, targetKey, value, res){
  for(var key in obj){
    if(obj.hasOwnProperty(key) && key === targetKey){
      if(res === undefined)
        res = true;
      res = res && (obj[key] === value);
    } else if(obj[key] instanceof  Object && !Array.isArray(obj[key])){
      let tempResult = findAndValidateKey(obj[key], targetKey, value, res);
      if(res === undefined)
        res = true;
      res = res && tempResult;
    }
  }
  return !!res;
}
console.log(findAndValidateKey(object1, "auth","ok", undefined));
console.log(findAndValidateKey(object2, "auth","ok", undefined));

You can also implement a simple non-recursive solution for this problem, by using a Stack data structure.

let  object1 = { auth : "ok", response : { auth : "ok" }, check : { check1 : { check2 : {auth : "no"} } } };
let object2 = { auth : "ok", response : { auth : "ok" }, check : { check1 : { check2 : {auth : "ok"} } } };

function findAndValidateKey(object, targetKey, value){
  let res = true, found = false;
  let stack = [JSON.parse(JSON.stringify(object))];
  while(stack.length){
    let obj = stack.pop();
    for(var key in obj){
      if(obj.hasOwnProperty(key) && key === targetKey){
        res = res && (obj[key] === value);
        found = true;
        if(!res)
          break;
      } else if(obj[key] instanceof  Object && !Array.isArray(obj[key])){
        stack.push(obj[key]);
      }
    }
    if(!res)
      break;
  }
  res = res && found;
  return res;
}

console.log(findAndValidateKey(object1, "auth","ok"));
console.log(findAndValidateKey(object2, "auth","ok"));

A: What you can do is to initialize an array to get all the values that are part of the same key, and then in the end check if all these array are equal to the searched value, using:
let rs = matches.every(m => m == value);

This is how should be your updated function:
let matches = [];
function findValue(obj, key) {
  if (obj.hasOwnProperty(key)) {
    matches.push(obj[key]);
  }
  for (k in obj) {
    if (Array.isArray(obj[k])) {
      obj[k].forEach(el => findValue(el, key));
    } else if (obj[k] && typeof obj[k] == "object") {
      findValue(obj[k], key);
    }
  }
}

Demo:

let object = {
  "statusCode": 200,
  "body": [{
    "id": "3",
    "externalId": "yehudakala4",
    "status": "active",
    "createdAt": "2018-11-14T08:36:50.967Z",
    "updatedAt": "2018-11-14T08:36:50.967Z",
    "firstName": "yehu",
    "lastName": "da",
    "email": "ye@g.com"
  }],
  "headers": {
    "x-powered-by": "Express",
    "access-control-allow-origin": "*",
    "content-type": "application/json; charset=utf-8",
    "content-length": "189",
    "etag": "W/\"bd-Emx3/KChQLzf9+6bgFSHXPQgDTM\"",
    "date": "<<Masked>>",
    "connection": "close"
  },
  "request": {
    "uri": {
      "protocol": "http:",
      "slashes": true,
      "auth": null,
      "host": "user-management-service.dev.local:4202",
      "port": "4202",
      "hostname": "user-management-service.dev.local",
      "hash": null,
      "search": "?username=yehudakala4",
      "query": "username=yehudakala4",
      "pathname": "/v1/users",
      "path": "/v1/users?username=yehudakala4",
      "href": "http://user-management-service.dev.local:4202/v1/users?username=yehudakala4"
    },
    "method": "GET",
    "headers": {
      "Content-Type": "application/json",
      "accept": "application/json",
      "content-length": 2
    }
  }
}

let key = "protocol";
let value = "http:";
let x;
let res = false;
let matches = [];

function findValue(obj, key) {
  if (obj.hasOwnProperty(key)) {
    matches.push(obj[key]);
  }
  for (k in obj) {
    if (Array.isArray(obj[k])) {
      obj[k].forEach(el => findValue(el, key));
    } else if (obj[k] && typeof obj[k] == "object") {
      findValue(obj[k], key);
    }
  }
}

findValue(object, key);
let rs = matches.every(m => m == value);
console.log(rs);

A:     let obj = {
    "statusCode": 200,
    "body": [{
            "id": "3",
            "externalId": "yehudakala4",
            "status": "active",
            "createdAt": "2018-11-14T08:36:50.967Z",
            "updatedAt": "2018-11-14T08:36:50.967Z",
            "firstName": "yehu",
            "lastName": "da",
            "email": "ye@g.com"
        }
    ],
    "headers": {
        "x-powered-by": "Express",
        "access-control-allow-origin": "*",
        "content-type": "application/json; charset=utf-8",
        "content-length": "189",
        "etag": "W/\"bd-Emx3/KChQLzf9+6bgFSHXPQgDTM\"",
        "date": "<<Masked>>",
        "connection": "close"
    },
    "request": {
        "uri": {
            "protocol": "http:",
            "slashes": true,
            "auth": null,
            "host": "user-management-service.dev.local:4202",
            "port": "4202",
            "hostname": "user-management-service.dev.local",
            "hash": null,
            "search": "?username=yehudakala4",
            "query": "username=yehudakala4",
            "pathname": "/v1/users",
            "path": "/v1/users?username=yehudakala4",
            "href": "http://user-management-service.dev.local:4202/v1/users?username=yehudakala4"
        },
        "method": "GET",
        "headers": {
            "Content-Type": "application/json",
            "accept": "application/json",
            "content-length": 2
        }
    }

}
let arrOfFound = [];
let key = "protoco";
let value = "http:";
let x;
let res = false;
let findValue = function findValue(obj, key, value) {
    JSON.last
    for(let localKey in obj){
        if(obj.hasOwnProperty(localKey)){
            //console.log(localKey)
            if(localKey === key){
                res = obj[localKey] === value;
                arrOfFound.push(res);
                //return res;
            }
            else
            {
                let val = obj[localKey];
                if(typeof val === 'object'){
                    x = findValue(val, key, value);
                    if (typeof x === 'boolean') {
                        arrOfFound.push(x);
                    }
                }
            }
        }
    }
}
function checkKeyValue(obj, key, value){
    findValue(obj, key, value)
    if(arrOfFound.length == 0){
        return false;
    }else{
        arrOfFound.forEach(element => {
            if(element == false)
                return false;
        });
    }
    return true;
}
res = checkKeyValue(obj, key, value)
console.log(res);


text:
Q: LEFT JOINing the max/top I have two tables from which I'm trying to run a query to return the maximum (or top) transaction for each person.  I should note that I cannot change the table structure.  Rather, I can only pull data.
People

+-----------+
| id | name |
+-----------+
| 42 | Bob  |
| 65 | Ted  |
| 99 | Stu  |
+-----------+

Transactions (there is no primary key)

+---------------------------------+
| person     | amount | date      |
+---------------------------------+
| 42         | 3      | 9/14/2030 |
| 42         | 4      | 7/02/2015 |
| 42         | *NULL* | 2/04/2020 |
| 65         | 7      | 1/03/2010 |
| 65         | 7      | 5/20/2020 |
+---------------------------------+

Ultimately, for each person I want to return the highest amount. If that doesn't work then I'd like to look at the date and return the most recent date.
So, I'd like my query to return:

+----------------------------------------+
| person_id  | name | amount | date      |
+----------------------------------------+
| 42         | Bob  | 4      | 7/02/2015 | (<- highest amount)
| 65         | Ted  | 7      | 5/20/2020 | (<- most recent date)
| 99         | Stu  | *NULL* | *NULL*    | (<- no records in Transactions table)
+----------------------------------------+

SELECT People.id, name, amount, date
FROM People
LEFT JOIN (
    SELECT TOP 1 person_id
    FROM Transactions
    WHERE person_id = People.id
    ORDER BY amount DESC, date ASC
)
ON People.id = person_id

I can't figure out what I am doing wrong, but I know it's wrong. Any help would be much appreciated.

A: You are almost there but since there are duplicate Id in the Transaction table ,so you need to remove those by using Row_number() function
Try this :
With cte as
 (Select People,amount,date ,row_number() over (partition by People
                                  order by amount desc, date desc) as row_num
  from Transac )
 Select * from People as a
 left join cte as b
 on a.ID=b.People
 and b.row_num=1

The result is in Sql Fiddle
Edit: Row_number() from MSDN
Returns the sequential number of a row within a partition of a result set,
starting at 1 for the first row in each partition.

Partition is used to group the result set and Over by clause is used
Determine the partitioning and ordering of the rowset before the
associated window function is applied.


text:
Q: How to export ppt slide as image using pptx python I want to export a ppt slide as an png format image through pptx python.
I have gone through this solution using win32com but facing error as com_error: (-2147221005, 'Invalid class string', None, None) while running win32com.client.Dispatch("PowerPoint.Application")
I have also tried using pptx_tools.utils.save_pptx_as_png, but it is asking Comptype module needed to save PNGs. and I don't find any comptype module in Python. I have installed comtype module but it is throwing an syntax error while importing.
Please let me know any efficient way to export pptx slide as image

A: As you've tagged this with "python-pptx" I have to tell you python-pptx can't do it.
You'd have to do it by automating the Powerpoint application itself. (Sorry, I don't know how to do that.)

A: After I try many times, I corrected some places and it runs fine:

*

*Import module:
import win32com.client

*Your path 1 (pptx file):
"/ddd/xxx/yyy/file.pptx"

*Your path 2 (output file):
"/ddd/xxx/yyy/file.jpg"


text:
Q: How to apply Hovering on html area tag? I am trying to hover the area tag of HTML. I tried this in CSS:
area:hover
{
    border:1px solid black;
}

This is the HTML on which it should be applied.

<map id='imgmap201293016112' name='imgmap_css_container_imgmap201293016112'>
    <area shape="poly" coords="2,0,604,-3,611,-3,611,166,346,165,345,130,-2,130,-2,124,1,128,1,126" href="" alt="imgmap201293016112-0" title="imgmap201293016112-0" class="imgmap201293016112-area" id="imgmap201293016112-area-0" />
    <area shape="rect" coords="1,131,341,213" href="" alt="imgmap201293016112-1" title="imgmap201293016112-1" class="imgmap201293016112-area" id="imgmap201293016112-area-1" />
    <area shape="rect" coords="346,166,614,241" href="" alt="imgmap201293016112-2" title="imgmap201293016112-2" class="imgmap201293016112-area" id="imgmap201293016112-area-2" />
    <area shape="poly" coords="917,242,344,239,345,496,574,495,575,435,917,433" href="" alt="imgmap201293016112-3" title="imgmap201293016112-3" class="imgmap201293016112-area" id="imgmap201293016112-area-3" />
    <area shape="rect" coords="1,416,341,494" href="" alt="imgmap201293016112-4" title="imgmap201293016112-4" class="imgmap201293016112-area" id="imgmap201293016112-area-4" />
    <area shape="rect" coords="1,215,341,410" href="" alt="imgmap201293016112-5" title="imgmap201293016112-5" class="imgmap201293016112-area" id="imgmap201293016112-area-5" />
    <area shape="poly" coords="916,533,916,436,578,436,576,495,806,496,807,535" href="" alt="imgmap201293016112-6" title="imgmap201293016112-6" class="imgmap201293016112-area" id="imgmap201293016112-area-6" />
    <area shape="rect" coords="805,536,918,614" href="" alt="imgmap201293016112-7" title="imgmap201293016112-7" class="imgmap201293016112-area" id="imgmap201293016112-area-7" />
    <area shape="rect" coords="461,494,803,616" href="" alt="imgmap201293016112-8" title="imgmap201293016112-8" class="imgmap201293016112-area" id="imgmap201293016112-area-8" />
    <area shape="rect" coords="0,497,223,616" href="" alt="imgmap201293016112-9" title="imgmap201293016112-9" class="imgmap201293016112-area" id="imgmap201293016112-area-9" />
    <area shape="rect" coords="230,494,456,614" href="" alt="imgmap201293016112-10" title="imgmap201293016112-10" class="imgmap201293016112-area" id="imgmap201293016112-area-10" />
    <area shape="rect" coords="345,935,572,1082" href="" alt="imgmap201293016112-11" title="imgmap201293016112-11" class="imgmap201293016112-area" id="imgmap201293016112-area-11" />
    <area shape="rect" coords="1,617,457,760" href="" alt="imgmap201293016112-12" title="imgmap201293016112-12" class="imgmap201293016112-area" id="imgmap201293016112-area-12" />
    <area shape="rect" coords="345,760,577,847" href="" alt="imgmap201293016112-13" title="imgmap201293016112-13" class="imgmap201293016112-area" id="imgmap201293016112-area-13" />
    <area shape="rect" coords="0,759,344,906" href="" alt="imgmap201293016112-14" title="imgmap201293016112-14" class="imgmap201293016112-area" id="imgmap201293016112-area-14" />
    <area shape="rect" coords="346,850,571,935" href="" alt="imgmap201293016112-15" title="imgmap201293016112-15" class="imgmap201293016112-area" id="imgmap201293016112-area-15" />
    <area shape="rect" coords="578,761,915,865" href="" alt="imgmap201293016112-16" title="imgmap201293016112-16" class="imgmap201293016112-area" id="imgmap201293016112-area-16" />
    <area shape="rect" coords="0,1017,226,1085" href="" alt="imgmap201293016112-17" title="imgmap201293016112-17" class="imgmap201293016112-area" id="imgmap201293016112-area-17" />
    <area shape="rect" coords="0,908,342,1017" href="" alt="imgmap201293016112-18" title="imgmap201293016112-18" class="imgmap201293016112-area" id="imgmap201293016112-area-18" />
    <area shape="rect" coords="229,1010,342,1084" href="" alt="imgmap201293016112-19" title="imgmap201293016112-19" class="imgmap201293016112-area" id="imgmap201293016112-area-19" />
    <area shape="rect" coords="0,1086,340,1206" href="" alt="imgmap201293016112-20" title="imgmap201293016112-20" class="imgmap201293016112-area" id="imgmap201293016112-area-20" />
    <area shape="rect" coords="0,1209,224,1290" href="" alt="imgmap201293016112-21" title="imgmap201293016112-21" class="imgmap201293016112-area" id="imgmap201293016112-area-21" />
    <area shape="rect" coords="0,1290,225,1432" href="" alt="imgmap201293016112-22" title="imgmap201293016112-22" class="imgmap201293016112-area" id="imgmap201293016112-area-22" />
    <area shape="rect" coords="0,1432,340,1517" href="" alt="imgmap201293016112-23" title="imgmap201293016112-23" class="imgmap201293016112-area" id="imgmap201293016112-area-23" />
    <area shape="rect" coords="346,1432,686,1517" href="" alt="imgmap201293016112-24" title="imgmap201293016112-24" class="imgmap201293016112-area" id="imgmap201293016112-area-24" />
    <area shape="rect" coords="461,1266,686,1429" href="" alt="imgmap201293016112-25" title="imgmap201293016112-25" class="imgmap201293016112-area" id="imgmap201293016112-area-25" />
    <area shape="rect" coords="230,1365,455,1430" href="" alt="imgmap201293016112-26" title="imgmap201293016112-26" class="imgmap201293016112-area" id="imgmap201293016112-area-26" />
    <area shape="rect" coords="231,1291,457,1360" href="" alt="imgmap201293016112-27" title="imgmap201293016112-27" class="imgmap201293016112-area" id="imgmap201293016112-area-27" />
    <area shape="rect" coords="230,1210,342,1289" href="" alt="imgmap201293016112-28" title="imgmap201293016112-28" class="imgmap201293016112-area" id="imgmap201293016112-area-28" />
    <area shape="rect" coords="692,928,916,1016" href="" alt="imgmap201293016112-29" title="imgmap201293016112-29" class="imgmap201293016112-area" id="imgmap201293016112-area-29" />
    <area shape="rect" coords="460,616,916,759" href="" alt="imgmap201293016112-30" title="imgmap201293016112-30" class="imgmap201293016112-area" id="imgmap201293016112-area-30" />
    <area shape="rect" coords="693,1316,917,1518" href="" alt="imgmap201293016112-31" title="imgmap201293016112-31" class="imgmap201293016112-area" id="imgmap201293016112-area-31" />
    <area shape="rect" coords="344,1150,572,1219" href="" alt="imgmap201293016112-32" title="imgmap201293016112-32" class="imgmap201293016112-area" id="imgmap201293016112-area-32" />
    <area shape="rect" coords="693,1015,916,1171" href="" alt="imgmap201293016112-33" title="imgmap201293016112-33" class="imgmap201293016112-area" id="imgmap201293016112-area-33" />
    <area shape="rect" coords="577,955,686,1032" href="" alt="imgmap201293016112-34" title="imgmap201293016112-34" class="imgmap201293016112-area" id="imgmap201293016112-area-34" />
    <area shape="rect" coords="577,1036,687,1101" href="" alt="imgmap201293016112-35" title="imgmap201293016112-35" class="imgmap201293016112-area" id="imgmap201293016112-area-35" />
    <area shape="rect" coords="576,1104,689,1172" href="" alt="imgmap201293016112-36" title="imgmap201293016112-36" class="imgmap201293016112-area" id="imgmap201293016112-area-36" />
    <area shape="rect" coords="691,1232,918,1313" href="" alt="imgmap201293016112-37" title="imgmap201293016112-37" class="imgmap201293016112-area" id="imgmap201293016112-area-37" />
    <area shape="rect" coords="341,1085,573,1151" href="" alt="imgmap201293016112-38" title="imgmap201293016112-38" class="imgmap201293016112-area" id="imgmap201293016112-area-38" />
    <area shape="poly" coords="917,868,917,925,688,927,688,955,576,955,574,867,572,864" href="" alt="imgmap201293016112-39" title="imgmap201293016112-39" class="imgmap201293016112-area" id="imgmap201293016112-area-39" />
    <area shape="poly" coords="919,1173,917,1231,688,1231,688,1266,574,1267,576,1175,576,1175" href="" alt="imgmap201293016112-40" title="imgmap201293016112-40" class="imgmap201293016112-area" id="imgmap201293016112-area-40" />
    <area shape="poly" coords="572,1222,572,1265,459,1265,458,1289,339,1290,344,1225" href="" alt="imgmap201293016112-41" title="imgmap201293016112-41" class="imgmap201293016112-area" id="imgmap201293016112-area-41" />
</map>

So how is it possible that when I hover the area, its border color turns to black or even red?

A: What I did was to create a canvas element that I then position in front of the image map. Then, whenever an area is moused-over, I call a func that gets the coord string for that shape and the shape-type. If it's a poly I use the coords to draw an outline on the canvas. If it's a rect I draw a rect outline. You could easily add code to deal with circles.
You could also set the opacity of the canvas to less than 100% before filling the poly/rect/circle. You could also change the reliance on a global for the canvas's context - this would mean you could deal with more than 1 image-map on the same page.
<!DOCTYPE html>

<title></title>

    <canvas id='myCanvas'></canvas>

<map id='imgmap201293016112' name='imgmap_css_container_imgmap201293016112'>
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="2,0,604,-3,611,-3,611,166,346,165,345,130,-2,130,-2,124,1,128,1,126" href="" alt="imgmap201293016112-0" title="imgmap201293016112-0" class="imgmap201293016112-area" id="imgmap201293016112-area-0" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,131,341,213" href="" alt="imgmap201293016112-1" title="imgmap201293016112-1" class="imgmap201293016112-area" id="imgmap201293016112-area-1" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,166,614,241" href="" alt="imgmap201293016112-2" title="imgmap201293016112-2" class="imgmap201293016112-area" id="imgmap201293016112-area-2" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="917,242,344,239,345,496,574,495,575,435,917,433" href="" alt="imgmap201293016112-3" title="imgmap201293016112-3" class="imgmap201293016112-area" id="imgmap201293016112-area-3" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,416,341,494" href="" alt="imgmap201293016112-4" title="imgmap201293016112-4" class="imgmap201293016112-area" id="imgmap201293016112-area-4" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,215,341,410" href="" alt="imgmap201293016112-5" title="imgmap201293016112-5" class="imgmap201293016112-area" id="imgmap201293016112-area-5" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="916,533,916,436,578,436,576,495,806,496,807,535" href="" alt="imgmap201293016112-6" title="imgmap201293016112-6" class="imgmap201293016112-area" id="imgmap201293016112-area-6" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="805,536,918,614" href="" alt="imgmap201293016112-7" title="imgmap201293016112-7" class="imgmap201293016112-area" id="imgmap201293016112-area-7" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="461,494,803,616" href="" alt="imgmap201293016112-8" title="imgmap201293016112-8" class="imgmap201293016112-area" id="imgmap201293016112-area-8" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,497,223,616" href="" alt="imgmap201293016112-9" title="imgmap201293016112-9" class="imgmap201293016112-area" id="imgmap201293016112-area-9" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,494,456,614" href="" alt="imgmap201293016112-10" title="imgmap201293016112-10" class="imgmap201293016112-area" id="imgmap201293016112-area-10" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="345,935,572,1082" href="" alt="imgmap201293016112-11" title="imgmap201293016112-11" class="imgmap201293016112-area" id="imgmap201293016112-area-11" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,617,457,760" href="" alt="imgmap201293016112-12" title="imgmap201293016112-12" class="imgmap201293016112-area" id="imgmap201293016112-area-12" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="345,760,577,847" href="" alt="imgmap201293016112-13" title="imgmap201293016112-13" class="imgmap201293016112-area" id="imgmap201293016112-area-13" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,759,344,906" href="" alt="imgmap201293016112-14" title="imgmap201293016112-14" class="imgmap201293016112-area" id="imgmap201293016112-area-14" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,850,571,935" href="" alt="imgmap201293016112-15" title="imgmap201293016112-15" class="imgmap201293016112-area" id="imgmap201293016112-area-15" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="578,761,915,865" href="" alt="imgmap201293016112-16" title="imgmap201293016112-16" class="imgmap201293016112-area" id="imgmap201293016112-area-16" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1017,226,1085" href="" alt="imgmap201293016112-17" title="imgmap201293016112-17" class="imgmap201293016112-area" id="imgmap201293016112-area-17" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,908,342,1017" href="" alt="imgmap201293016112-18" title="imgmap201293016112-18" class="imgmap201293016112-area" id="imgmap201293016112-area-18" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="229,1010,342,1084" href="" alt="imgmap201293016112-19" title="imgmap201293016112-19" class="imgmap201293016112-area" id="imgmap201293016112-area-19" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1086,340,1206" href="" alt="imgmap201293016112-20" title="imgmap201293016112-20" class="imgmap201293016112-area" id="imgmap201293016112-area-20" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1209,224,1290" href="" alt="imgmap201293016112-21" title="imgmap201293016112-21" class="imgmap201293016112-area" id="imgmap201293016112-area-21" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1290,225,1432" href="" alt="imgmap201293016112-22" title="imgmap201293016112-22" class="imgmap201293016112-area" id="imgmap201293016112-area-22" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1432,340,1517" href="" alt="imgmap201293016112-23" title="imgmap201293016112-23" class="imgmap201293016112-area" id="imgmap201293016112-area-23" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,1432,686,1517" href="" alt="imgmap201293016112-24" title="imgmap201293016112-24" class="imgmap201293016112-area" id="imgmap201293016112-area-24" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="461,1266,686,1429" href="" alt="imgmap201293016112-25" title="imgmap201293016112-25" class="imgmap201293016112-area" id="imgmap201293016112-area-25" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,1365,455,1430" href="" alt="imgmap201293016112-26" title="imgmap201293016112-26" class="imgmap201293016112-area" id="imgmap201293016112-area-26" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="231,1291,457,1360" href="" alt="imgmap201293016112-27" title="imgmap201293016112-27" class="imgmap201293016112-area" id="imgmap201293016112-area-27" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,1210,342,1289" href="" alt="imgmap201293016112-28" title="imgmap201293016112-28" class="imgmap201293016112-area" id="imgmap201293016112-area-28" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="692,928,916,1016" href="" alt="imgmap201293016112-29" title="imgmap201293016112-29" class="imgmap201293016112-area" id="imgmap201293016112-area-29" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="460,616,916,759" href="" alt="imgmap201293016112-30" title="imgmap201293016112-30" class="imgmap201293016112-area" id="imgmap201293016112-area-30" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="693,1316,917,1518" href="" alt="imgmap201293016112-31" title="imgmap201293016112-31" class="imgmap201293016112-area" id="imgmap201293016112-area-31" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="344,1150,572,1219" href="" alt="imgmap201293016112-32" title="imgmap201293016112-32" class="imgmap201293016112-area" id="imgmap201293016112-area-32" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="693,1015,916,1171" href="" alt="imgmap201293016112-33" title="imgmap201293016112-33" class="imgmap201293016112-area" id="imgmap201293016112-area-33" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="577,955,686,1032" href="" alt="imgmap201293016112-34" title="imgmap201293016112-34" class="imgmap201293016112-area" id="imgmap201293016112-area-34" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="577,1036,687,1101" href="" alt="imgmap201293016112-35" title="imgmap201293016112-35" class="imgmap201293016112-area" id="imgmap201293016112-area-35" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="576,1104,689,1172" href="" alt="imgmap201293016112-36" title="imgmap201293016112-36" class="imgmap201293016112-area" id="imgmap201293016112-area-36" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="691,1232,918,1313" href="" alt="imgmap201293016112-37" title="imgmap201293016112-37" class="imgmap201293016112-area" id="imgmap201293016112-area-37" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="341,1085,573,1151" href="" alt="imgmap201293016112-38" title="imgmap201293016112-38" class="imgmap201293016112-area" id="imgmap201293016112-area-38" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="917,868,917,925,688,927,688,955,576,955,574,867,572,864" href="" alt="imgmap201293016112-39" title="imgmap201293016112-39" class="imgmap201293016112-area" id="imgmap201293016112-area-39" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="919,1173,917,1231,688,1231,688,1266,574,1267,576,1175,576,1175" href="" alt="imgmap201293016112-40" title="imgmap201293016112-40" class="imgmap201293016112-area" id="imgmap201293016112-area-40" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="572,1222,572,1265,459,1265,458,1289,339,1290,344,1225" href="" alt="imgmap201293016112-41" title="imgmap201293016112-41" class="imgmap201293016112-area" id="imgmap201293016112-area-41" />
</map>

A: You can use jQuery to achieve this
Example:
$(function () {
        $('.map').maphilight();
    });

Go through this LINK to know more.
If the above one doesnt work then go through this link.
EDIT :
Give same class to each area tag like class="mapping"
and try this below code
$('.mapping').mouseover(function() {
    alert($(this).attr('id'));
}).mouseout(function(){
    alert('Mouseout....');
});

A: for complete this script , the function for draw circle ,
    function drawCircle(coordon)
    {
        var coord = coordon.split(',');

        var c = document.getElementById("myCanvas");
        var hdc = c.getContext("2d");
        hdc.beginPath();

        hdc.arc(coord[0], coord[1], coord[2], 0, 2 * Math.PI);
        hdc.stroke();
    }


text:
Q: Subclassing a UIView I am trying to subclass a UIView with a custom initializer but am running into multiple errors.
class ProgressAlertView: UIView {

    var title: String

    override init(frame: CGRect) {
        super.init(frame: frame)
        alertLayout()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        alertLayout()
    }

    convenience init(title: String) {
        self.title = title
        self.init(title: title)
    }
}

The code above will result in multiple error messages, among others for my variable title in the convenience init: 'self' used in property access 'title' before 'self.init' call
Swift however requires that all initializers in super class must be called after one initializes other instance variables. So the error must lie somewhere else.
Highly appreciate a tip here.

A: Think about what you expect to happen in…
override init(frame: CGRect) {
    super.init(frame: frame)
    alertLayout()
}

and
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    alertLayout()
}

You have a non-optional instance variable title. How is it supposed to get a value in these 2 cases?
And in your 3rd init…
convenience init(title: String) {
    self.title = title
    self.init(title: title)
}

init(title: String) calls init(title: String), which in turn calls init(title: String), etc. You're in infinite recursion territory.
If you want to instantiate the view in code, you'll need something like…
init(title: String, frame: CGRect) {
    self.title = title
    super.init(frame: frame)
    alertLayout()
}

and you'll also need to implement
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

If you're using this in a storyboard / nib, then you'll need…
required init?(coder aDecoder: NSCoder) {
    self.title = ""
    super.init(coder: aDecoder)
}

and then assign a value to title afterwards


text:
Q: Mouseover functionality in d3 line chart Hi I'm trying to get the mouseover function work for my line chart so I can hover over the line chart and see the values of each point. I tried using the mouse function but it didn't work. How can I fix/do this? I also included a picture of the line chart
 <!DOCTYPE html>
   <html>
  <head>
<meta charset="utf-8">
<title>Unemployment by Ward Bar Chart</title>

<style type="text/css">
.axis text{
  font-family: Arial;
  font-size: 13px;
  color: #333333;
  text-anchor: end;
}

path {
stroke: steelblue;
stroke-width: 2;
fill: none;
 }

 .axis path,
 .axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
 }

 .textlabel{
    font-family:  Arial;
    font-size:13px;
    color: #333333;
    text-anchor: middle;
  }
 }

  </style>
 <body>

  <script src="http://d3js.org/d3.v3.min.js"></script>

  <script>

  // Set the dimensions of the canvas / graph
  var margin = {top: 20, right: 0, bottom: 60, left: 60},

width = 475;
height = 350;
padding = 100;

 // Adds the svg canvas
 var svg = d3.select("body")
.append("svg:svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
   .attr("viewBox", "0 0 " + width + " " + height);

  // Parse the date / time
  var parseDate = d3.time.format("%m/%d/%y").parse;
   var formatTax = d3.format(",.2f");

  // Set the ranges
  var x = d3.time.scale()
    .range([0, width - margin.right - margin.left], .1)
    .nice();

  var y = d3.scale.linear()
    .range([height - margin.top - margin.bottom, 20])
    .nice();

 // Define the axes
 var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .ticks(5);

var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .tickFormat(function(d) {return "$" + d + "B"});

 // Define the line
 var valueline = d3.svg.line()

.x(function(d) { return x(d.Date); })
.y(function(d) { return y(d["Tax Collections"]); });

 // Get the data
  d3.csv("Yearly Tax Collections.csv", function(error, data) {
   data.forEach(function(d) {
    d.Date = parseDate(d.Date);
    d["Tax Collections"] = formatTax(+d["Tax Collections"]/1000000000);
  });

  var g = svg.selectAll("g").data(data).enter().append("svg:g")
        .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);

  // Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.Date; }));

y.domain([0, d3.max(data, function(d) { return Math.ceil (d["Tax   Collections"]); })
        ]);

// Add the valueline path and mouseover
     svg.append("path")
    .attr("class", "line")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
     .attr("d", valueline(data))
     .attr("id", "myPath")
     .on("mousemove", mMove)
     .append("title");

  function mMove(){

 var m = d3.mouse(this);
 d3.select("#myPath")
 .select("title")
 .filter(function(d, i)
  .attr({
    'x':function(d,i) {
        return x(d.Date);

    },
      'y':function(d,i) {
        return y(d["Tax Collections"]);
    }
})
 .text(function(d,i){
    return "$" + d["Tax Collections"] + "B";
 })

 }

// Add the X Axis
svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(" + margin.left + "," + (height - margin.bottom) + ")")
    .call(xAxis);

// Add the Y Axis
svg.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
    .call(yAxis);

    // Y-axis labels
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate ("+ (padding/4) + "," +(height/2)+") rotate(-90)")
.text("Tax Revenue")
.style("font-family", "Arial");

// X-axis labels
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate("+ (width/2) + "," +(height-(padding/4)) + ")")
.text("Fiscal Year")
.style("font-family", "Arial");

 //source

svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate("+ (width/4.5) + "," +(height/1) + ")")
.text("Source: DC OCFO")
.style("font-family", "Arial")

//title for the chart

svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("color", "#333333")
.attr("transform", "translate("+ (width/3) + "," +(height/30) + ")")
.text("DC Total Tax Revenues by Fiscal Year")
.style("font-family", "Arial");

svg.append("text")
.attr("text-anchor", "left")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate("+ (width/20) + "," +(height/12) + ")")
.text("2000 to 2015")
.style("font-family", "Arial")

//line labels

svg.append('g')
.classed('labels-group', true)
.selectAll('text')
.data(data)
.enter()

.append('text')
.filter(function(d, i) { return i === 0||i === (data.length - 1) })
.classed('label',true)

.classed('label',true)
.attr({
    'x':function(d,i) {
        return x(d.Date);

    },
      'y':function(d,i) {
        return y(d["Tax Collections"]);
    }
})
 .text(function(d,i){
    return "$" + d["Tax Collections"] + "B";
 })
 .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

  });

 </script>
</body>

Thank you in avance!


text:
Q: Why am I not able to loop through my JSON file? I am not able to loop through the contents of a JSON file because the JSON file starts with a '.' dot.
How do I clean the JSON file so that it removes the '.' dot in the begining of the file?
Find below my code:
  // Fetch API
  fetch(apiUrl, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(requestBody),
  })
  .then(response => response.json())
  .then(data => {
    // Get the generated response from the API
    const generatedResponse = data.choices[0].text;

    // Console log out response
    console.log("smartResponse:: ", generatedResponse);

    for (let section in generatedResponse) {
      // Get the prompt for the current section
      let prompt = generatedResponse[section].prompt;

      // Do something with the prompt, like print it to the console
      console.log(`Prompt for ${section}: ${prompt}`);
    }

The code above yields:
smartResponse::  .

{
    "whatIsABox": {
        "prompt": "What is a box?",
        "section": "What is a box?"
    },
    "typesOfBoxes": {
        "prompt": "What are the different types of boxes?",
        "section": "Types of Boxes"
    },
    "usesForBoxes": {
        "prompt": "What are some uses for boxes?",
        "section": "Uses for Boxes"
    }
}

Prompt for 0: undefined
Prompt for 1: undefined
Prompt for 2: undefined
Prompt for 3: undefined
Prompt for 4: undefined

The desired result should be:
smartResponse::

{
    "whatIsABox": {
        "prompt": "What is a box?",
        "section": "What is a box?"
    },
    "typesOfBoxes": {
        "prompt": "What are the different types of boxes?",
        "section": "Types of Boxes"
    },
    "usesForBoxes": {
        "prompt": "What are some uses for boxes?",
        "section": "Uses for Boxes"
    }
}

Prompt for What is a box?: A box is a container with six faces.  The faces are made of six panels.  The panels are attached to each other with hinges or latches.  A box has a lid and a bottom.

A: generatedResponse is a string, not an object. You need to remove the . at the beginning, then parse it.

fetch(apiUrl, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(requestBody),
  })
  .then(response => response.json())
  .then(data => {
      // Get the generated response from the API
      const generatedResponse = data.choices[0].text;
      generatedResponse = JSON.parse(generatedResponse.replace(/^\./, ''));

      // Console log out response
      console.log("smartResponse:: ", generatedResponse);

      for (let section in generatedResponse) {
        // Get the prompt for the current section
        let prompt = generatedResponse[section].prompt;

        // Do something with the prompt, like print it to the console
        console.log(`Prompt for ${section}: ${prompt}`);
      }

A: As per the response you mentioned in the OP, Looks like data.choices[0].text is returning a string. So to achieve this you can remove/replace that leading dot by using String.charAt(0).
Demo :

let generatedResponse = `.{
    "whatIsABox": {
        "prompt": "What is a box?",
        "section": "What is a box?"
    },
    "typesOfBoxes": {
        "prompt": "What are the different types of boxes?",
        "section": "Types of Boxes"
    },
    "usesForBoxes": {
        "prompt": "What are some uses for boxes?",
        "section": "Uses for Boxes"
    }
}`;

const jsonStr = generatedResponse.replace(generatedResponse.charAt(0), '');

const jsonObj = JSON.parse(jsonStr);

for (let section in jsonObj) {
  // Get the prompt for the current section
  let prompt = jsonObj[section].prompt;

  // Do something with the prompt, like print it to the console
  console.log(`Prompt for ${section}: ${prompt}`);
}

A: Have you tried using for loop like this.
for (var key in generatedResponse) {
// skip loop if the property is from prototype
if (!generatedResponse.hasOwnProperty(key)) continue;

console.log( generatedResponse[key].prompt );
}


text:
Q: In Scala what is difference Await, Thread.sleep and for comprehensions? I use Redis with Scala. Redis task is a future so I have to study future(Thread).
I found so many ways to wait for a future to stop. I don't know what the difference is. What is difference between a Await, Thread.sleep and for comprehensions?
  val redisResult1 = redis.set(objectId, value)
  Await.ready(redisResult1, Duration.Inf)

  val redisResult2 = redis.set(objectId, value)
  for {
    _ <- redisResult2
  } yield {
    "end"
  }

  val redisResult3 = redis.set(objectId, value)
  while(redisResult3.isCompleted) Thread.sleep(10)

A: Ok, so let's start from the seconds example.
Consider the following code snippet:
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

object Test2{
  def main(args:Array[String]):Unit={
    val f = Future{Thread.sleep(5000); "i'm done"}
    val r = for{
      _ <- f
    } yield "completed"
    println(r)
  }
}

Guess what it will print? It prints
Future(<not completed>)

Process finished with exit code 0

So in fact here you are not waiting for the future to complete, you merely map the result of the first future and return it as the other future which will complete after the first one is completed. As you see the program does not wait till the resulting future is completed and just gracefully exits. The for comprehension on futures is a sugar syntax for mapping and flatmapping them.
The Await.result and Await.ready really wait for the future to complete(or timeout to pass). But they make it in a blocking way, so your thread where you you use these methods will be blocked. This is not always very bad and sometimes might be helpful. E.g. in small test programs or REPL session where you want to finally out the result of your future computations to the console, or for example in tests where you anyway need to wait for the result and test has nothing to do while waiting.
Another way to see you result in such small programs is to use scala.io.StdIn.readLine() so the main thread will hang around and not exit. Consider the following which illustrates this and also provides you with one more additional way to wait for the future completion:
object Test2{
  def main(args:Array[String]):Unit={
    val f = Future{Thread.sleep(5000); "i'm done"}
    f foreach (println(_))

    scala.io.StdIn.readLine()
  }

}

Run it and you will see that program does not exit, prints the result of the future and exits then only after you press the ENTER key.
foreach applied to the future is a shortcut to adding the onComplete listener. Quite handy one.
Regarding the while loop continuously checking if the future is completed - I think it is probably the worst way to wait since it will keep the main thread busy and waste more idle CPU power than relying on efficiently implemented Await.result. Blocking as other things can as well be efficient and inefficient.
To make a sense of all this stuff with futures you need to realize clearly that actual execution of the future happens not in the same thread where you initiated it. In all our examples we just defined the future in the main thread but then it got executed in one of the thread in the imported scala.concurrent.ExecutionContext.Implicits.global execution contexts.

A: The idiomatic approach is to not block for the result. Instead you should chain Futures using map/for comprehensions and things like that.
A for comprehension is just syntactic sugar for flatMaps, maps, and withFilters depending on how you use it.
Not only is this as non-blocking as possible, but it allows you to code the "happy path" and not handle failures until as late as possible.
Many frameworks like Play allow you to never block for the Future to finish and allow you to return Futures to the caller and the Framework handles it for you.
If you do have to handle unwrapping the Future, you probably want to be using onComplete
Check out The Neophytes Guide to Scala for a pretty good tutorial on learning this stuff.


text:
Q: how can i get the average of list in java with no loop public static float myAverage(List<Float> elems){
    return /* Answer with no loop */;
}

how can i get the average of List in one line;
no extra library like apache, no loop
please help me
i can not make another methods and classes.
-----Original---
//The answer must have balanced parentesis, and not containing "exerciseAverage"
import java.util.*;
public class Exercise{
public static float myAverage(List<Float> elems){[???]}
//compute the average, 0f on empty lists
public static float exerciseAverage(List<Float> elems){
    /*omitted*/
    /*omitted*/
/*omitted*/
}
public static void main(String [] arg){
List<List<Float>> tests=Arrays.asList(
    Arrays.asList(1f,2f,3f,4f,5f,6f,7f),
    Arrays.asList(-1f,-2f,-3f,-7f,-13f),
    Arrays.asList(-0.5f,0f,0f,0f,30f,-100f,200f,23f,42f),
    Arrays.asList(-12f/3f,32f,12f,45f,-1000f,99f),
    Arrays.asList(-13f/0f,-100f/0f),
    Arrays.asList(7f,6f,4f,3f,2f,1f,0f,-100f),
    Arrays.asList(7f,6f,4f,3f,2f,1f,0f,1f,2f,3f,4f,5f,6f,7f,8f)
    );
    for(List<Float> ls:tests)
assert myAverage(ls)==exerciseAverage(ls): "error on"+ls+" "+myAverage(ls)+" " +exerciseAverage(ls);
    }
}

--- i found!
return (elems.size() == 0 ) ? 0 : (myAverage(elems.subList(0, elems.size()-1) ) * (elems.size()-1) + elems.get(elems.size()-1))/(float)elems.size();

A: With Java 8:
return elems.stream().reduce(0F, Float::sum) / elems.size();

Or
return (float) elems.stream().mapToDouble(Float::doubleValue).average().getAsDouble();

A: Use recursion:
public static float myAverage(List<Float> elems){
    final int N = elems.size();  // For brevity, inline if you wish
    return (N == 0) ? 0 : (myAverage(elems.subList(1,N)) * (N-1) + elems.get(0)) / N;
}

Live example: http://ideone.com/V7OVT3.
However, note that this will suffer from serious numerical problems; you shouldn't use this for real mathematical work.


text:
Q: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "". (I did type module) I'm getting this error though I don't know what I'm doing wrong (main.mjs and connect-database.mjs work when they aren't connected to html file)

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
index.html:

main.mjs:

connect-database.mjs:

A: Node scripts use the node run-time environment and have program access to resources on the server. They are not compatible with browser run time environments which have a different security model and architecture. Try sending requests to perform, or involve performing, database updates to endpoints on the server which update the DB as part of their request handling.
Typical methods of sending requests from the browser include the use of

*

*form submission

*extracting data from a form and posting it to the server as a FormData object, possibly using XMLHttpRequest to post it,

*the fetch API,

*HTTP request abstractions provided by front-end libraries included in the web page such as axios, or jQuery.ajax


text:
Q: Overloading the > operator with an array of a class I'm trying to compare two different objects inside an array of the object, if I don't use an array it works fine. Putting the objects in an array results in the overloading function not even being called ("yes" does not get printed). I'm not sure if I'm just using the wrong parameters inside my overloading function or what.
 #include <iostream>

using namespace std;

class myClass {
public:
    myClass(int num)
    {
        value = num;
    }

    friend bool operator>(myClass& a, myClass& b)
    {
        cout << "yes" << endl;
        return a.value > b.value;
    }

private:
    int value;
};

int main()
{
    myClass *list[5];

    list[0] = new myClass(15);
    list[1] = new myClass(4);

    if (list[0] > list[1])
        cout << "yes";
    else
        cout << "no";
}

Thanks.

A: list[0] > list[1] is comparing two pointers, which does not use your overloaded operator.  To call the overloaded operator, you would need *list[0] > *list[1].
By the way, the signature of operator> should be bool operator>(const myClass& a, const myClass& b).


text:
Q: How do I implement Facebook's new Registration Tool using Rails? So Facebook have just updated their login/connect product with this:
http://developers.facebook.com/docs/user_registration
I was wondering if anyone had taken the opportunity to play around with it and, if so, whether they'd be happy to help a nuby implement this as the only signup form for a site.
Any ideas?

A:
[Facebooker2] Provides rails helpers for interfacing with Facebook's OpenGraph Javascript
  API, http://developers.facebook.com/docs/reference/javascript/.

Check out this library:
https://github.com/mmangino/facebooker2

A: http://veerasundaravel.wordpress.com/2011/01/27/facebook-registration-plugin-in-rails/

A: Try this

*

*https://github.com/grosser/rpx_now

*https://github.com/slainer68/devise_rpx_connectable

*https://github.com/grimen/devise_facebook_connectable.git


text:
Q: JasperReports with XML as input --- Getiing Inputstream null pointer exception I am using iReport-4.1.1 to create the .jasper and .jrxml FILES. My files are under Webcontent/reports
Below is the code that I am using to open a PDF from jasper. I am passing XML as the input.
InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("/reports/FUECReport.jasper");
JRXmlDataSource xmlDataSource = new JRXmlDataSource(stringToDom(xmlResult));

HashMap parameterMap = new HashMap();
parameterMap.put("TITLE_MSG_PARAM", fUECRptMsg);
parameterMap.put("SURVEY_YEAR_PARAM", surveyYear);
parameterMap.put("STATE_CODE_PARAM", fipsStateCode);

JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, parameterMap,xmlDataSource);
response.setContentType("application/pdf");
servletOutputStream.flush();
servletOutputStream.close();

//this is the function that is converting the xmlsource to Document
public static Document stringToDom(String xmlSource)  throws SAXException, ParserConfigurationException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new InputSource(new StringReader(xmlSource)));
}

When I ran, I get a null pointer exception in the line:
JasperRunManager.runReportToPdfStream(*reportStream*,servletOutputStream, parameterMap,xmlDataSource);

saying reportStream is null
Anybody please let me know where the problem is.
When I run and compile from ireport, I am successfully able to open the PDF.
Thanks
GK

A: Firstly, you should check the path to the report template in line:
InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("/reports/FUECReport.jasper");

May be you should change path to /WEB-INF/reports/FUECReport.jasper? You can try to check the file availability with help of java.io.
On the second, the variable reportStream must contains the compiled report.
The javadoc does not say it for this method (you can read about parameters for the same method with another signature), but you can view the source code of this method:
runReportToPdfStream
public static void JasperRunManager.runReportToPdfStream(java.io.InputStream inputStream,
                                    java.io.OutputStream outputStream,
                                    java.util.Map<java.lang.String,java.lang.Object> parameters,
                                    JRDataSource jrDataSource)
                             throws JRException
                           throws JRException

- Fills a report and sends it directly to an OutputStream in PDF format. The intermediate JasperPrint object is not saved on disk.

Please, check your datasource - prepare another datasource and pass it to runReportToPdfStream method.
You can use JRMapArrayDataSource, the sample of JRMapArrayDataSource using:
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("Title", "Report title");

        Map<String, String> firstRow = new HashMap<String, String>();
        firstRow.put("title", "Greatest Hits");
        firstRow.put("artist", "Dolly Parton");
        firstRow.put("country", "USA");
        firstRow.put("company", "RCA");
        firstRow.put("price", "9.90");
        firstRow.put("year", "1982");

        Map<String, String> secondRow = new HashMap<String, String>();
        secondRow.put("title", "Still got the blues");
        secondRow.put("artist", "Gary Moore");
        secondRow.put("country", "UK");
        secondRow.put("company", "Virgin records");
        secondRow.put("price", "10.20");
        secondRow.put("year", "1990");

        Object[] data = {firstRow, secondRow};

        JRMapArrayDataSource dataSource = new JRMapArrayDataSource(data);

        JasperReport jasperReport = JasperCompileManager.compileReport(reportSource);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);

        JasperExportManager.exportReportToPdfFile(jasperPrint, targetFileName);

If everything will be OK, the problem in method you preparing dataSource.


text:
Q: "CONTENTS" in header issue I am currently using a header on my document that should do one of a few things.
If the current page is before any chapters or sections are defined, the header should only contain a number.
If there are any sections or chapters defined before the current page, the name of the last defined section / chapter should be in the header.
There are two excpetions to this rule. If there is a new chapter, there should be no header on the page or table of contents.
If there is a title page, there should be no footer / header.
This works great. However, when a table of contents is added, all the headers  become prefixed with CONTENTS. How can I prevent the headers being prefixed with CONTENTS without affecting any of the header functionality that was described above.
There is also a case when there is no section or title in the header, but there is a table of contents, the header is consists of CONTENTSCONTENTS.
If it makes a difference, I am building using LuaTex on the latest version of TexLive (downloaded today)
\documentclass[a4paper,oneside]{book}
\usepackage{lipsum}
\usepackage{fancyhdr}

%Header / Footer info
\pagestyle{fancy}
\renewcommand{\chaptermark}[1]{\markright{#1}}
\renewcommand{\sectionmark}[1]{\markright{#1}}

%Define the header / footer
\fancyhf{}
\fancyhead[L]{\topmark}
\fancyhead[R]{\thepage}
\renewcommand{\headrulewidth}{0pt}

\begin{document}
\begin{titlepage}
hello
\end{titlepage}
\tableofcontents
\clearpage
\lipsum[1-10]
\clearpage
\section{Paragraphs 1 - 10}
\lipsum[1-10]
\clearpage
\chapter{Lorem Ipsum :)}
\lipsum[1-5]
\section{Paragraphs 6 - 10}
\lipsum[6-10]
\section{Paragraphs 11 - 15}
\lipsum[11-15]
\end{document}

A: What you are asking is how to get rid of the header "CONTENTS", which is being carried over from the TOC into the beginning of the main text.  That header is present because it is being held as a mark.
You therefore want to obliterate all existing marks when you begin the main text.  The easiest way to do this is to add this command immediately after the \clearpage that closes out the contents:
\markboth{}{}

A: I'm afraid I am too new to LaTeX to know if this is the correct way, it certainly seems a bit to "hacky" to be correct, but it works for me.
The way I succeeded was to use two defined fancyhdr styles, as well as the plain style, and to keep switching the page style at different stages to produce the look I wanted.
At the start of the document, the plain page style was used. Then if there was any text but no chapters / sections defined, a separate fancyhdr was used that simply contained the current page number in the header.
Finally the fancyhdr style from the original code was used. However, the renrewcommand for the \chaptermark and \sectionmark was declared after the page style had been set to this style to force the CONTENTS not to be included in the header.
\documentclass[a4paper,oneside]{book}
\usepackage{lipsum}
\usepackage{fancyhdr}

%Header / Footer info
\fancypagestyle{NormalFancy}{ %Style for when there is at least
                              %one previous chapter or section
    \fancyhf{}
    \fancyhead[L]{\topmark}
    \fancyhead[R]{\thepage}
    \renewcommand{\headrulewidth}{0pt}
}

\fancypagestyle{FancyNoSectionChapter}{ %Style for when there are no
                                        %previous chapters or sections
    \fancyhf{}
    \fancyhead[R]{\thepage}
    \renewcommand{\headrulewidth}{0pt}
}

\begin{document}
\begin{titlepage}
hello
\end{titlepage}
\pagestyle{plain} %Set this here to remove the header and footer
                  %at the start of the document

\tableofcontents
\clearpage

%Set the page style before any chapters or sections are defined
\pagestyle{FancyNoSectionChapter}
\lipsum[1-10]
\clearpage

%Set the page style to the normal style before the start of
%the page with the first defined section / chapter
\thispagestyle{FancyNoSectionChapter}
\pagestyle{NormalFancy} %Make sure the page with the first defined
                        %section / chapter still has the `FancyNoSectionChapter` style
\renewcommand{\chaptermark}[1]{\markright{#1}} %Redefine how the chapter
                                               %looks so there are no numbers
\renewcommand{\sectionmark}[1]{\markright{#1}} %Redefine how the section
                                               %looks so there are no numbers

\section{Paragraphs 1 - 10}
\lipsum[1-10]
\clearpage
\chapter{Lorem Ipsum :)}
\lipsum[1-5]
\section{Paragraphs 6 - 10}
\lipsum[6-10]
\section{Paragraphs 11 - 15}
\lipsum[11-15]
\end{document}


text:
Q: Transferir lista para Arquivo binário em python Bom dia programadores. Preciso colocar uma lista em um arquivo binário mas está apresentando erro.
 lista = [-1, 333.0, -1, 333.0, 10, 8.0, 45, -66.5999984741211, 12, -44.70000076293945]

Código:
  open("saida.bin", "wb") as arq1:
  for x in lista:
      arq1.write(struct.pack('=i', x))
      arq1.write(struct.pack('=f', x))
  arq1.close()

erro:
arq1.write(struct.pack('=i', x))
struct.error: required argument is not an integer

A: O erro te diz exatamente qual é o problema. Quando você faz
arq1.write(struct.pack('=i', x))

Está tentando botar x em um espaço int (como indicado pelo =i), quer dizer, um número inteiro. Uma observação cuidadosa da lista nos revela que alguns dos valores não são inteiros (333.0, -66.59, etc).
Você também está adicionando os mesmos valores como float, quer dizer, números de ponto flutuante (não inteiros) na linha abaixo disso.
Como um float pode assumir um valor inteiro mas um int não pode assumir um valor fracionário, o que eu recomendaria é simplesmente remover a linha
arq1.write(struct.pack('=i', x))

Assim, seus números vão ser guardados como float e você pode retorná-los a uma lista normalmente:
with open('saida.bin', 'rb') as f:
    print(struct.unpack('=10f', f.read()))
# (-1.0, 333.0, -1.0, 333.0, 10.0, 8.0, 45.0, -66.5999984741211, 12.0, -44.70000076293945)

Se for necessário manter o formato de número inteiro para sua aplicação, então você vai ter que verificar o tipo da variável antes de inseri-la no struct.
with open("saida.bin", "wb") as arq1:
    for x in lista:
        if isinstance(x, int):
            arq1.write(struct.pack('=i', x))
        elif isinstance(x, float):
            arq1.write(struct.pack('=f', x))
        else:
            raise TypeError('x não é int nem float!')

Mas aí você tem outros problemas pra resolver porque você também tem que saber o tipo da variável ao dar unpack. Assim, ou você deve ter certeza de que os itens da lista têm seus tipos em uma certa ordem, ou guardar junto alguma informação sobre qual elemento tem qual tipo, ou deve armazená-los separadamente.


text:
Q: Rest API and admin in the same application I'm new to building APIs, I made the first one using an MVC framework: codeigniter, with chris kacerguis rest implementation.
I'm not really sure this was the best think to do because I believe maybe the framework is not that "slim" or light just to API's purposes.
I plan to do a mobile App, an admin and a website so the three can consume the Api's services.
Is it a bad idea to have the API, the website and the admin on the same project? which are the pros and cons? or the best architectural approach?
Otherwise I will have: One Codeigniter project for the API and Another Codeigniter project for website and admin
thanks

A: You can create folders in "controllers" folder to organize your project and use the same project/env configuration :
controllers/Home.php
controllers/api/MyApi.php
controllers/admin/Admin.php

Edit : You will share models and libraries too.

A: In my project I realized 2 types of controller - REST and API. Admin js gui work with REST, other world work with API. You can do it simply with silex framework, a little brother of symfony.

A: The purpose of building a REST API so that you only have to build one project for your business model. This allows you to construct any number of applications on any platform, only requiring you to consume the API in different ways. This essentially separates/decouples the user interface from the business logic, and vice versa.
You should create separate projects for the REST API and each UI project should also be separated projects. This allows you to change the underlying code, language and platform in any one of the projects without breaking any of the other projects as long as the API signatures remain the same.
For example, you could have a live version of your website built using Codeignitor while developing another septate project using AngularJS. When your AngularJS project is complete you would simply swap out the project on your server (or create an entirely new website or server) still allowing you to use the other if required. Additionally, you may decide that you would like to move the API onto a different platform, language or database, develope it and swap the implementation when finished causing no changes to any of your UI projects assuming you have not changed the API signatures.


text:
Q: Self-study. Hypothesis testing and confidence interval Given following porblem.

I have to ask this question because there is no detailed solution (only yes/no).
So my approach.
From given CI I can create following system of equations: $\begin{cases} \bar{X_n} - q_{\frac{\alpha}{2}} \sigma = -2 \\ \bar{X_n} + q_{\frac{\alpha}{2}} \sigma = 3 \end{cases}$,
$q_{\frac{\alpha}{2}} = 2.576$. Solving this system gives us $\bar{X_n} \approx .5$ and $\sigma \approx 0.97$
Next step is to find RR for $H_0$ which is RR={$|\bar{X_n}| > c$}, so $P(|\bar{X_n}| > c) = 0.01$, then I have (1) $P(\bar{X_n} < -c)=(P(Z< \frac{3-c}{\sigma}) = 0.005$ and (2)$P(\bar{X_n} > c)=P(Z > \frac{c+3}{\sigma}) = 0.005$
Then from (1) equation I got $c \approx -2.5$ and so $\bar{X_n} < 2.5$, from (2) $c\approx -0.5$ and so $\bar{X_n} > -.5$. So RR={$-.5 \leq \bar{X_n} \leq 2.5$}, given fact that $\bar{X_n} \approx .5$ belongs to RR $H_0$ should be rejected.
Does it make sense, is my solution valid?
Thanks in advance.

A: Generally, two methods can be used to explore the connection between
a t confidence interval and a t test.
Method 1: Confidence interval defined in terms of testing.
For normal data, a 99% t confidence interval (CI) can be defined
as an interval of values $\mu_0$ which would not be rejected in a
test of $H_0: \mu = \mu_0$ against $H_0: \mu \ne \mu_0.$
For your specific example, $\mu_0 = -3$ is not contained in the CI, so
when you test $H_0: \mu = -3$ against $H_0: \mu \ne -3,$ you will reject $H_0.$
Method 2: Deduce $\bar X$ and $S$ from the confidence interval and use the results to do a t test. This method works, provided that you know it's a t confidence interval and you know $n$ and the confidence level.
A 99% CI for normal mean $\mu$ is of the form $\bar X \pm t^*S/\sqrt{n},$
where $t^*$ cuts probability $0.005$ from the upper tail of Student's t distribution with $n-1$ degrees of freedom.
So you know $\bar X$ is as the center of the CI $(-2,3),$ which is $\bar X = (-2+3)/2 = 0.5.$
If $n = 20,$ then DF $= 19$ and $t^*= 2.861$ from printed tables of t distributions or by using software such as R:
qt(.995, 19)
[1] 2.860935

Then, half of the length $5$ of the CI (sometimes called the margin of error) is $2.5 = 2.861\,S/\sqrt{20},$
which you could solve to find the sample standard deviation $S.$
Finally, knowing $\bar X, S,$ and $n$ you could find the t statistic
$T = \frac{\bar X - \mu_0}{S/\sqrt{n}},$ and compare it with the critical values $\pm c = \pm 2.861$ to decide whether to reject $H_0.$
In this case, we don't know $n.$ I used $n = 20$ just to show an example where $n$ is known. In your case, only Method 1 is available.
Note: Suppose you had $n = 20$ observations as shown below, randomly sampled from a normal distribution with $\mu = -0.5, \sigma = 2.$
Then the procedure t.test in R can be used to test $H_0: \mu=-3$ against $H_a: \mu \ne -3$ at the 1% level and to give a 99% confidence interval for $\mu.$
In this particular case, the 99% CI is $(-2.53,  1.12),$ which does not contain $\mu_0 = -3,$ and a test of $H_0: \mu = -3$ against $H_a: \mu \ne -3$ has P-value $0.002 < 1\%,$ and so is rejected at the 1% level of significance.
set.seed(2020)
x = rnorm(20, -.5, 2)
summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
-6.5775 -2.3287 -0.3243 -0.7047  1.3334  3.1001
sd(x)
[1] 2.852494
t.test(x, mu=-3, conf.lev=.99)

    One Sample t-test

data:  x
t = 3.5985, df = 19, p-value = 0.001915
alternative hypothesis: true mean is not equal to -3
99 percent confidence interval:
 -2.529546  1.120074
sample estimates:
mean of x
-0.704736


text:
Q: Checking the results of the Metropolis - Hastings generated sample I've generated a sample for the distribuition $f(x) \propto cos(x), x \in [-\frac{\pi}{2}, \frac{\pi}{2}]$ through the Metropolis - Hastings algorithm. For that I've used as candidate distribuition $q \sim U_{[-\frac{\pi}{2}, \frac{\pi}{2}]}$ . I've used the following o r code to generate this sample:
N = 10^4
X = runif(n=N, min=-pi/2, max=pi/2)
target <- function (x) cos(x)

for(i in 2:N){

  y = runif(1, min=-pi/2, max=pi/2)
  rho = target(y) / target(X[i-1])
  X[i]  = X[i-1] + (y - X[i-1]) * (runif(1) < rho)

}

The variable X contains the generated sample.  My question is: Is the uniform distribuition i've chosen a good candidate distribuition? How do I check if X is proportionally distributed like $f$? I need to know a way to check if Xis a valid sample for $f$.


text:
Q: POSTGRESQL - Finding specific product when I've attempted to write a query but I've not managed to get it working correctly.
I'm attempting to retrieve where a specific product has been bought but where it also has been bought with other products. In the case below, I want to find where product A01 has been bought but also when it was bought with other products.
Data (extracted from tables for illustration):
Order | Product
123456 | A01
123457 | A01
123457 | B02
123458 | C03
123459 | A01
123459 | C03

Query which will return all orders with product A01 without showing other products:
SELECT
O.NUMBER
O.DATE
P.NUMBER

FROM
ORDERS O
JOIN PRODUCTS P on P.ID = O.ID

WHERE
P.NUMBER = 'A01'

I've tried to create a sub query which brings back just orders of product A01 but I don't know how to place it in the query for it to return all orders containing product A01 as well as any other product ordered with it.
Any help on this would be very grateful.
Thanks in advance.

A: You can use conditional SUM to detect if one ORDER group have one ore more 'A01'
CREATE TABLE orders
    ("Order" int, "Product" varchar(3))
;

INSERT INTO orders
    ("Order", "Product")
VALUES
    (123456, 'A01'),
    (123457, 'A01'),
    (123457, 'B02'),
    (123458, 'C03'),
    (123459, 'A01'),
    (123459, 'C03')
;

SELECT "Order"
FROM orders
GROUP BY "Order"
HAVING SUM(CASE WHEN "Product" = 'A01' THEN 1 ELSE 0 END) > 0

A: Use GROUP BY clause along with HAVING like
select "order", Product
from data
group by "order"
having count(distinct product) > 1;

A: I appreciated Juan's including the DDL to create the database on my system. By the time I saw it, I'd already done all the same work, except that I got around the reserved word problem by naming that field Order1.
Sadly, I didn't consider that either of the offered queries worked on my system. I used MySQL.

*

*The first one returned the A01 lines of the two orders on which other products were ordered too. I took Alex's purpose to include seeing all items of all orders that included A01. (Perhaps he wants to tell future customers what other products other customers have ordered with A01, and generate sales that way.)

*The second one returned the three A01 lines.
Maybe Alex wants:
select *
from orders
where Order1 in (select Order1
                 from orders
                 where Product = 'A01')

It outputs all lines of all orders that include A01. The subquery makes a list of all orders with A01. The first query returns all lines of those orders.
In a big database, you might not want to run two queries, but this is the only way I see to get the result I understood Alex wanted. If that is what he wanted, he would have to run a second query once armed with output from the queries offered, so there's no real gain.
Good discussion. Thanks to all!