text:
Q: Rails 5 beta bundle update has gem conflict I am trying to update Rails to 5.0.0.beta1, and I get errors that look like this:
Bundler could not find compatible versions for gem "minitest":
  In Gemfile:
    rails (= 5.0.0.beta1) was resolved to 5.0.0.beta1, which depends on
      activejob (= 5.0.0.beta1) was resolved to 5.0.0.beta1, which depends on
activesupport (= 5.0.0.beta1) was resolved to 5.0.0.beta1, which depends
on minitest (~> 5.1)
    minitest-rails-capybara was resolved to 0.0.1, which depends on
      minitest-rails was resolved to 0.5, which depends on
        minitest (~> 4.0)

No gem, including minitest-rails-capybara, has its version set explicitly in my Gemfile. There is no Gemfile.lock file in my app (I removed the existing one in the upgrade branch.)
minitest-rails-capybara is the latest version in the current gemset (and in others.) Why am I getting this error?
EDIT Even after starting with a new app, (rails new) if I add these lines to the Gemfile, I get the above errors:
group :test do
  gem 'minitest-spec-rails'
  gem 'minitest-rails-capybara'
end

Versions:

*

*Ruby: 2.3.0

*Bundler: 1.11.2

*gem: 2.5.1

A: Well, I guess I'm jumping the gun somewhat here - those gems at least don't have their Rails5-compatible versions on Rubygems.org.
Pointing directly to Github fixes this:
  gem 'minitest-rails',  git: 'https://github.com/blowmage/minitest-rails', branch: 'rails5'
  gem 'minitest-spec-rails'
  gem 'minitest-rails-capybara', git: 'https://github.com/blowmage/minitest-rails-capybara', branch: 'rails5'


text:
Q: The inverse of a perturbed identity matrix. Suppose I have a matrix $A$ as following:
$$A=\begin{bmatrix}1&a_{12}&\cdots&a_{1n}\\ a_{21}&1&\cdots&a_{2n}\\\vdots&\vdots&\ddots&\vdots\\a_{n1}&a_{n2}&\cdots&1\end{bmatrix}$$
Assuming $$\max_{1\le{i}\le{n},1\le{j}\le{n}}\left|a_{ij}\right|\ll1$$
How to obtain the inverse of $A$ in an explicit form?

A: Use
$$(I-A)^{-1} = I + A + A^2 + A^3 + \cdots$$
for $\|A\|<1$, where $\|A\|=\sup_{\|x\|=1} \|Ax\|$.

A: The answer provided by nayrb is the best you can expect.
However, if you do not want an infinite series, but a finite (but self-referential) form then the following may be useful
$$
(I-A)^{-1} = I + A + A^2 + A^3 \cdots A^{n-1} + A^n (I-A)^{-1}
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: What would be the effect of modeling a binary predictor in an OLS model as [-1, 1] instead of [0, 1]? I am using an OLS model to predict a continuous variable using several continuous predictors and one binary categorical predictor. I know that usually binary variables are modeled as [0, 1], but I am curious what the effect of giving a binary categorical predictor values of [-1, 1] would be. I had accidentally done the [-1, 1] coding in the first round of analysis, and after correcting the coding to [0, 1] I saw that the change in coding made the regression result similar but less extreme. I realize I don't fully understand what change this had on the model, and I'd appreciate insight into why it is so important to code the categorical variable as [0, 1].
[Edit] To clarify what I mean by the result being 'less extreme': I am fitting this model separately for each individual in our dataset, and then I do a wilcoxon signed-rank test across the coefficients from the binary variable (the coefficients do not meet the normality assumption for a t-test). The test is significant for the coefficients resulting from the [-1, 1] coding but not for the [0, 1] coding. Naturally I would like the test to be significant but now I feel that I cannot accept this result because it is arbitrarily affected by the coding. Is testing the coefficients resulting from the [-1, 1] coding somehow more or less legitimate? I am not sure which test result to accept, or whether I have approached the problem incorrectly.

A: If the model with $X$ coded as $\{0,1\}$ has the following form:
$$
y_i = \alpha_0 + \alpha_1 X_i + \varepsilon
$$
and model with $X^*$ coded as $\{-1, 1\}$ has the following form:
$$
y_i = \beta_0 + \beta_1 X^*_i + \varepsilon
$$
we can write the following equivalences:
$$
\beta_0 = \alpha_0 + \frac{\alpha_1}{2} \\
\beta_1 = \frac{\alpha_1}{2}
$$
$\alpha_0$ is the predicted mean of the outcome when $X=0$, and $\alpha_1$ is the difference between the predicted mean of the when $X=1$ and the predicted mean when $X=0$, i.e., the difference between the two predicted means. $\beta_0$ is the midpoint between the two predicted means, and $\beta_1$ is the difference between the predicted mean when $X=1$ and the midpoint. When other predictors are in the model, these interpretations involve holding those other variables constant (i.e., for a pair of units that were the same on all other covariates but differed in $X$).
The p-value on the test for $\beta_1$ will be identical to that for $\alpha_1$, but this will not be true for $\beta_0$ and $\alpha_0$.

A: The operation of transforming a $[0,1]$ dummy into a $[-1,1]$ dummy amounts to (see below for a more general case) transforming the categorical variable (it does not matter that it is categorical) via $2x-1$ and leaving the constant as is.
Via Scaling in linear regression and Adding a Constant to Every Column of X (OLS), this means first scaling the regressor matrix via
$$
\begin{pmatrix}
1&0\\0&2
\end{pmatrix}
$$
to then add
$$
\begin{pmatrix}
0&-1\\
\vdots&\vdots\\0&-1
\end{pmatrix}
$$
to the transformed regressor matrix. Now, this is, from the second link provided above, the same as multiplying the regressor matrix with
$$
\begin{pmatrix}
1&-1\\0&1
\end{pmatrix}
$$
Hence, we transform the originial regressor matrix with
$$
\begin{pmatrix}
1&0\\0&2
\end{pmatrix}
\begin{pmatrix}
1&-1\\0&1
\end{pmatrix}=\begin{pmatrix}
1&-1\\0&2
\end{pmatrix}=:A
$$
From the first link, the new and old coefficient vectors are related via
$$
\hat{\beta}^\circ=A^{-1}\hat{\beta},
$$
where
$$
A^{-1}=\begin{pmatrix}
1&0.5\\0&0.5
\end{pmatrix}
$$
All in all, the new coefficient for the constant will then be the old constant plus one half the old slope coefficient and the new slope will be one half the old slope. This is also intuitive, as moving from the lowest to the highest value of the regressor now is twice as far, so that increasing by one unit should only be half the effect.
Numerical illustration:
n <- 20

y <- rnorm(n)
x <- sample(c(0,1), n, replace = T) # a categorical predictor...
x <- rnorm(n)                       # ...but works for any predictor
x.trafo <- 2*x-1

> all.equal(0.5*coef(lm(y~x))[2], coef(lm(y~x.trafo))[2], check.attributes = F)
[1] TRUE

> all.equal(coef(lm(y~x))[1] + 0.5*coef(lm(y~x))[2], coef(lm(y~x.trafo))[1], check.attributes = F)
[1] TRUE

A more general case
Consider a constant and regressors $x_1,\ldots,x_k$, scaling factors to all variables, $s_0,s_1,\ldots,s_k$ and additions to regressors $\mathbf{a}:=(a_1,\ldots,a_k)'$ (since scaling and adding is equivalent for the constant, we omit $a_0$). Let $\mathbf{s}:=(s_1,\ldots,s_k)'$.
Then, the operation of scaling and adding can be expressed via a matrix
$$
S:=\begin{pmatrix}
s_0&a_1&\cdots&\cdots&\cdots&a_k\\
0&s_1&0&\cdots&\cdots&0\\
0&0&s_2&\ddots&\cdots&0\\
0&\vdots&\ddots&\ddots&\ddots&0\\
0&0&&&&0\\
0&0&0&\cdots&0&s_k\\
\end{pmatrix}=\begin{pmatrix}
s_0&\mathbf{a}'\\
\mathbf{0}&\text{diag}(\mathbf{s})\\
\end{pmatrix}
$$
This representation also reveals that the $s_j$ must not be zero. In the case of $s_0$ we would create a zero column. For $s_j$, $j\neq0$, the a corresponding $a_j\neq0$ would ensure a nonzero column for the transformed regressor even if $s_j=0$, but then, that transformed regressor would simply be $a_j$ and hence be collinear to the constant $s_0$.
By partitioned inverses,
$$
S^{-1}=\begin{pmatrix}
1/s_0&-\mathbf{a}'\text{diag}(\mathbf{s})^{-1}/s_0\\
\mathbf{0}&\text{diag}(\mathbf{s})^{-1}\\
\end{pmatrix}
$$
and the coefficients in the transformed dataset, $\hat{\beta}^\circ$, are related to those of the original one, $\hat{\beta}$, via
$$
\hat{\beta}^\circ=S^{-1}\hat{\beta}
$$
Hence, as also pointed out by Matthew in the comments, the new slope coefficients are simply the old ones reciprocally adjusted for by their own respective scaling while the new intercept is a function of all additions and all scalings.

A: Let me provide an explanation for this query with a simpler scenario.  Let's just take one scalar variable as the response variable, and one dichotomous variable as the predictor variable.  If you run OLS regression, you actually are just doing a 2 independent sample t-test (assuming homogeneity of variances between the two groups).  The key is to recognize that the dichotomous variable really is just a group-membership indicator variable.
Now, the results for the null hypothesis statistical test (NHST) are going to be the same as the results for the NHST asking if the slope of the OLS regression is different from zero.  (The t-ratio and p-values will be the same.)
So, here's the key to the OLS approach.  If you run the regression, you get something like
$$y = 12.34 + 5.67 D$$
(extracting the slope and intercept from the OLS output).  Here, I've used $D$ as the predictor variable (instead of $x$) because I want to indicate that it is a dichotomous variable (takes on only 1 of 2 values).
So, ¿what are the slope and intercept?  This is where the coding of {0,1} or {-1,1} comes into play.  If you use the former coding scheme of {0,1}, then the intercept of 12.34 is the mean of the $D=0$ group, and the slope is the difference in the group means.  So, if you plug in $D=1$, you can get the other group's mean from this equation:  12.34 + 5.67 = 18.01.
Now, if you use the latter coding scheme of {-1,1}, then the intercept is the GRAND mean (the mean if you put both data sets together).  In this case, the slope is half the difference between the group.  So, to get each of the groups means, you need to plug in the value for $D$ for each group: $D=-1$ would give a group mean of $12.34 - 5.67 = 6.67$ and $D=+1$ would give a group mean of $122.34 + 5.67 =18.01$.
Note, I'm assuming the same number of members in each group...but the ideas essentially can be adjusted to extend to account for unbalanced groupings.
The idea extends to more complicated models with other scalar predictors.
I hope this is helpful.


