How to redirect to a certain screen when opening a dynamic link?

Question: I'm developing an app that can receive Firebase's Dynamic Link. What I want is when a user click a Dynamic Link, the app redirects it to a certain UIViewController. So I have a code that looks like this on my AppDelegate.swift file:
@available(iOS 9.0, *)
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
        //return GIDSignIn.sharedInstance().handle(url)
        return application(app, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: "")
    }

    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        // On progress
        if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
            print("open url = open dynamic link activity")
            print("url = \(dynamicLink)")
            let destinationVC = UIStoryboard(name: "DynamicLink", bundle: nil).instantiateViewController(withIdentifier: "DynamicLinkView") as? DynamicLinkVC
            self.window?.rootViewController?.navigationController?.pushViewController(destinationVC!, animated: true)
        } else {
            print("open url = none")
        }
        return GIDSignIn.sharedInstance().handle(url)
    }

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // On progress
        let handled = DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
            print("dynamic link = \(dynamiclink)")
        }

        if handled {
            let destinationVC = UIStoryboard(name: "DynamicLink", bundle: nil).instantiateViewController(withIdentifier: "DynamicLinkView") as? DynamicLinkVC
            self.window?.rootViewController?.navigationController?.pushViewController(destinationVC!, animated: true)
        }

        return handled
    }

So what happened when I click the link the app opens up immediately but it doesn't redirects to the desired UIViewController that I wanted (in this case destinationVC). It directly went to the login page as usual. But in the debug area, the link appears like this =

dynamic link = Optional(https://xxxx], match type: unique, minimumAppVersion: N/A, match message: (null)>)

Unfortunately I couldn't record the log messages when the app is not built by Xcode.
I'm very confused by this, what's wrong with my code? I'm new to iOS development so I'm not sure where did I do wrong. If you need more information feel free to ask and I will provide it to you. Any help would be appreciated. Thank you.
Answer: If your rest-of-code is working fine, and you are just facing issue while navigating to another view controller, then this solution will work for you.
If you want to open particular ViewController, while clicking on dynamic link, then update your code written within restorationHandler, below updated code will help you to redirect/navigate to particular View Controller
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // On progress
        let handled = DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
            print("dynamic link = \(dynamiclink)")
        }

    if handled {

             let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "DynamicLink", bundle: nil)
             if let initialViewController : UIViewController = (mainStoryboardIpad.instantiateViewController(withIdentifier: "DynamicLinkView") as? DynamicLinkVC) {
                    self.window = UIWindow(frame: UIScreen.main.bounds)
                    self.window?.rootViewController = initialViewController
                    self.window?.makeKeyAndVisible()
               }

        return handled
    }

Hope this will resolve your issue.
Comment: Hope this answer help you. Happy Coding :-)


Popping from stack base

Question: I'm making an operating system for fun, whilist learning more Assembly on the way.
I learned about pushing and popping, as I understand, pop takes the value that is on top of any other value on the stack, so it gets the last pushed one. But I wonder, can we actually directly pop the value at the stack base (i.e. the first pushed one)?
Like:
push 'A'
push 'B'
push 'C'

pop bx ; Gets C

Instead of C, I want to get A as an example.
(I'm in 16-bit mode, and the assembler is NASM, specified in the tags as well.)
Comment: In truth, the stack is fictitious, in the sense that the elements of the stack don't get relocated every time you `pop`. Instead, the CPU does something much easier that gets the same end result: it uses what's called a "stack pointer" which references whatever the topmost item is (or on some other architectures the first "free" slot). Every time you `push` the CPU subtracts 2 from `sp` and every time you `pop` the CPU adds 2.
Answer: In 16-bit mode, there's no sp relative addressing mode, but you can copy the value in sp into, say, bp, and use bp relative addressing to access A's location.  This won't pop A, of course, but you can read or write A.
This is one reason why x86 functions often have mov bp,sp in their prologue (function startup code).  Once bp is set up to refer to its stack, a function can access the parameters that its caller pushed using bp relative addressing (bp + displacement).
Answer: Try to write down the layout of the stack in memory.  You'll see that "popping" any element in the middle of the stack would entail shuffling a lot stack elements around in memory.  Processors don't have support for that.  You can however load any element on the stack into a register at any time without popping it (i.e. it'll still be on the stack afterwards).
To do so, first copy the stack pointer into some register that can be used for addressing memory (bp is the canonical choice), then access the stack from that.
mov bp, sp      ; make the stack accessible
mov bx, [bp+4]  ; load stack element A into bx

Usually, bp is set up as a part of establishing a stack frame for the current function, so you have it always available for accessing the stack.  You can also use the registers bx, si, and di, but keep in mind that a ss segment override is needed in that case (it's implicit for bp).
Now, why do we have to add 4 to get item A?  Recall that the stack grows towards lower addresses in memory (i.e. with each push, sp is decreased) and each stack slot occupies 2 bytes of memory in 16 bit mode.  So assuming sp = 1000h after your sequence of pushes, we have the following memory layout:
1004h  A
1002h  B
1000h  C  <-- SP

so by simple arithmetic, SP + 4 points at stack slot A and SP + 2 at stack slot B.
Comment: Thanks for the great explanation, I'm not an Assembly expert, you helped me a lot.
Comment: How can I get 'B' in this case? And why we add 4? Adding 8 doesn't work to get 'B', so why 4 for 'A'?
Comment: @triangleBoi added a bit to the answer about that.
Comment: If you don't care about the other letters and just want 'A' you can do `pop bx pop bx pop bx`

Popping from stack base


Can I safely use the same UUID on independent sites?

Question: I'm trying to create a site building workflow which uses some sort of blueprint site, providing a shared, tested set of the Drupal core, modules, content types, paragraph types, a base theme, etc. for all our client work.
Projects/websites shall initially start with the same configuration as the blueprint site, but later on those projects are otherwise completely independent (different clients, different themes, modules will be added/removed, content types will change, ...)
From what I've read this should be possible with config export/import and by manipulating the UUID of the sites.
The question is:
Is it a problem when ALL our projects share the same UUID? In the long run I'm going to end up with about 30-50 projects, each project will a dev and a prod environment, so in total there will be ~ 60-100 installations with the same UUID.
Updating the core and shared modules shall also be done and tested on the central blueprint site, and then pulled and merged by all projects.
Answer: This is a perfect use case for Features. You can export shared sets of functionality and configuration without worrying about UUID stripping or collision.

The features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.
Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module. A feature module is like any other Drupal
  module except that it contains additional information in its info file
  so that configuration can be checked, updated, or reverted
  programmatically.
Examples of features might be:

A blog
A pressroom
An image gallery
Comment: I thought the primary use case for features is to export/import smaller subsets of configuration, while core's config-management should be used for the complete config set.
I intented to use the features module too, but only to reuse smaller, only infrequently used subsets. Is features really the right tool to export the _complete_ configuration?
Comment: The core CM is meant for the _same_ site, not for sharing across different sites. You can use Features to extract some or all config from a site and package it into modules or even an installation profile.
Comment: You can install Features and configure bundles - it does have a "Core" package which sounds like what you are after.
Answer: Following Kevin's hint using the Features module I've done some testing, and this is what I've got so far:
Blueprint site:

Create a Drupal composer project
composer require all shared modules
drush site-install minimal
Set up my desireded configuration
In features module, create a blueprint feature containing every single component and export it
Commit to git
(Later on: update core and shared modules, after successful test push to git again; repeat)

Client project spawning:

Init a new repository, add blueprint as additional remote and pull from blueprint
composer install
drush site-install minimal
drush en blueprint_theme
drush en blueprint_module
git push to project's own origin remote
(Later on: pull core and shared module updates from blueprint repository, but do not import config)

Some things I've learned so far:

Features exports your config as a custom module, you don't even need features to import the blueprint config into the client project, you simply enable the module.
The theme used on your blueprint site must exist and must be activated before enabling the blueprint module on the client project. (I guess this is coming from blocks being included in config)
All modules have to exist in your client project directory before activating the blueprint module. They don't need to be enabled, but Features can't download missing modules.
Features seems to merge & override the existing client project configuration, but it does not remove additional configuration existing only on client. (e.g. it does not delete additional content types from the client project. This behavior differs from Drupal core configuration management.)
Uninstalling the blueprint module has no effect at all, it will not revert your configuration.

It is neither perfect nor extensively tested so far, but it seems to be a much cleaner solution than messing around with UUIDs.


Universal property of quotient group to get epimorphism

Question: I know there are already answers to the question of the universal property of quotient groups. For example here: Universal property of quotient group.
My question is now: If I have the homomorphism: $\phi: G \to G'$ and let H be $H\subset ker(\phi)$. Moreover I have the canonical projection $\pi: G \to G/H$. Due to the univeraly property of quotient groups there exists a unique homomorphism: $\bar{\phi}: G/H \to G'$.
Can I now say that: I know that $\pi$ is surjective. The homormophism $\phi$ is surjective iff $\bar{\phi}$ is surjective?
Answer: Yes. In fact, this has nothing to do with group theory. If you have a surjective map $f\colon A\longrightarrow B$ and you have a map $g\colon B\longrightarrow C$, then $g$ is surjective if and only if $g\circ f$ is surjective.
Answer: In the situation displayed in the diagram below we have that $\varphi$ is surjective if and only if $\varphi'$ is surjective.

If $\varphi'$ is surjective, then $\varphi'\circ\pi$ is surjective because composition of surjective functions.
Conversely, if $\varphi$ is surjective, then $\varphi'$ is surjective as well.
This doesn't depends on the surjectivity of $\pi$.
For if $y'\in G'$ then there exists $x\in G$ such that $y'=\varphi(x)$, hence $y=(\varphi'\circ\pi)(x)\in\operatorname{Im}\varphi'$.


Let f be increasing and bounded above. Show that the limit of f when x tends to infinity exists as a real number.

Question: I tried considering the Mean Value Theorem but haven't gotten far.
How could I prove that the limit exists as a real number?
Answer: Consider the sequence $f(n)$. This is an increasing, bounded sequence, so it has a limit $L$.
For any $\epsilon>0$, there exists an $N$ s.t. for all $n\geq N$, $|f(n)-L|<\epsilon$. Moreover, since $f(n)$ is increasing and $L\geq f(n)$ then $|f(x)-L|<\epsilon$ for any $x>N$.
Answer: The trick is in the fact that an increasing function has always limit in his domain. Then $\exists lim_{x \rightarrow \infty} f(x) $. Being $f$ bounded this limit can't be infinite. Then it's real number.


Dimension of set of alternating n-linear functions

Question: I need please revision of my reasoning for this problem:
"Let $S$ be the set of $n \times n$ matrices over a field $F$. Let $V$ be the vector space of all functions from  $S$ into $F$. Let $W$ be the set of alternating $n$-linear functions on $S$.  What is the dimension of $W$?"

Now, I  considered the annihilator of $W$, that is, the set of all $n \times n$ matrices such that 2 rows in them are equal. Let $W^\circ$ be that set.
The dimension values would be then related by $$ \dim \,W + \dim \,W^\circ = \dim \,V $$ and then I would be able to find the dimension of $W$. But I found very complicated to find the dimension of $W^\circ$. I am not sure if I am thinking in the right direction. Any hint would be appreciated!
Comment: Also from my understanding of the way the question is written, you're considering multilinear functions on $S$ i.e. of multiple matrices. Yet your approach to the problem makes it seem like the functions operate on multiple columns/rows of one matrix. Which one do you mean?
Comment: @isccha89 That's right! They're al multiples of the unique determinant function so the dimension of that space would be 1.
Comment: Alas, this won't work: what you call $W^\circ$ is not a vector subspace, and the rank-nullity formula only holds for linear maps, not multilinear maps.
Comment: Hmmm I see. I am supposed to solve this by using linear transforms theory and determinant functions. Do you have an idea of how to proceed in this case? thanks in advance
Comment: You can identify $S$ with $F^{n^2}$ right? There would then be an isomorphism between the space of alternating functions on $S$ and alternating functions on $F^{n^2}$. Do you know the dimension of alternating n-linear functions on $F^n$?
Comment: @Osama Thanks for the help. Yes, I mean functions that operate on multiple rows of one matrix. Based on the chapter I found this problem, I guess that if  $D \in W$ and $D(I) = 1$ too then they are all determinant functions.
Answer: Let $D$ and $D'$ be two arbitrary alternating $n$-linear functions from $S$ to $F$.
Now, $D(A)=(\det A)D(I)$ and $D'(A)=(\det A)D'(I)$ where $I$ is the $n\times n$ identity matrix.
Then dividing them we can see $D'(A)=C\times D(A)$ where $C$ is a constant.
So $W$ has dimension $1$.


State the domain of each composite function?

Question: So we started a new section in precal today and I'm still trying to get the hang of it. I have a problem asking for:

For the given functions $f$ and $g$ find:
(a) $f\circ{g}$
(b) $g\circ{f}$
(c) $f\circ{f}$
(d) $g\circ{g}$
$f(x)= x + 1$ and $g(x)=x^2 - 4$

Would the domains be the following?
(a) $g(g(1))=\mathbb{R}$
(b) $f(f(1))=\mathbb{R}$
(c) $f(f(1))=\mathbb{R}$
(d) $g(g(1))=\mathbb{R}$
I highly doubt that's right. :/
Comment: The title of the question and the body are different. Do you want to know the domains of the functions, or do you want to know what the actual functions are?
Answer: a) $f\circ{g}=x^2-3$
b)  $g\circ{f}=(x+1)^2-4$
c) $f\circ{f}=x+2$
d)  $g\circ{g}=(x^2-4)^2-4$
The second part doenst make sense because they are not functions, but numbers!
Comment: As I mentioned in my comment above, there is contradictory information about what question Vernard actually wanted to ask - in the title, he asking about the domains of the functions (which of course are sets), but that is not what the actual question he referenced asks about.
Comment: yes, but you wrote it when I was writing the answer so I couldn't see before posting it!


