text:
Q: Get nearest location from a set of predefined locations with Google Maps Javascript API I have a set of 2 predefined locations and based on user's input of zipcode, I need to show the nearest one.
So far, I have searched the user input location using the zipcode:

$("form#zipcodeSearch").on("submit", function(event){
    event.preventDefault();
    var jsonUrl = 'http://maps.googleapis.com/maps/api/geocode/json?address='+$("input#zipcode").val();

    $.ajax({
        type: "POST",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'text/plain'
        },
        dataType: "json",
        url: jsonUrl,
        success: function (data) {

            var lat = (data.results[0].geometry.bounds.northeast.lat + data.results[0].geometry.bounds.southwest.lat) / 2;
            var lng = (data.results[0].geometry.bounds.northeast.lng + data.results[0].geometry.bounds.southwest.lng) / 2;

            initialize(lat, lng);

        }
    });

});

var map;
function initialize(lat, lng) {
    var mapOptions = {
        zoom: 15
    };
    map = new google.maps.Map(document.getElementById('map-canvas'),
                              mapOptions);

    // Try HTML5 geolocation
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var pos = new google.maps.LatLng(lat, lng);

            var infowindow = new google.maps.InfoWindow({
                map: map,
                position: pos,
                content: '
You are here!
'
            });

            map.setCenter(pos);

        }, function() {
            handleNoGeolocation(true);
        }, {
            enableHighAccuracy: true
        });
    } else {
        // Browser doesn't support Geolocation
        handleNoGeolocation(false);
    }
}

function handleNoGeolocation(errorFlag) {
    if (errorFlag) {
        var content = 'Error: The Geolocation service failed.';
    } else {
        var content = 'Error: Your browser doesn\'t support geolocation.';
    }

    var options = {
        map: map,
        position: new google.maps.LatLng(60, 105),
        content: content
    };

    var infowindow = new google.maps.InfoWindow(options);
    map.setCenter(options.position);
}
*{
    margin: 0;
    padding: 0;
}

body{
    font-family: arial;
    font-size: 62.5%;        /* so, 10px = 1rem */
}

#map-canvas{
    z-index: -1;
    position: absolute;
    top: 0;
    height: 100%;
    width: 100%;
}

<form id="zipcodeSearch">
    <input type="text" id="zipcode" placeholder="Enter Zipcode"/>
    <input type="submit" value="Search" />
</form>

jsFiddle
Any ideas on how to achieve this? If it is not possible with the JS API, is there any other API that can help me achieve this?
EDIT: Cleaned-up jsFiddle version

A: Update:
Keyless access to Google Maps Platform is now deprecated. You will need to have an API key with all your API calls to avoid service interruption . For further details please refer to http://g.co/dev/maps-no-account

Original Answer:
I was able to solve this in following way:

*

*Get lat, long co-ordinates of the input zipcode from this URL:
http://maps.googleapis.com/maps/api/geocode/json?address=zipcode
(add zipcode)

*Take average of the lats and longs of northeast and southwest returned in the response of this URL. Consider the calculated average lat and long as the input co-ordinates.

*Compute the distance to get the closest location using google.maps.geometry.spherical.computeDistanceBetween()

*Initialize the Google Map with all of the markers.

*Use google.maps.LatLngBounds() to adjust the zoom so that the map includes the input zipcode's location and the nearest searched location.

Here's a demo. The H icon stands for the input zipcode location and C icon stands for the closest location among the searched ones. (For now, I have kept only 2 predefined locations).

var predefinedLocations = [{
    "name": "Brookwood Medical Center",
    "lat": 33.4636415,
    "lng": -86.7771671
  },
  {
    "name": "Lutheran Medical Center",
    "lat": 40.646872,
    "lng": -74.020892
  }
];

$("form#zipcodeSearch").on("submit", function(event) {
  event.preventDefault();
  var jsonUrl = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + $("input#zipcode").val();

  $.ajax({
    type: "POST",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'text/plain'
    },
    dataType: "json",
    url: jsonUrl,
    success: function(data) {

      var lat = (data.results[0].geometry.bounds.northeast.lat + data.results[0].geometry.bounds.southwest.lat) / 2;
      var lng = (data.results[0].geometry.bounds.northeast.lng + data.results[0].geometry.bounds.southwest.lng) / 2;
      var p1, p2;

      predefinedLocations.forEach(function(obj) {
        p1 = new google.maps.LatLng(obj.lat, obj.lng);
        p2 = new google.maps.LatLng(lat, lng);

        obj.distance = calcDistance(p1, p2);
      });

      // sort by distance
      var locationInfo = predefinedLocations.sort(compare);

      //console.log('locationInfo', locationInfo);

      initializeGoogleMap(locationInfo, lat, lng);

    }
  });

});

var map;

function initializeGoogleMap(locationInfo, lat, lng) {
  var mapOptions = {
    zoom: 15
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  // zoom to only the input zipcode and closest location
  var latlngbounds = new google.maps.LatLngBounds();
  latlngbounds.extend(new google.maps.LatLng(locationInfo[0].lat, locationInfo[0].lng));
  latlngbounds.extend(new google.maps.LatLng(lat, lng));
  map.fitBounds(latlngbounds);

  var infowindow = new google.maps.InfoWindow();

  var marker, i;

  // set marker for input location
  setMarker(lat, lng, map, 'http://www.lsac.org/images/default-source/mainportalimages/icon-h-grey-bg.jpg?sfvrsn=2', "You are here!", i, infowindow);

  // set marker for closest location
  setMarker(locationInfo[0].lat, locationInfo[0].lng, map, 'http://alert.mta.info/sites/all/themes/mta/images/subway_bullets/c.png', locationInfo[0].name, i, infowindow);

  for (var j = 1; j < locationInfo.length; j++) {
    // set marker for other location
    setMarker(locationInfo[j].lat, locationInfo[j].lng, map, '', locationInfo[j].name, i, infowindow);
  }

}

function calcDistance(p1, p2) {
  return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}

function compare(a, b) {
  if (parseFloat(a.distance) < parseFloat(b.distance)) {
    return -1;
  }

  if (parseFloat(a.distance) > parseFloat(b.distance)) {
    return 1;
  }

  return 0;
}

function setMarker(lat, lng, map, icon, content, i, infowindow) {

  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: map,
    icon: icon
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(content);
      infowindow.open(map, marker);
    }
  })(marker, i));

}
* {
  margin: 0;
  padding: 0;
}

html {
  font-size: 62.5%;
  /* so, 10px = 1rem */
}

body {
  font-family: arial;
}

#map-canvas {
  z-index: -1;
  position: absolute;
  top: 0;
  height: 100%;
  width: 100%;
}

<form id="zipcodeSearch">
  <input type="text" id="zipcode" placeholder="Enter zipcode here" />
  <input type="submit" value="Search" />
</form>

jsFiddle version of the same code
I hope this answer helps someone facing the same problem as I did.


text:
Q: What is the difference between unique_index and unique? What is the difference  between unique_index and unique in GORM?
I am using MySQL 8.0, I cannot find the description about the difference between unique_index & unique form manual.
From here, see specifically the Email and MemberNumber fields:

Declaring Models
Models are usually just normal Golang structs, basic Go types, or pointers of them. sql.Scanner and driver.Valuer interfaces are also supported.
Model Example:
type User struct {
    gorm.Model
    Name         string
    Age          sql.NullInt64
    Birthday     *time.Time
    Email        string  `gorm:"type:varchar(100);unique_index"`
    Role         string  `gorm:"size:255"` // set field size to 255
    MemberNumber *string `gorm:"unique;not null"` // set member number to unique and not null
    Num          int     `gorm:"AUTO_INCREMENT"` // set num to auto incrementable
    Address      string  `gorm:"index:addr"` // create index with name `addr` for address
    IgnoreMe     int     `gorm:"-"` // ignore this field
}

A: unique is a database constraint that (in this case) prevents the multiple record have the same value for MemberNumber. If such an insert or update is made, the operation will not succeed and return an error.
unique_index will create a database index that also ensures that no two values can be the same. It will do the same, but create an index.
In your case: MySQL will use a unique index behind the scenes when using a unique constraint. So when using MySQL, there is no difference when using unique and using unique index.
If you use other database management systems there might be differences.
The differences (if any) will be handled by the database management system internally. For practical purposes you can regard them as the same. The differences will be documented for each database management system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Canvas doesn't draw anything? Kotlin When I write this code it doesn't work:
 if(shapeSpinner?.selectedItemPosition == 0){
            canvas.drawCircle((0..dimensionX).random().toFloat(), (0..dimensionY).random().toFloat(), (0..dimensionX).random().toFloat(), paint)
 }
 if(shapeSpinner?.selectedItemPosition == 1){
            canvas.drawRect((0..dimensionX).random().toFloat(), (0..dimensionY).random().toFloat(), (0..dimensionX).random().toFloat(), (0..dimensionY).random().toFloat(), paint)
 }

But when I write this code it works:
 canvas.drawCircle((0..dimensionX).random().toFloat(), (0..dimensionY).random().toFloat(), (0..dimensionX).random().toFloat(), paint)

But I want the user to be able to choose which shape they want to draw.
Why doesn't the first code work?

A: Is anything selected in the spinner at the time of execution of the drawing code? Maybe you just need to move it into the onSelectionChange listener?


text:
Q: How to set up codecept.conf.js for both android native and ios native in the same project I've worked through the docs and am not finding a solution to this problem.  What I'm trying to do is configure codeceptJS properly so as to be able to execute tests against both native iOS and native Android within the same project.  The docs seem to suggest that one can craft test cases which can target both android and iOS at the same time, e.g.
I.click({android: '//android.widget.Button', ios: '//UIAApplication[1]/UIAWindow[1]/UIAButton[1]'});

However, it's not clear how one would configure the appium helper in codecept.conf.js in order to accomplish this, and I have not been able to uncover any documentation that explains it.  In particular, it seems like the Appium helper can accept either an android .apk or an iOS .app / .ipa for app, but not both.
Would appreciate any insight the community might have on how to achiever this.  I can run against with android or iOS via different projects... but I would much rather do both via the same project, and if possible from the same test cases.

