Q: NSMetadataQuery doesn't send a notification when finished (or doesn't finish) I'm trying to access some files stored in the application's documents directory by using an NSMetadataQuery but the NSMetadataQueryDidFinishGatheringNotification doesn't notify my application. I found this question but the answer was to make the NSMetadataQuery an ivar, which I have already done.
Here's the code I am using:
self.query = [[NSMetadataQuery alloc] init];
[self.query setSearchScopes:[NSArray arrayWithObject:documentsDirectoryURL]];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K ENDSWITH '_task'", NSMetadataItemFSNameKey];
[self.query setPredicate:pred];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinishGathering:) name:NSMetadataQueryDidFinishGatheringNotification object:self.query];

[self.query enableUpdates];

[self.query startQuery];

Thanks for your help!

A: This is from the Apple document, "About File Metadata Queries" :
iOS allows metadata searches within iCloud to find files corresponding files. It provides only the Objective-C interface to file metadata query, NSMetadataQuery and NSMetadataItem, as well as only supporting the search scope that searches iCloud.
Unlike the desktop, the iOS application’s sandbox is not searchable using the metadata classes. In order to search your application’s sandbox, you will need to traverse the files within the sandbox file system recursively using the NSFileManager class. Once matching file or files is found, you can access that file in the manner that you require. You are also able to use the NSMedatataItem class to retrieve metadata for that particular file.
So, you have to use NSFileManager instead.


Q: Pass dynamic content to bootstrap modal 3.2 What i'm trying to do is to pass the data-id value to an external link via JQuery ajax.
The modal will show up but the data-id attribute is not sending to the external link. I think something is wrong with my Jquery script. But i can't find it.
This is my link:
Show Me

This is my Jquery ajax script:

This is my code for the modal:

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Dynamic Content

                Content is loading...

                <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-info">Save changes</button>

Can anyone help me out here?

I want to load the content of the page found by test-modal.
The code of test-modal.php is simple, see below:
<?php
$uid = $_GET['id'];
echo id: '. $uid;
?>

I have tried to make a jsfiddle: http://jsfiddle.net/2dp12ft8/3/ but it's totally not working.
I have changed the js code but it will still not work.
I see the modal showing up but only the word 'undefined' is showing up and not the content of the external file.

A: Dont mix onclick attributes with event handlers, its messy and can cause errors (such as mistaking the scope of this, which i believe is you main issue here).
If you are using jquery make use of it:
First add a class to the links you want to attach the event to, here i use the class showme:
Show Me

Then attach to the click event on those links:

To access the variable in php:
$uid = $_GET['id']; //NOT $_GET['uid'] as you mention in a comment

A: Try the load method instead.  I'm taking a guess here, but it seems like you want to actually load the contents of the page found at test-modal.php.  If that's correct, replace your ajax call as follows:
function showAjaxModal()
    {
        var uid = $(this).data('id');
        var url = "test-modal.php?id=" + uid;
        jQuery('#modal-7').modal('show', {backdrop: 'static'});
        jQuery('#modal-7 .modal-body').load(url);

    }

If your test-modal.php page contains more than a fragment (e.g., it has html and body tags), you can target just a portion of the page by passing an id of the containing element for the content that you want to load, such as:
jQuery('#modal-7 .modal-body').load(url+' #container');

which would only load the contents of the element with the id container from your test-modal.php page into the modal-body.


Q: A Simile for a Strenuous activity Could anyone offer some similes for a strenuous activity.
The context is that:
you can have all sorts of great ideas at random times and random places but
"when you actually sit down and make an effort to come up with a good idea it’s more akin to [insert simile for something strenuous or difficult]"

A: A one-legged man at an arse-kicking contest - Rowan Atkinson

A: nailing jelly to a tree

like nailing jelly to a tree adj.
   Used to describe a task thought to be impossible, esp. one in which the difficulty arises from poor specification or inherent slipperiness in the problem domain.

*

*Also used in variant “to a wall”

*In AmE, jello or Jell-O is used instead of jelly.

*In BrE, jelly is used instead of jello.

Bonus:
Actually, some people even tried to nail jelly to a wall:

Source: http://graeme.woaf.net/otherbits/jelly.html
It is like ideas slipping away...

These are related also:

*

*getting blood from a stone (also get blood out of a stone)

*catching/capturing lighting in a bottle

*tough row to hoe

*devil of a job (or devil's own job)

A: Lighthearted?  Self-menticide -you did say lighthearted ;-)
Aprosexia Inability to concentrate.

A: Like herding cats, which got a segment on Mythbusters and was found to be significantly more difficult than the proverbial like catching a greased pig.  (That episode also tested the similar like trying to put ten pounds of manure in a five pound bag.  They do not test herding rats with a blowdryer.  I should also note there was a great cat-herding commercial during the Superbowl during the dotcom boom.)


Q: Can't make 2 buttons play 2 different songs on my HTML Firstly, I'm super (SUPER) new to coding in general. I'm doing a college project for a site, and I wanted to make a certain page have 2 buttons that play songs, 2 different versions, one for each button. I copied the code  from stack overflow, can't remember where but I'll be forever thankful for that one answer. I'm new to SO too so I hope I put the code here the right way :|

    <button id="ASong" onClick="playPause()" >
  <audio
    src="mp3/Persona_5_OST-_Beneath_the_Mask_(getmp3.pro).mp3"
    autoplay
    loop
  ></audio>

</button>

    <button id="ASong2" onClick="playPause()" >
  <audio
    src="mp3/Persona_5_OST_-_Beneath_the_Mask_r_(getmp3.pro).mp3"
    autoplay
    loop
  ></audio>

</button>

The only thing I really tried was changing the ID name for the second song. What happens is. I choose a button and click it first. That one button, with that specific song is the one that'll play (edit, it's not the first one I click, it's only one of the songs :/ it switched which one it was when I changed the ID name) , even if I try to press the other button afterwards. It's like both of them become the same button, they function the same. What I wanted is that each one of them worked separately. I want to be able to click, start one song, pause it, click on the other button and start the other song, which is not what's happening right now. I hope that makes sense D=

A: I'm going to modernize this a bit. Inline event handlers listeners are not the way to go these days. I'' use addEventListener instead.
Next, I'm going to use one lot of code to handle the actions. One concept to get used to as you learn to program is DRY: Don't Repeat Yourself. To facilitate the state of your playback I'll use a data attribute on the button

/*Get the buttons*/
document.querySelectorAll(".playPause").forEach(function(el) {
  /*Add a click event listener*/
  el.addEventListener("click", function() {
    /*Get the first audio tag in the clicked button*/
    var aud = this.querySelector("audio");
    /*Check the data attirbute on the button if playing*/
    if (this.dataset.isplaying === "true") {
      /*Debug line*/
      console.log("Pausing " + aud.src)
      /*Change the status of the data attribute*/
      this.dataset.isplaying = "false";
      /*Pause the audio element*/
      aud.pause();
    } else {
      /*Debug line*/
      console.log("Playing " + aud.src)
      /*Change the status of the data attribute*/
      this.dataset.isplaying = "true";
      /*PLay the audio element*/
      aud.play();
    }
  })
});
<button id="ASong" class="playPause" data-isplaying="false">
  <audio
    src="mp3/Persona_5_OST-_Beneath_the_Mask_(getmp3.pro).mp3"
    autoplay
    loop
  ></audio>

</button>
<button id="ASong2" class="playPause" data-isplaying="false">
  <audio
    src="mp3/Persona_5_OST_-_Beneath_the_Mask_r_(getmp3.pro).mp3"
    autoplay
    loop
  ></audio>

</button>


Q: Javascript es6 - is it reassigning or a parameter? Can someone please explain what's happening here? I know these are middleware for express, I'm looking at the syntax.
I understand the es6 syntax for mustBeLoggedIn but I'm not sure what const forbidden = message => (req, res, next) => { is doing. Is message another parameter that comes before req, res, next? If so, why isn't it in the parenthesis? I originally  thought this was just assigning another variable name to the function. So I could call it either forbidden() or message(), no? But looking at how it's being used it looks more like a parameter...
Another interesting thing I noticed is that the middleware forbidden is being invoked in the get request and mustBeLoggedIn is only being passed and not invoked. Why?

   const mustBeLoggedIn = (req, res, next) => {
      if (!req.user) {
        return res.status(401).send('You must be logged in')
      }
      next()
    }

    const forbidden = message => (req, res, next) => {
      res.status(403).send(message)
    }

module.exports = require('express').Router()
 .get('/', forbidden('only admins can list users'), (req, res, next) =>
  User.findAll()
  .then(users => res.json(users))
  .catch(next))
 .post('/', (req, res, next) =>
  User.create(req.body)
  .then(user => res.status(201).json(user))
  .catch(next))
 .get('/:id', mustBeLoggedIn, (req, res, next) =>
  User.findById(req.params.id)
  .then(user => res.json(user))
  .catch(next))

A: I dislike this use of the ES6 syntax as it obscures the meaning of the code only in the interest of brevity.  The best code is not always the shortest possible way to write it.  Give people tools and they will sometimes use them inappropriately.
forbidden() is a function that takes one argument message that returns a middleware handler that uses that one argument.  So, it's a way of making a customized middleware handler that has a parameter pre-built-in.  When you call forbidden(msg), it returns a middleware handler function which you can then use as middleware.
The ES5 way of writing this (ignoring for a moment the difference in this which would be different, but is not used here) would look like this:
const forbidden = function(message) {
   return function(req, res, next) {
       res.status(403).send(message);
   }
}

So, when you call forbidden(someMsg), you get back a function that can be used as middleware.

If so, why isn't it in the parenthesis?

With the ES6 arrow syntax, a single argument does not have to be in parentheses.  Only multiple arguments require parentheses.

Another interesting thing I noticed is that the middleware forbidden is being invoked in the get request

This is because invoking it returns the actual middleware function so you have to execute to get the return value which is then passed as the middleware.

and mustBeLoggedIn is only being passed and not invoked. Why?

Because it's already a middleware function, so you just want to pass a reference to it, not invoke it yet.

FYI, this route:
.get('/', forbidden('only admins can list users'), (req, res, next) =>
    User.findAll()
    .then(users => res.json(users))
    .catch(next))

does not make sense to me based on the code you've shown because forbidden() will return a middleware that will ALWAYS return a 403 response and will not allow the next handler to get called.  This would only make sense to me if forbidden() had logic in it to check if the current user is actually an admin or not (which you don't show).


Q: Is there a reason NOT to install the RSAT-ADDS tools on an Exchange 2013 CAS server? I would've thought I already knew this answer.  Maybe I'm just being paranoid.
I have a need to run a local script on a CAS server that would in turn utilize the Active Directory cmdlets.  I need to install the RSAT tools for AD (rsat-adds) in order to accomplish this.
In the past versions of Exchange I always put these tools on the servers, but I can't find anything saying whether I should or shouldn't on an Exchange 2013 CAS.  I know it is a pre-req for Exchange to function to prep the domain so in the past I've installed it on the Exchange 2010 servers to prep the domain, but wasn't sure if something changed in Exchange 2013 where it was recommended to not install it on a CAS sever.
I have the RSAT tools on our mailbox servers, but not on our CAS servers currently.
So, can I install the RSAT tools for AD on an Exchange 2013 CAS with no concerns?

