text:
Q: Laravel Cashier - Unit Tests with creating subscriptions with payment methods Looking deeper into this, I'm not sure it's even possible, which is a shame because I'm trying to learn TDD.
I would like to test my model with Billable being created and subscribed to a plan.
/** @test */
public function an_account_can_subscribe_to_a_plan() {
    $account = factory("App\Account")->create();

    Stripe::setApiKey('key');
    $paymentMethod = PaymentMethod::create([
        'type' => 'card',
        'card' => [
            'number' => '4242424242424242',
            'exp_month' => '2',
            'exp_year' => '2021',
            'cvc' => '314'
        ]
    ]);

    $subscription = $account->newSubscription('default', 'starter')->create($paymentMethod);
    $this->assertTrue( $subscription->valid() );
}

The Laravel Cashier docs show how to send a token via Stripe.js, but that doesn't work for Unit Testing.
I've tried to include the Stripe library directly and create a PaymentMethod object, but this also requires me set an API key manually. Now the error I'm getting is that I have to verify my phone number to send raw credit card numbers to the stripe API.
I'm hoping there's a better way. How can I use Laravel Cashier in a TDD way and mock up fake subscriptions with fake payment methods?

A: Stripe provides not only test card numbers, but tokens and payment method's.
https://stripe.com/docs/testing#cards
Click the PaymentMethods tab. The value (for example pm_card_visa) can be used directly on the server-side in your tests without the need of front-end payment-intent implementation.
This is an example of a feature test I have:
    /**
     * @test
     */
    public function a_user_can_subscribe_to_a_paid_plan()
    {

        $this->actingAs($this->user);
        $this->setUpBilling();

        $enterprise = Plan::where('name', 'Enterprise')->first()->stripe_plan_id;

        $response = $this->post(route('paywall.payment'), [
            'payment_method' => 'pm_card_visa',
            'stripe_plan_id' => $enterprise
        ])
        ->assertSessionDoesntHaveErrors()
        ->assertRedirect();

    }

Your tests may vary, but you can make a normal request to your billing controller with these test payment methods and it goes through just as it would if you do it on the front-end.

A: You may want to use stripe-mock for mocking during tests. If that doesn't fit your needs, mocking the objects directly may be a better option.


text:
Q: Shortest path crossing unique x points Given a set of Y Points (locations) with Longitude and Latitude, what is the shortest path that crosses a Unique set of X points?
Just a algorithm problem I was having when designing a database. Not sure how to proceed or if there is an elegant solution to this problem. Please help! Thanks!
Edit: This is not the Travelling Salesmen Problem, it is not the shortest path visiting ALL the locations, but just any unique set that crosses X points.
For example, if we had 2000 locations, what's the shortest path that will visit any 10 locations?
The size of X will be very small compared to the overall set of Y.

A: I would put my data into an R* Tree then run a DBSCAN algorithm over it to break it down into clusters O(n * lg(n)). Once the points have been clustered you can then find the cluster that's closest in size to the number of points you want to find the shortest path between. Since you've broken everything down to just 10 points you have two options you can either: Solve the Traveling Salesman Problem for the points which is slow O(n!) and precise, or take the leftmost point and get the shortest path to the rightmost point using Dijkstra's algorithm which is much faster O(E + V * log(V)) but doesn't give you the optimal result.
EDIT!
As pointed out in the comments below using Dijkstra's algorithm here would result in O(n!+V * log(V)) since any path between two points is an edge. It would be faster to use the Held–Karp algorithm to solve the TSP which runs O(n^2 * 2^n)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to validate Shift+tab Button click in Js? Current Scenario is, For a textbox need to verify if Shift+tab is pressed then Js function should return True.
Tried with
event.shiftKey && event.keyCode == 9 But no luck.
Issue is While pressing Shift+Tab, We do press Shift 1st then Tab in sequence. Thus while pressing Shift (keycode is 16), so this condition is failing. Please help me how to check both key press at a time?


text:
Q: How to access the injected service in my formHandler? I'm trying to use the ewz_search.lucene service in my (FOSUserBundle) profileFormHandler.
I've injected the ewz_search.lucene service into the formHandler service like so:
application_sonata_user.form.handler.profile:
    class: Application\Sonata\UserBundle\Form\Handler\ProfileFormHandler
    arguments: ["@fos_user.profile.form", "@request", "@fos_user.user_manager", "@ewz_search.lucene"]
    scope: request
    public: false

I'd like to access this service in the handler so I can add an index to the username field
I've tried something like $this->lucene->updateIndex(), but it doesn't know the property $lucene.
References:
https://github.com/excelwebzone/EWZSearchBundle
http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services


text:
Q: Feature combination/joint features in supervised learning While trying to come up with appropriate features for a supervised learning problem I had the following idea and wondered if it makes sense and if so, how to algorithmically formulate it.
In an image I want to classify two regions, i.e. two "types" of pixels. Say I have some bounded structure, let's take a circle, and I know I can limit my search space to this circle. Within that circle I want to find a segmenting contour, i.e. a contour that separates my pixels into an inner class A and an outer class B.
I want to implement the following model:
I know that pixels close to the bounding circle are more likely to be in the outer class B.
Of course, I can use the distance from the bounding circle as a feature, then the algorithm would learn the average distance of the inner contour from the bounding circle.
But: I wonder if I can exploit my model assumption in a smarter way. One heuristic idea would be to weigh other features by this distance, so to say, if a pixel further away from the bounding circle wants to belong to the outer class B, it has to have strongly convincing other features.
This leads to a general question:
How can one exploit joint information of features, that were prior individually learned by the algorithm?
And to a specific question:
In my outlined setup, does my heuristic idea make sense? At what point of the algorithm should this information be used? What would be recommended literature or what would be buzzwords if I wanted to search for similar ideas in the literature?

A:
This leads to a general question:
How can one exploit joint information of features, that were prior individually learned by the algorithm?

It is not really clear what you are really asking here. What do you mean by "individually learned by the algorithm" and what would be "joiint information"? First of all, problem is too broad, there is no such tring as "generic supervised learning model", each of them works in at least slightly different way, most falling into three classes:

*

*Building a regression model of some kind, to map input data to the output and then agregate results for classification (linear regression, artificial neural networks)