A: You gonna need to configure a script for both android and ios in your package.json, like this:
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "ios": "PLATFORM=iOS APP='/path/to/example.app' DEVICE='iPhone 12 Pro Max' VERSION=14.4 npx codeceptjs run --steps",
  "android": "PLATFORM=Android APP='/path/to/example.apk' DEVICE='Pixel 2' VERSION=9 PACKAGE=com.exampleapp ACTIVITY=MainActivity npx codeceptjs run --steps"},

Then you can use each of the following commands in terminal:
npm run ios

npm run android

If you are using Appium, so you need to configure your codecept.conf.js file this way:
  helpers: {
   Appium: {
   //platform: 'Android',
   platform: 'iOS',
   //app: '/path/to/example.apk',
   app: '/path/to/example.app',
   desiredCapabilities: {
    deviceName: 'iPhone 12 Pro Max',
    platformVersion: undefined,
    appPackage: '',
    appActivity: '',
    automationName: 'XCUITest' //in case your xcode version is not updated
  }
 }


text:
Q: Tenant isolation in SaaS product based on PostGIS - do the same concepts as PostgreSQL apply? We're working on two different GIS apps and we're a bit torn around how to provide a level of tenant data isolation on our GIS systems.
System A would need to have strong tenant data isolation where 1 single app is used by multiple tenants to access their own separate data. We'd be looking at 50-500 range of clients to support and therefore up to 500 individual databases to connect to.
Our plan so far is to find a way to work with isolated shards or altogether different databases. Do all the capabilities of a standard PostgreSQL apply in this scenario? if anything works with PostgreSQL are we safe to assume it will work with PostGIS?
System B does not need complete tenant data isolation but it does need query-level isolation whilst keeping it possible for a 'tenant' manager to query all data.
This is aimed for a single company which has 50+ projects with separate users that need to query only project-relevant data, whilst at the top level being able to also query the data as a whole. We'd like to optimize for project-level query performance in this scenario.
So there's a project-level isolation when running queries for business/performance and to some degree security purposes.
Has anyone encountered any of these use cases with PostGIS/GIS data? We've yet to make a choice for database but PostGIS seems the obvious choice so far.


text:
Q: Is it ok to use Attribute::Handlers for implementing retry logic Is it ok to use Attribute::Handlers for implementing retry logic
I have almost 50+ subroutine like verifyXXXX. I need to implement the retry logic for all these subs. I want to write this retry logic where the sub is actually implemented. If the  return value of sub is false/undef then it will retry again.
subs will be called in regular way, so that the caller will not know about the retry logic, something like.
verify_am_i_doing_good()
    or die('sorry you are not doing as expected.');

verify_am_i_fine()
    or die ('sorry you are not find.');

:
:
the actual implementation of these functions is something like this in the package.
use Attribute::Handlers;

use constant RETRY_LIMIT => 4;
use constant RETRY_DELAY => 2;

sub verify_am_i_doing_good : __retry
{
    return 1 if ($x == $y);
    return;
}

sub __retry : ATTR(CODE) {
    my ($pkg, $sym, $code) = @_;

    my $name = *{ $sym }{NAME};
    no warnings 'redefine';

    *{ $sym } = sub
    {
        my $self = $_[0];
        my $result;

        logMsg (INFO, "Executing subroutine $name with retry limit " . RETRY_LIMIT);
        for (my $retryCount = 1; $retryCount <= RETRY_LIMIT; $retryCount++)
        {
            logMsg (INFO, "Executing subroutine $name with retry count $retryCount");
            my $result = $code->( @_ );
            if ($result)
            {
                logMsg (INFO, "Expected result observed in retry count $retryCount");
                return wantarray ? @$result : $result;
            }
            else
            {
                logMsg (INFO, "Expected result is NOT observed in retry count $retryCount");
                logMsg (INFO, "Retrying again by updating uixml");

                sleep RETRY_DELAY;
                $self->updateState();
            }
        }
        logMsg (WARN, "Failed to verify expected result for subroutine $name with retry limit " . RETRY_LIMIT);
        return;
    };
}

The reason to use Attribute::Handlers, inplace of Attribute::Attempts is that in the case of failure, I need to call another subroutine updateState() before retrying (re-executing) the subroutine.
I got this idea of writing the retry logic from following post http://www.perl.com/pub/2007/04/12/lightning-four.html
My main concern is that since I am using this __retry attribute for almost 50+ subs. Is it a good practice to do in this way or is there anything simple I can do?
You help will be highly appreciated.

A: You don't need attributes to do a sub wrapper. There was Memoize long before there was Memoize::Attrs (or Attribute::Memoize for that matter). You can just take a look at how Memoize handles it.
Quite recently, I was writing some Perl for functions called in another interface. All the arguments passed to the Perl function from this interface would be passed in a funky-but-universal format used by my division. Rather than deal with this everywhere, I wrote a logic wrapper like so
sub external (@) {
    my ( $subname, $code ) = @_;
    ...
    my $wrapped
        = sub {
            my $count = 5;
            while ( --$count and not my @results = &$code ) {
                adjust_stuff();
            }
            return @results;
        };
    {   no strict 'refs'; # my special "no-block"
        *$subname = $wrapped;
    }
    return;
}

And used it like this (some people don't like this use of the "fat comma")
external something_I_want_to_do => sub {
    my @regular_old_perl_args = @_;
    ...
};

The prototype (@) helps a sub act as an operator and need not always be called with parenthesis.
But by all means if you like method attributes and it works and you can get it not to bite you, use them. But you don't have to. You should probably read up on the caveats though.


text:
Q: How to hide 'note: ... ' gcc output for external headers? I try to compile my testproject with gcc 4.8.5. To exclude a warning messages from third-party code I put all external headers into my header - external.h:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
...
#include "Object.h"
...
#pragma GCC diagnostic pop

This works fine for warnings, but I see in gcc output many messages like below:
In file included from /home/testuser/testproject/external.h:26:0,
             from /home/testuser/testproject/main.cpp:14:
/home/testuser/externallib/Object.h: In instantiation of 'int ObjectImpl<T_Class, T_Type, T_Size>::addChild(IObj*, unsigned int) [with T_Class = Shape; ObjType T_Type = (ObjType)12u; unsigned int T_Size = 20u:
/home/testuser/externallib/Object.h:1618:43:   required from here
/home/testuser/externallib/Object.h:817:5: note: declarations in dependent base 'ObjBase' are not found by unqualified lookup
/home/testuser/externallib/Object.h:817:5: note: use 'this->get_Obj' instead

...
Unfortunately, I can't change the third-party code to hide that messages. Could anyone provide a way how to hide 'note:' messages when project builds? This will make my build-logs more clean :). Thanks in advance.

A: Taken from here:
https://unix.stackexchange.com/questions/547567/want-to-turn-off-note-level-messages-in-gcc
Adding:
-fcompare-debug-second

to the GCC build string worked for me.


text:
Q: can't send authToken in Apolloclient in react I need to send authToken along with the uri in appolloclient .
I tried doing it this way but it doesn't seem to send the auttoken .
const client = new ApolloClient({
  uri: 'some url',
  request: async operation => {
   const token = 'MvHE4SXPDa17yzh6Shswhsvwhswdwvd';
   operation.setContext({
     headers: {
       authorization: token
     }
   });
  }
})

I tried this way too
const client = new ApolloClient({
  uri: 'some url,
     headers: {
       authorization: token
     }
   });

What is the correct procedure to send headers with apollo client ?

A: check this out
const authLink = setContext(async (_, { headers }) => {
      // get the authentication token from local storage if it exists
      const token = await getToken();
      // return the headers to the context so httpLink can read them
      return {
        headers: {
          ...headers,
          authorization: token,
        },
      };
    });
    const newLink = authLink.concat(resetUser);
    const client = new ApolloClient({
      link: newLink.concat(link),
      // link,
      cache: new InMemoryCache({
        addTypename: false,
      }).restore(),
    });


text:
Q: SysTrayIcon and Recursive/loop function I'm having a bad time trying to create a simple program that runs in the notification area using the SysTrayIcon
While I can insert the program and start it, I can't manage to Quit/Suspend it from the the tray icon, because my program is in loop using a while True or a recursive function.
from systray import SysTrayIcon
from time import sleep

def program(SysTrayIcon):
    print "I'm Stuck in the loop!"
    sleep(1)
    program(SysTrayIcon)

menu = (('Start', icon.next(), program),)

SysTrayIcon(icon.next(),"Tray",menu)

It runs with no problem, when I click Start, it does what it have to do, in the case, print "I'm Stuck in the loop!" every 1 second, but I can't click to Quit.
Any hint?


text:
Q: SQL-query that finds the table that contains most rows in the database So as the title says i need a query that finds the table that contains most rows in my database.
I can show all my tables with this query:
select * from sys.tables

Or:
select *
from sysobjects
where xtype = 'U'
order by name

And all the indexes with this query:
select *
from sys.indexes

But how do i show the columns with most rows in the whole database?
Kind regards, Chris

A: I use this query usually to sort all tables by rowcount:
USE DATABASENAME
SELECT t.NAME AS TableName, SUM(p.rows) AS RowCounts
FROM sys.tables t
    INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id
    INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
WHERE t.NAME NOT LIKE 'dt%' AND i.OBJECT_ID > 255 AND i.index_id <= 1
GROUP BY t.NAME, i.object_id, i.index_id, i.name
ORDER BY SUM(p.rows) desc

If you want only the firts just add TOP 1 after SELECT
--in reply to your comment----
WHERE
 t.NAME NOT LIKE 'dt%' AND --exclude Database Diagram tables like dtProperties
 i.OBJECT_ID > 255 AND  --exclude system-level tables
 i.index_id <= 1 -- avoid non clustered index

A: Using the answer to this question, you can run the following to see the table with the highest row count:
CREATE TABLE #counts
(
    table_name varchar(255),
    row_count int
)

EXEC sp_MSForEachTable @command1='INSERT #counts (table_name, row_count) SELECT ''?'', COUNT(*) FROM ?'
SELECT TOP 1 table_name, row_count FROM #counts ORDER BY row_count DESC

DROP TABLE #counts

A: You may also use this query to get no duplicates in table names:
Use[DataBase_Name]
select max(i.rows) as recordCounts,t.name as table_name,
SCHEMA_NAME(t.schema_id) as schema_name from sysindexes i
inner join sys.tables t
on i.id=object_id
group by t.name, SCHEMA_NAME(t.schema_id)


text:
Q: How to use Record key as index for function arg type? I currently have :
const useFormTransform = <T>(
  formValues: T,
  transform: Partial<Record<keyof T, (value: T[keyof T]) => any>>,
) => ...

That is used like this :
type Line = { id?: string; fromQuantity: number };
const line: Line = { id: 'abc', fromQuantity: 123 };

useFormTransform(
  line,
  {
    id: f => f,
    fromQuantity: f => transformNumber(Number(f)),
  },
);

I would like to get something like Record<keyof T as U, (value: U) => any> for the transform arg so the value is not string | undefined | number but number since typeof line['fromQuantity'] === 'number'
I tries many things but I can't get it to work.
Thanks ! :)

A: You can't do it with Record you will need a custom mapped type:

const useFormTransform = <T, U extends keyof T>(
  formValues: T,
    transform: {
      [P in keyof T]: (value: T[P]) => T[P]
  },
) => {
    return null!;
}

type Line = { id?: string; fromQuantity: number };
const line: Line = { id: 'abc', fromQuantity: 123 };

useFormTransform(
  line,
  {
    id: f => f,
    fromQuantity: f => f + 1,
  },
);

Playground Link


text:
Q: Angular 4.3+ : HttpClient generic I'm getting a syntax error for specifying a generic type T as the return value of this method:
  private getResource<T>(resource: string, pagination?: string): T {
    this.updateSessionToken();
    const url = this.buildUrl(resource, pagination);
    this.http
      .get<T>(url, {headers: this.headers, observe: 'response'})
      .retry(3)
      .subscribe(
        (response) => {
          return response;
        },
        (error: HttpErrorResponse) => {
          return error;
        }
      );
  }

What would be the fix to avoid using the any or void as the following suggestion by tslint:

A: If you define a return value which is neither void nor any (which also allows returning void), you must return a value in any return path.
Your getResource function never returns any value, since it has no return statement.
The only places you define a return value is inside another nested lambda function, as the syntax (arg1,arg2,...) => {...} implies. Thus, writing a return statement inside the body of this nested function would NOT return a value for the outer function, as you probably tried to do. Furthermore, http.get function is asynchronous, which means that you send the request and go on with reading the function code, and not being blocked while waiting for a response, and since there is no next line for the function, you exit the function without returning any value.
It seems like your architecture might be wrong, because in asynchronous programming you should not expect an immediate response, and instead supply the consequent action as a success lambda (instead of returning the response, use it the way you would use it outside that function), and the same for a failure function.
I suggest you to read a bit more about the topic of asynchronous request because it is a primary principle in web development, and recommend you to read specifically about Observer (which works basically on the same concept of Promise) in Angular.


text:
Q: Directive Angular JS Have three html screens.
Screen1.html:
<button id="screenbtn"></button>

Screen2.html:

  Label for screen two

Screen3.html:

      Label for screen three

All these screens are in different folders but under same root.
So on click of the button I need to toggle between screen2 and screen3, need to achieve using Angular Js.
As it is easy to manipulate in Jquery which I already achieved, but the scenario is to achieve in Angular JS.
Can any one please let me know how to achieve this with basic demo.

A: Sounds like you want to use a routeprovider.
angular.module('myApp', ['ngRoute']).config(function($routeProvider) {
  return $routeProvider.when('/screen1', {
    templateUrl: 'screen1.html',
    controller: 'aController'
  }).when('/screen2', {
    templateUrl: 'screen2.html',
    controller: 'bController'
  });
});

Screen 1

Screen 2

I made a working example here
Keep in mind that in order to use the ngRoute you need to include it in your project.


text:
Q: numpy C-API: scalar multiplication in C How can I perform an element-wise multiplication of a numpy-nd-array with an arbitrary double-scalar in C?
I'm searching for a api-function like this:

// C-code
PyArray_MultiplyWithScalar((PyArrayObject *) myarray, double scalar_value);

corresponding to pure numpy:

# pure python
myarray = myarray * scalar_value

My current (bad) solution is to iterate over all entries and perform the normalization manually.

A: I don't know the right answer to your question, but if you do a loop in C that should be as fast as it gets, I would even think faster than calling a python api function if you do it right. Doing it that way you can even edit the array in place without the need for additional memory.


text:
Q: JavaServer Faces (JSF) and Twitter BootStrap: h:outputStylesheet and relative urls I'm using JavaServer Faces (JSF) to define layouts for pages which use Twitter BootStrap for styling (this question however is not strictly specific to BootStrap).
I defined the import of the bootstrap css stylesheet file and it works correctly except that it doesn't correctly interpret image urls inside the bootstrap css stylesheet.
<h:outputStylesheet name="bootstrap/css/bootstrap.css"></h:outputStylesheet>

Therefore a line like the one below inside bootstrap.css is not correctly finding the correct img file.
background-image: url("../img/glyphicons-halflings.png");

Am I missing something? how do I fix this?
Thank you


text:
Q: how to write a logical n-tier windows desktop application for both a physical 1-tier AND physical 3-tier deployment? I'm working on a unique windows desktop application that requires both a standalone and distributed deployment mode. In standalone mode the entire program will run on a single desktop machine. In distributed mode there will be several thin clients running on desktop machines that will communicate with an app server (IIS) and database over a LAN.
I will write the program using a logical n-tier architecture to separate the GUI, business logic, and data access layer.
Ideally I want the code for the stand alone mode to be the same as the distributed mode but just deployed differently. Does it make sense then to use WCF (or some form of web services) in the stand alone mode so that it can then be deployed in distributed mode without needing major code changes? Is there a better way to do this?
Thanks!

A: Visual Studio LightSwitch1 does a trick pretty similar to what you describe: develop once, deploy in single or three tiers. If you're app is mostly about data maintenance it may very well be your ticket.


text:
Q: Ruby : How to convert bytes array to image file (.jpg, .png ...) I received string representating a bytes array to a web service :

"/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL
  ... "

I want to know how to convert the bytes array to image bin file. Are there any gems to do that or do i need to manipulate it with File library.
I read some examples but not great solutions in Ruby.
Do i need first to convert string into bytes array and after file ? And what is the extention that i have to use ?
Thanks a lot.

A: Answer to the 1st part of your question
Your input looks like base64. so I'll assume you need to first decode from base64:
binary_data = Base64.decode64(data_from_web_service)
File.open('file_name', 'wb') {|f| f.write(binary_data)}

The answer to your 2nd part (how to detect the file extension) is the trickier part. Doesn't the web service return any information about this? If not, you may be successfull by analysing the magic number of the data.

A: Can you not just write the string to a file:
File.open('picture.jpg', 'w') { |file| file.puts(string) }


text:
Q: Float left bug in Firefox when when parent is absolutly positioned? I have an unusual layout requirement but Ive got it working in Chrome, Edge and IE11, only Firefox doen't work making me think it could be a bug with the browser.
Here is how the page should look:

But this is how it looks is Firefox:

Update: I also got this working on Chrome without float: left and instead using width: fit-content, however this and width: -moz-fit-content still don't work on Firefox.
The floated div with the red boarder doenst appear to be floated at all. As a result the blue box is off screen.

* {
  box-sizing: border-box;
}

body {
  padding: 0;
  margin: 0;
}

.wrapper {
  overflow: hidden;
}

.cont {
  display: flex;
  background: grey;
  margin-left: auto;
  margin-right: auto;
  max-width: 1000px;
}

.col {
  flex-basis: 50%;
  min-height: 600px;
  position: relative;
}

.col-1 {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.col1-inner {
  position: absolute;
  top: 40px;
  left: 0;
  bottom: 40px;
  right: -2000px;
}

img {
  max-width: 100%;
  width: auto;
  height: 100%;
}

.content {
  border: 2px solid red;
  float: left;
  height: 100%;
  position: relative;
}

.content:after {
  content: "";
  background: blue;
  display: flex;
  width: 100px;
  height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

Content

Stuff Stuff Stuff Stuff Stuff Stuff Stuff Stuff Stuff Stuff Stuff Stuff Stuff Stuff Stuff Stuff Stuff Stuff

https://codepen.io/_j_i_m_fb_/pen/GRgaKQE

A: Lame answer to the actual question
This is an edge case due to the large fixed units used. Chrome is collapsing the div when float is used. Firefox is not. To determine which browser is technically correct we must look at the appropriate specification. How boring is that... instead, here is a...
... possible solution for what you desire
I have created an alternative example with CSS Grid.
HTML
Simple layout. The body is used instead of an extra div, with two divs for the left and right column:

Content

Contents

CSS
The body:
body {
  display: grid;
  grid-template-columns: auto auto;
}

*

*Establish the grid.

*Create two equal width columns

The content div:
.content {
  display: grid;
  align-content: center;
  max-width: 600px;
  min-width: 400px;
  background: grey;
  padding: 0 20px;
  margin: 0 0 0 auto;
}

*

*Establish the inner grid

*Vertically center the contents

*Use appropriate max and min widths

*Instead of justify-items: end, the left auto margin provides the horizontal centering. This is so the background doesn't stretch all the way to the left.

The image div:
.image {
  position: relative;
  max-width: 700px;
  min-width: 500px;
  background: linear-gradient(to right, grey 0, grey 50%, transparent 50%);
}

*

*Position the pseudo-element in relation to this div

*Restrict the width of the image so it doesn't get too large

*Restrict the width of the image so it doesn't get too small

*Create the background colour with a gradient that covers only a percentage of the image div

The img is contained like so:
img {
  max-width: 100%;
  padding: 40px 0;
}

*

*Restrict width of image to parent div

*Pad out as desired

Example

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  display: grid;
  grid-template-columns: auto auto;
}

.content {
  display: grid;
  align-content: center;
  max-width: 600px;
  min-width: 400px;
  background: grey;
  padding: 0 20px;
  margin: 0 0 0 auto;
}

.image {
  position: relative;
  max-width: 700px;
  min-width: 300px;
  background: linear-gradient(to right, grey 0, grey 50%, transparent 50%);
}

.image::after {
  content: "";
  height: 100px;
  width: 100px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: blue;
  position: absolute;
}

img {
  max-width: 100%;
  padding: 40px 0;
}

Content

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec id bibendum enim. Integer blandit arcu lobortis, ultricies quam vitae, elementum urna. Nunc a mauris ex. Aenean egestas neque urna, eu euismod massa ultrices sit amet. Praesent imperdiet
    dictum ante, quis viverra nibh volutpat eu. Sed tempor, quam in molestie tincidunt, eros massa condimentum arcu, ut tempus mauris ligula et arcu. Donec nec faucibus neque, sit amet tincidunt nulla. Nullam et mattis ipsum. Sed euismod porttitor justo
    eu aliquet. Sed hendrerit finibus dignissim. Morbi id ipsum imperdiet, fringilla urna posuere, fermentum justo. Mauris eleifend, orci et eleifend consectetur, augue lacus hendrerit diam, eget dictum lacus sem vitae augue.


text:
Q: Different objects with the same name using a loop Why is the following correct and working? I thought each object should have a different name:
LinearLayout rootView = (LinearLayout)findViewById(R.id.rootView);

int i = 0;
while (i<5) {
    TextView wordView = new TextView(this);
    wordView.setText(words.get(i));
    rootView.addView(wordView);

    i++;
}

However, if I tried to do it without loop:
TextView wordView = new TextView(this);
wordView.setText(words.get(0));
rootView.addView(wordView);

TextView wordView = new TextView(this);
wordView.setText(words.get(1));
rootView.addView(wordView);

It's not allowed, so how does it work exactly in java - that a loop creates different objects with the same name?
Thanks!

A: What you need to understand is the block scope for a local variable i.e., Each local variable scope is limited to the block and try the following code and it will work:
{//1st block started
   TextView wordView = new TextView(this);
   wordView.setText(words.get(0));
   rootView.addView(wordView);
  //1st block wordView scope ends here
}//1st block ended

{//2nd block started
   TextView wordView = new TextView(this);
   wordView.setText(words.get(1));
   rootView.addView(wordView);
    //2nd block wordView scope ends here
}//2nd block ended

Also, coming to while loop, you can think of it like 5 blocks like above (i.e., each block getting executed for each iteration).
You can refer here from JLS how the local variable scope works:

Every local variable declaration statement is immediately contained by
  a block. Local variable declaration statements may be intermixed
  freely with other kinds of statements in the block.

Also, just one correction on your phrase "each object should have a different name", this should be like "each reference variable should have a different name" to make more sense (because objects are assigned to and pointed by reference variables).

A: This should guide you to enable you get different output name base on the arrays
 and if you are looking at same name loop

public static void main(String[] args) {
String option1 = "o1v1,o1v2,o1v3";
String option2 = "o2v1,o2v2,o2v3";
String option3 = "o3v1,o3v2,o3v3";
ArrayList<String> output = new ArrayList<String>();

String[] options1 = option1.split(",");
String[] options2 = option2.split(",");
String[] options3 = option3.split(",");

for(int i=0; i<options1.length; i++){
    StringBuilder sb = new StringBuilder();
    sb.append(options1[i]);
    sb.append(options2[i]);
    sb.append(options3[i]);
    output.add(sb.toString());

}

System.out.println(output);

}

Though this will output with a comma


text:
Q: Setting an observable on a 5 second timer RXJava I'm using RXJava 2 to perform an operation. I would like the operation to happen every 5 seconds. However after introducing the interval method it changes my function and breaks my .subscribe(DisponsableObserver<Boolean>)
mObserver = getObserver();              //return DisponsableObserver<Boolean>
observable = getSolultionObservable();  //return Observer<Boolean>

observable.subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .interval(5, TimeUnit.SECONDS)
            .subscribe(mSolutionObserver); //Now Produces Cannot Resolve Method error

How can I succesfully run my observable on a timer and return a boolean?

A: You can use the flatMap operator for converting the items (long) emitted by the interval every 5 seconds, into your Observable
Observable.interval(5, TimeUnit.SECONDS)
    .flatMap(long -> observable)
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(mSolutionObserver);

EDIT:
without lambda expression:
Observable.interval(5, TimeUnit.SECONDS)
    .flatMap(new Function<Long, ObservableSource<Boolean>>() {
                @Override
                public ObservableSource<Boolean> apply(Long aLong) throws Exception {
                    return observable;
                }
            })
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(mSolutionObserver);


text:
Q: Prevent imported libraries from using my logging-configuration file Hostile takeover of my logger !!

TL:DR imported library is using my logger's logging.properties file.
In order to keep track of everything that happens in my project, I implemented a custom logger class using java.utils.logging, with a nice simple configuration file "logging.properties":
handlers= java.util.logging.ConsoleHandler, java.util.logging.FileHandler
.level= ALL

java.util.logging.FileHandler.pattern = server/java/data/logs/myOwnLog%u.log
java.util.logging.FileHandler.limit = 20000
java.util.logging.FileHandler.count = 10
java.util.logging.FileHandler.formatter = server/java/src/main/java/controller/utils/logs/LineFormat.java

java.util.logging.ConsoleHandler.level = ALL

com.journaldev.files = SEVERE

Now after adding it, for some reason, one of my imported libraries - GraphStream start to use my configuration file.
Which means I get thier logs printed to my console and saved in log files in the location and with the name I defined in the configuration file.
I thought maybe there was a conflict of names with there configuration file but it wasn't it.
Any ideas?

first 3 lines are my logs and the rest are belongs to GraphStream.

A: This is how logging in Java works: anything can attempt to write logs, and if you have configured the logging framework that it's trying to use, you'll get its messages.
The way to stop seeing messages third-party libraries is to disable them in your logging configuration (or, alternatively, disable everything except your own classes) by changing the level at which they report.
I don't use java.util.logging, but by reading the docs it appears that you could include a configuration line like this to turn off a third-party package:
com.thirdparty.level = OFF

Or alternatively, default everything to OFF and set your packages to DEBUG:
.level = OFF
com.mycompany.level=DEBUG


text:
Q: How to limit API calls when using the Developer Console? In a Winter '14 Developer Edition and Spring '14 Pre-release I have noticed that using the Developer Console uses API calls.  It looks like this affects third party tools like MavensMate as well.  The limit for a Developer Edition is 5,000 / 24 hours and I've used about 125 in a 20 minute period.  This is without running unit tests.  Running unit tests burns through the API calls even quicker.
Add in another developer, code that uses the API, and frequent unit test execution and the limit can be hit without much effort.
Is there any configuration that I can make to not use as many API calls with the Developer Console?  Perhaps, some features that I can disable?
It's possible that it is related to this Idea about the Tooling API and limits.

A: You can reduce your API usage by allowing your developer console session to "idle". Once idle, you'll only incur one API call per incident (such as saving a class, running a test). While not idle, the current implementation polls the server once every 6 seconds, or 10 API calls per minute while doing absolutely nothing.
Also, using the Force.com IDE will drastically reduce your API calls, because you won't suffer from the "monitoring" API calls. Believe it, it makes a big difference.
For those interested, I asked this myself on the Salesforce Community:

@Josh Kaplan (Salesforce.com), in addition to the code coverage
  glitches in the API, your comment
  https://success.salesforce.com/ideaView?id=08730000000kuJtAAI about
  retiring the setup pages in exchange for the Developer Console is
  worrisome. Today, using the console consumes one API call per six
  seconds per developer. Given that a normal developer org has 5,000
  calls per day, this means that two developers working in the same
  organization (the maximum a normal developer edition supports) can
  only work for 4 hours a day actively in that organization before
  exhausting their daily usage limits. If we are required to use the
  console, we will be limited to working just a few hours a day inside
  the platform. Is there any plan to have the console no longer use API
  calls?

Josh Kaplan (SFDC PM) had this to say:

Starting with the coming release the number of API calls will
  dramatically decline. Results will be streamed, so polling will not
  consume so many API calls.

Presumably this applies to Spring '14.


text:
Q: GCP Dataflow vs Cloud Functions to automate scrapping output and file-on-cloud merge into JSON format to insert in DB I have two sources:

*

*A csv that will be uploaded to a cloud storage service, probably GCP Cloud Storage.

*The output of a scrapping process done with Python.

When a user updates 1) (the cloud stored file) an event should be triggered to execute 2) (the scrapping process) and then some transformation should take place in order to merge these two sources into one in a JSON format. Finally, the content of this JSON file should be stored in a DB of easy access and low cost. The files the user will update are of max 5MB and the updates will take place once weekly.
From what I've read, I can use GCP Cloud Functions to accomplish this whole process or I can use Dataflow too. I've even considered using both. I've also thought of using MongoDB to store the JSON objects of the two sources final merge.
Why should I use Cloud Functions, Dataflow or both? What are your thoughts on the DB? I'm open to different approaches. Thanks.