text:
Q: can you use a wild card for C_INCLUDE_PATH If I downloaded a source tree with a number of folders with source files in them can I use
c_include_path=/some/directory/*

so it searches through all the folders for the files?

A: AFAIK, this is not possible, you need to provide each directory path separately, most probably using -I option.
The usual convention is, however, to have a top level header at the directory root which includes other required headers with relative path, something like
root.h
#include <this/is/one.h>
#include <that/is/another/one.h>

and, we use #include <root.h> with -I /path/to/rootdir


text:
Q: Collatz conjecture function in Python3 calling itself when being assigned to a variable I'm reading the book "Automate the boring stuff" by Al Sweigart to start learning Python (it is free online, so you can check it if you're interested, or you think that it would help solve my problem). And by the end of Chapter 3, you are given an exercise, creating a program that can execute the Collatz Conjecture. I've successfully created a function that takes an input integer and divides it by 2 or multiplies it by 3 and adds 1 for even and odd numbers, respectively.
The issue comes, when I try to take the value returned by the function, and assign it to a variable(so I can make a loop that will stop when the number gets to one), it instead calls the function, and when I try to use the function inside a while loop it returns a None value.
I tried comparing it to other program that simulates a magic 8-ball, because the way I made the way I made the Collatz program is very similar to the 8-ball, but somehow the 8-ball does work, and the Collatz doesn't, and since I'm currently out of ideas, I ask you if you can notice any typos in my code that may indicate why this is happening.
I thank you in advance for your time and effort.
PS: don't forget to drink some water, it is good for you <3
THE CODES:
1.-Collatz(no while loop included)
import random
even = range(0, 1001, 2)

def collatz(number):
    if number in even:
        print(number // 2)
        return
    else:
        print(3 * number + 1)
        return

startNumber = int(input())
newNumber = collatz(startNumber)

2.- 8-ball
import random

def getAnswer(x):
    if x == 1:
        return 'It is certain'
    elif x == 2:
        return 'It is decidedly so'
    elif x == 3:
        return 'Yes'
    elif x == 4:
        return 'Reply hazy try again'
    elif x == 5:
        return 'Ask again later'
    elif x == 6:
        return 'Concentrate and ask again'
    elif x == 7:
        return 'My reply is no'
    elif x == 8:
        return 'Outlook not so good'
    elif x == 9:
        return 'Very doubtful'

r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)

3.- Collatz made with the hints from the book(includes while loop)
def collatz(number):
    if number % 2 == 0:
        print(number // 2)
        return
    elif number % 2 == 1:
        print(3 * number + 1)
        return

startNumber = int(input())

while startNumber != 1:
    collatz(startNumber)
    newNumber = collatz(startNumber)
    collatz(newNumber)

Also, here's an SS of the book, just in case
enter image description here

A: You have unused variables, and you need to define a return value for collatz().
Right now, you define a variable newNumber, but never use it anywhere in your code. You should be updating startNumber instead (renamed to num below for readability). You also need to define a return value for collatz(); otherwise, it will return None, which isn't what the question asks for.
Here's a solution which resolves these issues.
def collatz(number):
    if number % 2 == 0:
        print(number // 2)
        return number // 2
    elif number % 2 == 1:
        print(3 * number + 1)
        return 3 * number + 1

num = int(input())
while num != 1:
    num = collatz(num)


text:
Q: How to make the web page scrollabe when the browser size is reduced? I am using HTML and CSS in my web application. I have defined all my attributes inside a table. When I change the size of my browser all the components are flushed together.
For example when I reduce the browser size on youtube a horizontal scroll bar appears which allows to navigate through the website but does not change anything on the home page. I want to implement something similar for my web app.
Inside the web page I a tried to put all the content inside a div and then use css style overflow:sroll for that. But it was no help.
I have an iframe inside my webpage.

I cannot post my entire code as it's way to long. It's more than 1000 lines.

A: Not sure about whether the code overflow:sroll was a typo or not, you can just change sroll to scroll instead.
Also, maybe because of other CSS snippet defined the overflow attribute later on, you can try add this to your CSS code :
body {overflow:scroll!important;}

*

*First, !important is added to overflow:scroll to make it more important - than the later-defined overflow attribute.

*Second, you don't need to wrap it in a
, which is more convenient.

For other elements, just add style="overflow:scroll;" or style="overflow:scroll!important;" in case you really need to change the overflow attribute again.
Fiddle

A: add "overflow-y:auto;" property into the css to perform scroll while resizing

A: I'm really confused with your question:
If you need a scroll bar in the iframe you could use scrolling="yes" like this example:
If your question is about an internal scroll in your div, you must use the overflow-x:scroll and the overflow-y:scroll
If your question is about resizing browser behavior, you could use @media screen
Example:
@media screen and (max-width: 480px) {
   //SOMETHING OF CSS HERE
}
/* Some android phone portrait screen width*/
@media screen and (min-width: 321px) and (max-width: 360px) {
  //SOMETHING OF CSS HERE
}

I hope it helps you, SALUT!

A: To implement scroll you must define height first, example if height is 200px, then if browser decrease its size more than 200px, only the overflow:scroll; will work, make sure you use border for demo purpose to table or div later try to use overflow, it should do a trick


text:
Q: Access a class within a function Using as an example the class defined here
class Testclass {
    private $testvar = "default value";
    public function setTestvar($testvar) {
        $this->testvar = $testvar;
    }
    public function getTestvar() {
        return $this->testvar;
    }
    function dosomething()
    {
        echo $this->getTestvar();
    }
}

$Testclass = new Testclass();
$Testclass->setTestvar("another value");
$Testclass->dosomething();

I would like to add inside a function "one more value", like this:
function test_function() {
    $Testclass->setTestvar("one more value");
}

But it doesn´t work. I gives the error message undefined variable Testclass. In order to make it work, I have to define the variable as global within the function, like this:
function test_function() {
    global Testclass;
    $Testclass->setTestvar("one more value");
}

I am quite new to PHP, but it seems rather strange to me this way of using it. From the main PHP file it´s already defined, but when I use it from a function I have to define again.Basically what I am trying to do is to create a class that creates a new file and adds strings to it from different functions.  Is there not a better way? Any suggestions? Many thanks in advance.

A: One way is to use singleton
MyClass::getInstance()->doSomethingUsefull();
Sometimes you can use static method
MyClass::doIt();

A: Functions have their own private variable scope. So (for example) you can use $i in a function without worrying about it screwing up another $i somewhere else in the program. If you want to have a function perform actions on an already-existing object, just pass the object as a parameter to the function:
function test_function(Testclass $testclass)
{
    $testclass->setTestvar("one more value");
}

Then call it with your object:
$Testclass = new Testclass();
test_function($Testclass);

Note: If the functions you're defining outside the class are tightly related to the class, then you probably want to define them as methods inside the class instead of separate stand-alone functions.


text:
Q: rails: Is there any way to run three migrations before the last migration without given version I have different migrations file
20120205111326_change_users_login_limit.rb
20120223110929_change_attachments_container_defaults.rb
20120223110300_change_locals_container_defaults.rb
20120223110301_change_position_tracs.rb
I want to run up migration of 20120205111326, 20120223110929,  20120223110300 just before the last migration but condition is that it should not  point its migration VERSION numbers...
Is there any ways to do it...please suggest me..
Thank you in advance

A: There is one way, Run your migration via rails console
require "db/migrate/20120205111326_change_users_login_limit.rb"
ChangeUsersLoginLimit.change # or 'up' or 'down' whatever method of that migration you want to run.