*Building geometrical separation of data (like support vector machines, classification-soms' etc.)

*Directly (more or less) estimating probability of given classes (like Naive Bayes, classification restricted boltzmann machines etc.)

in each of them, there is somehow encoded "joint information" regarding features - the classification function is their joint information. In some cases it is easy do interpret (linear regression) and in some it is almost impossible (deep boltzmann machines, generally all deep architectures).

And to a specific question:
In my outlined setup, does my heuristic idea make sense? At what point of the algorithm should this information be used? What would be recommended literature or what would be buzzwords if I wanted to search for similar ideas in the literature?

To my best knowledge this concept is quite doubtfull. Many models tends to learn and work better, if your data is uncorrelated, while you are trying to do the opposite - correlate everything with some particular feature. This leads to one main concern - why are you doing this? To force model to use mainly this feature?

*

*If it is so important - maybe a supervised learning is not the good idea, maybe you can directly model your problem by appling set of simple rules based on this particular feature?

*If you know the feature is important, but you are aware that in some cases other things matter, and you cannot model them, then your problem will be how much to weight your feature. Should it be just distance*other_feature? Why not sqrt(distance)*feature? What about log(distance)*feature? There are countless possibilities, and seek for the best weighting scheme may be much more costfull, then finding a better machine learning model, which can learn your data from its raw features.

*If you only suspect the importance of the feature, the best possible option would be to... do not trust this belief. Numerous studies have shown, that machine learning models are better in selecting features then humans. In fact, this is the whole point of non-linear models.

In literature, problem they you are trying to solve is generally refered as incorporating expert knowledge into the learning process. There are thousands of examples, where there is some kind of knowledge that cannot be directly encoded in data representation, yet too valuable to omit it. You should research terms like "machine learning expert knowledge", and its possible synomyms.

A: There's a fair amount of work treating the kind of problem you're looking at (which is called segmentation) as an optimisation to be performed on a Markov Random Field, which can be solved by graph theoretic methods like GraphCut. Some examples are the work of Pushmeet Kohli at Microsoft Research (try this paper).
What you describe is, in that framework, a prior on node membership, where p(B) is inversely proportional to the distance from the edge (in addition to any other connectivity constraints you want to impose, there's normally a connectedness one, and there will certainly be a likelihood term for the pixel's intensity). The advantage of doing this is that if you can express everything as a probability model, you don't need to rely on heuristics and you can use standard mechanisms for performing inference.
The downside is you need a fairly strong mathematical background to attempt this; I don't know what the scale of the project you're proposing is, but if you want results quickly or you're lacking the necessary background this is going to be pretty daunting.


text:
Q: Display random text from a file with the WP built-in AJAX API I want to use a solution by @toscho to display and rotate some quotes. The unchanged code works very well, but if I replace the
protected function get_rand()
{
    return rand( 1, 1000 );
}

with (from here)
protected function get_rand()
{
    $array = file("wp-content/plugins/quotes-rotator/quotes.txt");
    $r = rand(0,count($array)-1);
    return $array[rand(0,count($array)-1)];
}

the code works well only at the first page load, but when I press the 'New' button to display a new quote the system outputs an error:

Warning: file(wp-content/plugins/quotes-rotator/quotes.txt): failed to
  open stream: No such file or directory in
  /var/www/.../public_html/wp-content/plugins/quotes-rotator/ajax-shortcode-demo.php
  on line 106

What is wrong here?

A: to have the good path to the file, try this :
$array = file(plugin_dir_path(__FILE__) . "quotes.txt");


text:
Q: Rails 3. Get totals from array I'm printing out a table with line totals but I also want to get the grand total of the columns. This following code doesn't work, instead of the grand totals it just prints out the values of the last iteration.
<% @shipments.each do |shipment| %>

    <%= shipment.file_number %>
    <%= shipment.shipper.company_name %>
    <%= shipment.hbl %>
    <%= shipment.status %>
    <%= shipment.age %>
    <%= shipment.invoice.read_issued_at unless shipment.invoice.nil? %>
    <%= number_to_currency shipment.invoice.customer_total unless shipment.invoice.nil? %>
    <%= number_to_currency shipment.invoice.customer_amount_paid unless shipment.invoice.nil? %>
    <%= number_to_currency shipment.invoice.customer_open_balance unless shipment.invoice.nil? %>

  <%
  grand_customer_total = 0
  grand_customer_amount_paid = 0
  grand_customer_open_balance = 0
  grand_customer_total += shipment.invoice.customer_total
  grand_customer_amount_paid += shipment.invoice.customer_amount_paid
  grand_customer_open_balance += shipment.invoice.customer_open_balance
  %>
  <% if @shipments.last == shipment %>

    Totals
    <%= number_to_currency grand_customer_total %>
    <%= number_to_currency grand_customer_amount_paid %>
    <%= number_to_currency grand_customer_open_balance %>

  <% end %>

A: You set the grand total to zero every time through the loop. move the initialization up before the loop.

A: The reason your code isn't working is that your variables are defined in the block, so they're considered block-local variables. Once the block is exited those variables are marked to be cleared; each iteration re-defines those variables. It also doesn't help that you're reassigning them to 0 on each iteration, but that isn't even coming into effect here because the variables aren't defined each time through.
You could simply define the variables before the block, but that's still pretty messy. Since Ruby idioms and conventions put an emphasis on clean and well-organized code, I'd stray away from that and instead calculate these numbers separately, possibly in your controller.
@totals = {
  :overall => @shipments.reduce(0) { |total, shipment| total + shipment.invoice.customer_total },
  :paid => @shipments.reduce(0) { |total, shipment| total + shipment.invoice.customer_amount_paid },
  :balance => @shipments.reduce(0) { |total, shipment| total + shipment.invoice.customer_open_balance }
}

Then, instead of using @shipments.last comparison, you can just do the following after your shipments table output:

  Totals
  <%= number_to_currency @totals[:overall] %>
  <%= number_to_currency @totals[:paid] %>
  <%= number_to_currency @totals[:balance] %>

A: you can use ruby inject
something like
@shipments.inject(0) { |sum, shipment| sum + shipment.invoice.customer_total }

or to keep with your code layout, just initialize the grand_customer_* objects outside of the @shipments.each loop because you are resetting them every time through

A: <%
grand_customer_total = 0
grand_customer_amount_paid = 0
grand_customer_open_balance = 0
%>
<% @shipments.each do |shipment| %>

  <%= shipment.file_number %>
  <%= shipment.shipper.company_name %>
  <%= shipment.hbl %>
  <%= shipment.status %>
  <%= shipment.age %>
  <%= shipment.invoice.read_issued_at unless shipment.invoice.nil? %>
  <%= number_to_currency shipment.invoice.customer_total unless shipment.invoice.nil? %>
  <%= number_to_currency shipment.invoice.customer_amount_paid unless shipment.invoice.nil? %>
  <%= number_to_currency shipment.invoice.customer_open_balance unless shipment.invoice.nil? %>

<%
grand_customer_total += shipment.invoice.customer_total
grand_customer_amount_paid += shipment.invoice.customer_amount_paid
grand_customer_open_balance += shipment.invoice.customer_open_balance
%>
<% if @shipments.last == shipment %>

  Totals
  <%= number_to_currency grand_customer_total %>
  <%= number_to_currency grand_customer_amount_paid %>
  <%= number_to_currency grand_customer_open_balance %>

<% end %>


text:
Q: how to cut a csv as parts for a condition I have a CSV which has the follwing data
time     t_count       state       hour
_____    ________      _____      _____
  1        10            2          1
  2        12            2          1
  3        30            2          1
  4        12            2          1
  1        9             3          1
  2        18            3          1
  6        27            3          1
  1        18            4          1
  2        30            4          1
  9        27            4          1
.......................................
......................................
  2        30            2          2
  8        18            2          2
  3        36            2          2
  3        6             3          2
  6        19            3          2
  8        28            3          2
  1        19            4          2
  2        36            4          2
  9        30            4          2
.....................................
.....................................
....................................

Likewise I have time and t_count for each state and each hour.I have state form 2 to 99 and hour from 1 to 23.So I need to split this CSV into  each CSV for each state and each hour as
 state_2_hour_1.csv
  1        10            2          1
  2        12            2          1
  3        30            2          1
  4        12            2          1

 state_3_hour_1.csv

  1        9             3          1
  2        18            3          1
  6        27            3          1

...
state_2_hour_2.csv
      2        30            2          2
      8        18            2          2
      3        36            2          2

and so on.

A: try this awk command.
awk 'NR>2{filename="state_"$3"_hour_"$NF".csv"; print $0 > filename}' input.csv


text:
Q: Why is "unsigned" mapped to a 32 bits in MSVC C++? I have the following structure defined in MSVC++ 2008:
struct{
 Uint16  XDD;
 unsigned XDD_UI:8;
 unsigned XDD_CR:8;
}byte;

When doing sizeof on the above structure it shows that unsigned uses 32 bits to store the data.

*

*Why is that, does it has something to do with memory alignment ?

*And how could I force the compiler to use only 8 bits as defined without
touching the struct definition ?

A: When you write unsigned, that is short for unsigned int, which is 32 bits wide on Windows. That means that it has alignment of 4. And since your struct is aligned, there are two bytes padding between XDD and XDD_UI, and two bytes padding at the end of the struct.
Your struct is laid out like this:

0-1  XDD
2-3  <padding>
4-4  XDD_UI
5-5  XDD_CR
6-7  <padding>

If you want the struct to be packed then you need to pack it. Use #pragma pack to achieve that. However, even if you do that, the compiler produces a struct with size 6. That's because the bitfields are packed into an unsigned int and so your two bitfields will always consume 4 bytes.
If you made sure that your bitfields were declared as being of a type whose size was no larger than 2 bytes, then your struct would be 4 bytes. And that would be true for an aligned struct. For instance, this struct has size 4.
struct s {
    unsigned short XDD;
    unsigned short XDD_UI:8;
    unsigned short XDD_CR:8;
};

However, it would be seem to me to be more sensible to declare your struct without bitfields:
struct s {
    Uint16 XDD;
    unsigned char XDD_UI;
    unsigned char XDD_CR;
};

You can declare that struct aligned and have the layout that you desire.

A: And how could I force the compiler to use only 8 bits as defined without touching the struct definition

Use #pragma
#pragma pack(1)
struct{
 Uint16  XDD;
 unsigned XDD_UI:8;
 unsigned XDD_CR:8;
}byte;
#pragma pack()

A: Depending on compiler and machine  unsigned could be 64 bit too. Since previously processors were 32 bit so it became common norm to use 32 bit for an int. But we should not rely on int or unsigned to determine it range always.
A char or unsgined char is sure way to using 8 bits. But internally compiler may have made adjustments it to be used as 4 byte for processing.


text:
Q: CORS on Azure Web App returning error: No 'Access-Control-Allow-Origin I have an Azure static web app running my frontend and an Azure web app running my backend. I've been using this app for a couple of months. Today, after deploying some changes, my backend has been responding with CORS errors. Specifically, the error is:

Access to XMLHttpRequest at 'https://memoriesforusbe.azurewebsites.net/auth?userEmail=xxxxxxxxxxxxxxx&userPassword=xxxxxxxxxxxxx' from origin 'https://www.memoriesforus.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

UPDATE: I did some more testing this morning and have found that the response is different depending on the user. This makes NO sense to me that a CORS response is based on the data being sent in? More confused than before.
The headers that I had in my node.js server file were:
res.header("Access-Control-Allow-Origin", "https://login.memoriesforus.com");
res.header("Access-Control-Allow-Origin", "https://www.memoriesforus.com");

To try to fix it, I added the following in hopes the wildcard might help.
res.header("Access-Control-Allow-Origin", "https://*.memoriesforus.com");
res.header("Access-Control-Allow-Origin", "https://memoriesforus.com");

I also noticed that Azure Web Apps has a blade for CORS. I tried adding my headers there and had the same result.
The error occurred on the login screen of the app. I have a couple of apis that don't require the user to be logged in or use tokens. So I tried those and they seem to be working. So I'm thinking it may have something to do with that?
I'm just very confused because the original request headers worked for so long. Is there something else I should be looking at that might cause this error? The changes I made in the backend were unrelated to CORS. Not sure if something changed on the app service? I also uploaded changes to the frontend. But the call to the api that is getting the error was also unchanged.
The whole CORS related section of the node.js server file currently looks like this:
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "https://login.memoriesforus.com");
  res.header("Access-Control-Allow-Origin", "https://www.memoriesforus.com");
  res.header("Access-Control-Allow-Origin", "https://*.memoriesforus.com");
  res.header("Access-Control-Allow-Origin", "https://memoriesforus.com");
  res.header("Access-Control-Allow-Origin", "https://salmon-plant-09df42110.2.azurestaticapps.net"); //the auto generated name of the frontend on Azure

  if(process.env.SERVER_STATUS === 'Dev' ) {
    res.header("Access-Control-Allow-Origin", "*");   }
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    if (req.method === "OPTIONS") {
      res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
      return res.status(200).json({});
    }
    next();
});

A: *

*You may have zero or one Access-Control-Allow-Origin headers. You can't have two or more.

*The * character is a special value meaning "any origin", it isn't a placeholder that can be included in the allowed origin as a wildcard for part of the origin.

To allow multiple, but not all, origins you need to:

*

*Read the Origin request header

*Compare it to whatever rules you care to write to see if it is an allowed origin

*Include res.header("Access-Control-Allow-Origin", the_origin_request_header_value); if it is one

You appear to be using Express, if so the cors module will handle this for you (and allow you to specify valid origins as a list, a regular expression, or a custom function).

A: I found this article which ended with the problem being the data. So I created a new user and tried with that user. The api works fine. So I will close this question and work on why my data is giving a CORS error. Never occurred to me that it could be the data itself.


text:
Q: Error creating new Meteor APP in Windows 8.1: future.js:398:15 I've been working in Meteor for some weeks, creating some applications to test it and assure that everything works fine before adopting it for the company. Yesterday I created and Meteor application in my Windows 8.1 with no problem, but today with no apparent change on my system, when I do any "meteor create [x]" or even "meteor update" it crashes:
Error: ENOENT, open 'C:\Users[user]\AppData\Local.meteor\packages\meteor-tool\1.1.4\os.json' at Object.Future.wait (C:\Users[user]\AppData\Local.meteor\packages\meteor-tool\1.1.3\mt-os.windows.x8632\d ev_bundle\lib\node_modules\fibers\future.js:398:15) at Object.wrapper [as readFile] (C:\Users[user]\AppData\Local.meteor\packages\meteor-tool\1.1.3\mt-os.window s.x86_32\tools\files.js:1350:24) at C:\Users[user]\AppData\Local.meteor\packages\meteor-tool\1.1.3\mt-os.windows.x86_32\tools\isopack.js:693: 15 at Array.forEach (native) at Function..each..forEach (C:\Users[user]\AppData\Local.meteor\packages\meteor-tool\1.1.3\mt-os.windows.x 86_32\dev_bundle\lib\node_modules\underscore\underscore.js:79:11) at [object Object]..extend.loadUnibuildsFromPath (C:\Users[user]\AppData\Local.meteor\packages\meteor-tool \1.1.3\mt-os.windows.x86_32\tools\isopack.js:680:7) at [object Object]..extend.initFromPath (C:\Users[user]\AppData\Local.meteor\packages\meteor-tool\1.1.3\mt- os.windows.x86_32\tools\isopack.js:606:17) at springboard (C:\Users[user]\AppData\Local.meteor\packages\meteor-tool\1.1.3\mt-os.windows.x86_32\tools\ma in.js:458:15) at C:\Users[user]\AppData\Local.meteor\packages\meteor-tool\1.1.3\mt-os.windows.x86_32\tools\main.js:1023:5
If I try to run my previous applications It works fine, but it do not allow me to create new apps.

