Bigcommerce Api - add sku to the base product without options

Question: I am using api to add products and i would like to add SKU to the products which is not possible. Is there any workaround for it.
As per  https://developer.bigcommerce.com/api/stores/v2/products/skus#create-a-product-sku the options is mandatory. But the products i created doesn't have options.
Any help will be appreciated.
Comment: Can you expand on the sample product you are using? If there are not options, then it sounds like it is a simple product. There is a SKU field at the product level that doesn't have to be at the a variant level.
Answer: In BigCommerce, product SKUs are referring to two things:

A variation of a product, which can contain options like size, color, etc.
SKU in the simple sense (an identifier).

For an example of (1), let's say you're selling a shoe that's size 10 (SKU: SHOE10), size 11 (SHOE11), and size 12 (SHOE12). The shoe is the product, the specific sizes you're buying are the SKUs. So these SKUs can have options like size, color, etc. SKU: SHOE10 has a size of 10.
If you have no options for your product, it sounds like you're not selling a variation, you're selling a single product. You want option (2). In this case, you want to use the products endpoint, not the SKU endpoint as you linked. You can add the sku that way. Here is what the product object looks like -- as you can see, you can pass in a value for "sku" when you create or update a product.


Baseball Home Run Flyout

Question: A batter hits the ball really high and runs the bases to home plate. However, one of the defending players catches the ball after the batter crosses home plate and the ball never touches the ground.
Would it be considered a flyout or a home run?
Answer: Kad's answer is correct -- any ball that has not touched the ground and is caught, regardless of the runner's position, is out by flyout.  However, I wanted to challenge the premise of the question.
This is an impossible scenario
This could never happen in any baseball game due to the physics of a flyball.  For example, this question has an answer for one of the highest flyballs from the 2019 season by Joey Gallo.  That flyball went over 200 feet up and had a hang time of 7.3 seconds.  My search results have yielded similar numbers for a top hang time for a flyball -- somewhere between 7 and 8 seconds in the air.  I'm no physics major, but even when factoring in spin, altitude, and an exceptionally hard-hit ball -- you aren't going to exceed 10 seconds of hang time on a flyball.
This HuffPost article breaks down the ideal path around the bases and the time required to do so.  They conclude that the ideal path would result in a total time of 16.7 seconds to round the bases.

The total time around the bases is about 16.7 seconds assuming maximum acceleration 10 feet per second per second, about 25 percent faster than following the baseline for 22.2 seconds (coming to a full stop at first, second, and third base), and about 6 percent faster than following a circular path for 17.8 seconds.

In fact, they provide the Guinness World Record for the fastest run around the base path.

The record time according to Guiness[sic] is 13.3 seconds, set by Evar Swanson in Columbus, Ohio, in 1932. His average speed around the bases was about 27 feet per second.

So even at world record speed with the maximum height on a fly ball, you would still be unable to complete the run prior to the ball being caught.
Comment: You could hit a ball onto one of the central Tropicana catwalks.  If it rolled around for a few seconds and then fell off, it could delay it enough while still remaining in play.  Never happened to my knowledge, but *almost* possible.  I'll bet umps wouldn't wait 10 seconds before calling the ball dead though.
Comment: Good point about the impossibility - you'd have to hit the ball to a height of over 700 feet to get a hang time of 13.3 seconds, *very* well beyond the record height of 200-300 feet.
Answer: He would be out. A home run is defined by a batter circling the bases in one play without being put out. Since the ball would still be in play even if he circled the bases, catching it would be an out.

Baseball Home Run Flyout


The equivalent condition to an element being invertible in a ring

Question: Show that an element $u$ of a ring is invertible with $v=u^{-1}$ if and only if $uvu=u$ and $v$ is the only element satisfying this condition. This is part of an exercise from Jacobson.
Answer: $u(1-vu+v)u=uvu=u$ and by uniqueness $1-vu+v=v$. Similarly, $u(1-uv+v)u=uvu=u$ implies $1-uv+v=v$. The proof completes.


HTTPS in IIS 5.1

Question: I'm using IIS 5.1 in Windows XP on my development computer. I'm going to set up HTTPS on my company's web server, but I want to try doing it locally before doing it on a production system.
But when I go into the Directory Security tab of my web site's configuration section, the "Secure communication" groupbox is disabled. Is there something I need to do to make this groupbox enabled?
Answer: You may need to manually create a certificate first (on WinXP there does not seem to be a built-in mechanism, so you need to use OpenSSL). Check out these two links:
Enabling SSL in IIS on Windows XP Professional
Enabling SSL (HTTPS) for IIS in Windows XP
Answer: That is because IIS 5.1 under the limited Windows XP version is limited to only HTTP.  You need to have a full version of IIS 6.0 on Windows 2003 to do this.  Luckily you can download a VHD image of Windows 2003 from Microsoft and run it under a Virtual PC instance.  Plus I would recommend this since you are trying to be careful and use a machine close to your production environment.  IIS 5.1 version is never deployed as a production machine so you cannot guarantee anything and the differences between IIS 5.1 and IIS 6.0 are significant enough where the VM is worth your while.

HTTPS in IIS 5.1


IIS TLS Certificate - Chrome says we are using "obsolete cryptography"

Question: We have installed a server certificate in IIS for a website. When browsing over HTTPS to the website and inspecting the icon using chrome, we get a message "Your connection ... is encrypted with obsolete cryptography".
How do I configure IIS so that Chrome stops displaying this message, also need to balance the need to support IE>=8.

[EDIT]: As per the screenshot, we can see that the encryption method used is "AES_256_CBC with SHA1 for message authentication". The question is how do we change this in IIS so that Chrome no longer complains about "Obselete Cryptography".
Answer: The answer Steffen gave is incorrect (although the link he provided does provide the answer if you read further down). The reason Chrome gives the error regarding obsolete cryptography in this case is due to AES in CBC mode.
It has nothing to do with having a SHA-1 certificate.
The TL;DR - ignore this error, it doesn't matter.
If you really want to get rid of the error then you need to enable AES GCM instead. However this is easier said than done. I answered this in full on serverfault recently - see the second half of my answer here;
https://serverfault.com/questions/683697/change-key-exchange-mechanism-in-iis-8/683705#683705
Answer: Since am new to SSL and certificates, I struggled with this too. Here's how we solved this issue. Note that in our case, we are working with an internal web application and use a self-signed certificate.