And do the same for all migration (don't forget to do it in sequence)
EDIT:
Rails actually don't provide a way to run migration skipping some. or run them by changing order. But the migration files are actually a ruby programs containing a single class. So you can always create a rake task and require migration in to rake task and run them in the custom logical order. After all migrations are the classes with methods.


text:
Q: Object reference error while reading specific JSON string? I have used JSON to C# Class Converter and it generates the following Class:
JSON
{"ios_info":{"serialNumber":"F2LLMBNJFFF","imeiNumber":"01388400413235","meid":"","iccID":"8901410427640096045","firstUnbrickDate":"11\/27\/13","lastUnbrickDate":"11\/27\/13","unbricked":"true","unlocked":"false","productVersion":"7.1.2","initialActivationPolicyID":"23","initialActivationPolicyDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","appliedActivationPolicyID":"23","appliedActivationDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","nextTetherPolicyID":"23","nextTetherPolicyDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","macAddress":"ACFDEC6C988A","bluetoothMacAddress":"AC:FD:EC:6C:98:8B","partDescription":"IPHONE 5S SPACE GRAY 64GB-USA"},"fmi":{"@attributes":{"version":"1","deviceCount":"1"},"fmipLockStatusDevice":{"@attributes":{"serial":"F2LLMBNJFFFQ","imei":"013884004132355","isLocked":"true","isLost":"false"}}},"product_info":{"serialNumber":"F2LLMBNJFFF","warrantyStatus":"Apple Limited Warranty","coverageEndDate":"11\/25\/14","coverageStartDate":"11\/26\/13","daysRemaining":"497","estimatedPurchaseDate":"11\/26\/13","purchaseCountry":"United States","registrationDate":"11\/26\/13","imageURL":"http:\/\/service.info.apple.com\/parts\/service_parts\/na.gif","explodedViewURL":"http:\/\/service.info.apple.com\/manuals-ssol.html","manualURL":"http:\/\/service.info.apple.com\/manuals-ssol.html","productDescription":"iPhone 5S","configDescription":"IPHONE 5S GRAY 64GB GSM","slaGroupDescription":"","contractCoverageEndDate":"11\/25\/15","contractCoverageStartDate":"11\/26\/13","contractType":"C1","laborCovered":"Y","limitedWarranty":"Y","partCovered":"Y","notes":"Covered by AppleCare+ - Incidents Available","acPlusFlag":"Y","consumerLawInfo":{"serviceType":"","popMandatory":"","allowedPartType":""}}}

From Above JSON all the data is read but only the line at which i get error is in reading the JSON is:
fmi":{"@attributes":{"version":"1","deviceCount":"1"},"fmipLockStatusDevice":{"@attributes":{"serial":"F2LLMBNJFFFQ","imei":"013884004132355","isLocked":"true","isLost":"false"}}},

Error:
Object Reference not set to an instance of object.
public class AppleAPI
{
    public IosInfo ios_info { get; set; }
    public ProductInfo product_info { get; set; }
    public Fmi fmi { get; set; }
    public class IosInfo
    {
        public string serialNumber { get; set; }
        public string imeiNumber { get; set; }
        public string meid { get; set; }
        public string iccID { get; set; }
        public string firstUnbrickDate { get; set; }
        public string lastUnbrickDate { get; set; }
        public string unbricked { get; set; }
        public string unlocked { get; set; }
        public string productVersion { get; set; }
        public string initialActivationPolicyID { get; set; }
        public string initialActivationPolicyDetails { get; set; }
        public string appliedActivationPolicyID { get; set; }
        public string appliedActivationDetails { get; set; }
        public string nextTetherPolicyID { get; set; }
        public string nextTetherPolicyDetails { get; set; }
        public string macAddress { get; set; }
        public string bluetoothMacAddress { get; set; }
        public string partDescription { get; set; }
    }

    public class ConsumerLawInfo
    {
        public string serviceType { get; set; }
        public string popMandatory { get; set; }
        public string allowedPartType { get; set; }
    }

    public class ProductInfo
    {
        public string serialNumber { get; set; }
        public string warrantyStatus { get; set; }
        public string coverageEndDate { get; set; }
        public string coverageStartDate { get; set; }
        public string daysRemaining { get; set; }
        public string estimatedPurchaseDate { get; set; }
        public string purchaseCountry { get; set; }
        public string registrationDate { get; set; }
        public string imageURL { get; set; }
        public string explodedViewURL { get; set; }
        public string manualURL { get; set; }
        public string productDescription { get; set; }
        public string configDescription { get; set; }
        public string slaGroupDescription { get; set; }
        public string contractCoverageEndDate { get; set; }
        public string contractCoverageStartDate { get; set; }
        public string contractType { get; set; }
        public string laborCovered { get; set; }
        public string limitedWarranty { get; set; }
        public string partCovered { get; set; }
        public string notes { get; set; }
        public string acPlusFlag { get; set; }
        public ConsumerLawInfo consumerLawInfo { get; set; }
    }

    public class Fmi
    {
        public Attributes invalid_nameattribute { get; set; }
        public FmipLockStatusDevice fmipLockStatusDevice { get; set; }
    }
    public class FmipLockStatusDevice
    {
        public Attributes2 invalid_nameattribute2 { get; set; }
    }
    public class Attributes
    {
        public string version { get; set; }
        public string deviceCount { get; set; }
    }

    public class Attributes2
    {
        public string serial { get; set; }
        public string imei { get; set; }
        public string isLocked { get; set; }
        public string isLost { get; set; }
    }
}

Reading JSON:
string responseText = string.Empty;
AppleAPI appobj = new AppleAPI();
responseText = appobj.VerifyAppleESN(newEsn);
var resobj = JsonConvert.DeserializeObject<AppleAPI>(responseText.Replace("@",string.Empty));
lblSerialNumber.Text = resobj.product_info.serialNumber;
.
.
lblappliedActivationDetails.Text = resobj.ios_info.appliedActivationDetails;
.
.
//getting here error below line: Object ref notset to instance of object
lblfmiVersion.Text = resobj.fmi.invalid_nameattribute.version;

Any Idea?

A: If you're getting Object Reference not set to an instance of object. that means that you're trying to access properties on an object that is null.  Since you said it happens on this line:
lblfmiVersion.Text = resobj.fmi.invalid_nameattribute.version;

that could mean that any of resobj, resobj.fmi, or resobj.fmi.invalid_nameattribute are null.  Ignoring the fact that you should have proper null checks in your code to help avoid this situation, let's ask the question, why would any of these objects be null if deserialization succeeded?  Perhaps some of the data was not deserialized correctly after all.
When deserializing using Json.Net, it is important to know that if any members of a class do not have matching properties in the JSON, those members will be skipped by Json.Net and thus retain their default values, e.g. null.  So one possible reason that you have a null is that the name of a property in your class does not match what is in the JSON.
If we take a look at your Fmi class, one thing that jumps out right away is that it has a suspiciously named property called invalid_nameattribute.  In the JSON, there is no such property.  Instead, there is a property called @attributes.  Your FmipLockStatusDevice class has the same problem.  Since they didn't match up, these properties did not get populated during deserialization, so they are null.
So how can we fix this?
This is simple enough: add a [JsonProperty] attribute to your class properties to map them to the right JSON properties.  (While you're at it, you might also consider changing the names of those properties in your C# class to something that actually makes sense, like "Attributes".)
public class Fmi
{
    [JsonProperty("@attributes")]
    public Attributes invalid_nameattribute { get; set; }
    public FmipLockStatusDevice fmipLockStatusDevice { get; set; }
}

public class FmipLockStatusDevice
{
    [JsonProperty("@attributes")]
    public Attributes2 invalid_nameattribute2 { get; set; }
}

OK, now that you have a solution, you should ask yourself, how did you get into this situation in the first place, and how can you avoid it in the future?
You said you used json2csharp.com to generate your classes.  You need to be aware that this tool is not foolproof, and will not always be able to generate correct classes to work with your JSON.  This is true whenever the JSON property names contain punctuation characters or spaces or start with numbers, because these cannot be turned into valid C# property names.  In these cases, json2csharp.com will generate a property name that starts with "invalid".  You need to look for these, and make manual adjustments to your classes to fix the issues.  Do not just blindly use the generated classes and assume they are correct.
Hope this helps.


text:
Q: Angular 2 project structure planning So, I already passed Anguar 2 QUICKSTART guide and read some topics, related to my question. Currently I'm trying to implement latest (2.1) Angular version.
So, I have next files in my angular app root directory
app.component.ts
main.ts
app.module.ts

If you are fimilar with Angular 2.1, then you may know that directives key word was removed from component decorator, so I should register any new directive in app.module.ts file, like so
@NgModule({
    imports:    [ BrowserModule ],
    declarations: [
        AppComponent,
        AutoGrowDirective,
        DirecComponent,
        BaseComponent
    ],
    bootstrap:    [ AppComponent ]
})

So, to add a new page to my project I can simply specify new route and assign it to a some base component, let's call them page component.
RouterModule.forRoot([
            {
                path: '',
                component: BaseComponent
            },
            {
                path: 'heroes',
                component: DirecComponent
            }
        ])

But, what if I want a lot of different components, that will be included to my page components?
I need to create a lot of reusable micro components, is it ok to add them into declarations array, possible I need a 200 of them or something.
When my project bootstraping - all of them will be loaded? Even if not all of them included to currently requested page component?
I want to hear your thoughts about it, thanks!


text:
Q: Capture mysql database error and use it in php I created the following table for user to user subscriptions.
CREATE TABLE IF NOT EXISTS `subscriptions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `subscribed_to` int(11) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_subscription` (`user_id`,`subscribed_to`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=76 ;

I'm disallowing identical rows by making the columns user_id and subscribed_to unique. If a user tries to resubmit the same data I get:

A Database Error Occurred Error Number: 1062
Duplicate entry '62-88' for key 'unique_subscription'
INSERT INTO subscriptions (user_id, subscribed_to, date) VALUES ('62',
  '88', '2011-07-11 19:15:13')
Line Number: 330

I'm preventing the database error by checking if an identical row exists before trying to insert data.
$query = "SELECT COUNT(*) FROM subscriptions WHERE (user_id = '62' AND subscribed_to = '88')";

if ($query > 0)
{
    //display already subscribed message
}
else
{
    //insert new row
}

The database already checks the table and returns an error. The select count(*) query above seems redundant. Do I really need to check the table once more in my application? Is there a way to capture the database error if it occurs, and do something with that in my application?
If you have an idea how please share an example. I haven't a clue how this is done..!

A: Check out PHP function mysql_error
You can wrap the db call within a try catch statement for functions that throw exceptions to prevent your application from crashing.
PHP function mysql_query does not throw exception on error, but returns FALSE. You can check the return value and execute mysql_error to find out the trouble or log it.


text:
Q: Confusion in terminology while defining Balanced Binary Tree: Height of a subtree vs. Height of a node Referencing the answer to this question
A balanced binary tree is:

*

*The left and right subtrees' heights differ by at most one, AND

*The left subtree is balanced, AND

*The right subtree is balanced

Now, using the same example
     A
   /   \
  B     C
 /     / \
D     E   F
     /
    G

The tree is rooted at A.
Now, when looking at the definition for height balanced tree, the first point says:

*

*The left and right subtrees' heights differ by at most one
If I am currently at the node A, to determine the height of the LEFT SUBTREE of A I am confused if I calculate:

*

*Height of node A looking at the deepest left child from A (D)      OR

*Height of node B looking at the deepest left child from A (by extension B) (D)

If I am currently at the node A, to determine the height of the RIGHT SUBTREE of A I am confused if I calculate:

*

*Height of node A looking at the deepest right child from A (F)      OR

*Height of node C looking at the deepest right child from A (by extension C) (F)

A: 'The height of a subtree' is generally translated as 'height of the root of the subtree'. Bumped into this explanation while listening to this MIT OpenCourseWare lecture, at timestamp 13:17.


text:
Q: OS X and apps keep forgetting saved credentials and login status The past couple of weeks, several apps have forgotten stored credentials a number of times:

*

*Google and iCloud account configured on the Macbook (have had to verify my Google account using 2-step verification for the 2nd time in 30 days)

*Facebook, Stack Exchange et al. keep logging me out (= session cookies seem to get wiped between browser restarts)

*Stored VPN passwords

*Skype

for no apparent reason. I haven't been installing any new apps. The only thing that has changed is a second screen.
Keychain Manager appears to be showing all entries without any problems. The "last changed" date for each entry looks okay (six months to several years back).
What could be causing this? Do I need to be worried?
I'm running a Macbook pro 15 (Late 2011) with Yosemite.


text:
Q: How do I display user profiles around my area using xcode while buiding an app? I need to access user profiles in my area for my app. Like accessing an image that a user uploads in my app. But I need to show all the images of all users in and around the area of the logged in user in my app.
I need help with this. :)

A: You can accomplish this by continously uploading the current location of each user , and when a logged in one tries to see other profiles in your server according to a specifed region you set loop for all users that exists in this region and send their profies as the search result


text:
Q: Domain Driven Design - testability and the "new" keyword I have been trying to follow a domain driven design approach in my new project.  I have always generally used Spring for dependency injection, which nicely separates my application code from the construction code, however, with DDD I always seem to have one domain object wanting to create another domain object, both of which have state and behaviour.
For example, given a media file, we want to encode it to a different format - the media asset calls on a transcode service and receives a callback:
class MediaAsset implements TranscodingResultListener {

    private NetworkLocation permanentStorage;
    private Transcoder transcoder;

    public void transcodeTo(Format format){
        transcoder.transcode(this,format);
    }

    public void onSuccessfulTranscode(TranscodeResult result){
        Rendition rendition = new Rendition(this, result.getPath(), result.getFormat());
        rendition.moveTo(permanentStorage);
    }

}

Which throws two problems:

*

*If the rendition needs some dependencies (like the MediaAsset requires a "Transcoder") and I want to use something like Spring to inject them, then I have to use AOP in order for my program to run, which I don't like.

*If I want a unit test for MediaAsset that tests that a new format is moved to temporary storage, then how do I do that?  I cannot mock the rendition class to verify that it had its method called... the real Rendition class will be created.

Having a factory to create this class is something that I've considered, but it is a lot of code overhead just to contain the "new" keyword which causes the problems.
Is there an approach here that I am missing, or am I just doing it all wrong?

A: I think that the injection of a RenditionFactory is the right approach in this case. I know it requires extra work, but you also remove a SRP violation from your class.  It is often tempting to construct objects inside business logic, but my experience is that injection of the object or a objectfactory pays off 99 out of 100 times. Especially if the mentioned object is complex, and/or if it interacts with system resources.

A: I assume your approach for unit testing is to test the MediaAsset in isolation. Doing this, I think a factory is the common solution.
Another approach is to test the whole system (or almost the whole system). Let your test access the outer interface[1] (user interface, web service interface, etc) and create test doubles for all external systems that the system accesses (database, file system, external services, etc). Then let the test inject these external dependencies.
Doing this, you can let the tests be all about behaviour. The tests become decoupled from implementation details. For instance, you can use dependency injection for Rendition, or not: the tests don't care. Also, you might discover that MediaAsset and Rendition are not the correct concepts[2], and you might need to split MediaAsset in two and merge half of it with Rendition. Again, you can do it without worrying about the tests.
(Disclaimer: Testing on the outer level does not always work. Sometimes you need to test common concepts, which requires you to write micro tests. And then you might run into this problem again.)
[1] The best level might actually be a "domain interface", a level below the user interface where you can use the domain language instead of strings and integers, and where you can talk domain actions instead of button clicks and focus events.
[2] Perhaps this is actually your problem: Are MediaAsset and Rendition the correct concepts? If you ask your domain expert, does he know what these are? If not, are you really doing DDD?


text:
Q: Wordpress memory error I just installed a plug in I had purchased named "Timely Pro". Its an interactive calender program that allows the administrator to post new events with a description and images. Whenever I go into the back end and try view all of the events I've created, it throws this error:

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 32 bytes) in /home/content/75/10928675/html/wp-includes/wp-db.php on line 1551

I changed my memory limit in both php.ini and wp-config to 512M

php.ini: memory_limit = 512M
  wp-config.php: define('WP_MEMORY_LIMIT', '512M');

Changing this did nothing for the error. Does anyone know any other definitions somewhere that could be causing this error?

A: A couple of things you could check/try:

*

*Verify that you've restarted Apache.

*Verify that you are editing the right php.ini file. I use MAMP and each version of PHP naturally has its own copy. I made this mistake once before.

*Check your Apache config's memory limit (e.g., httpd.conf). This SO answer might be of help: https://stackoverflow.com/a/14573923.


text:
Q: Matlab log2 graph scale I have been trying to put my graphic axis in log2 scale but something quite odd appears on the figure. The first data 63 appears at the beggining and the end of the x-scale and for some reason the first point does not appear. Also the points are not exactly centered on the x-ticks... do you have any idea why ?
Thanks in advance for you help !!!
clear all; clc;
%% Vectors

freq=[63 125 250 500 1000 2000 4000 8000 16000]
logfreq=log2(freq);
Lp1=[93.9 93.9 93.8 93.8 93.8 93.6 93.3 91.8 87.8]
Lp2=[93.9 93.9 93.8 93.8 94 94.1 94.4 94.6 95.3]
Lp3=[93.9 93.9 93.9 93.8 94.1 94.4 95.2 97.2 100.9]

%% Plot

figure
plot(log2(freq),Lp1,'+-','linewidth',1.7)
hold on; grid on;
plot(log2(freq),Lp2,'+-','linewidth',1.7)
plot(log2(freq),Lp3,'+-','linewidth',1.7)
set(gca,'fontsize',20)
set (gca, 'XTickLabel', logfreq);
set(gca,'XTickLabel',
{'63','125','250','500','1000','2000','4000','8000','16000'})
xlabel('Frequency [Hz]','fontsize',20)
ylabel('Pressure Level [dB]','fontsize',20)
leg=legend({'Sin correcion','Campo libre','Incidencia aleatoria'},'fontsize',18)

And here is the figure :

A: You want
set(gca,'XTick',logfreq);

instead of set(gca,'XTickLabel',logfreq)
With your incorrect code, the 63 appears at the start and the end because there are (incorrectly) 10 x tick locations but you are specifying only 9 labels, and hence the first one is repeated.  (If you'd only specified 8 then the first 2 would be repeated, etc.)


text:
Q: Spring kafka - Offset not setting on error In my listener after consuming the message if any exception happens then I throw an exception. If its successful then I acknowledge. But even if an exception thrown the offset is not getting set back. i.e the retry didn't happened as expected. The error event not coming again.
Also I see I am not consuming all the expected messages. Is there something I am doing wrong?
@Bean
public ConcurrentKafkaListenerContainerFactory<String,Result<FormatException,String>> kafkaListenerContainerFactory(){
    ConcurrentKafkaListenerContainerFactory<String, Result<FormatException, String>> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(this.consumerFactory());
    factory.setErrorHandler(new SeekToCurrentErrorHandler(3));
    factory.getContainerProperties().setAckOnError(false);
    factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);

    return factory;
}

public ConsumerFactory<String, Result<FormatException, String>> consumerFactory() {
   kafkaProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
    kafkaProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
}

Listener Class
@KafkaListener(topics = "${gpc.consumer.topic}")
    public void listenWithHeadersGPC(ConsumerRecord<String, Result<FormatException, String>> consumerRecord,
            Acknowledgment acknowledgment) {
        try {
            String body = consumerRecord.value().get();
            log.logInfo("Received message for " + GPCSourceName + ": " + body);
            log.logInfo("consumption successful from kafka. partition="+consumerRecord.partition()+", "
                    + "offset="+consumerRecord.offset());
                            if(body.contains("berlin+braze@gmail.com")) {
                                throw new RuntimeException("custom exception");
                            }
                            log.logInfo("Filtered message for " + GPCSourceName + " : " + body);
            acknowledgment.acknowledge();
        }catch(Exception e) {
            log.logError("Exception occurred in listenWithHeadersGPC: ", e);
            throw e;
        }
    }

I am doing acknowledgment.acknowledge(); in my listener if there is no exceptions
Edit: Spring Kafka Version: 2.2.8

A: factory.setErrorHandler(new SeekToCurrentErrorHandler(3));
With that configuration you should see 3 retries with zero delay between them; finally the record will be logged.
By default, the offset of the "recovered" record won't be committed.
When posting questions like this; indicate which version you are using.
Starting with version 2.3, you can use acknowledgment.nack(sleepTime); you can also call setCommitRecovered(true) on the SeekToCurrentErrorHandler and the offset of the recovered record will be committed (with MANUAL_IMMEDIATE).
This will all only happen if the exception is thrown to the container; if you catch the exception in your listener you won't see retries.
If you are not seeing retries at all, and your listener is throwing an exception, there is something wrong with your listener or configuration. Show all your configuration and the @KafkaListener code.


text:
Q: is it possible to build a graph having the adjacency matrix? I am readying about graph theory in sagemath or python,
g2=Graph({0:[1,2,3,4,5], 1:[2,3,4,5], 2:[5], 3:[4,5], 4:[5]})

if g2 is the graph, then with
g2.adjacency_matrix()

SAGEMATH easily constructs the adjacency matrix, I was wondering if it is possible or is there some code where if I have the adjacency matrix sage or python build the graph

thanks davidlowryduda,, Now  I have this matrix
T= array([[ 0, 0, 0,  1,  1],
          [0,  0,  1, 0,  1],
          [0,  1,  0,  1, 0],
          [ 1, 0,  1,  0, 0],
          [ 1,  1, 0, 0,  0]])

but, for
 G = Graph(T, format='adjacency_matrix'),

I need this type!
matrix([[0, 0, 0,  1,  1],[0,  0,  1, 0,  1],[0,  1,  0,  1, 0],[ 1, 0,  1,  0, 0],[ 1,  1, 0, 0,  0]]).

Is it possible to transform from array to the form I need to be able to load that code?

A: Sage will very happily plot the graph for you if you give it a matrix.
For your g2, if you simply type g2 at an interactive sage session, then it will present you with a plot of a graph. g2.show() and g2.plot() are other ways to cause the graph to display.
You can save the image using something like
p = g2.plot()
p.sage_image("file.png")

If you start from a adjacency matrix, sage will happily make a plot for you. For example,
M = matrix([[0 1 0 0 0 0],
[0 0 1 0 1 0],
[0 0 0 1 1 0],
[0 0 0 0 0 0],
[0 0 0 0 0 1],
[0 0 0 0 0 0]])
sage: G = DiGraph(M, format='adjacency_matrix')
sage: G.show()

Given a symmetric matrix, it makes sense to use Graph instead of Digraph.


text:
Q: Как выгрузить DataGrid в XML? Имеется DataGrid. Есть проблемы с выгрузкой содержимого в XML.
Класс для сериализации
[Serializable]
public class Buttons
{
    public bool VisibilityBut { get; set; }

    public string Name { get; set; }

    public string PathImag { get; set; }

    public string PathExe { get; set; }
}

Если делаю сериализацию так
XmlSerializer formatter = new XmlSerializer(typeof(Buttons));
using (FileStream fs = new FileStream(@"XML.XML", FileMode.OpenOrCreate))
    formatter.Serialize(fs, DataGrid1);

то файл создаётся пустым и возникает исключение

System.InvalidOperationException: "Ошибка при создании документа XML." InvalidCastException`: Не удалось привести тип объекта "System.Windows.Controls.DataGrid" к типу "ПанельКнопок.Buttons".

А если так делаю:
if (DataGrid1.ItemsSource == null) return;
var serializer = new XmlSerializer(typeof(List<Buttons>));
var writer = new StreamWriter("XML.xml");
serializer.Serialize(writer, DataGrid1.ItemsSource as List<Buttons>);
writer.Close();

то в файле создается только заголовок XML, и всё остальное пусто, путем подбора типов, решение такое.
ObservableCollection<ButtonEIIS> collection = null;

    private void butSaveXML_Click(object sender, RoutedEventArgs e) // нажали кн. "Сохранить в XML"
    {
        var serializer = new XmlSerializer(typeof(ObservableCollection<Buttons>));

        using (FileStream fs = new FileStream(@"XML.XML", FileMode.OpenOrCreate))
        {
            serializer.Serialize(fs, DataGrid1.ItemsSource as ObservableCollection<Buttons>);
        }
    }

в XAML привязка такая
<DataGrid x:Name="DataGrid1" Margin="10,171,10,52" FontSize="14" AutoGenerateColumns="False">

        <DataGrid.Columns>
            <DataGridCheckBoxColumn Header="Вид" Binding="{Binding VisBut}"/>
            <DataGridTextColumn Header="Надпись на кнопке (папка подсистемы)" Binding="{Binding NameSubEIIS}"/>
            <DataGridTextColumn Header="Полный путь к картинке" Binding="{Binding PathPNG}"/>
            <DataGridTextColumn Header="Полный путь к запускаемому приложению" Binding="{Binding PathEXE}"/>
        </DataGrid.Columns>
    </DataGrid>


text:
Q: Use grep and get text after the pattern I need to get the IP from a log I need to grep the true-client and after that I need to grep true-client-ip=[191.168.171.15] and get just the IP
2019.02.14-08:26:06:713,asd:1234:chan,0.000,asd,S,request-begin-site,POST,{remoteHost=1.2.3.4,remoteAddr=1.2.3.4,requestType=POST,serverName=api=[text/html],accept-charset=[iso-12345-15, utf-8;q=0.5, *;q=0.5],accept-encoding=[gzip],server-origin=[5],cache-control=[no-cache, max-age=0],pragma=[no-cache],program-header=[true],te=[chunked;q=1.0],true-client-ip=[191.168.171.15],true-host=[www.server.com]

I was trying  grep -o "true-client-ip=[^ ]*," but it brings me:
true-client-ip=[191.168.171.15],true-host=[www.server.com]

I need just true-client-ip=[191.168.171.15] so I can cut after to bring get the IP like true-client-ip=[191.168.171.15] | cut -d= -f2

A: Using grep -P flag if available :
grep -oP 'true-client-ip=\[\K[^]]*'

Perl's \K meta-character discards what precedes when displaying the result, so it will match the "true-client-ip=[" part but only display the IP.
If grep -P isn't available, I would use sed :
sed -nE 's/.*true-client-ip=\[([^]]*).*/\1/p'

A: If you have GNU grep, you can do it like this:
$ grep -oP "(?<=true-client-ip=\[)[^\]]*" file
191.168.171.15

The (?<=) is called Positive Lookbehind, which you can find related doc here.
The backslash \ in [^\]] is actually unnecessary, I just feel like to add it to make it more intuitive, less misleading-prone :-) .


text:
Q: Jquery-ui-rotatable , How to make a cloned element rotatable? I am using the code below found on
http://www.placona.co.uk/166/javascript/a-more-elaborated-jquery-drag-drop-cloning/
http://examples.placona.co.uk/drag_drop
For drag-drop-clone .
In the same code I have tried to implement , rotatable(params)
with jquery-ui-rotatable to the "cloned " element .
It does not function .
Where should I place the code below to make the clone rotatable
The clone here is draggable .
 var params = {
        start: function(event, ui) {
            console.log("Rotating started");
        },
        rotate: function(event, ui) {
            console.log("Rotating");
        },
        stop: function(event, ui) {
            console.log("Rotating stopped");
        },
    };  $('#drag1').resizable().rotatable(params);

When I implement it either draggable property is lost or there are 2 clones instead of one .


text:
Q: How do you carry over values from another def? so i just started learning python in school and I've been practicing it at home so i am new to python.
The problem im having is that i am trying to carry over the values from def two() into main(), however when i use {0} to put them in a print or a calculation, it says error and that they don't have any value.
here's my code:
def two():
  print("Hello world!")
  print("Please enter three numbers")
  nam=int(input("Enter the first number: "))
  num=int(input("Enter the second number: "))
  nom=int(input("Enter the third number: "))
  print("So the numbers you have entered are {0}, {1},{2}.".format(nam,nom,num))

def main():
  main=two()
  inpt=input("what math related problem would you like me to do with them? tell me here: ").capitalize()
  if inpt== "Divide":
    ans=({0}/{1}/{2})/1
    print("{0}, there you go!")
  elif inpt== "Times":
    ans=(nam*num*nom)/1
    print("{1}, there you go!")

And heres what i get from running it:
>>> main()
Hello world!
Please enter three numbers
Enter the first number: 30
Enter the second number: 30
Enter the third number: 30
So the numbers you have entered are 30, 30, 30.
what math related problem would you like me to do with them? tell me here:    divide
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
main()
File "C:\Users\chemg\Documents\PracticePY.py", line 40, in main
ans=({0}/{1}/{2})/1
TypeError: unsupported operand type(s) for /: 'set' and 'set'

A: You can return the values from your previous function and then set them to be variables.
At the end of two()
return nam, num, nom

In main() where you set main = two()
nam, num, nom = two()

Also, you should rename main you can override functionality by using namespaces that are already reserved.
You can then do division with these values
ans = nam / num / nom

As it is now these are singletons i.e. - sets containing one element.
You can then use format to input these into your strings in your print statements

A: In your code here:
ans=({0}/{1}/{2})/1

{0}, {1} and {2} are sets containing one element. You can't divide sets, which is what the error is complaining about.
You will need to pass the values from two() to main(). See Slayer's answer for details as to how that is done.
You cannot just use the {0} tokens where-ever you want because they are read from strings by format() to format text. Outside a string it's a set containing zero.

A: The issue at play here is that you're attempting to apply string formatting to a non-string operation within your main function.
print("So the numbers you have entered are {0}, {1},{2}.".format(nam,nom,num))

The curly braces that you're using in the line above only substittue for values within that single format function call. When you call ans=({0}/{1}/{2})/1 , you're actually creating three separate sets; that's a different Python data type. You're getting that error because sets are not meant to be divided like your code is attempting to do.
As mentioned in Slayer's answer, your best bet is to return all three variables form your 'two' function:
return nam, num, nom

That way, you can assign them other variable within your main function. I would highly recommend against creating a variable that's named the same thing as your function too. It'll create some very confusing behavior for you.
nam, num, nom = two()

Finally, the line of code that's actually creating the exception can be modified to work.
ans = nam / num / nom


text:
Q: Can I use the Android/Google speech recognition software on another platform? I have just acquired an Android phone recently... wonderful stuff. Starting to look at the OS guts and how to program the thing.
The voice-recognition-for-dictation is good too... given that this is an open-source OS, is there any way of harnessing the Android-Google speech recognition?  My current understanding is that the voice trace has to be sent to the Google servers to be processed, i.e. the software is not on the machine.  But I may be wrong!
Either way, does anybody have any idea whether such harnessing for one's own apps (on Android or another OS on a full-size 'puter, for example) is possible?

A: If you are talking about using voice recognition in your code somehow, then you can use it with the help of SpeechRecognizer class(http://developer.android.com/reference/android/speech/SpeechRecognizer.html) and RecognizerIntent.
But you can only use the currently existing functionality to some extent only.
About the confusion as to whether it lies in device or not, try using your Voice Recognition after turning off internet on your phone. It wont work.
You can also look into API Demos for some example:
sdk\samples\android-10\ApiDemos\src\com\example\android\apis\app\VoiceRecognition.java


text:
Q: Why table is not printed correctly with echo? I am following this tutorial to print the values of a submited file using echo in php.
Tutorial: http://www.learncomputer.com/tutorial-uploading-files-in-php/
<?php //Whole php code
echo "
";
echo "
Client FileName:
" . $_FILES["fileName"]["name"] . "
";
echo "
File Type:
" . $_FILES["fileName"]["type"] . "
";
echo "
File Size:
" . ($_FILES["fileName"]["size"] / 1024) . " Kb
";
echo "
Name of Temporary File:
" . $_FILES["fileName"]["tmp_name"] . "
";
echo "
";
?>

Nevertheless, when I upload and submit an image, the following result is printed on screen
"; echo "Client Filename: " . $_FILES["fileName"]["name"] . ""; echo "File Type: " . $_FILES["fileName"]["type"] . ""; echo "File Size: " . ($_FILES["fileName"]["size"] / 1024) . " Kb"; echo "Name of Temporary File: " . $_FILES["fileName"]["tmp_name"] . ""; echo ""; ?>

which is not the expected table with the name, type, size and name of temporary file as expected. I have even tried to replace the quotes " for ' but unsuccessfully. I don´t understand why is the semicolon at the beginning been printed and the code instructions ".$var." insted of the actual value of the variables
EDIT: My PHP version 7.2.1 and here is the html code with which I submit and call my php code:
   <!DOCTYPE html>

<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">

<link rel="stylesheet" type="text/css" href="Tops.css">
<link rel="stylesheet" type="text/css" href="Ejemplo_botones.css">
<link rel="stylesheet" type="text/css" href="Config.css">
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous">

<link rel="stylesheet" href="">

Home

About

Contacto

Iniciar Sesión

Paso 1

  Paso 2

 Paso 3

 Paso 4

 Paso 5

Cargar foto de Perfil

<form action="upload_table.php " method="post" enctype="multipart/form-data">

        Elige una foto:

                <input class="plus" type="file" name="fileName" id="file-5" class="inputfile inputfile-4" data-multiple-caption="{count} files selected" multiple="" hidden>

<svg id="upload" xmlns="http://www.w3.org/2000/svg" width="180" height="170" version="1.1">
                   <path id="upload" fill="white" heigthstroke="#f00" transform="scale(3.0)" d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z"></path>
                    </svg>

<input class="subir" type="submit" value="+ Subir foto">

    </form>

Siguiente

Articulos de gran calidad &nbsp  - &nbsp  Relojes y Pulseras

A: There is no reason to try to put everything into echo. Let the HTML be just plain HTML and add the PHP data where needed.
// assuming you were already in PHP
?>

Client Filename:
<?php echo $_FILES['fileName']['name']; ?>

File Type:
<?php echo $_FILES['fileName']['type']; ?>

File Size:
<?php echo ($_FILES['fileName']['size'] / 1024); ?> Kb

Name of Temporary File:
<?php echo $_FILES['fileName']['tmp_name']; ?>

<?php // back into PHP if you need to for something else

A: You have to debug your PHP code, cause it seems correct.
The best way to start debugging is to try using fake static values in $_FILES to see what happen :
<?php

    $_FILES["fileName"] = [];
    $_FILES["fileName"]["name"] = 'test.jpg';
    $_FILES["fileName"]["type"] = 'image/jpg';
    $_FILES["fileName"]["size"] = 134767;
    $_FILES["fileName"]["tmp_name"] = '/tmp/temp_filename.jpg';

    echo "
";
    echo "
Client Filename:
    " . $_FILES["fileName"]["name"] . "
";
    echo "
File Type:
    " . $_FILES["fileName"]["type"] . "
";
    echo "
File Size:
    " . ($_FILES["fileName"]["size"] / 1024) . " Kb
";
    echo "
Name of Temporary File:
    " . $_FILES["fileName"]["tmp_name"] . "
";
    echo "
";

?>

If it doesn't work, copy one of your php file that work, put the same code in it, and replace the upload_table.php in it. Because if the start of your upload_table.php has BOM (Byte Order Mark can cause display problem in PHP), it will print some blank characters at the top, and possibly prevent php code execution. Or you can save the file utf8 without BOM. But I doubt this is related to BOM, bu you never know.


text:
Q: Excel data mapping I have two different data sheets in excel like below.
1st: A is first  column B is second
A -> B
2nd: B is first  column C is second
B -> C
I want to add them together so I can get
A -> B -> C  values mapped correctly.
The problem is there is about 50K value in each column, some of them are empty and values are not in order.
Thanks in advance.

A: You can use the VLOOKUP formula on the C column of the first sheet
See this link or this one to understand how to use the VLOOKUP statement.
If you want more precise help, show us some data so that we will help you building the formula.


text:
Q: 404 custom post type I've set up some custom post types and wanted to visit the pages but I only get 404 errors.
I've searched the web and it seems to be a known problem, but I didn't find a solution that worked for me.
I saved the permalinks several times and also tried the flush_rewrite_rules( false ); command on every post type. But nothing changes.
If I set the permalink structure to basic, everything works fine, so the post types are ok...
Can anyone think of another problem?
Maybe it's because I used the same permalink for a page (post_type => 'page)? But I've deleted that page and I cannot find anything else than my page of the custom post type with that title in the database. So everything should be fine.

The $args:
$args = array(
    'labels'              => $labels,
    'public'              => true,
    'has_archive'         => true,
    'publicly_queryable'  => true,
    'query_var'           => true,
    'rewrite'             => array(
                              'with_front' => true,
                              'slug'       => 'practical-courses'
                            ),
    'capability_type'     => 'page',
    'hierarchial'         => true,
    'supports'            => array(
                              'title',
                              'editor',
                              'excerpt',
                              'thumbnail',
                              'revisions',
                              'author',
                              'page-attributes',
                              'comments',
                            ),
    'menu_position'       => 20,
    'menu_icon'           => '',
    'exclude_from_search' => false,
  );

The register-call:
register_post_type('practical-courses',$args);


text:
Q: Horizontal Capillary Question I have a fluid mechanics question, that I think is caused by a lack of understanding of some key concepts. Suppose we have a horizontal capillary with a radius of 10um. The fabrication process has led to water having a contact angle of 110 degrees with 0.072N/m for the air-water surface energy. Based on the equation for capillary pressure we know that at least 4900Pa are needed to fill the tube.
My question is what happens when a 10cm column of water is connected to the capillary. Based on hydrostatics, this gives us a pressure of ~1000Pa, not enough to fill the horizontal capillary. What is the pressure when the vertical and horizontal sections meet? Is the pressure 1000Pa based on hydrostatics or is it 4900Pa due to the capillary pressure? It is my understanding that fluid pressure doesn't change along the horizontal under static conditions.
Thank you for taking the time to answer my question.


text:
Q: Trying to get user IP, referrer data in PHP- Why doesn't this code work? The following code:
<?php
    // Get referrer:
    $ref=@$HTTP_REFERER;
    echo "Referrer of this page  = $ref
";

    // Get IP:
    $ip=@$REMOTE_ADDR;
    echo "IP Address= $ip
";
?>

Returns:
Referrer of this page =
IP Address=
Why wouldn't this work? Thanks-

A: Try using:
$_SERVER['HTTP_REFERER']

And
$_SERVER['REMOTE_ADDR']

A: $HTTP_REFERER and $REMOTE_ADDR are not defined because register_globals is turned off.
Use $_SERVER['HTTP_REFERER'] and $_SERVER['REMOTE_ADDR'] instead. Do not turn on register_globals.

A: In addition to what James posted, you can also try:
getenv('HTTP_REFERER'); and getenv('REMOTE_ADDR');
if his don't work.

A: It looks like you're reading some outdated info or code somewhere, probably PHP 4 era. What version of PHP are you currently working with?
For info on what is predefined in current PHP versions and standard configurations, please see
http://php.net/manual/en/reserved.variables.php.


text:
Q: Console Title C++ , Linux Is there any function in C++ on Linux such as SetConsoleTitle(const) in Windows?
Maybe there is any library includes the same or very similar functions.

A: For a console application (whether C++ or otherwise) you would typically use an escape sequence to set the console title. The docs are here:

*

*Dynamic titles
So for a C++ app you might use something like:
std::cout << "\033]0;" << title << "\007";

This escape sequence will be interpreted by the shell and in tern the console app, and change the title accordingly.


text:
Q: Double Click on Kendo Grid row's for React Component I'm using the React Grid component and I'm looking for a way to fire a function when double click a row.
I found a rowClick function and I can use it now to select a row or handle an onClick event : <Grid rowClick={e => yourFunction(e)}> .
But there is no function to handle a doubleClick event.
This is my approach, I passed a onDoubleClick() function as props to my component, and bind it with the listener of doubleClick on componentDidMount for each row :
componentDidMount() {
    let { onDoubleClick } = this.props;
      if (onDoubleClick) {
        const rows = document
          .getElementsByClassName('k-widget k-grid')[0]
          .getElementsByClassName('k-grid-table')[0]
          .getElementsByTagName('tbody')[0]
          .getElementsByTagName('tr');
        for (let i = 0; i < rows.length; i++) {
          rows[i].addEventListener('dblclick', () => onDoubleClick());
        }
      }
  }

For the moment this works but I'm not able to pass the clicked row data to my function.
Is there any hack to retrieve the row's data using the element ?
Like this for example : onDoubleClick(kendo.data.DataSource(rows[i])) => return the json data to function.

A: The grid have a rowRender property, that can be used as a RenderProp for fully modifying the rows, including attaching them a rowClick using the native React approach.
rowRender(trElement, dataItem) {
    const trProps = {
        ...trElement.props,
        onDoubleClick: () => {
            //place your logic here
        }
    };
    return React.cloneElement(trElement, { ...trProps }, trElement.props.children);
}

You may find this live example for how to attach mouse mousedown, blur and focus for the GridRow in the InCell editing demo The same logic for the onDoubleClick can be used as in my code-snipped above.


text:
Q: Debian Linux kernel ABI versioning I'm trying to understand Debian kernel image package versioning.
Take this output for example:
$ apt search linux-image | grep amd64-unsigned

linux-image-5.10.0-10-amd64-unsigned/stable 5.10.84-1 amd64
linux-image-5.10.0-11-amd64-unsigned/stable-security 5.10.92-1 amd64
. . .

If I understand it correctly, we have:

*

*Kernel version 5.10.84-1 → ABI version 5.10.0-10

*Kernel version 5.10.92-1 → ABI version 5.10.0-11

Clearly, Linux kernel doesn't seem to follow the semver model as the ABI is changing rather arbitrarily between patch releases.
So how does Debian determine when the ABI version number needs to be bumped?

A: This is documented in the Debian kernel handbook (Debian users can also install the debian-kernel-handbook package):

Maintaining and updating the ABI
In order to avoid the need for users to rebuild out-of-tree modules frequently,
we try to avoid changing the kernel ABI during updates to a Debian stable or
oldstable release.  Most importantly, we avoid making such changes without
changing the ABI name, except where it appears that out-of-tree modules do not
depend on that part of the ABI.
Bug fixes or configuration changes to the kernel may alter the ABI.  If an
exported function is conditional on
CONFIG_FOO, or it uses a type
whose definition depends on
CONFIG_FOO, then turning
CONFIG_FOO on or off changes the
ABI of that function, and thus of the kernel as a whole.  Enabling or changing
the configuration of a single driver usually doesn't change the ABI, because
most drivers don't export anything.
The kernel build process generates a 'symbol version' for each exported
function or variable.  This is a hash of the definitions that it depends on,
and should change whenever the function's ABI changes.  The kernel module
loader detects incompatible modules by comparing symbol versions.  The whole
set of symbol versions represents the kernel ABI.
We collect the symbol versions for previously uploaded packages under the
directory debian/abi and then compare the new kernel with
those.  If the ABI name is unchanged but the ABI itself is changed - except for
additions, or changes that we have marked as acceptable - then the build is
aborted.

So essentially, the ABI is changed if compatibility with existing modules can't be guaranteed. ABI bumps are traced in the package changelog, albeit not necessarily with the specific reason for the bump (there may well be more than one).
See Debian Linux kernel versioning for a more general description of the Debian kernel versioning scheme.


text:
Q: Interactive session with another application in child process in Python I have an application(.exe) written in any language eg. C++ and want to run the application from python. I can run that simple application by using below sample Python code by following tutorial here https://docs.python.org/2/library/subprocess.html
from subprocess import Popen, PIPE

process = Popen([r"C:\Users\...\x64\Debug\Project13.exe"],stdout = PIPE,
stderr=PIPE, stdin = PIPE)
stdout = process.communicate(input = b"Bob")[0]
print(stdout)

C++ code:
#include <iostream>
#include <windows.h>
#include <string>

using namespace std;

void foo(string s) {
    for (int i = 0; i < 3; ++i)
    {
        cout << "Welcome " << s << " ";
        Sleep(2000);
    }
}

int main()
{
    string s;
    cin>> s;
    foo(s);
    return 0;
}

This works fine for me. But what if i am reading input in C++ application multiple times as below:
#include <iostream>
#include <windows.h>
#include <string>

using namespace std;

int main()
{
    string s;
    for (int i = 0; i < 3; ++i)
    {
        cin >> s;
        cout << "Welcome " << s << " ";
        Sleep(2000);
    }
    return 0;
}

Here i am not able to use process.communicate() multiple times since the child has already exited by the time it returns.Basically i want to interact with the programme as a continuous session.
I want suggestion or any other approach to solve this issue in python? Thanks in advance.

A: Assuming you are working on windows I would suggest having a look at namedpipes, on python end you can use PyWPipe, on c++ end you will have to write your own wrappers to get the message for the process.


text:
Q: CSS border bigger than picture I'm trying to find out how I can make the border around my picture bigger than the image it self in CSS. See the pictures for an example:
Wrong border:

Correct border:

I want the image to be the original size independent from the border "size".

A: JSFiddle
HTML:
<img src="http://www.langology.org/wp-content/uploads/2011/03/hello1.jpg"/>

CSS:
img{
border-color: black;
border-width: 5px;
border-style: solid;
padding: 5px;

}
You can vary the padding value so that you can adjust the border with respect to image.

A: You need padding on the image's parent element to push the border out away from the image.

A: You could put the image in a <div> and set specific height and width values for that div. Then add the border to the div instead of the image.

A: You need to use css padding on the image element or it's parent to achieve your desired effect. See this link for more information.


text:
Q: Discord py How to add role by name not id How to add role by name not id. group is string
await message.author.add_roles(message.author, group)

A: You can use discord.utils.get function for this:
role_name = "role"  # specify role name here
role = discord.utils.get(message.guild.roles, name=role_name)
if role is not None:
    await message.author.add_roles(role)


text:
Q: Dynamic Links Custom Path not applied in Firebase Authentication I have setup Firebase Dynamic Links with an URL in the following format: a.b.c/d
However, emails sent by Firebase Authentication contain Dynamic Links of the format a.b.c/?link=... instead of a.b.c/d/?link=..., which means that they do not work.
I followed this guide / this guide to send the links.
Whenever I manually copy the link and add d/ in the URL, the Dynamic Links will work since Dynamic Links is set up this way in Firebase Console and also in firebase.json for Firebase Hosting.
"appAssociation": "AUTO",
"rewrites": [
  {
    "source": "/d/**",
    "dynamicLinks": true
  }
]

A: Unfortunately, Firebase Authentication does not yet support custom paths in Dynamic Links as bojeil pointed out (confirmed by Firebase support).
Unfortunately, capturing URL segments in Firebase Hosting redirects does not support query parameters, which would be required to redirect /?link=... to /d/?link=....
Because of these two unfortunate circumstances, I simply used some JavaScript to redirect any request to /?link=... to /d/?link...:
const link = new URLSearchParams(window.location.search).get('link')
if (window.location.pathname == '/' && link != null && link != '') window.location = `a.b.c/d/${window.location.search}`


text:
Q: mysql, how to ignore part of parameters? I have this sententce
SELECT FROM * Foods
And I am trying to attach a conditional statement according to what the user filters in the app.
For instance, I'm trying to create a filter for price and taste (sweet, salty) and region.
But the problem is that the user may not set the region or price. But WHERE price = null doesn't work because having a null value and not calling price filter by the user are two different things.
Is three a walk around? I want the statement to be reusable as much as possible. I'm new to rdbms, so I'd like to hear some methods Thank you!


text:
Q: What the best program for string manipulation I would like to know the best program (Surely a text editor) to make string manipulation like string substituion.
By the way, I would like to do the next:
String manipulation of type String substitution in mathematical expression
Thank you so much!

A: My preferences are in this order: perl, vim (vi, gvim, etc.) substitution commands, sed, and awk.
perl is a heavy software program that can do math as well.  See http://perlmonks.org/ for more details.
Vi is the well known text editor all *ix systems have (Linux, Unix, etc.), which, incidentally, can do some nice scripting.
Sed is, well see http://linux.die.net/man/1/sed
Awk (gawk and its brethren) is, well see http://linux.die.net/man/1/awk
... almost forgot. The absolute best, and with a price tag to match, is PowerGrep.  Without a doubt, the easiest way to formulate complex queries and replacements of text in DOC, TXT, and other files.

A: Take a look at sed


text:
Q: How do I keep on adding to the total of my variable I am currently working on a project which involves a dice game where you click "roll" and the dice generates the number and lists it on a JTextArea and adds to the total number below.
When the user gets a 3, the total number turns to 0.
My problem is that when pressing "roll" the total number doesn't add the rolled number each time instead it shows the current rolled number.
JButton roll=new JButton("Roll");
roll.setBounds(900,750,75,30);
roll.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        String command = e.getActionCommand();
        if (command.equals ("Roll")){

            int player1score = 0;
            int player2score = 0;
            int total = 0;
            int total2 = 0;

            Integer dice=(int)(Math.random()*6+1);

            if (dice==1 || dice==2 || dice==4 || dice==5 || dice==6) {

                area1.append(String.valueOf(dice + "\n"));

            } else if(dice==3) {

                dice = 0;
                total = 0;
                area1.setText(String.valueOf(total + "\n"));
                totalbox1.setText(String.valueOf(total + "\n"));

            }

        total = total + dice;
        totalbox1.setText(String.valueOf(total2));

        }
    }
});

A: You're resetting total to 0 at the beginning of the if statement. So every time you click roll, the line int total = 0; is being triggered, and at the end you add 'dice' to 'total' , which will always return dice.
You should instead initialize the variables outside of the if statement.


text:
Q: Sorted array object based on value I have an array of objects with nested array objects.
[
    {
        "neighborhoods": [
            {
                 "origin": "Kenwood",
                 "destination": "Portage Bay"
            }
        ]
    },
    {
        "neighborhoods": [
             {
                 "origin": "First Hill",
                 "destination": "Denny-Blaine"
              }
        ]
    },
    {
        "neighborhoods": [
            {
                "origin": "Belltown",
                "destination": "Eastlake"
            }
        ]
    }
]

I want to sort the objects alphabetically based on the origin value. What is the most efficient way to do this?

A: You could take the property and the object at the index zero with origin value for sorting.

var array = [{ neighborhoods: [{ origin: "Kenwood", destination: "Portage Bay" }] }, { neighborhoods: [{ origin: "First Hill", destination: "Denny-Blaine" }] }, { neighborhoods: [{ origin: "Belltown", destination: "Eastlake" }] }];

array.sort(function (a, b) {
    function getValue(o) { return o.neighborhoods[0].origin; }
    var aa = getValue(a),
        bb = getValue(b);

    return aa > bb || -(aa < bb);
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: ActionMailer not delivering mail in development I am trying to build a password reset email. I am Using Rails 3.2.16, and Ruby 1.9.3p327, I have read a ton of answers to this question and tried pretty much everything. I have also gone through the action mailer basics guide, and as far as i can see this should be working but its just not going well. Ill do a step by step guide of how i set it up.
firstly since i am trying to get this working in development, within development.rb Note: I have reset the application each time i edited the development.rb file.
#this is all the action mailer settings i have defined in development.rb
config.action_mailer.raise_delivery_errors = true # Set to true so that errors would be visible.
config.action_mailer.perform_deliveries = true # I read about this possible fix on SO
config.action_mailer.default_url_options = {
  host: "boogle.dev"
}
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :address              => "smtp.office365.com",
  :port                 => 587,
  :domain               => "mpowered.co.za",
  :user_name            => "support@mpowered.co.za",
  :password             => "password",
  :authentication       => :login,
  :enable_starttls_auto => true
}

My notifier class which inherits from ActionMailer
class Notifier < ActionMailer::Base
  default from: "Mpowered - BEEtoolkit <support@mpowered.co.za>"

  def deliver_password_reset_email(user)
    @edit_password_reset_url = edit_password_reset_url(user.perishable_token)
    @name = user.name

    mail(
      subject:       "Password Reset Instructions",
      to:            user.email,
      date:          Time.now,
      content_type:  "text/html")
  end
end

Within my User model i have set up the method which will send the mail along with setting up of a perishable_token
def deliver_password_reset_instructions!
  reset_perishable_token!
  Notifier.deliver_password_reset_email(self)
end

The Passwords reset controller is set up like this:
class PasswordResetsController < ApplicationController
  before_filter :require_no_user
  before_filter :load_user_using_perishable_token, :only => [ :edit, :update ]

  def new
  end

  def create
    @user = User.find_by_email(params[:email])
    if @user
      @user.deliver_password_reset_instructions!
      flash[:notice] = "Instructions to reset your password have been emailed to you"
      render action: :new
    else
      flash.now[:error] = "No user was found with email address #{params[:email]}"
      render action: :new
    end
  end

  def edit
  end

  def update
    @user.password = params[:password]
    # Only if your are using password confirmation
    @user.password_confirmation = params[:password]

    # Use @user.save_without_session_maintenance instead if you
    # don't want the user to be signed in automatically.
    if @user.save
      flash[:success] = "Your password was successfully updated"
      redirect_to @user
    else
      render action: :edit
    end
  end

  private

  def load_user_using_perishable_token
    @user = User.find_using_perishable_token(params[:id])
    unless @user
      flash[:error] = "We're sorry, but we could not locate your account"
      redirect_to root_url
    end
  end
end

I added resources to my routes:
resources :password_resets, :only => [ :new, :create, :edit, :update ]

My views are simple:
in app/views/password_resets/new.haml.html
%br
= form_tag password_resets_path, class: 'form-inline' do
  %legend Forgotten Password
  %p Enter your email address and instructions to reset your password will be emailed to you:
  %span.span1
    = label_tag :email, 'Email'
  = text_field_tag :email
  = submit_tag 'Reset my password', class: 'btn'
%br

So this should send the mail once you submit a valid email.
You should then receive an email with this content: app/views/notifier/password_reset_instructions.html.haml
%h1 Password Reset Instructions

%p
  A request to reset your password has been made. If you did not make
  this request, simply ignore this email. If you did make this
  request, please follow the link below.

= link_to "Reset Password!", @edit_password_reset_url

The link should bring you to a form where you can then save a new password and password confirmation.
app/views/password_resets/edit.html.haml
- if @user
  = form_for @user, :url => password_reset_path, :method => :put do |f|
    %legend Change My Password
    %p Please select a new password for your account
    .span8
      = f.field :password, :field_type => :password_field, :label => "New password"
      = f.field :password_confirmation, :field_type => :password_field
    .clearfix
    = f.submit "Update my password", class: 'btn'
- else
  %h3 We couldn't identify your reset code
  %p We're sorry, but we could not locate any accounts with reset codes that matched yours.
  %p If you are having difficulties resetting your password, try copying and pasting the URL from your password reset email into your browser or restarting the password reset process.

to which you can save your new password and then login once more.. this is what i have set up in the app. but everytime i try send it by following the system, it says the email was sent but nothing ever comes. I have also tried loading up a user in the console and then running u.deliver_password_reset_instructions!
and i get this:

But still no email in my inbox. I have currently set the email address in the notifier to my own personal one so no matter what valid email address is requested, the email should come to me.
I have been hitting walls for the last 12 hours and have no idea where to turn. i am hoping i have made a balls up that a fresh pair of eyes can catch.

A: You need to add .deliver when calling Mailer method like this
def deliver_password_reset_instructions!
  reset_perishable_token!
  Notifier.deliver_password_reset_email(self).deliver
end

Hope this helps


text:
Q: Android Dagger 2 Привет всем. Использую в своем проекте фреймворк Dagger 2.
У меня единственный AppComponent:
@Singleton
@Component(
        modules = {
                AppModule.class
        }
)

который содержит AppModule, AppModule в свою очередь содержит другие модули.
Использую создание этого компонента в классе Application
component = DaggerAppComponent
        .builder()
        .appModule(new AppModule(this))
        .build();

То есть создание компонента происходит только в одном классе. Встречал код, где используется создание различных компонентов во фрагментах и активити, используются различные самкомпоненты и скоупы. Объясните пожалуйста, чем плох мой вариант?

A: Ваш вариант не плох. Он просто базовый. Изначальный, общий для всех компонент dagger должен быть в классе Application. Далее, основываясь на нём, можно сделать подкомпоненты, которые будут существовать только в отдельных активити/фрагментах. Но и они должны быть прописаны в базовом компоненте.
Т.е. те способы, что вы видели - примеры расширения вашего и частные случаи.


text:
Q: Three questions to customizing `Ticks` in `Plot`, `LogPlot` and `LogLogPlot` When making a plot, sometimes I would like to alter the ticks and labeling of the ticks, in particular when doing a LogPlot or LogLogPlot.
Here an Example:
ticks = Automatic;

LogPlot[2/(3 Exp[3 x/2]), {x, 0, 40}, AxesOrigin -> {0, 1}, Ticks -> ticks]

There are a number of things I would like to change here.
(1) The x-Axis is now on top of the plot, so it would make more sense, and in many situation look better, to have the ticks below the axis, and the labeling {10,20,30,40} above. How can I do that?
(2) On the logarythmic y-Axis, I would like the main ticks to go in steps of 10^-3, rather than 10^-5. So from top to bottom I would like the labels to be {1,10^-3,10^-6,10^-9}, and between I would like to have small ticks without a label in steps of 10.
Now for two I actually know a way to do it, namely brute force specify the ticks manually like this:
ticks = {Automatic,
     {
      {10^-27, , {.008, 0}},
      {10^-26, , {.003, 0}}, {10^-25, , {.003, 0}},
      {10^-24, "10^-24", {.008, 0}},
      {10^-23, , {.003, 0}}, {10^-22, , {.003, 0}},
      {10^-21, , {.008, 0}},
      {10^-20, , {.003, 0}}, {10^-19, , {.003, 0}},
      {10^-18, "10^-18", {.008, 0}},
      {10^-17, , {.003, 0}}, {10^-16, , {.003, 0}},
      {10^-15, , {.008, 0}},
      {10^-14, , {.003, 0}}, {10^-13, , {.003, 0}},
      {10^-12, "10^-12", {.008, 0}},
      {10^-11, , {.003, 0}}, {10^-10, , {.003, 0}},
      {10^-9, , {.008, 0}},
      {10^-8, , {.003, 0}}, {10^-7, , {.003, 0}},
      {10^-6,"10^-6", {.008, 0}},
      {10^-5, , {.003, 0}}, {10^-4, , {.003, 0}},
      {10^-3, , {.008, 0}},
      {10^-2, , {.003, 0}}, {10^-1, , {.003, 0}},
      {1, 1, {.008, 0}
     }
    };

However this is extremely cumbersome, and I am wondering if there isn't an easier way to do it. Is there not a simple command that lets me specify the major ticks in steps of A, and the minor ticks in steps of B?
(3) Suppose I was satisfied with the default ticks that Mathematica makes for my plot. Then is there a way to manually add a tick and label at a special value, or I then have to manually specify all the ticks?
In the above example, for instance, could I add a single tick at x = 10.2, and specify a length of the tickmark, and position of its label? I know I could possibly do this by manually drawing a Graphics[Line[…]], however it would be a fiddling around to make it look good, adjusting the grayscale and thickness of the line. In the case of logarithmic plots, adjusting the position could also be cumbersome.

A: I will just answer the first question. You can use Frame/FrameTicks instead:
Show[
    LogPlot[
        2/(3 Exp[3 x/2]),
        {x,0,40},
        Frame->{{True,False},{False,True}}
    ],
    FrameTicks -> {{Charting`ScaledTicks["Log"], None}, {None, All}}
]