A: Having RSAT on an Exchange Server causes no issues.
Providing services like Exchange are mostly constrained to high uptimes and avoiding uneccessary reboots.
So, having the RSAT Tools (or other non-vital components) installed, may be related to additional udpates that have to be installed - this may cause the need for additional reboots.
Having a bunch of Exchange Servers (for move server roles) or maintenance windows may reduce the penalty associated with reboots.
A notice on multi-host-scenario:
Users working in online mode with exchange may experience some sort of short disconnects even if you manually move active server databases to other hosts. We saw quite often here, that working copies of edited messages have gotten corrupt then and the users had to go back to the stored version of the message from drafts.


Q: How to fetch file type data (image) on JQuery page and send to PHP page for image upload I want to upload an image using jQuery asynchronously with data... but cannot upload it... Only data variables can be fetch there in process page but cannot get the image file using $_FILES......
img_upload.php
<form name="frm" id="frm" novalidate enctype="multipart/form-data">
    <input type="text" id="txt_name" name="txt_name" />
    <input type="file" name="img_upload" id="img_upload">
</form>

img_upload.js
$(function() {

    $("#frm_edit input, #frm_edit textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour

        var txt_name =  $("input#txt_name").val();

        var FileImgData = $('#img_upload').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', FileImgData);

            $.ajax({
                url: "./img_upload_p.php",
                type: "POST",
                data: {
                    txt_name: txt_name,
                    upload_photo: FileImgData
                },
                cache: false,
            })
        },
    });
});

img_upload_p.php
$str_name="";
if(isset($_POST["txt_name"])) { $str_name=trim($_POST["txt_name"]); }

$str_upload_photo="";
if(isset($_FILES['file_photo']))
{ $str_upload_photo = trim($_FILES['file_photo']['name']); }

Please suggest me that image variable declared (upload_photo: FileImgData) in JQuery file "img_upload_p.js" is correct or not.
Also, the way image file variable is fetched in "img_upload_p.php" is correct or not.
if any of them are wrong then how can I assign that image variable in JQuery file and fetch in PHP process page...
PHP image upload code is ready and in working condition... but just having issue with above two mentioned points...

A: One of the best way to do this is use Dropzone js, this is a best library for uploading files using ajax and it also provides progress bar. You can use your own PHP(or any other server side language) code at server side.
I hope it will helpful.

A: img_upload.js
$(function() {

    $("#frm_edit input, #frm_edit textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour

            var formData = new FormData();
            formData.append("hdn_pkid", $("input#hdn_pkid").val()); // if hidden variable is passed
            formData.append("txt_name",$("input#txt_name").val()); // if other input types are passed like textbox, textarea, select etc...
            formData.append('img_upload', $('input[type=file]')[0].files[0]); // if image or other file is passed

            $.ajax({
                url: "./img_upload_p.php",
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                cache: false,
            })
        },
    });
});

img_upload_p.php

*

*Get all variables' value using POST method and store them in new variables to use and process on this page as usual.

*Get file variable like below mentioned code and then upload image using normal PHP function or your own way.
if(isset($_FILES['img_upload']))
{ $str_ = trim($_FILES['img_upload']['name']); }


Q: How do I continue to perform aggregation on a single thread that has polling? I create a flow, which polls rows from database by status, validate them and after that aggregate to collection. After processing the entire flow, each line is set to the appropriate status. But when I use aggregator with release strategy TimeoutCountSequenceSizeReleaseStrategy, and elapsed time is so small, release group doesn't happen. And after that the following polling occurs in another thread, but previous message group wasn't handled until amount of messages won't reach the target(threshold) in the strategy.
Code of my flow:
@Bean
public IntegrationFlow testFlow(EntityService entityService,
                                EntityValidator entityValidator,
                                EntityFlowProperties properties,
                                EntityChecker checker) {
    return IntegrationFlows
            .from(getMessageSource(entityService::getByStatus, properties.getMaxRowsPerPoll()),
                    e -> e.poller(getPollerSpec(properties)))
            .split()
            .transform(entityValidator::validate)
            .filter(ValidationStatus<Entity>::isValid, filter ->
                    filter.discardFlow(flow -> flow.handle(entityService::handleValidationErrors)))
            .transform(ValidationStatus<Entity>::getEntity)
            .aggregate(aggregatorSpec -> aggregatorSpec.releaseStrategy(new TimeoutCountSequenceSizeReleaseStrategy(5, 10000)))
            .transform(checker::checkOnSomething)
            .split()
            .transform(CheckResultAware<Entity>::getEntity)
            .handle(entityService::saveAndChangeStatus)
            .get();

I expect to perform aggregation on the same thread as polling, and don't make a new polling until the current flow is over.
The way of changing statuses between polling and aggregation isn't suitable.
Is there a way to do this?

A: Why do you need TimeoutCountSequenceSizeReleaseStrategy; your sequences are finite; just use the default SimpleSequenceSizeReleaseStrategy.
However the TimeoutCountSequenceSizeReleaseStrategy should release based on the sequence size anyway.
But, it's not really suitable for your use case because you can be left with a partial group in the store.


Q: Handle arrays in laravel I am learning laravel and trying to create a community with laravel. I stuck at some part and need to ask you guys.
Right now I am trying to displaying posts to reader.
This is what i accomplish so far

with this code :
public $restful = true;
public function get_index($title = '')
{
    //Do we have an arguement?
        if(empty($title))
        {return Redirect::to('dashboard');}

    $view = View::make('entry');
    $query = DB::table('threads')->where('title', '=', $title)->first();

    //Do we have this thread?
        if(!$query)
        {return Redirect::to('entry/suggest');}
    //We have? so lets rock it!
    $view->title = $query->title; //we get the title.

    $thread_id = $query->id;

    //getting posts.

    $posts = DB::table('posts')->where('thread_id', '=', $thread_id)->get();

    $view->posts = $posts;

  return $view;
}

and the view is :

{{$title}}

@foreach($posts as $post)

1{{$post->post_entry}}

{post_row.POST_USERNAME} {post_row.DATE}

@endforeach

But the hard part(for me) is integrate posts with poster's username or other user info like e-mail for moderate privileges. However hey are in 'users' table.
Lets say $posts variable holds data of 10 posts for a thread
 *a post has thread_id , poster_userid, post, posted_date.
How can i grab username from 'users' table and send it to my view? I am sure i need to use foreach after selecting posts from database I just dont know how to handle arrays in foreach.

A: Look up how to set up models and their relationships using Eloquent ORM:
http://laravel.com/docs/database/eloquent
Specifically http://laravel.com/docs/database/eloquent#relationships
You should have three models, Thread, Post and User (change poster_userid to user_id... or you can keep it but I wouldn't suggest it... just keep things simple. You could also use author_id or maybe even poster_id if that floats your boat.. just be sure to change 'user_id' out with what you choose)
//application/models/User.php

class User extends Eloquent {

 public function posts()
 {
      return $this->has_many('Post', 'user_id');
 }
}

and
//application/models/Post.php
class Post extends Eloquent {

 public function author()
 {
    return $this->belongs_to('User', 'user_id');
 }

 public function thread()
 {
    return $this->belongs_to('Thread', 'thread_id');
 }
}

and
 //application/models/Thread.php
    class Thread extends Eloquent {

     public function posts()
     {
          return $this->has_many('Post', 'thread_id');
     }

    }

and instead of
$query = DB::table('threads')->where('title', '=', $title)->first();

//Do we have this thread?
    if(!$query)
    {return Redirect::to('entry/suggest');}
//We have? so lets rock it!
$view->title = $query->title; //we get the title.

$thread_id = $query->id;

//getting posts.

$posts = DB::table('posts')->where('thread_id', '=', $thread_id)->get();

I would just put
$thread = Thread::where('title', '=', $title)->first();

if(!$query)
    {return Redirect::to('entry/suggest');}

$posts = $thread->posts()->get();
//or if you want to eager load the author of the posts:
//$posts = $thread->posts()->with('author')->get();

Then in your view you can look up the user's name by the following:
$post->author->username;

Easy peezy.

A: With Eloquent you can do this in multiple ways.
First, you can add a method to your post model that retrieves the related data. This approach will create a new query for each post, so it's normally not the best choice.
class Post extends Eloquent
{
    public function user()
    {
        return $this->has_one('User');
    }
}

Second, you can modify your initial query to join your desired data and avoid creating undo queries. Know as "Eager Loading".
// Example from Laravel.com

foreach (Book::with('author')->get() as $book)
{
    echo $book->author->name;
}


Q: how to install amd gpu open source drivers I have a dell inspiron 5520  running Ubuntu 16.04 LTS. MY laptop has a amd radeon hd 7000 series.How do i figure out wether my gpu is running or not ?.
This is the output i got whil running sudo xrandr
    Screen 0: minimum 8 x 8, current 1366 x 768, maximum 32767 x 32767
LVDS1 connected primary 1366x768+0+0 (normal left inverted right x axis y axis) 344mm x 194mm
   1366x768      60.00*+  40.00
   1360x768      59.80    59.96
   1280x720      60.00
   1024x768      60.00
   1024x576      60.00
   960x540       60.00
   800x600       60.32    56.25
   864x486       60.00
   640x480       59.94
   720x405       60.00
   680x384       60.00
   640x360       60.00
DP1 disconnected (normal left inverted right x axis y axis)
HDMI1 disconnected (normal left inverted right x axis y axis)
VGA1 disconnected (normal left inverted right x axis y axis)
VIRTUAL1 disconnected (normal left inverted right x axis y axis)

A: They are preinstalled. You don't need to worry.


Q: How to revert multiple pull request merges all at once and preserve history I have a case where the Github repo master currently has a series of individual pull requests that have already been merged into master. I want to revert say the last 20 of those pull request merges but do it from the command line and preserve history.
A similar question was marked as duplicate revert multiple merges
However the answers given as already existing do not really deal with the specific question of what happens when everything you want to revert came from a series of pull requests which are all merges. Using the -m option with git revert is good for one merge at time right? So I think the answer is that there is not a good way (from the command line) to quickly revert a series of individual pull requests that have been merged and preserve history? Please correct me if I am wrong about this. If I have to do one at a time, I might as well just use the Github console and click on revert for each one.

A: If you want to have a single (later) revision where you revert the changes from all those merges, you can do it like this:
git checkout <id-of-revision> # use the ID of the revision you would like to get your project back to (in terms of content)
git reset --soft <the-branch> # the branch where we want to add a revision to revert all of that
git commit -m "Reverting"
# If you like the results
git branch -f <the-branch> # move branch pointer to this new revision
git checkout <the-branch>

A: Step1
Create a new backup branch first and keep it aside. (backup-branch)
Create a new branch from master or dev wherever you want to revert.(working-branch)
git revert commitid1
git revert commitid2
git revert commitid3....
is the best option.
dont do git reset --hard commitid it will mesh up your indexing.
Reverting is the safe option.
i have done 180 revert commits.
Step2
git log -180 --format=%H --no-merges
use this command to print all the commit ids alone.
it will ignore the merge commit id.
commitid1 commitid2 commitid3 ..... it will print like that.
Copy it to sublime ctrl+a -> ctrl +alt + l add
git revert --no-commit commitid1
git revert --no-commit commitid2
git revert --no-commit commitid3
Copy all and paste in the command prompt. All your commits will be reverted. now do a git commit.
Then do git push.
create a merge request to master.
Step3
How to verifiy?
create a new branch (verify-branch).
YOu can verify it by doing a
git reset -hard commitidX. This is the commit id to which you need to revert.
git status It will give you the number of commits behind the master.
git push -f
Now compare this branch with your working-branch by creating a pull request between them. you will see no changes means your working branch successfully reverted back to the version you're looking for.


Q: What is the context for `this` in Node.js when run as a script? From the node REPL:
$ node
> var x = 50
> console.log(x)
50
> console.log(this.x)
50
> console.log(this === global)
true

Everything makes sense. However, when I have a script:
$ cat test_this.js
var x = 50;
console.log(x);
console.log(this.x);
console.log(this === global);
$ node test_this.js
50
undefined
false

Not what I expected.
I don't really have a problem with the REPL behaving differently from a script, but where exactly in the Node documentation does it say something like "NOTE: when you run a script, the value of this is not set to global, but rather to ___________." Does anyone know, what this refers to in the global context when run as a script? Googling "nodejs this global context script" takes me to this page which looks very promising, as it describes contexts for running scripts, but it doesn't seem to mention the use of the this expression anywhere. What am I missing?

A: In Node.js, as of now, every file you create is called a module. So, when you run the program in a file, this will refer the module.exports. You can check that like this
console.log(this === module.exports);
// true

As a matter of fact, exports is just a reference to module.exports, so the following will also print true
console.log(this === exports);
// true

Possibly related: Why 'this' declared in a file and within a function points to different object


Q: Twilio : Calculating estimated wait time in multi queue multi server system I have a system that has multiple queues, whenever a user calls if no agent is available it will wait in the queue. The queue has multiple filters which separates the agent based on their skills. I want to calculate the estimated wait time for each user in the queue based on their position as well as skill.


Q: REACT_APP_VERSION=$npm_package_version not working on build with Webpack I have a React app, initialized with CRA.
on my .env file I have the following env variable, to access on my application the version of the package.json file:
REACT_APP_VERSION=$npm_package_version
When I use nom run build with react-scripts build, the production build takes the env value from the .env file and shows the correct version defined on package.json.
But when I use web pack to build the production app, the version value is not injected to the env variable.
this is my web pack.config.js file:
const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
require('dotenv').config({ path: './.env.staging.local' })
const srcFolder = 'src'
const distFolder = 'dist'

module.exports = {
    // entry point for application
    entry: {
        app: path.join(__dirname, srcFolder, 'index.js'),
    },
    mode: 'production',
    resolve: {
        extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
        fallback: {
            fs: false,
            crypto: require.resolve('crypto-browserify'),
            stream: require.resolve('stream-browserify'),
        },
    },

    // output file settings
    // path points to web server content folder where the web server will serve
    // the files from file name is the name of the files, where [name] is the
    // name of each entry point
    output: {
        path: path.join(__dirname, distFolder),
        filename: '[name].js',
        publicPath: '.',
    },
    optimization: {
        splitChunks: {
            chunks: 'async',
            minSize: 20000,
            minRemainingSize: 0,
            minChunks: 1,
            maxAsyncRequests: 30,
            maxInitialRequests: 30,
            enforceSizeThreshold: 50000,
            cacheGroups: {
                defaultVendors: {
                    test: /[\\/]node_modules[\\/]/,
                    priority: -10,
                    reuseExistingChunk: true,
                },
                default: {
                    minChunks: 2,
                    priority: -20,
                    reuseExistingChunk: true,
                },
            },
        },
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                },
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'public/index.html',
            filename: 'index.html',
        }),
        new CopyWebpackPlugin({
            patterns: [
                { from: 'public/assets', to: './assets' },
                { from: 'public/favicon.ico', to: './favicon.ico' },
                { from: 'public/manifest.json', to: './manifest.json' },
                { from: 'public/robots.txt', to: './robots.txt' },
            ],
        }),
        new webpack.DefinePlugin({
            'process.env': JSON.stringify(process.env),
        }),
    ],
    performance: {
        hints: false,
        maxEntrypointSize: 512000,
        maxAssetSize: 512000,
    },
}