A: OK, that one was hard!
Uninstalling meteor and installing it again allowed Meteor to work.
After that, installing the pluigins of my project moved it to the same state.
I've found that the problem was that I was using PowerShell instead of "cmd".
The right procedure to make it work was:

*

*Uninstall Meteor

*Install it again

*Go to the app folder (in cmd as admin) and do meteor update

*Then meteor (and in my case add some packages because of changes of dependences in versions).

*All running OK

If you do the same thing with PowerShell step 3 (or 4 before 3) makes meteor stop working.

A: You are trying to install on a drive that either has no space, or has no permission to write. Meteor run as Admin and/or check for disk space. Reference.
Using Google Translate.

A: I've seen something similar and ended up being a permission related issue.  To confirm that it is indeed permission related, try to open the command line as an Administrator and do the update and see if you have the same problem.
If that does solve the issue, check the permission for C:\Users[user]\AppData\Local.meteor\packages\meteor-tool and see if it is accessible by the user you are logged in as.


text:
Q: Can I respond with XML to an HTML request in Rails? I want to put in a simple API that responds to a GET request with a query string. But I want to return XML, not HTML.
I would even like to test this in the browser so that if I key in the URL and the query string, then see the XML in the response.
I just about have it by rendering :text, but my xml is doing two things:
1. All tag names are being downcased.

2. My xml is being wrapped in an HTML container (HTML, HEAD, BODY, etc.)

I just need to get rid of that HTML wrapper.

A: This one works for me:
respond_to do |format|
  format.xml do
    headers['Content-Disposition'] = 'attachment;filename="katalog.xml"'
    render :xml => xml_array.to_xml(:skip_types => true, :root => "Items"),
           :layout => false,
           :content_type => Mime::XML
  end
end

You should be able to replace xml_array.to_xml(:skip_types => true, :root => "Items") with your string, since .to_xml doesn't do anything else but generating a string (and making sure it's proper XML)

A: You could simply render as xml (in your controller) with:
render xml: @your_object

A: layout false, only: [:action]
This will remove all layout associated code.

A: On rails 5.2.x this is how you do it
class UserController < ApplicationController
  def view
    @user = User.find(params[:id])
    render formats: [:xml]
  end
end

With its corresponding view on app/views/user/view.xml
xml.User do
  xml.name @user.name
end


text:
Q: Is this the right way to import gsap in vue.js (it works but is it the "right" way?) I'm quite new to Vue.js and have had some problems getting libraries to work without getting the "error  'X' is not defined  no-undef" message.
In this case it is 'Back' that is not defined (which is a part of GSAP)
I figured the only place to "define" Back would be in the import.
Is this just the way to import libraries?
Do I have to write every undefined part in the import like this?
It works but it just seems unnecessary.

<template>

This is the MainTemplaye.vue Component

</template>

A: I'm not sure where you're learning from, but you're using the old syntax of GSAP. If you use the new syntax of GSAP you don't have to import anything other than gsap in your case:
import { gsap } from "gsap";

export default {
  name: "MainTemplate",
  mounted() {
    const { box } = this.$refs;
    const timeline = gsap.timeline();

    timeline.to(box, { duration: 1, x: 200, rotation: 90, ease: 'back.inOut' })
    timeline.to(box, { background: 'green' }, '-=0.5')
  },
};

The best place to start learning is the official GSAP Getting Started article.


text:
Q: How to make poisson noise from uniform random numbers using central limit theorem? Using the fact that Gaussian(λ=σ) is an approximation of Poisson(λ), I want to compute an approximation of Poisson noise using only uniform random numbers without using factorials.
There are two things I have no clue.

*

*How to approximate gaussian noise from uniform noise.

*How to approximate Poisson noise with Gaussian noise when λ is small.


text:
Q: Is there a limit in Android on number of email address from contacts that I can fetch? I am making an Android app where when a user starts typing email address, he gets autocomplete suggestions from his phone contact book.
If I put a limit on my code to fetch only 100 address, it works perfectly fine. If I don't put any limit, the app freezes. I haven't tried to put a higher limit and see and what point it gives up.
How can I optimize my code?
    private ArrayList<String> getNameEmailDetails() {
    ArrayList<String> emlRecs = new ArrayList<String>();
    **int count = 0;** // THIS IS ADDITIONAL

    HashSet<String> emlRecsHS = new HashSet<String>();
    Context context = getBaseContext();
    ContentResolver cr = context.getContentResolver();
    String[] PROJECTION = new String[] { ContactsContract.RawContacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.Contacts.PHOTO_ID,
            ContactsContract.CommonDataKinds.Email.DATA,
            ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
    String order = "CASE WHEN "
            + ContactsContract.Contacts.DISPLAY_NAME
            + " NOT LIKE '%@%' THEN 1 ELSE 2 END, "
            + ContactsContract.Contacts.DISPLAY_NAME
            + ", "
            + ContactsContract.CommonDataKinds.Email.DATA
            + " COLLATE NOCASE";
    String filter = ContactsContract.CommonDataKinds.Email.DATA + " NOT LIKE ''";
    Cursor cur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION, filter, null, order);
    if (cur.moveToFirst()) {
        do {
            String emlAddr = cur.getString(3);

            // keep unique only
            if (emlRecsHS.add(emlAddr.toLowerCase())) {
                emlRecs.add(emlAddr);
                **count++;** // THIS IS ADDITIONAL
            }
        } while (cur.moveToNext() **&& count < 100**);
    }

    cur.close();
    return emlRecs;
}

A: Your app "freezes" because you are performing long-running or complicated calculations on the UI Thread. This is the Thread responsible for drawing your app's views and responding to user input.
You should move requests like this (as with all network activity) to another thread to keep your app from becoming unresponsive.
Look into Threads or AsyncTask to address these restrictions.


text:
Q: mysql update (i want to change the string last two character) i have a string
www.baabrada.aapnipanchayat.org

i want to change the string
www.baabrada.aapnipanchayat.in

and i have use this update query
UPDATE `gram_panchayat` SET web=in WHERE web=org;

A: Ensures what .org be replaced with .in only at the end of string:
UPDATE gram_panchayat
  SET web = CONCAT(LEFT(web, CHAR_LENGTH(web)-CHAR_LENGTH('org')), 'in')
  WHERE web LIKE '%.org'

Test it: http://sqlfiddle.com/#!2/e78a26/1
More info: String Functions

A: Another way to do this would be to use the INSERT() function:
UPDATE gram_panchayat
SET web = INSERT(web,
                 CHAR_LENGTH(web) - CHAR_LENGTH('org') + 1,
                 CHAR_LENGTH('org'),
                 'in'
                )
WHERE web LIKE '%.org';

Here's a SQL Fiddle demo to play with: http://sqlfiddle.com/#!2/524905/1