I used Show to add the actual ticks because handling of ticks inside of LogPlot seems to be suboptimal.


text:
Q: Group-ID according to numbering reset I have following data:
d <- as_tibble(c(1,2,1,2,3,4,5,1,2,3,4,1,2,3,4,5,6,7))

The running numbers are one group, and for every reset
I need hvae a new group. What I need is a group-ID for
every numbering reset; hence:
d$ID <- c(1,1,2,2,2,2,2,3,3,3,3,4,4,4,4,4,4,4)

To visualize it:
value ID

1   1
2   1
1   2
2   2
3   2
4   2
5   2
1   3
2   3
3   3
4   3
1   4
2   4
3   4
4   4
5   4
6   4
7   4

I have tried using group_indices of dplyr but
that doesnt do the trick as it groups by same value:
d$ID <- d %>% group_indices(value)

A: We can use diff to subtract the current value with previous value and increment the counter whenever the values are reset.
cumsum(c(TRUE, diff(d$value) < 0))
#[1] 1 1 2 2 2 2 2 3 3 3 3 4 4 4 4 4 4 4

In dplyr,we can use lag to compare it with previous value.
library(dplyr)
d %>% mutate(ID = cumsum(value < lag(value, default = first(value))) + 1)


text:
Q: Using an external HD as my applications folder I need to install more applications - can I use my external HD (samsung T5) and add an additional applications folder? I have loads of space on it and it the speeds are great.

