How to get large text into iOS app?

Question: I need a way to ship a few paragraphs of text to an iOS app.  This would be for a recipe or journal app.  If the user is only typing in a few sentences, they can do that directly in the app.  But for several paragraphs, they would want to do it on their computer then send the text to the app.
Or even if they are copying a recipe from the web (on their desktop).  They need a way to paste that data into the app.
Without creating a website or some other component the app needs to depend on, what is a way to get lots of text into the app?
For Mac users, they can use the Notes app via iCloud.  Then copy/paste from Notes into the app.  I don't think Windows users have this option.  However, this does create a disjointed experience.
Is there some way to tie into iCloud for shipping text over to the app so both Windows and Mac users have the same experience?
Answer: You can import Text-Files via iTunes for Example and access these files from your app.
Another way is using iCloud in your app. This will present a folder in iCloud Drive with the name of your app. Windows user can use the iCloud web interface to upload files.
And the easiest was is probably copy and paste from email sent to self.
Comment: For iCloud Drive, how do they get the text into it?  Mac=TextEdit and Windows=Notepad?  From there, how does the app read any of that?  I guess if it is .txt, I can search for that file type from the app?
Comment: Via iCloud Drive. There is a folder for every application that can access your iCloud Account. For example ... I am a Photomatix user on iOS and the app stores my files (and settings I think) and on iCloud drive I can see these files in a folder "Photomatix"
Answer: I can think of a few options:

Let users import text files into the app.
Implement a web server in your app. Serve an HTML page with a text view the user can type into. Then the user can connect to your app from any web browser on the same network (such as a user's home WiFi) and type into the web form on their computer. Look for CocoaHTTPServer on github.

How to get large text into iOS app?


How to save user session in a variable in PHP to be referenced in JavaScript

Question: Case:
User clicks on an image

If it is a returning user (user session valid for 30 minutes) navigate to the link of the image
If it is a new user show a pop-up div

I am now showing the pop-up div whenever the image is being clicked. Any advice on how to save the session and refer it as the variable in a JavaScript to perform a function like:
if {
    // user is log in.. do your task here..
} else {
    //user is not log in.. do your task here...
}

EDIT:

This is called for the image as:

    <img src="<cms:show my_image_thumb />" alt="" class="fade">

The above has no effect and now nothing opens onClick
Comment: i guess you can  write the javascript automaticly via php and insert the value of the session..
Comment: How exactly would I save the session in the JavaScript? Please see edit to the question
Comment: People have been using cookies to do this for a generation.
Answer: Don't perform the conditional check in client-side code, perform it in server-side code.
Assuming you have JavaScript implementations of what you want to achieve, let's call them these respectively:
navigateToLink();
showPopUp();

Then you'd conditionally emit the code for one or the other depending on a server-side session check.  Something like this:
<?php
if ($_SESSION['someValue'] == 'someKnownValue') {
?>
    navigateToLink();
<?php
} else {
?>
    showPopUp();
<?php
}
?>

The idea is that server-side code should determine what the user can or can not do.  Anything emitted to client-side code is entirely visible to (and modifiable by) the user.
Comment: How would I make a call to the php script in the `onClick` for the image? Since php only responds to get, post etc, will I be setting the value to true?
Comment: You can't. If you don't have the functions showPopup() and navigateToLink(), you still have to write them.
Comment: I already have the functions showPopup() and navigateToLink() but I need to make a call to the PHP on image click to show the correct function
Comment: @Sarah: If you want to invoke server-side logic without a page refresh then that would be an AJAX request.  You can have a server-side resource ("page" in PHP, most likely) which responds with data instead of markup, and the client-side code would consume that data.
Comment: I think you mean an ajax call, you want to call a php script using javascript?
Comment: @Sarah: Why do you need to invoke server-side code *after* the click event?  Isn't it known when the page loads whether or not the user can navigate to the link?
Comment: @David the login module which shows when the user session is not available calls an ajax function on hitting "login".In order to prevent the server-side code after the click event, should i save the session variable on the ajax call for login?where will I then check the user session?
Comment: @Sarah: I suspect you're over-engineering this.  It's not really clear what the order of operations is here, but it sounds like you're trying to perform authorization checks at the point of an action being requested (client side) instead of at the point of an action being handled (server side), which is where authorization checks belong.
Comment: @Pinki: Care to explain how?  It's a stated assumption that the JavaScript functions are already implemented elsewhere.  This is just conditionally emitting a single line of JavaScript within an existing JavaScript code block.
Comment: Oh boy, ok i think i need some better glasses :P my apologies. I feel so bad right now (and dumb) xD
Comment: @David so what should an approach be? Have to open a hyperlinked image - Need to see if it is a returning (registered/login) user or new user? If registered/login open link else show pop-up to login. Do i post it as another question? Can you advice?
Comment: @David, where and how will I call this php script, in the answer, on the `onClick` action?
Comment: @Sarah: I can think of two approaches. One is to display the link when the page loads if the user is logged in. Since you'd already know if the user is logged in, you'd know whether or not to show the link. Additionally, the link itself shouldn't be to the file but to a page which serves the file, so that page can also check authorization. Another approach would be to have an on-click action which makes an AJAX call to a page that returns whether or not the user is authorized. If they are, redirect them to that page which serves the file after internally checking authorization.
Answer: This should help you:


Minimizing the time taken for entity_load while using for apachesolr indexing

Question: I am working on a site with a specific node type that has close to 50 fields, most of which are taxonomy term references, a couple of node references and a few conventional text and integer values. Almost all of them accept multiple values.
While indexing the nodes with apachesolr I observe that most of the time in the indexing process is consumed by calls made to entity_load function, almost 3.5 - 4 minutes for loading 200 nodes when checked with timer based logging while the total indexing takes about 50 seconds more (4.5 minutes overall).
Adding a custom 'status back' with hook_apachesolr_entity_info_alter to query and return the node status directly instead of loading it, I was able to negate the entity_load in one instance, however another function apachesolr_index_entity_to_documents() where the drupal node to solr document conversion takes place had entity_load calls consumed more time since they could no longer use the cached result of the status callback.
My aim is to reduce the time taken for indexing to at least half of what it currently which now is completely dependant on the time taken by entity_load. Since entity_load is one of the critical aspects of Drupal 7 around which functions like node_load/node_load_multiple are derived from I'm unable to find a different option to proceed or determine ways to improvise entity_load usage.
Note: The site functions such that these nodes get created almost all the time and none of the fields can be pruned out, negating the option of pre-loading the entities. Also the site uses entity cache module with memcache
I'm hoping to get suggestions on improving the node load time programatically with entity_load or using alternative approach to load the respective entities to bring down my indexing time.
Comment: I doubt you'll be able to get `entity_load()` times down, if there was anything more to be had there it would already by in core. The only alternative is direct database queries, which bypass all the metadata in the API (which is why all modules should use the API in the first place) and would have to be updated manually when anything config-related changes. If you can't cache, there's not a lot you can do
Comment: Are you positive that your MySQL instance is optimized and that your memcache has enough memory and isn't thrashing?
Comment: @Clive & MPD Thanks for the response and feedback, the memcache stats show about 92% hit and that all subsequent entity_load calls on those nodes take only a few milliseconds make me believe that its holding up to its expectations. Also I'm informed that the MySQL is optimized and tuned for the best performance. Since new nodes keep getting churned in every second and get added to the solr indexing queue I was hoping to get some progress on initial entity load than caching, anyhow will try to check how things look and revert with my observations.
Answer: You could very well form an array of the nodes to be indexed after the query execute and do a single entity_load instead of doing a entity_load for each and every node separately and I hope that will reduce the time and below is the patch that could help you

Index: apachesolr/apachesolr.index.inc
--- apachesolr/apachesolr.index.inc     (revision 9348)
+++ apachesolr/apachesolr.index.inc     (working copy)
@@ -636,9 +636,21 @@
     $query->condition('aie.entity_type', $entity_type);
   }
   $query->range(0, $limit);
-  $records = $query->execute();
-  $status_callbacks = apachesolr_entity_get_callback($entity_type, 'status callback');
+  $records = $query->execute()->fetchAll();
+  foreach ($records as $node_record) {
+    $entities[] = $node_record->entity_id;
+  }
+  $arr_entity = entity_load($entity_type, $entities);
+  foreach ($records as $record) {
+    $record->status = $record->status && $arr_entity[$record->entity_id]->status;
+    $rows[] = $record;
+  }
+  // Commenting as we have already used the entity_load
+  /*$status_callbacks = apachesolr_entity_get_callback($entity_type, 'status callback');
   foreach ($records as $record) {
     // Check status and status callbacks before sending to the index
     if (is_array($status_callbacks)) {
@@ -651,7 +663,7 @@
       }
     }
     $rows[] = $record;
-  }
+  }*/
   return $rows;
 }

As you have said most of your fields are taxonomy term it is idle that you check the term_load method and also whether the term_data table is properly indexed.
Comment: Is there a link to this patch in the apache solr issue queue?
Answer: You should first figure out is why is entity_load so slow. What additional hooks are running inside of it that slows it down? An example of a module causing a slow entity_load is the metatag module. I have a patch for it in this issue: https://drupal.org/node/2183203 If you can find what is slowing down your entity_load that would be the most helpful.
If there are no slow performers inside entity_load, make sure that it is loading the entities in bulk and not one at a time.
If all else fails, one of the better looking alternatives is direct database queries at this point if the database layer has already been optimized. I've been working on some code that extends EFQ which I call EntityFieldQueryExtra. I got the idea for it from the apache solr module as apache solr also extends EFQ. For this use case you would only add in the fields that need to be indexed and I would use executeEntityBuild() as that will give you output similar to entity_load; just dpm() what is returned from executeEntityBuild() to find it.
If it is a volume issue (lots of entities to be processed), HTTPRL could be helpful if you want to roll your own solution or if you want to try a module that uses it like Apache Solr Parallel Indexing.
Comment: Thanks for the response, I'll try to debug for any additional modules that might be slowing down the entity_load calls and try loading multiple entities for any potential performance improvement, BTW awesome sandbox module!


Após git reset tem como ver git log anterior ao reset?

Question: Eu estava na seguinte situação, estava fazendo um treinamento e cheguei num ponto que minha pagina não estava carregando corretamente ficando diferente do instrutor, tudo indicava um problema de CSS então fiz um git log e fui fazendo o git reset para voltar aos commits anteriores e identificar onde que me perdi.
O problema é que quando fiz um git log para voltar novamente ao ultimo commit, percebi que não aparecia nenhum log dos meus commits atuais. Por sorte, rolando a pagina do Cmder, encontrei o primeiro git log e fiz um git reset usando o hash mais recente e meu projeto voltou ao ultimo status.
Teria alguma forma de fazer isso sem necessariamente perder os logs ou git reset é apenas para casos sem volta?
Para esta minha necessidade eu deveria ter usado git checkout <hash> anterior?
Answer: Sim, é possível ver o log após o git reset, basta usar o comando
git reflog

O git mantém um arquivo de log que registram todas as modificações (commit) do código, independe de resetar ou não uma alteração já existente.
ou então
git log -g