A: Regarding de use of Cloud Functions and Dataflow. In your case I will go for Cloud Functions as you don't have a big volume of data. Dataflow is more complex, more expensive and you will have to use Apache Beam. If you are confortable with python and having into consideration your scenario I will choose Cloud Functions. Easy, convenient...
To trigger a Cloud Functions when Cloud Storage object is updated you will have to configure the triggers. Pretty easy.
https://cloud.google.com/functions/docs/calling/storage
Regarding the DB. MongoDB is a good option but if you wanth something quick an inexpensive consider DataStore
As a managed service it will make your life easy with a lot of native integrations. Also it has a very interesting free tier.


text:
Q: Is there a way to convert a list to aligned columns/grid by F-String? How I can convert a single list to align columns/grid via f-string code? I know that this would be possible via certain packages, but I am only allowed to use f-string.
I have a list consisting of several items. For example:
lst = ['a', 'b', 'c', 'd', 'e'], ['1','2','3','4','5'], ['1', '3', '331', '1', '82']

Is there a way to make it look like a grid of aligned columns like this:
a b   c d  e
1 2   3 4  5
1 3 331 1 82

A: This is particularized to your example tuple but it does utilize f-strings:
lst = ['a', 'b', 'c', 'd', 'e'], ['1','2','3','4','5'], ['1', '3', '331', '1', '82']