A: Yes, you can use an external drive to keep (install) apps.
You should be fine. You don't need to specifically create a folder named Applications on the external drive. Any name or directory hierarchy should be fine.
macOS apps are generally made available as bundles (.app extension) which is technically a directory appearing as a single file to the user (with a specialized structure). An app bundle could be placed anywhere on secondary storage and the app can be used without any difference.
By default, apps are installed in boot volume's /Applications directory and are automatically made available to all the users on macOS. Keeping an app bundle in a folder/drive only accessible to you limits the app available to you.
On a related note, it is worth mentioning for the macOS newcomers that installing/uninstalling an app in macOS is as simple affair as copying/trashing the app's .app file.


text:
Q: How do I get the pk of a ForeignKey? I want to allow uploads that will be stored in the following way:
class Upload(models.Model):
    user = models.ForeignKey(User)
    category = models.ForeignKey(Category)
    file = models.FileField(upload_to='uploads/' + str(category.pk) + '/' + str(user.pk))

    class Meta:
        unique_together = ('user', 'category')

This way, each upload would be sandboxed in its own directory, first by the category ID and then by the user ID. I wouldn't have to worry about duplicated file names and the directory structure would be neat and organized.
However, ForeignKey does not have an instance of pk, so the above code does not actually work. Is there a way to store the file in a directory based on the category and user? Or, alternatively, is there another strategy commonly used to organize file uploads in Django?