Using OpenSSL on Linux, create a private key:
openssl genrsa -out box.key 2048
Then create and sign a certificate with the key (we set the expire date for a year out and 10 days):
openssl req -new -x509 -sha256 -days 375 -key box.key -out box.crt
Answer the questions (make sure the Common Name matches the web server's FQDN)
Configure your web server to use SSL using this key and certificate
Using Chrome on Windows, enter your web sites HTTPS URL
Click on the lock icon in the address bar, then select the Certificate Information link in the popup
Go to the Details tab, select the Copy to File... button to launch the Certificate Export Wizard
Using the wizard, select PKCS #7 as the export format, and save the certificate (i.e. mykey.p7b)
Install the certificate in the Trusted Root Certification Authorities certificate store (use certmgr.msc or right click on the certificate and select Install Certificate
Close Chrome, logout and re-login to Windows (force the old site warning out of the cache)
Re-open Chrome and enter your web sites HTTPS URL
Admire your shiny green lock icon with modern cryptography
Comment: The secret sauce is the number of bits in the `open genrsa` command and the use of the `-sha256` engine in the `openssl req` command
Answer: You might want to read https://www.chromium.org/Home/chromium-security/education/tls#TOC-Deprecation-of-TLS-Features-Algorithms-in-Chrome, which was the first hit when looking for this specific error message.
It is hard to know for sure without having a look at your certificate, but I guess the following description from the linked page will match your certificate:

SHA-1 is deprecated in Chrome at the start of 2015.
  Certificates expiring in 2016 will be marked as "secure, but with minor errors".
  Certificates expiring in 2017 are later will be treated as "affirmatively insecure".
Comment: Sorry Steffen that's just not true. RSA cryptography is used to exchange encryption keys for symmetric cryptography, and it's the symmetric cryptography that Chrome is complaining about. As per my screenshot, the symmetric cryptography uses "AES_256_CBC with SHA-1 for message authentication", this is the bit that chrome does not like and which we need to change in IIS. (This is the bit I was hoping someone would me with).
Comment: OK. How does one change the cryptography used by IIS from SHA-1 to something else that will be acceptable to Chrome?
Comment: Cryptography is used on multiple places. It is not only used for key exchange and symmetric cryptography but also to validate the certificate chain. In this context (i.e. as a signature algorithm) SHA-1 is considered unsafe while in the context of symmetric cryptography (i.e. as a HMAC) SHA-1 is still considered safe. Thus the problem is the certificate and not the cipher.
Comment: This stuff was great to read! Out of curiosity, how did you get to solve this? Did the certificate vendor generate a new certificate for your website?
Comment: The problem is not IIS but your certificate.  Contact your certificate vendor about the problem. But note that this solution here is only a guess based on your incomplete information.
Answer: To answer my own question:

Ensure latest Windows Updates have been installed
Download and run IIS Crypto (https://www.nartac.com/Products/IISCrypto)
Ensure that this Cipher is top of the list on the left hand side:
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
Apply changes in IIS Crypto
Restart the server
Answer: In this link there are a black and a white lists about ciphers. Maybe if you just use the white ones it would solve your problem. Look after the lists in the comments you will see that it has change a little since the answer was written.
It helped me a lot when I started to have this problem with Glassfish, I hope it helps you with IIS too.


Automatically save in associated datatable

Question:
Possible Duplicate:
Correct Way to Set Default Values in Rails

I have two data tables:
1) User
2) Profile (which has the field user_id)
They are associated through:

User has_one Profile
Profile belongs_to User

Is there a possibility to save some default values in the profile table each time I create a new user?
Thanks for your help!
Answer: You can create default profile by using ActiveRecord callbacks.
Just create a method, and use it as :after_create
class User < ActiveRecord::Base

  has_one :profile

  after_create :create_default_profile

  def create_default_profile
    profile = build_profile
    # set parameters
    profile.save
  end

end

build_profile builds and links an instace of Profile, but doesn't save it. create_profile is the same, but it also saves the object. For the full description, see the ActiveRecord documentation.
You can add attributes to both build_ and create_profile as a hash, so you probably can reduce create_default_profile to one line:
def create_default_profile
  profile = create_profile :some => 'attirbute', :to => 'set'
end

Comment: I think this could work - but how could I link the new created profile to the user I have just created...I dont' get it. What do I have to fill in the create_default_profile method?
Comment: something in the create_default_profile like profile = Profile.new(user_id:self.id)
Comment: Yeah, it worked! Thanks a lot! You are awesome! I tried it with "user_id:self_id".
Comment: One last question: Why do I have to use self.id? Why does user.id does not work.
Answer: Yes, you can add default value for profile.
I am setting some values for member_standing and points attributes of profile for a user.
In create action for users controller
def create
  @user = User.new(params[:user])
  profile = @user.profiles.build(:member_standing => "satisfactory", :points => 0)
  if @user.save
    redirect_to @user
  else
    render "new"
  end
end

Comment: mmmh, when I am doing this I get the error message "undefined method `build' for nil:NilClass" for UsersController#create...


Using random forest for survival analysis with time varying covariates

Question: I've been trying to train a model that predicts an individual's survival time.
My training set is an unbalanced panel; it has multiple observations per individual and thus time varying covariates. Every individual is observed from start to finish so no censoring.
As a test, I used a plain random forest regression (not a random survival forest), treating each observation as if it were iid (even if it came from the same individual) with the duration as the target. When testing the predictions on a test set, the results have been surprisingly accurate.
Why is this working so well? I thought random forests needed iid observations.
Answer: Although there is structure to your data, it may be that the variation in baseline risk does not vary substantially enough among your subjects to cause a model without a frailty term to form poor predictions. Of course, it's perfectly possible that a model with a frailty term would perform better than the pooled random forest model.
Even if you did run a pooled and hierarchical model and the pooled model did as well or slightly better, you may still want to use the hierarchical model because the variance in baseline risk is very likely NOT zero among your subjects, and the hierarchical model would probably perform better in the long term on data that was in neither your test or training sets.
As an aside, consider whether the cross validation score you are using aligns with the goals of your prediction task in the first place before comparing pooled and hierarchical models. If your goal is to make predictions on the same group of individuals as in your test/training data, then simple k fold or loo cross validation on the response is sufficient. But if you want to make predictions about new individuals, you should instead do k fold cross validation that samples at the individual level. In the first case you are scoring your predictions without regard for the structure of the data. In the second case you are estimating your ability to predict risk within individuals that are not in your sample.
Lastly, remember always that CV is itself data dependent, and only an estimate of your model's predictive capabilities.
Answer: I am just starting to work with Random Forest but I believe it is mainly the bagging that needs to be iid for each tree and the subset of features selection at each node. I am unaware of any formal constraints on the data itself.
Why it works so well on your data I can not say until I have investigated your data.
But the non-iid'ness of your features will not influence performance too much.
Comment: I have questions about the basic validity of what you've described. A "survival" model where none of the observations are censored is a misnomer. In the absence of censoring, your data structure defaults to a standard regression, regardless of the functional form or the fact that duration varies. Then there's the issue of using random forests which does assume iid data. Why RFs? Why not use a multi-level model as outlined in Singer and Willet's Applied Longitudinal Data Analysis? S&W have a chapter on "survival" model approaches to multilevel data.


Automatic Validation Using drupal_form_submit

Question: I have a content type (call it my_type) with some required fields. One of the fields uses the email module, so if I try and create a my_type node using Drupal's built in node create page and I put 'notanemail' as the email address, the node will not be created and I get an error saying 'notanemail is not a valid email address'.
When I make a node programmatically using drupal_form_submit, it does not do the validation and the node is made even though I put incorrect values in fields.
I don't want to implement hook_validate if I can avoid it. I would rather use the build-in validation. Is this possible?
Comment: can you paste your code?
Answer: Field validation is made only against node form submission, so you need to imitate this in your code.
If you are using Drupal 6, try this solution:https://stackoverflow.com/a/6471821/1387163
For Drupal 7 solution can as following:
<code>$node = new StdClass();

$node->type = 'my_type';
node_object_prepare($node);

// assign node field values here ...

$form_state = array (
  'node' => $node,
  'values' => (array)$node,
);
$form = drupal_get_form($node->type. '_node_form', $node);

node_form_validate($form, $form_state);

$errors = form_get_errors();

if ($errors) {
   // ...
} else {
   // ...
}
</code>


Starting with a string AB. Is it possible to obtain BA following these rules?

Question: Starting with a string AB. One is allowed to add, or remove any occurrence of AAA, BB, or ABAB anywhere in the string . Is it possible to obtain BA?
My attempt at proof of impossibility below:
In the proof, I will write about "creating a string X from scratch". That means applying a sequence of the rules to the empty string and ending up with X.
Note, for example, that it is possible to create BABA from scratch. $ -> BB -> BABABB -> BABA$
Also note, that since all the rules can be applied in reverse, if one can given a string A, produce a string B - one can also given a string B, produce string A.
One consequence of this is that if you can create a string X from scratch, you can also "destroy it" i.e. apply a sequence of operations to a string containing X until you get an identical string not containing X.
It is impossible, however, to create string B from scratch. After all, all the rules increment, or decrement the number of B's by $2$ so, starting with no B it is impossible to arrive at one B.
More generally, starting with a string with $n$ B's it is impossible to end up with  a string containing $n+1$ or $n-1$ B's.
What about A? Can one create A from scratch? First of all, if one could create A from scratch than the puzzle would be solved. $AB -> B - > BA$
More importantly though, if you can solve the puzzle, you can create A.
Start with $AB -> ABABAB -> AABBAB  -> AAAB -> B$.
This took AB and ended up with B, destroying A in the process. Of course one can also create A if the process is reversed.
Thus, by contrapositive, if A cannot be created, the puzzle cannot be solved.
There are only two ways one could conceivably create A. One of them is use AAA rule then do some magic and then remove ABAB.
The other way is to use ABAB twice getting ABABABAB then do some magic and subtract AAA.
The other ways are just simple variants of these.
Both of these are impossible because, in ABAB the A's are one B apart this distance cannot be reduced. None of the rules can be used to decrease this distance as you can just insert strings and remove them at will but reducing the distance would amount to the transformation $ABA -> AA$ which is impossible (as proved earlier).
So the A cannot be created from scratch and thus the puzzle cannot be solved.
Comment: Very cool problem!
Answer: As for the proof-verification, let me try to swallow your idea.

A string is said to be created from scratch if it can be created from the empty string $\varnothing$ by applying the rules finitely many times.
$B$ cannot be created from scratch because each rule preserves the parity of the number of $B$'s, and $B$ and $\varnothing$ have different parities.
If $BA$ can be obtained from $AB$, then $A$ can be created from scratch by
$$ \varnothing \to AAA \to AABBA \to ABABA \to A $$
So it suffices to prove that $A$ cannot be  created from scratch.

Now it is not entirely transparent to me how your argument on the impossibility of $\varnothing \to \cdots \to A$ works. Perhaps this is because I am not thinking hard enough to grasp the idea, but in any case, supplying some details seems no harm to the argument.

Meanwhile, here is another proof of the impossibility: Let $f_A(z) = 1 - \frac{1}{z}$ and $f_B(z) = 1 - z$. For each string $a_1\cdots a_n$ with $a_i \in \{A, B\}$, we define
$$ \phi(a_1\cdots a_n) = f_{a_1}\circ \cdots \circ f_{a_n}, \qquad \phi(\varnothing) = [z \mapsto z], $$
where $\varnothing$ is the empty string. Then we easily find that

For two strings $S_1, S_2$ and their concatenation $S_1 S_2$, we have $\phi(S_1 S_2) = \phi(S_1)\circ\phi(S_2)$.
$\phi(AAA) = \phi(BB) = \phi(ABAB) = \phi(\varnothing)$.

So the value of $\phi$ does not change when we apply the rules to the string, hence the value of $\phi$ is an invariant. But since
$$\phi(AB) = \left[ z \mapsto \frac{z}{z-1} \right], \qquad \phi(BA) = \left[ z
\mapsto \frac{1}{z} \right], $$
we have $\phi(AB) \neq \phi(BA)$. Therefore $BA$ cannot be obtained from $AB$ by the rules.
Comment: It is true, the argument that empty -> A is impossible is shaky. I will try to find a better one.
Comment: Following the same idea, I find another possible construction (maybe more geometrically) on the complex plane $\mathbb{C}$ is: $f_A(z) = z \cdot \omega$, $f_B(z) = -z$, where $\omega = \exp(i \cdot \frac{2\pi}{3})$. The two operators correspond to the reflection and rotating $2\pi/3$, and do not commute.
Answer: A quick proof using group theory:
Construct group $G=\langle A,B\mid A^3=1,B^2=1,ABAB=1\rangle$.
Showing that $BA$ cannot be obtained from $AB$ using the rules specified in the questions is equivalent to showing that within $G$, $AB\neq BA$.
The latter follows directly from the fact that the dihedral group of order $6$, $D_3$, has presentation $\langle r,a\mid r^{3}=1,a^{2}=1,ara=r^{{-1}}\rangle $, and that $ar$ and $ra$ are distinct elements of $D_3$.
Q.E.D.
P.S. I can add the proof that $D_3$ has presentation $\langle r,a\mid r^{3}=1,a^{2}=1,ara=r^{{-1}}\rangle $ if needed.


Calculate EWMA covariances and correlations in R

Question: Do you know where, in which package, I can find cov.EWMA and/or covEWMA funtion used in http://faculty.washington.edu/ezivot/econ589/econ589multivariateGarch.r for R?
Thank you.
Comment: Just google it! [This is what I found](https://r-forge.r-project.org/scm/viewvc.php/pkg/factorAnalytics/R/covEWMA.R?view=markup&root=factoranalytics&pathrev=14)
Comment: It's being sourced: `source("covEWMA.r")`. You need to... aaaaw, Jilber beat me to it.
Comment: @Jilber please post this as an answer (include code to prevent deletion of link only answer :) ).
Comment: Install the packages listed and use `getAnywhere()`
Answer: Searching the web I found this code on R-Forge.
<code>covEWMA <- function(factors, lambda=0.96, return.cor=FALSE) {
## Inputs:
## factors    N x K numerical factors data.  data is class data.frame
##            N is the time length and K is the number of the factors.
## lambda     scalar. exponetial decay factor between 0 and 1.
## return.cor Logical, if TRUE then return EWMA correlation matrices
## Output:
## cov.f.ewma  array. dimension is N x K x K.
## comments:
## 1. add optional argument cov.start to specify initial covariance matrix
## 2. allow data input to be data class to be any rectangular data object

if (is.data.frame(factors)){
  factor.names  = colnames(factors)
  t.factor      = nrow(factors)
  k.factor      = ncol(factors)
  factors       = as.matrix(factors)
  t.names       = rownames(factors)
} else {
  stop("factor data should be saved in data.frame class.")
}
if (lambda>=1 || lambda <= 0){
  stop("exponential decay value lambda should be between 0 and 1.")
} else {
  cov.f.ewma = array(,c(t.factor,k.factor,k.factor))
  cov.f = var(factors)  # unconditional variance as EWMA at time = 0
  FF = (factors[1,]- mean(factors)) %*% t(factors[1,]- mean(factors))
  cov.f.ewma[1,,] = (1-lambda)*FF  + lambda*cov.f
  for (i in 2:t.factor) {
    FF = (factors[i,]- mean(factors)) %*% t(factors[i,]- mean(factors))
    cov.f.ewma[i,,] = (1-lambda)*FF  + lambda*cov.f.ewma[(i-1),,]
  }

}
  # 9/15/11: add dimnames to array
  dimnames(cov.f.ewma) = list(t.names, factor.names, factor.names)

  if(return.cor) {
   cor.f.ewma = cov.f.ewma
   for (i in 1:dim(cor.f.ewma)[1]) {
    cor.f.ewma[i, , ] = cov2cor(cov.f.ewma[i, ,])
   }
   return(cor.f.ewma)
  } else{
      return(cov.f.ewma)
  }
}
</code>
Comment: Thanks! I saw this when I googled the topic, but didn't try it. I'm still new to R. I make too many mistakes. It's working perfectly now. Thanks a lot!


Heatplot/enrichGO, fold change display & order of genes

Question: Hello I'm working on the heatplot function offered in enrichPlot GO over-representation test (in R).
I was wondering if I could get some help with the following issues:

In what format should the 'geneList' in the 'foldChange=geneList' specification be? I can only get black and white results & not the colour scaled ones -When I tried to add the list of my DE genes (in my case 'fpkm_allGDE_up_345$Ens_ID_merge') I was getting the message:'Error: Discrete value supplied to continuous scale'.
It only worked when I set 'foldChange=fpkm_allGDE_up$FOLD_CHANGE' but then with no colorscale.

Is it possible to rank the genes on the x axis so as that genes associated with more GO terms (of the ones indicated) are first?

Here's what I tried:
egoall_up <- enrichGO(gene          = fpkm_allGDE_up_345$Ens_ID_merge, #DEgenes_posttreatment
                      universe      = fpkm_allG_345$Ens_ID_merge,       #all genes expressed
                      keyType       = "ENSEMBL",
                      OrgDb         = org.Hs.eg.db,
                      ont           = "ALL",
                      pAdjustMethod = "BH",
                      pvalueCutoff  = 0.01,
                      qvalueCutoff  = 0.05,
                      readable      = TRUE)

>heatplot(egoall_up, foldChange=fpkm_allGDE_up$FOLD_CHANGE,
            showCategory=10)

head(fpkm_allGDE_up)

Answer: Not sure if you figured this out already but I ran into the same issue. What worked for me was to change my 'geneList' into a named numeric vector.
To do this I took the gene names from my data frame and the Fold Change values and used the 'setNames' function.
ie
geneList<- setNames(mydf$foldchange,
mydf$Genes)
when you put this into the heatplot() function it works like a charm!
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


How to construct an array of incrementing subsets in Matlab

Question: In Matlab, say you have a large vector X
X = [1 2 3 4 5 6 ... 1000]

How would you select an array of K element subsets with incrementing indices? (No for loops please).
k = 100; % 100 element subsets
Y = foo(X,k);

>> Y =
        1   2   3 ... 100
      101 102 103 ... 200
      201 202 203 ... 300
       .   .   .  ...  .
       .   .   .  ...  .
       .   .   .  ...  .
      901 902 903 ... 1000

Thanks
-----Update--------
Thanks for the quick reply.  I hate it when ask stupid questions.
Now, I have a more challenging one (what I really wanted to know).
Given:
X = [1 2 3 4 5 6 ... 1000];
k = 900;

How do you produce?
Y = foo(X,k);

>> Y = 1   2   3 ... 900
       2   3   4 ... 901
       3   4   5 ... 902
       .   .   . ...  .
       .   .   . ...  .
       .   .   . ...  .
      100 101 102... 1000

Thanks again
Comment: Updated the question.  Thanks to Luis and the others.
Answer: Very easy: use reshape:
X = 1:1000;
k = 100;
Y = reshape(X,k,[]).';

Or, if you have the Communications Toolbox, you can use vec2mat:
Y = vec2mat(X,k);

Comment: What can I say? ["You're right. When you're right, you're right, and you're right!"](http://en.wikiquote.org/wiki/Chinatown_(film)). This was an easy one... :)
Comment: @chappjc Very easy, yes. I didn't know that quote! :-)
Comment: It came right to mind when I read this Q&A... Chinatown. Seriously though, I tried to come up with a clever alternative, but this just seems like one of those cases where there's just one sensible solution.  Maybe someone will prove me wrong?
Comment: @chappjc I bet you could do it with `accumarray`! :-D


Intersection of prime ideals in commutative ring

Question: The result may be well-known, in general form; but I faced difficulty in a simple case of the result. (Instead of referring to a result, I tried myself in some arguments, but came to some problems, and I want to solve these small problems I faced.)

Lemma: If $P_1,P_2,\ldots,P_k$ are prime ideals in a commutative ring $R$ with unity, and if $P_1\cap \cdots \cap P_k:=P$ is prime, then $P=P_i$ for some $i$.

Proof: Consider the natural map $f:R\rightarrow \frac{R}{P_1} \oplus \cdots \oplus \frac{R}{P_k}$; it is a ring homomorphism, with $\ker f=P_1\cap \cdots \cap P_k=P$ (prime, by assumption).
Thus, $f$ factors through $\overline{f}:\frac{R}{P} \rightarrow \frac{R}{P_1} \oplus \cdots \oplus \frac{R}{P_k}$, and this is injective.
Since $R/P$ is integral domain, so image of $\overline{f}$ should go inside $\frac{R}{P_i}$ for some $i$ (am I right? I couldn't properly justify this!)
Suppose $Im(f)\subseteq \frac{R}{P_1}$.
This forces that $\ker f\supseteq P_2\cup \cdots P_k$.
Thus, $P=P_1\cap P_2\cap \cdots \cap P_k\supset P_2\cap \cdots \cap P_k$. From this, we see that $P_1\supseteq P_2\cap \cdots \cap P_k$.
Question $1$. How should I proceed next?
Question $2$. Can one suggest some clear statements, via the CRT approach above, for the proof of Lemma?
Comment: What makes you think that the image is contained in $R/P_i$ for some $i$? That makes no sense. Actually, if the ideals $P_i$ are pairwise coprime then $\bar{f}$ is an isomorphism. Anyway, this theorem has an easy proof, you don't need to use this homomorphism $f$.
Comment: @Mark: Suppose we have a direct sum of two integral domains $R_1\oplus R_2$, which we make into a ring by pointwise addition and multiplication. If $S$ is a subring of this ring with same multiplicative identity, and if $S$ is integral domain, is it not true that $S\subset R_1\oplus 0$ or $S\subset 0\oplus R_2$? (This I thought intuitively).
Comment: No, that's not true. For example, if $R_1=R_2=R$ then you can take the diagonal $S=\{(r,r): r\in R\}$. This is a subring isomorphic to $R$, and in particular an integral domain.
Comment: What's the point to use CRT to prove such a trivial result that follows immediately from the definition of prime ideals?
Comment: @user26857: $R/P_1\cap\cdots \cap P_k$ will be integral domain and sitting inside direct sums of integral domains; it pops in mind naturally to see "what happens by CRT". (I mentioned in the first lines clearly what is my doubt; I pointed out that, I want to understand gaps in my specific way of understanding, but not any alternate  proof of the lemma. The lemma is easy consequence of a small lemma (1.11 perhaps) in Atiyah-MacDonald's book, which I verified. )
Answer: To put it more starkly, suppose each $P_i $ contains an element $x_i$ that is not in $P$.
Notice that $\prod_i x_i\in\bigcap_i P_i=P$.
Therefore, one of the $x_i$ is in $P$. Contradiction.
Answer: If $P\neq P_1$, then you can take an element $a\in P_1$ that is not in $P$. Then
$a(P_2\cap \cdots \cap P_n)\in P$
but $P$ is prime and $a\notin P$, so that
$P_2\cap \cdots \cap P_n\subseteq P$
that means
$P_2\cap \cdots \cap P_n= P$
Now you can go on supposing that $P\neq P_2$.
Thus at the end you will have that $P$ is equal to some $P_i$


How will I connect my search query to my ionic app?

Question: I have this query for searching multiple data but it is only static
user_model.php (coeigniter)
public function get_halal()
{
    $term = "Buko,Beef,Sugar";
    $terms = explode(',', $term);

    foreach($terms as $term){

    $this->db->select('*');
    $this->db->from('recipe');
    $this->db->join('menu', 'menu.recipe_id = recipe.recipe_id');
    $this->db->join('ingredient', 'ingredient.ingredient_id = menu.ingredient_id');
    $this->db->where('menu.category_id = 2');
    $this->db->like('ingredient.name', $term);
    $query = $this->db->get()->result();
   }
    return $query;
}

I want it to be dynamic and is connected to my ionic app. How would I do that?
Comment: parse `$term` as an argument?
Answer: When you think to create a function (or a class), first of all you have to abstract the question to realize how much this function is useful in different context. There are no rules, it's depend on your context and your goals.
In your example, i.e., the function return a database query object for terms "Buko", "Beef" and "Sugar" (de facto, only for "Sugar"). If you modify your function in this way:
public function get_halal( $what )

you can reuse the function to search any terms.
If you modify the function in this way:
public function get_halal( $what )
{
    if( is_array($what) ) ...
    else                  ...

you can use the same function to search for one or many terms.
If you modify the function in this way:
public function get_halal( $what, $where )

you can search a term in various field.
There are a lot of possibility, it's the best fun of coding.


kubelet breaks CRI standards by running containers in 'k8s.io' containerd namespace?

Question: Kubernetes pods run in the 'k8s.io' namespace of containerd. This 'runtime namespace' concept is containerd specific and not a part of CRI.
If kubelet truly follows the CRI standard, then it must not be able to run containers in such containerd namespaces.
crictl does not support this 'runtime namespace' thing and therefore can only communicate to containerd in the default namespace.
This qualifies for a bug report?
Answer: The Kubernetes Container Runtime Interface (CRI) defines the main gRPC protocol for the communication between the node components kubelet and container runtime.Your container runtime must support at least v1alpha2 of the container runtime interface.
crictl provides a CLI for CRI-compatible container runtimes. This allows the CRI runtime developers to debug their runtime without needing to set up Kubernetes components. This is an expected behaviour in kubernetes v1.29, the kubelet prefers to use CRI v1. If a container runtime does not support v1 of the CRI, then the kubelet tries to negotiate any older supported version. If the kubelet cannot negotiate a supported CRI version, the kubelet gives up and doesn't register as a node.
crictl is currently in Beta and still under quick iterations. It is hosted at the cri-tools repository. Github Community encourages the CRI developers to report bugs or help extend the coverage by adding more functionalities.
Comment: This is not a cri-tools issues. This is a problem with the CRI standard itself or the kubelet implementation of it.
Comment: @user2061812, This is expected behaviour, if the kubernetes is not upgraded, the kubelet will select the older version of CRI which allows all the namespaces for running containers. You can report the behaviour [here](https://discuss.kubernetes.io/) for the CRI.
Comment: Neither old nor new version of CRI support container runtime namespaces.


Criar um filtro utilizando Jquery

Question: Estou fazendo um filtro em jquery mas estou errando na minha lógica em algum lugar e não estou conseguindo sair do lugar. O meu filtro não está sumindo com algumas palavras que eu digito, ele me traz o bloco inteiro, mesmo a palavra digitada nao estando no item. estou com dificuldades pra resolver.
Esse é o portal : http://www.enap.gov.br/web/pt-br/perguntas-frequentes
Esse é o meu script (só jogar no console da página pra testar)
<code>$("input[name='_3_keywords']").keyup(function() {

    var palavrasChave = $("input[name='_3_keywords']").val();
    if (palavrasChave.trim() !== "") {
        var content = document.querySelectorAll('.asset-full-content.show-asset-title');
        content.forEach((element) => {
            element.style.display = 'none';
        });
        $(".taglib-header").hide();
        var $elements = $(".taglib-header:contains(" + palavrasChave + ")");
        $elements.each((index) => {
            $elements[index].nextElementSibling.style.display = 'block';
        });
        $elements.show();

        var $elementsContent = $(".asset-full-content:contains(" + palavrasChave + ")");
        $elementsContent.each((index) => {
            $($elementsContent[index]).show();
            console.log($($elementsContent[index]).prev());
            $($elementsContent[index]).prev().show(); $elementContent.style.display = 'none';

        });
    } else {
        var elements = $(".taglib-header");
        elements.show();
        elements.each((index) => {
            elements[index].nextElementSibling.style.display = 'none';
        });
    }
});
</code>
Answer: Olá
Creio que foi um simples na hora de definir o último objeto a dar display none
Testa assim
<code> $("input[name='_3_keywords']").keyup(function() {

    var palavrasChave = $("input[name='_3_keywords']").val();
    if (palavrasChave.trim() !== "") {
        var content = document.querySelectorAll('.asset-full-content.show-asset-title');
        content.forEach((element) => {
            element.style.display = 'none';
        });
        $(".taglib-header").hide();
        var $elements = $(".taglib-header:contains(" + palavrasChave + ")");
        $elements.each((index) => {
            $elements[index].nextElementSibling.style.display = 'block';
        });

        var $elementsContent = $(".asset-full-content:contains(" + palavrasChave + ")");
        $elementsContent.each((index) => {
            $($elementsContent[index]).show();
            $($elementsContent[index]).find(".painel-faq").css( "display", "none");

            var itens = $($elementsContent[index]).find(".painel-faq .panel-title a:contains("+palavrasChave +")");
            itens.each((index) => {
               $(itens[index]).show();
$(itens[index]).parent().parent().parent().css("display","block")
            });

            $($elementsContent[index]).prev().show();
            $($elementsContent[index]).style.display = 'none';

        });
    } else {
        var elements = $(".taglib-header");
        elements.show();
        elements.each((index) => {
            elements[index].nextElementSibling.style.display = 'none';
        });
      $('.painel-faq').show();
    }
});
</code>
Comment: PauloHDSouza , o problema é que mesmo que eu digite "pesquisa" ele me traz o bloco inteiro. no caso "Bloco de Pesquisa" , nesse bloco o item 6 nao deveria vir na pesquisa, mas ele vem junto com o bloco, mesmo nao tendo nenhum palavra "pesquisa".
Comment: Você  quer que venha O BLOCO com os itens ou só os itens dentro do bloco?

Você está filtrando os itens dentro do bloco ou o bloco?
Comment: A minha lógica era aparecer no caso, apenas os blocos com os itens que contenham a palavra digitada.  Se o bloco tem 10 itens , e apenas 2 tem a palavra pesquisa , o resto ficaria em display:none. ai se o cara apagasse na busca , voltaria tudo.
Comment: Você está filtrando o TITULO do BLOCO, você quer filtrar OS ITENS do bloco? é isso?
Comment: Na verdade teria que ser filtrado os dois. O cara poderia procurar pela palavra do titulo e do bloco.
Comment: Testa e vê se é isso
Comment: Tá faltando pouco, mas fiz vários testes e tá bugando ao fazer a pesquisa. Ex: se vc fizer a pesquisa , ele acha quase todos , mas no último bloco - Casoteca de Gestão Publica, se você digitar "notas" ele não acha. Ainda não entendi o porque.E ao fazer a pesquisa e apagar no campo de busca, o itens não voltam, ficam apenas o itens que você procurou, ou seja , ele não recupera todos itens do bloco após a pesquisa.
Comment: @Thiagolourenço edições que alterem código ou o sentido do post não são recomendadas neste site, sempre opte por informar o autor, por mais que o erro seja explicito.

Criar um filtro utilizando Jquery


I have a fragment container view in my mainactivity, I want to navigate through fragments when click back button

Question: override fun onBackPressed() {

        findNavController(R.id.fragmentContainerView2).popBackStack()
    }

this is the code I'm using for backstack navigation but the app don't exit on home fragment, and if I press back button on first fragment, the app should close.   How to do this?
This is My mainactivity.xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/motion_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutDescription="@xml/activity_main_scene2">

    <ImageView
        android:id="@+id/imageView7"
        android:layout_width="60dp"
        android:layout_height="50dp"
        android:contentDescription="@string/logo"
        android:src="@drawable/notification_icon"
        app:layout_constraintBottom_toBottomOf="@+id/imageView8"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/imageView8" />

    <ImageView
        android:id="@+id/image8"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:layout_marginStart="15dp"
        android:background="@color/white"
        android:contentDescription="@string/navigation_drawer"
        android:src="@drawable/three_lines"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/thehelfen"
        android:textColor="@color/black"
        android:textSize="20sp"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.fragment.app.FragmentContainerView
            android:id="@+id/fragmentContainerView2"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="55dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/navigation2" />

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="300dp"
        android:layout_height="match_parent"
        app:cardBackgroundColor="@color/white"
        app:cardElevation="150dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/logo"
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:clickable="true"
                android:contentDescription="@string/logo"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/person"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/my_profile"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:text="@string/my_profile"
                android:textColor="@color/black"
                android:textSize="35sp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/logo" />

            <ImageView
                android:id="@+id/icon1"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_margin="25dp"
                android:clickable="true"
                android:contentDescription="@string/icon"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/consultnow"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/my_profile" />

            <TextView
                android:id="@+id/consultnow"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20dp"
                android:clickable="true"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:text="@string/consult_now"
                android:textColor="@color/black"
                android:textSize="20sp"
                app:layout_constraintBottom_toBottomOf="@+id/icon1"
                app:layout_constraintStart_toEndOf="@+id/icon1"
                app:layout_constraintTop_toTopOf="@+id/icon1" />

            <ImageView
                android:id="@+id/icon2"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_margin="25dp"
                android:clickable="true"
                android:contentDescription="@string/icon"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/booklabtest"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/icon1" />

            <TextView
                android:id="@+id/booklabtest"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20sp"
                android:clickable="true"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:text="@string/book_lab_test"
                android:textColor="@color/black"
                android:textSize="20sp"
                app:layout_constraintBottom_toBottomOf="@+id/icon2"
                app:layout_constraintStart_toEndOf="@+id/icon2"
                app:layout_constraintTop_toTopOf="@+id/icon2" />

            <ImageView
                android:id="@+id/icon3"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_margin="25dp"
                android:clickable="true"
                android:contentDescription="@string/icon"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/bookhealthpackage"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/icon2" />

            <TextView
                android:id="@+id/bookhealth"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20sp"
                android:clickable="true"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:text="@string/book_health_npackages"
                android:textColor="@color/black"
                android:textSize="20sp"
                app:layout_constraintBottom_toBottomOf="@+id/icon3"
                app:layout_constraintStart_toEndOf="@+id/icon3"
                app:layout_constraintTop_toTopOf="@+id/icon3" />

            <ImageView
                android:id="@+id/icon4"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_margin="25dp"
                android:clickable="true"
                android:contentDescription="@string/icon"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/info_icon"
                app:layout_constraintBottom_toTopOf="@+id/contact_icon"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/about"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20sp"
                android:clickable="true"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:text="@string/about_us"
                android:textColor="@color/black"
                android:textSize="20sp"
                app:layout_constraintBottom_toBottomOf="@+id/icon4"
                app:layout_constraintStart_toEndOf="@+id/icon4"
                app:layout_constraintTop_toTopOf="@+id/icon4" />

            <ImageView
                android:id="@+id/contact_icon"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_margin="25dp"
                android:clickable="true"
                android:contentDescription="@string/icon"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/contact_us"
                app:layout_constraintBottom_toTopOf="@+id/icon5"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/contact_us"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20sp"
                android:clickable="true"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:text="@string/contact_us"
                android:textColor="@color/black"
                android:textSize="20sp"
                app:layout_constraintBottom_toBottomOf="@+id/contact_icon"
                app:layout_constraintStart_toEndOf="@+id/contact_icon"
                app:layout_constraintTop_toTopOf="@+id/contact_icon" />

            <ImageView
                android:id="@+id/icon5"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_margin="25dp"
                android:clickable="true"
                android:contentDescription="@string/icon"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/faq"
                app:layout_constraintBottom_toTopOf="@+id/icon6"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/faq"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20sp"
                android:clickable="true"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:text="@string/faqs"
                android:textColor="@color/black"
                android:textSize="20sp"
                app:layout_constraintBottom_toBottomOf="@+id/icon5"
                app:layout_constraintStart_toEndOf="@+id/icon5"
                app:layout_constraintTop_toTopOf="@+id/icon5" />

            <ImageView
                android:id="@+id/icon6"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_margin="25dp"
                android:clickable="true"
                android:contentDescription="@string/icon"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/tandc"
                app:layout_constraintBottom_toTopOf="@+id/icon7"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/termsandconditions"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20sp"
                android:clickable="true"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:text="@string/terms_and_conditions"
                android:textColor="@color/black"
                android:textSize="20sp"
                app:layout_constraintBottom_toBottomOf="@+id/icon6"
                app:layout_constraintStart_toEndOf="@+id/icon6"
                app:layout_constraintTop_toTopOf="@+id/icon6" />

            <ImageView
                android:id="@+id/icon7"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_margin="25dp"
                android:clickable="true"
                android:contentDescription="@string/icon"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/log_out"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/log_out"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20sp"
                android:clickable="true"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:text="@string/log_out"
                android:textColor="@color/black"
                android:textSize="20sp"
                app:layout_constraintBottom_toBottomOf="@+id/icon7"
                app:layout_constraintStart_toEndOf="@+id/icon7"
                app:layout_constraintTop_toTopOf="@+id/icon7" />

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.motion.widget.MotionLayout>

This is my motionscene file
<?xml version="1.0" encoding="utf-8"?>
<MotionScene
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetEnd="@+id/end"
        motion:constraintSetStart="@id/start"
        motion:duration="500">
       <KeyFrameSet>
           <KeyAttribute
               motion:motionTarget="@+id/cardView"
               motion:framePosition="0"
               android:translationX="-300dp"/>
           <KeyAttribute
               motion:motionTarget="@+id/cardView"
               motion:framePosition="0"
               android:translationX="0dp"/>
       </KeyFrameSet>

        <OnSwipe
            motion:targetId="@+id/imageView8"
            motion:autoCompleteMode="continuousVelocity"
            motion:dragDirection="dragRight"
            motion:maxAcceleration="20"
            motion:maxVelocity="20"/>

    </Transition>

    <ConstraintSet android:id="@+id/start">

        <Constraint
            android:layout_height="wrap_content"
            android:layout_marginTop="7dp"
            motion:layout_constraintTop_toTopOf="parent"
            android:layout_width="wrap_content"
            motion:layout_constraintEnd_toStartOf="@+id/imageView7"
            android:id="@+id/textView5"
            motion:layout_constraintStart_toEndOf="@+id/image8" />
        <Constraint
            android:id="@+id/image8"
            android:layout_width="55dp"
            android:layout_height="55dp"
            android:layout_marginStart="15dp"
            android:background="@color/white"
            android:src="@drawable/three_lines"
            motion:altSrc="@drawable/cancel_icon"
            motion:layout_constraintStart_toStartOf="parent"
            motion:layout_constraintTop_toTopOf="parent" />
        <Constraint
            android:id="@+id/fragmentContainerView2"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="55dp"
            motion:layout_constraintBottom_toBottomOf="parent"
            motion:layout_constraintEnd_toEndOf="parent"
            motion:layout_constraintHorizontal_bias="0.5"
            motion:layout_constraintStart_toStartOf="parent"
            motion:layout_constraintTop_toTopOf="parent"
            motion:navGraph="@navigation/navigation2" />
    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
        <Constraint
            android:layout_height="wrap_content"
            android:layout_marginTop="0dp"
            android:visibility="invisible"
            motion:layout_constraintTop_toTopOf="parent"
            android:layout_width="wrap_content"
            motion:layout_constraintEnd_toStartOf="@+id/imageView7"
            android:id="@+id/textView5"
            motion:layout_constraintStart_toEndOf="@+id/image8" />
        <Constraint
            android:id="@+id/image8"
            android:layout_width="55dp"
            android:layout_height="55dp"
            android:layout_marginStart="300dp"
            android:background="@color/white"
            android:src="@drawable/three_lines"
            motion:altSrc="@drawable/cancel_icon"
            motion:layout_constraintStart_toStartOf="parent"
            motion:layout_constraintTop_toTopOf="parent" />
        <Constraint
            android:id="@+id/fragmentContainerView2"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="250dp"
            android:layout_height="750dp"
            android:layout_marginTop="55dp"
            android:layout_marginStart="400dp"
            motion:layout_constraintBottom_toBottomOf="parent"
            motion:layout_constraintEnd_toEndOf="parent"
            motion:layout_constraintHorizontal_bias="0.5"
            motion:layout_constraintStart_toStartOf="parent"
            motion:layout_constraintTop_toTopOf="parent"
            motion:navGraph="@navigation/navigation2" />

    </ConstraintSet>
</MotionScene>

This is my main activity.kt file
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val contactus = findViewById<TextView>(R.id.contact_us)
        val drawer = findViewById<ImageView>(R.id.image8)
        val tandc = findViewById<TextView>(R.id.termsandconditions)
        val motionLayout = findViewById<MotionLayout>(R.id.motion_layout)

        contactus.setOnClickListener {

            supportFragmentManager.beginTransaction().apply {
                replace(R.id.fragmentContainerView2, contact_us_fragment())
                commit()

                motionLayout.transitionToStart()
            }
        }
        drawer.setOnClickListener {

            motionLayout.transitionToEnd()
            motionLayout.transitionToStart()
        }
        tandc.setOnClickListener {
            supportFragmentManager.beginTransaction().apply {
                replace(R.id.fragmentContainerView2, TandCFragment())
                commit()

                motionLayout.transitionToStart()

            }
        }
    }
}

Is it possible to set different navigation scenarios like from about_us fragment to home fragment and so on
Comment: Navigation already hooks up to the system back button if you [follow the Getting Started guide](https://developer.android.com/guide/navigation/navigation-getting-started#add-navhostfragment) and use `app:defaultNavHost="true"` in your XML - you should never have to override `onBackPressed()`.
Comment: It's not working sir, the problem is, I have made a custom navigation drawer using motion layout, so, there are many other views other than fragment container view in my main activity. So,whenever I'm clicking back button on any fragment the app simply terminate. It works perfectly when I only have fragment container view in my main activity. Please guide me why it's not working with other views and how do I impliment backstack navigation.
Comment: So if you know it works in one case, then you add in some other code and it breaks, then the problem is with your other code, but you haven't included that code in your question. How are we supposed to know what to suggest?
Comment: I'm so sorry Sir,
I have updated my Question. Please go through it.
Thank You
Answer: When using the Navigation Component and a NavHostFragment, you never, ever do a FragmentTransaction. Instead you should follow the guide to navigate to a destination that is in your navigation graph (your navigation/navigation2.xml you've set on your NavHostFragment.
contactus.setOnClickListener {
    // Use the Kotlin extension on Activity
    // to get a reference to your NavController
    val navController = findNavController(R.id.fragmentContainerView2)

    // Use the android:id associated with your contact_us_fragment
    // that needs to be in your navigation graph XML file
    navController.navigate(R.id.contact_us_fragment)

    motionLayout.transitionToStart()
}

Comment: Thank You So Much Sir, This is the simplest way. I'm new to coding and android development. Slowly understanding things. Thanks for helping me.


How to show $\sum_{k=1}^{80} {1 \over \frac{k}{81} - \frac{1}{2} - \frac{\iota}{2}} + {1 \over \frac{k}{81} - \frac{1}{2} +\frac{\iota}{2}} = 0$?

Question: I came across this sum while doing the homework my teacher gave us on series. It was originally $$a_k = \frac{k}{81}, S = \sum_{k=1}^{80} {a_k^2 \over 1+2a_k^2-2a_k}$$
I then decomposed it into partial fractions and ended up with
$40+ \sum_{k=1}^{80} {1 \over \frac{k}{81} - \frac{1}{2} - \frac{\iota}{2}} + {1 \over \frac{k}{81} - \frac{1}{2} +\frac{\iota}{2}}$. I know the answer is 40 from WolframAlpha, however I don't know how to go about showing that the sum with the complex numbers is 0.
How should I proceed?
Answer: There is no need to use complex numbers. Here the keyword is symmetry: note that $a_{81-k}=1-a_k$ and therefore
\begin{align}
2S&=\sum_{k=1}^{80} \frac{a_k^2}{1-2a_k(1-a_k)}+\sum_{k=1}^{80} \frac{a_{81-k}^2}{1-2a_{81-k}(1-a_{81-k})}\\
&=\sum_{k=1}^{80} \frac{a_k^2}{1-2a_k(1-a_k)}+\sum_{k=1}^{80} \frac{(1-a_k)^2 }{1-2(1-a_k)a_k}\\
&=\sum_{k=1}^{80} \underbrace{\frac{a_k^2+(1-a_k)^2}{1-2a_k(1-a_k)}}_{=1}=80
\end{align}
which implies that $S=40$.
Comment: Thanks. It's so clear once you notice that. I'll be sure to look out for those kinds of symmetries
Answer: Notice that :
$$S = \sum_{k = 1}^{80} \dfrac{k^2}{81^2 + 2 k^2 - 2 \times 81 \times k} = \sum_{k = 1}^{80} \dfrac{k^2}{(81 - k)^2 + k^2}$$
and :
$$\sum_{k = 1}^{80} \dfrac{k^2}{(81 - k)^2 + k^2} = \sum_{k = 1}^{80} \dfrac{(81 - k)^2}{k^2 + (81 - k)^2}$$
which allows us to deduce that :
$$2 S = \sum_{k = 1}^{80} \dfrac{k^2}{(81 - k)^2 + k^2} + \sum_{k = 1}^{80} \dfrac{(81 - k)^2}{k^2 + (81 - k)^2} = \sum_{k = 1}^{80} \dfrac{k^2 + (81 - k)^2}{k^2 + (81 - k)^2} = \sum_{k = 1}^{80} 1 = 80$$
Hence :
$$S = 40$$
Answer: Just some observations that can serve as "food for thought" to solve these problems:

Remember the proof of little Gauss that $1+2+...+(n-1)+n=n(n+1)/2$. The idea was to combine terms in the sum so that the sum is constant. In this case we can combine $(1,n),(2,n-1),(3,n-2)$ with constant sum $n+1$. Suppose $n$ is even as a start. Since we have $n/2$ such terms, the answer follows ;

If we have a new problem/sum how can we get an intuition on how to combine terms (supposing this technique makes sense to apply)? Either we are in a good day and see the solution (like the answers already posted), or we can start evaluating the sum for small $n$ by hand and see if we see a pattern, that we can conjecture and then verify.

In this case for example we could try to generalize:
$80 \rightarrow 2n, a_k \rightarrow \frac{k}{2n+1}$
and if we call:
$\beta_k=\frac{a_k^2}{1+2a_k^2-2a_k}$
it is not difficult to conjecture, looking at cases $n=1,2$, that:
$\beta_{2n+1-k}+\beta_{k}=1$,
independently of $k$. Once we verify this identity (some calculations), we know that:
$\sum_{k=1}^{2n} \beta_k=n$,
which is the correct answer for every $n$.


Why use a Gaussian mixture model?

Question: I am learning about Gaussian mixture models (GMM) but I am confused as to why anyone should ever use this algorithm.

How is this algorithm better than other standard clustering algorithm such as $K$-means when it comes to clustering? The $K$ means algorithm partitions data into $K$ clusters with clear set memberships, whereas the Gaussian mixture model does not produce clear set membership for each data point. What is the metric to say that one data point is closer to another with GMM?
How can I make use of the final probability distribution that GMM produces? Suppose I obtain my final probability distribution $f(x|w)$ where $w$ are the weights, so what? I have obtained a probability distribution that fits to my data $x$. What can I do with it?
To follow up with my previous point, for $K$ means, at the end we obtain a set of $K$ clusters, which we may denote as the set $\{S_1, \ldots, S_K\}$, which are $K$ things.  But for GMM, all I obtain is one distribution $f(x|w) = \sum\limits_{i=1}^N w_i \mathcal{N}(x|\mu_i, \Sigma_i)$ which is $1$ thing. How can this ever be used for clustering things into $K$ cluster?
Comment: GMM has other meanings, not least in econometrics. Abbreviation removed from title to reduce distraction.
Answer: I'll borrow the notation from (1), which describes GMMs quite nicely in my opinon.   Suppose we have a feature $X \in \mathbb{R}^d$. To model the distribution of $X$ we can fit a GMM of the form
$$f(x)=\sum_{m=1}^{M} \alpha_m \phi(x;\mu_m;\Sigma_m)$$
with $M$ the number of components in the mixture, $\alpha_m$ the mixture weight of the $m$-th component and $\phi(x;\mu_m;\Sigma_m)$ being the Gaussian density function with mean $\mu_m$ and covariance matrix $\Sigma_m$. Using the EM algorithm (its connection to K-Means is explained in this answer) we can aquire estimates of the model parameters, which I'll denote with a hat here ($\hat{\alpha}_m, \hat{\mu}_m,\hat{\Sigma}_m)$. So, our GMM has now been fitted to $X$, let's use it!
This addresses your questions 1 and 3

What is the metric to say that one data point is closer to another
  with GMM?
  [...]
  How can this ever be used for clustering things into K cluster?

As we now have a probabilistic model of the distribution, we can among other things calculate the posterior probability of a given instance $x_i$ belonging to component $m$, which is sometimes referred to as the 'responsibility' of component $m$ for (producing) $x_i$ (2) , denoted as $\hat{r}_{im}$
$$ \hat{r}_{im} = \frac{\hat{\alpha}_m \phi(x_i;\mu_m;\Sigma_m)}{\sum_{k=1}^{M}\hat{\alpha}_k \phi(x_i;\mu_k;\Sigma_k)}$$
this gives us the probabilities of $x_i$ belonging to the different components. That is precisely how a GMM can be used to cluster your data.
K-Means can encounter problems when the choice of K is not well suited for the data or the shapes of the subpopulations differ. The scikit-learn documentation contains an interesting illustration of such cases

The choice of the shape of the GMM's covariance matrices affects what shapes the components can take on, here again the scikit-learn documentation provides an illustration

While a poorly chosen number of clusters/components can also affect an EM-fitted GMM, a GMM fitted in a bayesian fashion can be somewhat resilient against the effects of this, allowing the mixture weights of some components to be (close to) zero. More on this can be found here.
References

(1) Friedman, Jerome, Trevor Hastie, and Robert Tibshirani. The
  elements of statistical learning. Vol. 1. No. 10. New York: Springer
  series in statistics, 2001.
  (2) Bishop, Christopher M. Pattern
  recognition and machine learning. springer, 2006.
Comment: What is the relationship between $x$ and $X$? Furhter, what is the difference between $x_i$ and $x$?
Answer:

How is this algorithm better than other standard clustering algorithm such as $K$-means when it comes to clustering?

k-means is well suited for roughly spherical clusters of equal size. It may fail if these conditions are violated (although it may still work if the clusters are very widely separated). GMMs can fit clusters with a greater variety of shapes and sizes. But, neither algorithm is well suited for data with curved/non-convex clusters.
GMMs give a probabilistic assignment of points to clusters. This lets us quantify uncertainty. For example, if a point is near the 'border' between two clusters, it's often better to know that it has near equal membership probabilities for these clusters, rather than blindly assigning it to the nearest one.
The probabilistic formulation of GMMs lets us incorporate prior knowledge, using Bayesian methods. For example, we might already know something about the shapes or locations of the clusters, or how many points they contain.
The probabilistic formulation gives a way to handle missing data (e.g. using the expectation maximization algorithm typically used to fit GMMs). We can still cluster a data point, even if we haven't observed its value along some dimensions. And, we can infer what those missing values might have been.

...The $K$ means algorithm partitions data into $K$ clusters with clear set memberships, whereas the Gaussian mixture model does not produce clear set membership for each data point. What is the metric to say that one data point is closer to another with GMM?

GMMs give a probability that each each point belongs to each cluster (see below). These probabilities can be converted into 'hard assignments' using a decision rule. For example, the simplest choice is to assign each point to the most likely cluster (i.e. the one with highest membership probability).

How can I make use of the final probability distribution that GMM produces? Suppose I obtain my final probability distribution $f(x|w)$ where $w$ are the weights, so what? I have obtained a probability distribution that fits to my data $x$. What can I do with it?

Here are just a few possibilities. You can:

Perform clustering (including hard assignments, as above).
Impute missing values (as above).
Detect anomalies (i.e. points with low probability density).
Learn something about the structure of the data.
Sample from the model to generate new, synthetic data points.

To follow up with my previous point, for $K$ means, at the end we obtain a set of $K$ clusters, which we may denote as the set $\{S_1, \ldots, S_K\}$, which are $K$ things.  But for GMM, all I obtain is one distribution $f(x|w) = \sum\limits_{i=1}^N w_i \mathcal{N}(x|\mu_i, \Sigma_i)$ which is $1$ thing. How can this ever be used for clustering things into $K$ cluster?

The expression you wrote is the distribution for the observed data. However, a GMM can be thought of as a latent variable model. Each data point is associated with a latent variable that indicates which cluster it belongs to. When fitting a GMM, we learn a distribution over these latent variables. This gives a probability that each data point is a member of each cluster.

Why use a Gaussian mixture model?


Fastest way to check ancestors using XPath and libxml2

Question: I'm working on a little reading app that processes HTML documents using libxml2. While processing an HTML tree, I check every text() node for its ancestors to choose a proper style. For headers I'm using the following of query to see whether a node is header or not:
boolean(ancestor::*[
self::h1 or
self::h2 or
self::h3 or
self::h4 or
self::h5 or
self::h6])

With a 5 MB book, it takes 1.1 seconds to pass. Together with two additional queries for emphasis and code styles (with larger set of node names), it adds up to 4.4 seconds.
According to Apple's Instruments, the bottleneck line is:
xmlXPathObject *object = xmlXPathNodeEval(node, query, context);

I cache context to speed things up. Is there anything else I could do to make it faster?
Answer: I think your XPath expression is optimal for libxml2. But it seems that you don't precompile your XPath query. If you compile the query using xmlXPathCompile once at the beginning of your program and evaluate it with xmlXPathCompiledEval, you should see a significant speedup.
On top of that, you can get a small speedup by removing the boolean function from your query and calling xmlXPathCompiledEvalToBoolean directly.


Variável executando sozinha

Question: Estou tentando criar uma variável que eu vá usar só quando quiser criar uma pasta. Mas essa mesma variável está criando essa pasta antes da condição IF e o do READ serem executados. Segue o exemplo simplificado:
#!/bin/bash

criar=$(mkdir API)

echo "Deseja criar a pasta raiz: "
echo "1 - Sim"
echo "2 - Não"
read opcao

if [ $opcao = "1" ]
  then
      $criar
  else
      echo error
fi

Answer: O problema é que o $(), um substituidor de comandos, irá capturar o valor do comando que você passar dentro e, no seu caso, inserir na variável criar. Isso faz com que o comando mkdir seja executado durante a declaração daquela variável.
Como você aparentemente quer criar um bloco de código que será executado posteriormente, é ideal criar uma função. No exemplo abaixo, criamos a função criar:
#!/bin/bash

# Definimos a função `criar`:
criar() {
  mkdir API
}

echo "Deseja criar a pasta raiz: "
echo "1 - Sim"
echo "2 - Não"
read opcao

if [ $opcao = "1" ]; then
    criar
  else
    echo "Usuário selecionou: Não."
fi

Você pode até criar uma verificação dentro da função, para impedir que o comando mkdir seja executado caso o diretório já exista:
criar() {
  folder_name="API"

  if [ ! -d "./$folder_name" ]; then
    mkdir $folder_name
  else
    echo "A pasta já existe."
  fi
}

Comment: Muito obrigado.

Variável executando sozinha


It should be set to 65000 to avoid operational disruption

Question: I'm following Taking Solr to Production | Apache Solr Reference Guide 8.5, however unable to overcome warning while restarting solr service:
# service solr restart
*** [WARN] *** Your open file limit is currently 1024.
 It should be set to 65000 to avoid operational disruption.
 If you no longer wish to see this warning, set SOLR_ULIMIT_CHECKS to false in your profile or solr.in.sh
*** [WARN] ***  Your Max Processes Limit is currently 1024.
 It should be set to 65000 to avoid operational disruption.
 If you no longer wish to see this warning, set SOLR_ULIMIT_CHECKS to false in your profile or solr.in.sh
Sending stop command to Solr running on port 8983 ... waiting up to 180 seconds to allow Jetty process 16065 to stop gracefully.
Waiting up to 180 seconds to see Solr running on port 8983 [\]
Started Solr server on port 8983 (pid=16320). Happy searching!

#

My system:
# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.10 (Santiago)
# uname -a
Linux X.X.X 2.6.32-754.30.2.el6.x86_64 #1 SMP Fri May 29 04:45:43 EDT 2020 x86_64 x86_64 x86_64 GNU/Linux
#

after doing man 5 limits.conf:
# cat /etc/security/limits.d/498-solr.conf
solr    hard    nofile  65000
solr    hard    nproc   65000
#

however, I am still getting that warning message while restart of solr service.
Please advise)
Thanks in advance!

@MirceaVutcovici:
# grep 'Max processes' /proc/$(pgrep solr)/limits
grep: /proc//limits: No such file or directory
# pgrep solr
# echo $?
1
# ps ax | grep solr
 1926 ?        Sl     2:37 java -server -Xms512m -Xmx512m -XX:+UseG1GC -XX:+PerfDisableSharedMem -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=250 -XX:+UseLargePages -XX:+AlwaysPreTouch -verbose:gc -XX:+PrintHeapAtGC -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -XX:+PrintTenuringDistribution -XX:+PrintGCApplicationStoppedTime -Xloggc:/var/solr/logs/solr_gc.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=9 -XX:GCLogFileSize=20M -Dsolr.jetty.inetaccess.includes= -Dsolr.jetty.inetaccess.excludes= -Dsolr.log.dir=/var/solr/logs -Djetty.port=8983 -DSTOP.PORT=7983 -DSTOP.KEY=solrrocks -Dhost=rlos.uftwf.local -Duser.timezone=UTC -Djetty.home=/opt/solr/server -Dsolr.solr.home=/var/solr/data -Dsolr.data.home= -Dsolr.install.dir=/opt/solr -Dsolr.default.confdir=/opt/solr/server/solr/configsets/_default/conf -Dlog4j.configurationFile=/var/solr/log4j2.xml -Xss256k -Dsolr.jetty.https.port=8983 -Dsolr.log.muteconsole -XX:OnOutOfMemoryError=/opt/solr/bin/oom_solr.sh 8983 /var/solr/logs -jar start.jar --module=http
 9029 pts/0    S+     0:00 grep solr
# grep 'Max processes' /proc/1926/limits
Max processes             1024                 65000                processes
#

Comment: You can see that the limits you configured in /etc/security/limits.d/498-solr.conf file are applied to the process by running: `grep 'Max processes' /proc/$(pgrep solr)/limits` Please attach the output to the question.
Comment: @MirceaVutcovici output is attached to the question and yes I see that limits were *NOT* applied (hence the warning), would you happened to know the right way to apply?
Answer: You set the hard limits, but not the soft limits, and the soft limits are what is being reported. You should also set the soft limits, in the same way.
solr    soft    nofile  65000
solr    soft    nproc   65000

(The app itself should be able to raise the limits, up to the hard limit, but apparently the developers haven't chosen to do this.)
Comment: That did the trick for me! Thanks!
Answer: For some reason this solution didn't work for me. the solution was to change the file /etc/systemd/system.conf by adding the following lines.
DefaultLimitNOFILE=65000
DefaultLimitNPROC=65000

after that, run systemctl daemon-reload.
Checking the settings:
~ # systemctl show | egrep "NOFILE|NPROC"
DefaultLimitNOFILE=65000
DefaultLimitNOFILESoft=65000
DefaultLimitNPROC=65000
DefaultLimitNPROCSoft=65000


Create a view block on a node reference field (using Node Reference)

Question: Creating a related content block on a node reference field. I have two content types: Article and Author.
The content type Article has the field Label: Por 'field_autor' which is a node reference to an author node.
I want to be able to take that ID and lis other articles with the same NID.
The view is setup as such:

Format: HTML List
Fields: Title
Filter: Published;
Type (Article)
Order: Weight

Advanced Options

Contextual Filters: (field_autor) Content: Nid
Relationships: Content: Por (field_autor) - reverse

However, this isn't displaying articles with the same author. Looking for assistance!
Answer: UPDATE
There are some decent explanations on the internet

http://www.webomelette.com/related-content-block-views-drupal-7
http://www.webomelette.com/related-content-views-taxonomy-drupal

As well the eva module was suggested as being helpful in my situation, but I haven't tried it yet
Currently, this is still an issue for me.


Alinhar Cards CSS Bootstrap

Question: Olá, gostaria de alinhar os cards do centro da minha página
Print:

Código:

*{
    font-family: "Ubuntu", sans-serif;
}

.logo{
    max-width: 27%;
}

.content-wrapper {
    max-width: 1250px;
    -webkit-box-shadow: 0 0 50px 5px rgba(0,0,0,0.15);
    box-shadow: 0 0 50px 5px rgba(0,0,0,0.15);
    position: relative;
    margin: -40px auto 0;
    background: #fff;
    z-index: 10;
    margin-bottom: 50px;
}

footer{
    background: #131313;
    height: 100px;
    display: flex;
    align-items: center;
}

footer p {
    color: #bdbdbd;
    font-size: 16px;
    margin-left: 100px;
    margin-top: 10px;
}

.card img {
    margin-top: 15px;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    max-width: 130px;
}

.card {
    margin-left: 20px;
    width: 400px;
    background: #fff;

}

.mid {
    position: relative;
    top: 50%;
    transform: translateY(-50%);

}

.presentation {
    overflow: hidden;
    position: relative;
    width: 100%;
    height: 60vh;
    background: url(../images/bg-1.jpg) top center;
}

.widget {
    background: white;
    margin: 25px 0px;
    width: 100%;
    text-align: center;
    border-radius: 4px;
}
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="google" value="notranslate">
    <meta name="language" content="pt-br" />
    <meta http-equiv="Content-Language" content="pt-br" />
    <meta name="robots" content="index,follow,noodp,noydir">
    <meta name="revisit-after" content="1 week">
    <base href="/">
    <link rel="canonical" href="http://localhost/" />

    <title>Atlas Plugins - Início</title>
    <meta name="description" content="Atlas Plugins de Minecraft - Home">
    <meta name="keywords" content="Minecraft, Plugins de Minecraft, Plugins, Plugin, Servidor de Minecraft, Servidor, Plugins para servidor de minecraft, plugins para minecraft, pl para servidores de minecraft, pl minecraft, pl de factions, pl da redesky">
    <meta name="theme-color" content="#79C9F9">
    <link rel="shortcut icon" type="image/x-icon" href="http://localhost/app/content/assets/images/A.png">

    <meta property="og:title" content="Atlas Plugins" />
    <meta property="og:image" content="http://localhost/app/content/assets/images/logo.png" />
    <meta property="og:type" content="website" />
    <meta property="og:locale" content="pt_BR" />
    <meta property="og:site_name" content="Atlas Plugins" />
    <meta property="og:description" content="Atlas Plugins de Minecraft - Home" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:site" content="Atlas Plugins" />
    <meta name="twitter:title" content="Atlas Plugins - Início" />
    <meta name="twitter:description" content="Atlas Plugins de Minecraft - Home" />
    <meta name="twitter:image" content="http://localhost/app/content/assets/images/logo.png" />

    <link href="//fonts.googleapis.com/css?family=Open+Sans:400,400i,300,700|Ubuntu:300,400,500,700&subset=Latin" rel="stylesheet" type="text/css"/>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link href="/app/content/assets/css/bootstrap/bootstrap-grid.min.css" rel="stylesheet" type="text/css">
    <link href="/app/content/assets/css/bootstrap/bootstrap-reboot.min.css" rel="stylesheet" type="text/css">
    <link href="/app/content/assets/css/normalize/normalize.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
    <link href="/app/content/assets/css/waves/waves.min.css" rel="stylesheet" type="text/css">
    <link href="/app/content/assets/css/sweetalert/sweetalert.css" rel="stylesheet" type="text/css">
    <link href="/app/content/assets/css/animate/animate.css" rel="stylesheet" type="text/css">
    <link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="/app/content/assets/css/atlas.css" rel="stylesheet" type="text/css">

        <button class="navbar-toggler waves waves-effect waves-light" type="button" data-toggle="collapse" data-target="#menu">  </button>

  Início

                      Plugins

 Pagos Gratuitos

  Contato

  Área do Cliente

Atualizações

Todos os plugins recebem updates sempre que possível

Agilidade

Suporte, desenvolvimento e entrega rápida e no prazo estipulado.

Segurança

Compra segura e plugins totalmente livre de malicia desenvolvidos em ambiente seguro.

Sobre Mim

 Olá, seja muito bem vindo ao Atlas Plugins!

 Meu nome é Gabriel e sou desenvolvedor java desde 2014,

 Atualmente desenvolvo para muitos servidores de portes variados, e estou a disposição para melhorar seu servidor também.

 Está esperando o que para conhecer mais sobre meu trabalho? Baixe meus plugins gratuitos e aprove a qualidade.

 Caso queira projetos para melhorar seu servidor ainda mais, veja alguns recursos pagos e caso não encontre o que precisa entre em contato e faça uma encomenda exclusiva como deseja.

 Copyright Atlas Plugins 2020 - Todos os direitos reservados.

Answer: Coloque a classe .justify-content-center na div.row onde estão os cards para que eles fiquem alinhados ao centro. A div.row já é flexbox e essa classe, nativa no Bootstrap 4, alinha os elementos filhos ao centro horizontalmente.
Retire o width: 400px; da classe .cards para que eles sejam responsivos. Eles já estão dentro de uma coluna responsiva, então não precisa definir uma largura fixa para eles senão um ficará por cima do outro se reduzir a largura da tela até certo ponto antes do breakpoint do .col-md-3.
Answer: Utilize o display flex na div que você usa como container para seus card e utilize
"justify-content: space-around;". Segue exemplo.
Eu recomendo que você dê uma olhada em display flex e grid.
Este código é css puro, coloquei-o pois você não utilizou a tag do twitter bootstrap.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

#container {
  display: flex;
  justify-content: center;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background-color: #eeeeee;
}

#container > div {
  width: 100px;
  height: 140px;
  border-radius: 10%;
  background-color: blue;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Teste de Página</title>

Comment: Não sei um jeito de te ajudar com isso, mas acho que você deveria fazer um novo post, pois acho que esta pergunta sobre padrão em resoluções diferentes já sai do contexto de alinhamento de cards.
Comment: Estou utilizando o container mas coloquei um ```margin-top: 100px;``` e de acordo com a resolução do monitor fica diferente, como posso ajustar isso para um padrão em todos os monitores?, segue exemplos em imagens de 2 prints de monitores diferentes:

[![inserir a descrição da imagem aqui][1]][1]

[![inserir a descrição da imagem aqui][2]][2]

  [1]: https://i.stack.imgur.com/JSM52.png
  [2]: https://i.stack.imgur.com/sq1MV.png
Answer: Estou utilizando o container mas coloquei um margin-top: 100px; e de acordo com a resolução do monitor fica diferente, como posso ajustar isso para um padrão em todos os monitores?, segue exemplos em imagens de 2 prints de monitores diferentes:

Alinhar Cards CSS Bootstrap


listar publicações de amigos

Question: eu estou fazendo uma consulta no banco de dados para listar as minhas publicações e a das pessoas que eu sigo na minha timeline, mais a consulta apenas esta trazendo as minhas publicações.
<?php

$tipo_news = "SELECT * FROM $table_post WHERE usuario=$cod_login order by codigo desc";
$tipo_news_resultado = mysqli_query($mysqli, $tipo_news);
$tipo_news_quantidade = mysqli_num_rows($tipo_news_resultado);

$consulta_contatos = "SELECT * FROM $table_contatos WHERE usuario=$cod_login || amigo=$cod_login";
$resultado_contatos = mysqli_query($mysqli, $consulta_contatos);
$quantidade_contatos = mysqli_num_rows($resultado_contatos);

for($i=0;$i < $tipo_news_quantidade;$i++)
{
$vetor_news = mysqli_fetch_array($tipo_news_resultado);

?>
<?php print($vetor_news['nickname']); ?>
<?php print($vetor_news['post']); ?>

 <?php
}

?>

Answer: se entendi certo deveria ser SQL mais ou menos assim :
buscar IDs dos meus contatos:
$contatos_ids_query = "SELECT id FROM $table_contatos WHERE usuario=$cod_login";
$lista_ids = mysqli_query($mysqli, $contatos_ids_query);
Transformar array com IDs em string
$string_ids = implode(',', (array)$lista_ids);
buscar postagens dos meus contatos:
$contatos_news_query = "SELECT * FROM $table_post WHERE usuario in($string_ids) order by codigo desc";
$contatos_news = mysqli_query($mysqli, $contatos_news_query);
var_dump($contatos_news)
Comment: oi, obrigado pela ajuda eu tentei fazer dessa forma e deu erro, vou tentar explicar melhor a pergunta, eu estou fazendo uma consulta no banco de dados para listar as minhas publicações e a das pessoas que eu sigo na minha timeline, mais a consulta apenas esta trazendo as minhas publicações.
Comment: Tem como mostra o erro?
Comment: Fatal error: Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array, string given in C:\xampp\htdocs\social\usuario.php:650 Stack trace: #0 C:\xampp\htdocs\social\usuario.php(650): implode(',', 'SELECT codigo F...') #1 {main} thrown in C:\xampp\htdocs\social\usuario.php on line 650
Comment: Transforme $contatos_ids em array,

$string_ids = implode(',', (array) $contatos_ids);
Comment: confira se  contatos_ids está retornando um objeto com lista de id dos contatos se positivo transforme em array

$string_ids = implode(',',  (array) $contatos_ids)
Comment: calma ai, eu reparei que tu atropelou alguns passos, tu jogou o SQL direto no $contatos_ids, isso é apenas um modelo para seguir a lógica
Comment: precisa por SQL do $contatos_ids em mysqli_query()
 mysqli_query(contatos_ids)
Comment: desculpa eu não sei fazer dessa forma.
Comment: Vou melhorar a resposta acima
Comment: Coloquei mais detalhes na resposta tenta agora.
Comment: deu erro no for. Parse error: syntax error, unexpected token "for" in C:\xampp\htdocs\social\usuario.php on line 663

listar publicações de amigos


Solve the ODE $4y''\sqrt{y}=9$

Question: Let $y(x)$ be a solution to the ODE $$\begin{cases}4y''\sqrt{y} = 9\\ y(0)=1\ ,y'(0)=3\end{cases}$$
then $y(\frac{28}{9})$ is equal to -

14
15
15
17
none of the above.

I tried solving it by reducing its power or by substitution but I got nowhere. Any hints on how to proceed?
Comment: Multiply both sides by $y'$.
Answer: hint
$$2y''.y' = 9 \frac{y'}{2\sqrt{y}}$$
So
$$y'^2 = 9\sqrt{ y }+C$$
Comment: I hope my account won't be closed for 60 days.
Comment: Why would it be?
Comment: Well, if you want to avoid penalties for answering poor questions, don't answer poor questions, don't admit you know this is a poor question and you answered it anyway…
Comment: @ThomasAndrews I just gave a hint. Unfortunately i cannot delete it from mobile.
Comment: That is one big hint.

Solve the ODE $4y''\sqrt{y}=9$


Toggling two CSS animations with jQuery only works once through

Question: I am trying to toggle between two CSS animations using jQuery, but they only work once! How can I get it to keep toggling? Also, this doesn't seem to work in jsFiddle at all for some reason. Please and thank you.

//hide and show counter-button
$('#counter-button').click(function() {
  $('#counter').toggle();

  //move button down/up on click
  if ($('#counter-button').attr('class') === 'movedown') {
    $('#counter-button').addClass('moveup');

  } else {
    $('#counter-button').addClass('movedown');
  }
});
#counter-button {
  font-size: 20px;
  position: fixed;
  right: 90px;
  bottom: 190px;
  z-index: 2;
  cursor: pointer;
}

.movedown {
  animation: down ease forwards 0.5s;
}

@keyframes down {
  from {
    right: 90px;
    bottom: 190px;
  }
  to {
    right: 90px;
    bottom: 100px;
  }
}
.moveup {
  animation: up ease forwards 0.5s;
}
@keyframes up {
  from {
    right: 90px;
    bottom: 100px;
  }
  to {
    right: 90px;
    bottom: 190px;
  }
}
#counter {
  position: fixed;
  height: 80px;
  width: 228px;
  bottom: 100px;
  right: 20px;
  border: 2px solid black;
  border-radius: 5px;
}

  COUNTER

Answer: Instead of .attr('class') === 'movedown' check class using hasClass(). And while adding moveup class you should remove the movedown class and vice-versa.
Check the code below here.

//hide and show counter-button
$('#counter-button').click(function() {
  $('#counter').toggle();

  //move button down/up on click
  if ($('#counter-button').hasClass('movedown')) {
    $('#counter-button').addClass('moveup').removeClass('movedown');
  } else {
    $('#counter-button').addClass('movedown').removeClass('moveup');
  }
});
#counter-button {
  font-size: 20px;
  position: fixed;
  right: 90px;
  bottom: 190px;
  z-index: 2;
  cursor: pointer;
}

.movedown {
  animation: down ease forwards 0.5s;
}

@keyframes down {
  from {
    right: 90px;
    bottom: 190px;
  }
  to {
    right: 90px;
    bottom: 100px;
  }
}
.moveup {
  animation: up ease forwards 0.5s;
}
@keyframes up {
  from {
    right: 90px;
    bottom: 100px;
  }
  to {
    right: 90px;
    bottom: 190px;
  }
}
#counter {
  position: fixed;
  height: 80px;
  width: 228px;
  bottom: 100px;
  right: 20px;
  border: 2px solid black;
  border-radius: 5px;
}

  COUNTER