text:
Q: Quarter-circle in top right corner I am looking to make a quarter-circle to place in the top right corner of my website (fixed) and I want it to animate towards its center when user scrolls ( I have the code working for shrinking the element but not for the element itself or its center)
I have the header shrinking with the following code:
HTML (script)
$(function(){
 var shrinkHeader = 50;
 $(window).scroll(function() {
 var scroll = getCurrentScroll();
  if ( scroll >= shrinkHeader ) {
       $('header').addClass('shrink');
    }
    else {
        $('header').removeClass('shrink');
    }
 });

with the shrink class applied to the header when the user scrolls. I will switch it over to the quarter circle when I figure it out.
NOTE: It will be white filled with an icon in the middle (acting as my nav toggle button)
EDIT: I am asking how to make a quarter-circle that sits top right of the screen (fixed) and can be animated from the top right corner (circle's center)

A:
I am looking to make a quarter-circle to place in the top right corner of my website (fixed) I want it to animate towards its center when user scrolls
I am asking how to make a quarter-circle that sits top right of the screen (fixed) and can be animated from the top right corner (circle's center)

Judging by the above, it seems like you want to know how to create a quarter-circle and also make it shrink (such that it goes towards its own top-right corner).
Creating a quarter-circle is simple and can be done with CSS itself. SVG is generally recommended for creating shapes but this is simple. All that is needed is to create a square and set it's bottom-left border radius as 100%. Positioning it (fixed) on the top right corner of the page is also very simple. Just add position: fixed with top and right as 0px.
Now for the shape to shrink, just change the height and width of the element to 0px and add to it a transition effect. In the below snippet, I have done it using an animation so that it is easily visible in the snippet window but you can put those two properties in a class and toggle it on/off depending on whether the user has scrolled the page or not.
Note: The other div and body CSS in the snippet are only for demo.

.quarter-circle {
  position: fixed;
  top: 0px;
  right: 0px;
  height: 75px;
  width: 75px;
  line-height: 75px;
  text-align: center;
  background: yellowgreen;
  border-bottom-left-radius: 100%;
  border: 2px solid;
  font-size: 1.5rem;
  animation: shrink 2s ease infinite;
}
@keyframes shrink {
  to {
    height: 50px;
    width: 50px;
    line-height: 50px;
  }
}
.some-content {
  min-height: 125vh;
  background: tomato;
}
body {
  margin: 0;
  padding: 0;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.css" rel="stylesheet" />

As you would have noticed in the above snippet, the animation is a bit jerky (the shape shivers when animation reaches its end). This is because we are animating the height and width properties both of which are super expensive because they result in a relayout, repaint and compositing. Instead, we can use transform: scale to achieve a similar effect like in the below snippet.

.quarter-circle {
  position: fixed;
  top: 0px;
  right: 0px;
  height: 75px;
  width: 75px;
  line-height: 75px;
  text-align: center;
  background: yellowgreen;
  border-bottom-left-radius: 100%;
  border: 2px solid;
  font-size: 1.5rem;
  animation: shrink 2s ease infinite;
  transform-origin: top right;
}
@keyframes shrink {
  to {
    transform: scale(.75);
  }
}
.some-content {
  min-height: 125vh;
  background: tomato;
}
body {
  margin: 0;
  padding: 0;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.css" rel="stylesheet" />

One drawback of using transform: scale is that the icon or text inside the shape will also get scaled down. This may or may not be a desirable outcome for you and hence choose accordingly.

A: SVG solution
I used your code (modyfied a bit) to change the width attribute of an svg shape.
The svg shape is Created using the path element.
Added a trigger for scrolling when page loads.
So that the change is imidiate when loading the example.
Added a css transition so the change is not imidiate (and more beautiful).

$(document).ready(function() {
  var svg = document.getElementById("slice");
  var shrinkHeader = 5;

  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll >= shrinkHeader) {
      svg.setAttribute('width', '200px');
    } else {
      svg.setAttribute('width', '100px');
    }
  });
  //Trigger scroll event
  $(window).scroll();
});
body {
  height: 300vh;
}
.header {
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  width: 100%;
  height: 200px;
}
.header svg {
  position: absolute;
  right: 5px;
  transition: width 2s;
}

  <svg id="slice" viewBox="0 0 100 100" width="200px">
    <path d="M5,5 95,5 95,95 Q 5,95 5,5" stroke="white" />
  </svg>

text

text

text

text

text

text

text

text

text

text

text

text

text

text

text

text

text

text


text:
Q: Zeep request xml, space is getting inserted between characters of xml restriction element I am trying to make SOAP service call using Zeep SOAP client code. I observed that an extra space is getting added between the characters of XML element.
Following is my code.
from zeep import Client, helpers, Settings
from zeep.plugins import HistoryPlugin
from lxml import etree
history = HistoryPlugin()
client = Client("SearchService.wsdl", plugins = [history])
ret_sea = client.get_type("ns0.MemberDetails")
sea_ser = client.get_type("ns0.SearchService")
source_t = client.get_type("ns0.Source")
members = ret_sea(Source= source_t('PAP'), NetworkID='TN7620384', Product='Gems')
sea_req = sea_ser(AppKey='89d038s0s-383nnsu3ms', members=members)
response = client.service.RetrieveMemberDetails(sea_req)
print(etree.tostring(h.last_sent["envelope"], encoding = "unicode", pretty_print = True))

which gives me following result on console
...
   <ns0:MemberDetails>
      <ns0:Source>P A P</ns0:Source>
      <ns0:NetworkID>TN7620384</ns0:NetworkID>
      <ns0:Product>Gems</ns0:Product>
   </ns0:MemberDetails>
...

Because of spaces getting added in Source value, I am not getting proper response. I have no clue why this is happening.
The Source xsd element is enumeration type defined in xsd as below.
<xs:simpleType name="Source">
  <xs:list>
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:enumeration value="PAP"/>
        <xs:enumeration value="XYZ"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:list>
</xs:simpleType name="Source">


text:
Q: How do I when pip install dtwalign pip install dtwalign

DEPRECATION: Python 3.4 support has been deprecated. pip 19.1 will be the last one supporting it. Please upgrade your Python as Python 3.4 won't be maintained after March 2019 (cf PEP 429).
Collecting dtwalign
Collecting numba>=0.34.0 (from dtwalign)
Requirement already satisfied: scipy in c:\anaconda3\lib\site-packages (from dtwalign) (0.16.0)
Requirement already satisfied: seaborn>=0.8.1 in c:\anaconda3\lib\site-packages (from dtwalign) (0.9.1)
Requirement already satisfied: numpy in c:\anaconda3\lib\site-packages (from dtwalign) (1.16.6)
Requirement already satisfied: networkx in c:\anaconda3\lib\site-packages (from dtwalign) (1.9.1)
Requirement already satisfied: matplotlib in c:\anaconda3\lib\site-packages (from dtwalign) (1.4.3)
Requirement already satisfied: enum34 in c:\anaconda3\lib\site-packages (from numba>=0.34.0->dtwalign) (1.1.10)
Requirement already satisfied: setuptools in c:\anaconda3\lib\site-packages\setuptools-27.2.0-py3.4.egg (from numba>=0.34.0->dtwalign) (27.2.0)
Collecting llvmlite>=0.31.0dev0 (from numba>=0.34.0->dtwalign)
  Using cached https://files.pythonhosted.org/packages/50/cc/04526507e80d546be5688ce0246e40277b61e7949c3347c6609b6a4154cf/llvmlite-0.32.1.tar.gz
Requirement already satisfied: singledispatch in c:\anaconda3\lib\site-packages (from numba>=0.34.0->dtwalign) (3.6.2)
Requirement already satisfied: funcsigs in c:\anaconda3\lib\site-packages (from numba>=0.34.0->dtwalign) (1.0.2)
Requirement already satisfied: pandas>=0.17.1 in c:\anaconda3\lib\site-packages (from seaborn>=0.8.1->dtwalign) (0.18.1)
Requirement already satisfied: six in c:\anaconda3\lib\site-packages (from singledispatch->numba>=0.34.0->dtwalign) (1.10.0)
Requirement already satisfied: python-dateutil>=2 in c:\anaconda3\lib\site-packages (from pandas>=0.17.1->seaborn>=0.8.1->dtwalign) (2.4.2)
Requirement already satisfied: pytz>=2011k in c:\anaconda3\lib\site-packages (from pandas>=0.17.1->seaborn>=0.8.1->dtwalign) (2015.4)
Building wheels for collected packages: llvmlite
  Building wheel for llvmlite (setup.py) ... error
  ERROR: Complete output from command 'c:\anaconda3\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\\\AppData\\Local\\Temp\\pip-install-ufd5rb5f\\llvmlite\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\\AppData\Local\Temp\pip-wheel-11jhoxwj' --python-tag cp34:
  ERROR: running bdist_wheel
  c:\anaconda3\python.exe C:\Users\\AppData\Local\Temp\pip-install-ufd5rb5f\llvmlite\ffi\build.py
  Trying generator 'Visual Studio 14 2015 Win64'
  Traceback (most recent call last):
    File "C:\Users\\AppData\Local\Temp\pip-install-ufd5rb5f\llvmlite\ffi\build.py", line 192, in <module>
      main()
    File "C:\Users\\AppData\Local\Temp\pip-install-ufd5rb5f\llvmlite\ffi\build.py", line 180, in main
      main_win32()
    File "C:\Users\\AppData\Local\Temp\pip-install-ufd5rb5f\llvmlite\ffi\build.py", line 89, in main_win32
      generator = find_win32_generator()
    File "C:\Users\\AppData\Local\Temp\pip-install-ufd5rb5f\llvmlite\ffi\build.py", line 77, in find_win32_generator
      try_cmake(cmake_dir, build_dir, generator)
    File "C:\Users\\AppData\Local\Temp\pip-install-ufd5rb5f\llvmlite\ffi\build.py", line 28, in try_cmake
      subprocess.check_call(['cmake', '-G', generator, cmake_dir])
    File "c:\anaconda3\lib\subprocess.py", line 556, in check_call
      retcode = call(*popenargs, **kwargs)
    File "c:\anaconda3\lib\subprocess.py", line 537, in call
      with Popen(*popenargs, **kwargs) as p:
    File "c:\anaconda3\lib\subprocess.py", line 859, in __init__
      restore_signals, start_new_session)
    File "c:\anaconda3\lib\subprocess.py", line 1112, in _execute_child
      startupinfo)
  FileNotFoundError: [WinError 2] Не удается найти указанный файл
  error: command 'c:\\anaconda3\\python.exe' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for llvmlite
  Running setup.py clean for llvmlite
Failed to build llvmlite
Installing collected packages: llvmlite, numba, dtwalign
  Found existing installation: llvmlite 0.20.0
ERROR: Cannot uninstall 'llvmlite'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
``

A: Make sure you first install pandas library.
https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html
You can then install dtwalign python with following command(administrator):
pip install dtwalign
Errors should then be solved.


text:
Q: Jscript mouse hover over menu always displaying behind other content I need some help with my navigation bar item, i have a shopping cart that is supposed to expand on mouse over. Which works, but the expansion is appearing behind other menu items and i cant figure out why. I have tried putting the z-index to ridiculous values and made the position absolute. Still no success.
Here is the Nav html:

            <?php
                if($this->request->session()->read('Auth')) {
               // user is logged in, show "account" link
                echo $this->Html->link(__('Account'), ['controller' => 'Users', 'action' => 'Index']);
                }
            ?>

            <?php
                if($this->request->session()->read('Auth')) {
                // user is logged in, show logout..user menu etc
                echo $this->Html->link(__('Logout'), ['controller' => 'Users', 'action' => 'logout']);
                } else {
                // the user is not logged in
                echo ''.$this->Html->link(__('Login/Register'), ['controller' => 'Users', 'action' => 'login']).'';
                }
            ?>

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

        </button>

            <?php

              echo $this->element('quick_cart');
            ?>

 |

 Secure Shipping anytime

 |

 <?php echo $this->element('search');?>

<?= $this->Html->link(__('Home'), ['controller' => 'Pages', 'action' => 'home']) ?>

<?= $this->Html->link(__('Products'), ['controller' => 'Products', 'action' => 'Index']) ?>

<?= $this->Html->link(__('New Arrivals'), ['controller' => 'Products', 'action' => 'newarrivals']) ?>

<?= $this->Html->link(__('Rings'), ['controller' => 'Products', 'action' => 'rings']) ?>

<?= $this->Html->link(__('Bracelets'), ['controller' => 'Products', 'action' => 'bracelets']) ?>

<?= $this->Html->link(__('Earrings'), ['controller' => 'Products', 'action' => 'earrings']) ?>

<?= $this->Html->link(__('Necklaces'), ['controller' => 'Products', 'action' => 'necklaces']) ?>

<?= $this->Html->link(__('Sales'), ['controller' => 'Products', 'action' => 'sales']) ?>

<?= $this->Html->link(__('Contact Us'), ['controller' => 'Pages', 'action' => 'About']) ?>

Here is the shopping cart code:

 <?php
            $counter = $this->request->session()->read('Cart.count');
            echo $this->Html->link('<?php echo $counter ;?>', array('controller'=>'Pages','action'=>'display','shoppingCart'), array('escape'=>false, 'id'=>'show-quick-cart'));
            ?>

Your cart

            <?php if ($this->request->session()->check('Cart.items')){
            ?>

                                Product
                                Quantity
                                Price

                        <?php
                        $products = $this->request->session()->read('Cart.items');
                        $cartTotal = 0;
                        foreach ($products as $product):
                        ?>

                                    <img src="<?= h($product['PicURL']) ?>" alt="BlueMountain">

                                    <?php echo $product['Quantity'];?>
                                    <?php if(isset($product['SalePrice'])){
                                        $cartTotal += $product['SalePrice']*$product['Quantity'];
                                         ?>
                                         <?php echo $product['SalePrice']*$product['Quantity'];?>
                                         <?php
                                         }

                                        else {
                                        $cartTotal += $product['UnitPrice']*$product['Quantity'];
                                         ?>
                                         <?php echo $product['UnitPrice']*$product['Quantity']; ?>
                                         <?php
                                         }
                                         ?>
                                    <?= $this->Form->postLink(__('x'), ['controller'=>'products', 'action' => 'removeFromCart', $product['ProductID']], ['confirm' => __('Are you sure you want to remove {0} from the cart?', $product['ProductName'])]) ?>

                        <?php endforeach; ?>

                                        Total:
                                        <?php echo $cartTotal; ?>

            <?php
            } else {
            ?>

 is empty!

            <?php
            }
            ?>

Any help is appreciated, thank you all very much.


text:
Q: How to return values in a textbox on different pages I have a data-set called Customers where I am running a simple sql query (select * from Customer). Instead of displaying the information from the data-set using a table or matrix , I want to use a textbox instead i.e. the textbox will return the CustomerID of each Customer on separate pages.
I am using the expression below in the texbox:
=First(Fields!CustomerId.Value, "Customers")

where "Customers" is the data-set containing the sql query.
Not sure if this can be done?

A: Alright I got you requierement and here is how I solved it.
I used Table but added some logic to it.

*

*I grouped row by CustomerID.

*Then I added Pagre break on Group as below

*Then I deleted Header row as we do not need in our case

*Now I added extra column before Customer ID as you need to show like Label and then it's Text

*I named it Customer ID:

*same goes for Customer Name:

*I added Row Inside group below

*Now I added Country as Text and in next column Country as value from Table

This is how my Table looks right now

Note I just made Border colour of each cell as white, because I assume you need to show like free text or something
Below is how output look like.

and so on.
You can use your imagination to make changes as you need.


text: Q: How to use calculus to find the surface area of this mug? I am working on an assessment to find the surface of this mug. I had just started learning calculus and I hoping to use the surface area of a revolution to find the it. But what I'm not sure as to how to go about it and what methodologies should I use to find the SA of the handle?enter image description here


text:
Q: How do I (re)broadcast a mjpegstream using html5 and C#? So far I have a C# project that has an event trigerred by new frames from an IPcam (stream in mjpeg). Those frames (as a video) I want to display to a webpage, so they are vieweble by all sorts of devices like iphones, android devices and other PC's. I think a HTML5 canvas is the way to go, but how?

A: I figured it out, altough the performance could be better:
I use VLC to rebroadcast the MJPEGstream as an mp4 one (h264/mp3) via HTTP protocol. Next I create a webpage that displays this stream using video-tags.


text:
Q: Boolean function with reference parameter I have been searching around and I cant quite get the answer I looking for or see the example I want.
I'm working with a binary tree. I have a bool search function that checks the whole tree. I currently have this
  bool search(int key)
  {
    NODE* cur = Root;

    while (cur != nullptr)
    {
      if (key == cur->Key)  // already in tree
        return true;

      if (key < cur->Key)  // search left:
      {
        cur = cur->Left;
      }
      else
      {
        cur = cur->Right;
      }
    }//while

    // if get here, not found
    return false;
  }

But now i want to modify this to as if the key is found the corresponding value is also returned as a reference parameter.
So adding, and having the function declaration be
bool search(int key, int& value)
If this is the case can I just declare int value on top of when I return true and have value equal whatever i want it to pass in my case what the value is in that key?

A: Just make the declare a value in your function and return it.


text:
Q: Playsound python module can't find file even in same folder I have imported the playsound python module and put a mp3 file in the same folder as the python file, and yet when I run the file all I get is an error message saying
        open Sound.mp3
    Cannot find the specified file.  Make sure the path and filename are correct.

    Error 263 for command:
        close Sound.mp3
    The specified device is not open or is not recognized by MCI.
Failed to close the file: Sound.mp3
Traceback (most recent call last):

A: File lookup is usually relative to the current working directory and not the Python source file itself. You could either run the script from the directory with the sound file (cd /path/to/sound_files, python3 /path_to_script), or pass and absolute path to the sound file when calling playsound.
If you're using an IDE, the working directory can usually be set in the run configuration.


text:
Q: How to call ruby value in Javascript I have a ruby value that is referred to as <%= @random_quote.quote %> which outputs a string, and I would like to set this string equal to the javascript value in document.getElementById("quoteArea").value =  "value". I have looked around here and found similar questions but none of them solve my problem. Any ideas? Thanks.

A: If you are using erb for your views:
# your_view.html.erb
document.getElementById("quoteArea").value =  "<%= @random_quote.quote %>";

If you are using HAML for your views:
# your_view.html.haml
:javascript
  document.getElementById("quoteArea").value =  "#{@random_quote.quote}";

A: You can use some.js.erb in your assets pipeline and assign the value from there, not a very good approach but one way to go, or you can set the value in DOM( Document Object Model ) in certain element data and get the value from there. As follows an dummy example.
<div data-my_value="<%= @random_quote.quote %>"></div>
jQuery("[data-my_value]").data("my_value");

Some thing like that. Hope this helps you.
Cheers

A: If the element with the id #quoteArea is available in your view, you should be able to set it's value using the same erb code you referenced in your question.
If you do not have any control over the #quoteArea element, you can define a javascript variable in your page that you can then use later:
// In Your HTML View
<script>
  var quote = "<%= @random_quote.quote %>";
</script>

// In a JS File loaded after the variable assignment
document.getElementById("quoteArea").value = quote;

A: Assign that Ruby value to a JavaScript variable.
Something like:
var myVariable = "<%= @random_quote.quote %>";

document.getElementById("quoteArea").value = myVariable;

A: You can make a file.js.erb
The files are interpreted first by ruby then by js.
var jsVariable = "<%=ruby_variable%>";

A: Check out the gon gem If you need to send some data to your js files and you don't want to do this with long way through views and parsing.
This assigns values to variables that will be accessed through javascript
gon.variable_name = variable_value

# or new syntax
gon.push({
  :user_id => 1,
  :user_role => "admin"
})

gon.push(any_object) # any_object with respond_to? :each_pair

Then to access that variable in javascript do:
gon.variable_name

In the JS file.


text:
Q: Matlab memory leak when forward propagating cell arrays or 3D matrices I'm having an issue with the way Matlab is dealing with forward multiplying matrices when there are a large number of them.
As a simplified example, i'd like to do x(ii + 1) = y(ii) * x(ii). However when the dimensions of the matrix are large, and there are a lot of them, the memory requirement grows exponentially, way out of range for what it should be.
Here's some example code, where according to the matlab memory profiler it's using 1e-07TB of RAM, which although isn't correct this loop often takes up 256GB of RAM.
function forward_test()
    K = 250;
    dim = 1024;
    U = cell(K,1);

    for ii = 1 : K
        U{ii} = rand(dim,dim) + (1i*rand(dim,dim));
    end

    r_tmp = cell(K + 1, 1); r_tmp{1} = eye(dim);
    for k = 1 : K
        r_tmp{k+1} = U{k} * r_tmp{k}; % <--- this line is the issue
    end

    % convert the matrix to a 3D array, I'm certian there's a better way of doing this, but this is quick and dirty
    u_test = zeros(dim, dim, K);
    for ii = 1 : K
        u_test(:,:,ii) = U{ii};
    end

    % test the same operation on a 3D array, rather than a set of 2D maricies.
    tmp2 = zeros(dim, dim, K + 1); tmp2(:,:,1) = eye(dim);
    for ii = 1 : K
        tmp2(:,:, ii + 1) =  U{ii} * tmp2(:,:,ii);
    end

    for ii = 1 : numel(r_tmp)
        if ~(all(all(r_tmp{ii} == tmp2(:,:,ii))))
            error('Result missmatch!');
        end
    end
end

To check performance run:
profile off
profile -memory on
forward_test
profreport


text:
Q: Thinking Sphinx returns all results with empty query Whenever I send an empty query to Thinking Sphinx it returns all the items in my table. I would assume that an empty query would return back null or an empty array. Does Thinking Sphinx have an option to prevent this behavior.
So for example the following code will return all the rows in Article:
Article.search

A: If you do not specify search terms then the search will (by default) be for everything of that type (the object type will be the only filter applied) and so you will get everything back. You should just check your query before you submit it to Thinking Sphinx and return no results if a blank query is passed.


text:
Q: Find difference when comparing lists of sets How do I find the difference of two lists that contains sets?
List 1:
    [{0, 1, 3, 9}, {2, 5, 6}, {8, 4}]
List 2:
    [{6, 7, 8, 9}]

Result should be:
[{7}]

A: Create two sets and fill them with values from your lists. Then the desired result is simple substraction.
l1 = [{0, 1, 3, 9}, {2, 5, 6}, {8, 4}]
l2 = [{6, 7, 8, 9}]

s1 = set()
for i in l1:
    s1.update(i)

s2 = set()
for i in l2:
    s2.update(i)

print(s2 - s1)
# {7}

A: Sounds like you can just flatten the list1, then find the differences:
>>> l1 = [{0, 1, 3, 9}, {2, 5, 6}, {8, 4}]
>>> l2 = [{6, 7, 8, 9}]
>>> l3 = [x for y in l1 for x in y]
>>> l3
[0, 9, 3, 1, 2, 5, 6, 8, 4]
>>> l4 = [set(i for i in l2[0] if i not in l3)]
>>> l4
[set([7])]


text:
Q: How can I change the background color of an activity dynamically within the onCreate statement with Android SDK? I would like to know if it is possible to change the background color of an activity dynamically by checking in the onCreate statement if the settings say 'Red' or 'Blue', and then accordingly change the background color of the activity to 'Red' or 'Blue'.
I have found several answers on StackOverflow that looked like they worked for other people, but they don't seem to work for me. Here's a list of things I tried:

*

*Using setBackgroundColor() combined with a view.
if (settings.getBoolean("Blue", true)) {

View currentView = (View) findViewById(R.layout.home_screen);
currentView.setBackgroundColor(getResources().getColor(R.color.blue));

} if (settings.getBoolean("Red", false)) {

View currentView = (View) findViewById(R.layout.home_screen);
currentView.setBackgroundColor(getResources().getColor(R.color.red));

}

*Using setTheme() combined with different styles. This works in a way that I the background of my elements such as TextViews change in 'Red' or 'Blue' instead of the background color of the whole activity.
<style name="RedTheme">
    <item name="android:background">@color/redbackground</item>
    <item name="android:windowBackground">@color/redbackground</item>
    <item name="android:colorBackground">@color/redbackground</item>
</style>

In this case, only android:background seems to change anything, but unfortunately it changes the backgroundcolor of my TextView element.

*Using getWindow().getDecorView().setBackgroundColor(Color.BLUE), but that also seems to do nothing at all.
Is there anyone who can tell me what I am doing wrong or tell me how I can successfully accomplish this?
Great thanks in advance!

Added the complete code by request:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    changeTheme();
    setContentView(R.layout.activity_home_screen);
}