A: You can use a callable function for upload_to:
import os

def upload_path(instance, filename):
    return os.path.join('uploads', str(instance.category.pk), str(instance.user.pk))

file = models.FileField(upload_to=upload_path)

A: There are two things to address here.
The quick thing is that the pk of the related Category is available on the in-memory Upload instance as self.category_id, and the pk of the related User is self.user_id.
The somewhat more complicated thing is that to use a dynamic upload_to, you have to give it a callable rather than an arbitrary expression. From the docs:

This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments that will be passed are:
instance
An instance of the model where the FileField is defined. More specifically, this is the particular instance where the current file is being attached.
In most cases, this object will not have been saved to the database yet, so if it uses the default AutoField, it might not yet have a value for its primary key field.
filename
The filename that was originally given to the file. This may or may not be taken into account when determining the final destination path.

So you'll want to define a function that takes the Upload instance and returns the desired path:
def upload_location(upload, original_filename):
    return os.path.join(str(upload.category_id), str(upload.user_id), original_filename)

Or something like that. Then use it in the model:
file = models.FileField(upload_to=upload_location)


text:
Q: Regex in python to get javadoc-style comments in CSS I'm writing a python script to loop through a directory of CSS files and save the contents of any which contain a specifically-formatted javadoc style comment.
The comment/CSS looks like this:
/**thirdpartycss

* @description Used for fixing stuff

*/
.class_one {
    margin: 10px;
}
#id_two {
    padding: 2px;
}

