text:
Q: How can I populate a vector with my functions? #include <iostream>
#include<string>
#include<vector>
#include<functional>
using namespace std;
void straightLineMethod();
void unitsOfActivity();
void decliningMethod();

int main()
{
    using func = std::function<void()>;
    string inputMethod;
    string depreciation[3] = { "straight line","units of activity","declining" };
    std::vector<func> functions;
    functions.push_back(straightLineMethod);
    functions.push_back(unitsOfActivity);
    functions.push_back(decliningMethod);
    cout << " Enter the method of depreciation you're using: " << depreciation[0] << ", " << depreciation[1] << " , or " << depreciation[2] << endl;
    cin.ignore();
    getline(cin, inputMethod);
    for (int i = 0; i <functions.size() ; i++) {
        while(inputMethod == depreciation[i])
        {
            functions[i]();
        }
}

I tried researching the answer and learned about using std::function, but I don't completely understand what it does. It's pretty hard to find an answer related to this question online. Essentially, what I want to is have the three functions put inside of a vector, compare user input to the string array , and then use the index in the array to use the correlating index in the vector to call the function . It seemed like a good idea to me but it failed. And using .push_back to try to populate the vector in this instance is giving me a
E0304 error:  no instance of overloaded function matches the argument list.

Edit: Specifically, I dont know what the syntax: using func= std::function<void()> is actually doing. I just added it to the code to try to get it to work , thats why my understanding is limited in troubleshooting here.

Edit: the E0304 error is fixed by correcting the syntax to reference the function instead of calling it. And i changed functions[i] to functions[i]() to call the functions, although it is still not working.

A: Looks like you've mixed up the function call syntax, and passing an actual (reference to a) function. In your functions.push_back(functionNameHere) remove the inner (), you don't want to call that function, you want to push the function itself to the vector. From the other side, your functions[i] should be functions[i](), cause here you are actually calling the function.
For example, this definitely works:
void testMethod()
{
    cout << "test method has been called\n";
}

int main()
{
    using func = std::function<void()>;
    std::vector<func> functions;
    functions.push_back(testMethod);
    functions[0]();
}

See it running here - http://cpp.sh/2xvnw


text:
Q: Using Breadboard Power Rails for i2c Bus I'm working on a raspberry pi project that will use about a dozen i2c devices (mostly mcp23017s) and the wiring is getting a little crazy. Are there any downsides to routing SDA and SDL to one of the power rails and using them as a sort of bus?

A: i2c is time dependant.  Most devices have limited pull down capability so that limits the size of the pull up resistor you can use.
Using larger pull up resistors with additional capacitance from the additional devices will limit your rise time.
Your rise time will limit you data rate.
So be sure to understand what is the smallest resistor value all of of your i2c devices can use, what is the total capacitance you have from all the devices, and there what is the fastest speed (or working from desired speed maximum number of devices).
Using the rails on a bread board will increase your stray capacitance, hence limit your rise time and speeds.
You can always check your rise time using a scope to ensure your timing will not be effected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create new string by replacing with string from another file in awk/linux I have two files as shown below:
FileA:
AGCTTTTCATTC...

FileB:
POS ID  REF ALT
 2   .   G   C
 8   .   C   -
 12  .   -   T

POS column in FileB: gives the string position in FileA: i.e 2 under POS means second letter "G" in the sequence in FileA.
Based on the POS column in FileB, FileA should be modified to FileA'and FileB'as shown below.
FileA' is formed by inserting string under REF column at respective positions in POS column
FileB' is formed by replacing string under ALT column at respective positions in POS column. And
FileA':
AGCTTTTCATT-TC...

FileB':
ACCTTTT-ATTTTC...

A: Perl solution:
#!/usr/bin/perl
use warnings;
use strict;

open my $DNA, '<', 'FileA' or die $!;
open my $POS, '<', 'FileB' or die $!;

my $dna = <$DNA>;
my $ref_out = $dna;
my $alt_out = $dna;
while (<$POS>) {
    my ($pos, $id, $ref, $alt) = split;
    next unless $pos =~ /^\d+$/; # Skip the header.
    substr $ref_out, $pos - 1, 1, $ref;
    substr $alt_out, $pos - 1, 1, $alt;
}
open my $REF, '>', "FileA'" or die $!;
print {$REF} $ref_out;
close $REF;

open my $ALT, '>', "FileB'" or die $!;
print {$ALT} $alt_out;
close $ALT;

You just keep two copies of the input string and modify it via substr for each line of FileB.


text:
Q: Narrowing down an array of intersections to best-fit the original contour I am making my own document scanner pipeline, this is good to note since image-specific methods of finding corners/contours..etc tend to be ineffective for a range of different images. I have found the best contour of the document and have retrieved an array of lines and their corresponding intersections.
Image with contour:

I am trying to narrow down all the lines/intersections to best fit the original contour, so I can get my 4 corner points of the document. I have tried narrowing it down based on the inner-angle of the intersections, then picking the best 4 intersections.
Image with line intersections with 90°(+-10°) interior angles (Green are the 4 best angles):

As you can see, the outcome is not ideal, I can make a rectangle with the green lines, and while it's the closest to a true rectangle, it's not the closest to the previous contour around the receipt.
What methods can I use to further narrow this down to pick intersections that better represent the shape of the original contour?
Reference Images:
Original Image:

Edged:


text:
Q: Contiguous subarray of floating numbers sums to integer algorithm Suppose we have an array A of size n, there are n unsorted floating point numbers. We want to find a contiguous subarray B such that B sums to an integer. Suppose we can use floor function at cost of O(1). Note that we need to return B if such B exists.
My idea:
rsum = running sum of A(i.e. rsum[i]=A[1]+A[2]+...+A[i])
for i from 1 to n:
   for j from i to n:
      e = rsum[j]-rsum[i]+A[i]
      if e==floor(e)
         return A[i....j]
return "no such subarray"

This is an O(n^2) algorithm, is there a way to do that in o(n^2)?

A: If we ignore floating point calculation errors, then we can put fractional parts of running sums into a map and check whether the same fraction exists twice - (close to) O(n) approach.
Considering precision issues, we can sort fractions (or put them into sorted container like RB tree) and get the smallest difference - O(nlogn) approach


text: Q: Is there a bug or a catch with the achievement for landing a combo after time is up in fruit ninja? So I've had this achievement sitting in my list since forever it seems like. It wants me to land a combo after time is up in zen mode. It's pretty simple, really. I've landed multiple combos after the timer hit 0 and the bell sound rang. Yet here sits this achievement, still saying it's not complete. Is there a known issue with this achievement, or is there a catch that I haven't been meeting? What else could it possibly want me to do?


text:
Q: What can be explanation for anamolus behavior of graph of equation $y=xy\cos(9^{f(x,y)})$ I was playing with graphs of desmos graph plotter and found this function
$$y=xy\cos(9^{f(x,y)})$$

If i substitute $f(x,y)$ with any function in $x$, $y$ i get some scattered points creating the function graph much more better illustration in graph picture what could be the reason for this is it some technical problem or something?


text:
Q: Where can I find an online list of CentOS packages and their versions? I am looking for an online list of the standard packages available for CentOS Linux.
I know that if I had a CentOs system running, I could use yum to list packages. However, I am trying to evaluate what roadblocks we will run into, when we switch our webservers from Ubuntu to CentOS, and I don't yet have a CentOS setup.
I've searched and searched, but all I can find are explanations of how to manage packages once you actually have a CentOS system setup. Any website recommendations would be appreciated.

A: This mirror seems to be kept up-to-date:
http://mirror.centos.org/centos/7/os/x86_64/Packages/

A: See https://pkgs.org/ which allows you to search a range of CentOS (and other) distributions.

A: I started with this, which got me a list of CentOS mirrors, and then picked the first mirror.
Here's a list of packages for CentOS 6.
If the particular mirror lsited here is dead, you can simply find another mirror by returning to the list of mirrors and follow the same logic.

A: take a look at any mirror
http://centos.mirror.nexicom.net/6/os/x86_64/Packages/


text:
Q: JQuery not appending div tag with attributes from a JS function object I'm trying to print out a block onto the browser window using JQuery. I made the block attributes into a JS object class via function. In this code I am using the "use strict"; method.
The HTML(5):
<!DOCTYPE html>
<TITLE>Logo Experiment</TITLE>

<meta charset="utf-8">

The JS/JQuery:
"use strict";

function Box(width, height, style) {//box object
width = this.width;
height = this.height;
style = this.style;
};

var lbx = new Box(256, 256, "bx"); //"lbx" is "logo box"

$(document).ready(function(){//appending a div to the  tag directly
$("
").appendTo("body");
});

Whenever I try to append the block with JQuery using the JS object attributes, I end up with this output:

Any help is much appreciated.
Sincerely, CA1K.

A: You got it backwards here. It should be this.parameter = paramter:
function Box(width, height, style) {//box object
width = this.width;
height = this.height;
style = this.style;
};

Like this:
function Box(width, height, style) {//box object
    this.width = width;
    this.height = height;
    this.style = style;
    };

The first way does nothing other than setting the call arguments to undefined (since none of the properties there are defined).


text:
Q: VS for Mac - Using Autolayout for landscape and portrait views I need help, having spent the day searching through various youtube videos and google etc I've hit that wall!
I'm using Visual Studio for Mac and basically, my Logon screen looks good in Portrait but not so in Landscape so I want to show a different view with a redesigned screen especially for Landscape.
Microsoft Forums suggest that I use the OnSizeAllocated event to work out the orientation which sounds fine but I just can't work out how you do that.
I have on View Controller which doesn't have any events.  I have one View and that doesn't have any events.  If I try to add the code in manually into the ViewControllers class it doesn't like it.  If I try and add it in Main.cs it doesn't like it or AppDelegate.cs it doesn't like it.
Designing screens to match the orientation must be like breathing air but for the life of me I just can't work it out and I'm suffocating here!
What am I missing?

A: So from the comments, I see you're using Visual Studio for Mac (VS4M)  as your IDE and you are using the single view template app but are trying to get the view to adapt to landscape and portrait.
If you open your storyboard in VS4M you should see something like this:

I have added some controls (image, username, password, and login button) in the next image just to show how I would create the layout using the iOS designer in VS4M

The key point here is to change to landscape and the press the Edit Traits > Edits apply to Compact Height only
You can read more about Size Class (Compact/Regular) here but this is a good image to get your head around it:

The Next step is to do the Autolayout for the username, password and login button.

You'll then have a view like this:

I have uploaded this to my GitHub just so you can have a look if you want the link is here.
Autolayout is one of the more difficult areas to get your head round in Xamarin.iOS development so I wouldn't be disheartened. Also, this link is good for more information on Autolayout with VS4M
If you are not doing in Autolayout but rather in code then if you could post that code, I can take a look and help.
Update - Adaptive layout
So to actually change/remove certain constraints for landscape/portrait you have to use the installed property. Here I am changing the image's center constraint to only be installed when in Any width and Regular height (aka portrait) and then having its left(leading) constraint to be installed when in 'Any' width and 'Compact' height (aka landscape)

Then to make it nicer I moved the login and password text boxes to the right of that. Firstly I have to make the current Username textbox Vertical Alignment constraint installed only on width Any and height Regular(portrait) then create a new top constraint to the top of the super view in width Any and height Compact(landscape).

Then the last bit is to have the leading(left) Horizontal Spacing constraints of the Username and password textboxes installed only on width Any and height Regular(portrait) and create two new leading(left) Horizontal Spacing constraints set to the trailing(right) of the image installed on width Any and height Compact(landscape), Rememeber to make the constant of those constraints 0 (and hit enter on your keyboard to set the value) like so:

Then the app will look like this:

I have updated my GitHub solution with this implementation. Sorry for all the images but I think its best to explain Autolayout with images.


text:
Q: SQL Error: ORA-00907: missing right parenthesis 00907. 00000 - "missing right parenthesis" I don't know what is wrong with this syntax.
create table table3 (
id number,
id_table1 number,
id_table2 number,
area varchar2(130) not null,
status varchar2(20),
additional_info varchar2(100),
data date default sysdate,
responsable varchar2(60) not null,
constraint ck_status_contract check(status in('value1','value2','value3')),
constraint fk_id_table1 references table1 on delete set null,
constraint fk_id_table2 references table2 on delete set null,
constraint pk_id_contract primary key(id)
);

The result is:

SQL Error: ORA-00907: missing right parenthesis
  00907. 00000 -  "missing right parenthesis"

I use OracleXE112_Win64.

A: On your FK you need to specify the columns affected on both ends
CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1,..)

A: You have missed to add foreign key references properly.
To specify foreign key constraint, you should either use inline
CONSTRAINT [constraint_name] FOREIGN KEY(customer_id) REFERENCES [master_table_name]([master_column_name])

See more example from this tutorial: What is foreign key?
Resource Link:
SQL Error: ORA-00907: missing right parenthesis


text:
Q: Does anyone have a working example for serverside datagrid pagination of Clarity? Does anyone have a working example for serverside datagrid pagination of Clarity?
Please share me a stackblitz or plunker link.

A: The Clarity website has one such example but here is the full example that you could use. Note it doesn't call a server, but it does the same thing by creating and destroying the array (which happens with an API call).
https://github.com/vmware/clarity/tree/master/src/dev/src/app/datagrid/server-driven


text:
Q: C memory allocation affects char array length #include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {

  //Step 1
  char *key = malloc(10000);
  int *arr = malloc(sizeof(int));
  free(arr);
  free(key);

  //Step 2
  char *msg = malloc(10000);
  printf("Size: %zu \n", strlen(msg));
  free(msg);

  return 0;
}