Android App Intent Filter sometimes not working

Question: For a project I have encountered a very strange issue:
Deeplinks have been working very well for the last year, but recently (since the beginning of January-2019) we have been getting complaints from our users that deeplinks have stopped working (some say 9 out of 10 time).
We have not changed any of this code and have great difficulty reproducing this issue.
Even stranger, in the sparse times that we do encounter the issue ourselves, the android OS does not even show our app as an option through the 'open with'-dialog. This suggest to us that the OS sometimes forgets that the app has intent-filters registered in its Manifest.
Restarting the app appears to fix this and deeplinks start working again.
The app also seems to work every time we do a new build from Android Studio, which makes it very hard to reproduce.
Our manifest has a specific activity that handles deeplinks:
<activity
    android:name="com.company.DeepLinkActivity"
    android:noHistory="true"
    android:launchMode="singleTask">
    <intent-filter>
        <action   android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data
            android:host="ideal-payment"
            android:scheme="com.company.ideal" />
        <data
            android:host="ideal-payment"
            android:scheme="com-company-ideal" />

    </intent-filter>

    <intent-filter android:autoVerify="true">
        <action   android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data
            android:host="${appLinkIdealHost}"
            android:pathPrefix="/ideal-betaling/landingpage"
            android:scheme="https" />
    </intent-filter>

    <intent-filter android:autoVerify="true">
        ...
    </intent-filter>

    <intent-filter android:autoVerify="true">
        ...
    </intent-filter>
</activity>

We thought it might have something to do with the autoVerify not being accessible, but then the OS should show the 'open with'-dialog, which does not happen when the issue surfaces.
Is there someone that has encountered a similar issue? Any help or suggestions would be greatly appreciated.
Comment: Can you specify the OS version on which the intent filters do not work?
Comment: also, manufacturer/device. could be device-specific.
Comment: Does it happen after a manual force-stop? Or when the application gets ranked in the "Rare" App Standby bucket?
Comment: We see this happen after a device has been brought to the background (for some time). When the app is started again the problem seems to go away.
The range of devices and OS versions that we get this sighting on is quite wide, for example: Huawei P10(8.0), Galaxy A5(8.0), Oneplus 6(9.0), Mate 10Pro(9.0), Mate 8(7.0), P9 lite(6.0.1), Honor 9(8.0), P20 Lite(8.0), OnePlus 2(6.0), Vivo1723(8.1)
Answer: When app is stopped for example with an exception or when user have force stopped it from settings or in some devices when user removes app from history (or from tasks) the app will be force stopped automatically (which is not a good choice from manufacturer) when app is in stopped state its manifest intentFilter will not be used (when app is first installed and never opened also it is in this phase)

While in stopped state, the application will not run for any reason,
  except by a manual launch of an activity, or an explicit intent that
  addresses an activity ,service or broadcast.

https://riptutorial.com/android/example/30592/android-stopped-state

Most of Android versions you mentioned was 8 or grater thus below quotation also may be useful but this is for services and broadcast receivers.

Whenever an app runs in the background, it consumes some of the
  device's limited resources, like RAM. This can result in an impaired
  user experience, especially if the user is using a resource-intensive
  app, such as playing a game or watching video. To improve the user
  experience, Android 8.0 (API level 26) imposes limitations on what
  apps can do while running in the background.

https://developer.android.com/about/versions/oreo/background
Answer: Can you specify the version of android OS ? because android:autoVerify="true" works only on Android 6.0 and higher to cause the system to attempt to verify all hosts associated with the URLs in any of your app's intent filters.
Comment: We see this happen after a device has been brought to the background (for some time). When the app is started again the problem seems to go away. The range of devices and OS versions that we get this sighting on is quite wide, for example: Huawei P10(8.0), Galaxy A5(8.0), Oneplus 6(9.0), Mate 10Pro(9.0), Mate 8(7.0), P9 lite(6.0.1), Honor 9(8.0), P20 Lite(8.0), OnePlus 2(6.0), Vivo1723(8.1)
Answer: these two entries also look strange to me, not sure what you are trying to accomplish there:
<data android:host="ideal-payment" android:scheme="com.company.ideal" />
<data android:host="ideal-payment" android:scheme="com-company-ideal" />

this is far from being ideal, because those hosts and schemes are both invalid, see data-element.
I would assume, based upon all the code which obviously had been withheld... that other intent-filter might also feature duplicate data elements, which would need to be moved into separate intent-filter, of which an activity element permits several. set android:autoVerify="true" on all these intent-filter and then closely review the logcat after the package installation.
Answer: Great news, we were able to find a solution.
The issue originated from an older version of the Chrome browser.
https://bugs.chromium.org/p/chromium/issues/detail?id=935864
After the release of version 73.0.3683.90 a few days ago, the issue has gone away.
Thanks Google :D


Using variable value as column name in data.frame or cbind

Question: Is there a way in R to have a variable evaluated as a column name when creating a data frame (or in similar situations like using cbind)?
For example
a <- "mycol";
d <- data.frame(a=1:10)

this creates a data frame with one column named a rather than mycol.
This is less important than the case that would help me remove quite a few lines from my code:
a <- "mycol";
d <- cbind(some.dataframe, a=some.sequence)

My current code has the tortured:
names(d)[dim(d)[2]] <- a;

which is aesthetically barftastic.
Comment: can't you do `colnames(d)[2] <- a` or even `names(d)[2] <- a` but I find the explicit former to be safer.
Answer: > d <- setNames( data.frame(a=1:10), a)
> d
   mycol
1      1
2      2
3      3
4      4
5      5
6      6
7      7
8      8
9      9
10    10

Answer: Is structure(data.frame(1:10),names="mycol") aesthetically pleasing to you? :-)
Comment: I'm one of the upvoters, but I was curious to see if your and my answer would be identical, and see that they are using `dput` and `identical` as tests.
Answer: just use colnames after creation.
eg
a <- "mycolA"
b<- "mycolB"
d <- data.frame(a=1:10, b=rnorm(1:10))
colnames(d)<-c(a,b)
d
mycolA     mycolB
 1 -1.5873866
 2 -0.4195322
 3 -0.9511075
 4  0.2259858
 5 -0.6619433
 6  3.4669774
 7  0.4087541
 8 -0.3891437
 9 -1.6163175
 10  0.7642909

Answer: Simple solution:
df <- data.frame(1:5, letters[1:5])
logics <- c(T,T,F,F,T)
cities <- c("Warsaw","London","Paris","NY","Tokio")
m <- as.matrix(logics)
m2 <- as.matrix(cities)
name <- "MyCities"
colnames(m) <- deparse(substitute(logics))
colnames(m2) <- eval(name)
df<-cbind(df,m)
cbind(df,m2)