The regex to fetch the entire contents of the file looks like this:
pattern = "/\*\*thirdpartycss(.*?)}$"
matches = re.findall(pattern, css, flags=re.MULTILINE | re.DOTALL)

This gives me the file contents. What I want to do now is write a regex to grab each CSS definition within the class. This is what I tried:
rule_pattern = "(.*){(.*)}?"
rules = re.findall(rule_pattern, matches[0], flags=re.MULTILINE | re.DOTALL)

I'm basically trying to find any text, then an opening {, any text, then a closing } - I want a list of all of the CSS classes, essentially, but this just returns the entire string in one chunk.
Can anybody point me in the right direction?
Thanks.
Matt

A: {(.*)} is a greedy match -- it will match from the first { to the last }, thus gobble up any {/} pairs that might be inside those.  You want non-greedy matching, that is
{(.*?)}

the difference is the question mark after the asterisk, making it non-greedy.
This still won't work if you need to properly match "nested" braces -- but then, nothing in the RE world will: among regular languages many well-known limitations (regular languages are those that regular expressions can match) is that "properly nesting" any kind of open/closed parentheses is impossible (some incredibly-extended so-called-RE manage to, but not Python's, and anybody with CS background will find calling those expression "regular" offensive anyway;-).  If you need more general parsing than REs can afford, pyparsing or other full-fledged Python parsers are the right way to go.