Can someone please point out what should I do to have this value injected on the env variable as with react-scripts build


Q: If A, B are homeomorphic then A is topologically homogeneous iif B is A, B are metric spaces.
Question: If A, B are homeomorphic then A is topologically homogeneous iif B is.
I know that if A and B are homeomorphic then there exist a function $g: A \to B$ continuous, biyective and which $g^{-1}$ is also continuous (an homeomorphism). And topologically homogeneous means that I can take any $(a,b) \in A$ where $\exists$ an homeomorphism $f: \ A \to A$ such that $f(a)=b$.
I'm confused about how to think about it.
If B is not topologically homogeneous it means that there exist some $(a,b)$ such that $f(a) \ne b$ and B is homeomorphic to A, assuming that A is topologically homogeneous means that $\exists \space f(a)=b$ for any $(a,b) \dots$ I'm trying to make a contradiction, could be?


Q: Java проверка одинаковых цифр Привет, всем. Я тут учусь Java и возникла проблема. Я хочу чтоб в случаи если будет два или больше одинаковых цифр в цикле то он мне его показывал.
public class Main {

public static void main(String args[]) {
    int b[];
    int c;
    int d=0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Введите размер массива ");
    c = sc.nextInt();
    b = new int[c];
    for (int i = 0; i < b.length; i++)
        b[i] = (int) (Math.random() * c);

    for (int i = 0; i < b.length; i++)
        System.out.println(" " + b[i]);

    for (int i=0; i < b.length; i++)
            if (b[i] > d)
               d = b[i];

    System.out.println("");
    System.out.println("Это самое большое число в массиве: " + d);
    }
}

A: Можно это сделать в одно цикле. Заводим счётчик максимальных элементов. Когда появляется новый максимальный, присваиваем ему единицу. Если встречается тот же максимальный, увеличиваем на 1.
public static void main(String args[]) {
    int b[];
    int c;
    int d=0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Введите размер массива ");
    c = sc.nextInt();
    b = new int[c];
    int count = 0;
    for (int i = 0; i < b.length; i++){
        b[i] = (int) (Math.random() * c);
        System.out.println(" " + b[i]);
        if (b[i] > d){
               d = b[i];
               count = 1;
        }
        else if (b[i] == d){
            count++;
        }
    }
    System.out.println();
    if (count == 1)
        System.out.println("Это самое большое число в массиве: " + d);
    else
        System.out.println("В массиве найдено несколько (" + count +") одинаковых самых больших чисел " + d);
}