Esse comando é um atalho para git log --walk-reflogs e faz basicamente o mesmo que o comando anterior.
Uma outra opção é abrir o arquivo .git\logs\refs\heads\<nome-do-branch>. Neste arquivo consta todos os logs

Referência:
https://git-scm.com/docs/git-reflog
https://git-scm.com/docs/git-log
Comment: Testei aqui e funcionaram perfeitamente muito obrigado.


Cast void pointer to int

Question: With a VC++ project I have a line:
FXint realIndex = (int)m_cmbDevice->getItemData(indx);

This reads a void pointer value from combo box to an int value. In VC++ it compiles and works well.
Now I have to port this to Linux and there I get a compile error
cpp:514:20: error:
      cast from pointer to smaller type 'int' loses information
        FXint realIndex = (int)m_cmbDevice->getItemData(indx);

Now I use
std::size_t x = reinterpret_cast<std::size_t>(m_cmbDevice->getItemData(indx));
FXint realIndex = x;

My question is now, is this the right way to go?
Comment: Yeah, that won't lose any info. But if `sizeof(FXint) < sizeof(size_t)`, then you will lose info at that point instead (i.e., in the actual assignment).
Comment: Add a `static_assert(sizeof(FXint) == sizeof(void*), "Size of FXint doesn't match size of a pointer!");` before doing the cast, to make sure you won't lose any information
Comment: please show a [mre], what is returned by `m_cmbDevice->getItemData`?
Comment: A simple Static Cast should Work fine
Comment: @just a guy How can a staticcast looks like?
Comment: static_cast(yourPointer) If you want to use it to save a pointer I would recommend using a unsigned long instead of an int
Answer:
reinterpret_cast is dangerous and is typically used only to interpret a pointer as another kind of pointer. You should use static_cast instead
size_t is not necessarily big enough to store a pointer. There are already intptr_t and uintptr_t which are signed and unsigned integer types that are capable of holding a pointer
FXint realIndex = x; still raises a warning if x is wider than FXint, so another cast is necessary to turn off all related warnings

So you need to do this
auto x = reinterpret_cast<uintptr_t>(m_cmbDevice->getItemData(indx));
auto realIndex = (FXint)x;

Comment: Also, casting to FXint with C-style cast is unsafe. That is where static_cast should have been used. Except, performing any cast is unsafe in the first place and the correct solution would be make sure that FXint is a sufficiently wide integer type.
Comment: This is very good but misses that one should `#include `, and that then only guarantees to declare these types within namespace `std::`, not the global namespace.

Cast void pointer to int


Constraining parameters in NLS in R to be less than a value, or greater than a different value

Question: The nls function in R comes with upper and lower arguments to specify the upper or lower limit of a parameter:
nls(Y~A*X,upper=list(A=40),algorithm="port")

However, how can I set a parameter constraint, for instance, on parameter A such that it must be less than 5, or greater than 10?
Comment: How many parameters have such a constraint?
Comment: Just one of the parameters. There are three parameters in my full model: Y=ax/(b+x) + c
Answer: Can you not simply solve it (by a call to nls) twice, applying one constraint in in the first problem and the other constraint in the second, and identify which of the two has the smaller sum of squares of error, thus yielding a least squares solution to the larger problem?
The same strategy would work for a small set of "outside this range" type constraints, but beyond a handful the combinatorial explosion will hurt. If the unconstrained problem is unimodal and if the parameters not highly correlated, one approach might be to fit the problem unconstrained and then start imposing constraints on variables that don't obey the bounds (which may in turn push other variables out of bounds). If problems are not so well behaved, you'd have to look to combinatorial optimization methods.


Question about continuous and categorical variables

Question: We have 211 measurements of iron and carbon export rates across 5 sites and 2 temperatures, and each of those 5 sites has its own discrete set of physical and chemical characteristics. Would it be correct to treat those physical and chemical characteristics as continuous variables? If we perform a simple ANOVA, the sites are found to be significantly different across the sites. Similarly, if we treat the physical and chemical characteristics as categorical variables, they will explain the same amount of variation as the sites do and all of them are found to be significant but each of those categories has its own coefficients (beta).
What would be the correct approach to obtain some sort of trend for physical and chemical characteristics in this case?
Answer: What you are telling us is that $E(y|x)$ is a significant function of $x.$ Excellent! Now you need a physical-chemical-engineering-motivated model to explain your data!
Since you only have 5 "sites" and 2 temperatures, your input space is limited to 10 points. That doesn't sound like much, but in astrophysics, that's a lot. You absolutely should develop some continuous models around temperature and "site" specifications, hopefully involving a small number of parameters. Then use reasonable engineering/physical/chemical arguments to limit the values of these parameters. Can they be negative? Can they be larger than some value? Should some parameters always be less than others? Then move forward with a Bayesian analysis, which multiplies the maximum likelihood estimate of your data with your well-reasoned prior estimates of the values of the parameters.
Any "trend" that you will see will arise from the best fit model, which will correspond to the most likely parameters given a) the data and b) good engineering limitations on what those parameters should be. In practice, you will select the parameters that maximize the $likelihood \times prior.$ Whatever trend they describe is the trend you can report.
But before you are done, you should test to see how robust your best result is. This gets into evaluating the Hessian of the posterior. If you would like guidance on that, feel free to write back.
Comment: This was supposed to be a simple analysis, but someone who had analyzed this data had treated the characteristics as continuous variables, which seemed to be wrong. I am mostly interested in evaluating the effects of individual characteristics on export rates, but there doesn't seem to be a regression analysis which would let us do that without splitting it into categories.
Comment: You have to have at least one explanatory variable (discrete or continuous) if you mean to predict the response variable. I really don't know enough about your data or your goals to comment further.
Comment: I do have multiple discrete numeric explanatory variables, and a single response variable. I wanted to know if I could get statistically significant trends even with discrete explanatory variables.


Linear regression, heteroscedasticity, White's test interpretation?

Question: I am trying to test whether my regression has an issue of heteroscedasticity. After running a regression, I can clearly see that the residual plot has a pattern. After taking a log of the dependent variable the pattern is much, much reduced. The White's test on the original formula returns a p-value of 0.0004 before the transformation (the model with strong pattern in residuals), and a p-value of 0.08 after the log transformation.
I can see that the second model has less heteroscedasticity on the plot, but how do I interpret the results of White's test? Does the first value mean that we can reject that there is heteroscedasticity at (100-0.0004)% significance, while in the second model, we can reject it at, say, 95% confidence?
Answer: The original White paper where the test statistic was proposed is an enlightening read. This excerpt I think is of interest here:

...the null hypothesis maintains not
  only that the errors are
  homoskedastic, but also that they are
  independent of the regressors, and
  that the model is correctly
  specified... Failure of any of these
  conditions cal lead to a statistically
  significant test statistic.

Assuming that the model is correctly specified your results indicate that for non-transformed case there is a clear presence of heteroskedasticity, and in the log case there is no heteroskedasticity at 5% significance level, but there is at 10%. This means that in the log case further tests should be made, since the test "barely" accepts the null hypothesis of no heteroskedasticity. For me personally this would be an indication that maybe model specification is not correct and other heteroskedasticity  tests should be made. Incidentally White gives an overview of alternative tests in its article: Godfrey, Goldfeld-Quandt, etc.
Answer: This does not answer the question of how to use the test. However, you should know that most economists generally never run those tests -- especially, applied microeconomists. Instead, you just use the Huber-White adjusted standard errors which corrects for various misspecifications in the distribution of your error terms.
That's not a sharp "statistics" answer, but it's how most practitioners in economics handle it. Godfrey Goldfeld-Quant or White's tests are barely ever used or discussed.
Comment: Hm, but why not test it? By using adjusting standard errors you lose out in efficiency, if you really do not have problems with heteroscedasticity.
Comment: there is no cost in terms of efficiency in large samples when using robust standard errors when they were not necessary (i.e., when the errors are homoskedastic)


Correct Notes for C## in Harmonic Minor Scale

Question: Is the following scale correct for C## Harmonic Minor?
C##, D##, E#, F##, G##, A#, B#
I read on a good music theory page and they had B## as 7th note in the key, so I was wondering, but I'm pretty sure mine is correct with B#.
Comment: This is theory gone crazy! Thank goodness it's only theory. Why would you want or need to write in such an obscure 'key'?
Comment: C## is enharmonically identical to D, so you can just compare your notes to the notes in D Harmonic minor to see whether you're right.
Comment: @Tim  no doubt an exam question from a grouchy teacher :-)
Comment: It would be helpful to know if this was purposefully difficult theory question from a teacher, a misunderstanding of enharmonic spelling, or just horrible web site.
Comment: Actually I just started learning music theory and I checked if everything I understood was correct so far. I transformed my knowledge into a Program and tested if my understaning was complete, so I compared my scales to some music page stuff and found a difference in this spot.
Answer: Close; you actually do need Bx (B doublesharp) instead of just B♯. B♯ would be the minor seventh above Cx, and since harmonic minor has the major seventh (also called the leading tone), it must be Bx. Your scale is actually the Cx natural minor scale.
It's hard for me to imagine an instance where you might need the Cx (x being a doublesharp) harmonic minor scale, but there's one quick trick when dealing with difficult accidentals:

Spell it without the difficult accidentals, and then add the accidental(s) back to each pitch.

So instead of spelling the Cx harmonic minor scale, let's instead spell the C♯ harmonic minor scale, which is much easier:

C♯ D♯ E F♯ G♯ A B♯ C♯

Since that scale starts with C♯ and we want Cx, let's just add a sharp to each pitch, because that's what we do to get from C♯ to Cx:

Cx Dx E♯ Fx Gx A♯ Bx Cx

Or, maybe you'd rather start with the C harmonic minor scale:

C D E♭ F G A♭ B C

In which case we would add two sharps to each pitch. E♭ and A♭ would then pass through E♮/A♮ before proceeding to E♯/A♯.
This trick works for anything: scales, intervals, chords, you name it. So if you ever find yourself having trouble spelling a D♯ major triad, just think of a D major triad instead:

D F♯ A

And just add a sharp to each pitch:

D♯ Fx A♯
Comment: Thx mate. I just took a second look into the harmonic minor and I read over the thing that the 7th in key really is just one Semitone before the tonic.

I had noted an Integer Notation of { 0, 2, 3, 5, 7, 8, 10 } where infact it is { 0, 2, 3, 5, 7, 8, 11 }
Comment: Love to know why, when there's already 12 quite usable scales available - Dm being one (!) why this comes up as a question. What about the Ebb harmonic minor?! And I bet the notes all have exactly the same pitch, even in just tuning...+1 for 2nd para. alone!
Comment: This is more of a theoretical correctness thing because I'm programming some Music/Piano stuff and I must have all the theory correct. It helps me understand everything better and will be useful for my Piano practice.


Why is DataPager ignoring my custom IPagedCollectionView