X1.5 letters.1.5. logics MyCities
1            a   TRUE   Warsaw
2            b   TRUE   London
3            c  FALSE    Paris
4            d  FALSE       NY
5            e   TRUE    Tokio


Meaning of sticky pitch

Question: What is the meaning of sticky pitch in cricket? Does it help the bowler or the batsmen? If it helps the bowler than which type of bowler? And where most of the sticky pitches are found in which part of the world?
Answer: A sticky pitch or wicket is just a term for a pitch that has usually had some rain on it and so is damp and then dries out. This causes batting conditions that are tough because the dampness causes unpredictable bounce. Luckily, we don't get sticky wickets in modern cricket anymore with the advent of covers being necessary today.

Meaning of sticky pitch


How to ignore/exclude some files/directory from linting in angular cli

Question: Similar to this question
I am running the following command to linting my angular2 typeScript code.
ng lint

It is proving all the linting error nicely.
But I want my vendor folder (let say "src/app/quote/services/generated/**/*") should not get included at the time of lining.
I know this can be done with tslint command as follows (Reference Here)
tslint \"src/**/*.ts\" -e \"**/__test__/**\"

But in angular cli what will be the parameter? How to exclude some files from tslint?
Note: My Angular Cli version is : @angular/cli: 1.0.0-rc.0
Answer: From Angular6+, .angular-cli.json has been replaced by angular.json, but you can still add the exclude path in its lint part.
"lint": {
      "builder": "@angular-devkit/build-angular:tslint",
      "options": {
        "tsConfig": [
          "src/tsconfig.app.json",
          "src/tsconfig.spec.json"
        ],
        "exclude": [
          "**/node_modules/**"      // excluded directories
        ]
      }
    }

According to the angular-cli issue#5063, you can add the exclude path in .angular-cli.json like this:
"lint": [
{
  "project": "src/tsconfig.app.json",
  "exclude": "**/node_modules/**/*"   // the node_modules for example
}]

Comment: Actually, I found that the solution for me was to edit the `exclude` property under `./src/tsconfig.app.json`, instead of `.angular-cli.json`.
Answer: Figured out it HAS to be a blob pattern..
If you want multiple files/directories just use an array in your .angular-cli.json
"exclude": [
 "**/*whatever.pipe.ts",
 "**/*whatever_else.component.ts"
]

Comment: Actually, I found that the solution for me was to edit the `exclude` property under `./src/app/tsconfig.app.json`, instead of `.angular-cli.json`.
Answer: Recent answer (10/2022 - eslint v8) :
Quote from eslint official documentation :

You can tell ESLint to ignore specific files and directories using
ignorePatterns in your config files. ignorePatterns patterns follow
the same rules as .eslintignore. Please see the .eslintignore file
documentation to learn more.

If you have an .eslintrc.json config file, you can set ignorePatterns option as following :
{
    "ignorePatterns": ["your_file.js", "/your_dir/*.js"],
    "rules": {
        //...
    }
}

If you don't have the .eslintrc.json file, check the link below to find a suitable solution for your setup.
Ressources & useful links you might want to check for more information
https://eslint.org/docs/latest/user-guide/configuring/ignoring-code
Answer: Your angular-cli.json file would be like this-
"lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ]

You need to remove the lint path for "src/tsconfig.spec.json". So either remove the second object or comment it.
Your updated lint array should be like this-
"lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ]


how to prove that one mean estimator converges faster than another

Question: Say that I have a target normal distribution $N=(\mu,\sigma)$. I have two estimators for $\mu$, say $\mu_1$ and $\mu_2$ that are estimated iteratively from $t=1...T$. Between $\mu_1$ and $\mu_2$, I know that $\mu_1$ has less bias than $\mu_2$ in estimating the true mean $\mu$ and is therefore the better estimator. How should I express in a formal way that using $\mu_1$ allows the estimated distribution $N_1$ to converge faster to $N$ as I iterate up to $T$?
Comment: @Carl The premise of the question is still a major problem. $\mu_1$ is not necessarily the better estimator because it has less bias. An estimator with more bias can in fact converge much faster. Is there a way of asking this question differently? For instance, I think it is meaningful to ask, "How do we measure the rate of convergence for an estimator" and secondarily "How can we compare two possibly biased estimators in terms of their rate of convergence?"
Comment: @AdamO This is a good example, I think, of the type of things one says when one tries to ask an insightful question without having the words to put it forward.
Comment: Where is a definition of a "dominant estimator"? Less bias doesn't matter a lick in its own right. One way of measuring convergence rate is seeing the $n$-factor which leads the estimator to have an approximate distribution. For instance, CLT tells us the mean is a root-n consistent estimator since $\sqrt{n}(\bar{X} - X) \rightarrow_d \mathcal{N}$.
Comment: @AdamO I pruned the word "dominant". It added nothing, other than confusion.
Comment: @AdamO Indeed. We can either close the question, or, point out what is wrong with it and provide answers.
Answer: In frequentist analysis, an idea like an estimator being better than another leads to very complicated questions and there is no clear consensual answer to it. For example, people often say being unbiased is "desirable", but this does not make an estimator necessarily better. See wikipedia. A simple measure of estimator quality is the MSE $E((\hat\theta-\theta)^2)$. Note that there is never an estimator with universally best MSE (among all estimators). The unbiased assumption is sometimes used just because there may be an estimator with universally best MSE among unbiased estimators. But unbiased does not mean better.
Let's assume $\sigma$ is known.

How should I express in a formal way that using $\mu_1$ allows the
  estimated distribution $N_1$ to converge faster to $N$ as I iterate up to
  T?

Well, first formalize this. Two normal distributions (with same variance) are close when their means are close. You could use a formal definition of a distance between distributions, but in this simple case, we can say you're interested in $|\mu-\mu_1|$. Hopefully this tends towards 0.
Since $\mu_1$ is a random variable, we need a convergence measure for random variables. For example $L^2$: we look at $d_1=E((\mu-\mu_1) ^2)$. Note that at this point, there are other ways to express the limit of random variables, but this one may be the simplest for a first study.
Finally, you can try to prove $d_1$ converges faster towards 0 than $d_2$ which is done by studying the ratio $d_1/d_2$, either with formal proofs or simulations. But fundamentally, this may depend on $\mu$, which makes the frequentist analysis tricky. What you can reasonably hope is to find a result that is independent of $\mu$. This often happens with normality.
Answer: @AdamO points out, quite rightly that an estimator "is not necessarily the better estimator because it has less bias. An estimator with more bias can in fact converge much faster." For instance, one might ask "How do we measure the rate of convergence for an estimator" and secondarily "How can we compare two possibly biased estimators in terms of their rate of convergence?"
A normal distribution is not an especially good example of what you are trying to ask.
The best measure of location for a distribution is its minimum variance unbiased estimator MVUE. Let us take estimation of parameters of the Cauchy distribution. The mean is not robust, in fact, it will diverge from the Cauchy distribution's location parameter when more data is added because of the heavy tails of that distribution. The median is robust and converges to the distribution's location. A properly trimmed mean will be more robust than the median, and converge to the distribution's location faster.
Another exemplary distribution is the uniform distribution, the median will converge to the location, the mean will converge faster, and the average extreme value will converge to the uniform distribution's location faster still.
How one finds which measurement converges faster to the location is to look it up. For one thing, it takes mental effort coupled with trial and error to come up with better measurements if one starts from scratch. One can confirm easily enough, once one has an answer, what works better, but, one cannot specify a general methodology for creating better measurements other than to say, it is a bit like asking how one performs magic. Intuition perhaps, after having seen it done for a number of different cases. For example, a Pareto type I distribution has harmonic mean as a best measure of location overall, but demonstrating that might require doing Monte Carlo simulations.
Finally, robustness is sometimes more important than bias, for example, ridge regression introduces bias which can decrease variance and increase robustness at the cost of that bias, nor is bias for fitting necessarily inappropriate as ill-posed problems may have optimal solutions that are not optimal for the data fitting, but rather are optimized for other considerations.


Como redirecionar a 'interface' para uma página inicial após um tempo de inatividade?

Question: Estou construindo uma interface interativa para um totem com HTML/CSS3 que irá funcionar offline, com os arquivos locais, sem localhost, usando o Chrome no modo "Kiosk" e implementei este script(costurado com a ajuda da net) para que após um tempo de inatividade, no mouse/touchscreen a interface volte para a página inicial, acontece que nada acontec, eu trabalho com HTML e CSS3, mas agora iniciei em programação e ainda sou iniciante, então onde eu errei?
var idleTime = 60000;

$(document).ready(function() {
    //Increment the idle time counter every minute.
    var idleInterval = setInterval(timerIncrement, 60000); // 1 minute

    //Zero the idle timer on mouse movement.
    $(this).mousemove(function(e) {
        idleTime = 0;
    });
    $(this).keypress(function(e) {
        idleTime = 0;
    });
});

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 1) { // 20 minutes
        window.location.reload = "initial_page.html";
    }
}

Answer: O problema do seu código está no window.location.reload = "initial_page.html", da uma olhada na documentação p/ saber melhor como o método funciona. O restante está funcionando bem, traduzi o código e coloquei alguns log's somente para ficar mais claro o que está acontecendo. Como @Derlei respondeu, utilize window.location.replace para fazer o redirecionamento.

var segundos = 0;

$(document).ready(function() {
    //Incrementa o tempo de inatividade
    var inatividade = setInterval(timerIncrement, 1000);

    //Zera o tempo de inatividade
    $(this).mousemove(function(e) {
        segundos = 0;
        console.log("Mouse movimentado.");
    });

    $(this).keypress(function(e) {
        segundos = 0;
        console.log("Tecla pressionada.");
    });
});

function timerIncrement() {
    segundos++;
    console.log(segundos + " segundo(s) de inatividade.");
    if (segundos > 5) {
        console.log("Redirecionando...");
        window.location.replace("initial_page.html");
    }
}

Comment: Realmente estava desconfiando do window.location.reload(); obrigado pelo esclarecimento, vou verificar.
Answer: Ao invés de:
    window.location.reload = "initial_page.html";

Utilize:
    window.location.replace("initial_page.html");

Ou:
    window.location.href = "initial_page.html";