private void changeTheme() {
    SharedPreferences settings = getSharedPreferences(Settings, 0);

    if (settings.getBoolean("Blue", true)) {

        View currentView = (View) findViewById(R.layout.activity_home_screen);
        currentView.setBackgroundColor(getResources().getColor(R.color.blue));

    } if (settings.getBoolean("Red", false)) {

        View currentView = (View) findViewById(R.layout.activity_home_screen);
        currentView.setBackgroundColor(getResources().getColor(R.color.red));

    }
}

A: first of all, your main layout of home_screen should be FrameLayout, dont forget to give it some id, i.e. like this
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".HomeScreenActivity"
    android:id="@+id/activity_home_screen">

<!-- rest of your UI here -->

</FrameLayout>

Then in your onCreate create View variable and connect it to this layout by ID.
From now on your setBackgroundColor() should work (below code with small changes works for me - i'm not refering to settings, but i call changeTheme() after some time with changed value)
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_screen);

    changeTheme();
}

private void changeTheme()
{
    SharedPreferences settings = getSharedPreferences(Settings, 0);
    View currentView = (View) findViewById(R.id.activity_home_screen);

    if (settings.getBoolean("Blue", true))
    {
        currentView.setBackgroundColor(getResources().getColor(R.color.blue));
    }
    else if (settings.getBoolean("Red", false))
    {
        currentView.setBackgroundColor(getResources().getColor(R.color.red));
    }
}

