Objective-C Stop loading the view while in viewDidLoad from presentViewController

Question: I am using the presentViewController method to present a subview as shown below.  However, I need to be able to stop the subview from loading if a valid license does not exist.  I must do it from the subview.
- (void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag
{
    NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"innerID-iOS-Resources" withExtension:@"bundle"]];
    if (bundle) {
        if (!self.cameraVC) {
            self.cameraVC = [[IDCameraViewController alloc] initWithNibName:@"IDCameraViewController" bundle:bundle];
        }
        [self.cameraVC willMoveToParentViewController:self];
        [self addChildViewController:self.cameraVC];
        [self.view addSubview:self.cameraVC.view];
        [self.cameraVC didMoveToParentViewController:self];
    }
}

There is a callback method that calls the following closeCameraView method when done.  I do not want to use another callback for when license does not exist.
- (void)closeCameraView
{
    [self.cameraVC willMoveToParentViewController:nil];
    [self.cameraVC.view removeFromSuperview];
    [self.cameraVC removeFromParentViewController];
    [self showControls];
}

The viewDidLoad is the first method that gets executed when the subview is presented.
I want to check for a valid license and return to the calling view if one does not exist.
- (void)viewDidLoad
{
    [super viewDidLoad];

    if ([self isLicenseValid]) {
        self.cameraSettings = [IDCameraSettings cameraSettings];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"License Activation"
                                   message:@"A valid license must be activated for this product."
                                  delegate:self
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil];
        [alert show];

        //Do not load view
    }
}

I've tried the following two approaches to no avail and am having difficulty finding similar questions/answers on the Internet.
[self.view removeFromSuperview];
[self.parentViewController dismissViewControllerAnimated:YES completion:Nil];

Any ideas?  Please.
Thank you,
Lucy
Answer: By the time viewDidLoad is called, the view is, as the method name suggests, already loaded. So you can't stop the view from loading at that point.
From the little bit of code you show, it looks like you could just call your isLicenseValid method on your view controller before you try to display it, since it's the act of trying to display it that will cause it to load its views.
Comment: The parent controller will belong to someone else's application.  I am exposing a xib file in a bundle from an SDK.  Is there no way to dismiss the view from its parent and make the parent the active view?
Comment: So... What you want to do is make it so that if someone else displays your view controller that it is immediately dismissed if this license isn't there? I think you just need to document how to properly use your view controller, meaning they need to explicitly check your `isLicenseValid` method before trying to display the view controller. As for if they go ahead and display it without doing this check first, your view controller should display an error dialog upon being displayed.
Comment: Thank you, Gavin, for your help.  I think we decided to add an NSNotification callback to inform them of invalid license and let their UI dismiss the subview.  Plus, that would allow our SDK users to put any notifications to their users in any language of their choice.
Comment: Also, we put the license check inside loadView, which stops the view from loading if the license does not exist.  YaY!!!


Unable to restore database using Microsoft SQL Server Management Studio Express

Question: I am unable to restore database in form of .bak files using Microsoft SQL Server Management Studio Express.
It gives following error message:

Too many backup devices specified for backup or restore; only 64 are allowed.
RESTORE HEADERONLY is terminating abnormally. (.Net SqlClient Data Provider)

Can you please help?
Thanks!
Comment: Which version of SQL Server did you use to create this backup? Do you have SQL Server 2000 installed?
Comment: I took backup from my webhosting server. It was SQL Server 2005.
Answer: Looks like you are trying to restore backup on older version of MS SQL Server than the backup was made. For example, if you made backup on MS SQL Server 2008 and restore on MS SQL 2005.
In this case you need to install the correct version of MS SQL Server and move the data by Export/Import functionality.


Alter entity_translation vertical tab access

Question: How can you set #access to false for the vertical tab "Translation" (entity translation) on the node edit form?
When using entity translation and a user has the permission to edit a node and edit translations, a new vertical tab is injected in the node edit form:

Translation
Translation is published. Do notflag translation as outdated
  [x] This translation is published
  [ ] Flag translation as outdated

Since I have editors that need to edit translations but shall not have access to this v-tab (it is being confused with the Publishing options for the node, leading to people altering the translation status where the node in its entirety should be unpublished/published instead).
Using hook_form_alter() in a custom module, I do not find any trace of the above form element in the $form array. According to a grep search, it is defined in the file /modules/entity_translation/includes/translation.handler.inc:1051. I assume it is being cached somehow, as that part of the code is not being executed when the form is built (breakpoints do not trigger).
Worst case, I could use Javascript to hide the form element, but I would rather not have to rely on such a hack. If possible, I would like to set #access to false for the editor role (or similar).
Answer: The reason you cannot use hook_form_alter() to modify the tabs is because the hook you implement in your custom module is being fired before entity translation injects the tab.
If you use hook_module_implements_after() you can change the order of the execution of the hooks.
function CUSTOMMODULE_module_implements_alter(&$modules, $hook)
{
    if ($hook == "form_alter")
    {
print_r($modules);
        // save off hook
        $temp = $modules["testing"];

        // remove it
        unset($modules["testing"]);

        // add it to the end
        $modules["testing"] = $temp;
print_r($modules);
    }
}

The first print_r outputs:
Array
(
    ...
    [CUSTOMMODULE] =>
    [entity_translation] =>
)

The second print_r outputs:
Array
(
    ...
    [entity_translation] =>
    [CUSTOMMODULE] =>
)

Now that the custom module fires after entity translation, use hook_form_alter() to hide the tab:
function CUSTOMMODULE_form_alter(&$form, &$form_state, $form_id)
{
    // make sure you set the form_id in this conditional properly.
    // I am using the edit form of a "page" node type.
    if ($form_id == "page_node_form")
    {
        $form["translation"]["#access"] = FALSE;
    }
}


closed form for $\int_{0}^{\infty}\frac{ \beta(a+ix,a-ix)}{\beta(b+ix,b-ix)}\frac{dx}{(b^2+x^2)}$

Question: closed form for :
$$\int_{0}^{\infty}\frac{ \beta(a+ix,a-ix)}{\beta(b+ix,b-ix)}\frac{\mathrm{dx}}{(b^2+x^2)}$$
where $\beta$ is beta function
I tried with the definition of beta and i got
$$I=\frac{\Gamma(2b)}{\Gamma(2a)}\int_{0}^{\infty}\frac{\Gamma(a-ix)\Gamma(a+ix)}{\Gamma(b-ix)\Gamma(b+ix)}\frac{\mathrm{dx}}{(b^2+x^2)}$$
I also used the product form but i failed
I think it's something related to complex analysis so if there is any help .
Thanks.
Answer: The integral is evaluated to be
\begin{align}
\int_{0}^{\infty} \, \left| \frac{\Gamma(a + i x) }{ \Gamma(b + 1 + ix)} \right|^{2} \, dx = \frac{4^{b-a}}{2 \, b} \, B\left( b - a + \frac{1}{2} , \frac{1}{2} \right)
\end{align}
Comment: @mhd.math Are you unhappy with this answer? Do you expect something simpler?
Comment: @L.G. I doubt there is anything more simple than the answer you had posted and the one presented by myself.


What services must I leave switched on in Elysia cron

Question: I have installed Elysia Cron to import some Feeds data periodically.
However, I have switched off all the other cron tabs that I have in order not to interfere. However, my database size grows to ten times the size as when the cron was switched on without Elysia cron.
Must I switched them on and with what periodicity?
Answer: Elysia cron is just an improved durpal cron service. You must have enabled the services you have enabled by deafualt in the standard Drupal cron. Some of them, for example, remove temporal data from the database (probably the reason your database is growing).
So, yes, you must have the services enabled, and those are the services enabled byu default by Drupal. Obviously the exact services that must be turned on depends on each installation.


faster way of combining two date columns (YYMMDD and hhmmss) into one datetime column?

Question: I have a rather annoyingly formatted CSV file, and I end up with time and date split into two columns.
I want to combine them into one datetime index. I have figured out a way to to it, but it's rather slow:
MWE:
CSV example:
21.03.1968 07:01:00 661.79999   "I,"
25.03.1968 07:01:00 661.77002
28.03.1968 07:01:00 661.75   "I,"
01.04.1968 07:01:00 661.72998
04.04.1968 07:01:00 661.1   "I,"
08.04.1968 07:01:00 661.70001

As you can see, it uses a single whitespace as delimiter, and 3 for the last column, and it's (euro-style) time series data. I'm reading it with
df = pd.read_csv('file.csv', delim_whitespace=True, # Should use spaces as delimter
                 header=0, names=['year', 'hours', 'data'],
                 usecols=[0,1,2]) # get's rid of the weird "I,"

and end up with a df with a  default 0, 1, 2, 3... index and year, hours and data columns. As this is a time series, I obviously want to turn year and hours into a datetime index.
MY first instinct was to just brute force it, by looping over the rows and fucking around with the strings, but as we all know, that's not the best way. So with some quick searching, I found the seemingly obvious way:
df['date'] = pd.to_datetime(df['year'] +' '+df['hours'], dayfirst=True)