Question: I've written a implementation of IPagedCollectionView and when I hook it to a DataPager, it remains empty and disabled.  I'm providing members for IPagedCollectionView and ICollectionView, IEnumerable, IEnumerable<T>, and the notifies.  What am I doing wrong?
Also is there already an implementation of IPagedCollectionView for silverlight that wraps around a RIA Services EntityQuery in order to provide server-side sorting that requests only a single page of data at a time?
Answer: IPagedCollectionView must be implemented side-by-side with ICollectionView, not alone. I don't know what can be your problem, but you could check this sample from Simon Ferquel.


How to reset a field formatter settings or layout builder configuration

Question: I was settings up an images field through layout builder. Change it from Bootstrap Basic Image Gallery to OwlCarousel.
When I submit the form, the UI does not have any response. and then I refresh the page, the website crash on this configuration page. /admin/commerce/config/product-types/easel/edit/display/default/layout
I wonder if there is any method to reset field formatter settings or the layout builder configuration.
PAGE ERROR:
Drupal\Component\Plugin\Exception\MissingValueContextException: Required contexts without a value: entity in Drupal\Core\Plugin\Context\ContextHandler->applyContextMapping() (line 155 of core/lib/Drupal/Core/Plugin/Context/ContextHandler.php).
Drupal\layout_builder\SectionComponent->getPlugin(Array) (Line: 70)
Drupal\layout_builder\Event\SectionComponentBuildRenderArrayEvent->__construct(Object, Array, 1) (Line: 89)
Drupal\layout_builder\SectionComponent->toRenderArray(Array, 1) (Line: 87)
Drupal\layout_builder\Section->toRenderArray(Array, 1) (Line: 240)
Drupal\layout_builder\Element\LayoutBuilder->buildAdministrativeSection(Object, 1) (Line: 124)
Drupal\layout_builder\Element\LayoutBuilder->layout(Object) (Line: 98)
Drupal\layout_builder\Element\LayoutBuilder->preRender(Array)
call_user_func_array(Array, Array) (Line: 101)
Drupal\Core\Render\Renderer->doTrustedCallback(Array, Array, 'Render #pre_render callbacks must be methods of a class that implements \Drupal\Core\Security\TrustedCallbackInterface or be an anonymous function. The callback was %s. See https://www.drupal.org/node/2966725', 'exception', 'Drupal\Core\Render\Element\RenderCallbackInterface') (Line: 772)
Drupal\Core\Render\Renderer->doCallback('#pre_render', Array, Array) (Line: 363)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 435)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 201)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 241)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 564)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 242)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 132)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 142)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch(Object, 'kernel.view') (Line: 174)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 81)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 58)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 48)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 48)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 51)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 709)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Answer: REF: https://drupal.stackexchange.com/a/310906/109110
I got the layout-builder back after deleting name = 'commerce_product.easel.default' from table key_value_expire


Sheets or Excel Formula for YOY% Change

Question: Say I have the following table, and I want to calculate YOY% Change.
How would I do this in Excel or Google Sheets, if they are not placed in the same row?
<code>Date   Sessions  YOY% Change
4/1/2016  300
5/1/2016  400
6/1/2017  500
5/1/2017  20000      ?  (Answer would be) 20,000/400-1
4/1/2017  10000      ?  (Anwswer would be) 10,000/300-1
</code>
Comment: Here is what the table should look like. Seems like when I typed this question through, the table didn't format properly. https://docs.google.com/spreadsheets/d/1_qJm5WFwu1iJiNVof-mZOcDnLa0QNqtXHt7okgPsvUs/edit?usp=sharing
Answer: Put this in C2 and copy/drag down:
<code>=IFERROR(B2/INDEX($B$1:B1,MATCH(DATE(YEAR(A2)-1,MONTH(A2),DAY(A2)),$A$1:A1,0))-1,"")
</code>
Comment: That's perfect Thank you!
Comment: @Inaya after the question is 15 minutes old you can select this as the correct answer by clicking the check mark by the answer.  Please do so as it will mark the question as answered and remove it from the unanswered queue.

Sheets or Excel Formula for YOY% Change


"contains" keyword with bracketed if-statement

Question: if clip contains Cho,oos,ose,wor,ord
          ...

How do I convert the above legacy style to non-legacy style:
if(...)
{
      ...
}

For example:
clip = %clipboard%

can be converted to non-legacy
clip := clipboard

I tried
if (clip contains "Cho","oos","ose","wor","ord")