A: Move this from onCreate to separate method:
private void changeTheme(){

    if (settings.getBoolean("Blue", true)) {
        View currentView = (View) findViewById(R.layout.home_screen);
        currentView.setBackgroundColor(getResources().getColor(R.color.blue));
    } else if (settings.getBoolean("Red", false)) {
        View currentView = (View) findViewById(R.layout.home_screen);
        currentView.setBackgroundColor(getResources().getColor(R.color.red));
    }

}

and then call changeTheme() from onClick() or whatever


text:
Q: Error : "Trying to use an SPWeb object that has been closed or disposed.." I am creating document library in code behind.
I added an application page and put one label, a text box and a button. Text box accepts the name of  the document library, when button is pressed the library is created.
My code for creating library is :
protected void Page_Load(object sender, EventArgs e)
{
    lblMsg.Visible = false;
    txtDocumentLibrary.Focus();
    btnDocumentLibrary.Click += new EventHandler(btnDocumentLibrary_Click);
}
void btnDocumentLibrary_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(txtDocumentLibrary.Text))
    {
        lblMsg.Text = "Please Enter Name";
        lblMsg.ForeColor = System.Drawing.Color.Red;
        lblMsg.Visible = true;
    }
    else
    {
       using(SPSite site = SPContext.Current.Site)
       {
           using (SPWeb web = site.RootWeb)
           {
               web.AllowUnsafeUpdates = true;
               Guid id = web.Lists.Add(txtDocumentLibrary.Text, "Created Programmatically", SPListTemplateType.DocumentLibrary);
               SPList lst = web.Lists[id];
               lst.OnQuickLaunch = true;
               web.Update();
               web.AllowUnsafeUpdates = false;
               lblMsg.Text = txtDocumentLibrary.Text + "Library Created Successfully";
               lblMsg.ForeColor = System.Drawing.Color.Green;
               lblMsg.Visible = true;
            }
        }
    }
}

First I used SPSite site = SPContext.Current.Site and used Dispose() method, and then I searched for resolving the error and found that the using() statement will be helpful, but after using such also throws error. How should I resolve it? Please help.

A: You should open new SPSite and SPWeb objects in the using statement, like:
using(SPSite site = new SPSite(SPContext.Current.Site.ID))
       {
           using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
           {
               web.AllowUnsafeUpdates = true;
               Guid id = web.Lists.Add(txtDocumentLibrary.Text, "Created Programmatically", SPListTemplateType.DocumentLibrary);
               SPList lst = web.Lists[id];
               lst.OnQuickLaunch = true;
               web.Update();
               web.AllowUnsafeUpdates = false;
               lblMsg.Text = txtDocumentLibrary.Text + "Library Created Successfully";
               lblMsg.ForeColor = System.Drawing.Color.Green;
               lblMsg.Visible = true;
            }
        }

Some info about disposing of SPWeb and SPSite objects:

*

*You should never dispose the SPContext.Current.Web resp. SPContext.Current.Site, since these objects are currently used by SharePoint.

*If you use "using" statements for opening fresh objects, you do not have to dispose the objects explicitly, when exiting the using block, dispose will be called automatically.

*If not using "using" statements, you will in most cases have to call .Dispose() yourself, once you are done working with the object.

(more here, for wss 3.0 but all seems still valid)
Here are code examples for different patterns: http://msmvps.com/blogs/sundar_narasiman/archive/2011/07/30/sharepoint-2010-recommended-practices-for-disposing-objects-part1.aspx

A: in my strange case because i was just manipulating with SharePoint designer 2013,
this error and exception is showing only to normal users and me as admin was not seeing that.
although i removed the 2 using in my weather webpart and fixed the problem but i think that this is not essential because this webpart was working before i removed many snippets of the page in SharePoint designer.
i am suspicious of the following  code which is essentially a webpart zone title handler and is hidden but i think WebPartPages:TitleBarWebPart is responsible for fixing this problem .
note the "ms-hide" class
<div class="ms-hide">
    <WebPartPages:WebPartZone runat="server" title="loc:TitleBar" id="TitleBar" AllowLayoutChange="false"
    AllowPersonalization="false" Style="display:none;"><ZoneTemplate>
    <WebPartPages:TitleBarWebPart runat="server" HeaderTitle="Home8" Title="Web Part Page Title Bar"
     FrameType="None" SuppressWebPartChrome="False" Description="" IsIncluded="True"
     ZoneID="TitleBar" PartOrder="2" FrameState="Normal" AllowRemove="False"
     AllowZoneChange="True" AllowMinimize="False" AllowConnect="True" AllowEdit="True"
     AllowHide="True" IsVisible="True" DetailLink="" HelpLink="" HelpMode="Modeless" Dir="Default"
     PartImageSmall="" MissingAssembly="Cannot import this Web Part."
     PartImageLarge="" IsIncludedFilter="" ExportControlledProperties="True"
     ConnectionID="00000000-0000-0000-0000-000000000000" ID="g_7fe5ac76_a5b6_4813_9238_fcbbcae38915"
     AllowClose="False" ChromeType="None" ExportMode="All"
     __MarkupType="vsattributemarkup" __WebPartId="{7FE5AC76-A5B6-4813-9238-FCBBCAE38915}"
     WebPart="true" Height="" Width=""></WebPartPages:TitleBarWebPart>

    </ZoneTemplate></WebPartPages:WebPartZone>
  </div>


text:
Q: Adding individual item to a TableView? I have started using JavaFX for a few weeks. Here is a code snap of a TableView
@FXML protected void handleSubmitButtonAction(ActionEvent event) {
    log.debug("handleSubmitButtonAction");
    service.save(new InputText(inputText.getText()));

    List<OutputData> outputDataList = new ArrayList<>();
    service.getAll().forEach(e -> outputDataList.add(new OutputData(e)));
    ObservableList<OutputData> list = FXCollections.observableArrayList(outputDataList);
    outputView.setItems(list);

    inputText.setText("");
}

What it does is that

*

*Create a new entry

*Save it to DB

*Fetch all entries from DB

*Create TableView row data for each entry

*Create an ObservableList with all of the row data

*Add the list to the TableView

That certainly isn't effective. Is a way to add a newly created entry directly to the TableView?

A: Here is what I would do.

*

*Have service.save(new InputText(inputText.getText())); return a
true if the data was saved to the DB and false otherwise.

*If true is returned, I would then add the data to the TableView
using outputView.getItems().add(inputText.getText());

*If false is retured, I would use an Alert to let the user know
that the data was not added to the DB.


text:
Q: Adding clojure dependency and running lein uberjar causes java.lang.IllegalAccessError I am a novice engineer with experience writing PHP, python, and ruby. I am trying to contribute to a project written in clojure. I am trying to add a library to the project, but after adding the library and running lein uberjar, I am receiving an error. I would like to know what it means and whether you can recommend a method for troubleshooting it. Thank you in advance for your help!
What I am trying to achieve
Include the uap-clj library in my project and compile the project into a jarfile.
What I wrote
I have added the library as the second-to-last item in the dependencies list.
  :dependencies [[lots-of-dependencies]
                 [uap-clj "1.1.1"] ; user agent parser
                 [another-dependency]]

What I ran in lein
According to the instructions on github, after saving my changes to project.clj, I run lein deps then lein clean && lein uberjar.
What happened
After updating and saving the file, running the command gives the following error before a long stacktrace:
java.lang.IllegalAccessError: tried to access method clojure.lang.RT.classForNameNonLoading(Ljava/lang/String;)Ljava/lang/Class; from class clj_yaml.core$loading__5340__auto____29, compiling:(flexmaster.clj:1:1)

What else I tried
I wanted to test whether I had made a mistake adding the library. I created a new clojure project from scratch and created a jarfile using lein deps and then lein uberjar. Next, I added uap-clj to the :dependencies in my new project, saved project.clj, and executed lein deps and lein uberjar again. I was able to successfully create a jarfile, so I believe I am adding the library correctly.
I cannot think of another reason why the act of including another dependency would prevent me from creating the jarfile. If you can think of something I should check based on the information I provided, it would help me very much. Thank you!

A: It looks like the referenced library depends on Clojure 1.7.0, but you're explicitly referencing version 1.6.0.
Try changing:
[org.clojure/clojure "1.6.0"]

to:
[org.clojure/clojure "1.7.0"]

Alternatively, you could reference an older version of the library which doesn't depend on Clojure 1.7.0, like: [uap-clj "1.0.1"]


text:
Q: In node js, how do I create a prompt loop using inquirer? For some reason, npm inquirer will blast through a while loop without prompting the user questions.  The only way I can think of(cleanly) is to put it in function with a switch like the following:
function callMenu (selection){
  switch (selection){
    case 'main':
        //Use inquirer to show main menu and set selection = 'selection1' or selction = 'selection2'
        callMenu(selection);
        break;
    case 'selection1':
        //Use inquirer to show selection1 second level menu then go back to main menu
        callMenu('main');
        break;
    case 'selection2':
        //Use inquirer to show selection2 second level menu then go back to main menu
        callMenu('main');
        break;
   }
}
callMenu('main');

The problem is, I do not want to create a leak on call stack by calling the function within its self.

A: You are definitely on the right track. I created inquirer submenus in different node modules so they can get called from any prompt menu. I also have my main menu as it's own module so it can be called from anywhere in any of the submenus.
So this is what my mainMenu.js file looks like:
const menu = () => {
  inquirer
    .prompt([{
      type: 'input',
      name: 'menu',
      message: "Type 'Menu' or hit enter to see the menu. Type in a player's name to search for a player."
    }]).then(answer => {
      answer.menu === '' ? subMenu.subMenu() :
        answer.menu.toLowerCase().trim() === 'menu' ? subMenu.subMenu() :
        tools.quickNameLookup(answer.menu);
    });
}

module.exports.menu = menu;

And here is what my subMenus.js file looks like:
const subMenu = () => {
  inquirer
    .prompt([{
      type: 'list',
      name: 'subMenu',
      message: 'Welcome to the MLB stats app. What would you like to do?',
      choices: ['Roster Search Menu', 'Player Search Menu', 'Player Statistics Menu', 'Leaderboards', 'Reports Menu', 'Back']
    }]).then(submenu => {
      let currentMenu = Object.keys(submenu)[0];
      switch (submenu.subMenu) {
        case 'Roster Search Menu':
          rosterMenu.rosterSearchPrompt(currentMenu);
          break;
        case 'Player Search Menu':
          playerSearchMenu.playerSearchPrompt(currentMenu);
          break;
        case 'Player Statistics Menu':
          statisticsMenu.statsSearchPrompt(currentMenu);
          break;
        case 'Reports Menu':
          reportsMenu.reportsPrompt(currentMenu);
          break;
        case 'Leaderboards':
          leaderboardsMenu.leaderboardsPrompt();
        case 'Back':
          menu.menu();
          break;
      }
    });
};