Comment: Obrigado, essa mudança resolveu o problema, o código está 100% funcional.
Answer: Olá, eu utilizo este plugin, ele trata várias condições, eu troquei tambem window.location.reload por window.location.href:
https://www.paulirish.com/2009/jquery-idletimer-plugin/
Código retirado da página do plugin:
 $.idleTimer(10000);

    $(document).bind("idle.idleTimer", function(){
     // executado quando o usuário ficar inativo, aqui você pode por o redirecionamento
        window.location.href= "initial_page.html";
    });

    $(document).bind("active.idleTimer", function(){
     // executado quando o usuário voltar a ficar ativo
    });

    // para parar o timer
    $.idleTimer('destroy');


MariaDB and MYSQL5.6 returns different results

Question: I was trying to get the richest user in the table.
This table consist of all the transaction and transaction time.
The user's money in bank was determined by the latest value of bankbalance order by tstamp DESC
SELECT b.bankid,b.bankbalance,b.remark,b.tstamp
  FROM (SELECT * FROM `bank` WHERE 1 ORDER BY tstamp DESC) AS b
 WHERE 1
group by warid
ORDER BY bankbalance DESC LIMIT 0,10

the same query gives me different results.
5.6.27 - MySQL Community Server (GPL)
5.5.56-MariaDB - MariaDB Server
The table structure is here
CREATE TABLE `bank` (
  `bankid` int(20) NOT NULL,
  `warid` int(11) NOT NULL,
  `fbid` varchar(50) NOT NULL,
  `banknumber` varchar(20) NOT NULL,
  `gross` int(20) NOT NULL,
  `bankbalance` bigint(11) NOT NULL,
  `remark` varchar(12) NOT NULL,
  `tstamp` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `bank` (`bankid`, `warid`, `fbid`, `banknumber`, `gross`, `bankbalance`, `remark`, `tstamp`) VALUES
(24, 22, '10001', 'banknumber', 5, 5, '', 1477155284),
(25, 22, '10001', 'banknumber', 1, 6, '', 1477155591.617),
(26, 22, '10001', 'banknumber', 1, 7, '', 1477155726.2211),
(27, 22, '10001', 'banknumber', 1, 8, '', 1477155730.1399),
(28, 22, '10001', 'banknumber', 1, 9, '', 1477155736.8127),
(29, 22, '10001', 'banknumber', 1, 10, '', 1477155743.4662),
(30, 23, '13332', 'banknumber', 5, 5, '', 1477155830),
(31, 23, '13332', 'banknumber', 1, 6, '', 1477155839.9243),
(32, 23, '13332', 'banknumber', 1, 7, '', 1477155842.8865),
(33, 23, '13332', 'banknumber', 1, 8, '', 1477155845.4773);

Comment: Are you sure you pasted the exact query you are using? The one you pasted has a `group by warid` but `warid` isn't in the `select` statement.
Comment: yes, it's the query that I used. Please try it on Maria DB server if possible. thanks
Comment: Newer versions of both MariaDB and MySQL throw away the `ORDER BY` in the derived table.  MariaDB started doing that before MySQL, so that may be why you got it.  The rational:  "A derived table is an _unordered_ set, so any `ORDER BY` (without a `LIMIT`) is irrelevant."
Answer: The feature that allows grouping by columns not in the SELECT portion of the query is a MySql extension. It would not be allowed in many other databases. According to the v5.6 MySql documentation (https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html):

In standard SQL, a query that includes a GROUP BY clause cannot refer
  to nonaggregated columns in the select list that are not named in the
  GROUP BY clause.
MySQL extends the standard SQL use of GROUP BY so that the select list
  can refer to nonaggregated columns not named in the GROUP BY clause.
  This means that the preceding query is legal in MySQL. You can use
  this feature to get better performance by avoiding unnecessary column
  sorting and grouping. However, this is useful primarily when all
  values in each nonaggregated column not named in the GROUP BY are the
  same for each group. The server is free to choose any value from each
  group, so unless they are the same, the values chosen are
  indeterminate. Furthermore, the selection of values from each group
  cannot be influenced by adding an ORDER BY clause. Result set sorting
  occurs after values have been chosen, and ORDER BY does not affect
  which values within each group the server chooses.

The takeaway message from the documentation is that when you write the query as you have, you cannot influence the ordering, even if you add an ORDER BY clause. The result ordering is indeterminate.
Even if you were running two instances of the same database and version, you could very well end up with different results with the same query. The solution is to rewrite your query to meet an ANSI standard and explicitly define the grouping.
Your sql might look something like this:
SELECT b.warid, b.bankbalance
  FROM bank b
       INNER JOIN (SELECT warid, max(tstamp) AS tstamp FROM bank GROUP BY warid) b2
       ON (b.warid = b2.warid AND b.tstamp = b2.tstamp)

There are a number of other useful answers on Stackoverflow that go into detail for this same question. Here is one such question: MySQL wrong results with GROUP BY and ORDER BY.
Comment: If you want to order the result set, you'll need to explicitly put that into an order by clause at the end of the sql. Without an order by clause, it will sort by whatever rules the database engine has in place.
Comment: your answer works, but how could you order by the timestamp DESC? Is it done automatically?


Unknown error when submit a REST request to Liferay json API

Question: I'm writing an script in Python to automatically update the structures in my Liferay portal and I want to do it via the json REST API.
I make a request to get an structure (method getStructure), and it worked.
But when I try to do an structure update in the portal it shows me the following error:

ValueError: Content-Length should be specified for iterable data  of type class 'dict' {'serviceContext': "{'prueba'}", 'serviceClassName': 'com.liferay.portlet.journal.service.JournalStructureServiceUtil', 'name': 'FOO', 'xsd': '... THE XSD OBTAINED VIA JSON ...', 'serviceParameters': '[groupId,structureId,parentStructureId,name,description,xsd,serviceContext]', 'description': 'FOO Structure', 'serviceMethodName': 'updateStructure', 'groupId': '10133'}

What I'm doing is the next:
<code>urllib.request.Request(url = URL, data = data_update, headers = headers)
</code>
URL is http://localhost:8080/tunnel-web/secure/json

The headers are configured with basic authentication (it works, it is tested with the getStructure method).

Data is:

data_update = {    "serviceClassName" : "com.liferay.portlet.journal.service.JournalStructureServiceUtil",     "serviceMethodName" : "updateStructure",     "serviceParameters" : "[groupId,structureId,parentStructureId,name,description,xsd,serviceContext]",     "groupId" : 10133,     "name" : FOO,     "description" : FOO Structure,     "xsd" : ... THE XSD OBTAINED VIA JSON ...,     "serviceContext" : "{}" }

Does anybody know the solution? Have I to specify the length for the dictionary and how? Or this is a bug?
Answer: This might help you. It seems it is python's bug.
Comment: That's true, I tried it with Python 2.7 and it makes the request.


Computing the radical of an ideal

Question: What is the best way to compute $\sqrt{(X^2-YZ,X(1-Z))}$ ?
This is after using Nullstellensatz by the way as I thought it would be easier to compute a radical than finding the vanishing ideal.
Answer: In this case there is no need to work over an algebraically closed field to get $$\sqrt{(X^2-YZ,X(1-Z))} = (X,Y) \cap (X,Z) \cap (Z-1,Y-X^2).$$

The radical of an ideal is the intersection of the minimal primes over it.

Let $P$ be a minimal prime over $(X^2-YZ,X(1-Z))$. Since $X(1-Z)\in P$ there are two cases to consider:

If $X\in P$, then from $X^2-YZ\in P$ we get $Y\in P$ or $Z\in P$, so $P=(X,Y)$ or $P=(X,Z)$.
If $1-Z\in P$, since $X^2-YZ=X^2+Y(1-Z)-Y\in P$ it follows that $X^2-Y\in P$, so $P=(X^2-Y,1-Z)$. (Well, now we have to know that $(X^2-Y,1-Z)$ is a prime ideal, but this is easy: $K[X,Y,Z]/(X^2-Y,1-Z)\simeq K[X,Y]/(Y-X^2)\simeq K[X]$.)

Edit. If the field is algebraically closed I think is easier to find the radical of an ideal (as an intersection of primes) by using the Nullstellensatz.
Comment: I don't understand your edit. Could you please explain? How can the nullstellensatz be used to find the radical if the field is closed? By the way +1 :)
Comment: The nullstellensatz says that when the field is algebraically closed, then the radical of $I$ is $I(V(I))$. But as far as i know the nullstellensatz does not say how to compute the radical. That's according to my understanding.
Comment: I see what you are saying. Could you please point me to an example which illustrates that computing $I(V(I))$ is simpler than computing the intersection of minimal primes?
Comment: @Manos If I understand well you are actually asking about the finding of the generators of the radical, while I'm talking about writing the radical as an intersection of primes. Is this right?
Comment: Yes, that's right.
Comment: I am sorry, i still don't understand the edit. I just don't see why computing $I(V(I))$ is a simpler problem than finding the minimal primes of $I$.
Comment: How do you know that these equations are elementary and what does that mean? Also what are these equations? That's why i asked if you had an example which demonstrates that :)
Comment: @Manos You have an example on this page. But as I said, I'll look for more illustrative ones in the near future.
Answer: You can just compute $\mathcal I [\mathcal Z [ (X^2-YZ,X(1-Z))]]$ ; assuming you're working over an algebraically closed field, notice that
$$
x^2 - yz = 0 = x(1-z) \quad \Longleftrightarrow \quad x=y=0 \quad \text{ or } \quad x=z=0 \quad \text{ or } \quad y-x^2=0=z-1,
$$
so that
$$
\mathcal Z[(X^2-YZ,X(1-Z))] = \mathcal Z[ (x,y) ] \cup \mathcal Z[ (x,z) ] \cup \mathcal Z[ (z-1,y-x^2)].
$$
Taking the ideal of zeros of this union gives you
$$
\sqrt{(X^2-YZ,X(1-Z))} = (X,Y) \cap (X,Z) \cap (Z-1,Y-X^2)
$$
(I used the fact that all three of these ideals are prime, so that they are equal to their radicals ; to see it, compute the quotient ring and see that they are integral domains.)
If your question involves finding generators for this intersection, I'll think about a hint later if you ask for it.
Hope that helps,
Comment: See http://math.stackexchange.com/questions/791789/computing-irreducible-components-of-algebraic-set/791954#791954 for generators of this intersection.

Computing the radical of an ideal


How can I disable revisioning on specific node field

Question: I currently use hook_entity_extra_field_info() and hook_ENTITY_TYPE_view() to create a custom field displayed in nodes that generates content dynamically via PHP.
However, Drupal 9 seems to be tracking changes to the output of this field each time I save a node revision, which I don't want because that field's content is generated dynamically and is already under version control in a custom module.
Is there a way to tell Drupal in one of those hooks, or anywhere else in the configuration, not to track revisions for a specific node field?
Comment: How is it tracking the changes exactly? Is it just a display field? or is it actually storing a value in the database?
Comment: What does `generates content dynamically` mean exactly? Can you show us some sample code? If you generate content in the sense of attaching something to the same node of course revisioning kicks in if you don't store the stuff somewhere else. Pseudo fields are normally only used for displaying computed markup, not for generating content.
Answer: As the content of your field is dynamically generated, it sounds like you need a computed field. Which will remove the issue you are running into. A computed field is one that is generated dynamically, rather than through user input. As it is a field, it can be managed like any other field in Drupal (though integration with Views requires some additional efforts). Fields are also cached with Drupal's various cache APIs.
To create a computed field, first extend Drupal\Core\Field\FieldItemList, use the Drupal\Core\TypedData\ComputedItemListTrait, and implement the computeValue() method:
namespace Drupal\[EXAMPLE]\Plugin\Field;

use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;

class SomeDynamicField extends FieldItemList {

  use ComputedItemListTrait;

  /**
   * {@inheritdoc}
   */
  protected function computeValue() {
    $values = some_function_to_get_an_array_of_values();
    foreach ($values as $index => $value) {
      $this->list[$delta] = $this->createItem($delta, $value);
    }
  }
}

Next, this field needs to be added to each entity type that you need, in hook_entity_base_field_info_alter():
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * Implements hook_entity_base_field_info_alter().
 */
function EXAMPLE_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  // Add/alter entity types as necessary.
  $applicable_entity_types = ['node'];
  if (in_array($entity_type->id(), $applicable_entity_types)) {
    $fields['my_computed_field'] = BaseFieldDefinition::create('string')
      ->setName('example_field')
      ->setLabel(t('Example Calculated Field'))
      ->setDescription(t('An example of a calculated field'))
      // Set the field as a computed field.
      ->setComputed(TRUE)
      // Set the class that generates the field value(s).
      ->setClass('\Drupal\[EXAMPLE]\Plugin\Field\Computed\SomeDynamicField');
  }
}