but it doesn't seem to work.
Comment: Just to be congruent with the rest of the code because all values are taken as literals in legacy style unless we add %...% around them to indicate it is a variable.
Comment: From the [AHK documentation](https://www.autohotkey.com/docs/commands/IfIn.htm), _**Caution**: The operators "between", "is", "in", and "contains" are not supported in expressions._.  You can't put them in ().
Comment: I don't know the answer, but I'm curious, why do you need/want to do this? (thinking maybe I can learn something from this)
Comment: Thanks! Yep, it's important to have a code you like and that is consistent in form. But I guess there is no practical advantages with one or the other, then. I think I found a solution, see answer.
Comment: @Yane  Great catch!  But how is `clip contains Cho,oos,ose,wor,ord` not an expression by definition? Doesn't it evaluate to true or false?
Answer: This seems to work fine:
var := "schwurtzen"
if var contains % "wurt"
    MsgBox true
else
    MsgBox false

Comment: Evaluates true. If qoutation marks is excluded in the `if` it evaluates false.
Comment: Does this work if you add brackets for the if-condition?  Like so: if (var contains % "wurt")
Comment: No, the brackets doesn't contain an expression, so that won't work. And I can't figure out if it's possible to have several strings to match within this form, unless the MatchList is a variable var2: `if var contains % var2`. So I realise I didn't solve your problem after all.


there is no bounded linear functional on $ H$

Question: let $ H= L^2[0,1]$ and $ C^1 $ be the set of all continuouse functions on $ [0,1] $ that have continuouse derivative.Let $ t \in [0,1] $ and define $ L: C^1 \longrightarrow F $ by $ L (h)= h'(t) $. show that there is no bounded linear functional on $ H $ that agrees with $ L $ on $ H $ .thanks
Comment: What is the space $F$?
Comment: Hi!, what sequence of functions {fn}∈C1{fn}∈C1, we can use?? I think, fn(x)=sin(nx)/nfn(x)=sin(nx)/n. Regards!
Answer: Hint: Try to find a sequence of functions $\{f_n\}$ in $C^1$, such that $f_n$ is bounded in $H$ (i.e., the function values should not be large), but $f_n'$ unbounded in $F$ (i.e., the derivative is large).
Comment: Hi, what sequence of functions $\{f_n\}\in\mathcal{C}^1$, we can use?? I think, $f_n(x)=sin(nx)/n$. Regards!
Comment: This might work but will be tedious to check. I think it is easier to work with piecewise quadratic polynomials.


Falha no adb usando react-native no ubuntu

Question: Estou com um problema para rodar um app react-native no meu celular.
Com tudo configurado executo
react-native start
react-native run-android

e aparece o seguinte erro:

05:32:56 E/adb: adb server version (32) doesn't match this client (39); killing...

pelo que consegui entender estou com o adb instalado duas vezes no computador, porem nao consigo resolver o problema.
Answer: Resolvi o problema já, se mais alguem tiver o problema fiz o seguinte
sudo find -name adb

vi que uma das copias tava no

./usr/bin/adb

e outra no

./home//Android/Sdk/platform-tools/adb

então copiei o da pasta do android para o bin com
sudo cp ./home/<usuario>/Android/Sdk/platform-tools/adb ./usr/bin/


C++ method overloading

Question: I have a method and I need to overload it, but as I try I get error which says no matching function for call to Vehicle_Renting::Order::Order()
Here's how it looks:
Class declaration:
class Order
{
    private:
    class ImplementationOrder;
    ImplementationOrder* implOrder;

Inner class:
class Order::ImplementationOrder
{
private:
    string date;
    int price, id;
    friend class Order;
    bool isVerified;
    vector<Vehicle> orderedVehicles;
    Customer* customer;
    friend class Order;
};

Constructors:
Order::Order(int price)
        :implOrder(new ImplementationOrder())
    {
        #ifdef DEBUG
            clog << DEBUG_PREFIX "Constructor (1 arg) called!" << endl;
        #endif // DEBUG
        setDate();
        setPrice(price);
        assert(price >= 0);
    }

    // copy constructor---------------------------------------------------------
    Order::Order(const Order &other)
      : implOrder(new ImplementationOrder(*(other.implOrder)))
    {
    }

Methods:
void addOrder(const Order& o, const Client& c);
void addOrder(const Client& c);
void Auto_Rent::addOrder(const Order& o, const Customer& c)
{
    addCustomer(c);
    int pos = getCustomerPosition(c);
    Order o1(o);
    o1.setCustomer(implAuto_Rent->customers[pos]);
    implAuto_Rent->orders.push_back(o1);
}

void Auto_Rent::addOrder(const Customer& c)
{
    addCustomer(c);
    int pos = getCustomerPosition(c);
    Order o1;
    o1.setCustomer(implAuto_Rent->customers[pos]);
    implAuto_Rent->orders.push_back(o1);
}

I create object called customer:
Customer c5("Agriosas", "Lasiokas", 1994), c6("Edves", "Lasas", 1992), c7("MAtkes", "brolis", 1991);

And I call addOrder function:
  s.addOrder(c5);
  s.addOrder(c7);
  s.addOrder(c6);

Comment: Missing the line producing the error, missing the supposed declaration of that ctor, missing its definition. We basically arrive at the same conclusion as the compiler: if you want a working executable, show some source code.
Comment: Your `Order` class has no default-constructor, but somewhere in the code you haven't shown us you're doing something like `Order odr;`.
Comment: Where is code where you have called these functions?
Comment: Show the class declaration of `Order` please. That's the code in question at least! Most probably you simply don't have a default constructor provided for class `Order`.
Answer: On this line:
Order o1;

You need the default-constructor to construct this Order object, please add one to your class that does the right thing.
Comment: How it should look? Sorry for asking I'm a bit confused.
Comment: @user3476593 `Order() : implOrder(...) { ... }`

C++ method overloading


Optional Output Parameters

Question: In C# 4, is there a good way to have an optional output parameter?
Comment: I disagree that there's no value in this feature. If a method has some logic in it BESIDE returning data via out-parameters - I want to be able to call this logic, just don't need the output...
Comment: I use Int32.TryParse() to see if the given string can be parsed into a number and, if it can, sometimes that's all I care about. So Jitbit is right.
Comment: It's can be handy to optionally capture sidechain information from a function.  Plus, if VB has it, why doesn't C#?  It should automatically overload.
Comment: Don't see any value for such a feature. If you have ever listen to C# compiler guys' sessions on PDC, you will see every changes has a meaning.
Answer: Not really, though you can always overload the method with another one that does not take the output parameter.
Comment: In C# 7.0 you can do `Foo(out string dummy);` or even better `Foo(out _);` (underscore)
Comment: any idea how to handle the optional parameter more elegantly than `{ string dummy; return Foo(out dummy); }` in the overload that does not take the output parameter?
Comment: @Louis: Nope, that's probably what I'd have done!
Comment: the fact that this is possible, shows that it should have been optional in the language design. this seems like an okay solution. although, it does not allow me to put the output parameter after other optional parameters, which can cause typos if i expect the overloads to have the same parameter order
Comment: That's a lot of extra boiler plate code.
Answer: No.
To make it "optional", in the sense that you don't need to assign a value in the method, you can use ref.
Comment: A `ref` parameter is a very different use case.  An optional parameter passes in a specific value if the caller does not specify one -- with a ref parameter, the caller is always specifying a value, whether they feel like they have specified it or not. The `ref` always points to valid memory location, and a valid memory location always contains _something_.  At best, this is just a magic value without the benefit of a default specification saying "the default value is X."
Comment: Yea, this answer isn't a design judgment, which is why I added the "in the sense that" qualifier.
Answer: Decorating the parameters with OptionalAttribute doesn't work, either.  To extend the previous sample, you'd get something like:
private void Func(
    [Optional] out int optional1,
    [Optional] out string optional2)
{ /* ... */ }

Note that the above will compile (perhaps unfortunately). However, attempting to compile:
Func(out i);

will fail unless an overload with a one-parameter signature is explicitly provided.
To (theoretically) make the above work is a significant problem. When a method with an omitted optional parameter is called, a stack frame containing the values of all the parameters is created, and the missing value(s) are simply filled with the specified default values.
However, an "out" parameter is a reference, not a value. If that parameter is optional and not supplied, what variable would it reference? The compiler still needs to enforce the requirement that the "out" parameter be filled before any normal return from the method, as the compiler doesn't know a priori which (if any) optional parameters are specified by a caller. This means that a reference to dummy variable somewhere would have to be passed so the method has something to fill. Managing this dummy variable space would create a nasty headache for the writer of the compiler. I'm not saying that it would be impossible to work out the details of how this would work, but the architectural implications are great enough that Microsoft understandably passed on this feature.
Answer: private object[] Func();

assign as many as optional outputs you want in return object array and then use them!
but if you mean optional output something like
private void Func(out int optional1, out string optional2)

and then you call something like
Func(out i);

then the answer is no you cant.
also C# and .NET framework hast many many data structures that are very flexible like List and Array and you can use them as an output parameter or as return type so there is no need to implement a way to have optional output parameters.
Answer: public class Dummy<T>
{
    public T Value;
}

Then use DoSomething(out new Dummy<int>().Value), where int could be of any type.

Optional Output Parameters


Zooming in/out some tiles not rendering - Osmdroid offline maps

Question: I'm loading tiles from asstets, these is my code, which initialize map:
    mapView = (MapView)findViewById(R.id.offline_map_view);
    mapView.setClickable(true);
    mapView.setBuiltInZoomControls(false);
    mapView.setMaxZoomLevel(macroZoomLevel);
    mapView.setMinZoomLevel(macroZoomLevel);
    mapView.getController().setZoom(macroZoomLevel); //set initial zoom-level, depends on your need
    mapView.setTileSource(new XYTileSource("MapQuest", 0, 18, 256, ".png",new String[] {"file:///android_asset/try/"} ));
    mapView.setUseDataConnection(false); //keeps the mapView from loading online tiles usi1ng network connection.
    mapView.getController().setCenter(new GeoPoint(54.370958, 18.589210));
    giveMarkersForActualLevel();

and everything is ok till I try to zoom in, there are part of maps which not rendering properly. Then I zoom out and then area which was on the beginning rendered properly is now having some gray tiles.
Firstly, I used osmdroid 4.3, added in this way:
 compile 'org.osmdroid:osmdroid-android:4.3'

Then I try with newest version of osmdroid, importing it by method which is described on the website compile 'org.osmdroid:osmdroid-android:5.1@aar'
Then I read here tu build from sources so I download newest sources, build it by gradle and added aar file osmdroid-android-release.aar.
This doesn't fix my issue, too.
After zoom in and zoom out, I'm removing markers and adding another ones, so I tried to refresh map in this way.
((View)mapView.getParent()).invalidate();
mapView.invalidate();
mapView.postInvalidate();

Marker startMarker = new Marker(mapView);
startMarker.setPosition(new GeoPoint(54.337385, 18.662132));
setPropertiesForTopMarker(startMarker);
mapView.getOverlays().add(startMarker);

Marker startMarker1 = new Marker(mapView);
startMarker1.setPosition(new GeoPoint(54.332781, 18.587932));
setPropertiesForTopMarker(startMarker1);
mapView.getOverlays().add(startMarker1);

mapView.invalidate();
((View)mapView.getParent()).invalidate();
mapView.invalidate();
mapView.postInvalidate();

but it doesn't work too.
Have you got any ideas, how this issue can be resolved?
EDITED:
I tried to build osmdroid from sources to change this values mentioned by @spy. The debug from my logcat looks ok. Here are logs. I can't paste it here, because there are too many lines.
I tried with adding tiles providers in this way:
 final IRegisterReceiver registerReceiver = new SimpleRegisterReceiver(getApplicationContext());

        final ITileSource tileSource = new XYTileSource("MapQuest", 12, 14, 256, ".png",new String[] {"file:///android_asset/MapQuest/"} );

        final MapTileFilesystemProvider fileSystemProvider = new MapTileFilesystemProvider(
                registerReceiver, tileSource);

        final MapTileProviderArray tileProviderArray = new MapTileProviderArray(
                tileSource, registerReceiver, new MapTileModuleProviderBase[] {
                fileSystemProvider});

        mapView = new MapView(this, new DefaultResourceProxyImpl(this), tileProviderArray);

or this way
 final IRegisterReceiver registerReceiver = new SimpleRegisterReceiver(getApplicationContext());

            final ITileSource tileSource = new XYTileSource("MapQuest", 12, 14, 256, ".png",new String[] {"file:///android_asset/MapQuest/"} );

            final MapTileFilesystemProvider fileSystemProvider = new MapTileFilesystemProvider(
                    registerReceiver, tileSource);

            final MapTileProviderArray tileProviderArray = new MapTileProviderArray(
                    tileSource, registerReceiver, new MapTileModuleProviderBase[] {
                    fileSystemProvider});

 TilesOverlay tilesOverlay =
                new TilesOverlay(tileProviderArray, getApplicationContext());

        mapView.getOverlays().add(tilesOverlay);

but both methods didn't show me any map. Source of this code.
Comment: are you sure you have tiles at that zoom level?
Comment: If i haven't got tiles on that level, I wouldn't see any tiles rendered after zoom in. What is more if I go back to initial zoom level, I can see some gray tiles, which previously was rendered in properly way. I try to update question with more details, when I come back to home.
Comment: I have the same problem, I don't know the reason yet, but when zooming in and out I have the following message several times: "Called reconfigure on a bitmap that is in use! This may cause graphical corruption!"

I'm using OSMDroid 5.1 and targeting Android M
Answer: Something worth trying...
If you only want asset loading, then use a custom tile provider array that only includes the asserts loader. In the above config, it will still is the online mechanisms (okhttp or whatever's on the device) to try and download the file from file:/// which may behave strangely with file urls.
Also try turning on tile debugging via OpenStreetMapTileProviderConstants.DEBUGMODE and DEBUG_TILE_PROVIDERS. It may reveal the root cause
Comment: Thx for this hint, I will try to go in that way with investigating this problem ;)
Comment: Have you got any other idea? Have you been working with offline maps, maybe you know better solution or other library ?
Answer: Ok, finally I solve my issue by using Providers.
I made few modification of code taken from this answer, so right now it looks like this.
        mapView.setClickable(true);
        mapView.setBuiltInZoomControls(false);

        mapView.setMaxZoomLevel(macroZoomLevel);
        mapView.setMinZoomLevel(macroZoomLevel);
        mapView.getController().setZoom(macroZoomLevel); //set initial zoom-level, depends on your need

        mapView.setUseDataConnection(false); //keeps the mapView from loading online tiles usi1ng network connection.
        mapView.getController().setCenter(new GeoPoint(54.370958, 18.589210));

        // save zip to sd
        AssetManager assetManager = this.getAssets();
        InputStream is;
        String fileName = "map.zip";    // the zip file lies in assets root
        String path = this.getExternalFilesDir(null) + File.separator + fileName; // the path I save SD to

        File tileFile = new File(path);
        if(!tileFile.exists()) {
            try {
                is = assetManager.open(fileName);

                FileOutputStream fo = new FileOutputStream(path);

                byte[] b = new byte[1024];
                int length;
                while((length = is.read(b)) != -1) {
                    fo.write(b, 0, length);
                }

                fo.flush();
                fo.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        IArchiveFile[] archives = new IArchiveFile[1];
        archives[0] = ArchiveFileFactory.getArchiveFile(tileFile);

        // Simple implementation that extends BitmapTileSourceBase and nothing else
        CustomTileSource customTiles = new CustomTileSource("MapQuest", null, 10, 14, 256, ".png");  // Maverik is the name of the folder inside the zip (so zip is map.zip and inside it is a folder called Maverik)

        MapTileModuleProviderBase[] providers = new MapTileModuleProviderBase[1];
        providers[0] = new MapTileFileArchiveProvider(new SimpleRegisterReceiver(this.getApplicationContext()), customTiles, archives);    // this one is for local tiles (zip etc.)

        MapTileProviderArray tileProvider = new MapTileProviderArray(customTiles,
                new SimpleRegisterReceiver(this.getApplicationContext()), providers);
        tilesOverlay = new TilesOverlay(tileProvider, this.getApplicationContext());
        tilesOverlay.setLoadingBackgroundColor(Color.TRANSPARENT);  // this makes sure that the invisble tiles of local tiles are transparent so we can see tiles from web, transparent have a minor performance decline.

        mapView.getOverlays().add(tilesOverlay);

CustomTileSource looks like this:
public class CustomTileSource extends BitmapTileSourceBase {

    public CustomTileSource(String aName, ResourceProxy.string aResourceId, int aZoomMinLevel, int aZoomMaxLevel, int aTileSizePixels, String aImageFilenameEnding) {
        super(aName, aResourceId, aZoomMinLevel, aZoomMaxLevel, aTileSizePixels, aImageFilenameEnding);
    }
}

so this is just subclass of BitmapTileSourceBase without any additional method.
I have in assets zip type file, which name is map.zip, structure of this directory looks like this:
map.zip/MapQuest/[lvlOfZoom]/[x]/[y.png]

And now it works ok, I only zooming when I click on my marker, the user by gesture can't do that.
If you have some problems with implementing approach descripted by me or something isn't clear for you, I will try to help you in comments.


Equal number of 1s and 0s in number of n digits

Question: How many ways could one create a binary number of n digits where the number of 1s and 0s are equal?
For example, if n was 8 then we could have:
10101010
or
11110000
In addition to this, I may add that numbers such as:
00001111
are allowed as I am concerning the application of 1 and 0 as abstract ideas.So 1 and 0 could easily be replaced by "banana" and "apple" or (in better context) "y+1" and "x+1".
Comment: Are numbers like $00001111$ allowed?
Answer: Pick $n$ of the $2n$ digits to put one's in: $$\binom{2n}{n}=\frac{(2n)!}{(n!)^2}$$
Answer: Suppose there are $2n$ digits to fill. (The problem is clearly impossible if the number of digits is odd.) Once we have chosen the location of the $n$ zero digits the position of the ones digits will be uniquely determined. It follows that the number of strings of the form you are looking for is the number of ways to choose $n$ objects from a set of $2n$ objects without caring about ordering, i.e. the number is
$$
\binom{2n}{n}=\frac{(2n)!}{(n!)^2}.
$$


c# how to get a file path of the same file on different computers

Question: i am trying to make a code which takes an image from a file path which i type in manually.
here is my code:
<code>pieceImage = Image.FromFile(@"O:\Projects\imagename.png");
</code>
This code is saved on my USB flash drive.
However, whenever i run this code on a different computer, the path is different (obviously) and doesn't necessarily start with O:\ but something else, for example F:.
What can i use so that the path will change accordingly to the computer on which it runs? many thanks in advance.
Comment: perhaps you can look at how to map a folder.. not all computers will have the same drive names
Comment: thats impossible because those computers can have different drive names. you should first copy that image file  nearer to the project folder in the other computer so that you can use Relative path.
Answer: You could get the drive letter based on the drive name, then build the Path to the file based on that (so only use the relative path from the root of the drive, no letter). See the DriveInfo class on MSDN and this question for a practical example of usage.
Of course, if the image is not on the USB drive, you will need to be more creative. But then I would recommand a different approach all the same, because there might be a design flaw in all this.
Answer: Assuming your program is in directory /Program/, include all images under your /Program/ directory, such as /Program/Images/. That way the images will be available no matter where the program is run.


Exporting Images with JAR in Eclipse (Java)

Question: I've been working on a little project that requires external images for display. I'm not all that familiar with how to use Eclipse and this is my first time attempting to export a completed project so I can share it with others. Right now, it seems the only way I can get my images to show up is if I assign a specific folder on my hard drive and have the image paths in the code go to that.
I'm looking for a way to export the images as part of my JAR or as part of the same package so when I go to send this program to other people, I don't have to send them a separate archived folder of images. I'd also be interested in learning what I need to do to have my code reference the images within that package so they'll work without an external folder.
I have read about some kind of package system within Eclipse, but have thus far had no luck in figuring out how to use it. Could use some explicating!
Thanks in advance to anyone willing to give me their two cents.
Answer: Something I would have found useful with this answer is the following: make sure you put your images/files in the same eclipse folder (or sub-folder below) as your source code.  I created a folder "images_ignored" using eclipse, added it to the build path but still it refused to be included in my JAR file (when creating an executable JAR).
Comment: I think this breaks convention just a bit.  It is helpful for only `.java` source files (and other actual source code files) to be in the `src` directory.  I think @danny's answer is most sufficient, to right click on the desired folder and go to build path, "use as source folder".  This way you can easily separate resources (images, sounds, source, config, etc.)
Comment: I signed in specifically to upvote @MichaelPlautz's comment. Please don't add images in with your .java files just because it happens to work.
Answer: Just drag the images folder into your Eclipse project, then choose to "Copy New Folder" or "Copy File and Folder" depending on Eclipse version, and then right click on the image folder (in Eclipse) and --> build path "use as source folder".
Comment: Thanks @danny, this answer addresses what I was trying to do.  However, when you do this, it removes the bottom-level folder.  For example, I had a folder called `img` that stored all of my images, and when I did "use as source folder", all of the contents of the `img` directory appeared at the base/root level of my `jar` file. To get around this, I created a folder called `lnk`, and then created a symbolic link to my `img` folder (in Windows, this can be done with `JUNCTION`) within the `lnk` folder. Now, when I added `lnk` "as source folder", the images were in the `img` folder in the `jar`.
Answer: you might need to load them as class path resources if they are within a jar. see: getClass().getClassLoader().getResourceAsStream(...)
Comment: Ok, well, first problem then is that I apparently have no idea how to get them into the JAR using Eclipse. Can you maybe explain that to me?
Comment: place them on the class path. so, find a eclipse source folder and put them in it. or whatever folder they are in - just right click and click add to build path
Answer: Use getResource() to load the images:
ImageIcon qmarkIcon = new ImageIcon(getClass().getResource("images/mark.gif"));

Answer: If you're using JDK 1.7 or JDK 1.8, you might want to use the NIO.2 API.
for (FileSystemProvider provider : FileSystemProvider.installedProviders()) {
    if ("jar".equals(provider.getScheme()))
        return provider.newFileSystem((new File(Start.class
                .getProtectionDomain().getCodeSource().getLocation().toURI()))
                .toPath(), new HashMap<String, Object>());
}

If you enter this code into a method that returns a java.nio.file.FileSystem, you can call the method to get the FileSystem for the JAR file.
To get the path to access the files inside your JAR file, you can use the following method, which then allows you to read the files however you may want.
fileSystem.getPath("/images/image.gif")

If you would like to be able to run this in Eclipse, make sure you surround the call to the method with a try/catch IOException and assign to your FileSystem object the following.
new File(Start.class.getProtectionDomain().getCodeSource().getLocation().toURI())
        .toPath().toString();

This will allow you to run your program whether it's compressed into a JAR file or not.

I recommend you get used to using NIO.2, since it is a very powerful API.
Answer: If you add a folder to build path you can retrieve the images either in eclipse and when you exported it in jar file, just remember to don't reference the image with the path like img/myImage.gif but only myImage.gif !


random sampling in a polygon

Question: I would like to sample a uniformly random point in a polygon...
If sample a large number they'd be equally likely to fall into two regions if they have the same area.
This would be quite simple if it were a square since I would take two random numbers in [0,1] as my coordinates.
The shape I have is a regular polygon, but I'd like it to work for any convex polygon.
https://stackoverflow.com/questions/3058150/how-to-find-a-random-point-in-a-quadrangle
Comment: There are many approaches; one simple one would be accept-reject (generate an enclosing rectangle, and then generate uniform points inside it, keeping any points inside the polygon). You could overlay it with a sequence of strips, and do accept reject in each strip, with each strip being selected in proportion to its area (in effect generalizing the ziggurat method).  You could split it into triangles, find the area of each, and then at each iteration select between the  triangles in proportion to their area and then place a point uniformly in the selected triangle.
Comment: @Glen_b Those are all great suggestions. Another approach, which I have found practicable, simple to code, and of general application, is to use rejection sampling whenever the polygon occupies an acceptably large proportion of its bounding box and otherwise to split that BB in half along its longer dimension, select one half with probability proportional to the area of the polygon within that half, and proceed recursively. (This implicitly builds an adaptive quadtree representation of a tight envelope around the polygon.) The hardest part is to clip a polygon to a rectangle, which is easy.
Comment: @whuber +1 very nice. That sounds reminiscent of the unimodal adaptive rejection sampling Radford Neal has described (in turn probably based on Luc Devroye's idea for monotonic densities in his book);  I came up with the same idea for unimodal densities some years ago but Neal seems to have had the idea well before me; such a unimodal sampler is still unpublished, I believe. That basically involves knowing (or finding) the mode and using step functions as both upper and lower bounds, which are updated on every (presumed costly) function evaluation (lower bounds avoid many evaluations).
Comment: @Glen_b Have you seen this [beautiful] answer?  http://stats.stackexchange.com/questions/13630/how-to-sample-from-ca-da-1-gammaa/13767#13767.
Answer: The spsample function in the sp package for R will generate a random sample of points within a polygon (does not even need to be convex).
Comment: this is great to know... perhaps I was asking how `sp` works.
Comment: @johnmangual, The `spsample` function has many options to do the sampling in different ways.  But I believe that the default method for random sampling in a polygon is rejection sampling as mentioned in the comments above.

random sampling in a polygon


How to write statement in Console.WriteLine so that it prints in separate lines

Question: I want to write a line in Console.WriteLine such that each part should be printed on separate line, temporary I have formatted with \r\n but it is difficult to manage, is there any good alternative ?
Console.WriteLine("\nWhat Operation you need to perform \r\nA-Addition: \r\nS-Subtraction: \r\nM-Multiplication: \r\nL-FindLargestElementInMatrix: \r\nS-FindSmallestElementInMatrix: \r\nDL-DisplayLowerTriangularMatrix: \r\nDU-DisplayUpperTriangularMatrix: \r\nT-FindTransposeOfMatrix: \r\nE-CheckIfTwoMatricesEqual: \r\nI-CheckIfTwoMatrixIsIdentityMatrix: \r\nS-SumOfDiagonalElementsOfMatrix: \r\nAR-SumOfEachRowOfMatrix: \r\nAC-SumOfEachColumnOfMatrix: \r\nIR-InterchangeRowsOfMatrix: \r\nIC-InterchangeColumnsOfMatrix: ");

I want to write a line in Console.WriteLine such that each part should be printed on separate line, temporary I have formatted with \r\n but it is difficult to manage, is there any way out ?
Answer: The preferred option here is probably to call Console.WriteLine(...) once per line; the reason for this is so that the runtime/core-libs can make the determination about the most appropriate line-endings suitable for your display / stdout / etc - rather than the hard-coding present either explictly in strings "like\r\nthis" or in verbatim-string-literals or raw-string-literals (@"...includes line-breaks natively..." or """...includes line-breaks natively...""").
Console.WriteLine(value) is simply a short-cut to Console.Out.WriteLine(value), where Out can be redirected via Console.SetOut(TextWriter) - which means the output device could in theory be anything.
Answer: In C# 11, you can use a raw string literal:
string output = """
    What Operation you need to perform
    A-Addition:
    S-Subtraction:
    ...
    """
Console.WriteLine(output);

In earlier versions of C# you can use a verbatim string. Note that we can't indent each line as we can with a raw string literal, as this will mean that the string printed to the console is also indented:
string output = @"What Operation you need to perform
A-Addition:
S-Subtraction:
...";
Console.WriteLine(output);

You can also just split your string into multiple strings, and concatenate them together:
string output = "What Operation you need to perform\r\n" +
    "A-Addition:\r\n" +
    "S-Subtraction:\r\n" +
    "...";
Console.WriteLine(output);


Why this code not work

Question: Public Class Form1
Dim i = 0
Dim re = True
Private Sub Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)   Handles Timer.Tick
    If i = 225 Then
        re = False
    ElseIf i = 0 Then
        re = True
    End If
    If re = True Then
        i += i
    ElseIf re = False Then
        i -= i
    End If
    color1.BackColor = Color.FromArgb(i, i, i)
End Sub
End Class

In this code, i want the label from black to white and then from white to black.
I set the re var to indicate whether it is white, then i will reduce until the color to black. => Not works
Comment: Try stepping your code sometimes. Putting a breakpoint at the beginning at the function, and stepping through it probably would have allow you to find the typing mistakes yourself.
Answer: i += i

Should be:
i += 1

i starts at 0, so you keep adding 0+0 and never get anywhere.
Also, RGB colors go all the way to 255, not 225, but you would have seen that one.
Answer: First of all, make sure you have enabled timer Timer somewhere else in your code. Also, do what Kobi said, change i += i to i += 1.
What's also important is to start using Option Strict On, Option Explicit On and declaring the types of your variables:
Dim i As Integer = 0
Dim re As Boolean = True

This is the first step to improve your code quality.
Comment: There are many issues with this code: `i` should be `shade`, `re` should probably be `increasingSahde`, and `if increasingSahde then`. I can think of a few more.
Comment: Thanks, but i am not english, so i just make a random var name :(

Why this code not work


Can someone find a way to fix my unidentified type error?

Question: I'm trying to create a custom cursor in Vue 3, but my code does not work. Here's my code
    <template>

</template>

The console gives me this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'x')

Comment: Yes, computed looks a bit skanky
Comment: yeah, the error shows that's where the error begins
Comment: Please explain in fair detail exactly what you're trying to achieve with your code.
Answer: Your computed should have the cursorPoint variable:
    ...
    computed: {
      cursorPoint() {
        return `transform: translate(${this.x}px,${this.y}px)`
      }
    },
    ...


Como filtrar resultado de outra pagina com Jquery Load() ou Get()?

Question: Em um HTML tenho por exemplo:
<fieldset>

Dados da conta

        Usuário
        MEU-USUARIO

        Modificar

        E-mail
        email@example.com
        Modificar

        Senha
        **********
        Modificar

</fieldset>

Preciso de Outra página capturar o Nome de usuário e salvar numa variável, o mais próximo que conseguir alcançar com jQuery Load() foi:
$( "#id-de-teste" ).load("https://myaccount.mercadolivre.com.br/profile .ch-form-row span:first", function(data, status){
username = $('#retorno_webtracker').html();
alert(username);
    });

Porém eu tive 2 problemas: A variável com o Username ficou também com as tags , e eu não quero/preciso que este valor seja exibido na página, só preciso dele na variável para prosseguir com a rotina do script.
Com jQuery Get() consigo "baixar" a página com os dados que preciso, no entanto não estou conseguindo filtrar somente a classe .ch-form-row depois a primeira tag
$.get("https://myaccount.mercadolivre.com.br/profile", function(data, status){
        //alert("Data: " + data + "\nStatus: " + status);
//username = $('span',$('.ch-form-row')).html();
filtro = data.getElementsByClassName('ch-form-row');
console.log( filtro );
    });

Answer: Consegui resolver
$.get("https://myaccount.mercadolivre.com.br/profile", function(data, status){
        var username = $('.ch-form-row span', $(data)).html();
//todo o codigo que precisa da variavel
});


Unsupported operating system with Docker on windows 10 with wsl2

Question: I installed docker and downloaded an ubuntu distro to run with laravel sail,planing to use swoole php,and made it default,also made wsl version to 2

with docker-compose.yml ready from laravel sail docker-compose.yml:

but every time I try to run the sail up cmd,it gives me this error " Unsupported operating system [MINGW64_NT-10.0]. Laravel Sail supports macOS, Linux, and Windows (WSL2)."

any ideas how to fix this ?
Comment: C:\wamp64\www\mtqdma\l_8\mzaedh>vendor\bin\sail up
|
/bin/bash: C:\wamp64\www\mtqdma\l_8\mzaedh\vendor\bin\/../laravel/sail/bin/sail: No such file or directory
Comment: Tried using cmd.exe?
Comment: i did,but it do no work,i saw some ppl say i have to use bash not cmd,because bash is interpreted
Comment: cmd : " ./vendor/bin/sail up "
response : " '.' is not recognized as an internal or external command,
operable program or batch file. "

cmd : " /vendor/bin/sail up "
response : " 'vendor' is not recognized as an internal or external command,
operable program or batch file. "

cmd : " vendor/bin/sail up "
response : " 'vendor' is not recognized as an internal or external command,
operable program or batch file. "

even though i did php artisan sail:install
Comment: cmd is interpreted too... -- you have to do `vendor\bin\sail up` in cmd, no `./` or `/` sep
Answer: If you are using windows follow these steps.

Make sure ubuntu and WSL 2 is installed, you can follow the instructions here
After successful installation of ubuntu, your file system now shares the same file system with your ubuntu, this means if you want to run ubuntu commands on a folder path you have to open the corresponding terminal. If you are using Visual Studio Code, you can select the corresponding ubuntu terminal for the file directory by selecting ubuntu as the new terminal, it will open the Ubuntu terminal on the current path.
You can run ./vendor/bin/sail up. Make Sure you are running the command from your project folder in Ubuntu. Usually the folder is always in /mnt/c/users/path/to/project.
If you see docker not running. Open your docker desktop, go to setting, under resources, select WSL and enable integration with your ubuntu

Restart your terminal, and run the command again. Don't forget under you Ubuntu file system which is usually in /mnt/c/users/path-to-laravel-project.
you should see the following for the first time. Note the folder path highlighted.
One last thing, in order to access your laravel app on your localhost, you have to access the WSL IP address that connects to Ubuntu. use the following command. wsl hostname -i it outputs an IP address like , Note! your IP address may be different. Navigate to the IP address on default port 80 and you should see.

I wish you a successful project. Enjoy!!
Comment: I didn't have to do the point 6, I simply managed to connect to `localhost`. (Using Laravel Sail 1.0.1, Docker Desktop 4.25.1.)
Answer: You need to run the sail up command from inside your WSL2 Ubuntu Image not directly from your terminal. Once you do that it should work ok
Comment: You have to `cd /mnt/c/path/to/laravel` @AhmedWagihRefaey
Comment: do i have to cd to the laravel project or just anywhere ?
also i saw some ppl say that i have to move my project to the image,to directory same as this as example
Comment: \\wsl$\Ubuntu-20.04\home\wagih\mzaedh
Comment: thanks, it worked, no one mentioned it at the tutorials, although it needed some permissions to run the command

but right now after the container downloaded and stuff,i cant run the project
Comment: [Mon Mar  1 02:25:38 2021] PHP 8.0.2 Development Server (http://0.0.0.0:80) started

this is at the ubuntu image terminal

but once i run that at the browser it gives nothing
Comment: let me serve some more tutorial, it seems i'm missing lots of untold things
Comment: the problem now is that the container is running i docker,and once i type localhost in my browse,it opens the wamp homepage,although wamp is not running, any ideas ?
Comment: Thank you all,it worked, i had to change wamp port to 8090 instead of 8080 to solve the confilect
Comment: Check out my comprehensive answer above.


Determine if the sequence $a_n= (c^n +d^n)^\frac{1}{n}$ is an increasing or a decreasing sequence

Question: If $0 \lt c\lt d$, then the sequence $a_n= (c^n +d^n)^\frac{1}{n}$

a.) is bounded and monotone decreasing.
b.) is bounded and monotone increasing.
c.) is monotone increasing , but unbounded for $1 \lt c\lt d$.
d.) is monotone decreasing , but unbounded for $1 \lt c\lt d$.

My approach:
We can clearly see $ \lim_{n\to \infty}$ $a_n =d $, hence it is bounded above so option c and d cannot be correct. Now using the Nth term test, $ \lim_{n\to \infty}$ $a_n =d $ ($d\ne 0$), we can say the sequence is divergent. But using this divergence can we say the sequence is  monotonically increasing?
And if my approach is correct then c would be correct option.
Comment: How are you saying that the sequence is divergent? You've already said that it has $d$ as the limit. The test you're talking about seems to be one about the **series** $\sum a_n$ but no one is talking about that?
Comment: What exactly is the $N$-th term test that you're talking about?
Comment: @AryamanMaithani I suspect it's what I know as the divergence test: if $a_n \not\to 0$, then $\sum a_n$ diverges.
Comment: @TheoBendit yes you are right. https://en.wikipedia.org/wiki/Term_test
Comment: Notice when $n=1$, that it's $c+d$ Which is greater than the limit of $d$, so it can't be monotonically increasing.
Comment: @AryamanMaithani so you are implying that we cannot use Nth term test here because it is a sequence not series.
Comment: @AryamanMaithani I also tried to determine whether $\frac{a_{n+1}}{a_n} $ is < or > 1 but i could not reach a concrete result.
Answer: I suppose you did like, $a_n= (c^n+d^n)^{\frac{1}{n}}= d\left(1+\left(\frac{c}{d}\right)^n\right)^\frac{1}{n}$, so $\lim a_n= d$. Now since limit exist its convergent. Its not divergent!
And also its monotone decreasing, since the first term is $c+d> d$ and as $n$ increases, $a_n\rightarrow d$, so it must be decreasing. (This approach is helpful only in mcq type exams)
Another way to show its decreasing: $a_{n+1}= d\left(1+\left(\frac{c}{d}\right)^{n+1}\right)^\frac{1}{n+1}< d\left(1+\left(\frac{c}{d}\right)^{n+1}\right)^\frac{1}{n}< d\left(1+\left(\frac{c}{d}\right)^{n}\right)^\frac{1}{n}$, since $c< d\Rightarrow \frac{c}{d}< 1\Rightarrow \left(\frac{c}{d}\right)\cdot\left(\frac{c}{d}\right)^n< \left(\frac{c}{d}\right)^n\Rightarrow \left(\frac{c}{d}\right)^{n+1}< \left(\frac{c}{d}\right)^n$, because $\frac{c}{d}> 0$.
Thus we have $a_{n+1}< a_n\,\,\,\forall n\in\mathbb{N}$
And also divergence not neccesarily imply the sequence is increasing, it may diverge to $-\infty$.
Comment: It should be pointed out that it only "must" be decreasing because we eliminated the other options. Simply starting from $c + d > d$ and converging to $d$ is not enough to conclude a sequence is monotone decreasing.
Comment: yes i did it the same way. yes i got it that this is the decreasing sequence. But what about the nth term test ? we can't use it because it a sequence and not series.
Comment: If nth term test is what you mean by divergence test, then I would say it is of no use, since you can already establish its converging


communicate new/changed values between taxonomies

Question: I have a taxonomy called Species, and another taxonomy called Protected Areas.
Inside of the Protected Areas I have a multifield widget (Taxonomy reference pointing to Species), where user can select different Species present on the Area.
Users are able to manipulate also the Species taxonomy, when adding a new Species they are able to choose in which Protected Area is this specie present. Then, when users do it, I would like to automatically update the user selected Protected Area taxonomy (for this Species), adding on the multifield widget the recently added Species value.
Even shorter: how to communicate new/changed values between taxonomies.
Some chances to avoid writing my own module? thanks
Comment: Can you add a drupal version tag please?
Answer: Unfortunately you are probably stuck writing your own module. You need to implement hook_taxonomy_term_update and hook_taxonomy_term_insert.  In each you can check the item being updated and force a change on any associated terms in the other taxonomy.
The one thing to be careful of is an update spiral. Forcing an update on associated terms will then force an update of the original term, because it is now associated.  Because the changes in those two hooks are not committed to the db until the whole mess resolves it will lock up unless you put in a variable to keep it from spiraling.
For example:
if ($term->tid == args(2)) _update_related_terms($term);

should check the term being updated against the current page.  If they do not match it won't fire. (I haven't tested this snippet, so test thoroughly!)
Then in _update_related_terms
function _update_related_terms($term){
  $associated_terms = $term->associated_term_field;
  if (isset($associated_terms['und'][0]['tid']) && $associated_terms['und'][0]['tid'] != ''){
    foreach ($associated_terms['und'] as $key => $value){
      if (isset($value['tid']) && $value['tid'] != ''){
        //check the associated term here.  You could load it, or check the db, or all sort of things
      }
    }
  }
}