module.exports.subMenu = subMenu;

Works for input prompts but I prefer using lists when I can to avoid user error.


text:
Q: Spawn Python subprocess (async?) on Nginx reverse proxy response return I have an Nginx which acts as a reverse proxy for an upstream web service.
I use it to cache some results -  mainly to reduce my upstream costs.
I want to get the results back to the client/browser/requestor ASAP, however, as a secondary endeavour, I also want to use Python to process the response.
This processing will take some seconds; and I certainly don't want to make the requestor wait.
So can I send the upstream response back to the requestor immediately, but also shart a Python subprocess(?) for processing the response?  (And what is the most performant way of doing that?   WSGI?)
I guess I'm wondering if the undocumented post_action can execute asynchronously


text:
Q: Optimize function for multiple language support I have created my own multiple language support for one of my projects. I have 3 different database tables for it: languages, languages_variables, and languages_words (as seen below).
CREATE TABLE IF NOT EXISTS `languages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_user` int(11) NOT NULL,
  `data_name` text NOT NULL,
  `data_currency` text NOT NULL,
  `is_standard` tinyint(4) NOT NULL,
  `data_note` text NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
)

CREATE TABLE IF NOT EXISTS `languages_variables` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data_name` text NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
)

CREATE TABLE IF NOT EXISTS `languages_words` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_language` int(11) NOT NULL,
  `id_variable` int(11) NOT NULL,
  `data_name` text NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
)

When I want to extract the specific string to the website, I'll use a function called language() (as seen below). $user in the code below gets information about the logged in user, such as the language the user have chosen.
With the function, I can simply call for the variable that are in languages_variables with language('menu_about') ( menu_about is just an example of a variable).
function language($variable) {

    global $user;

    # DATABAS (kontrollera)
    $check_language = sql("SELECT COUNT(lv.data_name)

                           FROM languages AS l
                           JOIN languages_variables AS lv

                           JOIN languages_words AS lw
                           ON l.id = lw.id_language

                           WHERE lv.data_name = :variable
                           AND lw.id_language = :idlanguage
                          ", Array('idlanguage' => ($user['id_language'] == 0 ? '1' : (int)$user['id_language']),
                                   'variable' => $variable), 'count');

    # DATABAS (räkna)
    $count_words = sql("SELECT COUNT(lw.id)
                        FROM languages_words AS lw
                        JOIN languages_variables AS lv
                        ON lw.id_variable = lv.id
                        WHERE lw.id_language = :idlanguage
                        AND lv.data_name = :variable
                       ", Array('idlanguage' => ($user['id_language'] == 0 ? '1' : (int)$user['id_language']),
                                'variable' => $variable), 'count');

    # KONTROLL
    if($check_language == 0 OR $count_words == 0) {

        return $variable;

    # KONTROLL
    } else {

        # DATABAS (hämta)
        $get_languages = sql("SELECT *,
                                     lv.data_name AS name_variable,
                                     lw.data_name AS name_translation

                              FROM languages AS l
                              JOIN languages_variables AS lv

                              JOIN languages_words AS lw
                              ON lv.id = lw.id_variable

                              WHERE lv.data_name = :variable
                              AND lw.id_language = :idlanguage
                             ", Array('variable' => $variable,
                                      'idlanguage' => ($user['id_language'] == 0 ? '1' : (int)$user['id_language'])));

        # LOOP
        foreach($get_languages AS $language) {

            # KONTROLL
            if($language['name_variable'] == $variable) {
                return $language['name_translation'];

            # KONTROLL
            } else {
                return $variable;
            }

        }

    }

}

The problem is that the website loads very slow with all the stuff that are within language(). Especially when I will list a lot of items from the database (for an example with a loop). The loading speed goes from under 2 seconds to under 10 seconds.
Is there another, more better and faster way to get the chosen language string?
UPDATE I have lower the loading speed from 7-8 seconds to 3-4 seconds. But it's still too slow.
function language($variable) {

    # DATABAS (hämta)
    $language = sql("SELECT lv.data_name AS name_variable,
                            lw.data_name AS name_word

                     FROM languages AS l
                     JOIN languages_variables AS lv
                     JOIN languages_words AS lw

                     ON lv.id = lw.id_variable
                     WHERE lv.data_name = :variable
                     AND l.id = :idlanguage
                    ", Array('variable' => $variable,
                             'idlanguage' => ($user['id_language'] == 0 ? '1' : (int)$user['id_language'])), 'fetch');

    return $language['name_word'];

}

I'm thinking of to use files (sv.php, en.php, etc.) instead of database. But then the users can't translate the website from the browser (if I do not sacrifice myself several hours of blood, sweat and tears).

A: Start by profiling the build with Xhprof to validate PHP performance. For the SQL calls Google Chrome has a built-in web inspector which lets you know how long each component is taking (Firebug for Firefox).
If you post the logs it can go a long way towards suggesting relevant areas for improvement.


text:
Q: Mongod service crashed after performing mongodump I performed this query
query: mongodump --db=elastic --collection=q_moonx_notifications_2019-08-26 --out=/home/centos/mongo-dump/
on my mongo db to take a dump of one collection which is around
Collection name: q_moonx_notifications_2019-08-26
size : 80GB
storageSize : 23.6GB
Soon after doing this, mongod service crashed.
I went through /var/log/messages to find the problem.
I got to know it happened due to 'out-of-memory' issue.
Can someone help me how it happened and how can I take a dump of a single collection without effecting my running mongo service.
Machine has 32 gb memory and 0 swp.
/var/log/messages content
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbdb61e41>] dump_stack+0x19/0x1b
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbdb5c86a>] dump_header+0x90/0x229
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd700bcb>] ? cred_has_capability+0x6b/0x120
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd5ba4e4>] oom_kill_process+0x254/0x3d0
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd700c9c>] ? selinux_capable+0x1c/0x40
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd5bad26>] out_of_memory+0x4b6/0x4f0
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbdb5d36e>] __alloc_pages_slowpath+0x5d6/0x724
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd5c1105>] __alloc_pages_nodemask+0x405/0x420
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd60df68>] alloc_pages_current+0x98/0x110
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd5b6347>] __page_cache_alloc+0x97/0xb0
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd5b8fa8>] filemap_fault+0x298/0x490
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffc0400d0e>] __xfs_filemap_fault+0x7e/0x1d0 [xfs]
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffc0400f0c>] xfs_filemap_fault+0x2c/0x30 [xfs]
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd5e444a>] __do_fault.isra.59+0x8a/0x100
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd5e49fc>] do_read_fault.isra.61+0x4c/0x1b0
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd5e93a4>] handle_pte_fault+0x2f4/0xd10
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd50cbf8>] ? get_futex_key+0x1c8/0x2c0
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbd5ebedd>] handle_mm_fault+0x39d/0x9b0
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbdb6f5e3>] __do_page_fault+0x203/0x500
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbdb6f915>] do_page_fault+0x35/0x90
Oct 11 07:07:33 ip-1.23.345.678 kernel: [<ffffffffbdb6b758>] page_fault+0x28/0x30
Oct 11 07:07:33 ip-1.23.345.678 kernel: Mem-Info:
Oct 11 07:07:33 ip-1.23.345.678 kernel: active_anon:7972560 inactive_anon:30565 isolated_anon:0#012 active_file:2831 inactive_file:4651 isolated_file:0#012 unevictable:0 dirty:0 writeback:5 unstable:0#012 slab_reclaimable:42065 slab_unreclaimable:12016#012 mapped:18928 shmem:55424 pagetables:19349 bounce:0#012 free:49154 free_pcp:558 free_cma:0
Oct 11 07:07:33 ip-1.23.345.678 kernel: Node 0 DMA free:15904kB min:32kB low:40kB high:48kB active_anon:0kB inactive_anon:0kB active_file:0kB inactive_file:0kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present:15988kB managed:15904kB mlocked:0kB dirty:0kB writeback:0kB mapped:0kB shmem:0kB slab_reclaimable:0kB slab_unreclaimable:0kB kernel_stack:0kB pagetables:0kB unstable:0kB bounce:0kB free_pcp:0kB local_pcp:0kB free_cma:0kB writeback_tmp:0kB pages_scanned:0 all_unreclaimable? yes
Oct 11 07:07:33 ip-1.23.345.678 kernel: lowmem_reserve[]: 0 3597 31992 31992
Oct 11 07:07:33 ip-1.23.345.678 kernel: Node 0 DMA32 free:121020kB min:7596kB low:9492kB high:11392kB active_anon:3397760kB inactive_anon:11020kB active_file:284kB inactive_file:508kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present:3915776kB managed:3684320kB mlocked:0kB dirty:0kB writeback:0kB mapped:5892kB shmem:14892kB slab_reclaimable:131668kB slab_unreclaimable:5368kB kernel_stack:1472kB pagetables:7364kB unstable:0kB bounce:0kB free_pcp:1184kB local_pcp:0kB free_cma:0kB writeback_tmp:0kB pages_scanned:2829 all_unreclaimable? yes
Oct 11 07:07:33 ip-1.23.345.678 kernel: lowmem_reserve[]: 0 0 28394 28394
Oct 11 07:07:33 ip-1.23.345.678 kernel: Node 0 Normal free:66532kB min:59952kB low:74940kB high:89928kB active_anon:28492480kB inactive_anon:111240kB active_file:11040kB inactive_file:11684kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present:29622272kB managed:29079004kB mlocked:0kB dirty:0kB writeback:20kB mapped:69820kB shmem:206804kB slab_reclaimable:36592kB slab_unreclaimable:42696kB kernel_stack:6720kB pagetables:70032kB unstable:0kB bounce:0kB free_pcp:3320kB local_pcp:0kB free_cma:0kB writeback_tmp:0kB pages_scanned:8574 all_unreclaimable? no
Oct 11 07:07:33 ip-1.23.345.678 kernel: lowmem_reserve[]: 0 0 0 0
Oct 11 07:07:33 ip-1.23.345.678 kernel: Node 0 DMA: 0*4kB 0*8kB 0*16kB 1*32kB (U) 2*64kB (U) 1*128kB (U) 1*256kB (U) 0*512kB 1*1024kB (U) 1*2048kB (M) 3*4096kB (M) = 15904kB
Oct 11 07:07:33 ip-1.23.345.678 kernel: Node 0 DMA32: 2724*4kB (UEM) 1319*8kB (UEM) 2734*16kB (UEM) 1065*32kB (UEM) 296*64kB (UEM) 32*128kB (UEM) 0*256kB 0*512kB 0*1024kB 0*2048kB 0*4096kB = 122312kB
Oct 11 07:07:33 ip-1.23.345.678 kernel: Node 0 Normal: 10268*4kB (UEM) 3615*8kB (UEM) 0*16kB 0*32kB 0*64kB 0*128kB 0*256kB 0*512kB 0*1024kB 0*2048kB 0*4096kB = 69992kB
Oct 11 07:07:33 ip-1.23.345.678 kernel: Node 0 hugepages_total=0 hugepages_free=0 hugepages_surp=0 hugepages_size=1048576kB
Oct 11 07:07:33 ip-1.23.345.678 kernel: Node 0 hugepages_total=0 hugepages_free=0 hugepages_surp=0 hugepages_size=2048kB
Oct 11 07:07:33 ip-1.23.345.678 kernel: 61902 total pagecache pages
Oct 11 07:07:33 ip-1.23.345.678 kernel: 0 pages in swap cache
Oct 11 07:07:33 ip-1.23.345.678 kernel: Swap cache stats: add 0, delete 0, find 0/0
Oct 11 07:07:33 ip-1.23.345.678 kernel: Free swap  = 0kB
Oct 11 07:07:33 ip-1.23.345.678 kernel: Total swap = 0kB
Oct 11 07:07:33 ip-1.23.345.678 kernel: 8388509 pages RAM
Oct 11 07:07:33 ip-1.23.345.678 kernel: 0 pages HighMem/MovableOnly
Oct 11 07:07:33 ip-1.23.345.678 kernel: 193702 pages reserved
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ pid ]   uid  tgid total_vm      rss nr_ptes swapents oom_score_adj name
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 2415]     0  2415    55590    32605     114        0             0 systemd-journal
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 2456]     0  2456    11953      611      25        0         -1000 systemd-udevd
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 2704]     0  2704    15511      170      29        0         -1000 auditd
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 4346]    32  4346    18412      189      38        0             0 rpcbind
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 4464]    81  4464    16600      204      34        0          -900 dbus-daemon
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 4532]   998  4532    29446      143      29        0             0 chronyd
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 4588]     0  4588     6652      156      19        0             0 systemd-logind
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 4589]   999  4589   153057     1381      63        0             0 polkitd
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 4592]     0  4592     5416      101      14        0             0 irqbalance
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 4596]     0  4596    50404      162      38        0             0 gssproxy
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 4940]     0  4940    26839      508      51        0             0 dhclient
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5035]     0  5035   143455     3309      99        0             0 tuned
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5102]     0  5102    31253      535      58        0             0 nginx
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5103]   995  5103    31375      641      59        0             0 nginx
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5104]   995  5104    31375      641      59        0             0 nginx
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5105]   995  5105    31375      641      59        0             0 nginx
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5106]   995  5106    31375      641      59        0             0 nginx
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5107]   995  5107    31375      641      59        0             0 nginx
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5108]   995  5108    31375      641      59        0             0 nginx
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5109]   995  5109    31375      641      59        0             0 nginx
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5110]   995  5110    31375      641      59        0             0 nginx
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5183]     0  5183    22603      310      42        0             0 master
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5189]    89  5189    22673      286      43        0             0 qmgr
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5231]   997  5231  4365796  4120011    8150        0             0 mongod
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5295]     0  5295   104225    16973     121        0             0 rsyslogd
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5297]     0  5297    28189      267      58        0         -1000 sshd
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5337]     0  5337    31580      194      18        0             0 crond
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5343]     0  5343    27523       50      10        0             0 agetty
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5347]     0  5347    27523       50      13        0             0 agetty
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 5662]    27  5662   691356    97174     303        0             0 mysqld
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 7361]   996  7361 12739660  2366239    5813        0             0 java
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 7462]   996  7462    17192      173      30        0             0 controller
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 7661]  1000  7661  3588101  1239871    2579        0             0 java
Oct 11 07:07:33 ip-1.23.345.678 kernel: [14974]     0 14974   371181     6509     107        0             0 metricbeat
Oct 11 07:07:33 ip-1.23.345.678 kernel: [ 6781]   994  6781   430375    60775     604        0             0 node
Oct 11 07:07:33 ip-1.23.345.678 kernel: [24008]    89 24008    22629      301      47        0             0 pickup
Oct 11 07:07:33 ip-1.23.345.678 kernel: [25163]     0 25163    39154      367      77        0             0 sshd
Oct 11 07:07:33 ip-1.23.345.678 kernel: [25167]  1000 25167    39154      366      74        0             0 sshd
Oct 11 07:07:33 ip-1.23.345.678 kernel: [25168]  1000 25168    28893      149      15        0             0 bash
Oct 11 07:07:33 ip-1.23.345.678 kernel: [28554]  1000 28554   260690    34619     132        0             0 mongodump
Oct 11 07:07:33 ip-1.23.345.678 kernel: Out of memory: Kill process 5231 (mongod) score 503 or sacrifice child
Oct 11 07:07:33 ip-1.23.345.678 kernel: Killed process 5231 (mongod) total-vm:17463184kB, anon-rss:16480044kB, file-rss:0kB, shmem-rss:0kB
Oct 11 07:07:34 ip-1.23.345.678 systemd: mongod.service: main process exited, code=killed, status=9/KILL
Oct 11 07:07:34 ip-1.23.345.678 systemd: Unit mongod.service entered failed state.
Oct 11 07:07:34 ip-1.23.345.678 systemd: mongod.service failed.
Oct 11 07:07:39 ip-1.23.345.678 systemd-logind: New session 1220 of user centos.