for item in lst:
    print(f'{item[0]:>2}{item[1]:>2}{item[2]:>4}{item[3]:>2}{item[4]:>3}')

Output:
a b   c d  e
1 2   3 4  5
1 3 331 1 82

This might prove illustrative.


text:
Q: ngOnInit can't update a local variable Pretty simple really, I have a variable set up on the page which I use to create a bunch of boxes on the font end. I initialise this variable like so:
organisations: Organisation[];

and then in ngOnInit I am getting some data back from storage which I will then use to populate this variable. So the whole page looks like this:
export class SelectOrganisationPage implements OnInit {
  organisations: Organisation[];

  constructor(private authentication: AuthenticationService, private storage: Storage) { }

  ngOnInit() {
    this.storage.get(USER_DETAILS).then(user => {
      const parsedUser: User = JSON.parse(user);

      parsedUser.organisations.forEach(org => {
        if (!org.active) {
          return;
        }

        this.organisations.push(org);
      });
    });
  }
}

On the line this.organisations.push(org); I get the following error:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined

I don't understand why it can't read this.organisations at that point. Unless I am mistaken on the actual error?
This is contextually different to the other question.

A: The error says organisations is undefined, so you have to initialize it with an empty array.
Try like this:
organisations: Organisation[] = [];


text:
Q: How to make a footer popup to cover all page? I want to do the following:

*

*Press menu link called "Contacts" - Done

*Create a footer with Email, Rights & Contacts - Done

*After press "Contacts" (menu), all page becomes white and Email, Rights & Contacts stay on middle (jQuery maybe?)

Is this possible?
I don't want to create a page with contact forms, just for this. I should just continue my index.html page with #contacts on bottom, and use Parallax or FullPage.JS?
See the page & code: www.wemadeyou.pt

A: Yes this is possible and not very difficult.  One way you can do it make a div on the page and use css display: none to hide the div. Then use jQuery to show that div when the 'Contacts' menu button is clicked.
Something like:
Html:

Here is some content

    <form class="contact-form">

    </form>

CSS:
.contact-form-container {
  display: none;
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.25);
  z-index: 200;
}

JS (jquery):
$(document).ready(function() {
  $('.contacts').click(function(e) {  //or whatever the class/id of your menu button is
    e.preventDefault();
    $('.contact-form-container').toggle();
  }
}

This will get you  most of the way there.  You will still have to handle the form of course.
Hope that helps.


text:
Q: R: How to pass rVector through java in connection eval () function R Code
abc <- function(theta,y) {
    a <- y[1]
    b <- y[2]
    c <- y[3]
    p <- c/(1+(a*(theta-b)))
    return(p)
}

Java Code
RConnection connection = new RConnection();
connection.eval("source('D:\\\\file.R')");
double theta = 7
double a = 5
double b = 9
double c = 2
double y = "c(a,b,c)" // 'y' is R vector of length 3 (one-dimensional array)
with a, b, and c parameters as elements
double sum = connection.eval("abc("+theta+","+y+")")
log.info("The sum is=" + sum);

Problem
I want to pass vector (y) on eval function but not able to do that. Is there any way to do that ??


text:
Q: LaTeX export or convert into either R or Matlab? Forgive me if this may be already asked. I am kind of new to all this. I wondered if there is a simple facility to have Matlab or R import or convert from LaTeX documents? This would be no different than how you can create a MuPAD script document and convert into Matlab M code. This would be through the Matlab Math Symbol toolbox.
Thanks

A: No, converting general LaTeX equations into some sort of procedural programming language is most decidedly not possible.
LaTeX is a system for creating documents with structured text formatting and typesetting. It is not much different than writing individual letters and symbols onto a piece of paper yourself; there are no intrinsic semantics as to which symbols mean what. It doesn't know (or care) if the expression x = y is an assignment or a test for equality. Or if \cdot is a dot product or simple multiplication. All that really matters in the end is that the equations are readable and look good to a human eye. To convert this soup of symbols into a procedural programming language is quite impossible.
MuPAD, however, is a computer algebra system. You tell it what is a function and what are variables. It has this knowledge.  As such, it is able to identify inputs and outputs and some sort of directional flow. It has a grammar to its equations: you must, for example, use := to denote assignment. When converting to an m-file, MuPAD uses this additional information to determine which variables are scalar or vector, what is an assignment and what is a boolean test, what is input and what is output, etc.
This difference is obvious in usage of MuPAD vs LaTeX: one can rearrange and simplify your equations for you, the other cannot.


text:
Q: selecting top record in ORACLE join statement between subqueries I would like to ask for your help for constructing a single ORACLE SQL statement:
using job table as below
Object | Operation | Time
A      | Move      | 12:01
B      | Move      | 12:02
C      | Pickup    | 12:03
D      | Move      | 12:04
B      | Pickup    | 12:05

to get the result table as below.
Object | Operation | Time  | Cause
A      | Move      | 12:01 | C
B      | Move      | 12:02 | C
D      | Move      | 12:04 | B

This is to figure out which Pickup operation caused each Move operation.
"Cause" column must include Object of the pickup job record with smallest time right next to move operation.
I have some ideas as below but do not know how to.
-. It requires join statement between subquery for Move and subquery for Pickup
-. Subquery for Pickup must be partitioned by move record to be joined
-. Must select top record only from each partition of Pickup subquery

A: This is my try:
select  m.object, m.operation, m.time,
  max(p.object) keep (dense_rank first order by p.time) cause,
  max(p.time) keep (dense_rank first order by p.time) cause_time
from a m
join a p on (p.time > m.time)
where m.operation = 'Move'
and p.operation = 'Pickup'
group by m.object, m.operation, m.time;

see SQLFiddle
I've put column time as number, this does not have any importance as it is sortable.
I've splitted the table in two, Moves and Pickups and the join is made on time, time of pickup being greater than time of move. (This type of join is not great on performance). Then I choose the pickup with smallest time(first clause, with order by p.time).

A: This is my try:
select object, operation, time, t.pobject
from a join
   (select object pobject, time cur, lag(time,1, 0) over (order by time  ) prev
      from a
     where operation = 'Pickup')t
on a.time > t.prev and a.time <= t.cur
where operation = 'Move';

Here is a sqlfiddle

A: There is one from old-school
select j1.Object, j1.Operation, j1.Time, substr(min(j2.Time || j2.Object), 6) Cause
from job j1, job j2
where j1.Operation like 'Move'
  and j1.Time < j2.Time
  and j2.Operation like 'Pickup'
group by j1.Object, j1.Operation, j1.Time

Here is SQLFiddle


text:
Q: Examples of arbitrary groups If $G$ is an arbitrary group with order $m$ and $n$ divides $m$, then $G$ need not have a cyclic subgroup of order $n$. Find two such examples, one where $n=m$ and another where $n<m$.

Should I be looking at certain types of groups here? I've looked at $U(\mathbb{Z}_{13})$ and didn't have any luck, so I figured I'd ask.

A: Let $G=S_4$, the symmetry group of degree 4. Then $m=|G|=24$. But $G$ does not have any elements of order $n=12$. This is the example for $n <m$. The group for $n=m$ is easy to find, for example, $S_3$.


text:
Q: How do I get hundred percent code coverage with my unit testing on this component and access the else part? I have no idea how to access the remaining line of code. I simply need to get a full code coverage. Checking if the function has been called (toHaveBeenCalled() ) will also do.
Pasting in the TypeScript file and my Spec file. My current code-coverage is as follows
TOTAL: 7 SUCCESS
==================== Coverage summary ========================
Statements   : 87.5% ( 35/40 )
Branches     : 100% ( 10/10 )
Functions    : 75% ( 6/8 )
Lines        : 86.11% ( 31/36 )
================================================================================

auth-guard.service.ts
import { AuthKeywords } from './../_models/common.model';
import { environment } from 'src/environments/environment';
import { AppService } from './../app.service';
import { Observable, of } from 'rxjs';
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { ConfirmationService } from 'primeng/api';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
  isLoggedIn: boolean = false;
  constructor(public router: Router, public appService: AppService,
    public cookieService: CookieService, public confirmationService: ConfirmationService) { }

  canActivate(): Observable<boolean> {
    const token = this.cookieService.get(AuthKeywords.TOKEN);
    if (token && !this.tokenExpired(token)) {
      this.isLoggedIn = true;
      return of(this.isLoggedIn);
    } else {
      this.appService.confirmButtonLabel = 'Login';
      this.confirmationService.confirm({
        message: 'You are not logged in, Please login to Traders Desktop',
        accept: () => {
          this.isLoggedIn = false;
          window.location.replace(environment.traders_desktop);
          return of(this.isLoggedIn);
        }
      });
    }
  }

  public tokenExpired(token: string) {
    const expiry = (JSON.parse(atob(token.split('.')[1]))).exp;
    return (Math.floor((new Date).getTime() / 1000)) >= expiry;
  }
}

auth-guard.service.gen.spec.ts
import { TestBed } from '@angular/core/testing';
import { AppService } from './../app.service';
import { Router } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { Confirmation, ConfirmationService } from 'primeng/api';
import { AuthGuardService } from './auth-guard.service';
import {} from 'jasmine';

describe('AuthGuardService', () => {
  let service: AuthGuardService;

  beforeEach(() => {
    const appServiceStub = () => ({ confirmButtonLabel: {} });
    const routerStub = () => ({});
    const cookieServiceStub = () => ({ get: token => ({}) });
    const confirmationServiceStub = () => ({ confirm: object => ({}) });

    TestBed.configureTestingModule({
      providers: [
        AuthGuardService,
        { provide: AppService, useFactory: appServiceStub },
        { provide: Router, useFactory: routerStub },
        { provide: CookieService, useFactory: cookieServiceStub },
        { provide: ConfirmationService, useFactory: confirmationServiceStub }
      ]
    });
    service = TestBed.get(AuthGuardService);
    const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dnZWRpbiI6dHJ1ZSwidXNlcm5hbWUiOiJ5YXNoLW1pc2hyYSIsImxvZ2luX3RpbWUiOjE2MDE0NTMxNDAsIkxBU1RfQUNUSVZJVFkiOjE2MDE0NTMxNDAsInN1cGVyX3VzZXIiOnRydWUsImlzcyI6IlRyYWRlVmlzaW9uMjAyMC5jb20iLCJzdWIiOiJDaGFydElRVmVyaWZpY2F0aW9uIiwiYXVkIjoieWFzaC1taXNocmEiLCJleHAiOjE2MDE1Mzk1NDB9.6S2cIrflTPRdTjXIaYaFcb2J5LrTa9-yqzfVVuNC85M';
    service.tokenExpired(token)
  });

  it('can load instance', () => {
    expect(service).toBeTruthy();
  });

  it(`isLoggedIn has default value`, () => {
    expect(service.isLoggedIn).toEqual(false);
  });

  it('checks button label value', () => {
    const appServiceStub: AppService = TestBed.get(AppService)
    expect(appServiceStub.confirmButtonLabel).toBeTruthy();
    expect(appServiceStub.confirmButtonLabel).toBeDefined()
  })

  describe('token expiration', () => {
    it('checks token expiration', () => {
      const cookieServiceStub: CookieService = TestBed.get(CookieService);
      const confirmationServiceStub: ConfirmationService = TestBed.get(ConfirmationService);
      const component: AuthGuardService = TestBed.get(AuthGuardService);

      spyOn(component, 'tokenExpired').and.callThrough();
      const token:string = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dnZWRpbiI6dHJ1ZSwidXNlcm5hbWUiOiJ5YXNoLW1pc2hyYSIsImxvZ2luX3RpbWUiOjE2MDE0NTMxNDAsIkxBU1RfQUNUSVZJVFkiOjE2MDE0NTMxNDAsInN1cGVyX3VzZXIiOnRydWUsImlzcyI6IlRyYWRlVmlzaW9uMjAyMC5jb20iLCJzdWIiOiJDaGFydElRVmVyaWZpY2F0aW9uIiwiYXVkIjoieWFzaC1taXNocmEiLCJleHAiOjE2MDE1Mzk1NDB9.6S2cIrflTPRdTjXIaYaFcb2J5LrTa9-yqzfVVuNC85M'
      component.tokenExpired(token)

      expect(component.tokenExpired).toHaveBeenCalled();

    })
  })

  describe('checks canActivate Observable', () => {
    it('checks inside if condition', () => {
      const component: AuthGuardService = TestBed.get(AuthGuardService);
      spyOn(component, 'tokenExpired')
      let tempToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dnZWRpbiI6dHJ1ZSwidXNlcm5hbWUiOiJ5YXNoLW1pc2hyYSIsImxvZ2luX3RpbWUiOjE2MDE0NTMxNDAsIkxBU1RfQUNUSVZJVFkiOjE2MDE0NTMxNDAsInN1cGVyX3VzZXIiOnRydWUsImlzcyI6IlRyYWRlVmlzaW9uMjAyMC5jb20iLCJzdWIiOiJDaGFydElRVmVyaWZpY2F0aW9uIiwiYXVkIjoieWFzaC1taXNocmEiLCJleHAiOjE2MDE1Mzk1NDB9.6S2cIrflTPRdTjXIaYaFcb2J5LrTa9-yqzfVVuNC85M'
      component.tokenExpired(tempToken);
      component.canActivate().subscribe(token => {
        expect(token).toBe(true);
      });
    })

    it('checks inside else condition', () => {

      const component: AuthGuardService = TestBed.get(AuthGuardService);
      const appServiceStub: AppService = TestBed.get(AppService);

      spyOn(component, 'tokenExpired').and.returnValue(true)
      service.canActivate()
      expect(appServiceStub.confirmButtonLabel).toBe('Login')
    })

    it('checks accept inside else condition', () => {
      const component: AuthGuardService = TestBed.get(AuthGuardService);
      const appServiceStub: AppService = TestBed.get(AppService);
      const confirmationServiceStub: ConfirmationService = TestBed.get(ConfirmationService)
      let param: Confirmation = {message: 'Test Message', accept: () => {return false}}

      spyOn(component, 'tokenExpired').and.returnValue(true)

      spyOn(confirmationServiceStub, 'confirm')

      })
    })

});

A: The tricky part here is that the code you need to test is in a callback function (accept()) that, in a normal runtime scenario, would be invoked by the ConfirmationService (presumably when a user clicks a button). However, since you're mocking the ConfirmationService for your test, you need to invoke that callback function yourself in your test.
Looking at your code, you can see that the ConfirmationService#confirm method is passed a confirmation object with a message property and the accept callback function whose logic you need to test:
this.confirmationService.confirm({
  message: 'You are not logged in, Please login to Traders Desktop',
  accept: () => {
    // you need to test the business logic in this function
  }
});

You need to get a hold of that passed-in confirmation object so you can invoke its accept method yourself to trigger the business logic inside and verify its effects.
To do that, you can create a Spy for the ConfirmationService#confirm method that callsFake a function that you control in your test. That function will then be passed the confirmation object so you can manually invoke its accept method, like this:
spyOn(confirmationServiceStub, 'confirm').and.callFake(confirmation => {
  confirmation.accept() // <---- manually invoke the accept callback
})

Here's what the final test would look like:
it('checks accept inside else condition', () => {
  const component: AuthGuardService = TestBed.get(AuthGuardService);
  const confirmationServiceStub: ConfirmationService = TestBed.get(ConfirmationService)
  const locationStub: Location = TestBed.get(Location)

  spyOn(component, 'tokenExpired').and.returnValue(true)
  const locationSpy = spyOn(locationStub, 'replaceState').and.stub();

  spyOn(confirmationServiceStub, 'confirm').and.callFake(confirmation => {
    expect(confirmation.message).toContain('You are not logged in')

    confirmation.accept() // <---- manually invoke the accept callback
  })

  component.canActivate().subscribe(token => {
    expect(token).toBe(false)
    expect(locationSpy).toHaveBeenCalledWith('//traders_desktop.org')
  });
})

Before you do that, though, you need to fix your canActivate method because the else block is not returning an Observable like it needs to. In fact, isn't returning anything, it's just calling this.confirmationService.confirm().
What you need to do is wrap the this.confirmationService.confirm() call inside an Observable that you return, and have that Observable emit when the accept callback is invoked. Something like this:
} else {
  this.appService.confirmButtonLabel = 'Login';

  return new Observable((subscriber: Subscriber) => { // <--- you need to return an Observable here
    this.confirmationService.confirm({
      message: 'You are not logged in, Please login to Traders Desktop',
      accept: () => {
        this.isLoggedIn = false;
        window.location.replace('//traders_desktop.org')

        subscriber.next(this.isLoggedIn); // <--- emit from Observable when accept callback is invoked
        subscriber.complete();
      }
    });
  });
}