I know I am using und in this example, but it is off the cuff.  Again, not tested
Please note: this example is for d7.


Login at two wordpress blogs at once

Question: I'm stumbling into a little problem as I'm currently trying to programmatically log into two wordpress blogs at once. I have a custom login page and the sessions for both wordpress blogs have to be created. One blog works just fine, but as I have to include another wp-load.php it doesn't work for the second one... My code so far:
...
public static function blogLogin($mail, $password) {
        require __DIR__ . '/../blog/wp-load.php';

        $wpuser = get_user_by('email', $mail);
        if (!$wpuser) $wpuser = get_user_by('login', $mail);

        if (!empty($wpuser) && !empty($wpuser->ID)) {
            wp_set_auth_cookie($wpuser->ID, true);
            return true;
        } else {
            return false;
        }
}

public static function secondBlogLogin($mail, $password) {
        require __DIR__ . '/../secondblog/wp-load.php';

        $wpuser = get_user_by('email', $mail);
        if (!$wpuser) $wpuser = get_user_by('login', $mail);

        if (!empty($wpuser) && !empty($wpuser->ID)) {
            wp_set_auth_cookie($wpuser->ID, true);
            return true;
        } else {
            return false;
        }
}
...

And is being called by:
Class::blogLogin(...); Class::secondBlogLogin(...);
This seems not to work as the include is not only "sandboxed" inside the function but also available in the outside. Is there a ways to either kind off an inclusion or otherwise to achieve this login at both wordpress blogs in one script?
Comment: ok, try check here maybe it can point u to right direction http://wordpress.stackexchange.com/questions/131399/share-login-data-cookies-between-multiple-installations