Could someone explain this:

*

*if I execute both step 1 and 2, the length of msg will be 6, sometimes 4

*if I exectue both step 1 and 2, but without the allocation and freeing of key, the length is 0

*if I execute only step 2, the length of msg will be 0

why does the allocation of the int and key array affect the length of a char array?
I realize that strlen requires a '\0' char, but why does it behave different?

A: char *msg = malloc(10000);
printf("Size: %zu \n", strlen(msg));

msg is allocated, but not initialized, so it is undefined behavior to call strlen(msg).
In your cases, perhaps it just happens that in the uninitialized memory allocated by malloc, the first 0 appeared at different places.

A: strlen() assumes a null-terminated string.  If you don't initialize your array, then all bets are off.  This is called "undefined behavior".
One easy fix is to use calloc(), which initializes all bytes to "zero".

A: Allocation and initialization are different things. In your program, you are allocating memory (with malloc), but you are never initializing it. The C language makes no guarantees about the contents of un-initialized heap-space memory.
In practice, the memory's contents will not be random, but it will take the value of whatever was in that place in memory previous to you allocating it. But, don't rely on any particular behavior you observe, as it could (and will) change from run-to-run or from day-to-day.


text:
Q: Moving from $x^2+x+1=0$ to $x+1+\frac1x=0$ seems to introduce a solution, how is this possible? I recently saw this: ($x\in\mathbb{C}$)

*

*$$x^2+x+1=0,x\neq0,\pm1$$

*$$x+1+\frac{1}{x}=0$$
  Plugging (2) into (1) we get $x^2-\frac{1}{x}=0$ so $x=1$

Why does this happen? I know that eq. (1) has solutions $x=\frac{-1\pm\sqrt{-3}}{2}$, and that these still are solutions for eq. (2), but where is the extra solution $x=1$ coming from? (And why is that step not valid? Is it like squaring both sides?)

A: Another way to look at this.

*

*$$x^2 + x + 1 = 0, x \neq 0, \pm 1$$

*$$x + 1 + \frac{1}{x} = 0$$

*$$x^2 - \frac{1}{x} = 0$$

*$$x = 1$$

We're asking for 'the solutions' to 1. What does that mean? It means, find the set of numbers, $X \subset \mathbb{C}$ with
$$x \in X \iff 1.$$
We know that

*

*$\implies$ 2.

And clearly 2. $\implies$ 1.
So 1. $\iff$ 2.
We know that, together,

*

*and 2. $\implies$ 3.

BUT, it is not the case that

*$\implies$ 1.

This is an assumption that is implicit in the 'proof' given.
We also know that

*$\implies$ 3.

BUT, again, it is not the case that

*$\implies$ 4.

With these implications made explicit, it should be clear why this reasoning is unsound. We are effectively making the claim that 4. $\implies$ 1!
The particular fallacy is called Affirming the Consequent because we 'affirm' the right hand of an implication, and fallaciously deduce from that that the left hand must be true.
This kind of fallacy is particularly common when 'equational' reasoning is used without making the implications explicit.

A: In effect, you have taken the equation
$$x^2+x+1=0,$$
divided by $x$ to get
$$x+1+\frac1x=0$$
and then multiplied by $x-1$ to get
$$x^2-\frac1x=0.$$
The extraneous root $1$ is the solution of $x-1=0$, and $x-1$
is the factor you multiplied by.

A: If $$x^2-\dfrac{1}{x}=0,$$ then $$\frac{x^3-1}{x}=0;$$ but note that $$\frac{x^3-1}{x} =\frac{(x-1)(x^2+x+1)}{x}=0,$$ so you just basically multiplied both sides of $(1)$ by $(x-1)$.

A: When you perform equation (1) - equation (2), you are multiplying $\left(1-\frac1x\right)$ to both sides of equation (1):
$$\begin{align*}
x^2+x+1 &= 0\\
(x^2+x+1)\left(1-\frac1x\right) &= 0\\
x^2 - \frac1x &= 0
\end{align*}$$
So you introduced the root $\frac1x = 1$, i.e. $x=1$.


text:
Q: React-lazy-load-image-component: how to add a transition? I have a list of images made with React-lazy-load-component library, it works very well, but I can't have any transition effect, as promised by the documentation.
Here is my code:

const LazyPicture = styled(LazyLoadImage)`
  object-fit: cover;
  width: ${({ width }) => (width ? `${width}px` : "100%")};
  height: ${({ width }) => (width ? `${width}px` : "100%")};
  &.lazy-load-image-background.opacity {
  background-image: none !important;
  opacity: 0;
  }

  &.lazy-load-image-background.opacity.lazy-load-image-loaded {
  opacity: 1;
  transition: opacity .3s;
  }
`;

 //(...)

       <LazyPicture
        src={image}
        width={width}
        height={height}
        effect="opacity"
      />

Since importing the css file doesn't work, I have directly written the css source code in my styled-component. With no success so far.
How to fix this?

A: You should move transition to scope before it's loaded. Consider trying this code.
const LazyPicture = styled(LazyLoadImage)`
  object-fit: cover;
  width: ${({ width }) => (width ? `${width}px` : "100%")};
  height: ${({ width }) => (width ? `${width}px` : "100%")};

  &.lazy-load-image-background.opacity {
    background-image: none !important;
    opacity: 0;
    transition: opacity .3s;
  }

  &.lazy-load-image-background.opacity.lazy-load-image-loaded {
    opacity: 1;
  }
`;


text:
Q: How do I identify if a character/symbol is a number or not? I'm doing a simple calculator using Ruby as practice. Everything is fine except how do I identify if a character/symbol I input is a number or not using if-else statement.
For example:
Enter first number: a
Error: Enter correct number
Enter first number: -
Error: Enter correct number
Enter first number: 1
Enter second number:b
Error: Enter correct number
Enter second number: 2
Choose operator (+-*/): *
The product is: 2

This is the code I input first:
print "Enter first number: "
x = gets.to_i
print "Enter second number: "
y = gets.to_i
print "Choose operator (+-*/): "
op = gets.chomp.to_s

I will use if-else statement to identify if the number input is a number or not

A: If you wish to test if the string represents an integer or float use Kernel#Integer or Kernel#Float with the optional second argument (a hash) having the value of the key :exception equal to false.
For example,
Integer('-123', exception: false)
  #=> -123
Integer("0xAa", exception: false)
  #=> 170
Integer('12.3', exception: false)
  #=> nil,
Integer('12a3', exception: false)
  #=> nil

Float('123', exception: false)
  #=> 123.0
Float("1.2e3", exception: false)
  #=> 1200.0
Float('12a3', exception: false)
  #=> nil,
Float('1.2.3', exception: false)
  #=> nil

Note
Integer("123\n", exception: false)
  #=> 123

shows you don't have to chomp before testing if the string represents an integer (similar with Float).
Some of the examples illustrate a limitation or complication when using a regular expression to test whether a string represents an integer or float.

A: Create a new String method
irb(main):001:0> class String
irb(main):002:1>   def number?
irb(main):003:2>     Float(self) != nil rescue false
irb(main):004:2>   end
irb(main):005:1> end

irb(main):012:0> x = gets
1
=> 1
irb(main):013:0> x.number?
=> true

irb(main):009:0> x = gets
s
=> "s\n"
irb(main):010:0> x.number?
=> false

A: This typical way to do this would be to match it with a regexp:
x = gets.chomp
if x.match?(/^\d+$/)
  puts "#{x} is a number"
else
  puts "#{x} is not a number"
end

This tests if the given string matches the pattern ^\d+$, which means "start of line, one or more digit characters, then end of line". Note that this won't match characters like "," or "." - only a string of the digits 0-9. String#match? will return a boolean indicating if the string matches the given pattern or not.

A: use this ruby method
.is_a?(Integer)

For example:
input = gets.chomp
input.is_a?(Integer) # => true || false


text:
Q: I am getting this warning Warning: Error loading I am upgrading from rails 2.3 to rails 3.2. I have models divided into sub folders. Just like there is a model app/models/ad/ad.rb the other app/models/ad/ad_city.rb but inside the model it is written as:
class Ad < ActiveRecord::Base
class AdCity < ActiveRecord::Base