A: You ran into a "problem" called the "OOM-Killer".
A quote from the part of the MongoDB documentation aptly named Production notes:

Swap
Assign swap space for your systems. Allocating swap space can avoid issues with memory contention and can prevent the OOM Killer on Linux systems from killing mongod.
For the WiredTiger storage engine, given sufficient memory pressure, WiredTiger may store data in swap space.

(emphasis by me)
What basically happened is that the memory pressure on the system became critical, and the kernel decided to kill a process to free some RAM in order to ensure the system can still run. It does so by determining the "badness" of a task via
badness_for_task = total_vm_for_task / (sqrt(cpu_time_in_seconds) *
sqrt(sqrt(cpu_time_in_minutes)))

and killing the baddest task. See https://www.kernel.org/doc/gorman/html/understand/understand016.html
for details.
Gist: MongoDB presumably consumes several orders of magnitude more RAM than any other process on the server, hence it get's killed by the OOM Killer when the Kernel has no option to swap out some data and thereby ensure the basic system tasks still can run.
This behaviour can basically be prevented by allocating swap, which is why it is accordingly documented in the production notes.

A: From the official document -

mongodump reads data from a MongoDB database and creates high fidelity BSON files which the mongorestore tool can use to populate a MongoDB database. mongodump and mongorestore are simple and efficient tools for backing up and restoring small MongoDB deployments, but are not ideal for capturing backups of larger systems.
When connected to a MongoDB instance, mongodump can adversely affect mongod performance. If your data is larger than system memory, the queries will push the working set out of memory, causing page faults.

and for the above said result it is important to have swap memory ready for using these commands.
I would suggest to create swap memory as a first step you can check the required steps for your specific os you are using. This is the best I can recommend for creating swap space.
If that doesn't help please increase the memory.


text:
Q: Create class method with already existing name from a DLL I come from this post : Create class method with already existing name, where I explain that I need to make code compatible with MS Access and PostgreSQL. My first thought was to create a new class for PostgreSQL support and rewrite the functions previously used. The solution brought could work, but the problem is that the MS Access database class is loaded from a DLL (Microsoft Shared\DAO\dao360.dll, DAO.DBEngine). How can I interface or override those DLL functions and get rid of this "ambiguous name detected" error ?

A: As said in the answer to your first post you can use the Implements feature to do this. Without further details and yout code it is just more than difficulut to tell where your issue is.
IDatabase could look like that
Option Explicit

Sub OpenDB(fileName As String)
End Sub

Function ReadData(lngNr As Long) As String
End Function

clsAccess like that
Option Explicit

Implements IDatabase

Dim m_Dbs As DAO.Database
Dim m_Rcd As DAO.Recordset
Dim m_Filename As String

Sub IDatabase_OpenDB(fileName As String)
    m_Filename = fileName
    Set m_Filename = OpenDatabase(m_Filename, , True)
End Sub

Function IDatabase_ReadData(lngNr As Long) As String
    Set m_Rcd = m_dbs.OpenRecordset("qryTable", dbOpenSnapshot)
    m_Rcd.Move lngNr - 1
    IDatabase_ReadData = m_Rcd.Fields("fldName").Value
    m_Rcd.Close
End Function

You need to add the references in Tools/References.


text:
Q: Why are the variables in my object being reset to the default? I'm trying to write a chess clock on an Arduino with an LCD keypad shield. I'm almost completely new to C++ and I think I'm having trouble with how it handles class objects.
In my code I have a menu which should allow players to change the amount of time available to them by pressing the right and left buttons on the keypad. This seems to work at first, but when I switch to the other player and back again using the up and down buttons the minutes variable gets reset to the default value of 5 minutes.
What am I missing about how my Player objects are being handled?
boolean menuActive = true;

class Player {
  // Represents a player.
  public:
    int minutes;              // number of minutes allowed
    void IncrementMinutes();
    void DecrementMinutes();
};

void Player::IncrementMinutes() {
  this->minutes += 1;
}

void Player::DecrementMinutes() {
  if (this->minutes > 1) {
    this->minutes -= 1;
  }
}

Player p1 = {5, false, 1, "P1 mins: ", 0};
Player p2 = {5, false, 2, "P2 mins: ", 0};

Player menuPlayer = p1;

void setup()
{
 lcd.begin(16, 2);
 lcd.setCursor(0,0);
 lcd.print("ChessClock");
}

// Main loop
void loop()
{
 lcd_key = read_LCD_buttons();
 if (menuActive) {
   switch (lcd_key)
   {
     case btnRIGHT:
       {
        // increase minutes
        menuPlayer.IncrementMinutes();
        delay(250);
        break;
       }
     case btnLEFT:
       {
        // decrease minutes
        menuPlayer.DecrementMinutes();
        delay(250);
        break;
       }
     case btnUP:
       {
        // select player 1
        menuPlayer = p1;
        break;
       }
     case btnDOWN:
       {
        // select player 2
        menuPlayer = p2;
        break;
       }
     case btnNONE:
       {
       // display the current value for minutes
       lcd.print(menuPlayer.minutes);
       break;
       }
     }
 } else {
   // Main timer code
   }
}

A: You're making a copy of your Players:
// The actual players
Player p1 = {5, false, 1, "P1 mins: ", 0};
Player p2 = {5, false, 2, "P2 mins: ", 0};

// A COPY of player 1
Player menuPlayer = p1;

When you make calls like
menuPlayer.IncrementMinutes();

You are simply changing menuPlayer, not p1 or p2. So when you do the following
menuPlayer = p2;

All the changes made to menuPlayer are lost, and you make a new copy.
You could fix this by copying menuPlayer into p1 before swapping:
p1 = menuPlayer;
menuPlayer = p2;

Or by making menuPlayer a Player*:
// Point to p1:
Player* menuPlayer = &p1;

// Changes p1
menuPlayer->IncrementMinutes();