I'm not tht in to wp
Comment: Not sure if this what you wanna achieve have a look here : https://infinitewp.com/
Comment: This seems to be only for adminstration logins, I am looking for a solution for all users (authors and users). One login form starts a main session + blog 1 and blog 2 sessions.
Comment: Thanks, this looks correct, but somehow isn't working either
Answer: Here programmatically log into two wordpress blogs at once,
Below code may fulfil your requirement.
It need two php file for enable cookies for two wordpress
Place below code into your first PHP file:
e.g. www/folder/first-blog-login.php
//Your form which contain custom login (email,password).

<?php
//afer submit form post login credential value into PHP code of first file.
if(isset($_POST) && isset($_POST['submit'])){
require("path of first wordpress root directory \wp-load.php");
if ( is_user_logged_in() ) {
    $user = wp_get_current_user();
} else {
    $creds = array();
    // Use the submited information to populate the user_login & user_password
    $creds['user_login']    = $_POST['username or email'];
    $creds['user_password'] = $_POST['password'];
    $creds['remember']      = true;
    $user                   = wp_signon( $creds, false );
    if ( is_wp_error( $user ) ) {
        echo $user->get_error_message();
    } else {
        wp_set_auth_cookie( $user->ID, true );
    }
    ?>

    <?php
}
}
?>