Comment: @RoryMcCrossan yes true! :)
Comment: @RoryMcCrossan initially OP doesnt have either of the class in his HTML, so `toggleClass` will either remove both or will add both. It could be done using `toggleClass` if `moveup` is already present there.
Comment: ah yes, you're right. My bad. Although I'd suggest adding a default state class to the element to prevent ambiguity and make the JS simpler.
Answer: You forgot to remove the unnecessary class and hence unexpected behavior. Just add removeClass and remove respective classes. Snippet below

//hide and show counter-button
$('#counter-button').click(function() {
  $('#counter').toggle();

  //move button down/up on click
  if ($('#counter-button').attr('class') === 'movedown') {
    $('#counter-button').addClass('moveup').removeClass('movedown');

  } else {
    $('#counter-button').addClass('movedown').removeClass('moveup');
  }

});
#counter-button {
  font-size: 20px;
  position: fixed;
  right: 90px;
  bottom: 190px;
  z-index: 2;
  cursor: pointer;
}
.movedown {
  animation: down ease forwards 0.5s;
}
@keyframes down {
  from {
    right: 90px;
    bottom: 190px;
  }
  to {
    right: 90px;
    bottom: 100px;
  }
}
.moveup {
  animation: up ease forwards 0.5s;
}
@keyframes up {
  from {
    right: 90px;
    bottom: 100px;
  }
  to {
    right: 90px;
    bottom: 190px;
  }
}
#counter {
  position: fixed;
  height: 80px;
  width: 228px;
  bottom: 100px;
  right: 20px;
  border: 2px solid black;
  border-radius: 5px;
}

  COUNTER