Here's a StackBlitz showing this approach.
You'll notice that I also replaced your reference to window.location with Angular's Location service so it can be mocked in the unit test (it's also considered a best practice).


text:
Q: Changing Task Name font color when Percent Complete equals 100 - MS Project Program: MS Project 2013 Professional
I am trying to change the Task Name font color to green when the % Complete is equal to 100%. This is what I have, but it is still not working for me.
Sub TurnGreen100Complete()
' 100% Task Completion - Turn Green

    Dim T As Task

    For Each T In ActiveProject.Tasks
        Select Case T.PercentComplete
            Case Is = "100%"
                SelectTaskField Row:=T.Name, RowRelative:=False
                Font Color:=pjGreen
        End Select
    Next T
End Sub

A: Try:
Dim T As Task
For Each T In ActiveProject.Tasks
    If not t is nothing then  'Ignore blank rows
      If T.PercentComplete=100 then
          editgoto ID:=t.id
          Font Color:=pjGreen
      End If
    End IF
Next T


text:
Q: Like is not working as expected in update query of join condition Code :
UPDATE elections_ls_2014_stats e
      JOIN `pc-details` p
      ON ( e.name LIKE CONCAT('%' ,p.candidate_name ,'%') )
SET    e.pc_details_id = p.id  WHERE  p.year =  '2014'
AND p.`candidate_results_position` ='1' AND e.pc_details_id IS NULL

Here its not working as expected
eg :Dr Pandula Ravindra Babu    AND  Pandula Ravindra Babu
this is one of the case where this condition is not working as expected , means update query is not working .
but in select statement I am getting the result for the above cases .(Dr Pandula Ravindra Babu    AND  Pandula Ravindra Babu)
code :
SELECT pd.id AS pc_details_id, el.id AS election_2014_id, pd.candidate_name, el.name
FROM  `pc-details` pd,  `elections_ls_2014_stats` el
WHERE pd.`year` LIKE  '2014'
AND pd.`candidate_results_position` =1
AND pd.candidate_name LIKE CONCAT(  '%', el.name,  '%' )

Am I doing anything wrong in the update query .
Any suggestion will be appreciated.Thank u

A: You can try below -
  UPDATE elections_ls_2014_stats e
          JOIN `pc-details` p
    SET    e.pc_details_id = p.id
    WHERE  p.year =  '2014'
    AND p.`candidate_results_position` ='1' AND e.pc_details_id IS NULL and  e.name LIKE CONCAT('%' ,p.candidate_name ,'%')

A: In your UPDATE query the LIKE expression is the opposite way around to the way it is in your SELECT query. Try this instead:
UPDATE elections_ls_2014_stats e
      JOIN `pc-details` p
      ON p.candidate_name LIKE CONCAT('%', e.name,  '%')
SET    e.pc_details_id = p.id  WHERE  p.year =  '2014'
AND p.`candidate_results_position` ='1' AND e.pc_details_id IS NULL


text:
Q: How To Transpose matrix list I am trying to Transpose matrix list but error:
def transpose_matriks(mat_a):
  def wrapper():
      temp_row = []
      temp_mat = []
      for i in range(0, pjg_matriks(mat_a)):
        for j in range(0, lbr_matriks(mat_a)):
          temp_row.append( mat_a[j][i])
        temp_mat.append(temp_row)
        temp_row = []
      return temp_mat
  return wrapper

@transpose_matriks
def matrixY():
  X = [3,2,4,5]
  return matrixY

print(matrixY())

erorr problem TypeError: object of type 'function' has no len() :
Traceback (most recent call last):
  File "C:\Users\ASUS X441U\PycharmProjects\PfModul4\coba.py", line 23, in <module>
    print(matrixX())
  File "C:\Users\ASUS X441U\PycharmProjects\PfModul4\coba.py", line 4, in wrapper
    rows = len (matrix)
TypeError: object of type 'function' has no len()

the output should be like this
 matrixY = [3,4,2,5]


text:
Q: Django ALLOWED_HOSTS settings I developing a mobile application, using react-native like a front-end and python Django REST framework like a back-end. The question is what I should write in Django settings.py ALLOWED_HOSTS, besides my server's adress? I don't use any website like a front-end, because my application is on App Store and Google Play.
If I will write ['*'], it certainly will work, but it is not a safe method


text:
Q: 'Echo' linux command is not working through Java Code I am trying to execute a simple linux command to append some text to a file in remote server through my java code. But it isn't working. When I run the same command in the linux box it works fine.
try {
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();

        Session sessionwrite = jsch.getSession(user2, host2, 22);
        sessionwrite.setPassword(password2);
        sessionwrite.setConfig(config);
        sessionwrite.connect();
        System.out.println("Connected");

        Channel channel = sessionwrite.openChannel("exec");
        BufferedReader in = new BufferedReader(new InputStreamReader(
                channel.getInputStream()));

        String command = "echo \"hello\" >> welcome.txt";
        ((ChannelExec) channel).setCommand(command);
        System.out.println("done");
}

A: Channel channel = sessionwrite.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(
        channel.getInputStream()));