and then df = df.set_index('date') and df.drop(['year', 'hours'], axis=1).
Works perfectly fine, however, with my real data (test file has 110506  rows, I've got approx. 880 files in total), %timeit tells me 7.96 s ± 95.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each), so I'm looking at around two hours for the whole deal!
So, is there a (significantly) faster way of combining two dataframe columns into one datetime index?
It would be great to just define fixed columns lengths in read_csv, but that doesn't seem to be possible. I'm always amazed about the thousands of easy and blazingly fast comfort-functions inbuilt into pandas, but if one exists for this (rather common, I'd have thought) case exists, I haven't found it yet. read_fwf, comented by
Quang Hoang seemed good, but as I just learned, my data field has various lengths! So my data always ends up with various 661.1   " strings in what should be floats. Maybe in the linked apply answer? But I can't figure it out.
Comment: [`pd.read_fwf`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_fwf.html) is better for you in this case.
Comment: Have you tried to give pandas more information on the formatting? `format="%m.%d.%Y %H:%M%S"`
Comment: @QuangHoang: That seemed like the method I was searching for, but apparently, my files are even worse than I though (`data` field has various lenghts). @Jacob: Shouldn't `dayfirst=True` be enough information? If I read in a "good" CSV, that always works without noticeable delay, so it seems like the slow part is in the merging.
Answer: Using the pd.to_datetime() is the correct way to go. However, to merge the dates you also need to know if the dates in your files are matching, or if they need to be synchronized.
In case they match, you can use pd.join() with the datetime as key.
If they do not match you can use pd.merge_asof(). This will match your datetime with the closest one it can find. You will lose some accuracy but your data will be synchronized.
Comment: What do you mean with "matching"? I need to take each line in the raw file as is, i.e. the `DD.MM.YYY` and the `hh:mm:ss` part must ALWAYS be combined, as they are read in.
Comment: If in the first file, one line is i.e. 10:35:17 and in the other file this time does not exist, it will try to match it to the closest one. So 10:35:17 could be matched to 10:35:18. If you know that you have the same timestamps across your files then you do not need to match your timeframes.


Covariance matrix of the residuals in the linear regression model

Question: I estimate the linear regression model:
$Y = X\beta + \varepsilon$
where $y$ is an ($n \times 1$) dependent variable vector, $X$ is an ($n \times p$) matrix of independent variables, $\beta$ is a ($p \times 1$) vector of the regression coefficients, and $\varepsilon$ is an ($n \times 1$) vector of random errors.
I want to estimate the covariance matrix of the residuals. To do so I use the following formula:
$Cov(\hat{\varepsilon}) = \sigma^2 (I-H)$
where $\hat{\varepsilon}=Y-X\hat{\beta}$, $\sigma^2$ is estimated by $\hat{\sigma}^2 = \frac{e'e}{n-p}$, $I$ is an identity matrix, and $H = X(X'X)^{-1}X'$ is a hat matrix (see Kutner, 2005).
However, in some source I saw that the covariance matrix of the residuals is estimated in other way.
The residuals are assumed to follow $AR(1)$ process:
$\varepsilon_t = \rho \varepsilon_{t-1} + \eta_t$
where $E(\eta) = 0$ and $Var({\eta}) = \sigma^2_{0}I$.
The covariance matrix is estimated as follows
$Cov(\varepsilon) = \sigma^2 \begin{bmatrix}
  1 & \rho & \rho^2 & ... & \rho^{n-1}\\
  \rho & 1 & \rho & ... & \rho^{n-2} \\
... & ... & ... & ... & ... \\
\rho^{n-1} & \rho^{n-2} & ... & ... & 1
\end{bmatrix}$
where $\sigma^2 = \frac{1}{1-\rho^2}\sigma^2_0$
My question is are there two different specifications of the covariance matrix of residuals or these are somehow connected with each other?
Comment: Connected is a pretty vague term but I would claim that they're dis-connected. The first method assumes that the disturbances are iid and normally distributed. The second method assumes that they are autocorrelated and follow an AR(1) process. How you estimate the regression model depends on which model you assume for the disturbances so they are connected only in that sense.
Comment: The first one is suitable for independent observations while the second one for serial observations on the same sampling unit.
Comment: @mlofton: does the first method really assume independance of the disturbances ? If it were the case, an estimator of the covariance matrix of errors should just be $\hat {\sigma} I$, but here, the matrix $I - H$ is not necessarily diagonal..
Comment: @CherryGarcia: what assumptions are you willling to make on your errors $\varepsilon$ ? Maybe looking at Feasible Generalized Least Squares methods could help..
Comment: @Pohoua: Definitely the assumption is independence but the use of $(I-H)$ has something to do ( waving my hands here because I forget so hopefully someone else can explain more clearly )  wiith the fact that the estimates are not independent in that the sum of the residuals estimates has to equal zero because of the nature of OLS. That still doesn't explain why you get a non diagonal estimate but it's related to that. I'd love to know the answer myself so hopefully someone else can explain. Thanks for great question.
Comment: @Pohoua: I did not plan on imposing any assumptions. In fact, do we really need any assumptions to get to $Cov(\varepsilon) = \sigma^2 (I-H)$? I wanted to know how we can get from the general specification to the case with $AR(1)$ residuals.
Comment: The formula $cov(\varepsilon) = \sigma ^ 2(I - H)$ is not correct: a hat is missing (I detailed that in an answer to the question).
Supposing AR(1) process for your residuals drops the assumption of independance, but still assumes that your $\varepsilon_i$ are identically distributed (in particular you can't have heteroskedasticity).
Comment: Isn't the hat matrix actuallty $H = X(X^\intercal X)^{-1}X^\intercal$ ? At least that's what I find in Kutner, M. H. (Ed.). (2005). Applied linear statistical models (5th ed). McGraw-Hill Irwin on page 202.
Answer: After some investigation, I think I found a small (but crucial!) imprecision in what your post.
The first formula you wrote : $var(\varepsilon) = \sigma^2 (I - H)$ is actually not totally exact. The formula should be $var(\hat \varepsilon) = \sigma ^2 (I - H)$ where $\hat\varepsilon = Y - \hat\beta X$ considering the OLS estimator $\hat\beta = (X^TX)^{-1}X^TY$. Thus $\hat\sigma(I - H)$ is an estimator of the variance of the estimated residuals associated with OLS estimator. This formula does not suppose independance of the $\varepsilon_i$, just that they all have same variance $\sigma^2$. But this is not what you want! You want an estimate of the variance of the true residuals, not the estimated residuals under OLS estimation.
OLS estimator corresponds to maximum likelihood estimator under the hypothesis that residuals are i.i.d. and normal. The estimated residuals can thus be very poor estimates of the true residuals if these hypothesis are not met, and there covariance matrix can be very different from the covariance of the true residuals.
The second formula you wrote does correspond to the covariance matrix of the $\varepsilon_i$ under the hypothesis that they follow an AR(1) process.
Estimating covariance matrix of the residuals of a linear regression without any asumption cannot easily be done: you would have more unknown than datapoints... So you need to specify some form for the covariance matrix of the residuals. Supposing that they follow an AR(1) process (if this is relevent) is a way of doing so. You can also assume that they have a stationnary parametrized autocorrelation function, whose parameters you can estimate, and use it to deduce the covariance matrix.
Comment: don't mistake residuals for errors. residuals $r$ (that you call *estimates of the residuals*) are the difference between the real and the fitted y values, you don't have to estimate them, you have them. the errors $\epsilon$ instead are the random part of the data generating process. those are assumed to be IID, not residuals. a good estimate of errors are the studentized residuals (simple residuals are heteroshedastic and hence biased estimators)
Comment: @Pohuoa: Thanks for explaining the $(I-H)$ issue. Now I get it that you don't estimate the covariance matrix of the residuals. The $(I-H)$ matrix is estimating something totally different. Cherry Garcia:  The estimates of the residuals in the first case ( where you assume they are iid )  are just the $\hat{\epsilon}$ that come out of the regression. In the second case, you're  specifying a model for the residuals, namely an AR(1). So, the estimation method needs to know that so that is why you use feasible generalized least squares. There are other methods also besides FGLS.
Comment: @Pohuoa: Thank you very much for spotting the mistake; I have adjusted my question accordingly.

I think that I understand what you mean, but to be sure, let me summarize:

1) Under Gauss-Markov assumptions the covariance matrix of the residuals is
$Cov(\varepsilon) = \sigma^2I$

2) Assuming residuals follow AR(1) process the covariance matrix of the residuals is the second case I described in the question.

3) The covariance matrix of OLS residuals is:
$Cov(\hat{\varepsilon})=\hat{\sigma}^2(I-H)$
Comment: @CherryGarcia: Yes, exactly.
Comment: for Multiple Linear Regression can see [here](http://parker.ad.siu.edu/Olive/slch2.pdf) (for Normal Equation in matrix form)
Answer: In basic OLS you don't estimate the covariance matrix of residuals. You assume that errors (not residuals) are spherical, meaning that they're not correlated with each other. Residuals will come out of OLS uncorrelated.
What you described as a second method is a different assumption. When applying basic OLS to time series you run into an issue that its assumptions are not practical. In time series the residuals are often correlated. So, you could assume that they're AR(1) process, and that what that method does: it estimates the model assuming the errors are AR(1). This is called feasible generalized least squares
Comment: well but you do compute the covariance matrix of residuals in OLS, that's $\sigma^2(I-H)$
Comment: but nothing of $Y$ goes in there other than the residual variance so I kind of agree.
Comment: you DO calculate covariance matrix of residuals if you'd like to calculate Condition Number from it further in order to find out if your model is **stable** ! (the lower C.N. the better), if it is not low you can either change scaling or change/select predictors to achieve better stability of your model when small changes in predictors will not result in huge changes/variation of output


xss protection and html purifier

Question: I am currently using the CodeIgniter framework, and looking to strengthen the XSS protection by using HTMLPurifier (http://htmlpurifier.org/).
Is my understanding correct that you want to 'clean' data on post, so that its purified before its inserted into the Database? Or do I run it before displaying in the view?
If so, do I want to run HTMLPurifier on every single post that takes place? Since the app contains a lot of forms, I'd hate to have to selectively choose what gets cleaned and what doesnt - assuming that I can intercept all posts, is this the way to go? Of course, I validate some fields anyway (like email addresses, numeric numbers, etc)
Answer: Use $this->input->post() to get $_POST data. Codeigniter filters it automatically if global xss filter is set to true.
See the docs: http://codeigniter.com/user_guide/libraries/input.html

Edit: to clarify
Yes you should filter before inserting into the DB and yes you should filter all user input.
A quick google search, http://www.google.com/search?q=codeigniter+htmlpurifier, led to this page: http://codeigniter.com/wiki/htmlpurifier which is a helper for htmlpurifier.  Regarding catching all $_POST data: you have to do something with the data, right? In your models, when you're doing that something, just make purify() part of that process:
$postdata = purify($_POST);

Comment: Also look at for more in depth explanation: http://codeigniter.com/user_guide/libraries/security.html
Comment: CI's XSS filtering, whilst good, is not adequate. HTMLPurfier is considered much stronger and more secure.

xss protection and html purifier


Get hyperlink text when clicked on dynamically generated anchor tag

Question: I am trying to display contents of sqllite table using bottle on html template file. And here is the handler code in the template file.
%for row in rows:

  %for col in row[0::2]:

{{col}}

 %end
%end

It render the table as per the expectation on html page with three rows as data(please refer the below html source code which can be viewed on browser once the page is generated).

Testbatch1

Testbatch2

Testbatch3

Now I have written simple javascript code to display text on the link ie. value of {{col}} when it gets clicked

Now problem is, when I click on any of the hyperlink, JS display
Testbatch1 in alert window.
I have also tried with below code, but still geting the same output
$('a1').click(function(){
 window.alert($(this).text());
});

Can anyone suggest me how to get the hyperlink text of such dynamically generated anchor tags? My aim is to read the text of the hyperlink when clicked and send back to my python code where I will use it as paramter for sql query to render some other output.
Comment: 1) id's must be unique, 2) the second one will never fire because you don't have a `` tag.
Comment: @KevinKloet: Thanks Kevin, I was looking for root cause of such behaviour. Can you please tell me how can I get unique ID for such code?
Comment: in this case you don't need a id at all, you can use a class for example as you want to group them, if you give them the class "anchorClass" you can do something like `$('.anchorClass').click(function(){
 window.alert($(this).text());
});`
Answer: As Identifiers must be unique. You can't assign duplicate IDs. CSS class can be used for binding event handler. Here in snippet I have added a1 class to anchor.
%for row in rows:

  %for col in row[0::2]:

{{col}}

 %end
%end

And for binding event handler use .on() method with Event Delegation approach, when generating elements dynamically.
Example
$(document).on('click', ".a1", function(){
    alert($(this).text())
});

In place of document you should use closest static container.
Answer: When you click on link .button class event is occurred
$(document).on('click', ".button", function(){
   alert($(this).text())
});


Are there any other interpretations besides bayesian and frequentist?

Question: I am aware of the frequentist and bayesian interpretations of statistics. I prefer Bayesian because I think it's closer to how people think, and because we in practice often can't rerun a trial a million times to estimate the probability.
But are there any other interpretations besides those two?
Comment: Yes, see [Probability interpretations](http://en.wikipedia.org/wiki/Probability_interpretations) for instance.
Answer: I think we should distinguish between "interpretations of probability" and "interpretations of statistics" (or more adequately- "statistical argumentation"). Both, are naturally tightly related.
Regarding interpretations of probability- I like the following criteria [a]:

Single-case or replicable?
Mental or physical?
Objective or subjective?

Any interpretation out there can be classified according to these aspects.
Regarding statistical arguments, the classics are indeed the frequentist and the Bayesian but there are more out there-- fiducial, fuzzy logic. Indeed, there are infinitely many ways to argument with data, but the two you mentioned are preferred in the sense they are considered more "convincing".
[a] [Williamson, Jon. "Philosophies of probability." Handbook of the Philosophy of Mathematics 4 (2009).]
Answer: Fisher had his own interpretation, called Fiducial probability. There is a school of Likelihood theorists, who try do something similar to Bayesian but don't use priors. They just compute and report the likelihood function. (Misguided in my view.) Apart from probability there are some approaches to uncertainty (all wrong-headed in my view) that are used in computer science. Possibility theory, Dempster-Shafer theory, rough sets, Desert-Smaradanche theory.
Comment: Welcome to the site, @BlaiseEgan. If you want to comment on the other existing interpretations, it might help if you provided an argument in support of your views, or possibly even better, just leave them out. 1 thing we're a little bit concerned about here is ending up w/ lists of various people's opinions. (Note that opinions *can* be valid & I don't doubt that you have thought about the issues before having come to yours.) Since you're new here, you may want to read our [FAQ](http://stats.stackexchange.com/faq), which discusses issues like these.


context "this" não retorna correto

Question: Ao dar um console.log(this),
Eu queria que o THIS do console retornasse o Vue, e não o This do Validate,

this.$ValidateUtil({
        el: this.$refs.cadMain,
        rules: {
          cep: {
            required: true,
            regex: /^\d{5}-\d{3}$/
          }
        },
        messages: {
          cep: {
            regex: "CEP inválido"
          }
        },
        submitHandler: function () {
          // AQUI!! -->>console.log(this);
          return false;
        }
      })

import Vue from 'vue'
import 'jquery-validation'
var LibsUtil = (function () {
    function LibsUtil() {
    }
    LibsUtil.ValidateUtil = function (options) {
      options = options || {}
      $(options.el).validate({
        rules: options.rules || {},
        messages: options.messages || {},
        submitHandler: function (form) {
          if (typeof options.submitHandler !== 'undefined') {
            options.submitHandler(this, form)
          }
          return false;
        }
      })
      Return Vue;
    };

    LibsUtil.install = function (Vue) {
        Vue.ValidateUtil = LibsUtil.ValidateUtil;

        if (!Vue.prototype.hasOwnProperty("$ValidateUtil")) {
          Vue.prototype.$ValidateUtil = LibsUtil.ValidateUtil;
      }

    };
    return LibsUtil;
}());
export { LibsUtil };
export default LibsUtil;

Comment: Consegui! em vez de chamar assim options.submitHandler(this, form), eu chamo assim:
options.submitHandler.call(Vue,this, form)! ^^
Answer: Acontece que tem momentos em algumas funções que mudam o contexto do this, e por isso você não consegue mais acessá-lo, um exemplo disso é a função setInterval, onde dentro da execução da função é mudado o contexto, e com isso você não tem mais acesso ao this da instancia, para resolver isso você pode fazer da seguinte maneira:
todo(){
    const self = this; //preserva instancia do this na variavel self
    this.intervalid1 = setInterval(function(){
        self.changes = ((Math.random() * 100).toFixed(2))+'%';
        console.log (this.changes);
    }, 3000);
}

dessa forma dentro do setInterval é possível utilizar a instancia do Vue com a variável "self", você pode utilizar essa mesma estratégia para essa lib de validação

context "this" não retorna correto


Geo-Availability Single Terminal Server Opinions

Question: First off, I am not an Azure specialist by any means, but I do have experience with creating Azure VM's for site to cloud replication and stand-alone cloud environments for business solutions.
Recently, I been tasked with proposing a solution for a global company who will need access to a terminal server in the cloud from many parts of the globe. Included areas are South Africa, Vietnam, Asia, European countries, south America, and the USA. Now, I know Azure has servers around the world, but I am unclear to whether or not to create multiple terminal servers for access, or if there is a feature that I can replicate the server across different geo locations for performance. Or if anyone has any input as to what would be best practices for providing a terminal server that needs to be accessed from many different locations.
Can I replicate a single terminal server across multiple data centers in azure?
Basically I am in need of a way to make an Azure terminal server performance solid no matter where someone remotes in from. I know RDP protocol in general is very solid with minimal bandwidth requirements, but want to ensure this is a proper solution for my client.
To add, I understand that Azure may not be the best solution. In a perfect work I would have different domains across multiple locations, but I am trying to leverage the cloud as a possible solution to prevent a management nightmare for this company, especially considering their budget is not very large.
End goal is to get them in a Microsoft environment, and remove google drive as their go to for storage and access to documents for their entire business.
Thanks all.
Comment: `End goal is to get them in a Microsoft environment, and remove google drive as their go to for storage and access to documents for their entire business.` Geo-located RDS servers seems like an odd way to achieve that goal.
Answer: I assume you are referring to Azure RemoteApp which is an RDP service in azure as opposed to your own VM running terminal services. The only advantage you'll get by having RD RemoteApp in different data centres is the slightly better connectivity to the local Azure data centre.  Azure RemoteApp is resilient by itself, so my advice start in the data centre closest to the most users and scale out if performance is an issue.  This you you'll only have one image to manage update with your applications


undecidability of halting

Question: In the "Halting Problem" lecture, the Prof. Shai Simonson introduced a magic trick to use the fact that there exists no TM that accepts all other TM that accept themselves to prove that the halting problem is undecidable. There he asked to change the algorithm to alternate the answer i.e if the answer is yes change it to no and vice versa. Then he proved that the halting problem is undecidable. I kind of didn't get his magic trick for the proof. It would be great if somebody can shed some light on it. Thanks!
https://www.youtube.com/watch?v=e9zzY7uqT8g
Answer: 'magic trick' is a big word.  Anyway, the 'trick' is easy to explain.
So the question is:
Is there a Turing machine (a 'Halting Macine') that can take a description of any Turing machine M, and input I on its input, and that can decide whether machine M with input I will halt?
The answer is No.
To prove that there is no such 'Halting Machine', you do a proof by Contradiction:
If there is a Halting machine, then you expand that machine by two little bits of code:
First, you have a 'Copy' machine that simply produces two copies of its input on its output.
Second, you have a 'Negator' machine that takes the output of the Halting machine, and does the following:
If the Halting machine says that M with I halts, then the Negator machine will go into some infinite loop, i.e. it will not halt.
If the Halting machine says that M with I does not halt, then the Negator machine will do nothing (and thus the Negator machine will halt)
Now, both the Copy machine and the Negator machine are easily shown to be implementable by a Turing machine. Thus, if there is a Halting machine, we can create a new Turing machine $Q$ that take as input a description of some machine $M$, runs the Copy machine, then the Halting machine, and finally the Negator machine.
Now, since $Q$ is a Turing machine itself, we can feed the description of $Q$ into $Q$ itself. So, the Copy machine will take the description of $Q$, and make two copies of it, and pass that to the Halting machine. So, the Halting machine has on its input $Q$ and $Q$, and so the Halting machine will try to figure out whether machine $Q$ with input $Q$ will halt or not. Fibally, oince the Halting machine has made its decision, the Negator machine will do its thing.
But note:
If we assume that $Q$ with input $Q$ halts, then the Halting machine will say exactly that on its output. But, the Negator machine was set up in such a way that it will then go into an infinite loop. So: If $Q$ with input $Q$ halts ... then it does not halt!
OK, so what if $Q$ with input $Q$ does not halt?  Then the Halting machine will say so, and then the Negator machine will do nothing, and hence the whole machine $Q$ will halt. So: If $Q$ with input $Q$ does not halt ... then it does halt!
OK, but now we have a contradiction: machine $Q$ with input $Q$ will halt if and only if it does not!
OK, so where did things go wrong?  In our assumption that we could create such a Halting machine .. apparently that is impossible!
Here is a cute video that goes through the same proof:
https://www.youtube.com/watch?v=92WHN-pAFCs
Comment: But what if we don't have Halting Machine followed by Negator? What if we don't have Negator at all? I really couldn't get why Negator was needed.
Comment: The Negator is to get a contradiction. If we don't use a Negator, we don't get a contradiction.

undecidability of halting


C# - Remove an item for a Linked List

Question: OK I'm having a problem, I just can't seem to get this to work, no matter what I try. The problem is everytime I write to Console I get an error:

Argument 1: cannot convert from 'void' to 'bool'

However, there is no boolean data from what I can see, bar the conditions.
    class Link
{
    private int data;
    private Link next;

    public Link(int item) //constructor with an item
    {
        data = item;
        next = null;
    }
    public Link(int item, Link list) //constructor with item and list
    {
        data = item;
        next = list;
    }

    public int Data //property for data
    {
        set { this.data = value; }
        get { return this.data; }
    }

    public Link Next //property for next
    {
        set { this.next = value; }
        get { return this.next;}
    }

}

}
All my other methods work i.e. Display item, count the number of items etc. But what seems to be the problem:
class LinkList
{
    private Link list = null; //default value – empty list

    public void AddItem(int item) //add item to front of list
    {
        list = new Link(item, list);
    }

    public string DisplayItems() //write items to string and return
    {
        Link temp = list;
        string buffer = "";
        while (temp != null) // move one link and add head to the buffer
        {
            buffer += temp.Data + "";
            temp = temp.Next;
        }
        return buffer;
    }

    public int NumberOfItems() // returns number of items in list
    {
        Link temp = list;
        int count = 0;
        while (temp != null) // move one link and add 1 to count
        {
            count++;
            temp = temp.Next;
        }
        return count;
    }

    public void RemoveItem(int item)
    {
        Link current = list;
        Link previous = null;

        while (current != null)
        {
            if (current.Data == item)
            {
                if (previous != null)
                {

                    previous.Next = current.Next;
                    current = current.Next;

                }

                else
                {
                    previous = current;
                    current = current.Next;
                    list = current;
                }
            }
            else
                previous = current;
               current= current.Next;
        }

    }

    public bool IsPresent(int item)
    {
        Link temp = list;
        bool result = false;
        while (temp != null)
        {
            if (temp.Data == item)
            {
                result = true;
                break;

            }

            else
            {
                temp = temp.Next;

            }
        }
        return result;
    }

}

This is my program class I use to print to console-
    class Program
{
    static void Main(string[] args)
    {
        LinkList testList = new LinkList();
        testList.AddItem(10);
        testList.AddItem(20);
        testList.AddItem(30);
        testList.AddItem(40);
        testList.AddItem(50);
        testList.AddItem(60);

        System.Console.WriteLine("Number of Items " + testList.NumberOfItems());
        System.Console.WriteLine("Display Items " + testList.DisplayItems());
        System.Console.WriteLine("10 is Present " + testList.IsPresent(10));
        System.Console.WriteLine("20 is Present " + testList.IsPresent(20));
        System.Console.WriteLine("30 is Present " + testList.IsPresent(30));
        System.Console.WriteLine("40 is Present " + testList.IsPresent(40));
        System.Console.WriteLine("50 is Present " + testList.IsPresent(50));
        System.Console.WriteLine("60 is Present " + testList.IsPresent(60));
        System.Console.WriteLine(testList.RemoveItem(10));

        System.Console.ReadLine();
        Console.ReadKey();
    }

}

But the RemoveItem method giving me grief, could someone please possibly help me out? Thank you.
This is the bit of code giving me a problem-
    public void RemoveItem(int item)
    {
        Link current = list;
        Link previous = null;

        while (current != null)
        {
            if (current.Data == item)
            {
                if (previous != null)
                {

                    previous.Next = current.Next;
                    current = current.Next;

                }

                else
                {
                    previous = current;
                    current = current.Next;
                    list = current;
                }
            }
            else
                previous = current;
               current= current.Next;
        }

    }

Thank you.
Answer: You have a problem at
 System.Console.WriteLine(testList.RemoveItem(10));

since RemoveItem doesn't return any value:
 // void - the method doesn't return any value
 public void RemoveItem(int item)
 {
   ...
 }

you can't print it out. Just call RemoveItem and do not WriteLine:
 testList.RemoveItem(10);

A better approach is to re-design RemoveItem and let it return bool (if item has been removed):
 public bool RemoveItem(int item) {
   ...
 }

Comment: Thank you so much kind sir. I apologise for my stupid idiotic mistake. Thank you. Greatly appreciated.
Answer: You've touched on your own problem. You are trying to print the output of RemoveItem on this line:
System.Console.WriteLine(testList.RemoveItem(10));

But RemoveItem doesn't have any output since it has a return value of void. But void doesn't mean "ignore this method". Console.WriteLine still expects a value, but the value it is given isn't something it can do anything with, hence the error.
You need to either remove the print call:
RemoveItem(10);
System.Console.Writeline("10 removed.");

Or change RemoveItem to return a value:
public bool RemoveItem(int item)
{
    ...
    return true;
}

Comment: Thank you so much kind sir. I apologise for my stupid idiotic mistake. Thank you. Greatly appreciated.

C# - Remove an item for a Linked List


ASP.NET MVC - Como realizar o upload de um arquivo com mais de 5mb usando ajax?

Question: Estou utilizando o seguinte código para realizar upload de arquivos:
HTML:
<form action="/Employee/FileUpload?UnityId=1&ObjectId=1" data-ajax="true" data-ajax-failure="OnFailure" data-ajax-method="Post" data-ajax-success="OnSuccess" enctype="multipart/form-data" id="form6" method="post" class="MultiFile-intercepted">

    <input multiple type="file" tabindex="-1" name="File" required title=" " autocomplete="off" maxlength="10" onchange="this.setCustomValidity('')" data-maxsize="10240" class="multi custom-file-input" accept=".bmp,.jpeg,.jpg,.pdf,.xls,.xlsx,.csv,.txt,.mp4,.mkv,.avi,.wmv,.mp3,.3gp,.doc,.docx">
    <input id="file" name="submit" role="button" type="submit" class="btn btn-primary validate-form upload-archive" tabindex="0" value="Enviar" />
</form>

JQUERY:
$(function () {
$("#form6").submit(function (event) {
    var dataString;
    event.preventDefault();
    var action = $("#form6").attr("action");
    if ($("#form6").attr("enctype") == "multipart/form-data") {

        dataString = new FormData($("#form6").get(0));
        contentType = false;
        processData = false;
    } else {

    }
    $.ajax({
        type: "POST",
        url: action,
        data: dataString,
        dataType: "json",
        contentType: contentType,
        processData: processData,
        success: function (data) {

        },
        error: function (jqXHR, textStatus, errorThrown) {

            alert("fail");
        }
    });
});

});
CONTROLLER:
    [HttpPost]
    public ActionResult FileUpload(string ObjectId, string UnityId, HttpPostedFileBase File)
    {
         .. Meu código
    }

Com esse código estou conseguindo fazer upload de arquivos de até 5mb, no entanto quando tento carregar um de 9mb o código não funciona, o controller sequer é chamado e não é exibida nenhuma mensagem de erro.
Existe algum limite para o upload de arquivos usando esse método?
Como posso fazer para resolver esse problema?
Answer: Essa limitação é do asp, para alterar é só mudar a parametrização no seu arquivo web.config, exemplo:
<configuration>
  <system.web>
    <httpRuntime maxRequestLength="xxx" />
  </system.web>
</configuration>

Comment: Perfeito. Era exatamente isso.


ElasticSearch how to use boost

Question: This query works great, but it's returning too many results. I would like to add the boost function but I don't know the proper syntax.
$data_string = '{
"from" : 0, "size" : 100,
"sort" : [
    { "date" : {"order" : "desc"} }
],
"query": {
        "more_like_this_field" : {
            "thread.title" : {
                "like_text" : "this is a test",
                "min_word_len" : 4,
                "min_term_freq" : 1,
                "min_doc_freq" : 1
            }
        }
    }
}';

Answer: Found the solution. Looks like using fuzzy_like_this_field and min_similarity is the way to go.
$data_string = '{
"from" : 0, "size" : 100,
"query": {
        "fuzzy_like_this_field" : {
            "thread.title" : {
                "like_text" : "this is a test",
                "min_similarity": 0.9
            }
        }
    }
}';

Answer: According to the docs, you just need to add it to the other parameters:
...
"thread.title" : {
    "like_text" : "this is a test",
    "min_word_len" : 4,
    "min_term_freq" : 1,
    "min_doc_freq" : 1,
    "boost": 1.0
}
...

Also, if you have too many docs, you can try to increase the min_term_freq and the min_doc_freq, too.
Comment: Thank you for your reply, miku. I've tried that but adding "boost": 1.0 like that appears to do nothing. I've tried changing the number to a higher number, but it doesn't change the results.

ElasticSearch how to use boost


Do I need a teacher to learn singing for a hobby

Question: Basically I want to learn how to sing, but I want to mantain only as a hobby, not pursuing any career or academic success. I have no background in singing and I think my voice sounds terrible when doing it.
Is it mandatory to find a teacher ?
Note that I have the following experience with piano: I have played for 8 years without any lessons, I just watched synthesia videos from youtube and practiced my favorite songs, no matter the level. I do not know how to read sheet music etc. I went to a few piano lessons, but they bored me when they started to teach me how to read music, play it in tempo etc. I decided I am fine with the skills I got on the piano, I am just doing it for fun, that's why I couldn't continue going to these lessons.
Now I want to learn singing on a hobby level and do it just for fun. I have read that there are many specific techniques and warmups involved, so I don't damage my voice. Is there any way to learn it alone (again, on a hobby level and doing it just for fun, only when I like to), or do I need a teacher to do that ? I am afraid it will be just a waste of time and money like the piano lessons.
What are your thoughts ?
Comment: Pretty subjective. Most teachers are going to want to use music sheets. You don't like them. Your voice sounds terrible. How do you expect to get it better by yourself? How would you know if an internet site is good, bad or indifferent?
Comment: @Tim so you are saying I need to go to lessons and learn how to read sheet music ?
I am accepting that as an answer, maybe there is no escape, I just want to know what are the possibilities of learning alone with the tools on the internet and getting it to a level where I don't find my voice terrible and maybe be proud enough to show it to my friends on facebook for example :)
Comment: Learning to read music is a good goal, but lots of people can sing with being able to read. One particular incentive of learning to read is being able to read tons and tons or vocal exercises and song books.
Comment: Just sharing, I got a crash course kind of a thing. A Musical (Music+Theatre) Person took classes for me for 3 Months, It was not the technical stuff. Obviously You can't do all sorts of things that Professional Vocalists do in Three Months. He taught Exercises and Practice Routines that (Effectively) Open Up the Voice. It really does come a long way. He doesn't teach me anymore, It was just 3 months one hour a week.
Answer: I'm having trouble reconciling...

...on a hobby level...just for fun

...and...

...but they bored me when they started to teach me how to read music, play it in tempo etc.

...with...

...I think my voice sounds terrible

...and...

...I want to learn how to sing

By what standard of singing?
If all you are doing is entertaining yourself, and anyone's attempt to correct you is a bore, it seems you can do whatever you like. But I wouldn't call that learning to sing. Just like playing the piano with bad rhythm isn't really learning to play the piano.
If you don't have natural singing talent, you surely will need to follow some practice method. Do you need a teacher to follow a method? No. But if you get bored when a teacher starts to teach you a method, how will you use a method on your own without a teacher?
At some point you need to set a standard and then work toward it. Playing less than perfect is one thing. But, playing with no sense of time and singing out of tune is not really learning. Just be honest with yourself about what you are actually doing and put in the practice time.
Answer: You could never go wrong taking lessons from an experienced teacher.  The problem with trying to teach yourself is that you don't know how to critique yourself and if you are doing something wrong you might hurt you vocal chords, or develop other problems.  In my opinion it is not obvious what's going on inside the body and a good teacher will be able to assess what you are doing by listening to your sound, watching your body and communicating with you.  We need feedback to develop.
If it's hobby and you think paying for lessons is too much you could do them once a month or so rather than once a week, search for group lessons at a community center or a local school which might be cheaper per person.  Then once you have your bearings you can go on your own.
Comment: Seconding this! You will need a teacher to listen to your singing and give you advice. Singing is different from other instruments in the way that **you hear everything through your inner ear, not outer.** What you hear through your inner ear is not the same as your "outer" singing voice, you just hear vibrations from the bones/tissue inside your face. Your singing teacher will be able to tell you how your singing sounds to the outside and will give you advice how to improve.
Answer: Like you have learnt how to speak without a teacher you will always be able to learn singing without a teacher (for a hobby). You can  read information about singing and voices. You will find a lot of information  and advice  to improve your voice sound  in this stack exchange community.
Answer: Find a local venue that does karaoke.
Sing things you enjoy once or twice a week for a year or five.
By that time, if you have any raw talent, you may be approaching a level at which you would actually be considered a singer.
No teacher required - just practice, perseverance & some innate ability.
Comment: Wouldn't you need to get prepared to be booed if you choose this route?
Comment: It's all part of the learning experience ;) tbh karaoke audiences tend to have pretty low expectations & be fairly forgiving. You know they like you if you can ever get better than half of them to stop talking for 3 minutes & pay attention.
Answer: Singing technique has a lot of seemingly small but important nuances (tongue position and tension, how to inhale/exhale, chest + head voice, jaw tension and position, etc) that not only shape tone, pitch, and dynamics (like vibrato), but also prevent you from hurting yourself. So, for singing in particular, I believe it's a good idea to seek a teacher.
You can get pretty far with video tutorials on youtube though. I've seen several great teachers and vocal coaches from many different styles give awesome tutorials. The problem is that every voice is different, and your specific needs can't be met through a generalized youtube tutorial. They are pretty good, they can get you really close, but it's just still not close enough to being the one-on-one experience, and efficiency if you want to see it that way.
Having a teacher will speed everything up, and make everything safer. It's an important commitment though, since consistency is required to make progress, so think about budget and how much time you want to invest. But at the very least swim in video tutorials and other media/literature.
Answer: No singer needs a teacher, but for a singer at any level, whether a complete beginner with no serious ambitions or a top professional hoping to get even better, the right teacher is going to help them get the results they want. The key to success is finding the right teacher.
Comment: That's all very well, but what constitutes the right teacher?
Comment: @Tim That's a completely different (and much more interesting) question which has probably been asked here many times.


How to have equal height for elements in the CSS Grid

Question: I am using CSS-Grid layout and wondering how can I set the equal heights for panel-heading elements?
Specifically as in the row below I would like to have all country names section have same height, whereas, the TotalContacts section should be smaller in height.

CodePen
https://codepen.io/ghazanfarmir/pen/ddNBEZ

body {
  padding: 30px;
}

.countries {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  grid-gap: 20px;
  grid-auto-rows: 1fr;
}

.countries .country {
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  margin-bottom: 0;
}

.country .panel-heading {
  display: grid;
  grid-template-columns: 70px 1fr;
  align-items: center;
  grid-gap: 20px;
  grid-auto-rows: 1fr;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

Abkhazia

Total Addresses 0

 Total Contacts 0

Afghanistan

Total Addresses 0

 Total Contacts 0

Aland

Total Addresses 0

 Total Contacts 0

Albania

Total Addresses 0

 Total Contacts 0

Algeria

Total Addresses 0

 Total Contacts 0

American Samoa

Total Addresses 0

 Total Contacts 0

Andorra

Total Addresses 0

 Total Contacts 0

Angola

Total Addresses 0

 Total Contacts 0

Anguilla

Total Addresses 0

 Total Contacts 0

Antigua and Barbuda

Total Addresses 0

 Total Contacts 0

Argentina

Total Addresses 0

 Total Contacts 0

Armenia

Total Addresses 0

 Total Contacts 0

Aruba

Total Addresses 0

 Total Contacts 0

Ascension

Total Addresses 0

 Total Contacts 0

Ashmore and Cartier Islands

Total Addresses 0

 Total Contacts 0

Australia

Total Addresses 3

 Total Contacts 9

Australian Antarctic Territory

Total Addresses 0

 Total Contacts 0

Austria

Total Addresses 3

 Total Contacts 1

Azerbaijan

Total Addresses 0

 Total Contacts 0

Bahamas, The

Total Addresses 0

 Total Contacts 0

Bahrain

Total Addresses 0

 Total Contacts 0

Baker Island

Total Addresses 0

 Total Contacts 0

Bangladesh

Total Addresses 0

 Total Contacts 0

Barbados

Total Addresses 0

 Total Contacts 0

Belarus

Total Addresses 0

 Total Contacts 0

Belgium

Total Addresses 1

 Total Contacts 1

Belize

Total Addresses 0

 Total Contacts 0

Benin

Total Addresses 0

 Total Contacts 0

Bermuda

Total Addresses 0

 Total Contacts 0

Bhutan

Total Addresses 0

 Total Contacts 0

Answer: It may not be the effect you are looking for but making the country elements display:grid and setting rows to 1fr makes the two sections the same height
.countries .country {
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  margin-bottom: 0;
  display:grid;
  grid-template-rows: repeat(2, 1fr);
}

body {
  padding: 30px;
}

.countries {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  grid-gap: 20px;
  grid-auto-rows: 1fr;
}

.countries .country {
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  margin-bottom: 0;
  display: grid;
  grid-template-rows: repeat(2, 1fr);
}

.country .panel-heading {
  display: grid;
  grid-template-columns: 70px 1fr;
  align-items: center;
  grid-gap: 20px;
  grid-auto-rows: 1fr;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Abkhazia

Total Addresses 0

 Total Contacts 0

Afghanistan

Total Addresses 0

 Total Contacts 0

Aland

Total Addresses 0

 Total Contacts 0

Albania

Total Addresses 0

 Total Contacts 0

Algeria

Total Addresses 0

 Total Contacts 0

American Samoa

Total Addresses 0

 Total Contacts 0

Andorra

Total Addresses 0

 Total Contacts 0

Angola

Total Addresses 0

 Total Contacts 0

Anguilla

Total Addresses 0

 Total Contacts 0

Antigua and Barbuda

Total Addresses 0

 Total Contacts 0

Argentina

Total Addresses 0

 Total Contacts 0

Armenia

Total Addresses 0

 Total Contacts 0

Aruba

Total Addresses 0

 Total Contacts 0

Ascension

Total Addresses 0

 Total Contacts 0

Ashmore and Cartier Islands

Total Addresses 0

 Total Contacts 0

Australia

Total Addresses 3

 Total Contacts 9

Australian Antarctic Territory

Total Addresses 0

 Total Contacts 0

Austria

Total Addresses 3

 Total Contacts 1

Azerbaijan

Total Addresses 0

 Total Contacts 0

Bahamas, The

Total Addresses 0

 Total Contacts 0

Bahrain

Total Addresses 0

 Total Contacts 0

Baker Island

Total Addresses 0

 Total Contacts 0

Bangladesh

Total Addresses 0

 Total Contacts 0

Barbados

Total Addresses 0

 Total Contacts 0

Belarus

Total Addresses 0

 Total Contacts 0

Belgium

Total Addresses 1

 Total Contacts 1

Belize

Total Addresses 0

 Total Contacts 0

Benin

Total Addresses 0

 Total Contacts 0

Bermuda

Total Addresses 0

 Total Contacts 0

Bhutan

Total Addresses 0

 Total Contacts 0

Comment: Thanks Paulie for helping. I am not happy with the height of Total Contacts section. This shouldn't be too big.
Comment: Then you need to explain what it is you are trying to achieve...this did *exactly* what you asked for *before* any edit.
Comment: If you are trying to equalise the heights of the top sections **only** there is NO CSS method for that...you will need javascript.


Simple random walk hitting time asymptotic behavior

Question: Let $p(n,t)$ be the probability that a simple random walk starting at state $n$ hits $0$ within $t$ steps.
How big can $p(n,t(n))$ get for large $n$ when $t(n) = o(n^2)$? It seems like maybe it could be $e^{-o(n^2/t)}$, since you also get to count paths that hit $0$ but end positive.
Answer: For a symmetric random walk with standard derivation $1$, start at $x_0$ at $t = 0$.
The probability distribution of it landing at $x_1$ for large time $t$ is approximately given by:
$$P[\,x(t) = x_1|x(0) = x_0] = \frac{1}{\sqrt{2\pi t}}e^{ -\frac{(x_1-x_0)^2}{2t} }$$
For large $t$, $p(n,t)$ is known to be about twice the probability for $x(t) \le 0$
at time $t$ and can be expressed in terms of the complementary error function. i.e.
$$\begin{align}p(n,t) &\sim 2 P[\,x(t) \le 0| x(0) = n]\\
&\sim 2\int_{-\infty}^0 \frac{dx}{\sqrt{2\pi t}} e^{ -\frac{(x-n)^2}{2t} } = 2\int_{-\infty}^{-n} \frac{dx}{\sqrt{2\pi t}} e^{-\frac{x^2}{2t}}\\
&= \textrm{erfc}(\frac{n}{\sqrt{2t}})\end{align}$$
The relation $p(n,t) \sim 2P[\,x(t) \le 0|x(0) = n]$ can be proved using the reflection principle for Bronwian motion. Unluckily, I can't find any good explanation how this is done on the web. I hope this is a start.
EDIT about the factor of two.
In the expression of $p(n,t)$, the factor of two in front of $P[\,x(t) \le 0|x(0) = n]$ isn't that surprising.
If one enumerate all possible history of a random walk between time $\tau = 0$ to $\tau = t$. Those walks which have hitted state $0$ at a time $\tau \le t$ falls into 3 classes.
Namely, those with $x(t) < 0, = 0 \textrm{ and } > 0$. For large $t$, the case for $x(t) = 0$ is much less probable than the other two. Because the walk is symmetric, the case for
$x(t) > 0$ and for $x(t) < 0$ has exactly the same probability!
Comment: Thanks! It's good to know that you can only get an extra factor of two.
Comment: @abc, there is a reason for the factor of two. see update of the answer.


Does Mapbox host the mapbox-gl-opacity plugin?

Question: I'm looking at the mapbox-gl-opacity plugin, but would like to implement this similarly to the Mapbox example for the mapbox-gl-compare plugin, by using an inline script include such as this:
<code><script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.js"></script>
</code>
Is the mapbox-gl-opacity plugin hosted in such a way? If so, what is the URL?
Answer: The mapbox-gl-compare plugin is developed by Mapbox, whereas mapbox-gl-opacity is community-maintained (since the repository is not under the Mapbox GitHub organization). So, Mapbox does not host the mapbox-gl-opacity plugin. Rather than using an inline script, you can either follow the example in the plugin's README, or use the corresponding npm package as demonstrated here.


ordenar grafico e fixar valor em python

Question: estou tentando fazer um gráfico da variação dos preços da ação do Itau porem o resultado fica com os valores das ações desordenados
insira o código aqui

  import matplotlib.pyplot as plt

  dados = open("ITUB4.csv").readlines()

  x = []
  y = []

    for i in range(len(dados)):
       if i != 0:
          linha = dados[i].split(";")
         x.append(linha[0])
         x.sort()

         y.append(linha[1])
         y.sort()

    plt.plot(x, y)
    plt.show()

como posso fazer pra os valores de 0-100 ficarem no lado esquerdo do gráfico e os valores da acão na linha apenas
insira o código aqui
 Date;Close
  2019-02-25;36
  2019-02-26;36
  2019-02-27;35
  2019-02-28;35
  2019-03-01;34
  2019-03-06;34
  2019-03-07;35
  2019-03-08;35
  2019-03-11;36
  2019-03-12;37
  2019-03-13;37
  2019-03-14;36
  2019-03-15;36
  2019-03-18;36
  2019-03-19;36
  2019-03-20;35
  2019-03-21;34
  2019-03-22;33

Comment: Se o objetivo é que eles fiquem na mesma ordem do arquivo, porque você está ordenando eles com `x.sort()` e `y.sort()`?
Answer: Olá, tudo bem?
Veja que você está ordenando a lista x e y toda vez que passa no for, mas não é necessário fazer isso, pois os dados já estão ordenados pelo arquivo que você apresentou acima.
Veja esta sugestão:
import csv
from datetime import datetime
import matplotlib.pyplot as plt

### Lendo o arquivo ###
with open("ITUB4.csv") as file:
    dados = csv.reader(file, delimiter=";")
    next(dados) # Pula a linha que contem o nome das colunas
    dados = list(dados) # Transforma em uma lista

### Percorrendo a lista dados ###
x = []
y = []
for d in dados:
    # Salvando os na lista x no formato datetime
    x.append(datetime.strptime(d[0], '%Y-%m-%d'))
    # Salvando os na lista y no formato float
    y.append(float(d[1]))

### Construindo o gráfico ###
plt.xlabel('Date')
plt.ylabel('Close')
plt.plot(x,y, 'r-o')
# Organiza o eixo x de modo a facilitar a visulização dos dados
plt.gcf().autofmt_xdate()
plt.show()

O plot do dados fica na seguinte forma.
Comment: muito bom! obrigado

ordenar grafico e fixar valor em python


django bulk user import user django-import-export

Question: i want use import export to bulk user import in django
i get a file include list of users then create users according to file rows
i try implement before_import like this
from import_export import resources
class UserResource(resources.ModelResource):
    def before_import(self,dataset, dry_run, **kwargs):
        #dataset is  tablib.Dataset()
        for i in dataset:
            i[1]=make_password(i[1])
        return super(UserResource, self).before_import(dataset, dry_run, **kwargs)

but it return tuple' object does not support item assignment
Comment: what si UserResource? what is dataset?
Comment: UserResource is import-export Resource ,see question update
Comment: that still leaves "what is dataset?" Also it would be a lot easier if you could tell us what exactly you are trying to achieve.
Comment: question updated,dataset is  tablib.Dataset()
Answer: For Passwords you could write your own password widget, which turns the plain password into a hash. Like this (untested):
class PassWidget(Widget):
    def clean(self, value):
        if self.is_empty(value):
            return None
        return make_password(value)
    def render(self, value):
        return force_text(value)

Answer: I hope you are trying to hash your password before importing.
it helps you:
    from import_export import resources, fields
    from import_export.admin import ImportExportModelAdmin
    from django.contrib.auth.hashers import make_password

    class UserResource(resources.ModelResource):

       groups = fields.Field(
           column_name='group_name',
           attribute='groups',
           widget=ManyToManyWidget(Group, ',','name')
       )
       def before_import_row(self,row, **kwargs):
           value = row['password']
           row['password'] = make_password(value)
       class Meta:
           model = User


Read parquet data from AWS s3 bucket

Question: I need read parquet data from aws s3. If I use aws sdk for this I can get inputstream like this:
S3Object object = s3Client.getObject(new GetObjectRequest(bucketName, bucketKey));
InputStream inputStream = object.getObjectContent();

But the apache parquet reader uses only local file like this:
ParquetReader<Group> reader =
                    ParquetReader.builder(new GroupReadSupport(), new Path(file.getAbsolutePath()))
                            .withConf(conf)
                            .build();
reader.read()

So I don't know how parse input stream for parquet file.
For example for csv files there is CSVParser which uses inputstream.
I know solution to use spark for this goal.
Like this:
SparkSession spark = SparkSession
                .builder()
                .getOrCreate();
Dataset<Row> ds = spark.read().parquet("s3a://bucketName/file.parquet");

But I cannot use spark.
Could anyone tell me any solutions for read parquet data from s3?
Answer: String SCHEMA_TEMPLATE = "{" +
                        "\"type\": \"record\",\n" +
                        "    \"name\": \"schema\",\n" +
                        "    \"fields\": [\n" +
                        "        {\"name\": \"timeStamp\", \"type\": \"string\"},\n" +
                        "        {\"name\": \"temperature\", \"type\": \"double\"},\n" +
                        "        {\"name\": \"pressure\", \"type\": \"double\"}\n" +
                        "    ]" +
                        "}";
String PATH_SCHEMA = "s3a";
Path internalPath = new Path(PATH_SCHEMA, bucketName, folderName);
Schema schema = new Schema.Parser().parse(SCHEMA_TEMPLATE);
Configuration configuration = new Configuration();
AvroReadSupport.setRequestedProjection(configuration, schema);
ParquetReader<GenericRecord> = AvroParquetReader.GenericRecord>builder(internalPath).withConf(configuration).build();
GenericRecord genericRecord = parquetReader.read();

while(genericRecord != null) {
        Map<String, String> valuesMap = new HashMap<>();
        genericRecord.getSchema().getFields().forEach(field -> valuesMap.put(field.name(), genericRecord.get(field.name()).toString()));

        genericRecord = parquetReader.read();
}

Gradle dependencies
    compile 'com.amazonaws:aws-java-sdk:1.11.213'
    compile 'org.apache.parquet:parquet-avro:1.9.0'
    compile 'org.apache.parquet:parquet-hadoop:1.9.0'
    compile 'org.apache.hadoop:hadoop-common:2.8.1'
    compile 'org.apache.hadoop:hadoop-aws:2.8.1'
    compile 'org.apache.hadoop:hadoop-client:2.8.1'

Comment: Thank you for this. How do we provide aws credentials for this code? I am getting:
com.amazonaws.AmazonClientException: No AWS Credentials provided by BasicAWSCredentialsProvider
Comment: Answering my own question: I have set the access key and secret key as:
    Configuration conf = new Configuration();
    conf.set("fs.s3a.access.key", "XXXXXXXXXXXXX");
    conf.set("fs.s3a.secret.key", "XXXXXXXXXXXXXXXXXXXXXXXX");
Comment: Just an update: `AvroParquetReader.builder(path)` is deprecated an will be removed in version 2.0.0

Read parquet data from AWS s3 bucket


General formula for $\frac{1}{1} + \frac{1}{2}+\frac{1}{3} ... +\frac{1}{n} $

Question: We know that this series does not converge and tends to infinity but is there a general and exact formula for sum to n terms of this series
Comment: I don't think there's an exact formula. Probably an approximation
Comment: This seems related: [Do harmonic numbers have a "closed-form" expression?](https://math.stackexchange.com/q/52572) Maybe also some [other posts linked there](https://math.stackexchange.com/questions/linked/52572) might be of interest.
Comment: Possible duplicate of [Do harmonic numbers have a "closed-form" expression?](https://math.stackexchange.com/questions/52572/do-harmonic-numbers-have-a-closed-form-expression)
Answer: This is known as the $n$-th harmonic number and is denoted $H_n$.
What do you think of this formula
$$H_n=\int_0^1\frac{1-x^n}{1-x}\,dx?$$
Comment: Yeah you are right thank you very much for your help
Answer: As already answered by Lord Shark the Unknown, this is $H_n$.
For large values of $n$, there are good approximation using their asymptotics
$$H_n=\gamma +\log \left({n}\right)+\frac{1}{2 n}-\frac{1}{12
   n^2}+O\left(\frac{1}{n^4}\right)$$ where $\gamma$ is Euler constant $(\approx 0.577216)$ which is very good even for small vales of $n$ as shown in the table below
$$\left(
\begin{array}{cccc}
 n & H_n & H_n \approx & \text{approximation} \\
 1 & 1 & 1.000000000 & 0.9938823316 \\
 2 & \frac{3}{2} & 1.500000000 & 1.499529512 \\
 3 & \frac{11}{6} & 1.833333333 & 1.833235361 \\
 4 & \frac{25}{12} & 2.083333333 & 2.083301693 \\
 5 & \frac{137}{60} & 2.283333333 & 2.283320244 \\
 6 & \frac{49}{20} & 2.450000000 & 2.449993653 \\
 7 & \frac{363}{140} & 2.592857143 & 2.592853705 \\
 8 & \frac{761}{280} & 2.717857143 & 2.717855123 \\
 9 & \frac{7129}{2520} & 2.828968254 & 2.828966991 \\
 10 & \frac{7381}{2520} & 2.928968254 & 2.928967425
\end{array}
\right)$$
Comment: Thank you claude


Error "expected string or buffer"

Question: I am generating images of 2 character permutations and using arabic_reshaper for joining characters. Permutation of 2 for 2 character will generate 4 images but arabic_reshaper is generating error "Expected String or buffer" at t1 =  arabic_reshaper.reshape(word).
Please ask if question is not clear.
from bidi.algorithm import get_display
import PIL.Image, PIL.ImageFont, PIL.ImageDraw
import arabic_reshaper

unicode_text = u"\u06F1"+ u"\u06CC"+ u"\u06A9"
list_of_letters = list (unicode_text)
folder = 1
n=2
for i in range(1,n+1):
    for word in itertools.permutations( list_of_letters,i):
        print word
        t1 =  arabic_reshaper.reshape(word)
        print t1
        img= PIL.Image.new("L", (200, 200))
        draw = PIL.ImageDraw.Draw(img)
        font = PIL.ImageFont.truetype( r"C:\Users\arabtype.ttf", 40)
        t2 = get_display(t1)
        print t2# <--- here's the magic <---
        draw.text( (10,50), ' ' + t2, fill=220, font=font)
        img.show()

Answer: The problem is that itertools.permutations produces a tuple.
You need to convert it to string. Something like this:
for word in itertools.permutations( list_of_letters,i):
    word = u''.join(word)
    print word

Error "expected string or buffer"


How to show that $f(0) = 0$?

Question: I'm stuck on an exercise, I tried few things but I really do know know what is the way to proceed.

Be $A\subset \mathbb{R}$ defined as $$A = \left\{ (-1)^n \frac{n}{2n^2+3};\ n\in\mathbb{N}\right\}$$

and be $f:\mathbb{R}\to\mathbb{R}$ such that $$xf(x) = 0\qquad \forall x \in A$$

if $f$ is continuous, show that $f(0) = 0$. Propose then a function $f$ that satisfies the above condition and such that $f(0) \neq 0$.

First of all, I do not know if I have to consider $\mathbb{N}$ containing $0$ or not. I think not, because otherwise I would not know what the boundary of $A$ is, since if $0\in\mathbb{N}$ then for $n = 0$ the first element is zero, but it's also zero when $n\to +\infty$.
Onthe contrary if $0\not\in\mathbb{N}$ then the first element is $-\frac{1}{5}$, and then I have $\partial A = \left(-\frac{1}{5}, 0\right)$.
I don't really know if this helps me...
I have no information on $f(x)$ if not its continuity, so I may state that $f(x)$ is continuous on $\partial A$ but $0\not\in A$, so how to show $f(0) = 0$?
Also for the second part I thought about some discontinuous function like $f(x) = 1$ for $x = 0$ but I think it's wrong.
I don't understand.
Answer: Chose a sequence $a_n\in A$ with $\lim_{n \to \infty}a_n=0.$ Then $a_nf(a_n)=0$ and thus $f(a_n)=0$ since we can divide by $a_n\neq 0.$ Finally, if $f(x)$ is continuous, then
$$
0=\lim_{n \to \infty}f(a_n)=f(\lim_{n \to \infty}a_n)=f(0).
$$
Answer: First, note that for each $x \in A$ we have $x \neq 0$, hence the fact that
$$xf(x) = 0$$ implies that $f(x) = 0.$
Suppose $f$ is continuous. If we have a sequence $x_{1}, x_{2}, \ldots$ of elements in $A$ converging to $0$, then $f(x_{1}), f(x_{2}), \ldots$ converges to $f(0)$. We know that $f(x_{1}), f(x_{2}), \ldots$ are all zero by the above argument, so $f(0)$ must be zero.
Therefore, it suffices to find a sequence $x_{1}, x_{2}, \ldots$ of elements in $A$ converging to $0$. I leave this to you.
Your idea for the second part is right: just take $f(x)$ to be a function which is zero for all $x \neq 0$ and is $1$ for $x = 0.$ Then certainly $xf(x) = 0$ for all $x \in A$, but $f(0) = 1 \neq 0.$
Answer: The problem throws a couple of complications your way as red herrings. First, the particular definition of $A$ is more or less irrelevant. The important parts are $0\notin A$ and $0\in\partial A$. Second, since $0\notin A$, the requirement on $f$ is equivalent to $f(x)=0$ for all $x\in A$.
Assume $f(0)=a\neq0$. Pick $\varepsilon=\frac{|a|}2$, and use $(-\delta,\delta)\cap A\neq\varnothing$ to show $f$ is necessarily discontinuous. By contraposition, if $f$ is continuous we have $f(0)=0$.
As for the concrete discontinuous example, the way I read your attempt, it seems to be just right. You just have to write it down in a way that doesn't require interpretation. Something like
$$
f(x)=\cases{1&if $x=0$\\0&otherwise}
$$

How to show that $f(0) = 0$?


API de Gifs em python

Question: é minha duvida e a seguinte eu tenho esse script onde eu digito o nome do gif que eu quero e ele me retorna vários tipo de url do tamanho(largura,altura) do gif sorteado aleatoriamente, eu queria que ele me retornasse apenas isso:

image_url':
  'https://media1.giphy.com/media/3og0IEvmsGQMvKRTEs/giphy.gif',
  que no caso seria a maior imagem que ele tem.

Como faço isso?

script  tirado :https://github.com/Giphy/giphy-python-client/blob/master/docs/DefaultApi.md#gifs_random_get

<code>import time
import giphy_client
from giphy_client.rest import ApiException
from pprint import pprint

api_instance = giphy_client.DefaultApi()
api_key = 'dc6zaTOxFJmzC'
tag = input('Nome do gif : ')
rating = 'g'
fmt = 'json'

try:
    # Random Endpoint
    api_response = api_instance.gifs_random_get(api_key, tag=tag, rating=rating, fmt=fmt)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling DefaultApi->gifs_random_get: %s\n" % e)
</code>
Answer: Tente isso:
<code>...
pprint(api_response.data.image_url)
...
</code>
Comment: Funcionou Muito obrigado

API de Gifs em python


Prove that a polyhedron contains an extreme point if and only if it does not contain a line using matrix of tight constraints

Question: I want to prove that a polyhedron $P = \{x\in\mathbb{R}^n\;:\;Ax\leq b\}$ has an extreme point if and only if it does not contain a line, but I want to do so in a particular way (I am aware of a proof by induction on $n$ which generalizes this result for any closed convex set, but this is not how I want to go about the proof here). Specifically I want to utilize the result that:
$x$ is an extreme point of $P$ if and only if $\text{rank}(A^=) = n$, where $A^=$ is the matrix of tight/active constraints of $x$.
I already know how to prove that if $P$ contains a line then $P$ has no extreme points, but my question is about the converse. I have an informal sketch of a proof, but I would appreciate some help making it rigorous. I want to show that if $P$ contains no extreme points, then it must contain a line. Here is my rough idea:
Let $x\in P$. We know it is not extreme, so therefore there exists $d_1\in\mathbb{R}^n$ such that $x + td_1\in P$ for $t\in (-\varepsilon_1, \varepsilon_1)$ for sufficiently small $\varepsilon_1$. Either $x + td_1$ is a line contained in $P$, in which case we are done, or $x \pm td_1$ has an active/tight constraint for some $t = t_1$. WLOG assume the '+' case, i.e. it is $x + t_1d_1$ which has an active constraint. By assumption, $x + t_1d_1$ is not an extreme point, and so therefore there exists $d_2\in\mathbb{R}^n$ which is not in $\text{span}(d_1)$ such that $(x + t_1d_1) \pm td_2\in P$ for $t\in (-\varepsilon_2, \varepsilon_2)$ for sufficiently small $\varepsilon_2$. Either $P$ contains the line $(x + t_1d_1) + td_2$ in which case we are done, or there exists $t = t_2$ such that $(x + t_1d_1) \pm t_2d_2$ which has an active constraint. Again WLOG assume the '+' case. Since $d_2$ is not in $\text{span}(d_1)$ then the active constraint from before is still active, and now a new constraint is active too. We iterate this process, so that we find a $d_3\in\mathbb{R}^n$ not in $\text{span}(d_1, d_2)$ such that $(x + t_1d_1 + t_2d_2) \pm td_3$ is contained in $P$ for small $t$ and either this is a line in $P$ or there is $t_3$ such that $x + t_1d_1 + t_2d_2 + t_3d_3$ has an active constraint. Since $d_3\notin\text{span}(d_1, d_2)$, the original two active constraints will still be active, and so there is now a third active constraint, etc. At some point we will have either found a line, or we will have $x + t_1d_1 + \cdots + t_nd_n$ which has $n$ active constraints. But then this should imply that the matrix of active constraints $A^=$ for this point is rank $n$, which would imply that $x + t_1d_1 + \cdots + t_nd_n$ is extreme, which contradicts the hypothesis. So therefore, at some iteration of this process we will necessarily have found a direction $d_i$ such that the line in that direction was contained in $P$.
My intuition tells me something like this should work, but I am struggling to make this rigorous. Specifically, I make the claim that each $d_i$ is not in the span of the preceding $d_1,\dots, d_{i - 1}$, but I don't know how to guarantee this is true. Second, I claim that since each $d_i$ is not in the span of the prior $d_1,\dots, d_{i - 1}$ then the constraints that were active before still remain active after traveling in direction $d_i$. This feels like it should be true, but I am not sure how to prove it. Finally, by my argument I should have at least $n$ active constraints if we end up iterating $n$ times, but I don't actually know how to prove that the rank of $A^=$ is actually equal to $n$ in this case (which gives us the desired contradiction if we have gotten to this stage). Maybe it is the case that $\text{rank}(A^=)$ is still strictly less than $n$, even though we have $n$ active constraints. I hope that this is impossible, but I am not sure how to prove it.
If someone could help make these points rigorous so that this becomes a valid proof, or instead shows why this proof cannot work, I would be very appreciative.
Answer: I'm fairly sure your proof can be made rigorous.  At each stage of your procedure, let $\ A_j^=\ $ be the matrix of tight constraints and $\ A_j^<\ $ the matrix of slack constraints for $\ \displaystyle x_j=x+\sum_{i=1}^jt_id_i\ $. Because $\ x_j \ $ is not an extreme point, the rank of $\ A_j^=\ $ is less than $\ n\ $, so you can choose $\ d_{j+1}\ $ to lie in its kernel.  Then all of the constraints with matrix $\ A_j^=\ $ will remain tight for $\ x_j+td_{j+1}\ $ (regardless of whether $\ d_{j+1}\in\text{span}\left(d_1,d_2,\dots,d_j\right)\ $ or not). If $\ x_j+td_{j+1}\ $ is not a line, then one or more of the constraints with matrix $\ A_j^<\ $ must be tight for $\ x_{j+1}=x_j+t_{j+1}d_{j+1}\ $.  Therefore $\ A_j^=\ $ must be a strict submatrix of $\ A_{j+1}^=\ $.  Since $\ A\ $ has only a finite number of rows, your procedure must terminate either with a line $\ x_k+td_{k+1}\ $ for some $\ k\ $, or with $\ A_k^==A\ $, and hence $\ Ax_k=b\ $.  In the latter case, since $\ x_k\ $ is not an extreme point, then the rank of $\ A\ $ must be less than $\ n\ $ and hence have a non-empty kernel.  If $\ d\ $ is any non-zero member of the kernel, then $\ x_k+td\ $ will be a line in $\ P\ $.
Comment: sorry that I didn't reply to this much earlier, but yes, I was able to make this work using effectively what you said here. thanks for your response.


Lilypond does not propperly render Chords when used with --png

Question: I'm truing to compile a lilypond score with the --png option. For some reason the chords do not get compiled properly when using this option. Running lilypond without the --png option works fine. The PDF file comes out as as expected, only the PNG file looks like this:

This is the code I'm using:
\version "2.18.2"

#(set-global-staff-size 30)
\include "lilypond-book-preamble.ly"

\paper {
  ragged-last = ##f
}

\header {
  title = "Title"
  subtitle = \markup { \null }
  tagline = ##f
}

\score {
  <<
    \new ChordNames \chordmode { c1 d1:m e1:m f1 }
      { \set chordChanges = ##t }
    \new Staff { \relative c' { c1 d e f }}
    \addlyrics { \lyricmode { \tiny good mor -- ning all. }}
  >>
  \layout { }
  \midi { }
}

Some System INFOS:
  Operating System: Debian GNU/Linux buster/sid
            Kernel: Linux 4.13.0-1-686-pae
      Architecture: x86
  Lilypond Version: 2.18.2-11`

       Ghostscript: 9.22~dfsg-1