and not:
class Ad::Ad < ActiveRecord::Base
class Ad::AdCity < ActiveRecord::Base

I have in my application.rb:
config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]

even I tried including each folder in config.autoload_paths. But it give me a thousand lines warning:
Warning: Error loading /home/deep/projects/upgrade/models/myapp/app/models/ad/ad_city.rb:
uninitialized constant Ad::AdCity
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/inflector/methods.rb:230:in `block in constantize'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/inflector/methods.rb:229:in `each'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/inflector/methods.rb:229:in `constantize'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/core_ext/string/inflections.rb:54:in `constantize'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/thinking-sphinx-2.0.11/lib/thinking_sphinx/context.rb:64:in `block (2 levels) in load_models'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/thinking-sphinx-2.0.11/lib/thinking_sphinx/context.rb:54:in `each'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/thinking-sphinx-2.0.11/lib/thinking_sphinx/context.rb:54:in `block in load_models'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/thinking-sphinx-2.0.11/lib/thinking_sphinx/context.rb:53:in `each'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/thinking-sphinx-2.0.11/lib/thinking_sphinx/context.rb:53:in `load_models'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/thinking-sphinx-2.0.11/lib/thinking_sphinx/context.rb:15:in `prepare'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/thinking-sphinx-2.0.11/lib/thinking_sphinx.rb:81:in `block in context'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/thinking-sphinx-2.0.11/lib/thinking_sphinx.rb:78:in `synchronize'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/thinking-sphinx-2.0.11/lib/thinking_sphinx.rb:78:in `context'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/thinking-sphinx-2.0.11/lib/thinking_sphinx/active_record.rb:162:in `define_index'
/home/deep/projects/upgrade/models/myapp/app/models/user/user_indexes.rb:6:in `included'
/home/deep/projects/upgrade/models/myapp/app/models/user/user.rb:295:in `include'
/home/deep/projects/upgrade/models/myapp/app/models/user/user.rb:295:in `<class:User>'
/home/deep/projects/upgrade/models/myapp/app/models/user/user.rb:1:in `<top (required)>'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/bundler/gems/rails-dev-boost-bf49caca6670/lib/rails_development_boost/dependencies_patch.rb:364:in `block in load_file_with_constant_tracking_internal'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/bundler/gems/rails-dev-boost-bf49caca6670/lib/rails_development_boost/dependencies_patch.rb:240:in `now_loading'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/bundler/gems/rails-dev-boost-bf49caca6670/lib/rails_development_boost/dependencies_patch.rb:364:in `load_file_with_constant_tracking_internal'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/bundler/gems/rails-dev-boost-bf49caca6670/lib/rails_development_boost/dependencies_patch.rb:234:in `block in load_file_with_constant_tracking'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/bundler/gems/rails-dev-boost-bf49caca6670/lib/rails_development_boost/dependencies_patch.rb:383:in `async_synchronize'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/bundler/gems/rails-dev-boost-bf49caca6670/lib/rails_development_boost/dependencies_patch.rb:229:in `load_file_with_constant_tracking'
/home/deep/projects/upgrade/models/myapp/lib/authenticated_system.rb:108:in `login_from_session'
/home/deep/projects/upgrade/models/myapp/lib/authenticated_system.rb:24:in `current_user'
/home/deep/projects/upgrade/models/myapp/lib/authenticated_system.rb:14:in `logged_in?'
/home/deep/projects/upgrade/models/myapp/app/controllers/application_controller.rb:288:in `set_timezone'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/callbacks.rb:429:in `_run__402496120916004207__process_action__1098406492416702350__callbacks'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/callbacks.rb:405:in `__run_callback'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/callbacks.rb:385:in `_run_process_action_callbacks'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/callbacks.rb:81:in `run_callbacks'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/abstract_controller/callbacks.rb:17:in `process_action'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_controller/metal/rescue.rb:29:in `process_action'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_controller/metal/instrumentation.rb:30:in `block in process_action'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/notifications.rb:123:in `block in instrument'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/notifications.rb:123:in `instrument'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_controller/metal/instrumentation.rb:29:in `process_action'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_controller/metal/params_wrapper.rb:207:in `process_action'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activerecord-3.2.19/lib/active_record/railties/controller_runtime.rb:18:in `process_action'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/abstract_controller/base.rb:121:in `process'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/abstract_controller/rendering.rb:45:in `process'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_controller/metal.rb:203:in `dispatch'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_controller/metal.rb:246:in `block in action'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/routing/route_set.rb:73:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/routing/route_set.rb:73:in `dispatch'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/routing/route_set.rb:36:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/journey-1.0.4/lib/journey/router.rb:68:in `block in call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/journey-1.0.4/lib/journey/router.rb:56:in `each'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/journey-1.0.4/lib/journey/router.rb:56:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/routing/route_set.rb:608:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/exception_notification-4.0.1/lib/exception_notification/rack.rb:28:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/bundler/gems/rails-dev-boost-bf49caca6670/lib/rails_development_boost/async.rb:14:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/rack-1.4.5/lib/rack/etag.rb:23:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/rack-1.4.5/lib/rack/conditionalget.rb:25:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/head.rb:14:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/params_parser.rb:21:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/flash.rb:242:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/rack-1.4.5/lib/rack/session/abstract/id.rb:210:in `context'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/rack-1.4.5/lib/rack/session/abstract/id.rb:205:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/cookies.rb:341:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activerecord-3.2.19/lib/active_record/query_cache.rb:64:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activerecord-3.2.19/lib/active_record/connection_adapters/abstract/connection_pool.rb:479:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/callbacks.rb:405:in `_run__2960753221531180313__call__4371824738127159201__callbacks'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/callbacks.rb:405:in `__run_callback'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/callbacks.rb:385:in `_run_call_callbacks'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/callbacks.rb:81:in `run_callbacks'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/callbacks.rb:27:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/reloader.rb:65:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/remote_ip.rb:31:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/better_errors-2.0.0/lib/better_errors/middleware.rb:84:in `protected_app_call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/better_errors-2.0.0/lib/better_errors/middleware.rb:79:in `better_errors_call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/better_errors-2.0.0/lib/better_errors/middleware.rb:57:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/railties-3.2.19/lib/rails/rack/logger.rb:32:in `call_app'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/railties-3.2.19/lib/rails/rack/logger.rb:16:in `block in call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/tagged_logging.rb:22:in `tagged'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/railties-3.2.19/lib/rails/rack/logger.rb:16:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/request_id.rb:22:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/rack-1.4.5/lib/rack/methodoverride.rb:21:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/rack-1.4.5/lib/rack/runtime.rb:17:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/activesupport-3.2.19/lib/active_support/cache/strategy/local_cache.rb:72:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/rack-1.4.5/lib/rack/lock.rb:15:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/actionpack-3.2.19/lib/action_dispatch/middleware/static.rb:63:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/railties-3.2.19/lib/rails/engine.rb:484:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/railties-3.2.19/lib/rails/application.rb:231:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/rack-1.4.5/lib/rack/content_length.rb:14:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/railties-3.2.19/lib/rails/rack/log_tailer.rb:17:in `call'
/home/deep/.rvm/gems/ruby-2.1.2@upgrade_mygemset/gems/rack-1.4.5/lib/rack/handler/webrick.rb:59:in `service'
/home/deep/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/webrick/httpserver.rb:138:in `service'
/home/deep/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/webrick/httpserver.rb:94:in `run'
/home/deep/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/webrick/server.rb:295:in `block in start_thread'

for all the models. It doesn't throw any error just gives warning each time my app makes any connection with the database. What should I do. Please help


text:
Q: pgAdmin4 v4: TypeError: string indices must be integers When I open pgAdmin4 v4 on Windows 10, the dashboard displays
An error occured whilst rendering the graph
on all charts. The link (1) told me that the logs on windows are at
Windows log location: C:\Users\YOUR_USERNAME\AppData\Roaming\pgAdmin\pgadmin4.log
The logs contained numerous times the same error
2019-05-10 10:01:32,139: ERROR  flask.app:  string indices must be integers
Traceback (most recent call last):
  File "C:/Program Files (x86)/pgAdmin 4/v4/venv/Lib/site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:/Program Files (x86)/pgAdmin 4/v4/venv/Lib/site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:/Program Files (x86)/pgAdmin 4/v4/venv/Lib/site-packages\flask_login\utils.py", line 261, in decorated_view
    return func(*args, **kwargs)
  File "C:\Program Files (x86)\pgAdmin 4\v4\web\pgadmin\dashboard\__init__.py", line 251, in wrap
    return f(*args, **kwargs)
  File "C:\Program Files (x86)\pgAdmin 4\v4\web\pgadmin\dashboard\__init__.py", line 371, in dashboard_stats
    for chart_row in res['rows']:
TypeError: string indices must be integers