String command = "echo \"hello\" >> welcome.txt";
((ChannelExec) channel).setCommand(command);
System.out.println("done");

You're missing the call to channel.connect(). connect() is the method which actually sends the request to the remote server to invoke the command. You should also call channel.disconnect() when finished with the channel to terminate it. Your code might look something like this:
Channel channel = sessionwrite.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(
        channel.getInputStream()));

String command = "echo \"hello\" >> welcome.txt";
((ChannelExec) channel).setCommand(command);
channel.connect();
channel.disconnect();
System.out.println("done");

I'll add that, in this particular example, there's no reason to open an input stream on the exec channel's standard input, so you could leave that line out.


text:
Q: Parse ACL Not working I have set up a user which has an associated role, and an object that has the ACL set to that role.
When i query the objects as that user, i get 0 results.
Am i missing something, or is there a bug?
Thanks.
Also, any pointers on my code would be nice.
var Budget = Parse.Object.extend("budget");
    var budget = new Budget();

    var acl = new Parse.ACL();
    acl.setPublicReadAccess(false);
    acl.setWriteAccess(Parse.User.current().id, true);
    acl.setReadAccess(Parse.User.current().id, true);
    budget.setACL(acl);

    budget.set("name", 'Test');

    budget.save(null, {
      success: function(budget) {
            var Role = new Parse.ACL();
            Role.setPublicReadAccess(true);
            Role.setPublicWriteAccess(false);
            var role = new Parse.Role(budget.id, Role);
            role.getUsers().add(Parse.User.current());
            role.save(null, {
              success: function(role) {
                    var acl = new Parse.ACL();
                    acl.setPublicReadAccess(false);
                    acl.setWriteAccess(budget.id, true);
                    acl.setReadAccess(budget.id, true);
                    budget.setACL(acl);

                    budget.save(null, {
                      success: function(budget) {
                            console.log(budget);
                      },
                      error: function(result, error) {
                        console.log(result, error);
                      }
                    });
              },
              error: function(result, error) {
                console.log(result, error);
              }
            });
      },
      error: function(result, error) {
        console.log(result, error);
      }
    });

A: Figured it out, i was using acl.setWriteAccess(budget.id, true); but i should have been using acl.setRoleWriteAccess(budget.id, true);
Fixed!


text: Q: Query system stats on OS X So I've checked in the past, and I could not find any information so I let it rest. I'm curious what OS X APIs are called in apps like iStat Menu or other system information apps? I could not find what functions  to call to get CPU temp or fan speeds. Are these kexts or very specific Unix system calls? I would be very grateful for anyone with insight!


text:
Q: Gem::LoadError - Ruby on Rails with postgreSQL I am not even able to get to basic rails landing page. I have gem 'pg' installed and postgreSQL installed but still the following error -
Gem::LoadError
Specified 'postgresql' for database adapter, but the gem is not loaded. Add gem 'pg' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).
Rails.root: C:/Sites/simple_cms
Application Trace | Framework Trace | Full Trace
Request
Parameters:
None
Toggle session dump
Toggle env dump
Response
Headers:
None
Any help would be appreciated. Thanks!


text:
Q: flutter bloc dispose while using get_it I have a question about do we need to dispose of a bloc while creating it in the get_it package? as an example, I have bloc named LoginBloc.and I created it like :
final GetIt sl = GetIt.instance;
sl.registerFactory(() => LoginBloc(sl(), sl()));