I tried to compile with different fonts, by adding:
\paper  {
  #(define fonts
    (make-pango-font-tree "Times New Roman"
                          "Nimbus Sans"
                          "Luxi Mono"
                          (/ staff-height pt 20)))
}

PDF output again works fine, --png output looks like this:
Answer: This seems to be a problem rather related to ghostscript then lilypond
Using Century Schoolbook L instead of Times New Roman:
\paper  {
  #(define fonts
    (make-pango-font-tree "Century Schoolbook L"
                          "Nimbus Sans"
                          "Luxi Mono"
                          (/ staff-height pt 20)))
}

finally worked:

Thanks again to the support from Channel: #lilypond on Freenode!


Routing custom module with alphabetic pagination

Question: My custom module:
- Plugin/Ziektes.php array returns to hook_theme
public function build() {

$letter_path = 'B';
$path = base_path();
$current_url = Url::fromRoute('<current>');
$current_path = $current_url->toString();

// Query for newest articles and return max 3 results.
$query = \Drupal::entityQuery('node');
$news = $query->condition('type', 'ziekte')
  ->condition('status', 1)
  ->condition('title', $letter_path, 'STARTS_WITH' )
  ->sort('created', 'ASC')
  ->execute();

// LoadMultiple News in $nodes variable
$nodes = Node::loadMultiple($news);

// Return $nodes variable with name items to the module.
return array(
  '#theme' => 'mytheme_ziektes',
  '#items' => $nodes,
  '#path'  => $path,
  '#url'   => $current_path,
);

I have an alphabetical pagination printedn in twig like this:

Below this pagination there are the results of nodes for example in the letter 'B' there are nodes from content-type 'ziektes' that starts with the letter B.
As you can see in my module Ziektes.php file its not dynamic it uses
$letter_path = 'B';
->condition('title', $letter_path, 'STARTS_WITH' ).
When there is clicked on a letter it goes to ziektes/'theletter' for example ziektes/b so that I can get the letter from the url and make the query dynamic.
But at page ziekte/*anyletter I get an 404 page not found so I've made a Controller and a routing:
Routing:
myroutingname.settings:
  path: '/ziektes/{letter}'
  defaults:
    _controller: '\Drupal\myblocksroute\Controller\ZiektesController::ziekte'
    _title: 'Routing Ziektes'
  requirements:
    _permission: 'access my routing ziektes'

Controller:
namespace Drupal\myblocksroute\Controller;

class ZiektesController
{
  public function ziekte($letter) {
    return [
      '#title' => $letter
    ];
  }
}

This returns the letter that is clicked, that's good! But Its only a new page with the as title the letter 'b' for example, I can't keep the twig template and the EntityQuery are not reachable from here. It suppose to stay at /ziektes form template but the url is /ziektes/b, so that the query will check the letter after the ziektes/ where I can make my $letter_path dynamic.
How can I do this?
Comment: You can probably do this without a plugin and your hook_theme is still usable. Your controller has to return a renderable array with the `#theme` function set. The reason you only see `$letter` output is because thats all you're passing to the rendering layer.
Comment: Your controller needs to extend ControllerBase, for starters. From there, entity query service could be injected and available to use. The namespace also needs to be uniform, i.e. the name of your module.
Answer: As I alluded to in my comment, you are close, I believe. Here are some changes to get you in the right direction which begins by extending ControllerBase:
class ZiektesController extends ControllerBase
{

  // set any scope/variables here

  public function __construct($args...) {
    // set your injected dependencies to local variables
  }

  public static function create($args...) {
    // here you inject dependencies you need
  }

  public function ziekte($letter) {
    return array(
     '#theme' => 'mytheme_ziektes',
     '#items' => $this->queryNodes($letter),
     '#path'  => $path,
     '#url'   => $current_path,
    );
  }

  protected function queryNodes($letter) {
    // the following code can be refactored
    $letter_path = 'B';
    $path = base_path();
    $current_url = Url::fromRoute('<current>');
    $current_path = $current_url->toString();

    // Query for newest articles and return max 3 results.
    $query = \Drupal::entityQuery('node');
    $nodes = $query->condition('type', 'ziekte')
      ->condition('status', 1)
      ->condition('title', $letter_path, 'STARTS_WITH' )
      ->sort('created', 'ASC')
      ->execute();

    return count($nodes) ? $this->entityTypeManager->getStorage('node')->loadMultiple($nids) : array();
  }
}

ControllerBase should inject everything you need already, like entityTypeManager. That can be used to load nodes, as shown above. You don't need to call Node, and you likely don't have to do the same for Url either.
You can bring in your query as a helper method and you can inject entityQuery into your controller, see this comment on how to do that. That way, you're not using the global static container (\Drupal::). Then your code becomes:
    // Query for newest articles and return max 3 results.
    $query = $this->entityQuery->get('node');
    $nodes = $query->condition('type', 'ziekte')
      ->condition('status', 1)
      ->condition('title', $letter_path, 'STARTS_WITH' )
      ->sort('created', 'ASC')
      ->execute();

I am not sure why you need path and url though - every filter link will be routed to '/ziektes/{letter}'.
Comment: Amazing, thanks for your clear solution and fast respone Kevin!
Comment: Look into dependency injection w `services.yml` in your module to fill in the blanks - it will go a long way for you here. https://docs.acquia.com/article/lesson-83-dependency-injection