I can also not open any databases(pressing the databases button doesn't unfold the list of databases) via pgAdmin4 v4.
Since I was working with the permissions of my users on certain databases, this has probably to do with it. The commands I recall running are
REVOKE ALL ON DATABASE Database_Name FROM Database_User;
REVOKE ALL ON DATABASE Database_Name FROM PUBLIC;

To verify that I did not completly corrupt my databases and the error is just weird I logged in with the admin user via psql. Running \du and \l did not show anything was off.
What Should I do to fix this?
(1) https://stackoverflow.com/questions/41766323/pgadmin4-dashboard-does-not-display-sessions
-- edit --
DataGrip doesn't seem to have the problem either.

A: I have the same problem in Ubuntu 18.04 with pgAdmin 4.11 and postgres 11.
What works for me is to go to the process list and kill the pgadmin4 process and reload it. You may do it from Task Manager on windows. Good luck.
BTW Datagrip always work fine for me too.

A: Please use Internet Explorer for this issue. I have same error message on Google chrome. My chrome version is Version 77.0.3865.90 (Official Build) (64-bit)


text:
Q: Split string on * character regex I am attempting to split a string in two on the '*' character, I have the following sentence : This is * test string
and I have written this code
            Regex regex = new Regex(@"\\*");
            string[] substrings = regex.Split(text);

            foreach (string match in substrings)
            {
                Console.WriteLine("'{0}'", match);
            }

But I get the following output:
'T'h'i's' 'i's'....

But I desire:
'This is ' ' test string'

Any ideas how to correct my regex?
Edit : My sentence may have more than one '*' character, in which case i would need three sentences, e.g :
This is * test *

A: Remove the double escape from you regular expression:
Regex regex = new Regex(@"\*");

...
Regex regex = new Regex(@"\*");
String text = "This is * test * more * test";
string[] substrings = regex.Split(text);

foreach (String match in substrings)
         Console.WriteLine("'{0}'", match);

Output
'This is '
' test '
' more '
' test'

A:
"I may have more than one '*' in a sentence, will String.split work?"

Yes, you can achieve what you're trying to do with String.Split() as well:
var text = "This is * test *";

var substrings = text.Split('*');

This will give you an array with three strings.

"This is "
" test "
""

The final string is an empty string, which you can omit by using the method overload that accepts a StringSplitOptions value:
var substrings =
    text.Split(new[] {'*'}, StringSplitOptions.RemoveEmptyEntries);

A: As per your expected output below code might help:
string text = "This is * test string";
Regex regex = new Regex(@"\*");
string[] substrings = regex.Split(text);
string output = "";
foreach (string match in substrings)
{
    output += match;
}
Console.WriteLine(output);


text:
Q: How to replace files in a folder by webpack's config in JHipster? I want to replace files in a folder by webpack's config in JHipster. For example, dev-config replaces files in "webapp/app/home" folder with "environments/dev/home".
I know @angular-devkit/build-angular:browser in pure Angular can replace files in configurations, but it is not used in JHipster and does not seem to be able to replace files in a folder.

A: Thank you for your help, but I cannot understand your suggestions.
Finally, I have decided getting the all files under a folder and set to hostReplacementPaths in AngularCompilerPlugin.
I wrote as below.
tenant-util.js
const TENANT_ARG_KEY = '--tenant=';

module.exports = {
    getTenant
};

/**
 * webpack arg example: --tenant=company1
 * @param {string[]} argv process.argv
 */
function getTenant(argv /* : string[] */) /* : string */ {
    if (!Array.isArray(argv)) {
        return '';
    }

    for (let i = 0; i < argv.length; ++i) {
        if (!argv[i].startsWith(TENANT_ARG_KEY)) {
            continue;
        }
        return argv[i].substr(TENANT_ARG_KEY.length);
    }

    return '';
}

webpack.common.js
const tenantUtils = require('./tenant-utils');
const tenant = tenantUtils.getTenant(process.argv);

const hostReplacementPaths = {};
if (tenant) {
    const glob = require('glob');
    const replaceToFolder = `environments/${tenant}`;
    const filenamesInEnvironment = glob.sync(`./src/${replaceToFolder}/**/*.*`);
    if (!filenamesInEnvironment) {
        throw Error('check the tenant setting');
    }
    for (const filename of filenamesInEnvironment) {
        const originalFilename = filename.replace(replaceToFolder, 'main/webapp')
        hostReplacementPaths[originalFilename] = filename;
    }
}

...
        new AngularCompilerPlugin({
            mainPath: utils.root('src/main/webapp/app/app.main.ts'),
            tsConfigPath: utils.root('tsconfig.app.json'),
            sourceMap: true,
            hostReplacementPaths: hostReplacementPaths
        }),


text:
Q: Integral inequality on $\mathbb C$ Suppose $f$ is a holomorphic function on $\mathbb C$ . Suppose for every $z \in \mathbb C$, il exists a positive function $M : \mathbb C \to \mathbb R^+$ such that $|f(z)| \leq M(z)$. Is it true that, for any path $C$, we always have: $\displaystyle\int_C |f(z)| dz \leq \displaystyle\int_C M(z) dz$. If not, what conditions should we impose so that this inequality is true?

A: You can say two things here: first, $\left| \int \limits _C f(z) {\rm d} z \right| \le \int \limits _C | f(z) |  | {\rm d} z |$; second, $\int \limits _C | f(z) | | {\rm d} z | \le \int \limits _C M(z) | {\rm d} z |$. Here, if $c : [a,b] \to \Bbb C$ is a parametrization of $C$, then $| {\rm d} z | = |c' (t)| {\rm d} t$.


text:
Q: Why are the "increment" and "decrement" operators not composable in Kotlin? If I have a var i : Int = 0, then i.inc().inc() works just fine, i.e. inc() is composable with itself. Why then does (i++)++ make Kotlin report the error "Variable expected"?

A: When you call inc(), it returns a new Int and does nothing to the property or variable that held the original value. When you use it as an operator, it is interpreted as also setting the return value on the original property or variable. This cannot conceptually extend to using it as an operator on something that is not a variable or value.

A:
The effect of computing the expression [a++] is:

*

*Store the initial value of a to a temporary storage a0.

*Assign the result of a0.inc() to a.

*Return a0 as the result of the expression.

So if you tried to use i++ as a above to determine the meaning of (i++)++, it would translate to
val i1 = i++
i++ = i1.inc()
i1

Of course, i++ = i1.inc() doesn't make sense (never mind that it would also calculate i++ twice).


text:
Q: Does Node.js support the String.MatchAll method? When I test the code:
let result = 'heymama'.matchAll(/m(a)/g);

I get the error "'heymama'.matchAll is not a function"
When I run the version:
let result = 'heymama'.match(/ma/g);

There's no error.

A: Before Node 12:
As @dennis-vash alredy pointed out, it's currently not supported in Node.js.
There is this "match-all" npm package alternative though.
const matchAll = require("match-all");

let s = "Hello _World_ and _Mars_";
console.log(matchAll(s, /_([a-z]+)_/gi).toArray());
// => [ "World", "Mars" ]

A: #String.matchAll is supported in Node.js from version 12.0.0
Check out the compatibility on MDN.

A: matchAll is available in Node.js starting from v12.0.0


text:
Q: Firewall problem using autofs with NFS-exported mounts I have successfully set up a working NFS server/client system on my local network machines. I love it!
But, having grown weary of the long delay when a mount is not available during boot-time, I decided to take @ridgy up on his suggestion to use autofs to mount the shares instead - using the information from this post.
I had firewall issues before, So, I immediately suspected the ufw might be the reason for the mounts timing out. So, I disabled ufw on server and client. And, sure enough; That got autofs working nicely. So, I am sure the basic configuration is correct.
The only other rules in ufw at this point are ALLOW rules for ports 2078 and 6589. There are no BLOCK rules set up. And, since NFS works fine with ufw on during fstab-controlled mounting, I am a bit confused as to where the blockage is occurring.
So far, I haven't found documentation on what ports/protocols are unique to autofs besides the usual NFS 111,2049 TCP/UDP.
Whenever I re-enable ufw. The shares become inaccessible again.
Any ideas?

@ridgy
After following your advice below to edit nfs-common and nfs-kernel-server.. I triple checked, and the edits were made exactly as shown.
I rebooted and ran...
$sudo netstat -nalp | grep rpc... The output was;
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1220/rpcbind
tcp        0      0 0.0.0.0:32767           0.0.0.0:*               LISTEN      4158/rpc.mountd
tcp6       0      0 :::111                  :::*                    LISTEN      1220/rpcbind
tcp6       0      0 :::32767                :::*                    LISTEN      4158/rpc.mountd
udp        0      0 0.0.0.0:972             0.0.0.0:*                           1220/rpcbind
udp        0      0 0.0.0.0:32767           0.0.0.0:*                           4158/rpc.mountd
udp        0      0 0.0.0.0:111             0.0.0.0:*                           1220/rpcbind
udp6       0      0 :::972                  :::*                                1220/rpcbind
udp6       0      0 :::32767                :::*                                4158/rpc.mountd
udp6       0      0 :::111                  :::*                                1220/rpcbind
unix  2      [ ACC ]     STREAM     LISTENING     15939    1/init              /run/rpcbind.sock
unix  2      [ ]         DGRAM                    49175    4158/rpc.mountd
unix  3      [ ]         STREAM     CONNECTED     48294    1220/rpcbind        /run/rpcbind.sock
unix  3      [ ]         STREAM     CONNECTED     16984    1220/rpcbind
unix  3      [ ]         STREAM     CONNECTED     48275    4157/rpc.idmapd
unix  3      [ ]         STREAM     CONNECTED     48276    4157/rpc.idmapd

OK... So, I wonder... Where is rpc.statd ???
Additionally, my NFS shares (autofs was still disabled) were still visible from the client. even though the firewall had not been updated with the new rpc.mountd port 32767.

A: In the end itwas not that complicated, following the hints in Securing NFS. I modified the files /etc/default/nfs-common and /etc/default/nfs-kernel-server according:
nfs-common:
.
.
# Options for rpc.statd.
#   Should rpc.statd listen on a specific port? This is especially useful
#   when you have a port-based firewall. To use a fixed port, set this
#   this variable to a statd argument like: "--port 4000 --outgoing-port 4001".
#   For more information, see rpc.statd(8) or http://wiki.debian.org/SecuringNFS
STATDOPTS="--port 32765 --outgoing-port 32766"
.
.

nfs-kernel-server:
.
.
# Options for rpc.mountd.
# If you have a port-based firewall, you might want to set up
# a fixed port here using the --port option. For more information,
# see rpc.mountd(8) or http://wiki.debian.org/SecuringNFS
# To disable NFSv4 on the server, specify '--no-nfs-version 4' here
RPCMOUNTDOPTS="--manage-gids --port 32767"
.
.

Why those ports? As 32767 is the highest 15bit-number, it is very unlikely that these ports are already in use by something else.
I am not using quotas, so I did not modify /etc/default/quota as suggested. And I had to reboot after I made these changes. Then I saw the result with
$ sudo netstat -nalp | grep rpc

tcp        0      0 0.0.0.0:32767           0.0.0.0:*               LISTEN      1018/rpc.mountd
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      735/rpcbind
tcp        0      0 0.0.0.0:32765           0.0.0.0:*               LISTEN      806/rpc.statd
tcp6       0      0 :::32767                :::*                    LISTEN      1018/rpc.mountd
tcp6       0      0 :::111                  :::*                    LISTEN      735/rpcbind
tcp6       0      0 :::32765                :::*                    LISTEN      806/rpc.statd
udp        0      0 0.0.0.0:875             0.0.0.0:*                           735/rpcbind
udp        0      0 127.0.0.1:982           0.0.0.0:*                           806/rpc.statd
udp        0      0 0.0.0.0:32765           0.0.0.0:*                           806/rpc.statd
udp        0      0 0.0.0.0:32767           0.0.0.0:*                           1018/rpc.mountd
udp        0      0 0.0.0.0:111             0.0.0.0:*                           735/rpcbind
udp6       0      0 :::875                  :::*                                735/rpcbind
udp6       0      0 :::32765                :::*                                806/rpc.statd
udp6       0      0 :::32767                :::*                                1018/rpc.mountd
udp6       0      0 :::111                  :::*                                735/rpcbind
unix  2      [ ACC ]     STREAM     LISTENING     11412    735/rpcbind         /run/rpcbind.sock
unix  2      [ ]         DGRAM                    9521     806/rpc.statd
unix  2      [ ]         DGRAM                    9614     1018/rpc.mountd
unix  3      [ ]         STREAM     CONNECTED     11721    862/rpc.idmapd
unix  3      [ ]         STREAM     CONNECTED     11722    862/rpc.idmapd

As you can see, the ports rpc.mountd and rpc.statd are listening to are now static.
When entering showmounton the client(here 192.168.192.20), Wireshark shows the communication (server is 192.168.192.111). Important here: The GETPORT Call and the GETPORT reply, which returns Port:32767. The communication then uses this port.

Now you should be able to modify the firewall rules according, and then use showmountand autofs through firewall.
Just for the record
Following the hints in the comments and my own experience, I found different behaviour in different distributions:

*

*In current raspbian jessie (based on debian), there is a service nfs-common (file /etc/init.d/nfs-common), which when enabled starts e.g. rpc.statd at boot, respecting the port settings in /etc/default/nfs-common.

*In current Ubuntu 16.04 there is no such service. rpc.statdis not started at boot, as it is not needed with NFS V4. But as soon as mount .... -o nfsvers=3 is done, rpc.statd is started, respecting the port settings in /etc/default/nfs-common.

I did not find a consistent documentation on that; in How to configure NFS the file /etc/init.d/nfs-common is explicitly mentioned, although it is not in the package. If anyone has hints/links on that it would be richly deserved.
One more remark: man rpc.mountd and man rpc.statd say (for option --port):
"If this option is not specified, rpc.statd will try to consult /etc/services, if gets port succeed, set the same  port  for all listener socket, otherwise chooses a random ephemeral port for each listener socket."
Even when setting the ports in /etc/services (as suggested in the above mentioned wiki), this did not work. So modifying the files in /etc/default seems mandatory - the man pages are not correct at that point.


text:
Q: FFT of an Audio Buffer How do I take the FFT of an AudioBuffer using WebAudioApi ?
AudioBuffer {length: 8575407, duration: 178.6543125, sampleRate: 48000, numberOfChannels: 2}
length: 8575407
duration: 178.6543125
sampleRate: 48000
numberOfChannels: 2
__proto__: AudioBuffer

Visualization Doc calls for stream insted of a buffer
https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API
source = audioCtx.createMediaStreamSource(stream);
source.connect(analyser);

Update
  console.log(buffer);

  source = audioCtx.createBufferSource(buffer);
  source.connect(analyser);
  analyser.connect(audioCtx.destination);

  analyser.fftSize = 2048;
  var bufferLength = analyser.frequencyBinCount;
  var dataArray = new Uint8Array(bufferLength);

  analyser.getByteTimeDomainData(dataArray);

  console.log(analyser);

conosle
AnalyserNode {fftSize: 2048, frequencyBinCount: 1024, minDecibels: -100, maxDecibels: -30, smoothingTimeConstant: 0.8, …}
fftSize: 2048
frequencyBinCount: 1024
minDecibels: -100
maxDecibels: -30
smoothingTimeConstant: 0.8
context: AudioContext {baseLatency: 0.01, destination: AudioDestinationNode, currentTime: 8.04, sampleRate: 48000, listener: AudioListener, …}
numberOfInputs: 1
numberOfOutputs: 1
channelCount: 2
channelCountMode: "max"
channelInterpretation: "speakers"
__proto__: AnalyserNode


text:
Q: Recover Deleted File Stuck In Linux shell process I have a background process that is running for a long time and using a file to write the logs in it. It`s size has increased too large. I just deleted the file and created a new one with the same name and same permission and ownership but the new file does not get any entry.
Old file is marked as deleted and still being used by the process which can clearly be seen by lsof command.
Plz let me know, is there any way that I can recover that file and.
Your positive response will really be much helpful.

A: If the file is still open by some process, you can recover it using the /proc filesystem.
First, check the file descriptor number under which that file is opened in that process. If the file is opened in a process with PID X, use the lsof command as follows:
lsof -p X

This will show a list of files that are currently opened by X. The 4th column shows the file descriptors and the last column shows the name of the mount point and file system where the file lives (ignore the u, r and other flags after the file descriptor number, they just indicate whether the file is opened for reading, writing, etc.)
If the file descriptor number is Y, you can access its contents in /proc/X/fd/Y. So, something like this would recover it:
cp /proc/X/fd/Y /tmp/recovered_file


text:
Q: What is the BBT (ff) disk partition type? What is the BBT (ff) disk partition type?
It appears to be the format used on a USB-connected media player.
Where was it created, with what purpose? What are its typical uses? What are it's advantages and its disadvantages?
Where can I find more information about it.

A: Just about any MBR type collection lists partition type 0xFF as "XENIX Bad Block Table" (hence BBT).
This is most certainly not what the media player uses. It's most likely a proprietary format. You may be able to find information on the net when searching for the specific media player model.


text:
Q: Get Value from within a Function - Bootstrap-Slider What I'm trying to achieve:
Receive both the Height & Weight values from the Bootstrap-Sliders and use these values to work out the BMI.
Current Problems:
Unable to get both the Height & Weight values from within each function due to the .change event.
Open to suggestions and advice,Thank you!
JS
$(function() {
  // Weight
  $('#weight').slider({
    formatter: function(value) {
        return value;
    }
  }).on('slideStop', function(ev){
     $(this).val($(this).data('slider').getValue());
  });
  $('#weight').change(function() {
    var weightval = $('#weight').val();
  });
  // Height
  $('#height').slider({
    formatter: function(value) {
        return 'Height: ' + value;
    }
  }).on('slideStop', function(ev){
     $(this).val($(this).data('slider').getValue());
  });
  $('#height').change(function() {
    var heightval = $('#height').val();
  });
  // BMI
  $('#bmi').text(weightval + heightval);
});

JS - Also Tried.
  var heightval;
  $('#height').change(function() {
    heightval = $('#height').val();
  });
  $('#bmi').text(heightval);

HTML
    <input id="weight" data-slider-id='weightSlider' type="text" data-slider-min="50" data-slider-max="150" data-slider-step="1" data-slider-value="0"/>
    <input id="height" data-slider-id='heightSlider' type="text" data-slider-min="100" data-slider-max="250" data-slider-step="1" data-slider-value="0"/>

JS - Anwser
$(function() {
  // Weight
  $('#weight').slider({
    formatter: function(value) {
        return value;
    }
  }).on('slideStop', function(ev){
     $(this).val($(this).data('slider').getValue());
  });
  $('#weight').change(updateBmi);
  // Height
  $('#height').slider({
    formatter: function(value) {
        return 'Height: ' + value;
    }
  }).on('slideStop', function(ev){
     $(this).val($(this).data('slider').getValue());
  });
  $('#height').change(updateBmi);

  function updateBmi(){
    var heightval = $('#height').val(); // Height
    var weightval = $('#weight').val(); // Weight
    var bmicalc = (weightval/heightval)/heightval; // BMI Calc
    var bmi = Math.round(bmicalc * 10) / 10; // Decimal
    $('#bmi').text(bmiround); // Display Value
  }
});

Live URL
RawGit

A: Assuming I got the question right (if not, please post a jsfiddle or jsbin sample), I think you can use a single handler for the change:
$('#weight').change(updateBmi);
$('#height').change(updateBmi);

function updateBmi(){
    var heightval = $('#height').val();
    var weightval = $('#weight').val();
    $('#bmi').text(weightval + heightval);
}

A: You can take a look at following code:
$(function() {
  // Weight
  var weightSlider = $('#weight').slider({
    formatter: function(value) {
        return value;
    }
  }).on('slideStop', function(ev){
     calculateBMI();
  });

  // Height
  var heightSlider = $('#height').slider({
    formatter: function(value) {
        return 'Height: ' + value;
    }
  }).on('slideStop', function(ev){
     calculateBMI();
  });

  function calculateBMI(){
      // BMI
      var weightSelected = weightSlider.getValue();
      var heightSelected = heightSlider.getValue();
      $('#bmi').text(weightSelected + heightSelected );
  }
});

No need to go for .change event


text:
Q: how to use the method correctly in js? <script>
function Person(gender) {
  this.gender = gender;
}

Person.prototype.sayGender = function()
{
  alert(this.gender);
};

var person1 = new Person('Male');
var genderTeller = person1.sayGender;
genderTeller();
</script>

Question:
It shows 'undefined'. what is the problem with the script?

A: You need to call it in the scope of person1
genderTell.call(person1);

A: Evan is right. The scope is window when you call the function. You need to call it on the person. When you retrieve the function like that you only get the function, not the scope.
This also works instead:
function Person(gender) {
    this.gender = gender;
}

Person.prototype.sayGender = function () {
    alert(this.gender);
};

var person1 = new Person('Male');
person1.sayGender(); // <-- calling the function ON "person1" directly

FIDDLE


text:
Q: Translate Animation incorrect view move I have 3 view objects(essentially ImageView's) with in a LinearLayout that in turn is within a RelativeLayout , The views are aligned within the LinearLayout as follows:

1 -   2 -  3 - -

The 3 views are wrapped under the Linear layout as demonstrated above.
Basically the idea is to get the side views(1st and 3rd views) move with animation to the place of the middle view onClick() .(so if 3rd view is clicked it should move to middle view's place and the middle moves right to the 3rd view's place.)
I implemented the translate animation as such that the 3rd view when clicked over 100dp to left and 2nd view moves to right, happens fine, but when I apply the translate animation on the onClick() of 1st view to make it move to right and 2nd to move to left then the 2nd and 3rd views both move collectively!! , This means the views are mapped next to each other automatically by the Android!!(note: that's why I used a LinearLayout so that alignment problems don't occur like 2nd view is aligned_below 1st view and aligned_left of 3rd view problems. )
also another problem is that though the views make a move land on another position that was originally belonging to the other view before the animated movement they still maintain the original view ID ?? For.Example that when 3rd view moves left to 2nd views place and 2nd mvoes to 3rd views place the onClick() still is mapped to their original location's?
XML file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
</LinearLayout>

<RelativeLayout
    android:id="@+id/Container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#138AF8" >

    <RelativeLayout
        android:id="@+id/RelativeLayout01"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="#138AF8" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/ImageView01"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:src="@drawable/cost" />

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:src="@drawable/cost" />

            <ImageView
                android:id="@+id/ImageView02"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:src="@drawable/cost" />
        </LinearLayout>

    </RelativeLayout>
</RelativeLayout>

</LinearLayout>

Those 3 ImageViews with the names of ImageView1, ImageView01, ImageView02 are the one's I'm trying to animate.
Animation code:
final TranslateAnimation moveLefttoRight = new TranslateAnimation(0,
            100, 0, 0);
    final TranslateAnimation moveRightToLeft = new TranslateAnimation(0,
            -100, 0, 0);
    moveRightToLeft.setDuration(1000);
    moveLefttoRight.setDuration(1000);
    moveRightToLeft.setFillAfter(true);
    moveLefttoRight.setFillAfter(true);
    final ImageView image1 = (ImageView) findViewById(R.id.imageView1);
    final ImageView image2 = (ImageView) findViewById(R.id.ImageView01);
    final ImageView image3 = (ImageView) findViewById(R.id.ImageView02);

        image1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            Toast.makeText(getApplicationContext(), "image1 clicked",
                    Toast.LENGTH_SHORT).show();
        }
    });
    image2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            Toast.makeText(getApplicationContext(), "image2 clicked",
                    Toast.LENGTH_SHORT).show();
            image2.startAnimation(moveLefttoRight);
            image1.startAnimation(moveRightToLeft);
        }
    });
    image3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            Toast.makeText(getApplicationContext(), "image3 clicked",
                    Toast.LENGTH_SHORT).show();
            image2.startAnimation(moveLefttoRight);
            image3.startAnimation(moveRightToLeft);
        }
    });

A: Translate animation doesn't actually move the view, it just makes it look like that. You have to set the params before the end of the animation so that the button moves as well.example
with the other issue can you post your xml layout file? do you use weights in the imageviews?

A: I ended up using ObjectAnimator builtin animating API and this moves the view's position permanently to the co-ords. requested.


text:
Q: Center of a circle and shopping center There is a disagreement in the office. Are 'center of a circle' and 'shopping center' using the same meaning of the word center? Don't they both mean the middle or heart of the thing being referenced?

A: They're two different meanings for the same word.  From the Oxford Dictionary (which has "centre" rather than "center" but we can ignore that distinction, I think):
http://www.oxforddictionaries.com/definition/english/centre

1: The point that is equally distant from every point on the circumference of a circle or sphere.
2: The point from which an activity or process is directed, or on which it is focused

It doesn't make sense to say that a shopping centre is at the "middle" of the shopping - if anything, it's the other way round:  the shopping is contained within the "shopping centre".

A: Center of a circle is the original meaning, by extension "the middle of anything" that is of the shopping in your specific case:

*

*late 14c., "middle point of a circle; point round which something revolves," from Old French centre (14c.), from Latin centrum "center," originally fixed point of the two points of a drafting compass, from Greek kentron "sharp point, goad, sting of a wasp," from kentein "stitch," from PIE root *kent- "to prick" (source also of Breton kentr "a spur," Welsh cethr "nail," Old High German hantag "sharp, pointed").

*Figuratively from 1680s. Meaning "the middle of anything" attested from 1590s. Spelling with -re popularized in Britain by Johnson's dictionary (following Bailey's), though -er is older and was used by Shakespeare, Milton, and Pope. Center of gravity is recorded from 1650s. Center of attention is from 1868.

(Etymonline)


text:
Q: Azure SQL Database sandbox based on production I have a large Azure Sql Database. I need to provide a sandbox to a team that is a copy of the database, but allows them to create sql objects. The data in the sandbox needs to be up to date with production. I used elastic queries, but the performance is not ideal. I've looked at data sync, but the company requires AD  authentication. Restoring production periodically as the sandbox is not ideal as the team does not want to lose their work. Any suggestions? I'm sure I must be overlooking something.

A: I would first make a copy the production database, then create a "From the Hub" sync group.
1. Copy Database
You can easily create a copy of an Azure SQL database by going to the database blade and clicking "Copy" in the header. From there it will ask you the new database name and target server. You can put it on the same server or create a new server, that is up to you.
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-copy
Once you've done that, you now have a "sandbox" database you control which would be an exact copy of production.
2. Sync Group
After that, you can sync specific tables from production to the sandbox by creating a Azure SQL "Sync Group".

*

*You want to initiate this from your production database since that is the source (or hub) database, so go to the database blade of your production database and choose "Sync to other databases".

*Click on "New Sync Group". From there it will ask you for a sync group name which could be something like "SyncSandbox".

*Select your member database(s), this would be your sandbox database, so choose "Use Existing Database" and select your sandbox database.

*Choose your sync direction. This is important, since you only want to sync from production to the sandbox, select "From the Hub".

*Finally you can configure the sync group. On the Tables page, select a database from the list of sync group members and select Refresh schema. Once you're done, select Save. You can also go into the properties and select the sync frequency if you want it automatic.

https://learn.microsoft.com/en-us/azure/sql-database/sql-database-get-started-sql-data-sync

A: The only one thing worry me that you mentioned your team want to keep their work. I dont know how it would be possible imagine you copy database and your team created new customer with new id which is lets say 31 and then same thing will happens on production so how to resolve those conflicts. If to omit this then I would recommend you to do following.

*

*Setup database replication

*Create job Logic App or Azure function which will execute command on that replica

CREATE DATABASE Database2 AS COPY OF Database1;

*I am not sure but you probably will need to run command make this database writable since if you copy replica it will be read only.

*Run script to replace all sensitive data.

But keep in mind that you will have down time so probably better would be to do this job every morning so when team starts they will have fresh data
More options how to COPY


text:
Q: Jquery slider update value on event change I have the following code which I'm using to calculate the price of a service based on the sliders value.
It works well except the PriceVal doesn't update in real-time. It only updates once the user has lifted the mouse click from the slider.
Does anyone know how I can get it to update in real-time as the slider slides?
The page can be viewed at http://www.voxlogic.net/pricing/
$(function() {
//document.getElementById("f1").reset();
$(":range").rangeinput({ progress: true, max: 100, value:1 });
$(":range").change(function(){
    var sliderVal = this.value;
    calculatePrice(sliderVal);
});
$(":range").keyup(function(){
    var sliderVal = this.value;
    if (sliderVal==""){
        $("#priceVal").html('');
}
else
        {
            //check if value is from 1..25 range and correct otherwise
            if (isNaN(sliderVal)){sliderVal=1;}
            if (sliderVal<1){sliderVal=1;}
            if (sliderVal>25){sliderVal=25;}
            this.value = sliderVal;
            calculatePrice(sliderVal);
        }
    });

    $(":range").keydown(function(){
        var sliderVal = this.value;
        calculatePrice(sliderVal);
});
});

function calculatePrice(sliderVal){
    if (isNaN(sliderVal)){sliderVal=1;}
    if (sliderVal<1){sliderVal=1;}
    if (sliderVal>25){sliderVal=25;}
    var priceVal;
    if (sliderVal<=9){
        priceVal = sliderVal*6;
    }
    else if ((sliderVal>9)&&(sliderVal<=19)){
        priceVal = 9 * 6 + (sliderVal-9) * 4.5;
    }
    else if (sliderVal>19){
        priceVal = 9 * 6 + 10 * 4.5 + (sliderVal-19) * 3.6;
    }
    $("#priceVal").html('£'+priceVal.toFixed(2));
}
});

A: You need to bind the onSlide event

onSlide
When sliding occurs. You can cancel the action by returning false or calling preventDefault() for the event object. Note that assigning this event listener is performance heavy and may affect the smoothness of the sliding experience.

instead of the change event.

change
After the range value is changed. If you slide the range by clicking on the underlying slider this is the only event that is being triggered. Note that the name is the same as the jQuery's change method and you can bind the event directly with that function. For other events you must use the bind method. This leads to more fluent syntax as shown in the example above.

You can do this in your $.rangeinput call:
$(":range").rangeinput({
  progress: true,
  max: 100,
  value: 1,
  onSlide: function(evt, val) {
    calculatePrice(val);
  }
});

Or afterwards using bind.
$(":range").bind('onSlide', function(evt, val){
  calculatePrice(val);
});

A: You need to hookup to the slide event:
$(".SliderDiv").slider({ min: 0, max: 16, step: .25, slide: SliderSlide, animate: true });

// ---- SliderSlide ---------------------------
//
// user is dragging or clicking a slider

function SliderSlide(event, ui)
{
    var Value = ui.value
    var $Sender = $(ui.handle);
    var $Row = $Sender.parentsUntil("table", "tr");
    ...
    // Call your function here


text:
Q: Flutter gives me error everytime i run any app I recently installed flutter but whenever i run any flutter app it shows this error -
FAILURE: Build failed with an exception.

* Where:
Script '/Users/ashvinbhagat/development/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 1

* What went wrong:
Could not compile script '/Users/ashvinbhagat/development/flutter/packages/flutter_tools/gradle/flutter.gradle'.
> startup failed:
  script '/Users/ashvinbhagat/development/flutter/packages/flutter_tools/gradle/flutter.gradle': 1: expecting EOF, found ':' @ line 1, column 32.
     Script started on Wed Apr 29 18:07:22 2020
                                    ^

  1 error

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
Finished with error: Gradle task assembleDebug failed with exit code 1

How should i fix it, it is not a problem with my app, it is problem with flutter

A: After a lot of tries i solved the issue with changing cached_network_image
cached_network_image: ^2.1.0+1


text:
Q: Help me finding closed form of sum of 4 elements I've been reading Wilf's Gfology and tried to calculate some complicated sum
Let's say $0<k \le n$
$$f(k,n) = \sum_{i} i(-1)^i \binom{n}{i} \binom{i}{k-i}  $$
I will write down my calculations, i hope there is no mistake.
I want to calculate generating function of $f(k,n)$ it is $F(k,n) = \sum_{n} f(k,n) x^n$
$$\sum_{n}x^n \sum_{i} i(-1)^i \binom{n}{i} \binom{i}{k-i}=$$
$$\sum_{i} i(-1)^i \binom{i}{k-i} \sum_{n} \binom{n}{i} x^n=$$
$$\sum_{i} i(-1)^i \binom{i}{k-i} \frac{x^i}{(1-x)^{i+1}}=$$
$$\frac{1}{1-x} \sum_{i} i(-1)^i \binom{i}{k-i} \left(\frac{x}{(1-x)}\right)^i$$
I don't really know how to proceed with this sum.
I'd like to solve it with generating functions if it's possible.
I will be greatful for any hints or solutions to this.

A: Here's a variant to obtain a generating function $F(x,y)=\sum_{n\geq 0}\sum_{k\geq 0}f(k,n)x^ky^n$. It's not obvious (for me) to derive a closed formula from it. Maybe this indicates that there is no one obtainable.
Let
\begin{align*}
f(k,n)=\sum_{i}i(-1)^i\binom{n}{i}\binom{i}{k-i}\qquad\qquad0\leq k\leq n
\end{align*}
We use with $k\geq 0$ a slightly extended range of definition.

We now introduce the formal generating function $$F_n(x)=\sum_{k\geq 0}f(k,n)x^k\qquad\qquad n\geq 0$$ and show

The following is valid
\begin{align*}
F_n(x) =-nx(1+x)(1-x-x^2)^{n-1}\qquad\qquad n\geq 0\tag{1}
\end{align*}

We observe
  \begin{align*}
F_n(x)&=\sum_{k\geq 0}f(k,n)x^k\\
&=\sum_{k\geq 0}\sum_{i\geq 1}(-1)^ii\binom{n}{i}\binom{i}{k-i}x^k\\
&=\sum_{k\geq 0}\sum_{i\geq 1}(-1)^in\binom{n-1}{i-1}\binom{i}{k-i}x^k\tag{2}\\
&=n\sum_{i\geq 1}(-1)^i\binom{n-1}{i-1}x^i\sum_{k\geq 0}\binom{i}{k-i}x^{k-i}\tag{3}\\
&=n\sum_{i\geq 1}(-1)^i\binom{n-1}{i-1}x^i\sum_{r\geq 0}\binom{i}{r}x^{r}\tag{4}\\
&=n\sum_{i\geq 1}(-1)^i\binom{n-1}{i-1}x^i(1+x)^i\\
&=n\sum_{i\geq 0}(-1)^{i+1}\binom{n-1}{i}x^{i+1}(1+x)^{i+1}\tag{5}\\
&=-nx(1+x)\sum_{i\geq 0}(-1)^{i}\binom{n-1}{i}x^{i}(1+x)^{i}\\
&=-nx(1+x)\left(1-x(1+x)\right)^{n-1}\\
\end{align*}
  and the claim (1) follows.

Comment:

*

*In (2) we use the identity $i\binom{n}{i}=n\binom{n-1}{i-1}$

*In (3) we do some rearrangements to prepare for the index substitution in (4)

*In (4) we introduce the index $r := k-i$

*In (5) we shift the index $i$

We now calculate the complete generating function
  \begin{align*}
F(x,y)=\sum_{n\geq 0}F_n(x)y^n=\sum_{n\geq 0}\sum_{k\geq 0}f(k,n)x^ky^n
\end{align*}

The following is valid
\begin{align*}
F(x,y) =-\frac{x(1+x)y}{\left(1-(1-x-x^2)y\right)^2}
\end{align*}

We observe, using the expression (1) of the generating function $F_n(x)$
\begin{align*}
F(x,y)&=-x(1+x)\sum_{n\geq 0}n(1-x-x^2)^{n-1}y^n\\
&=-x(1+x)y\sum_{n\geq 1}n(1-x-x^2)^{n-1}y^{n-1}\\
&=-x(1+x)y\sum_{n\geq 0}(n+1)(1-x-x^2)^{n}y^{n}\tag{6}\\
&=-x(1+x)y\sum_{n\geq 0}\binom{-2}{n}(1-x-x^2)^{n}(-y)^{n}\tag{7}\\
&=-\frac{x(1+x)y}{\left(1-(1-x-x^2)y\right)^2}\tag{8}
\end{align*}
and the claim follows.

Comment:

*

*In (6) we shift the index $n$

*In (7) we use the binomial identity $\binom{-n}{k}=\binom{n+k-1}{k}(-1)^k$


text:
Q: mysql2 adapter issue: libruby.so.1.8: cannot open shared object file: No such file or directory I note that there have been many other similar questions, but my context seems to be different.
Error
The following is the error I am getting, trying to run/restart a Rails Application (Redmine).  Redmine was running fine, but there have been some server updates by the shared host, thus seeing these problems.
mysql2 is listed in the gem/bundle list.  mysql2.so exists in the location it is looking for, and has the required (executable) permissions.  Thank you any suggestions in addressing this issue.
Error message:
Please install the mysql2 adapter: `gem install activerecord-mysql2-adapter` (libruby.so.1.8: cannot open shared object file: No such file or directory - /home/test/gems/gems/mysql2-0.3.11/lib/mysql2/mysql2.so)

Exception class:
LoadError

Enviornment
# ruby -v
ruby 1.9.3p429 (2013-05-15 revision 40747) [x86_64-linux]

# rails -v
Rails 3.2.6

# gem -v
1.8.23

# mysql --version
mysql  Ver 14.14 Distrib 5.5.34, for Linux (x86_64) using readline 5.1

#gem list
...
mysql2 (0.3.11)
...

#bundle show
...
mysql2 (0.3.11)
...

#vim database.yml

production:
 adapter: mysql2
 database: database_name
 host: localhost
 username: dbuser
 password: dbpwd
 encoding: utf8

A: Answer to this question solved my issue.
gem uninstall mysql2
bundle install


text:
Q: Need help in Paginating Hash values in rails I have the following Hash
var messages = { 7 => [m1,m2,m3,m4,m5], 8 => [m1,m2,m3,m4,m5] }

Containing User id and a list of messages for that user where the user id is the key and the messages are the values.
I would like to implement a pagination on the Hash values[Messages].
Can anyone tell me how to implement pagination for such scenario?


text:
Q: How to replace the Data Array in jQuery DataTables I have a DataTables table that is initially filled by a JSON Array (directly written to HTML with ASP.NET). Now I want to refresh this data with Ajax but the data simply won't be added. I want to use my own method, not DataTables' internal Ajax method. (Using DataTables 1.10.0).
$.getJSON("?ajax=1", null, function(json, status, xhr) {
    var table = $("#" + proTableId).DataTable();

    oSettings = table.settings();
    //table.clear();
    table.rows().remove();

    var data = table.data();
    for (var i = 0; i < json.length; i++)
    {
        data.push(json[i]);
    }
    table.draw();
});

The JSON result is correct but after this call the DataTable is always empty. How do I replace the Data inside the DataTables object and preferably keep sorting and filtering?

A: For adding data to the data table, you have to access the property row of the data table object, and then call the add method. Finally, you update this table by calling the draw method.
As it can be seen on the Data Table documentation. You would have to do this:
for(var i= 0; i < json.length; i++){
    table.row.add([
       json[i].firstProperty,
       json[i].secondProperty
    ]).draw();
}


text:
Q: Lost access to sudo on Mac. Want to regain access I don't know what came in my mind that I just typed this in my shell:
sudo chmod 700 /usr/bin/sudo

and then also entered my password. The above command ran and I lost control over sudo.
sudo is owned by root. I am not the root user. My username is aditya.
Previously sudo had a permission of 711. That means I could execute it being a non-root user. But now, I have lost control.
When I try to access sudo from my shell, I get:
-bash: /usr/bin/sudo: Permission denied

Is there any way I can re-gain access to sudo without having to re-install my OS or call some engineer to fix it?

A: First use pkgutil to list the installer information for sudo.
pkgutil --file-info /usr/bin/sudo

Note the mode which is the permissions in octal notation for the file.
Shutdown your computer and then start the computer holding down the command key and the "s" key. You are booting the computer into single user mode.
At the prompt force check the file system with the command
/sbin/fsck -fy

then mount the file system read write
/sbin/mount -uw /

Now change the permissions on sudo
chmod 4511 /usr/bin/sudo

Then reboot the computer
reboot


text:
Q: Why do I Get Different Results Using Array? I've made a simple program that counts matrices, here's the code:
#include <iostream>
#include <math.h>
using namespace std;

int main()
{
int result[3] = {0,0,0};
int matrixc[3][6] = {
        {0,0,0,0,0,1},
        {0,0,0,1,1,1},
        {1,0,1,0,0,1}
        };
for(int x=0;x <3;x++)
{
    for(int y=0;y < 6;y++)
    {
        result[x] += (matrixc[x][y] * pow(2,6-y));
    }
    cout << result[x] << endl;
}
}

The output is what I wanted, it is: 2,14,and 82.
But, when I delete the initialization in the integer array of result:
#include <iostream>
#include <math.h>
using namespace std;

int main()
{
int result[3]; //deleted initialization
int matrixc[3][6] = {
        {0,0,0,0,0,1},
        {0,0,0,1,1,1},
        {1,0,1,0,0,1}
        };
for(int x=0;x <3;x++)
{
    for(int y=0;y < 6;y++)
    {
        result[x] += (matrixc[x][y] * pow(2,6-y));
    }
    cout << result[x] << endl;
}
}

I got odd outputs: 1335484418,32618, and 65617.
Would you like to explain me why would the output be different between an array with and without an initialization?
Actually, I don't want to initialize all result array, because I have a huge data of matrices.
Is it possible if I use std::vector without initializing all of the result array?

A:
Would you like to explain me why would the output be different between an array with and without an initialization?

Without initialisation, automatic variables aren't initialised. They will have an indeterminate value, depending on what happened to be in the memory they occupy.

Actually, I don't want to initialize all "result" array, because I have a huge data of matrices.

You can zero-initialise the whole array, even if it's huge, like this:
int result[huge] = {};

although, if it is huge, then it shouldn't be an automatic variable. These are typically kept on the stack, which is typically not huge and liable to overflow if you put too much stuff on it.

Is it possible if I use std::vector without initializing all of the "result" array?

Yes, a vector will zero-initialise its elements by default.

A: Without the initialization, the result array contains undetermined values, i.e. values that could be anything that fits into an int.

A: When you delete the initialization of the result array, those locations are initially set to unspecified, arbitrary values. You then add to this arbitrary value within the for loop, and end up those unexpected results. The results may be completely different the next time you run your program.
Also, since result[x] += ... reads from an uninitialized variable, deleting the initialization results in your code having undefined behavior.
If you switch over to using a vector you can zero initialize it as
std::vector<int> result(count);  // zero initialized with `count` elements

or
std::vector<int> result; // contains zero elements
result.resize(count);    // now it contains `count` elements, all set to 0

A: As I mentioned in my comment if you do not initialize result it will have undetermined values. Later on your are then adding a value to an unknown value which will still be an unknown value. In this situation you need to initialize your data, can zero initialize like so:
int result[3] = {} ;

A:
Would you like to explain me why would the output be different between an array with and without an initialization?

Seriously?  If you don't initialize the array elements  they are not initialized!
That means they contains junk data, so when you do result[x] += xxx; you are adding to junk, so you get more junk.

Actually, I don't want to initialize all "result" array, because I have a huge data of matrices.

Then you shouldn't rely on their initial value being zero.
You can do this:
int result[3] = { };  // initialize all elements to zero

Is it possible if I use std::vector without initializing all of the "result" array?

std::vector always initializes its members.


text:
Q: How can I make a class iterable in Java to use foreach loop I try to create a manual LinkedList class and then I made a function to merge two LinkedList. I implement iterable for my LinkedList class in order to use foreach loop but something went wrong. I don't know how to override iterator() function to solve problem. this is my code:
Node.java
package app;
public class Node<R> {
    private R Data;
    private Node<R> nextNode;
    public final void setData(R data) {
        Data = data;
    }
    public R getData() {
        return Data;
    }
    public void setNextNode(Node<R> nextNode) {
        this.nextNode = nextNode;
    }
    public Node<R> getNextNode() {
        return nextNode;
    }
    public Node(R dR){
        this.setData(dR);
    }
}

LinkedList.java
package app;
import java.util.Iterator;
public class LinkedList<R> implements java.lang.Iterable<R>{
    private Node<R> headNode;
    public void addNode(Node<R> nR){
        if(headNode == null){
            headNode = nR;
        } else {
            nR.setNextNode(headNode);
            this.headNode = nR;
        }
    }
    public void addData(R dR){
        Node<R> nR = new Node<>(dR);
        addNode(nR);
    }
    public LinkedList(){
        headNode = null;
    }

    @Override
    public Iterator<R> iterator() {
        return null;
    }
}

App.java
package app;
public class App {
    public static <R>LinkedList<R> unionLinkedList(LinkedList<R> list , LinkedList<R> list2){
        LinkedList<R> unionLinkedList = new LinkedList<>();
        for (R dR : list) {
            unionLinkedList.addData(dR);
        }
        for (R dR : list2) {
            unionLinkedList.addData(dR);
        }
        return unionLinkedList;
    }
    public static void main(String[] args) throws Exception {
        LinkedList<Integer> list = new LinkedList<>();
        LinkedList<Integer> list2 = new LinkedList<>();
        list.addData(3);
        list.addData(9);
        list.addData(8);
        list2.addData(11);
        list2.addData(5);
        list2.addData(7);
        LinkedList<Integer> u = unionLinkedList(list, list2);
    }
}

I know I have to change return null; in iterator() but I don't know what should replace it.

A: You implement the Iterable interface.
Documentation.

public interface Iterable
Implementing this interface allows an object to be the target of the
"for-each loop" statement.

At the very least you'll need to return an iterator.

Iterator   iterator()
Returns an iterator over elements of type T.

'null' (as in your code) is not an iterator.  You'll need to implement a class (can be nested, if you like) that knows how to iterate over your particular linked-list implementation.  Probably, all it needs is a 'next node to process' member; the next() and hasNext() methods can be implemented with just that.

A: finally I can do it with this modification:
@Override
public Iterator<R> iterator() {
    return new Iterator<R>(){
        Node<R> current = (Node<R>) headNode;

        @Override
        public boolean hasNext(){
            return current != null;
        }

        @Override
        public R next(){
            if (hasNext()){
                R dR = current.getData();
                current = current.getNextNode();
                return dR;
            }
            return null;
        }
    };
}

in LinkedList.java


text:
Q: How to write your own custom legends for google line chart/ Google line chart legend manipulation I am using Google Visualisation to create line charts for my application. I have following requirements in that :

*

*Manipulating events on legends (like doubleClick, which I have
    solved somehow)

*Wrapping the legends in two rows avoiding pagination (Most imp and required)

I have gone through the following questions to get solution for my answers:
1) Issue with legend pagination (Google Interactive chart API)
Issue : I would avoid playing with font-size because the number of legends may increase over time
2)How the legends on Google charts can be wrapped
Issue: I do not want legends to be anywhere else than at the position:bottom. And maxLines solution does not work on position : bottom
3) Is there any way I can avoid pagination in legends of a google visualisation chart and show all the lines in two lines in a single page?
Issue: This is another link, which mentions my problem, but no useful answers found on it.
4) Google Documentation :
Heading : Chart Legend Text and Style chdl, chdlp, chdls [All charts]
https://developers.google.com/chart/image/docs/chart_params#axis-label-styles-chxs
Heading : Setting Chart Margines
https://developers.google.com/chart/image/docs/chart_params#chart-margins-chma-all----charts
Heading : Tooltips
https://developers.google.com/chart/interactive/docs/customizing_tooltip_content#tooltips-an-introduction
Comment : These are few google documentation links where few legend manipulating properties are mentioned, but still they does not solve my problem.
5)https://github.com/google/google-visualization-issues/issues/1286
Comment : This is the link where I can see that, google has not provided many properties to manipulate legends, and no much useful information to solve my issue
6) Google charts legend manipulation
Comment : This is the only link, where I got a hint about how to solve my issue i.e. writing own legends. But there is no more links provided for documentation, no jsFiddle or no ref links apart from one link which is not useful for me.
While gone through all these, I can see only solution to solve my problem is to write my own custom legends. But I have no idea about how to write a complete element adding to google API.
Please guide me to go through this, any suggestions/links/refs/hints are welcome.
Thank you.

A: Example: Build custom legend, which syncs with data and chart...

google.charts.load('44', {
  callback: drawChart,
  packages: ['controls', 'corechart']
});

function drawChart() {
  // adapted from a previous example
  var colorPallette = ['#273746','#707B7C','#dc7633','#f1c40f','#1e8449','#2874a6','#6c3483','#922b21'];

  var data = new google.visualization.DataTable();
  data.addColumn('date', 'X');
  data.addColumn('number', 'Y1');
  data.addColumn('number', 'Y2');

  data.addRow([new Date(2016,  0, 1),   1, 123]);
  data.addRow([new Date(2016,  1, 1),   6,  42]);
  data.addRow([new Date(2016,  2, 1),   4,  49]);
  data.addRow([new Date(2016,  3, 1),  23, 486]);
  data.addRow([new Date(2016,  4, 1),  89, 476]);
  data.addRow([new Date(2016,  5, 1),  46, 444]);
  data.addRow([new Date(2016,  6, 1), 178, 442]);
  data.addRow([new Date(2016,  7, 1),  12, 274]);
  data.addRow([new Date(2016,  8, 1), 123, 934]);
  data.addRow([new Date(2016,  9, 1), 144, 145]);
  data.addRow([new Date(2016, 10, 1), 135, 946]);
  data.addRow([new Date(2016, 11, 1), 178, 747]);

  // use view to add various columns for example purposes
  var view = new google.visualization.DataView(data);
  view.setColumns([0, 1, 2,
    {
      calc: function (data, row) {
        return data.getValue(row, 1) + data.getValue(row, 2);
      },
      type: 'number',
      label: 'Y3'
    },
    {
      calc: function (data, row) {
        return data.getValue(row, 2) - data.getValue(row, 1);
      },
      type: 'number',
      label: 'Y4'
    },
    {
      calc: function (data, row) {
        return data.getValue(row, 1) * 2;
      },
      type: 'number',
      label: 'Y5'
    },
    {
      calc: function (data, row) {
        return data.getValue(row, 2) * 3;
      },
      type: 'number',
      label: 'Y6'
    },
    {
      calc: function (data, row) {
        return data.getValue(row, 1) * 1.5;
      },
      type: 'number',
      label: 'Y7'
    },
    {
      calc: function (data, row) {
        return data.getValue(row, 1) * 1.5;
      },
      type: 'number',
      label: 'Y8'
    }
  ]);

  var control = new google.visualization.ControlWrapper({
    controlType: 'DateRangeFilter',
    containerId: 'control_div',
    options: {
      filterColumnIndex: 0
    }
  });

  var chart = new google.visualization.ChartWrapper({
    chartType: 'LineChart',
    containerId: 'chart_div',
    options: {
      chartArea: {
        width: '80%'
      },
      // add colors for legend mapping
      colors: colorPallette,
      hAxis: {
        format: 'MMM',
        slantedText: false,
        maxAlternation: 1
      },
      legend: 'none',
      width: 320
    }
  });

  // add legend marker
  function addLegendMarker(markerProps) {
    var legendMarker = document.getElementById('template-legend-marker').innerHTML;
    for (var handle in markerProps) {
      if (markerProps.hasOwnProperty(handle)) {
        legendMarker = legendMarker.replace('{{' + handle + '}}', markerProps[handle]);
      }
    }
    document.getElementById('legend_div').insertAdjacentHTML('beforeEnd', legendMarker);
  }

  // chart ready event
  google.visualization.events.addListener(chart, 'ready', function () {
    var legend = document.getElementById('legend_div');

    // colors from chart
    var colorPallette = chart.getOption('colors');

    // clear previous legend
    legend.innerHTML = '';

    // add legend marker for each Y axis column - skip X axis --> i = 1
    for (var i = 1; i < chart.getDataTable().getNumberOfColumns(); i++) {
      var markerProps = {};
      markerProps.index = i;
      markerProps.color = colorPallette[i - 1];
      markerProps.label = chart.getDataTable().getColumnLabel(i);
      addLegendMarker(markerProps);
    }

    // add click event to each legend marker
    var markers = legend.getElementsByTagName('DIV');
    Array.prototype.forEach.call(markers, function(marker) {
      marker.addEventListener('click', function (e) {
        var marker = e.target || e.srcElement;
        if (marker.tagName.toUpperCase() !== 'DIV') {
          marker = marker.parentNode;
        }
        var columnIndex = parseInt(marker.getAttribute('data-columnIndex'));
        document.getElementById('message_div').innerHTML = 'legend marker clicked = ' + chart.getDataTable().getColumnLabel(columnIndex);
      }, false);
    });
  });

  var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
  dash.bind([control], [chart]);
  dash.draw(view);
}
#legend_div {
  text-align: center;
  width: 320px;
}

.legend-marker {
  display: inline-block;
  padding: 16px 4px 8px 4px;
}

.legend-marker-color {
  display: inline-block;
  height: 12px;
  width: 12px;
}

A:  if ($("#source svg text[text-anchor='end']").length > 0){
        var n = $("#source svg text[text-anchor='end']").length;
        $("#source svg text[text-anchor='end']")[n-5].innerHTML = "";
        $("#source svg text[text-anchor='end']")[n-4].innerHTML = "Create your own legend";
        $("#source svg text[text-anchor='end']")[n-3].innerHTML = "Create your own legend";
        $("#source svg text[text-anchor='end']")[n-2].innerHTML = "Create your own legend";
        $("#source svg text[text-anchor='end']")[n-1].innerHTML = "";
    }


text:
Q: Template initialization: I want to create row vector and column vector alias from Matrix class. How can I do that?
template<class T, unsigned int m, unsigned int n>
class Matrix {
public:
    Matrix();

    .
    .
    .

private:
    unsigned int rows;
    unsigned int cols;
    .
};

I get error here. I see that type alias for templates cannot be done. Is there any way I can handle it? For below I get error as "Partial specialization of alias template".
template<class T, unsigned int m, unsigned int n>
using rowVector<T,n> = Matrix<T,1,n>;

template<class T, unsigned int m, unsigned int n>
using colVector<T,m> = Matrix<T,m,1>;

Any pointers how can I achieve this?

A: This is the correct syntax:
template <class T, unsigned int n>
using rowVector = Matrix<T, 1, n>;

template <class T, unsigned int m>
using colVector = Matrix<T, m, 1>;

A: I believe you must have more code than what you posted, because this
template<class T, unsigned int m, unsigned int n>
class Matrix {};

template<class T, unsigned int m, unsigned int n>
using rowVector<T,n> = Matrix<T,1,n>;

template<class T, unsigned int m, unsigned int n>
using colVector<T,m> = Matrix<T,m,1>;

Causes the following error
prog.cc:5:16: error: expected '=' before '<' token
 using rowVector<T,n> = Matrix<T,1,n>;
                ^
prog.cc:5:16: error: expected type-specifier before '<' token
prog.cc:8:16: error: expected '=' before '<' token
 using colVector<T,m> = Matrix<T,m,1>;
                ^
prog.cc:8:16: error: expected type-specifier before '<' token

The correct syntax for an alias template is:

template < template-parameter-list >
using identifier attr(optional) = type-id ;

So the fix is
template<class T, unsigned int m, unsigned int n>
using rowVector = Matrix<T,1,n>;

template<class T, unsigned int m, unsigned int n>
using colVector = Matrix<T,m,1>;

And I suppose you want to remove m as parameter of rowVector and n as parameter of colVector:
template<class T, unsigned int n>
using rowVector = Matrix<T,1,n>;

template<class T, unsigned int m>
using colVector = Matrix<T,m,1>;