iOS app size: over-the-air vs. wi-fi

Question: TL;DR: Is the size message I got in App Store Connect just a warning, or do I need special permission (some checkbox?) to go past the size limit.
I understand that the over-the-air size is limited to 150 MB (latest limit) and the wi-fi size is limited to 2 GB. This is well-explained here on SO and other places.
Now... the last time I submitted an app that was over the limit I got this warning (or is it fatal error?):

(Yeah it says 100 MB: it's an old screen shot.) So the question is: when my next submission goes over 150 MB (as it surely will) and I get this message again, what to do?

Just proceed with approval process?
Check some box somewhere
acknowledging that users won't be able to use their cellular
connection to download?
Get some permission?
Answer: As you said, 100MB is the limit for cellular download. You can submit your app and it won't affect your approval, but users will not be able to download your app unless they are on Wifi.
However, a common solution to this problem is to perform a one-time download of large files the first time your app is launched. That way, you can still have all of those files, but your initial app store download will be within the download limit.
You can also use app thinning to reduce your file size or move some of your larger resources to on demand storage. Apple has given you links to both of those methods in that warning message you posted.
Comment: Already using bitcode (for thinning) and ODR. (The app is a freemium model with additional resources buyable via in-app purchase.) I believe there is a race condition in `conditionallyBeginAccessingResources` that kept freezing my app. Spent weeks trying to debug it. Switching to supplying resources via AWS fixed the problem.
Comment: To forestall well-intended advice about iOS ODR, see https://forums.developer.apple.com/thread/43202. It's an ongoing pain point. If you thought the write-compile-debug cycle was slow, don't even think about the build-upload-download-debug cycle.

iOS app size: over-the-air vs. wi-fi


Prove that $x$ and $x+1$ are coprime numbers

Question: Given $\{x \mid x > 1\}$, how do I prove that any given $x$ and $x+1$ are coprime?
Comment: $p \mid x,x+1 \Longrightarrow p \mid 1$.
Answer: If $y$ divides $x$ and $x+1$ then it divides $(x+1)-x=1$. Conclude.
Comment: If $y$ divides $x$ and $x+1$ then there's $a$ and $b$ such that $x=ay$ and $x+1=by$ then $(x+1)-x=(b-a)y$ so... Do you understand?
Comment: "If y divides x and x+1 then it divides (x+1)−x=1." Why is this true?
Comment: Nice! A one-liner kills the question!
Comment: Nice and concise.
Answer: $\gcd(x,x+1)=\gcd(x,x+1-x)=\gcd(x,1)=1$.
Hence $x$ and $x+1$ are coprime.
Comment: +1 for a general method
Comment: I feel dumb, that I didn't get to it myself. Thank you!
Answer: If $x$ is a multiple of $p$, then the next multiple of $p$ is $x+p$, but that's clearly larger than $x+1$.
Comment: Or, $ $  mod $\,p\!:\ x\equiv 0\,\Rightarrow\, x+1\equiv 1\not\equiv 0\ $ (else $\,p\mid 1-0)\ \ \ $


How to add a tpl file to a block from a custom module

Question: I have a custom module that build a block. I'm trying to add a tpl file, but I don't get nothing.
This is my code:
<?php
/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function tados2_block_info() {
  $blocks = array();

  $blocks['block_with_tpl'] = array(
    // info: The name of the block.
    'info' => t('Tados2 example: block with tpl'),
    'status' => TRUE,
  );

  return $blocks;
}
/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function tados2_block_view($delta = '') {
  switch ($delta) {
    case'block_with_tpl':
      // The subject is displayed at the top of the block. Note that it
      // should be passed through t() for translation. The title configured
      // for the block using Drupal UI supercedes this one.
      $block['subject'] = t('Tados2 block with tpl');
      // The content of the block is typically generated by calling a custom
      // function.
      $block['content'] = t('Hola mundo');//_tados2_block_with_tpl_contents();
    break;
  }
  return $block;
}
?>

I'm trying to move the content to a tpl.php file.
This what I'm trying:
<?php
/**
 *
 * Implementen hook_theme
 *
 */
function tados2_theme(){
  return array(
    'tados2_block' => array(
      //'render element' => 'elements',
      'template' => 'tados2_block',
      'variables' => array('title' => NULL, 'content' => NULL),
    ),
  );
}
/**
 * preprocess function
 *
 */
function template_preprocess_tados2_block(&$variables) {
  dpm($variables);
}
?>

Answer: You have to call your theming function:
$block['content'] = theme('tados2_block', array('title' => 'foo', 'content' => 'bar'));

Comment: Hello Leni,Thanks it will only for the content.
For the title will be the same?
Answer: I have tried to use a template file in my block. This is my solution.

Fist step: You need to register your theme. Use the following code in yourmodule.module.
function yourmodule_theme($existing, $type, $theme, $path){
  return array(
    'yourmodule_block' => array(
      'template' => 'yourmodule',
      'variables'=> array('var1' => NULL, 'var2' => NULL),
    ),
  );
}

Note that in 'template' => 'yourmodule' 'yourmodule' is the template filename in your module folder.
Check hook_theme() for more details.
Secondnd step: Use your theme for a block.
function yourmodule_block_view($delta = '') {
  switch ($delta) {
    case 'yourmodule_block':
      $block['subject'] = 'LinhNH-Training';
      $block['content']['yourmodule'] = array(
        '#theme' => 'yourmodule_block',
        '#var1' => 'Module Title',
        '#var2'=>'Content '
      );

      return $block;
      break;
  }

  // return $block;
}


Programmatically load the contents of a Product in a particular product type

Question: I am developing an Ecommerce site and I am using Drupal-commerce module for it. I have an issue regarding loading the contents of a product which is: How can I programmatically get the contents of all the products in a particular product type?
Answer: This can be done with an EntityFieldQuery:
<code><?php
  $query = new EntityFieldQuery();
  $result = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'product')
    ->execute();
  $nodes = node_load_multiple(array_keys($result['node']));
?>
</code>
Answer: This code will help you.
<code>$banner_query = db_select('node','n');
$banner_query->innerJoin('field_data_field_weight','w','w.entity_id = n.nid');  // join with another table
$banner_query->fields('n',array('nid'));
$banner_query->fields('w',array('field_weight_value'));
$banner_query->condition('n.status',1,'=');
$banner_query->condition('n.type','skin_and_hair_banners','=');
$banner_query->orderBy('w.field_weight_value','ASC');
$banner_res = $banner_query->execute();

while($banner_fetch = $banner_res->fetchObject()){
    $banner_load = node_load($banner_fetch->nid);
    echo "<pre>"; print_r($banner_load)
}
</code>


How to calculate the probability of picking a certain number of distinct marbles out of a bag, given a certain number of selections?

Question: Imagine I have a bag of n labeled marbles. I would like to pick a single random marble out of the bag x number of times. Every time I pick a marble, I place it back in the bag.
How do I calculate the probability that I will only pick p distinct marbles?
In my case, I have 90 labeled marbles, 550 selections and I want to know what the probability is that I will only select 60 distinct marbles.
Comment: I want to inform you that the answer you accepted earlier had a mistake in its reasoning, which I explain in my latest edit. I updated my answer with what I now believe is correct. At the end, I give a brief explanation for why my previous, accepted answer, was wrong.
Answer: We can start by asking the following combinatorics question:

Given a set of $m$ categories and $l$ items, such that each item and each category is unique, how many possible ways can we distribute the $l$ items among the $m$ categories?

For example, suppose we went fishing and I told you I caught 5 fish. In the lake there are three types of fish: tuna, salmon, and carp. How many ways are there to distribute the 5 catches among the 3 fish types, where the order of the catches matter?
If both item and category are unique, then the label of the catch number matters. So, for example, it's not enough to say "we caught 3 tuna and 2 carp", because we want to distinguishing between the scenario "TTTCC" and "TCTCT". (In both cases there were 3 tuna and 2 carp, but the order was different.)
Another way of asking this question is as follows:

How many functions are there from the set $\{1, 2, \dots, l\}$ to $\{1, 2, \dots, m \}$?

The answer is $m^l.$
Now we can ask the following, more restricted combinatorics question:

Given a set of $m$ categories and $l$ items, such that each item and each category is unique, how many possible ways can we distribute the $l$ items among the $m$ categories such that each category is represented at least once? (i.e. none of the categories have been selected zero times).

An equivalent form of this question is,

How many functions are there from $\{1, \dots, l \}$ to $\{1, \dots, m \}$ that is a surjection?

A "surjection" is a mapping from set $S_1$ to $S_2$ such that each element in $S_2$ has been mapped to at least once.
Without going into too much detail about how to solve this, this can be done using the inclusion-exclusion principle, which states that the size of the union of a finite number of sets is equal to the sum of the size of each set, minus the sum of the sizes of each intersection of pairs of sets, plus the sum of the sizes of each intersection of set triplets, etc. A good intuitive explanation of why this is can be found here.
In general, the number of surjections from $\{1, \dots, l \}$ to $\{1, \dots, m \}$ is given by $m! {l \brace m},$ where $l \brace m$ is a Stirling Number of the Second Kind, defined as,
$$
{l \brace m} = \frac{1}{m!} \sum_{j=0}^m (-1)^{m-j} {m \choose j} j^l.
$$
This is an example of a set of combinatorics problems called the "twelvefold way", specifically this one.
Now to bring this to the above problem. Because each marble can be selected any number of times, we can treat each marble as a category, and each selection as an item. For $n$ marbles, of which we only select a specific set of size $p$ out of $k$ draws, but for which we select all of those $p$ marbles, the number of possible selections is $p! {k \brace p}.$
Now, there can be $n \choose p$ possible groups of $p$ marbles out of $n$. Because the above result is for a specific choice of $p$ marbles out of $n,$ the total number of ways to select exactly a set of $p$ marbles out of $n$ given $k$ selections is,
$$
N_p = {n \choose p} p! {k \brace p}.
$$
The total number of ways of distributing the $k$ selections out of $n$ marbles with replacement, with no regard to how many unique marbles were selected, is
$$
n^k.
$$
The probability of selecting exactly $p$ out of $n$ marbles given $k$ selections is just $N_p/N.$ That is,
$$
P_p = \frac{ {n \choose p} p! {k \brace p} }{ {n^k} } = \frac{n! {k \brace p}} {(n-p)! n^k}.
$$
Keep in mind that this is not a closed-form solution, because the Stirling number of the second kind is not an analytic function, but rather, the result of a sum. Therefore each computation of this probability must be done numerically, by evaluating the Stirling number.
Using the numbers in your example is tricky, because the numbers are large enough that operations like exponents and factorials can't be stored in most systems. We could try and apply approximation methods to get accurate results. But we could also be lazy and use the "gmp" library in R, which uses the class "bigz" to store huge integers, and "bigq" to store rational fractions of huge integers, then convert back to numeric after the calculations. As well as its built-in functions "chooseZ", "factorialZ", and "Stirling2" that automatically does these operations on bigZ objects. Here is a code snippet:
<code>library('gmp')
P <- function(p, n, k) chooseZ(n,p) * factorialZ(p) * Stirling2(k,p) / ( as.bigz(n) ^ as.bigz(k) )

n <- 90
k <- 550

Pp <- lapply(1:n, function(p) P(p,n,k))
Pvec <- sapply(Pp, asNumeric)

Pvec[60]
#[1] 9.449035e-74
#As a sanity check, see if Pvec is a valid probability distribution
sum(Pvec)
#[1] 1
</code>
The probability of only selecting 60 unique marbles from 550 selections, when there are 90 total marbles, is roughly a negligible $10^{-73}.$

NOTE
This is an update to a previous solution that I submitted, which was incorrect but accepted nonetheless. This edit was made on January 30, 2018, so if you want to see the old (incorrect) accepted submission you can look at an edit from before then.
To summarize, the old solution was,
$$
P_p = \frac{ {n \choose p} {k-1 \choose k-p} } {n+k-1 \choose k}.
$$
I used the "stars-and-bars" combinatorics problem that answers the question of surjective functions from $\{1, \dots, l \}$ to $\{1, \dots, m \}$ up to a permutation of the first set, given by this twelvefold way. Essentially, it's asking how many enumerations of marble choices there are, where order of the choice doesn't matter. Even though the above is a valid probability distribution (which you can verify), it is still wrong.
The reason it is wrong is because it doesn't identify each choice. For example, suppose we only choose marbles A and B out of 5 selections. Consider the two scenarios:
1) Marble A gets chosen 4 times and marble B gets chosen 1 time
2) Marble A gets chosen 3 times and marble B gets chosen 2 times
There are 5 different possibilities for the first scenario, and 10 possibilities for the second scenario. Yet the above solution treats those scenarios equally, because it doesn't consider the order in which the choices are taken.
Comment: Thanks for that incredible explanation. Now, if I plug all my numbers in, I get P(60) = 2.98525×10^17 for k = 550, n = 90. That number makes no sense to me. How can I have a probability of 2.98525×10^17?