and I provide it like:
    BlocProvider(
       child: LogInPage(),
          create: (BuildContext context) {
                return sl<LoginBloc>();
               }

my question is that does bloc provider dispose of bloc while the page is disposed or not needed or I must dispose of it manually cuz I used the get_it package to create it?
thank you all

A: BlocProvider will automatically handles the closing of bloc when used with create.
You can see the official document for more.
https://pub.dev/documentation/flutter_bloc/latest/flutter_bloc/BlocProvider-class.html
When you register something via sl.registerFactory,  GetIt will create new instance every time you access it.


text:
Q: How to use WIX's SetDirectory correctly I have a fragment that handles the installation location for my app, however I want to install to a custom location (C:\PtecMonitor) vs Program Files(x86)....
<Fragment>
   <Directory Id="TARGETDIR" Name="SourceDir">
       <Directory Id="WINDOWSVOLUME">
         <Directory Id="INSTALLLOCATION" Name="PtecMonitor" />
       </Directory>
     <Directory Id="ProgramMenuFolder">
       <Directory Id="ApplicationProgramsFolder" Name="Ptec Share Monitor"/>
     </Directory>
   </Directory>
   <SetDirectory Id="WINDOWSVOLUME" Name="[WindowsVolume]" />
</Fragment>

This throws up an error "The SetDirectory/@Value attribute was not found; it is required."
Where is SetDirectory supposed to be set in order for this to work?

A: <SetDirectory /> Does not have a Attribute called "Name" you Probably want to set "Value" instead.
Please see the Documentation for more information
https://wixtoolset.org/documentation/manual/v3/xsd/wix/setdirectory.html

A: SetProperty and SetDirectory are syntactical sugar to simplify authoring MSI Type 51 (Set Property ) and Type 35 ( Set Directory ) custom actions.  In general type 51 should be scheduled prior to costing and type 35 should be scheduled after costing.


text:
Q: Will Apple service secondhand iPad still under warranty? I bought an iPad on eBay a few weeks ago. It's still covered under the original Apple warranty. There's a clear problem with the battery. Will the Genius Bar staff look at and service this device if I'm not the original owner? Do I have to disclose that I'm not the original owner?

A: Normally saying that you've bought it as secondhand you're ok, even because, before they start working on it, they need to have "Find my iPhone" disabled so, if you have stolen that iPad, you wouldn't be able to disable that.


text:
Q: map infoWindow doesn't displayed from the first click I've checked around and read a couple articles on this issue and tried a few things but nothing seems to be working. The issue is when the marker is clicked the first time nothing happens. The second time its clicked then the event is fired off.The infowindow doesn't shows before 4 or 5 clicks, I don't know what i have done wrong.
This is not acutally brower issue. Because, I have checked with all browers.
I am using below code to open up a infowindow in my map:
 import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import _ from 'lodash';
import {
  withGoogleMap,
  GoogleMap,
  Marker,
  InfoWindow,
  TrafficLayer,
} from 'react-google-maps';
import {loadGodViewDrivers} from '../../../actions/driverActions';
import {loadGodViewBranches} from '../../../actions/branchActions';
import './OverviewMap.scss';

const actions = {
  loadGodViewDrivers,
  loadGodViewBranches,
};

const GoogleMapsContainer = withGoogleMap(props => {
  function getPosition(marker) {
    return {
      lat: marker.address
          ? marker.address.location.latitude
          : marker.location.latitude,
      lng: marker.address
          ? marker.address.location.longitude
          : marker.location.longitude,
    };
  }

  return (

      <GoogleMap
          ref={props.onMapLoad}
          defaultZoom={11}
          options={props.mapsOptions}
          onDragEnd={props.mapChanged}
          onZoomChanged={props.mapChanged}
          defaultCenter={props.mapCenter}
      >
        <TrafficLayer autoUpdate/>
        {typeof props.mapHolderRef !== 'undefined' &&
        _.size(props.branches) > 0 && (
            props.branches.map((it, i) => {
                  return (
                      <Marker
                          key={i}
                          position={getPosition(it)}
                          onClick={() => props.onMarkerClick(it)}
                          icon={'/img/merchant.png'}
                      >

                        {it.showInfo && (
                            <InfoWindow
                                onCloseClick={() => props.onMarkerClose(it)}>
                              {it.merchant ? (

{ it.merchant.suspended
                                      ? 'suspended'
                                      : 'active'}

{it.name}

                                    {it.address.firstLine}

                                    <span style={{
                                      backgroundColor: '#337ab7',
                                      border: '2px solid #2e6da4',
                                      fontSize: '15px',
                                      color: '#fff',
                                      display: 'inline-flex',
                                      alignItems: 'center',
                                      justifyContent: 'center',
                                      borderRadius: '50%',
                                      width: '32px',
                                      height: '32px',
                                      marginRight: '6px',
                                    }}><a
                                      href={`/merchants/${it.merchant._id}`}>{it.merchant.name}

                                    <span
                                        style={{
                                          backgroundColor: '#337ab7',
                                          border: '2px solid #2e6da4',
                                          fontSize: '15px',
                                          color: '#fff',
                                          display: 'inline-flex',
                                          alignItems: 'center',
                                          justifyContent: 'center',
                                          borderRadius: '50%',
                                          width: '32px',
                                          height: '32px',
                                          marginRight: '6px',
                                        }}><a
                                      href={`tel:${it.phone}`}>{it.phone}

) :
No merchant
                                data
}
                            </InfoWindow>)}
                      </Marker>
                  );

                },
            )
        )}
        {typeof props.mapHolderRef !== 'undefined' &&
        _.size(props.drivers) > 0 && (
            props.drivers).map((it, i) => {
              if(it.available || (it.orderStatus && it.currentOrder && it.orderStatus !== null && it.currentOrder !== null))
              return (
                  <Marker
                      key={i * 2}
                      position={getPosition(it)}
                      onClick={() => props.onMarkerClick(it)}
                      onCloseClick={() => props.onMarkerClose(it)}
                      icon={it.orderStatus === 'en_route' ? '/img/driver_green.png' : it.orderStatus === 'waiting_pack' ? '/img/driver_yellow.png' : it.available ? '/img/driver_grey.png' : '/img/driver_red.png'}
                  >

                    {it.showInfo && (
                        <InfoWindow
                            onCloseClick={() => props.onMarkerClose(it)}>

{ !it.available
                                  ? 'unavailable'
                                  : 'available'}

<a
                                  href={`/drivers/${it._id}`}>{it.userName}

                                {it.userEmail}

                                    <span style={{
                                      backgroundColor: '#337ab7',
                                      border: '2px solid #2e6da4',
                                      fontSize: '15px',
                                      color: '#fff',
                                      display: 'inline-flex',
                                      alignItems: 'center',
                                      justifyContent: 'center',
                                      borderRadius: '50%',
                                      width: '32px',
                                      height: '32px',
                                      marginRight: '6px',
                                    }}>
                                <a href={`/orders/${it.currentOrder}/`}>Current order

                                    <span
                                        style={{
                                          backgroundColor: '#337ab7',
                                          border: '2px solid #2e6da4',
                                          fontSize: '15px',
                                          color: '#fff',
                                          display: 'inline-flex',
                                          alignItems: 'center',
                                          justifyContent: 'center',
                                          borderRadius: '50%',
                                          width: '32px',
                                          height: '32px',
                                          marginRight: '6px',
                                        }}><a
                                  href={`tel:${it.workPhone}`}>{it.workPhone}

                        </InfoWindow>)}
                  </Marker>
              );
            },
        )}

      </GoogleMap>
  );
});
class OverviewMap extends Component {
  constructor(props) {
    super(props);

    this.state = {
      center: null,
    };

    this.handleRecenterClick = this.handleRecenterClick.bind(this);
    this.handleMapsRef = this.handleMapsRef.bind(this);
    this.mapChanged = _.debounce(this.mapChanged.bind(this), 500);

  }

  handleMapLoad = this.handleMapLoad.bind(this);

  handleMapLoad(map) {
    this._mapComponent = map;
    this.mapHolderRef = map;

    this.mapChanged();
  }

  mapChanged() {
    const bounds = this.mapHolderRef.getBounds();

    const ne = bounds.getNorthEast();
    const sw = bounds.getSouthWest();
    this.props.loadGodViewDrivers({
      nw: {lat: ne.lat(), lng: sw.lng()},
      se: {lat: sw.lat(), lng: ne.lng()},
    });

    this.props.loadGodViewBranches({
      nw: {lat: ne.lat(), lng: sw.lng()},
      se: {lat: sw.lat(), lng: ne.lng()},
    });

    this.setState({
      center: {
        lat: this.mapHolderRef.getCenter().lat(),
        lng: this.mapHolderRef.getCenter().lng(),
      },
    });
  }

  componentDidMount() {
    this.mapChanged();
    this.mapChangedInterval = setInterval(this.mapChanged, 2000);
  }

  componentWillUnmount() {
    clearInterval(this.mapChangedInterval);
  }

  getDefaultCenter() {
    return {
      lat: 29.234232862891145,
      lng: 47.947988063964885,
    };
  }

  handleRecenterClick() {
    const center = this.getDefaultCenter();

    this.setState({
      center: {
        lat: center.lat + Math.pow(10, -5),
        lng: center.lng,
      },
    });
  }

  handleMapsRef(mapHolder) {
    this.mapHolderRef = mapHolder;
    this.googleMaps = mapHolder && mapHolder.props.map;

    if (this.googleMaps) this.mapChanged();
  }

  handleMarkerClick = this.handleMarkerClick.bind(this);
  handleMarkerClose = this.handleMarkerClose.bind(this);

  handleMarkerClick(targetMarker) {
    this.setState({
       branches: this.props.branches.map(marker => {
        if (marker == targetMarker) {
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;

      }),
      drivers: this.props.drivers.map(marker => {
        if (marker == targetMarker) {
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;
      }),
    });
  }

  handleMarkerClose(targetMarker) {
    this.setState({
      branches: this.props.branches.map(marker => {
        if (marker == targetMarker) {
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;
      }),
      drivers: this.props.drivers.map(marker => {
        if (marker == targetMarker) {
          return {
            ...marker,
            showInfo: false,
          };
        }
        return marker;
      }),

    });
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.branches !== nextProps.branches ||
        _.size(this.state.branches) === 0) {
      this.setState({
        branches: _.map(nextProps.branches, (marker, i) => {
          return {
            ...marker,
            showInfo: typeof this.state.branches !== 'undefined'
                ? typeof this.state.branches[i] !== 'undefined'
                    ? this.state.branches[i].showInfo
                    : false
                : false,
          };
        }),
      });
    }
    if (this.props.drivers !== nextProps.drivers ||
        _.size(this.state.drivers) === 0) {
      this.setState({
        drivers: _.map(nextProps.drivers, (marker, i) => {
            return {
              ...marker,
              showInfo: typeof this.state.drivers !== 'undefined'
                  ? typeof this.state.drivers[i] !== 'undefined'
                      ? this.state.drivers[i].showInfo
                      : false
                  : false,
            };
        }),
      });
    }
  }

  render() {
    const mapCenter = this.state.center || this.getDefaultCenter();
    const mapsOptions = {
      streetViewControl: true,
      mapTypeControl: true,
      signInControl: true,
    };

    return (
        <GoogleMapsContainer
            containerElement={

            }
            mapElement={

            }
            onMapLoad={this.handleMapLoad}
            mapCenter={mapCenter}
            mapsOptions={mapsOptions}
            mapChanged={this.mapChanged}
            mapHolderRef={this.mapHolderRef}
            mapRef={this.handleMapsRef}
            branches={this.state.branches}
            drivers={this.state.drivers}
            onMarkerClick={this.handleMarkerClick}
            onMarkerClose={this.handleMarkerClose}
        />
    );
  }
}
function mapStateToProps(state) {

  return {
    branches: state.branches.godView,
    drivers: state.drivers.godView,
  };

}
export default connect(mapStateToProps, actions)(OverviewMap);

The above code, calling while loading on the marker in the google map. At fist time, first click on the marker through ajax call, the content of the infowindow comes as response. In the second click the infowindow will open. Next time onwards, clicking on the marker loading the infowindow comes in first click.
Has any one had this bug before ? could some one help me to sort this issue please ?

A: Since no one else is bothering to answer my question, i found it by my self,:
my mistake that i was comparing two Javascript objects "marker == targetMarker".
So for that  just updated this line to marker == targetMarker._id" and it works well. Hope it will be helpful for many of you who are stucked for something like this. If you want to compare two Javascripts objects you need to use a specific attribute like i just do with the id.


text:
Q: iAd enabled app not receiving any requests The last iAd enabled app I released started generating requests almost immediately as soon as it appeared in the app store, but did not generate any impressions for 3-4 days until it started receiving ads from Apple (that behavior is normal)
Yesterday I released an iAd enabled app and it has not generated a single request let alone impression.
https://itunes.apple.com/us/app/barograph/id926055907?mt=8
The app is NOT listed as for kids.
The app does successfully generate test ads when I was running my beta builds before submitting it.
The apps shows up in my iAd.apple.com dashboard normally with a green light and it says it is recieving ads, but it has not generated a single request yet.
My contracts in ITC are up to date.
Is there anything I might have done wrong, or anything I have forgotten to do which would be preventing me from getting any ad requests?

A: The answer is, this appears to be normal. Even though some apps generate requests immediately, others take a few days (in both cases it takes a few days to generate actual impressions). My latest app started receiving requests just over 24 hours after the release date and started generating impressions at the same time. The dapp before that started generating requests immediately but did not get any impressions for 3-4 days.