Place below code into your secound PHP file:
e.g. www/folder/secound-blog-login.php
<?php
  $user =  $_COOKIE['user'];
  $password =  $_COOKIE['password'];
  require("path of secound wordpress root directory\wp-load.php");
  if ( is_user_logged_in() ) {
    $user = wp_get_current_user();
} else {
    $creds= array();
    // Use the submited information to populate the user_login & user_password
    $creds['user_login']    = $user;
    $creds['user_password'] = $password;
    $creds['remember']      = true;
    $user                   = wp_signon( $creds, false );
    if ( is_wp_error( $user ) ) {
        echo $user->get_error_message();
    } else {
        wp_set_auth_cookie( $user->ID, true );
    }
}
//Your further code for execution.
?>

You can encode / decode login credential while sending to new window.
Hope it will help you!!!
Comment: Thanks for you answer, this is indeed working - and pretty similar to what I did as a workaround as well (I made a redirect with an auto submitting form - which is a bit more secure than storing the password unencrypted in a cookie) but as mentioned above I'm actually looking for a solution without a redirect...
Comment: Please check my another answer in which i have been using one file and after first login of wordpress i am calling ajax for another wordpress login during one execution.I am  posting another answer as different method.Hope it will help you out as well.
Answer: Below answer is for enable login of two word press during one execution from single custom login page.
//Your form which contain custom login (email,password).

<?php
//afer submit form post login credential value into PHP code of first file.
if(isset($_POST) && isset($_POST['submit'])){
require("path of first wordpress root directory \wp-load.php");
if ( is_user_logged_in() ) {
    $user = wp_get_current_user();
} else {
    $creds = array();
    // Use the submited information to populate the user_login & user_password
    $creds['user_login']    = $_POST['username or email'];
    $creds['user_password'] = $_POST['password'];
    $creds['remember']      = true;
    $user                   = wp_signon( $creds, false );
    if ( is_wp_error( $user ) ) {
        echo $user->get_error_message();
    } else {
        wp_set_auth_cookie( $user->ID, true );
    }
    ?>

    <?php
}
}

if(isset($_POST) && !empty($_POST)){
    $user =  $_POST['user'];
  $password =  $_POST['password'];
  require("path of secound wordpress root directory\wp-load.php");
  if ( is_user_logged_in() ) {
    $user = wp_get_current_user();
} else {
    $creds= array();
    // Use the submited information to populate the user_login & user_password
    $creds['user_login']    = $user;
    $creds['user_password'] = $password;
    $creds['remember']      = true;
    $user                   = wp_signon( $creds, false );
    if ( is_wp_error( $user ) ) {
        echo $user->get_error_message();
    } else {
        wp_set_auth_cookie( $user->ID, true );
    }
}
}
?>

Comment: Still not a PHP-only solution, I've also thought about an AJAX request, but you're right this is definitely working more comfortable as it doesn't have a redirect. And probably the only way to get this done properly. Thanks for your effort!

Login at two wordpress blogs at once


Sampling intercept and slope pairs from lm in R

Question: Let's say I have a model Y~X+trt, and by running lm and summary functions in R I get these results:
Call:
lm(formula = Y ~ X + trt)

Residuals:
     Min       1Q   Median       3Q      Max
-2.31706 -0.70884  0.09831  0.60996  2.46301

Coefficients:
                          Estimate Std. Error t value Pr(>|t|)
(Intercept)                 8.5782     0.6412  13.379  < 2e-16 ***
X                           2.1056     0.1542  13.658  < 2e-16 ***
trtB                       -1.8097     0.8234  -2.198 0.030597 *
trtC                       -3.3090     0.6395  -5.174 1.42e-06 ***
trtE                       -3.5157     0.5844  -6.016 4.00e-08 ***
trtF                       -2.2839     0.6647  -3.436 0.000904 ***
trtG                       -3.0587     0.6263  -4.883 4.63e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.9805 on 88 degrees of freedom
Multiple R-squared:  0.8232,    Adjusted R-squared:  0.8112
F-statistic: 68.31 on 6 and 88 DF,  p-value: < 2.2e-16

I suspect that the slope estimates and the intercept estimates are not independent, co-varing with one another. The question is what do I have to do in order to sampling intercept and slope pairs for each treatment group, such that they conform the model?
Any helps would be very much appreciated.
Comment: @Pakorn Welcome to the site! I think you may have a misunderstanding of what a confidence bound is. The confidence bound is generally a confidence bound on the expected value. A 95% confidence bound on the mean does not tell you that approximately 95% of your single observations will be within the confidence bound.
Comment: Could you precise what kind of "conforming with the model" do you expect ? Maybe the R function `simulate` performs what you are looking for (see `?simulate`).
Comment: Thank you @StéphaneLaurent. What I meant by that is something along this line. Say for group A, if I were to (and I have tried this) randomly pair the slope ~ N(2.1056,0.1542), and the intercept ~ N(8.5782,0.6412), the simulated equations won't always stay within the estimated confidence bound given by the model. This is what I meant by not conforming the model. I just want to sample slopes and intercepts such that the simulated equations always stay within the confidence bound given by the model. Cheers
Comment: @TrynnaDoStat Thank you for your comment and the answer below. They are both extremely helpful. Actually, indeed as you said, the confidence bound of the 'expected value' isn't the same as (much smaller than) the confidence bound of the 'data'. So if you don't mind. May I ask you, how to simulate the equations from the model so that they capture the confidence interval of the data, instead of the expected values? (I try to follow your comment below. It indeed under estimated the confidence bound of the data.) Cheers.
Answer: require(mvtnrom) #needed for rmvnorm function

model=lm(y~x)
sigma.sq=vcov(model)
mu=model$coef

rmvnorm(n,mean=mu,sigma=sigma.sq)

This will simulate n values from the multivariate normal sampling distribution of your coefficient estimates. It will incorporate covariance between coefficients.
Comment: Oh, this is exactly what I am looking for. Thank you so much, sir (+1)
Comment: +1, the same code should work w/ a factor included. You may want to add `trt` to the `lm()` call to make the parallel easier for the OP to see.
Comment: @Pakorn, unfortunately, you can't upvote until your reputation is 15. If this has resolved your question, you can *accept* it by clicking the check mark to its left below the vote total.


Condição no VBA se Data informada no TextBox for Maior ou Menor

Question: Estou com uma macro para caso a Data que o usuário inseriu no TextBox, for menor que a data de uma célula de determinada linha, eu farei uma alteração na informação de uma coluna desta linha.

Sub test()

Dim data As String
Dim ultima As Long
Dim split As Range

data = TextBox4.Value
data_i = Format(data, "dd/mm/yy")

ultima = Range("B" & Rows.Count).End(xlUp).Row

Set split = Range("B7:B" & ultima)

For Each cell In split

    If cell < data_i Then

        cell.Offset(0, 4) = "Data Menor"

    End If

Next cell

End Sub

Eu sei que o VBA lê em formato americano. Teria que transformar as datas da coluna B em "mm/dd/yy"  para fazer a comparação com o que o usurário escreveu no TextBox?
Qual seria a melhor maneira de resolver isso, por favor?
Agradeço desde já! Abraços!
Answer: Mesmo se seu Excel estiver configurado em inglês, não é preciso mudar a formatação da data na sua planilha. Eu já fiz comparações datas com padrão "brasileiro" em Excel configurado em inglês americano e funcionou.
Eu não sei como a planilha funciona como um todo, porém eu queria sugerir que:

As variáveis de data fossem declaradas como "As Date"
Ao invés de usar "TextBox" dentro de um formulário, eu usaria o método "inputbox", desse jeito:

data = InputBox("Qual a data que você gostaria de inserir?")