Вообще, так как мы всё делаем в одном цикле, запоминать элементы в массив совсем необязательно. Можно генерировать новые числа обрабатывать их и забывать:
public static void main(String args[]) {
    int c;
    int d=0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Введите размер массива ");
    c = sc.nextInt();
    int count = 0;
    for (int i = 0; i < c; i++){
        int b = (int) (Math.random() * c);
        System.out.println(" " + b);
        if (b > d){
               d = b;
               count = 1;
        }
        else if (b == d){
            count++;
        }
    }
    // Дальше так же


Q: Css needed to highlight common words in a table I came across this page on slate.com that highlights similar words in a table when you hover over one instance:
http://www.slate.com/blogs/lexicon_valley/2013/09/11/top_swear_words_most_popular_curse_words_on_facebook.html
Does anyone know how this is done?

A: You can do it with jQuery like this:
$('table td').mouseover(function() {
    $('table td').removeClass('highlight')
    var text = $(this).text();
    $('table td').filter(function() { return $(this).text() == text; }).addClass('highlight');
})

Check this jsFiddle

A: using jQuery.data
Always to know how something works, the first step is to read the source code
Check this:
EXAMPLE
$('.interactive_table .cell_word')
    .hover(function(){
        var word = $(this).data('word');
        $(this).parent().parent()
        .find('.word_'+word)
        .addClass('highlighted');
    },function(){
        var word = $(this).data('word');
        $(this).parent().parent()
        .find('.word_'+word)
        .removeClass('highlighted');
});

$('.interactive_table .cell_rank_number')
    .hover(function(){
        $(this).parent()
        .find('.cell_word')
        .addClass('highlighted');
    },function(){
        $(this).parent()
        .find('.cell_word')
        .removeClass('highlighted');
});


Q: Vue radio button v-if with v-model I am very new to html and vue, and trying to create radio button. I use local JSON file which is being used for creating UI. I loop through JSON object and create radio buttons accordingly. I used "defaultedOptionId" to find which one to be checked as default. Here is my JSON:
{ "id": 1,
  "selected": 1,
  "defaultedOptionId": 2,
  "selections": [
    {
      "selectionId": 1,
      "description: "XX"
    },
    ...
},
...

I am using Vue component, which basically holds JSON file. In the template, I have code so when 'defaultedOptionId === selectionId', check as default

     <input v-if="choice.defaultOptionId === selection.selectionId" type="radio" :name="'option_' + choice.choiceId" :value="selection.selectionId" checked></input>
     <input v-else type="radio" :name="'option_' + choice.choiceId" :value="selection.selectionId"></input>
        {{ index+1 }}. {{ selection.description }}

'choice' is basically JSON object.
This works if I change defaultOptionId to something else. HOWEVER, if I want to update JSON object as user selects radio button, I have to add v-model to the input field like this:

     <input v-if="choice.defaultOptionId === selection.selectionId" type="radio" :name="'option_' + choice.choiceId" :value="selection.selectionId" v-model="choice.selectedOptionId" checked></input>
     <input v-else type="radio" :name="'option_' + choice.choiceId" :value="selection.selectionId" v-model="choice.selectedOptionId"></input>
        {{ index+1 }}. {{ selection.description }}

With this, radio buttons with 'checked' property doesn't work. It checks first option and even if I change 'defaultOptionId', it doesn't care.
Basically, I want to load different JSON file with different 'defaultOptionId' which changes default check for radio button WHILE when user selects radio button, it updates JSON file's 'selectedOptionId'. I can make it work separately, but not together. I have to use this design since other templates are following the same design.

A: It's difficult to understand what you're trying to do and what the problem is because the question looks like a mess, but I'll try to help anyway.
Demo:
Here's a working example with your data:
https://codepen.io/AlekseiHoffman/pen/XWJmpod?editors=1010
Template:

    <input
      type="radio"
      :id="selection.id"
      :value="selection.selectionId"
      v-model="choice.selected"
    >

      {{selection.description}}

    Selected: {{ choice.selected }}

Script:
choice: {
  "id": 1,
  "selected": 2,
  "selections": [
    {
      "selectionId": 1,
      "description": "Radio One"
    },
    {
      "selectionId": 2,
      "description": "Radio Two"
    }
  ]
}

I simplified the JSON object since the other properties are not needed there to make it work.
Let me know if you're still having difficulties with your task.


Q: Comparison of serializing methods
Possible Duplicate:
Fastest serializer and deserializer with lowest memory footprint in C#?

I'm using BinaryFormatter class to serialize an structure or a class. (after serialization, I'm going to encrypt the serialized file before saving. (And of course decrypt it before deserialization))
But I heard that some other serialization classes are present in .Net Framework. Like  XmlSerializer, JavaScriptSerializer, DataContractSerializer and protobuf-net.
I want to know, which one is best for me?
Less RAM space needed for serialize/deserialize is the most important thing for me. Also speed is important.

A: If your aim is to reduce memory demands, then don't serialize then encrypt: instead - serialize directly to an encrypting Stream. The Stream API is designed to be chained (decorator pattern) to perform multiple transformations without excessive buffering. Likewise: deserialize from a decrypting stream; don't decrypt then deserialize. Done this way, data is encrypted/decrypted on-the-fly as needed; in addition to reducing memory, it is also good for security - since this also means the entire data never exists in decrypted form as a single buffer. See CryptoStream on MSDN for a full example.
Some additional notes; if you do happen to use protobuf-net, there are ways of reducing any in-memory buffering by using "grouped" encoding; you see: the default for sub-messages (including lists) is "length prefixed" - and the way it usually does this is by buffering the data in memory to calculate the length. However, protobuf also supports a format that uses a start/end marker which never requires knowing the length, so never requires buffering - and so the entire sequence can be written in a single pass direct to output (well, it does still use a buffer internally to improve IO, but it pools the buffer here, for maximum re-use). This is as simple as, for sub-objects:
[ProtoMember(11, DatFormat = DataFormat.Grouped)]
public Customer Customer {get;set;} // a sub-object

(where there is no significance in the 11)

A: See http://code.google.com/p/protobuf-net/wiki/Performance for a comparison of performance.


Q: Looking for jQuery find(..) method that  includes the current node The jQuery find(..) traversal method doesn't include the current node - it starts with the children of the current node.  What is the best way to call a find operation that includes the current node in its matching algorithm? Looking through the docs nothing immediately jumps out at me.

A: Define
$.fn.findSelf = function(selector) {
    var result = this.find(selector);
    this.each(function() {
        if ($(this).is(selector)) {
            result.add($(this));
        }
    });
    return result;
};

then use
$.findSelf(selector);

instead of
$find(selector);

Sadly jQuery does not have this built-in. Really strange for so many years of development. My AJAX handlers weren't applied to some top elements due to how .find() works.

A: $('selector').find('otherSelector').add($('selector').filter('otherSelector'))

You can store $('selector') in a variable for speedup. You can even write a custom function for this if you need it a lot:
$.fn.andFind = function(expr) {
  return this.find(expr).add(this.filter(expr));
};

$('selector').andFind('otherSelector')

A: The accepted answer is very inefficient and filters the set of elements that are already matched.
//find descendants that match the selector
var $selection = $context.find(selector);
//filter the parent/context based on the selector and add it
$selection = $selection.add($context.filter(selector);

A: You can't do this directly, the closest I can think of is using .andSelf() and calling .filter(), like this:
$(selector).find(oSelector).andSelf().filter(oSelector)
//or...
$(selector).find('*').andSelf().filter(oSelector);

Unfortunately .andSelf() doesn't take a selector, which would be handy.

A: If you want the chaining to work properly use the snippet below.
$.fn.findBack = function(expr) {
    var r = this.find(expr);
    if (this.is(expr)) r = r.add(this);
    return this.pushStack(r);
};

After the call of the end function it returns the #foo element.
$('#foo')
    .findBack('.red')
        .css('color', 'red')
    .end()
    .removeAttr('id');

Without defining extra plugins, you are stuck with this.
$('#foo')
    .find('.red')
        .addBack('.red')
            .css('color', 'red')
        .end()
    .end()
    .removeAttr('id');

A: In case you are looking for exactly one element, either current element or one inside it, you can use:
result = elem.is(selector) ? elem : elem.find(selector);

In case you are looking for multiple elements you can use:
result = elem.filter(selector).add(elem.find(selector));

The use of andSelf/andBack is pretty rare, not sure why. Perhaps because of the performance issues some guys mentioned before me.
(I now noticed that Tgr already gave that second solution)

A: I know this is an old question, but there's a more correct way. If order is important, for example when you're matching a selector like :first, I wrote up a little function that will return the exact same result as if find() actually included the current set of elements:
$.fn.findAll = function(selector) {
  var $result = $();

  for(var i = 0; i < this.length; i++) {
    $result = $result.add(this.eq(i).filter(selector));
    $result = $result.add(this.eq(i).find(selector));
  }

  return $result.filter(selector);
};

It's not going to be efficient by any means, but it's the best I've come up with to maintain proper order.

A: I was trying to find a solution which does not repeat itself (i.e. not entering the same selector twice).
And this tiny jQuery extention does it:
jQuery.fn.findWithSelf = function(...args) {
  return this.pushStack(this.find(...args).add(this.filter(...args)));
};

It combines find() (only descendants) with filter() (only current set) and supports whatever arguments both eat. The pushStack() allows for .end() to work as expected.
Use like this:
$(element).findWithSelf('.target')

A: For jQuery 1.8 and up, you can use .addBack(). It takes a selector so you don't need to filter the result:
object.find('selector').addBack('selector')

Prior to jQuery 1.8 you were stuck with .andSelf(),  (now deprecated and removed) which then needed filtering:
object.find('selector').andSelf().filter('selector')

A: I think andSelf is what you want:
obj.find(selector).andSelf()

Note that this will always add back the current node, whether or not it matches the selector.

A: If you are strictly looking in the current node(s) the you just simply do
$(html).filter('selector')

A: Here's the right (but sad) truth:
$(selector).parent().find(oSelector).filter($(selector).find('*'))

http://jsfiddle.net/SergeJcqmn/MeQb8/2/


Q: Kendo Grid plumbing I'm trying to get the Kendo UI grid connected in my MVC3 app, but I'm not getting any data displaying. I think it should be simple, but I'm not seeing it. Here is my code:
View:
@model List<pests.web.com.Models.Workitem>

@{
    ViewBag.Title = "Worklist";
    ViewBag.CurrentPage = "Worklist";
}

<link href="../../Styles/kendo.common.min.css" rel="stylesheet" />
<link href="../../Styles/kendo.default.min.css" rel="stylesheet" />

Layout page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Styles/Site.css")" rel="stylesheet" type="text/css" />

        @RenderBody()

Controller code I'm trying to call from the view:
 public class HomeController : Controller
    {
        [HttpPost]
        public ActionResult GetWorklist()
        {
            List<Workitem> worklist = PestsLogic.GetWorklist();
            return View("Home", worklist);
        }
    }

GetWorklist() is returning a few items. They are simple object with a few properties. Here's it is:
public class Workitem
{
    public string PartNumber { get; set; }
    public string ProcurementCode { get; set; }
    public int Priority { get; set; }
    public string Status { get; set; }
}

Is there anything obvious that I've got hooked up wrong? There are no error messages, just a blank page (with a title, though).
Thanks!

A: The problem was simply that I needed to move the references to the JS files to before I tried to use the Kendo grid.


Q: Train Stacked Autoencoder Correctly I try to build a Stacked Autoencoder in Keras (tf.keras). By stacked I do not mean deep. All the examples I found for Keras are generating e.g. 3 encoder layers, 3 decoder layers, they train it and they call it a day. However, it seems the correct way to train a Stacked Autoencoder (SAE) is the one described in this paper: Stacked Denoising Autoencoders: Learning Useful Representations in
a Deep Network with a Local Denoising Criterion
In short, a SAE should be trained layer-wise as shown in the image below. After layer 1 is trained, it's used as input to train layer 2. The reconstruction loss should be compared with the layer 1 and not the input layer.

And here is where my trouble begins. How to tell Keras which layers to use the loss function on?
Here is what I do. Since the Autoencoder module is not existed anymore in Keras, I build the first autoencoder, and I set its encoder's weights (trainable = False) in the 1st layer of a second autoencoder with 2 layers in total. Then when I train that, it obviously compares the reconstructed layer out_s2 with the input layer in_s, instead of the layer 1 hid1.
# autoencoder layer 1
in_s = tf.keras.Input(shape=(input_size,))
noise = tf.keras.layers.Dropout(0.1)(in_s)
hid = tf.keras.layers.Dense(nodes[0], activation='relu')(noise)
out_s = tf.keras.layers.Dense(input_size, activation='sigmoid')(hid)

ae_1 = tf.keras.Model(in_s, out_s, name="ae_1")
ae_1.compile(optimizer='nadam', loss='binary_crossentropy', metrics=['acc'])

# autoencoder layer 2
hid1 = tf.keras.layers.Dense(nodes[0], activation='relu')(in_s)
noise = tf.keras.layers.Dropout(0.1)(hid1)
hid2 = tf.keras.layers.Dense(nodes[1], activation='relu')(noise)
out_s2 = tf.keras.layers.Dense(nodes[0], activation='sigmoid')(hid2)

ae_2 = tf.keras.Model(in_s, out_s2, name="ae_2")
ae_2.layers[0].set_weights(ae_1.layers[0].get_weights())
ae_2.layers[0].trainable = False

ae_2.compile(optimizer='nadam', loss='binary_crossentropy', metrics=['acc'])

The solution should be fairly easy, but I can't see it nor find it online. How do I do that in Keras?

A: It seems like the question is outdated by looking at the comments. But I'll still answer this as the use-case mentioned in this question is not just specific to autoencoders and might be helpful for some other cases.
So, when you say "train the whole network layer by layer", I would rather interpret it as "train small networks with one single layer in a sequence".
Looking at the code posted in this question, it seems that the OP has already built small networks. But both these networks do not consist of one single layer.
The second autoencoder here, takes as input the input of first autoencoder. But, it should actually take as input, the output of first autoencoder.
So then, you train the first autoencoder and collect it's predicitons after it is trained. Then you train the second autoencoder, which takes as input the output (predictions) of first autoencoder.
Now let's focus on this part: "After layer 1 is trained, it's used as input to train layer 2. The reconstruction loss should be compared with the layer 1 and not the input layer."
Since the network takes as input the output of layer 1 (autoencoder 1 in OP's case), it will be comparing it's output with this. The task is achieved.
But to achieve this, you will need to write the model.fit(...) line which is missing in the code provided in the question.
Also, just in case you want the model to calculate loss on input layer, you simply replace the y parameter in model,fit(...) to the input of autoencoder 1.
In short, you just need to decouple these autoencoders into tiny networks with one single layer and then train them as you wish. No need to use trainable = False now, or else use it as you wish.


Q: Itemize and alignment of text I would like to look my text like this:
\item Parameter     and the text should continue at the same "tab space"
\item Variable      so it looks like this

Can seem to find an easy way to do this.
Edit: sorry question is unclear.
It supposed to be an itemize and I want to align the text that describes the parameters and variables on the right like the example above.

A: Perhaps, you can try this:
   \documentclass{article}
   \usepackage{listliketab}
   \begin{document}

   \storestyleof{itemize}
   \begin{listliketab}
   \begin{tabular}{Llll}
   \textbullet &   Parameter & and the text should continue at the same "tab space"   \\
   \textbullet &  Variable & so it looks like this  \\
   \end{tabular}
   \end{listliketab}
   \end{document}

A: \documentclass{beamer}

\newcommand\itemshape[1]{%
  \setbeamertemplate{itemize item}[#1]%
  \usebeamertemplate{itemize item}%
}

\begin{document}
\begin{frame}

  \begin{description}[align=right]
    \item[\itemshape{circle} First Item] Description of first item
    \item[\itemshape{circle} Second Item] Description of second item
    \item[\itemshape{circle} Third Item] Description of third item
    \item[\itemshape{circle} Fourth Item] Description of fourth item
  \end{description}

\end{frame}
\end{document}

[but I am not sure, why the first bullet is not aligned]


Q: Can I inherit my WCF DataContract from a shared interface? I have a WCF service and client in the same solution (different projects). The service class itself inherits from an interface, and that interface is shared between client and server (via a linked file). The client uses a service factory to generate a proxy. This has proved a really nice way to link the two sides without referencing the server-side project from the client.
One of the service methods returns an object that includes the DataContract and DataMember attributes, and until recently this class was linked to the client as well, but the server-side logic was excluded from the client using compilation symbols.
I decided it would be more sensible to turn this into an interface as well. But now I get the following exception every time the service method is called from the client:
The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.
Its inner exception is as follows:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
So by way of simplified example, my service essentially shares the following interface with the client:
public interface IMyData
{
    [DataMember]
    int Id {get; set;}

    [DataMember]
    string Description {get; set;}
}

The actual object that the interface works with and will return looks something like this:
[DataContract]
public class MyData : IMyData
{
    [DataMember]
    public int Id {get; set;}

    [DataMember]
    public string Description {get; set;}
}

The interface of my service looks something like this:
[ServiceContract]
public interface IMyService
{
    [OperationContract]
    IMyData GetData();
}

The implementation looks something like this:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single)]
public class MyService : IMyService
{
    [OperationContract]
    IMyData GetData()
    {
        // Get data.
    }
}

Hope that all makes a little sense! I'm just wondering if I'm doing this all wrong. I'll just go back to sharing the class and sectioning off the server-side-only code if I have to .. but I'd rather use an interface if I can.
Any ideas?

A: There is no benefit to putting an interface on a DataContract as they simply represent data and no logic. You typically put those DataContracts inside the same assembly with the ServiceContracts or a separate assembly all together. This will prevent exposing the business logic to your clients.


Q: The MailChimp PHP library is missing the required GuzzleHttp library I have installed Guzzle on my Godaddy shared hosting via SSH but my Drupal site is still telling me that:

"The MailChimp PHP library is missing the required GuzzleHttp library.
  Please check the installation notes in README.txt."

Any ideas why it would be saying that? it appears to have installed correctly.
godaddy@user [~/public_html]$ php composer.phar require guzzlehttp/guzzle:~6.0
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing guzzlehttp/promises (1.2.0)
    Downloading: 100%

  - Installing psr/http-message (1.0)
    Downloading: 100%

  - Installing guzzlehttp/psr7 (1.3.0)
    Downloading: 100%

  - Installing guzzlehttp/guzzle (6.2.0)
    Downloading: 100%

Writing lock file
Generating autoload files

A: On the library page, if you are using the package https://github.com/thinkshout/mailchimp-api-php/releases which contains everything e.g. v1.0.6-package.zip (and therefore having everything already doesn't require composer to get them), then remove /vendor from .gitignore so that all the files in /vendor - including guzzle are included in your code base so that should you deploy the code from your repo to a production server, all of it will be loaded.
CREDIT: https://www.drupal.org/node/2709615#comment-11888769

A: This fixed the issue, Guzzle needed to be installed into the MailChimp libraries folder?! Guzzle Instructions
godaddy@user [~/public_html]$ cd sites/all/libraries/mailchimp/
godaddy@user [~/public_html/sites/all/libraries/mailchimp]$ curl -sS https://getcomposer.org/installer | php
All settings correct for using Composer
Downloading 1.1.1...

Composer successfully installed to: /home/mysite/public_html/sites/all/libraries/mailchimp/composer.phar
Use it: php composer.phar
godaddy@user [~/public_html/sites/all/libraries/mailchimp]$ ./composer.phar install
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing sebastian/version (1.0.6)
    Downloading: 100%

  - Installing sebastian/global-state (1.1.1)
    Downloading: 100%

  - Installing sebastian/recursion-context (1.0.2)
    Downloading: 100%

  - Installing sebastian/exporter (1.2.1)
    Downloading: 100%

  - Installing sebastian/environment (1.3.7)
    Downloading: 100%

  - Installing sebastian/diff (1.4.1)
    Downloading: 100%

  - Installing sebastian/comparator (1.2.0)
    Downloading: 100%

  - Installing symfony/yaml (v3.0.6)
    Downloading: 100%

  - Installing doctrine/instantiator (1.0.5)
    Downloading: 100%

  - Installing phpdocumentor/reflection-docblock (2.0.4)
    Downloading: 100%

  - Installing phpspec/prophecy (v1.6.0)
    Downloading: 100%

  - Installing phpunit/php-text-template (1.2.1)
    Downloading: 100%

  - Installing phpunit/phpunit-mock-objects (2.3.8)
    Downloading: 100%

  - Installing phpunit/php-timer (1.0.8)
    Downloading: 100%

  - Installing phpunit/php-token-stream (1.4.8)
    Downloading: 100%

  - Installing phpunit/php-file-iterator (1.4.1)
    Downloading: 100%

  - Installing phpunit/php-code-coverage (2.2.4)
    Downloading: 100%

  - Installing phpunit/phpunit (4.8.21)
    Downloading: 100%

  - Installing guzzlehttp/promises (1.2.0)
    Loading from cache

  - Installing psr/http-message (1.0)
    Loading from cache

  - Installing guzzlehttp/psr7 (1.3.0)
    Loading from cache

  - Installing guzzlehttp/guzzle (6.2.0)
    Loading from cache

sebastian/global-state suggests installing ext-uopz (*)
phpdocumentor/reflection-docblock suggests installing dflydev/markdown (~1.0)
phpdocumentor/reflection-docblock suggests installing erusev/parsedown (~1.0)
phpunit/php-code-coverage suggests installing ext-xdebug (>=2.2.1)
phpunit/phpunit suggests installing phpunit/php-invoker (~1.1)
Writing lock file
Generating autoload files


Q: Building Postgresql C function with Multidimensional Array as input I am extending the Postgresql functions using the C SPI. The function needs to be able to take in a Postgres N-Dim Array and get the data out of it. I am able to get the data from a 1D array but I get a segfault when trying to access a N-Dim array.
My first try to just access an element was simply
PG_FUNCTION_INFO_V1(sum_elements);
Datum
matmul(PG_FUNCTION_ARGS)
{

    ArrayType *anyArray = PG_GETARG_ARRAYTYPE_P(0);
    int32 **a = (int32 **)  ARR_DATA_PTR(anyArray);

    PG_RETURN_INT64(a[1][1]);
}

I also tried as if it flattened the matrix into a 1D array but the values that came out were just garbage.
Thanks for the help!

A: You can try using the deconstruct_array (..) function to extract the values. This function will give you a Datum type pointer.
Example of the book:
deconstruct_array(input_array, //one-dimensional array
                  INT4OID, //of integers
                  4,//size of integer in bytes
                  true,//int4 is pass-by value
                  'i',//alignment type is 'i'
                  &datums, &nulls, &count); // result here

"The datums pointer will be set to point to an array filled with actual elements."
You can access the values using:
DatumGetInt32(datums[i]);


Q: How to get the timestamps of lyrics in songs? We have built an application in Python for getting the lyrics of a song that the user searches for. We are using the Genius API for this. However, we also want to know the timestamps of each lyric in the song, so that we know when each lyric plays or shows up. Is there an API or library that we could use to get the timestamp of each lyric? Or would we need to manually recognize each lyric in the song using an audio recognition technique?
Thank you for all of the help.

A: Last time I looked, Genius Lyrics' APIs do not include timestamps unfortunately. There are alternatives out there, such as Musixmatch - although they're not free (and apparently not cheap).
I did find Lyrics Plus though. It's an integration for Spotify. Maybe their code on GitHub could help. Good luck!


Q: How to ask someone to continue the play when they have stopped playing for some reasons like thinking or looking at their phones? Imagine you're playing cards with your friends and there is someone among you who plays really slowly. Suddenly he stops to play and starts thinking about something. How would you ask them to play? What do you say them to invite them to continue the game? I've written my own translation sentences which work in my language. I have no idea if they work in English too. If they don't then please let me know what shall I say them:

*

*Play!

*Continue!

*Throw your card.

A: Given the informality of the situation, there are a multitude of responses that one could give, depending on how friendly you are with the other players, and to what degree you want to show your impatience. For example, a simple

*

*c'mon!

*You're up.

*Your turn.

*Throw down a card.

...and so on may be all that's needed to get the game going again. If you wish to show impatience or exasperation at a slow player, then the comments can quickly degenerate from there.
Given the suggestions that you made, they all work, but play! and continue! seem quite formal to me, and out of character with the setting of playing cards.


Q: How to add generic condition to sp select? I really don't know what to do in this situation, so don't be too harsh.
If I have my select:
declare @Id uniqueidentifier = 'some parent guid'
declare @Type int = 1 -- can be 1, 2 or 3
declare @UserType varchar(max) --can be 0, anything else than 0, or all users at once

if(@Type = 1)
set @UserType = 'and UserType <> 0'
if(@Type = 2)
set @UserType = 'and UserType = 0'
if(@Type = 3)
set @UserType = ''
    select * from users where parentId = @Id + @UserType

What to do in the situation where condition is "generic"? Do i really need to create 3 different Sp?

A: You can use AND/OR logic to simulate the If-else condition in where clause. Try something like this
select * from users
where
parentid= @id
and
(
(@Type = 1 and UserType <> 0)
or
(@Type = 2 and UserType = 0)
or
(@Type = 3)
)

or you can also use Dynamic sql to do this
declare @Id uniqueidentifier = 'some parent guid'
declare @Type int = 1 -- can be 1, 2 or 3
Declare @UserType varchar(max) --can be 0, anything else than 0, or all users at once
Declare @sql nvarchar(max)

if(@Type = 1)
set @UserType = ' and UserType <> 0'
if(@Type = 2)
set @UserType = ' and UserType = 0'
if(@Type = 3)
set @UserType = ''

set @sql = 'select * from users where parentId ='''+ cast(@Id as varchar(25))+''''+ @UserType

--Print @sql

Exec sp_executesql @sql

A: Different select statements would be most efficient since each is a fundamentally different query.  If static SQL becomes unwieldly, use dynamic SQL.  Below is a parameterized example using techniques from http://www.sommarskog.se/dyn-search.html.
declare @sql nvarchar(MAX) = N'select * from users where parentId = @Id';
declare @Id uniqueidentifier = 'some parent guid';
declare @Type int = 1; -- can be 1, 2 or 3
declare @UserType varchar(max); --can be 0, anything else than 0, or all users at once

SET @sql = @sql + CASE @Type
    WHEN 1 THEN N' and UserType <> 0'
    WHEN 2 THEN N' and UserType = 0'
    WHEN 3 THEN N'' END;

EXEC sp_executesql
      @sql
    , N'@Id uniqueidentifier'
    , @Id = @Id;


Q: net::ERR_CONTENT_LENGTH_MISMATCH on angular 2 on docker cloud I am getting a net::ERR_CONTENT_LENGTH_MISMATCH  main.bundle.js  while running angular 2 on docker cloud ,the same however works on my local docker instance
The below is the docker file
FROM node

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app

COPY . /usr/src/app

RUN npm install

and the docker compose
version: '2'
services:
app:
 build: .
 volumes:
   - ./:/usr/src/app
 ports:
   - 4200:4200
   - 49153:49153
 command: npm start

Any clue as to why this is happening will be of much help

A: Happened to me after I updated one of the packages in node_modules. Probably integrity/checksum-related issue. The cure was to flush node_modules and run
$ npm install
again.


Q: Using the deep neural network package "Chainer" to train a simple dataset I'm trying to use the chainer package for a large project I'm working on. I have read through the tutorial on their website which gives an example of applying it to the MNIST dataset, but it doesn't seem to scale easily to other examples, and there's simply not enough documentation otherwise.
Their example code is as follows:
class MLP(Chain):
    def __init__(self, n_units, n_out):
        super(MLP, self).__init__(
            # the size of the inputs to each layer will be inferred
            l1=L.Linear(None, n_units),  # n_in -> n_units
            l2=L.Linear(None, n_units),  # n_units -> n_units
            l3=L.Linear(None, n_out),    # n_units -> n_out
        )

    def __call__(self, x):
        h1 = F.relu(self.l1(x))
        h2 = F.relu(self.l2(h1))
        y = self.l3(h2)
        return y

train, test = datasets.get_mnist()
train_iter = iterators.SerialIterator(train, batch_size=5, shuffle=True)
test_iter = iterators.SerialIterator(test, batch_size=2, repeat=False, shuffle=False)
model = L.Classifier(MLP(100, 10))  # the input size, 784, is inferred
optimizer = optimizers.SGD()
optimizer.setup(model)
updater = training.StandardUpdater(train_iter, optimizer)
trainer = training.Trainer(updater, (4, 'epoch'), out='result')
trainer.extend(extensions.Evaluator(test_iter, model))
trainer.extend(extensions.LogReport())
trainer.extend(extensions.PrintReport(['epoch', 'main/accuracy', 'validation/main/accuracy']))
trainer.extend(extensions.ProgressBar())
trainer.run()

Could someone point me in the direction of how to simple fit a straight line to a few data points in 2D? If I can understand a simple fit such as this I should be able to scale appropriately.
Thanks for the help!

A: I pasted simple regression modeling here.
You can use original train data and test data as tuple.
    train = (data, label)
Here, data.shape = (Number of data, Number of data dimesion)
And, label.shape = (Number of data,)
Both of their data type should be numpy.float32.
import chainer
from chainer.functions import *
from chainer.links import *
from chainer.optimizers import *

from chainer import training
from chainer.training import extensions
from chainer import reporter
from chainer import datasets
import numpy

class MyNet(chainer.Chain):

    def __init__(self):
        super(MyNet, self).__init__(
            l0=Linear(None, 30, nobias=True),
            l1=Linear(None, 1, nobias=True),
        )

    def __call__(self, x, t):
        l0 = self.l0(x)
        f0 = relu(l0)
        l1 = self.l1(f0)
        f1 = flatten(l1)
        self.loss = mean_squared_error(f1, t)
        reporter.report({'loss': self.loss}, self)
        return self.loss

def get_optimizer():
    return Adam()

def training_main():
    model = MyNet()

    optimizer = get_optimizer()
    optimizer.setup(model)

    train, test = datasets.get_mnist(label_dtype=numpy.float32)
    train_iter = chainer.iterators.SerialIterator(train, 50)
    test_iter = chainer.iterators.SerialIterator(test, 50,
                                                 repeat=False,
                                                 shuffle=False)

    updater = training.StandardUpdater(train_iter, optimizer)
    trainer = training.Trainer(updater, (10, 'epoch'))
    trainer.extend(extensions.ProgressBar())
    trainer.extend(extensions.Evaluator(test_iter, model))
    trainer.extend(
        extensions.PlotReport(['main/loss', 'validation/main/loss'],
                              'epoch'))
    trainer.run()

if __name__ == '__main__':
    training_main()


Q: What's behind Excel Solver Evolutionary? I have an optimization problem on Excel, using Evolutionary algorithm.
Works fine, but i'd like to understand how it gets to the solution, ie what is or are the exact method(s) used.
Is that available anywhere ?
The final purpose being to move this project from Excel to a Java program, because it gets more and more complex.
Thank you

A: Do the same optimization in LibreOffice Calc. Algorithms done in LibreOffice Calc are available as part of the open-source project.


Q: Open browser windows without menu bars (JavaScript?) The users in my community want the chat to be opened in a small window without all the control bars.
So I think a popup window without scroll bars, location bar, status bar and so on would be the best solution. Right?
What is the best way to have such a popup window? JavaScript? Can I do it like this?
BETWEEN  AND

BETWEEN  AND
Open chat

ON CHAT.HTML
<form><input type="submit" value="Close chat" onClick="window.close()"></form>

A: If you want the new window not to have the menu bars and toolbars, the only way to do it is through JavaScript as with the example you provided yourself. However keep in mind that most browsers, nowadays, ignore what you set for the status bar (always show it) and may be configured to also always show the remaining toolbars. If a browser is configured in such a way there's no escaping it, although the default should be that you'll only get the status bar and perhaps the address bar.

A: Your solution is good, but there are alternatives.
You can create the window by your own, as some kind of layer. Then you need to implement lots of things but it gives you full control over window Look And Feel. Of course you can always use some scripts like jQuery UI Dialog.

A: In short, you can't control everything that the browser displays in a pop-up window. Most browsers keep the URL visible, for example. This page explains most of the details (though it is a couple years old).


Q: Php laravel 5 fatalexception unexpected end of file I have the following code snippet to end a file in php and laravel.
 @extends('master')
 @section('content')

Hello World

 @endsection

master.blade.php file is as below
<!doctype html>

   <meta charset="UTF-8">
   <title>{{ $title }}</title>
    {{ HTML::style('css/bootstrap.css') }}
    {{ HTML::script('js/bootstrap.js') }}
    {{ HTML::script('js/jquery.js') }}

      {{ HTML::link('/','login',array('class' => 'brand')) }}

        @if(Auth::user())

{{ HTML::link('logout', 'Logout') }}

        @else

{{ HTML::link('login','login') }}

    @yield('content')

However, I get the following error:
FatalErrorException in 4d94a10943d3d038e850b4e898e794a8 line 33:
syntax error, unexpected end of file

What exactly is the syntax to end the file in laravel,php using the blade template.

A: You're missing the @endif directive. Your blade syntax needs to be:
@if(Auth::user())

{{ HTML::link('logout', 'Logout') }}

@else

{{ HTML::link('login','login') }}

@endif

Without the @endif directive, you'll get the "unexpected end of file" error.


Q: Memory for a member array in C# I have been programming for a while today and I think I need a break because I can't seem to figure this very simple thing. A help will be greatly appreciated.
I have a class (actually Form1) and there a member array int[,]f.
Now I don't manage memory for it there and then (maybe I should?).
Instead in another method, I call a function say:
myFunction(f,.....);

this function is like
void myFunction(int[,] f, ...some other arguments)
{
    //....
    f = new int[NX ,NY];
    //....
}

As you can see, I separate memory for the array f inside the function.
Now my question is; is this memory going to be garbage collected when I leave myFunction?

A: First, you have to understand a few very important things:

Garbage Collection happens randomly.

Secondly,

Only those objects that have no variables referring to them are eligible for GC

Thirdly,
f= new int[NX,NY];

You are making f refer to something else. The original f is still referenced by the Form1.f. But this new int[NX, NY] object is now created and referred to only by the local f in the method.
After the method returns, nothing should be referring to the new f (unless you assigned it to somewhere else), so the new f becomes eligible for GC. Note that I said "becomes eligible for GC" instead of "is garbage collected".
However, since Form1 is still holding a reference to the original f, the original f will not become eligible for GC before the form does (unless you set it to something else).


Q: Subtracting dates from 2 different tables with join I am trying to Select all records in the claims data where the “from_date” field is before the “eff_date” for the same “emp_ssn”, same “pt_ssn”, in the "patient data".
SELECT *
FROM CLAIM
   left join PATIENT on claim.pt_ssn = Patient.pt_ssn
WHERE (CLAIM.emp_ssn = Patient.emp_num AND Patient.pt_ssn=Claim.pt_ssn)
  AND (CLAIM.FROM_DATE < Patient.eff_date);

This is giving me undesired results also with duplicates.
I have tried left join, right join, inner join, and no join. I still cannot receive desired result.  Any help would be appreciated.

A: (CLAIM.emp_ssn = Patient.emp_num AND Patient.pt_ssn=Claim.pt_ssn)

The second part of the clause Patient.pt_ssn=Claim.pt_ssn is already mentioned in the ON clause so you don't need to mention it again.
Try this :
SELECT      CLAIM.*
FROM        CLAIM
left join   PATIENT on claim.pt_ssn = Patient.pt_ssn
WHERE       CLAIM.emp_ssn = Patient.emp_num
AND         CLAIM.FROM_DATE < Patient.eff_date

EDIT : I'm not sure what data set you have, but I think a simple group by should resolve your query.
I'll try my best to help you out :
Table : CLAIM
pt_ssn   emp_ssn   claim_name   from_date
1234        1       Claim_1     2015-05-10
2345        2       Claim_2     2015-07-10
3456        3       Claim_3     2015-09-10
4567        4       Claim_4     2015-11-10
5678        5       Claim_5     2015-12-10
5678        5       Claim_5     2015-12-04
6789        6       Claim_6     2015-12-12

Table : PATIENT
pt_ssn    emp_num        eff_date
 1234       1           2015-05-12
 2345       2           2015-07-08
 3456       3           2015-09-15
 4567       4           2015-11-07
 5678       5           2015-12-09
 5678       5           2015-12-12
 6789       6           2015-12-02

You can see that I have created duplicate records with the pt_ssn as 5678. Now, if I use the aforementioned query, namely :
SELECT      CLAIM.*
FROM        CLAIM
left join   PATIENT on claim.pt_ssn = Patient.pt_ssn
WHERE       CLAIM.emp_ssn = Patient.emp_num
AND         CLAIM.FROM_DATE < Patient.eff_date

then the result set I get is :
pt_ssn      emp_ssn claim_name  from_date
 1234       1       Claim_1     2015-05-10
 3456       3       Claim_3     2015-09-10
 5678       5       Claim_5     2015-12-04
 5678       5       Claim_5     2015-12-04       /*DUPLICATE ENTRY*/
 5678       5       Claim_5     2015-12-10

SQL Fiddle : http://sqlfiddle.com/#!9/342d0/1
You can see the duplicate entry above. If you want to exclude such duplicate entries, you'll need to use Group By as follows :
 SELECT     CLAIM.pt_ssn,
            CLAIM.emp_ssn,
            CLAIM.claim_name,
            CLAIM.from_date
FROM        CLAIM
left join   PATIENT on #claim.pt_ssn = Patient.pt_ssn
WHERE       CLAIM.emp_ssn = Patient.emp_num
AND         CLAIM.FROM_DATE < Patient.eff_date
GROUP BY    CLAIM.from_date,
            CLAIM.pt_ssn,
            CLAIM.emp_ssn,
            CLAIM.claim_name

This will give you the result set as follows :
pt_ssn  emp_ssn claim_name  from_date
 1234   1       Claim_1     2015-05-10
 3456   3       Claim_3     2015-09-10
 5678   5       Claim_5     2015-12-04
 5678   5       Claim_5     2015-12-10

SQL Fiddle : http://sqlfiddle.com/#!9/342d0/2
Observe that there are two entries for the pt_ssn : 5678. This is because they are for different dates.
Hope this helps!!!

A: I am guessing there is a patient record even if there is no claim.. so the left join should be the other order.
Try this (or even list the fields you want returned):
SELECT distinct *
FROM PATIENT left join CLAIM
on claim.pt_ssn = Patient.pt_ssn
and CLAIM.emp_ssn = Patient.emp_num
WHERE CLAIM.FROM_DATE < Patient.eff_date;


Q: How to type function calls when using Function.prototype.apply I have the following types:
type Options = 'A' | 'B' | 'C' | 'D'

type SpecificOptions = 'A' | 'B'

type OptionsValueType = {
  A: () => void,
  B: string
}

I use those to build the following class methods:
declare class MyClass {
  myFunction(option: 'A', value: OptionsValueType['A'])
  myFunction(option: 'B', value: OptionsValueType['B'])
  myFunction(option: Exclude<Options, SpecificOptions>, value: number)

}

This works great:

And I also have some code that calls myFunction inside a loop, using Function.prototype.apply, it looks something like this:
const calls = [
  ['A', 1],
  ['B', 1],
  ['C', 1],
]

for (const call of calls) {
  a.myFunction.apply(undefined, call)
}

But the code above does not shows any type error.
I cannot use as const on the calls array because it's built dynamically (and even if I could, it does not seems to work either).
How to type the code above to make sure the .apply is correctly typed?  Or is that currently not possible with Typescript?
Above code is available on this Typescript playground

A: If calls is built dynamically then no, there is no way to get a compile time error based on its value.
You can check the values at runtime and throw an error of your own.  Otherwise, JS will pass them in as function arguments regardless of their type.
If you wanted to check the types yourself you could do:
for (const call of calls) {
  if (typeof call[0] !== 'string' || typeof call[1] !== 'string') {
    throw new Error('Both arguments to myFunction must be strings');
  }
  a.myFunction.apply(undefined, call)
}


Q: Custom post type – customise single.php in child theme I’ve managed to create my first custom post type (in this case artists) but I want to customise how the single page layout look when click on ‘Read more’ about the artist? So far, I have copied the single.php from the Kalium theme to Kalium child theme, but do not know how to change the code in single.php
The page I need help with:
https://staging2.africanwomensplaywrightnetwork.org/artist/philisiwe-twijnstra/
<?php
/*
* Template Name: AWPN Featured Article
* Template Post Type: Artists
*/
/**
* Kalium WordPress Theme
*
* Single post template.
*
* @author Laborator
* @link https://kaliumtheme.com
*/
if ( ! defined( ‘ABSPATH’ ) ) {
exit; // Direct access not allowed.
}

/**
* Theme header.
*/
get_header();

/**
* Show post information if exists.
*/
if ( have_posts() ) :

while ( have_posts() ) : the_post();

/**
* kalium_blog_single_before_content
*
* @hooked kalium_blog_single_post_image_full_width – 10
**/
do_action( ‘kalium_blog_single_before_content’ );

?>
<div <?php kalium_blog_single_container_class(); ?>>

<?php
/**
* kalium_blog_single_content hook
*
* @hooked kalium_blog_single_post_image_boxed – 10
* @hooked kalium_blog_single_post_layout – 20
* @hooked kalium_blog_single_post_sidebar – 30
**/
do_action( ‘kalium_blog_single_content’ );
?>

<?php

/**
* kalium_blog_single_after_content
*
* @hooked kalium_blog_single_post_comments – 10
**/
do_action( ‘kalium_blog_single_after_content’ );

endwhile;

endif;

/**
* Theme footer.
*/
get_footer();

A: Make sure you give Template Name: AWPN Featured Article a new unique name.
Then go inside an artist's post and select from the right sidebar the new Template you created.
Write some content, publish, and check the page in the front-end.


Q: SQLite invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] in CPP Need to update database by new value (Name and Address) provided by the user.The error in query is that:

*

*error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]   sqlite3_bind_text(res, 2, *c2)

*error: too few arguments to function ‘int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int, void ()(void))’
     sqlite3_bind_text(res, 2, *c2)

my code is:
        const char *c1 = updatedName.c_str();
        const char *c2 = updatedAdd.c_str();

char *sql = ("UPDATE RECORDS SET NAME = ? AND ADDRESS = ? WHERE ACCOUNT_No = ?");
        rc = sqlite3_prepare_v2(db, sql, -1, &res, 0);
        sqlite3_bind_text(res, 1, *c1);
        sqlite3_bind_text(res, 2, *c2);
        sqlite3_bind_int(res, 3, acc);
        rc = sqlite3_step(res);
        sqlite3_finalize(res);

A: sqlite3_bind_text() wants a pointer to the entire string, not only the first character. (You need to understand how C pointers and strings (character arrays) work.)
And the sqlite3_bind_text() documentation tells you to use five parameters:
sqlite3_bind_text(res, 1, updatedName.c_str(), -1, SQLITE_TRANSIENT);


Q: Node js promise in a method I am new to asynch programming and I cannot understand Promises. I am trying to use a reverse geocoding library where lat/long is sent to Google Maps and a json detailing the location is returned.
class Geolocator
{
    constructor()
    {
        let options = {
            provider: 'google',
            httpAdapter: 'https',
            apiKey: mapsKey,
            formatter: null
        };

        this._geocoder = NodeGeocoder(options);
    }

    getLocationId(lat, lon)
    {
        this._geocoder.reverse({lat: lat, lon: lon})
            .then(function(res) {
                return this._parse(null, res);
            })
            .catch(function(err) {
                return this._parse(err, null);
            });
    }

    _parse(err, res)
    {
        if (err || !res)
            throw new Error(err);
        return res;
    }

When I call geolocator.getLocationId I get undefined. I am guessing that the method call exits and returns undefined. What is the best way to encapsulate the promise?

A: Like @smarx said, you would return the Promise at getLocationId() and execute then branch:
class Geolocator {
  // ...

  /* returns a promise with 1 argument */
  getLocationId(lat, lon) {
   return this._geocoder.reverse({ lat, lon })
  }
}

// calling from outside
geolocator
  .getLocationId(lat, lon)
  .then((res) => {
     // whatever
  })
  .catch((err) => {
    // error
  })


Q: difference between environment variables and System properties iam using the below link to understand environment variables and system properties.
https://docs.oracle.com/javase/tutorial/essential/environment/env.html
The link says environment variables are set by OS and passed to applications.
When i fetch environment variables using System.getenv() it shows me lot of properties which i never set.
So it must be OS (im using macOS) which had set these properties.
Some of the properties in System.getenv() are MAVEN_CMD_LINE_ARGS, JAVA_MAIN_CLASS_1420, JAVA_MAIN_CLASS_1430.
My question is why would OS would like to set the java specific properties in environment variables? Ideally these should be set by JVM (in System.properties()).
P.S.: From whatever i have read on net i understand that environment variables are set by OS and System.properties() are set by JVM
Also if someone can point me to a good link on environment variable and System.properties it will be very helpful. Iam very confused between the two.

A: Environment variables is an OS concept, and are passed by the program that starts your Java program.
That is usually the OS, e.g. double-click in an explorer window or running command in a command prompt, so you get the OS-managed list of environment variables.
If another program starts your Java program1, e.g. an IDE (Eclipse, IntelliJ, NetBeans, ...) or a build tool (Maven, Groovy, ...), it can modify the list of environment variables, usually by adding more. E.g. the environment variable named MAVEN_CMD_LINE_ARGS would tend to indicate that you might be running your program with Maven.
In a running Java program, the list of environment variables cannot be modified.

System properties is a Java concept. The JVM will automatically assign a lot of
system properties on startup.
You can add/override the values on startup by using the -D command-line argument.
In a running Java program, the list of system properties can be modified by the program itself, though that is generally a bad idea.

1) For reference, if a Java program wants to start another Java program, it will generally use a ProcessBuilder to set that up. The environment variables of the new Java process will by default be the same as the current Java program, but can be modified for the new Java program by calling the environment() method of the builder.


Q: "stripeErr : Error: You cannot accept payments using this API as it is no longer supported in India I got this error while using stripe, on 23 feb 2022

A: Check your account. You should provide a valid IEC export code to accept any payment.

A: As per latest RBI guidelines, Stripe has switched from Charges API to Payment Intent API. Use below API as per data :
Stripe::PaymentIntent.create(
  :customer => customer.id,
  :amount => params[:amount],
  :description => 'Rails Stripe transaction',
  :currency => 'usd',
)

It worked for me. Checkout Stripe API documentation here

A: you need to change "charges" to "paymentIntents"
example:
const payment  = await stripe.charges.create(  //Change here
  {
    amount: subTotal * 100,
    currency: "inr",
    customer: customer.id,
    receipt_email: token.email,
  },
  {
    idempotencyKey: uuidv4(),
  }
);


Q: Tech-stack for querying and alerting on GB scale (streaming and at rest) datasets Trying to scope out a project that involves data ingestion and analytics, and could use some advice on tooling and software.
We have sensors creating records with 2-3 fields, each one producing ~200 records per second (~2kb/second) and will send them off to a remote server once per minute resulting in about ~18 mil records and 200MB of data per day per sensor. Not sure how many sensors we will need but it will likely start off in the single digits.
We need to be able to take action (alert) on recent data (not sure the time period guessing less than 1 day), as well as run queries on the past data. We'd like something that scales and is relatively stable .
Was thinking about using elastic search (then maybe use x-pack or sentinl for alerting). Thought about Postgres as well. Kafka and Hadoop are definitely overkill. We're on AWS so we have access to tools like kinesis as well.
Question is, what would be an appropriate set of software / architecture for the job?

A: Have you talked to your AWS Solutions Architect about the use case? They love this kind of thing, they'll be happy to help you figure out the right architecture. It may be a good fit for the AWS IoT services?
If you don't go with the managed IoT services, you'll want to push the messages to a scalable queue like Kafka or Kinesis (IMO, if you are processing 18M * 5 sensors = 90M events per day, that's >1000 events per second. Kafka is not overkill here; a lot of other stacks would be under-kill).
From Kinesis you then flow the data into a faster stack for analytics / querying, such as HBase, Cassandra, Druid or ElasticSearch, depending on your team's preferences. Some would say that this is time series data so you should use a time series database such as InfluxDB; but again, it's up to you. Just make sure it's a database that performs well (and behaves itself!) when subjected to a steady load of 1000 writes per second. I would not recommend using a RDBMS for that, not even Postgres. The ones mentioned above should all handle it.
Also, don't forget to flow your messages from Kinesis to S3 for safe keeping, even if you don't intend to keep the messages forever (just set a lifecycle rule to delete old data from the bucket if that's the case). After all, this is big data and the rule is "everything breaks, all the time". If your analytical stack crashes you probably don't want to lose the data entirely.
As for alerting, it depends 1) what stack you choose for the analytical part, and 2) what kinds of triggers you want to use. From your description I'm guessing you'll soon end up wanting to build more advanced triggers, such as machine learning models for anomaly detection, and for that you may want something that doesn't poll the analytical stack but rather consumes events straight out of Kinesis.


Q: cosine and sine value of large numbers VHDl I want to implement a CPM modulation in VHDL and my device is Spartan 3A DSP. After the mathematical operation the provided data is the argument for a trigonometric functions and i'm trying to use CORDIC IP CORE in Xilinx 14.7 for this and the problem is that the input data for CORDIC must place between -pi to pi and i don't know how to do this that it could be synthetizable! for now i'm trying to implement the modulation in base band and only the cosine and sine value of the provided data should be send. for example i need the value of "cosine(234.56)" but i don't know how to do it!! i would appreciate if anyone could help me on this.


Q: Mysql2 Error - using COALESCE, Unknown column in where clause In my Rails 4.1 Application, I'm building a query to find records in my collection (orders) by an attribute (name) of a polymorphic relationship (buyer). There are 2 possible tables for that polymorphic, so I'm using 2 LEFT JOINS + COALESCE to merge the attributes. Then attempting use the value from the COALESCE in a where clause.
The method in my ActiveRecord model looks like this:
class Order
  ...
  scope :join_by_buyer_name, -> { select("stock_orders.*", "COALESCE(core_customers.business_name, core_entities.name) AS buyer_name")
      .joins("LEFT JOIN core_customers ON stock_orders.buyer_id = core_customers.id AND stock_orders.buyer_type='Core::Customer'")
      .joins("LEFT JOIN core_entities ON stock_orders.buyer_id = core_entities.id AND stock_orders.buyer_type='Core::Entity'")
    }
  ...

  def find_by_buyer_name(term)
    all.join_by_buyer_name.where("buyer_name LIKE ?", term)
  end

end

When the ActiveRecord query is executed it looks like this
SELECT stock_orders.*, COALESCE(core_customers.business_name, core_entities.name) AS buyer_name
FROM `stock_orders`
LEFT JOIN core_customers ON stock_orders.buyer_id = core_customers.id AND stock_orders.buyer_type='Core::Customer'
LEFT JOIN core_entities ON stock_orders.buyer_id = core_entities.id AND stock_orders.buyer_type='Core::Entity'
WHERE `stock_orders`.`type` IN ('Stock::SalesOrder') AND (buyer_name LIKE "blah")

Until recently this worked, However I've started receiving the following error:
Mysql2::Error: Unknown column 'buyer_name' in 'where clause': SELECT stock_orders.*, COALESCE etc etc etc
It works perfectly for sorting by the COALESCE value - ie collection.order("buyer_name asc") and up until recently the where query worked perfectly too...
I'm not sure what has changed and can't see anything in Rails or Mysql documentation. Can you see what's wrong here? Please help!

A: You cannot use the ALIAS in WHERE clause that is created from the SELECT clause. Use the computed column instead,
AND (COALESCE(core_customers.business_name, core_entities.name) LIKE "blah")

if you want to use the ALIAS, you have to wrap it in subquery like the query below,
SELECT *
FROM
     (
     SELECT stock_orders.*,
           COALESCE(core_customers.business_name, core_entities.name) AS buyer_name
     FROM `stock_orders`
          LEFT JOIN core_customers
                ON stock_orders.buyer_id = core_customers.id
                     AND stock_orders.buyer_type='Core::Customer'
          LEFT JOIN core_entities
                     ON stock_orders.buyer_id = core_entities.id
                     AND stock_orders.buyer_type='Core::Entity'
     ) subquery
WHERE `type` IN ('Stock::SalesOrder')
      AND (buyer_name LIKE "blah")


Q: How can send array as an data using ajax Please see attached jsfiddle link, I need to collect data from multiple forms and combined the data as Single data array send it to server(spring mvc controller) to persist using ajax.post
Please let me know best way to do it, will my array be converted to Json by ajax call or I have to do some magic on it.
Thanks
http://jsfiddle.net/6jzwR/1/
<form id="form1" name="formone" class="myclass">
    <input type="text" id="txt11" name="txt11" value="name1" />
    <input type="text" id="txt12" name="txt12" value="name2" />
</form>
<form id="form1" name="formtwo" class="myclass">
    <input type="text" id="txt21" name="txt21" value="name3" />
    <input type="text" id="txt22" name="txt22" value="name4" />
</form>
<input type="button" id="button" value="Click Me" />

(function ($) {
    $(document).ready(function () {
        alert("serialize data :" + $('.myclass').length);
        var mydata = null;
        $('#button').on('click', function (e) {

            $('.myclass').each(function () {
                alert("serialize data :" + $(this).serialize());
                if ((mydata === null) || (mydata === undefined)) {
                    mydata = $(this).serializeArray();
                    alert("My data is null");
                } else {
                    mydata = $.merge(mydata, $(this).serializeArray());
                    alert("My data final data after merger " + test);
                }
            });

        });
    });
}(jQuery));

A: Try this:
var array = $('input[type="text"]').map(function() {
    return $(this).val();
}).get();

alert(JSON.stringify(array));

Demo.

A: You can put all the forms' data in an array and join them with &
var formdata = []
$('.myclass').each(function(){
    formdata.push($(this).serialize());
});
var data = formdata.join('&');

http://jsfiddle.net/6jzwR/3/


Q: Two sources of water filling tank suppose that we have two different sources of water. one is filling the tank full with 90 min and the other one is filling it up in 30 min. If we combined the two sources together, then how many minutes will take to fill the same tank ?
I found this question in a child book. I tries to solve it out and I found the most logical answer is 27,7 while 100/3=3.3 so 30-3.3=27.7
is this solution right ? others says it is 22,5 min. Can anyone relate?

A: The part filled by tap $A $ in one minute $=\frac{1}{90} $.
The part filled by tap $B $ in one minute $=\frac {1}{30}$.
The part filled by taps $(A+B) $ in one minute $=(\frac {1}{90}+\frac {1}{30}) =\frac {4}{90} = \frac {1}{22.5} $.
Thus both pipes can fill in $22.5$ minutes. Hope it helps.

A: Let us illustrate this information on a table:
    \begin{array}{| l | l | l | l |}
\hline
\textbf{Water Source} & \textbf{Time taken to fill} & \textbf{Amount of water filled} & \textbf{Rate of filling/minute} \\ \hline
\text{Source 1} & 90 \text{ mins} & x & \frac{x}{90} \\ \hline
\text{Source 2} & 30 \text{ mins} & x & \frac{x}{30} \\ \hline
\text{Combined} & ? & x & \frac{x}{90}+\frac{x}{30} \\
\hline
\end{array}
The rate of filling per minute is taken by dividing the amount of water filled by the time taken to fill the tank.
Which is: $$\text{Rate}=\frac{\text{Amount}}{\text{Time}}$$
This can be rearranged to give the time taken to fill:
$$\text{Time}=\frac{\text{Amount}}{\text{Rate}}$$
For the Combined sources, we just simply substitute these values:
$$\text{Time}=\frac{x}{\left(\frac{x}{90}+\frac{x}{30}\right)}$$
$$\text{Time}=\frac{x}{\left(\frac{x}{90}+\frac{3x}{90}\right)}$$
$$\text{Time}=\frac{90x}{4x}$$
The $x$'s cancel, and give:
$$\boxed{\text{Time}=22.5 \text{ mins}}$$

A: OK, so in the comments you explain your reasoning as:

So in 90 min the tank will be filled by source B. thats means in the first 30 min of source B will be filling the tank 1/3 of the whole amount of the 100% tank right ? that's why I divided 100 over 3 to get the percentage of filling in the first 30 min of 90 min. After that, I subtract the 3,3 from the fast 30 min filling of source A

Where is your reasoning mistake?
OK, first your basic arithmetic is a bit off: 100 over 3 is 33.3, not 3.3. That is, if we use source B alone, then the percentage of the tank that would be filled after 30 minutes is 33.3%, not 3.3%. So, you are right that it is 1/3, but 1/3 of 100% is 33.3%.
OK, but now you make a second, and much more serious mistake: you subtract this percentage from the time (30 minutes) it takes for source A to fill the tank. But notice how these are completely different kinds of quantities!  And you cannot use basic arithmetic when you are talking about different kinds of units or measurements. For example, you might just as well have subtracted 1/3 from 30 .. and that would equally have been a mistake: you are comparing apples and oranges!
Hope that helps!