Updated Code
Further you can optimize the above code by initially adding class moveup to your button and then you can just use toggleClass without checking for any condition.

//hide and show counter-button
$('#counter-button').click(function() {
  $('#counter').toggle();
  //move button down/up on click
    $(this).toggleClass('movedown moveup');
});
#counter-button {
  font-size: 20px;
  position: fixed;
  right: 90px;
  bottom: 190px;
  z-index: 2;
  cursor: pointer;
}
.movedown {
  animation: down ease forwards 0.5s;
}
@keyframes down {
  from {
    right: 90px;
    bottom: 190px;
  }
  to {
    right: 90px;
    bottom: 100px;
  }
}
.moveup {
  animation: up ease forwards 0.5s;
}
@keyframes up {
  from {
    right: 90px;
    bottom: 100px;
  }
  to {
    right: 90px;
    bottom: 190px;
  }
}
#counter {
  position: fixed;
  height: 80px;
  width: 228px;
  bottom: 100px;
  right: 20px;
  border: 2px solid black;
  border-radius: 5px;
}

  COUNTER

Answer: Use toggleClass

     //hide and show counter-button
    $('#counter-button').click(function() {
      $('#counter').toggle();

        $('#counter-button').toggleClass('moveup movedown');

    });
#counter-button {
  font-size: 20px;
  position: fixed;
  right: 90px;
  bottom: 190px;
  z-index: 2;
  cursor: pointer;
}
.movedown {
  animation: down ease forwards 0.5s;
}
@keyframes down {
  from {
    right: 90px;
    bottom: 190px;
  }
  to {
    right: 90px;
    bottom: 100px;
  }
}
.moveup {
  animation: up ease forwards 0.5s;
}
@keyframes up {
  from {
    right: 90px;
    bottom: 100px;
  }
  to {
    right: 90px;
    bottom: 190px;
  }
}
#counter {
  position: fixed;
  height: 80px;
  width: 228px;
  bottom: 100px;
  right: 20px;
  border: 2px solid black;
  border-radius: 5px;
}

  COUNTER