A: @Alex is right (is he ever not? but I digress). You are better off using a custom parser if you need more specific parsing than what regular expressions can offer. Luckily you don't have to reinvent the (CSS parsing) wheel. There is an already existing solution for this.
I faced a similar requirement some time back. The cssutils module came in handy at the time. I just refreshed my cssutils fu to cook up this code snippet for you:
In [16]: import cssutils

In [17]: s = """/**thirdpartycss
* @description Used for fixing stuff
*/
.class_one {
    margin: 10px;
}
#id_two {
    padding: 2px;
}"""

In [26]: sheet = cssutils.parseString(s)

In [27]: sheet.cssRules
Out[27]:
[cssutils.css.CSSComment(cssText=u'/**thirdpartycss\n* @description Used for fixing stuff\n*/'),
 cssutils.css.CSSStyleRule(selectorText=u'.class_one', style=u'margin: 10px'),
 cssutils.css.CSSStyleRule(selectorText=u'#id_two', style=u'padding: 2px')]

In [28]: sheet.cssRules[0].cssText
Out[28]: u'/**thirdpartycss\n* @description Used for fixing stuff\n*/'

In [29]: print sheet.cssRules[0].cssText
-------> print(sheet.cssRules[0].cssText)
/**thirdpartycss
* @description Used for fixing stuff
*/

You can parse the CSS and then loop through the sheet object's cssRules to find all CSSComment instances.


text:
Q: From XMPP and RabbitMQ what should i use for group chat? I am developing a chat application for android and i phone . Here i am to make persistent groups like whatsapp where members remain joined even after they get offline and after getting online they get their offline group messages. As it is not possible with XMPP so i am thinking about to go for rabbitmq and ejabberd both.
Here is how i want to make group-

*

*When a group is created , an exchange is created in rabbitmq and each group members will add this user to its roster.

*Now when a user send a message to rabbitmq then it will be delivered to members who are subscribed to that exchange and offline messages will remain in the queue till user gets online.

My Questions are-

Is it the correct way which i am thinking?
  How much exchanges can we create in rabbitmq and how much memory an exchange takes ?
  How much messages a queue can store and how much memory it takes?
  Should i use it or simply go with XMPP-MUC for group chat?