[Here is the wolfram alpha link](https://www.wolframalpha.com/input/?i=P_p+%3D+(%7B90+%5Cchoose+60%7D+%7B550-1+%5Cchoose+550-90%7D)+%2F+%7B90+%2B+550+-+1+%5Cchoose+550.%7D)
Comment: You accidentally did $k-1 \choose k-n$. Here's the corrected link.
https://www.wolframalpha.com/input/?i=P_p+%3D+(%7B90+%5Cchoose+60%7D+%7B550-1+%5Cchoose+550-60%7D)+%2F+%7B90+%2B+550+-+1+%5Cchoose+550.%7D


Connect to localhost from Guest running on VirtualBox

Question: I have a Rails app running on Mac at http://localhost:3000 and I would like to access it from Windows 7, which is a guest OS running on VirtualBox.
Can you explain me how to do that?
Thanks!
Answer: Make sure networking is active in the virtual machine and you can web browse, etc. from the Windows machine. Then you can enter the ip address of your Mac and the port in the web browser of the virtual machine and it should come up for you.
You can get your Mac's IP address from the system preferences (networking) or using ifconfig on the terminal application. Then use http://xxx.yyy.aaa.bbb:3000 and your app should pop up for you.
Answer: Just in case others read this more recently... by doing ifconfig or ipconfig /all (in windows) guest.. you can get yor gateway ip.. which will be your host...
thus say your gateway is 10.x.x.x in guest... (and on host it is somethign else), just
try http://10.x.x.x/ (add port as desired).
lakmilis
Answer: Try http://your.mac.ip.address:3000


Is a ball which spins significantly and misses leg stump a wide?

Question: If a cricket ball pitches outside off stump, but then turns so sharply that it misses leg stump, is it is a wide ball or not?
Comment: Which format of cricket? Tests, ODI or T20?
Answer: In the laws of cricket a wide is defined as a ball that a batsmen cannot play a normal cricket shot too.  See Law 25 Wide Ball.
That is the basis for judging whether a ball is wide in cricket where there are not playing conditions relating to the wide ball.
Most limited overs cricket will have some variation of leg side wides, where balls passing to the leg side of the batsmen and stumps are liable to be called wide.  However the exact wording will depend on the competition.
One day international Playing Conditions and T20 playing conditions are examples of this as are the ECB generic conditions
So to answer the question, under the laws of cricket the ball is probably not a wide, under the playing conditions of one day cricket it is likely to be a wide.
Answer: I'm not sure of it ... But I think in T20 cricket it would be a wide. But, in more bowling friendly formats like test cricket it would probably not be a wide.


How do I move a group of nodes to another Drupal instance?

Question: What:
I'm breaking a part a huge D7 site into a D7 multi-site instance.
Why:
Marketing demands have changed. They different units still want to use the same theme but have different main menus and slight CSS tweaks here and there. They also want separate authors and very different approval processes. This site is crippled under it's own weight.
So far: I've already copied over Content Types via Bundle Copy and most everything that will remain standard via source controlled features.
How/Question: How can I move a piece of content (node/XXX) to another Drupal 7 instance?  A drush solution would be preferred so that I have the ability to script this across Stage and Production servers once we figure it out on Dev.
Errata:
I've seen interesting methods to scrape content via feeds, sharing content, and seen great dev to prod workflows. However, I haven't seen something that addresses a one-time move of a node between instances.
Comment: Would it be an option to NOT split the site in multiple instances, but instead use the [Group](https://www.drupal.org/project/group) module to implement similar functionality in your existing site? If so, and if you wonder "how", post some kind of related/followup question (and let me know you did) ...
Comment: Thanks Pierre. For this project, the changes are beyond content and authoring. In fact, I think the multisite separation phase is only one part of a larger plan. Some units may be becoming more independent. Having them already separated off will make my life easier down the road.
Comment: OK, that makes sense ... sounds like "How do you eat an elephant?", with answer "1 bite (or byte???) at a time", right? Good luck!
Answer: What would suit you is the Deploy module: https://www.drupal.org/project/deploy
The README.txt states:
The Deploy module is used to deploy Drupal content to other Drupal sites or arbitrary systems. Two concrete use cases are:

using it as a content staging solution
using it to push content downstream from a main site to several sub sites.

Here's a demo:
https://www.youtube.com/watch?v=7PjwT0HWHxw
Comment: Upvote. This module interests me. We have a dev-stage-prod model for development and module evaluation. But I'd love to add an authoring server tot that mix. Thanks.
Answer: For the scenario you describe, i.e. a once-off, one-way move from one site to another, automated with drush, Node Export is a good way to do it. You can use the node_export_import() function in your drush script or update hook:
  $file = 'exported_nodes.txt';
  if (file_exists($file)) {
    $nodes = file_get_contents($file);
    $status = node_export_import($nodes);
    // etc.
  }


Build is Success but No sources to compile

Question: Maven test output in the Eclipse console:
[INFO] Scanning for projects...
    [WARNING]
    [WARNING] Some problems were encountered while building the effective model for Mabi:Mabi:jar:0.0.1-SNAPSHOT
    [WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.seleniumhq.selenium:selenium-java:jar -> duplicate declaration of version 2.45.0 @ line 20, column 21
    [WARNING] 'build.plugins.plugin.(groupId:artifactId)' must be unique but found duplicate declaration of plugin org.apache.maven.plugins:maven-surefire-plugin @ line 74, column 10
    [WARNING]
    [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
    [WARNING]
    [WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
    [WARNING]
    [INFO]
    [INFO] ------------------------------------------------------------------------
    [INFO] Building Mabi 0.0.1-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    [INFO]
    [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Mabi ---
    [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
    [INFO] skip non existing resourceDirectory E:\workspace\Mabi\src\com.TestCase
    [INFO]
    [INFO] --- maven-compiler-plugin:3.5:compile (default-compile) @ Mabi ---
    [INFO] Changes detected - recompiling the module!
    [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
    [INFO] Compiling 166 source files to E:\workspace\Mabi\target\classes
    [INFO]
    [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ Mabi ---
    [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
    [INFO] skip non existing resourceDirectory E:\workspace\Mabi\src\test\resources
    [INFO]
    [INFO] --- maven-compiler-plugin:3.5:testCompile (default-testCompile) @ Mabi ---
    [INFO] No sources to compile
    [INFO]
    [INFO] --- maven-surefire-plugin:2.19.1:test (default-test) @ Mabi ---
    [INFO] No tests to run.
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 7.287 s
    [INFO] Finished at: 2016-03-23T11:32:40+05:30
    [INFO] Final Memory: 21M/283M
    [INFO] ------------------------------------------------------------------------

Above image shows the directory of my project but when I run the project via Maven it gives me the above result without running the test. Looking forward for some accurate solutions.
And this is what my POM.XML file looks like:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Mabi</groupId>
  <artifactId>Mabi</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
    <groupId>com.relevantcodes</groupId>
    <artifactId>extentreports</artifactId>
    <version>2.40.2</version>

    </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.45.0</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8</version>
       </dependency>
</dependencies>

  <build>
    <sourceDirectory>src</sourceDirectory>

    <resources>
      <resource>
        <directory>src/com.TestCase</directory>
        <includes>
        <include>**/com.*TestCase.java</include>
        </includes>
        </resource>
     </resources>

    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5</version>
        <configuration>
          <source/>
          <target/>
        </configuration>
      </plugin>
     <plugin>

        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
            <version>2.19.1</version>
                <inherited>true</inherited>
            <configuration>
                <suiteXmlFile>testng.xml</suiteXmlFile>
            </configuration>
    </plugin>
 </plugins>

</build>
</project>

Comment: Have you tried using [the Standard Directory Layout](https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html)?
Comment: Follow the conventions and remove ` sourceDirectory`, and your `resources` entries in your pom file. Tests are usually name like `*Test.java` and **NOT** `*TestSuite.java` ...and furthermore if you use testng you seldom need to define a suiteFile...surefire plugin will handle that all fine..If those tests are integration tests than you should name them like `*IT.java` and use the maven-failsafe-plugin...and follow the name schema...
Comment: I'm currently using the standard method which is src-->test-->java files
Answer: Maven is all about "convention over configuration" idiom. In order that maven-surefire-plugin will run your testcases it expects to find it under src/test/java, hence, you should follow the maven's standard directory layout and put all your test cases under src/test/java.
Comment: Thanks, I glad it helped!
Comment: Saved me another hour of going crazy \o/


Como colocar um alert de sucesso em uma inserção de dados via ajax?

Question: estou mexendo em um projeto em andamento e o que preciso fazer nele é colocar um alert e atualizar a página após inserir dados no banco. Os dados estão sendo inseridos através de uma planilha, ou seja, cada item é uma linha da planilha que contém outras tantas colunas. Da forma que coloquei o alert ele está aparecendo o alert para cada item que for inserido com sucesso, ou seja, se a planilha tiver 50 itens irá aparecer 50 alerts de sucesso. Eu gostaria que aparecesse apenas um no final de todos serem inseridos.
Código:

Comment: Tenta criar um contador para cada registro salvo, daí no Success você faz um if(contador == numeroLinhas) { alert('Salvo') }
Answer: var qtdRegistros = dados.length;
var contador = 0;
success: (function(data) {
 contador++;
 if (contador == dados.length)
  alert('Mensagem');
});

Implementa um contador e compara se os registros inseridos são a mesma quantidade que a dos teus dados.


how is this Bottleneck design the same as original residual block in resnet?

Question: This paper/link talks about resnet's bottleneck design.

It's totally not clear to me how the bottleneck design on the right is equivalent to the left-diagram and how is it reducing the parameters? Left has 64-d input whereas right has 256-d. What is 'd' denote? If it's channel in the input, then what does 64 in '1x1, 64' denote? If the input to 1x1 conv is 256 channel, then doesn't it implicity mean, we have a filter of 1x1x256 for the conv? So not sure, where that 64 comes from.
In short it's very unclear how left-side is equivalent to the bottneck diagram on right and how right is better. Could someone please explain?
Answer: They're not equivalent, the claim is just that the block on the right has more expressivity while being more computationally efficient.
Number of parameters of each layer can be computed as $NMK^2$ where the kernel is $K \times K$ and there are $N$ input and $M$ output channels. So the left block has about 74k parameters and the right block has 70k.
d denotes the channels in the output of each layer.
Comment: I see. Any reason then why the paper/link above compares these two in the diagram and not the ones that would have been equivalent?


Get select field value inside of a module

Question: I have a taxonomy reference field field_location_type with terms: Term A, Term B.
Inside of my custom module, I'm setting up a presave function that will set a hidden field value depending on the term selected in field_location_type.
I'm trying to log the current value of the field just to confirm i'm getting the right one, but there are no values displaying, like ...
function general_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
    \Drupal::logger('general')->notice('here: ' . $entity->field_location_type->value);
}

How do i get the value of the select field field_location_type?
Answer: Update as @berdir suggested in the comments, the best way to get a field value is:
$node->get('field_location_type')->target_id
In addition, you could also use Field::getValue method if you want an array representation.  Something like:
$entity->field_location_type->getValue()[0]['target_id']);

In addition if you need the term name (Option A ) from the id you can do this:
  $tid = $entity->get('field_location_type')->target_id;
  $term = \Drupal\taxonomy\Entity\Term::load($tid);
  // $name should have 'option A' or 'option b'
  $name = $term->getName();

Update: one way to figure out what methods are available  to you is to use xdebug in PhpStorm. If you set a break point after $field = $entity->field_location_type; you can then type $field-> and then hit ctrl and space the editor will provide suggestions based on the type of $field Here is a screen shot:
Comment: I don't understand why everyone uses getValue(). Don't do that unless you really want an array representation of the values. Just use $node->get('field_location_type')->target_id for the first delta. [1]->target_id for other deltas. Like this, you can also access ->entity on reference fields and you have the loaded entity. See https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet
Comment: Unfortunately thats brining back an empty value. Note, 'Option A' is the expected value.
Comment: sorry you are using taxonomy term, you need to use target_id, updated answer. I will update it on how you can get the name from it.
Comment: You rock @awm! How did you know to use `getValue()[0]['target_id']`? I want to be able to figure that out without you next time.
Comment: I usually check the type of the object returned then proceed to open the appropriate api. If you use xdebug you can see the type of the object returned on the entity.


Sistema dinâmico de imagens e comportamento de SEO

Question: Fiz uma leitura sobre SEO e entendi que quanto maior o trafego de texto, você possuí mais conteúdo a ser indexado pelo Google.
Possuo uma aplicação que se baseia em imagens, é praticamente uma "múltipla-galeria" gerada não exatamente assim, mas mais ou menos da seguinte forma.
foreach(var foto in galeria){

}

Estava pensando, se criar uma tabela que contenha um título para a foto e declarar no alt ou  title, as minhas imagens passarão a ter um valor para indexação?
foreach(var foto in galeria){

}

Além disso, pensei em gerar uma tabela na qual o usuário possa cadastrar TAGs. Exemplo:
A aplicação passará disso:
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript">

Para mais ou menos isso:
<meta name="keywords" content="@foreach(var tag in tags){@tag.nome,}">

Meu conteúdo será tratado como texto pelo Google apesar de estar recebendo o mesmo dinamicamente?
Comment: Com relação a usar `alt` e `title`, se você usar esses atributos, o Google indexará os textos deles. Isso realmente torna suas imagens mais fáceis de serem achadas.
Answer: Sempre que pensar em SEO pense em texto. Se quiser ter uma ideia mais aproximada como um motor de busca visualiza a sua página use o Lynx ( um browser que só lê texto). O Google afirma que não lê a meta="keywords", mas ao que parece o Yahoo e o Bing atribuem uma certa importância a essa meta tag. Quando aos atributos alt, são obrigatórios para a sua página pode ser validada. Então cada imagem deve ter sempre uma descrição que sirva de alternativa caso a imagem não possa ser exibida. O Google lê esse atributo e usa-o não só para entender a sua página , como também para exibir as imagens quando procura por imagens no google.
Comment: Acho que pra gestão total são 3 fatores: nome do arquivo (descritivo, higienizado e separado con hífens), meta dados EXIF do próprio arquivo e atributos `title` + `alt` no HTML.


What is the difference between a partition and a subinterval?

Question: For example the norm of a partition is the widest subinterval
Comment: A partition of an interval can give you several subintervals.
Comment: Welcome to Mathematics Stackexchange! I've shortened your title to make it more on point and added the terminology and definition tags.
Comment: I also suggest that you [edit](https://math.stackexchange.com/posts/3983221/edit) your question to explain the context a little better.
Comment: If $[a, b] $ is a closed interval then a partition $P$ of $[a, b] $ is a finite set of points from that interval including both the end points $a, b$.
Answer: Here is a formal definition of partitions of intervals:

In mathematics, a partition of an interval $[a, b]$ on the real line is a finite sequence $x_0, x_1, x_2, ..., x_n$ of real numbers such that
$$
a = x_0 < x_1 < x_2 < ... < x_n = b.
$$

Such partition gives you $n$ "subintervals" of $[a,b]$,
$$
[x_{k-1},x_{k}],\quad k=1,\cdots,n\tag{1}
$$
The norm (or mesh) of the partition
$$
x_0 < x_1 < x_2 < ... < x_n
$$
is the length of the longest of the subintervals in (1):
$$
\max\{|x_i − x_{i−1}| : i = 1, ... , n \}.
$$

To see a simple example for the interval $[0,10]$,
take the partition:
$$
0<1<6<8.5<10
$$
This partition gives you four subintervels:
$$
[0,1],\quad [1,6],\quad [6,8.5],\quad [8.5,10]
$$
and the norm of this partition is $5$.
Answer: A partition of an interval is a division of the interval into subintervals; the subintervals are the 'pieces' of the partition, so to speak, the subintervals of which the partition is composed.
The norm of a partition is not the sidest subinterval of the partition: it is the width of the widest subinterval. Consider, for instance, the partition of $[0,1]$ into subintervals $\left[0,\frac13\right],\left[\frac13,\frac12\right]$, and $\left[\frac12,1\right]$. The partition is this collection of subintervals. The lengths of the subintervals are $\frac13,\frac16$, and $\frac12$, so the norm of the partition is $\frac12$; it is *not the interval $\left[\frac12,1\right]$.
Comment: I thought the norm of the partition P is the length of the widest subinterval? I am also a little confused where 1/6 came from. Sorry if this is a stupid q.
Comment: @fintechgenie: Yes, that is what I said: It the length (or width, if you prefer — same thing) of the widest subinterval. $\frac16=\frac12-\frac13$, the width of the middle interval.
Comment: Oh my bad sir thank you so much for the explanation!!! appreciate it!!
Comment: @fintechgenie: You're welcome!
Answer: A partition of a set $S$ is a collection of subsets $S_i\subset S$ such that the union $\bigcup S_i=S,$ and each distinct $S_i$ have empty intersection. In the case of $S=[a,b]\subset \Bbb R^1$, this gives you non-overlapping subintervals of $[a,b]$ which together forms the entirety of $[a,b]$.


What are the assumptions of a Gamma GLM or GLMM for hypothesis testing?

Question: What are the assumptions when doing hypothesis testing using a Gamma GLM or GLMM? Are the residuals suppose to be normally distributed and is heteroscedasticity a concern like the Gaussian (normal) distribution? Do you test the assumptions in the same fashion Levene Tests of individual fixed effects, residual and qqplots, and Shapiro-Wilks test?
Discussion of when to use Gamma Glm and Glmm is found here:
When to use gamma GLMs?
However, I found little to no discussion of the assumptions and how to test them?
Edit 1: Requested Example residual plots- are any of these a concern. Levene's test, comes back significant.
Residuals are plotted using this code. Time (Obs) is the ordinal factor levels from the data
modelresiduals = residuals(Gama_model)
plot(modelresiduals)
plot(y = modelresiduals, x = Model_data2$Obs)

1. All resids-

2. By time

Edit 2 Based on comment suggestions- Patterns look good
ypred = predict(gama_model)
res = residuals(gama_model, type = 'pearson')
plot(ypred,res)
hist(res)
plot(res)
plot(y = res, x = Model_data$Obs)

3. Pearson histograms- based on answer code

4. Pearson vs pred (link scale)- based on answer code

5. All Pearson residual- based on answer code

6. Pearson residual by Time- based on answer code
Answer: A nice approach for checking the fit of your assumed model to the data, accounting for features, such as, over-dispersion, non-normality, zero-inflation is the simulated scaled residuals provided by the DHARMa package. If your assumed model is correct, these residuals should have a uniform distribution. You can find more details on the procedure they are defined and used in the vignette of the package.
As an example, using the simulated example above, I compare below the fit of the Gamma model to the fit of the wrong normal model:
set.seed(0)
N <- 250
x <- runif(N, -1, 1)
a <- 0.5
b <- 1.2
y_true <- exp(a + b * x)
shape <- 2
y <- rgamma(N, scale = y_true / shape, shape = shape)

gamma_model <- glm(y ~ x, family = Gamma(link = "log"))
normal_model <- glm(y ~ x, family = gaussian())

library("DHARMa")
check_gamma_model <- simulateResiduals(fittedModel = gamma_model, n = 500)
plot(check_gamma_model)

check_normal_model <- simulateResiduals(fittedModel = normal_model, n = 500)
plot(check_normal_model)

Comment: In my **GLMMadaptive** package (https://drizopoulos.github.io/GLMMadaptive/) that fits similar models as the **glmmTMB** but using the adaptive Gaussian quadrature instead of the Laplace approximation it works. For an example you may check: https://drizopoulos.github.io/GLMMadaptive/articles/Goodness_of_Fit.html
Comment: note if  using glmmtmb for mixed models...random effects can make residual vs predicted line plots go haywire....despite good fit and lack of overdispersion..thanks for addition
Answer:
Are the residuals suppose to be normally distributed...

No.  The distribution of $y\vert x$ is assumed to be gamma, and I don't think that $X - \mathbb{E}(X)$ is gamma for $X\sim \text{Gamma}(k,\theta)$.  The deviance residuals, on the other hand, should be normal.

is heteroscedasticity a concern like the Gaussian (normal) distribution?

Heteroscedasticity should be observed since the variance changes with the mean.
Here is an example of Gamma regression in R.
library(tidyverse)

#Simulate
set.seed(0)
N <- 250
x <- runif(N, -1, 1)
a <- 0.5
b <- 1.2
y_true <- exp(a + b * x)
shape <- 2
y <- rgamma(N, scale = y_true/shape, shape = shape)

#Model
plot(x,y)
model <- glm(y ~ x, family = Gamma(link = "log"))
summary(model)

#Deviance residuals
ypred = predict(model)
res = residuals(model, type = 'deviance')
plot(ypred,res)
hist(res)

#Deviance GOF

deviance = model$deviance
p.value = pchisq(deviance, df = model$df.residual, lower.tail = F)
# Fail to reject; looks like a good fit.

For more on GLMs, I would recommend Extending the Linear Model by Faraway.
Comment: "Heteroscedasticity should be observed since the variance changes with the mean." This is true for the modeled **response** variable but not for the residuals vs. the predicted values as part of the model validation process? Your `plot(ypred,res)` looks good and there is no residual pattern present.
Comment: @Stefan, yes, thank you for clarifying.  The response should be heteroskedastic, but the deviance residuals should not.
Comment: I agree with Demetri. You shouldn't use those tests to assess whether assumptions are met. I mostly use Pearson residuals and not Deviance residuals for model validation  - although both (Pearson and Deviance residuals) are defined in Faraway's book to do diagnostic plots. This paper might be helpful too (see Step 7): https://besjournals.onlinelibrary.wiley.com/doi/full/10.1111/2041-210X.12577
Comment: so am I correct in saying that if my data is hetersocedastic in time (ie. Cone shaped), if I want to do hypothesis tests with pairwise comparisons and I'm doing a gamma glmm, it's not a concern like it would be in a linear mixed model(Gaussian)?
Comment: That should be correct. The variance should change with the mean for a Gamma Glm
Comment: OK! I wasn't exactly sure what @DevonOliver meant (modeled response or residual) when he said "so am I correct in saying that if my data is hetersocedastic in time...it's not a concern..."
Comment: @DemetriPananos  if a levennes test of the residuals(without specifying deviance) for one of thefixed effects (time; since thats the example ive been using)came back significant, is that a concern .
Comment: It isn't normally recommended to use those sorts of tests for model diagnostics.  Can you plot and post your residuals?
Comment: @DemetriPananos added requested plots
Comment: @DevonOliver Tough for me to say without any context for the problem
Comment: @DemetriPanano In general, I should plot deviance residuals against preds and if there is no pattern, I should consider it good to go? Other than the Chi-sq test you listed is there any formal test?
Comment: @DevonOliver Doesn't seem to be a pattern, but there is something up with the residuals.  That test is called a "Deviance goodness of fit test"
Comment: @DevonOliver I used a regular GLM.  If you are using a mixed model, they are likely evaluated differently.  I would suggest you talk to a statistician at your institution about this.  I cant help without understanding what we are modelling
Comment: This really helped my understanding; I think I got in my own head and went down a wormhole. I generally live in the Poisson (Neg. Bin) and Binomial world or have much cleaner data. I will be sticking to Pearson and deviance resid plots going forward. Thanks for advice
Answer: For checking the deviance goodness-of-fit statistic for a Generalized Linear Model like a Gamma Regression Model I recommend to follow the instructions on slide 18/19 of Technical University Munich respectively on slide 104 of Technical University Graz.
That is, if dispersion parameter disp can not be assumed to be '1', the residual deviance test, i.e. calculating the p-value, should be applied on the scaled deviance, since the scaled statistic follows the chi square distribution (as outlined in the cited slides), e.g.:
p.value = pchisq(myModel$deviance/summary(myModel$disp), df = myModel$df.residual, lower.tail = F)
Comment: Actually you should use `summary(myModel)$disp`


How to replace a particular column in a CSV with some string?

Question: Sorry for a really basic question. How to replace a particular column in a tab separated file with some string, say "xyz"?
e.g.
Input:
abc\t  def\t   \t   xyz
pqr\t  ert\t   \t   yut

Output:
abc\t  def\t   new_str\t   xyz
pqr\t  ert\t   new_str\t   yut

In short, the 3rd column in my file is empty and I want to replace it with a string.
I tied something like this:
awk '{$3="new_str"}1' test1.csv > test1_op.csv

but looks like it does not maintain the tabs. Also note that the file has 400 columns, so writing an awk command something like this:
awk -F, '{OFS=",";print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,...,$400}' in.csv > outfile.csv

I would like to avoid.
Thanks.
Answer: Since it's tab-delimited, you are on the right track by splitting on a tab, rather than awk's default of splitting on any whitespace (any combination of spaces, tabs, and possibly other more esoteric types). Once you've done that, you can assign directly to the column you want to change and just print $0 again.
awk -F$'\t' 'BEGIN {OFS="\t"} {$3="new_str"; print}' in.csv > outfile.csv

awk can also process variable assignments that appear in its input file list, so this is a little cleaner-looking:
awk '{$3="new_str"; print}' FS=$'\t' OFS=$'\t' in.csv > outfile.csv

Answer: This might work for you (GUN sed):
sed -i 's/\t/new_str&/3' file

Answer: It's not clear exactly how you want to deal with whitespace, but perhaps you just want:
awk '{$3="new_str"}1' FS=\\t OFS=\\t

Note that this discards the whitespace that was originally in $3.  You could keep it with either:
awk '{$3=$3"new_str"}1' FS=\\t OFS=\\t

or
awk '{$3="   new_str"}1' FS=\\t OFS=\\t

depending on your needs.