Assim, dá para manipular datas usando as devidas propriedades, diferentemente do que ocorre com Strings e comparar as datas no formato dia/mês/ano.
Além disso, o "cell.Offset(0, 4) = "Data Menor" está inserindo o texto "Data Menor" em cima dos valores da coluna "Preço Unitário". Eu não sei se onde esse texto deveria ser posicionado, mas creio que terá que mudar o índice usado para a coluna.
Espero que ajude.


How to construct the "lobed Hopf tori"?

Question: I've done the following construction. I expected to get the Clifford torus or another "Hopf torus", such as the ones we can see here: lobed Hopf tori.
Here is my construction.
First I take the "inverse" Hopf map:
$$
H^{-1}(q,t) = \frac{1}{\sqrt{2(1+q_1)}}
\begin{pmatrix}
-(1+q_1)\sin t \\
(1+q_1) \cos t \\
q_2 \cos t + q_3 \sin t \\
-q_2 \sin t + q_3 \cos t
\end{pmatrix}, q \in S^2, t \in \mathbb{R}.
$$
I generate all the great circles of $S^2$:
$$
C_{\theta,\phi} = \begin{pmatrix}
\cos \theta \sin \phi \\
\sin \theta \sin \phi \\
\cos \phi
\end{pmatrix}.
$$
Then I calculate the circles of $S^3$ obtained by the inverse Hopf map as follows:
$$
[0, 2\pi] \ni t \mapsto H^{-1}(C_{\theta, \phi}, t)
$$
Finally I apply the stereographic projection to these circles in $\mathbb{R}^4$ in order to map them to $\mathbb{R}^3$. And this is the picture I obtain:

Here is the same object but drawn in a different way:

Its not ugly but this does not look like a torus. And I've never seen such a picture elsewhere. What is it?
More importantly, I would like to know how to obtain the lobed Hopf tori (lobed Hopf tori). Is the way to get them close to my construction of am I totally in a wrong way ? In case I'm totally in a wrong way I would appreciate a couple of hints.
Comment: See my blog for an answer : [1/3](https://laustep.github.io/stlahblog/posts/HopfTorus_1over3.html) [2/3](https://laustep.github.io/stlahblog/posts/HopfTorus_2over3.html) [3/3](https://laustep.github.io/stlahblog/posts/HopfTorus_3over3.html). I think there was an error in my $H^{-1}$ formula.
Answer: I absolutely don't remember how I got the strange shape in my question...
Well, here is how to get a Hopf torus.
The preimage of a point $p=(p_x,p_y,p_z)$ on the unit sphere $S^2$ by the Hopf map is the circle on $S^3$ with parameterization:
$$
\begin{array}{ccc}
\mathcal{C}_p \colon & (0,2\pi[ & \longrightarrow & S^3 \\
 & \phi & \longmapsto & \mathcal{C}_p(\phi)
\end{array}
$$
where
$$
\mathcal{C}_p(\phi) =
\frac{1}{\sqrt{2(1+p_z)}}
\begin{pmatrix}
(1+p_z) \cos(\phi) \\
p_x \sin(\phi) - p_y \cos(\phi) \\
p_x \cos(\phi) + p_y \sin(\phi) \\
(1+p_z) \sin(\phi)
\end{pmatrix}.
$$
Now consider a spherical curve. That is, let $\Gamma$ be a function mapping an interval $I \subset \mathbb{R}$ to the unit sphere $S^2$.
Then the Hopf cylinder corresponding to $\Gamma$ has parameterization
$$
\begin{array}{ccc}
H_\Gamma \colon & I \times (0,2\pi[ & \longrightarrow & S^3 \\
 & (t, \phi) & \longmapsto & \mathcal{C}_{\Gamma(t)}(\phi)
\end{array}.
$$
When the spherical curve is closed, its corresponding Hopf cylinder is called
a Hopf torus. Then we can get a beautiful 3D surface by stereographic projection. A "lobed Hopf torus" as the ones shown here is obtained by taking for a sinusoidal-like spherical curve, and the number of lobes corresponds to the number of sinusoidal waves.
For example, consider the tennis ball curve, given for a real constant $A$ and an integer constant $n$ by:
$$
\Gamma(t) =
\begin{pmatrix}
\sin\bigl(\pi/2 - (\pi/2 - A) \cos(nt)\bigr)
\cos\bigl(t + A \sin(2nt)\bigr) \\
\sin\bigl(\pi/2 - (\pi/2 - A) \cos(nt)\bigr)
\sin\bigl(t + A \sin(2nt)\bigr) \\
\cos\bigl(\pi/2 - (\pi/2 - A) \cos(nt)\bigr)
\end{pmatrix}, \quad t \in (0,2\pi[.
$$
Then $\Gamma$ is $(2\pi/n)$-periodic and $n$ corresponds to the number of lobes of the Hopf torus. Here is the result:

Another example: take the closed curve $\Gamma \colon [0,2\pi] \to S^2$ defined by
$$
\begin{cases}
\Gamma_x \colon t \mapsto \sin\bigl(h\cos(nt)\bigr) \\
\Gamma_y \colon t \mapsto \cos(t)\cos\bigl(h\cos(nt)\bigr) \\
\Gamma_z \colon t \mapsto \sin(t)\cos\bigl(h\cos(nt)\bigr)
\end{cases}
$$
where $h$ is a real number and $n$ is an integer, corresponding to the number of lobes as before.

How to construct the "lobed Hopf tori"?


Using R2WinBUGS, how to extract information from each chain?

Question: I am new to Gibbs Sampling, and have been using WinBUGS, but I find that it is not well-suited towards storing/presenting results, so I have been calling it from R using the R2WinBUGS package.  The data is apparently stored as a "bug" class.
I converted it to coda to run diagnostics, and it displays each of the chains, but I am confused as to the $ extension for each individual chain.  I cannot find any good documentation for the "coda" class (the cran instructions are not helpful).
My code is below:
> bugs.sim <- bugs(data, inits, parameter, "gl.bug", n.chains = 5,
                   codaPkg = TRUE, DIC = FALSE, n.iter = 5000)
> codaobject <- read.bugs(bugs.sim)

As you can see, I have 5 chains, and I would like to take the mean and standard deviation of each.  How do I go about doing this?  I can use the codaobject to take the Geweke diagnostic of each chain, it displays each chain as [[i]] ($i=1,\dots,5$).
Thanks in advance.  And any references to a detailed documentation for R2Winbugs, would also be greatly appreciated.
Comment: You mean something like http://www.people.fas.harvard.edu/~plam/teaching/methods/convergence/convergence_print.pdf ?
Comment: I looked through that exact link last night actually, which was what prompted me to convert my bugs output to CODA, but from what I can see, they aren't calling WinBUGS, they are using a built in function in R's MCMC package.
Comment: You can also use my function read.winbugs(): ["Storing WinBUGS output"](ftp://ftp.cirad.fr/pub/group-r/groupe-r/Fiches/WinBUGS_reading_v3.pdf)
Answer: The object returned by read.bugs is an object of S3 class mcmc.list.
You can use the double brackets [[ to access the separate chains, i.e. the different mcmc-objects that make up the larger mcmc.list object, which really is simply a list of mcmc-objects that inherits some information about thinning and chain length from its components.
More to the point, s.th. like lapply(codaobject, function(x){ colMeans(x) }) should return the posterior means for each parameter in each chain and lapply(codaobject, function(x){ apply(x, 2, sd) }) should give chain- and parameter-specific posterior sd's, since each chain is essentially just a numeric matrix with rows corresponding to the (saved) iterations and columns corresponding to the different params.
EDIT:
I think Gelman/Hill's "Bayesian Data Analysis" contains some worked examples using R2WinBUGS.
Comment: Thanks! That is just what I need.  I have "Bayesian Data Analysis" and I will take a closer look for the worked examples.
Comment: (+1) E.g. [Example of computation in R and Bugs](http://www.stat.columbia.edu/~gelman/bugsR/software.pdf) (Online Appendix C of BDA).
Answer: The contents of your chains are stored in three different formats.  Take a look at
bugs.sim$sims.array
bugs.sim$sims.list
bugs.sim$sims.matrix

and read the Value section of ?bugs.


Union of a convex domain with closure of a component is open?

Question: Let $\Omega$ be a convex open subset of $\mathbb{R}^n,\ n\geq 2,$ and let $U$ be a connected component of $(\overline{\Omega})^c.$ Now let $V:=\Omega\cup \overline{U},$ can we prove $V$ is open?
If not, what about the extra assumptions that $\Omega$ is bounded and $U$ is one of the bounded components?
If $\Omega$ is bounded and convex, the conclusion is true. In fact, we know
$\overline{\Omega}$ is bounded and convex, and then $(\overline{\Omega})^c$ is connected. Thus, we have $U=(\overline{\Omega})^c,$ and then
$$\overline{U}=\overline{(\overline{\Omega})^c}=((\overline{\Omega})^\circ)^c=\Omega^c.$$
Therfore, we have $V=\mathbb{R}^n$ is open. The claim is false, I have made a fatal mistake. $(\overline{\Omega})^\circ\neq \Omega$ in general.
However, I have no idea for the general case.
Aschepler have answered the case where $\Omega$ is not connected.
From which, we can easily get a counterexample where $\Omega$ is bounded connected.
Comment: $\bar U$ denotes the closure in $\mathbb R^n$?
Comment: Yes, it denotes the closure in $\mathbb{R}^n$.
Comment: Did you check any examples to verify the truth of the statement that you want to prove?
Comment: @LeeMosher  If $\Omega$ is convex, I have no example to show that $(\overline{\Omega})^c$ admits a bounded component.
Answer: No. As a counterexample, consider in $\mathbb{R}^2$
$$ \Omega = \left\{(x,y) \in \mathbb{R}^2 : |x| < |y| \right\} $$
The complement of the closure is
$$ (\overline{\Omega})^c = \left\{ (x,y) \in \mathbb{R}^2: |x| > |y| \right\} $$
$\overline{\Omega}$ contains the $x$-axis $(\mathbb{R} \times \{0\})$, and $(\overline{\Omega})^c$ has connected components
$$ \begin{align*}
U_1 &= \left\{ (x,y) \in \mathbb{R}^2 : y > |x| \right\} \\
U_2 &= \left\{ (x,y) \in \mathbb{R}^2 : y < -|x| \right\}
\end{align*} $$
$(0,0) \in \overline{U}_1$ and $(0,0) \in \overline{U}_2$. Every open neighborhood of $(0,0)$ contains some points in $U_1$ and some points in $U_2$. So no matter which component $U$ is, $(0,0) \in \Omega \cup \overline{U}$ but no open ball containing $(0,0)$ is a subset of $\Omega \cup \overline{U}$, so $\Omega \cup \overline{U}$ is not open.
This example is not difficult to extend to the general $\mathbb{R}^n$, cases where $\Omega$ is bounded, cases where $\Omega^c$ is bounded, and cases where $\Omega \cup \overline{U}$ is bounded.
Comment: Thanks for your patient reply.
Comment: Can you give me an example where $\Omega$ is convex?
Comment: No - intuitively, I think the conjecture is true when $\Omega$ is convex, since it can't have any of these "pinch points". I don't have a solid proof right now either, though.
Comment: I think in this case,  there will exist no bounded components.