How to make about us slider responsive to mobile and lower resolution

Question: so i made about us slider with three persons and how do i make it responsive that it resize based on resolution, i tried @media and other stuff but it isnt working
Thanks
html code:

                      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,

xyz

xxx

                      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,

xyz

xxx

                      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,

xyz

xxx

css code

.glowny {
  height: 100vh;
  width: 100%;
  position: relative;
  padding-top: 80px;
  margin: 0 auto;
}

.glowny h1 {
  text-align: center;
  padding: 5px;
  font-size: 30px;
  max-width: 100%;
  margin-bottom: 20px;
}

.glowny1 {
  width: 100%;
  position: relative;
  padding-top: 80px;
}

.glowny1 h1 {
  text-align: center;
  padding: 5px;
  font-size: 30px;
  max-width: 100%;
  margin-bottom: 20px;
}

.slide-row {
  display: flex;
  width: 100%;
  transition: 0.8s;
}
.slide-col {
  width: 100%;
  height: 33%;
  position: relative;
}
.user-img {
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
}

.user-img img {
  height: 100%;
  border-radius: 10px;
  max-width: 100%;
  text-align: center;
}

.user-text {
  background: #2d3a59;
  width: 100%;
  max-width: 900px;
  height: 50%;
  min-height: 450px;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 10px;
  color: #d3d4d6;
  padding: 45px;
  box-sizing: border-box;
  z-index: 2;
}

.user-text p {
  font-size: 18px;
  line-height: 24px;
  text-align: justify;
}

.user-text h3 {
  margin: 35px 0 5px;
  color: #fff;
}

.conteiner-onas {
  width: 1250px;
  height: 625px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.indicator {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: -50px;
}

.active {
  width: 40px;
}

.testimonial {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

Thank you so much im stuck there
i tried media screen and some chat gpt responsive answers but none of them worked
Answer: just a little change
.conteiner-onas {
  width: 100%;  /* changed from 1250px to 100%*/
  height: 625px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Comment: Still isnt working :/


How to allow a client to do specialized styling for a single node?

Question: I'm working on converting an existing website to Drupal, and I'm looking for best practices for creating specialized styling on specific nodes. I have a page that looks like this (baconized for your viewing pleasure):

Can someone advise me as to the best way to accomplish styling a node this way - specifically in a way where the content can be managed by the client?
I've had a few different ideas as to how to accomplish it, but I'm not sure which is best.
Write raw HTML as the content and add CSS in the template?
 - The downside with this is that I'd prefer my client not have to mess with raw HTML when managing the content, if at all possible.
Create a custom content type that has fields for each snippet which I can style within the theme?
 - This seems like a reasonable course of action, except that I'll be creating a one-off content type for a single node, and that seems less than optimal.
Do something with Views?
 - Views is always an option, but I don't know if it's the right one here. Would I create a separate node for the intro snippet, the 3 blockquotes, and the rest of the page, or something else? I'm not sure.
Do something with Panels?
 - I'm still figuring out how to use Panels, and it seems like a possibility here, but an overly complicated one. Additionally, how will the client manage it?
Any insight or advice here would be immensely helpful. Thank you!
Answer: If it is a page with unique structure and no other pages will have same structure, I usually do this by creating an empty page (not a node, just a page - an item in drupal menu system).
You can create a page in your module like so:
function YOUR_MODULE_menu() {
    $items = array();
    $items['your-page-url'] = array(
        'type' => MENU_NORMAL_ITEM,
        'title' => t('Page title'),
        'page callback' => 'your_callback_function_name',
        'access callback' => TRUE
    );
    return $items;
}

function your_callback_function_name() {
    return '';
}

the code above will provide an empty page. If you need custom page structure for this page you can always declare a template specifically for this page just put:
page--your-page-url.tpl.php

to your theme template folder.
Then you can create blocks for each piece of content and assign them to proper regions. Your users will be able to edit content through blocks edit while all styling and layout tags will be built into template file.
Comment: So would you suggest creating custom block regions in the template for the one page, then?
Comment: that's one of the possible solutions. You can create new regions for blocks within your existing theme. You can create a new theme with its own set of regions and assign this theme only to this page using themekey module. And of course you can not to create new regions and just make use of css to align blocks properly within your content region. In my opinion the last option suits this task best.
Comment: What is the appropriate way to include blocks into the theme without using custom regions?
Comment: the point is that you use the very same regions that the ones in your main theme, but you can layout them differently in your custom page--your-page-url.tpl.php file. At the very least you can put all the blocks to the one region and render that region somewhere on the page.
Besides that you can of course print any block with the following code:
    $block = module_invoke('module_name', 'block', 'view', 0);
    print $block['content'];
Answer: In most simple case you can use CKEditor module and some css in your theme for blockquote tag inside node content. Also you can define your custom element style for CKEditor that will wrap disred text into tag with class or inline style. This way allow you to avoid metting your user with raw HTML. Panels and Views or blocks is good approach for small amounts of pages with complicated structure(for example), but not always it is appropriate way.
Answer: You might consider whether Skinr meets your needs. The idea is that you can apply extra CSS selectively, and your client can, too.
Answer: I like using views to output content, but this could be done in lots of ways.  One way could be to create your columns as taxonomies and then in a newly created content type, create an existing term reference to the taxonomy.  Then create the other content from fields and then once all your content is in the node, style it accordingly with CSS.  A second way could be to use a combo of blocks and views.  In this solution your could create a view of taxonomy terms that displays them as list items in a block, so you could specify what URL's to route your block to. After you have the columns as views you could create the bottom content as a block and the top content as view with a field for the body and a field for the image (from a referenced content type).  You can always move your elements around on your page with a bit of CSS.  Hope this helps.


Registros Diferentes

Question: Tenho duas tabelas:
MATRICULA_A <-c(123,234,345,456)
dados_1 <- data.frame(MATRICULA_A)

MATRICULA_A <-c(345,456,111,222,333,444)
dados_2 <- data.frame(MATRICULA_A)

Necessito extrair somente as informações da tabela dados_1 que são diferentes da dados_2. Neste exemplo, quero que apareça, como resultado, somente as matrículas 123 e 234 (dados_1). Tentei através do anti_join e não deu.
Answer: Não sei como você utilizou a função anti_join, mas ela funcionou aqui:
library(dplyr)
anti_join(dados_1,dados_2,by='MATRICULA_A') # 'MATRICULA_A' é a variável em comum

  MATRICULA_A
1         123
2         234

Answer: Em R base pode fazer isso de várias maneiras.
Com setdiff:
setdiff(dados_1$MATRICULA_A, dados_2$MATRICULA_A)
#[1] 123 234

Com %in% é mais flexível, tanto pode obter um vetor como um objeto de classe "data.frame", tal como o original df1:
i <- !dados_1$MATRICULA_A %in% dados_2$MATRICULA_A

dados_1[i, ]
#[1] 123 234

dados_1[i, , drop = FALSE]
#  MATRICULA_A
#1         123
#2         234

Registros Diferentes


HTTP File Repository

Question: I'm looking for a HTTP based file repository / web application to facilitate passing large files back and forth to clients. Something similar to http://www.rejetto.com/hfs/?f=intro but more server friendly and easier for our staff to maintain client accounts.
Features need include:

Each client needs to have isolated access to only there own files.
An easy web interface for our staff to create/delete client accounts.
Files mapped to a domain accessible folder on the server

Originally we used to use an FTP server, but that proved too hard for some clients to cope with. Then we moved to HFS, but its not simple enough for our staff to manage.
Any suggestions?
Answer: I would suggest you look into HTTP Commander. You can easily use SSL for secure logins, it matches all of your criteria, it's highly scalable and very user friendly and easy to learn / administer.
Comment: Has potential. A little pricey for what it is, although it does have quite a few features.
Comment: I've deployed it with several clients and they all love it. Dev is very responsive and does a great job responding to inquiries.

HTTP File Repository


Why we go for template files and why we go for theme function?

Question:
Possible Duplicate:
When should I add a new tpl.php file, and when should I implement a theme function?

To theme a form: There are two ways.

using function theme_themename_form($form)
Assigning to a variable in preprocess and printing it in the template files.

My question is:

Why two ways?
Which way is best for which case ?
That is for which type of cases we should go for function theme and for which cases we should go for template files.
What is all time best way?
Answer: I always think of it like this:
If you need to write a fair bit of HTML for your theme then you want a template file. This way you can maintain as much separation HTML and PHP as you'd like.
If you theme is just accepting data and putting that data through (say) another theme function, then you're not going to be writing any/much HTML. In this case a theme_* function is more appropriate in my opinion.
I don't think there really is an "all time best way", both methods are appropriate for different situations.
Answer: Both theme functions and template files are useful under different contexts. Tpl files are used if there isn't much preprocessing logic involved. These are the views equivalent in an MVC architecture. So, the maximum allowed logic here is "if-else" constructs, and even that is debatable.
Example use cases for tpl: If you want to change the basic structure of an entity, like print the taxonomy tags as CSV links instead of the default div structure.
Theme functions OTOH, allow for more granularity like augmenting class and other attributes. Preprocessing logic mixes well here as it is till in the "Controller" part of MVC and is not rendered yet.
Example use case for theme functions: add a class based on the taxonomy term value
In the real world, the demarcation between views and controllers is really thin. Drupal gives the provision(flexibility rather) of having themeing done at both levels for different contexts.


Efficiency of load-value instructions versus load-address instructions for fields of structs

Question: Consider the following C# struct definitions:
public struct A
{
    public B B;
}

public struct B
{
    public int C;
}

Also consider the following static method:
public static int Method(A a) => a.B.C;

Calling this method will result in a copy of the struct type A. For example, in the following code:
A a = default;
Method(a);

the call to Method will compile to IL that looks something like this:
IL_0008: ldloc.0      // V_0
IL_0009: call         int32 Class::Method(valuetype A)

ldloc will copy the value of local variable a (V_0) onto the evaluation stack, and that value will be used in Method. If A (or B) was a large struct, this copy could supposedly be expensive. The IL for Method also results in load-value instructions:
IL_0000: ldarg.0      // a
IL_0001: ldfld        valuetype B A::B
IL_0006: ldfld        int32 B::C
IL_000b: ret

Recent versions of C# include features that can help make working with structs more efficient. C# 7.2 introduced the in modifier on parameters that enables the passing of a value type by reference when the compiler can verify that the argument will not be modified by the called method. For example, applying the in modifier to parameter a:
public static int Method(in A a) => a.B.C;

will result in the following compiled IL at the call site:
IL_0008: ldloca.s     a
IL_000a: call         int32 Class::Method(valuetype A&)

and in the implementation of Method:
IL_0000: ldarg.0      // a
IL_0001: ldflda       valuetype B A::B
IL_0006: ldfld        int32 B::C
IL_000b: ret

Note the load-address instructions. My assumption (please correct me if I am wrong) is that for deep field reads (such as reading C that's inside of B that's inside of A), load-address instructions are more efficient than load-value instructions.
With that in mind, consider changing the example code:
A a = default;
var c = a.B.C;

The second line then compiles to:
IL_0008: ldloc.1      // V_1
IL_0009: ldfld        valuetype B A::B
IL_000e: ldfld        int32 B::C
IL_0013: stloc.0      // c

Why wouldn't the compiler prefer to use load-address instructions in this case too? Is there an efficiency difference simply because a is a local variable versus a method parameter, or is there something else I'm missing here?
Answer: It's definitely not related to a being a local variable vs a method argument. Not from efficiency point of view, at least.
The first thing to understand is that structs in C# sit (in the memory) directly where they are declared - so directly on the stack, for local variables. More importantly - nested structs behave the same. It is possible for the JIT, in any point during runtime (not always during compilation, read more about StructLayoutAttribute) , to know exactly where B is inside of A, where C is inside of B, and where B.C lies inside of a.
When looking at the assembly code after the JIT compiles the method (it's important to compile in Release - debug builds will not get optimized the same way. Make sure the compiler doesn't optimize the variables away as well), you'll see that no matter where you type a.B.C it will always be a direct assignment from memory (in relation to where A stands in memory).
In my case, I added another variable int a1 inside A to move the memory a bit - this is the resulting code:
A a = default;
xor         ecx,ecx
mov         qword ptr [rbp-30h],rcx

var c = a.B.C;
mov         esi,dword ptr [rbp-2Ch]

where esi is a temporary register for var c and [rbp-30h] is where a sits in the stack. B has an integer sitting in offset 0, A has an integer sitting in offset 0 and B sitting in offset 4, so the final address of a.B.C is always a+4 ([rbp-2Ch]).
Comment: Thank you very much for looking into this for me. I have a couple follow-up questions. You mentioned that structs sit directly on the stack for local variables. Is this also the case for method parameters passed by value? And second, at a higher level, if the JIT is going to essentially load the address of the field anyway, why wouldn't the compiler just use load-address instructions? In other words, why would the compiler leave "room for interpretation" for the JIT implementation to do something inefficient in the first place?
Comment: @WizardBrony In case you pass a struct to a method by value it copies your struct on the stack for the callee method.
If you want to prevent struct copying, you can use `out` or `ref` keywords, it tells compiler use `by address` instructions (like ldloca) and copy on the stack address only.
For the second part of the previous comment I don't have an answer.
Comment: @WizardBrony if this or any answer has solved your question please consider [accepting it](https://meta.stackexchange.com/q/5234/179419) by clicking the check-mark.
This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this.
Comment: About the second question: The JIT won't always "essentially load the address of the field". Even in this particular case - it won't load the address of the field. Instead, it knows exactly where it sits and uses this to know where the rest of the information lies. In a nested struct, for example, we don't "load the address" of the second struct at all.
It's important to understand what exactly are you asking. Is it "Why does the JIT even copies the struct and not use the address of the original?" Is it "Why does accessing A.B.C inside a method uses load by value and not load by address"?
Comment: Think of the .Net compiler (Roslyn) as the one who says "what" he expects to happen, and the JIT to decide "how" to do that. The JIT has a lot more information and can make better decision making - it can cache locals or arguments in a register, it can inline methods and a lot of much more complicated decisions in runtime.
Comment: Value types don't necessarily sit on the stack if they are used in local variables. If you use them in an anonymous method/lambda, they will get moved to a closure which is a normal object.


Radial acceleration of an object that is in ecuador

Question: A question which I could not solve.

The radius of earth is $6.371$ km. The earth is rotating around itself in $24$ hours. Then, calcuate the radial acceleration of an object that is in ecuador.

We know that
$$a_{r} =  \frac{v^{2}}{r}$$
Given values
$$r = 6.371$$
$$a_{rad} = ?$$
$$v = ?$$
According to the solution

The circumference of earth  $=$ $v$ . period

I cannot apply it because I don't know how to find the velocity ($v$). Could you take a look?
Regards!
Comment: Can someone help, please?
Comment: Radius of earth is $6371km$ no?
Comment: @MyGlasses Absoulety, it's. but It says in ''ecuador''.
Comment: @MyGlasses It says an object that is in ecuador. So, we need to make something different while finding velocity ($v$)
Comment: Ecuador is an example of an object on earth, not matter!
Comment: What's circumference of earth ? Drop dot from radius.
Comment: @MyGlasses That's $40.075$ km.
Comment: So $v=\dfrac{x}{t}$.
Comment: @MyGlasses So we'll use $v = \frac {x}{t}$ to calcuate the velocity?
Comment: Yes.  Drop dot from radius of earth.
Comment: @MyGlasses is $t$ time? Also can you answer it?
Comment: $t=24h$ convert to seconds
Comment: If you answer it, It'd be great. I think I found the velocity from your equation.
Comment: Also what do you mean with $v$?
Comment: Wrong typed $v=\dfrac{x}{t}$. what's your answer now.
Comment: @MyGlasses I didn't get what $x$ means but according to this formula; (the circumference of earth) = $v$ x (period) I'm getting $v \approx 464$
Comment: Circumference of earth it is
Answer: Compute the circumference from the radius you know.  You cover that distance in $24$ hours, so that gives you the speed.  The point of being in Ecuador is that it is close to the equator, so you can use the radius to find the distance traveled in a day.  At other locations you would need to multiply by the cosine of the latitude, but this is (close to) $1$ in Ecuador.
Comment: Could you be more clear? It seems like  $v \approx 464 m/s$
Comment: It says an object that is in ecuador.  So, we need to make something different while finding velocity ($v$)
Comment: You got the right velocity.  What is the problem?  When you compute the acceleration you need to use consistent units.
Answer: Circumference of earth $x$ is
$$x=2\pi R=2\pi\times6731km=40030km$$
and $t=24h=24\times60\times60s=86400s$, then
$$v=\dfrac{x}{t}=463\dfrac{m}{s}$$
and
$$a=\dfrac{v^2}{R}=3.3\times10^{-2}\dfrac{m}{s^2}$$
Comment: Got it now. Thanks for great answer.


awk on vmstat to get si,so

Question: I am writing a shell script to check the vmstat si and so data at various time intervals
vmstat  1 sample output:
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
0  0  45820 899252  86700 468520    0    0     0    60  127 5821 20  7 34  0
0  0  45820 899252  86704 468504    0    0     0    32   44  104  0  0 100  0

I want to use awk, sed to extract si and so into different variables for further usage. I Am new to awk, sed and am still struggling to find my way through. Can you show me how I can do this ?
Answer: This AWK script reads the second line and uses the field headers as indices into the data on each line so you can refer to them by name. Here is the one-liner. I break it out line by line below.
vmstat -n 1 | awk 'NR == 1 {next} NR == 2 {for (i = 1; i <= NF; i++) fields[$i] = i; next} {split($0, data); item = data[fields["si"]]; print item; totals[fields["si"]] += item} NR >= 6 + 2 {exit} END {print "Average", totals[fields["si"]]/(NR - 2)}'

As shown, it prints the contents of the "si" column and the average at the end. You could handle multiple fields or iterate over all the fields.
You can expand on this to handle other fields, do comparisons of one line to the previous one or do totals or other calculations. You can stop, as I have shown, after a certain number of records.
The -n option to vmstat causes the header to only be printed once.
The breakdown:
vmstat -n 1 | awk 'NR == 1 {next}    # skip the first line
# for the second line, create an array of field positions indexed by the
# name of the field then do "next" so this line is not processed further
NR == 2 {for (i = 1; i <= NF; i++) fields[$i] = i; next}
{split($0, data); # split the line of values into an array
item = data[fields["si"]];    # pick out an item based on its name
print item;
totals[fields["si"]] += item}    # accumulate a total
# exit when the number of desired records (plus the two header lines)
# has been read, you could use a vmstat argument to do this instead
NR >= 10 + 2 {exit}
# calculate and print the average (subtract the two header lines from the record count)
END {print "Average", totals[fields["si"]]/(NR - 2)}'

Answer: SWAPIN=$(vmstat | egrep -v 'swap|si' | awk '{ print $7 }')
SWAPOUT=$(vmstat | egrep -v 'swap|si' | awk '{ print $8 }')

or more "standard" way:
$ vmstat | awk '{ for (i=1; i<=NF; i++) if ($i=="si") { getline; print $i }}'

The built-in NF variable gives you the number of fields in the
current line
getline reads the next input line
Comment: AWK can do grep's job.
Answer: I would feel remiss if I didn't supply the perl oneliner equivalents:
SWAPIN=$(vmstat | perl -lane 'next if /^(procs|r)/; print $F[7]')
SWAPOUT=$(vmstat | perl -lane 'next if /^(procs|r)/; print $F[8]')

awk on vmstat to get si,so


How to get aggregated data in moor_flutter?

Question: Let's say I have 2 simple tables Users and Orders:

Users has columns Id

Orders has columns Id and UserId

How do I get all orders of a user easily using moor_flutter and return it as a stream of the following model?
class UserModel {
  final String id;
  final List<OrderModel> orderModels;

  UserModel(this.id, this.orders);
}

class OrderModel {
  final String id;

  OrderModel(this.id);
}

This is the official documentation but it is not covering this use case.
Equivalent call with EFCore and C# would be:
public async Task<IEnumerable<UserModel>> GetUserOrders(String userId)
{
    return await _db.Users
        .Include(user  => user.Orders)
        .Where(user => user.Id == userId)
        .Select(user => new UserModel
        {
            Id = user.Id,
            OrderModels = user.Orders.Select(order => new OrderModel
            {
                Id = null,
            }).ToList()
        })
    .ToListAsync();
}

Answer: I faced the same problem recently. I was confused to use Joins as per the given example in documentation.
What I have done is:
The created class (in database file only. see below example) has two objects which you want to join(combine). I wrote the query in a class of database.
You will get better understanding with example:
@UseMoor(
  tables: [OfflineProductMasters, OfflineProductWiseStocks],
)
class MyDatabase extends _$MyDatabase {
  // we tell the database where to store the data with this constructor
  MyDatabase() : super(_openConnection());

  // you should bump this number whenever you change or add a table definition. Migrations
  // are covered later in this readme.

  @override
  int get schemaVersion => 1;

  Future<List<ProductWithStock>> getProductWiseStock(String searchString, int mappingOfflineSalesTypeId) async {
    try {
      final rows = await (select(offlineProductMasters).join([innerJoin(offlineProductWiseStocks, offlineProductMasters.itemId.equalsExp(offlineProductWiseStocks.itemId))])
        ..where(offlineProductWiseStocks.salesTypeId.equals(mappingOfflineSalesTypeId) & offlineProductMasters.productName.like('$searchString%'))
        ..limit(50)
      ).get();
      return rows.map((row) {
        return ProductWithStock(
          row.readTable(offlineProductMasters),
          row.readTableOrNull(offlineProductWiseStocks),
        );
      }).toList();
    }catch(exception){
      print(exception);
      return Future.value([]);
    }
  }
}

class ProductWithStock {
  final OfflineProductMaster offlineProductMaster;

  final OfflineProductWiseStock? productWithStock;

  ProductWithStock(this.offlineProductMaster, this.productWithStock);
}

Now you got the structure that how you can use this type of query. Hope you will write your query in this way.
I don't know whether you have solved it or not. If solved then please post the answer so others can get help.
Thank you.
Comment: What I have ended up doing is similar. Your code is part of the idea but doesn't answer my question directly. I will add an answer.
Answer: This feels like a hacky workaround but what I ended up doing is  that I created 2 classes called HabitWithLogs and HabitModel. I put my query result into HabitWithLogs instances and then group them into HabitModel instances.
Data classes:
class HabitWithLog {
  final Habit habit;
  final HabitLog? habitLog;

  HabitWithLog({required this.habit, required this.habitLog}) : assert(habitLog == null || habitLog.habitId == habit.id);
}

class HabitModel {
  final Habit habit;
  final List<HabitLog> habitLogs;

  HabitModel({required this.habit, required this.habitLogs});
}

Dao method:
Future<List<HabitModel>> getAllHabits() async {
  // Get habits and order
  final query0 = (_db.select(_db.habits)..orderBy([(t) => OrderingTerm(expression: t.order, mode: OrderingMode.asc)]));

  // Join with habit logs
  final query1 = query0.join([
    leftOuterJoin(_db.habitLogs, _db.habitLogs.habitId.equalsExp(_db.habits.id)),
  ]);

  // Naive way that return the same habit multiple times
  final hwlList = query1.map((rows) => HabitWithLog(
        habit: rows.readTable(_db.habits),
        habitLog: rows.readTableOrNull(_db.habitLogs),
      ));

  // Group hwlList by habits
  final groups = (await hwlList.get()).groupListsBy((hwl) => hwl.habit);

  // Map grouping
  return groups.entries
      .map((group) => HabitModel(
            habit: group.key,
            habitLogs: (group.value[0].habitLog == null) ? List<HabitLog>.empty() : group.value.map((hwl) => hwl.habitLog!).toList(),
          ))
      .toList();
}

Mapping the stream feels terrible and should not be the only way to achieve this.


Gostaria da opinião de vocês sobre um Diagrama Entidade-Relacionamento de um script do POSTGRESQL

Question: Estou fazendo um trabalho da faculdade cujo o objetivo é fazer um banco de dados de uma biblioteca particular e elaborar um diagrama entidade-relacionamento do mesmo , fiz o script no postgresql mas tenho muita dificuldade na hora de passar a fazer o diagrama no brmodelo, principalmente na parte de cardinalidade, poderiam me ajudar? Aqui está o meu script da biblioteca. Logo abaixo postarei o DER.
<code>CREATE TABLE CATEGORIA(
ID SERIAL PRIMARY KEY,
DESCRICAO VARCHAR (50) NOT NULL
);

CREATE TABLE EDITORA(
ID SERIAL PRIMARY KEY,
NOME VARCHAR (50) NOT NULL
);

CREATE TABLE AUTOR(
ID SERIAL PRIMARY KEY,
NOME VARCHAR (50) NOT NULL
);

CREATE TABLE LIVRO(
  ID SERIAL PRIMARY KEY,
  NOME VARCHAR (50) NOT NULL,
  ID_CATEGORIA INT,
  ID_AUTOR INT,
  ID_EDITORA INT,
  FOREIGN KEY (ID_CATEGORIA) REFERENCES CATEGORIA(ID),
  FOREIGN KEY (ID_AUTOR)     REFERENCES AUTOR(ID),
  FOREIGN KEY (ID_EDITORA) REFERENCES EDITORA(ID)
);
</code>
O DER:
Comment: Olá Emanoel! Seja bem-vindo à nossa comunidade. Vou elaborar uma resposta e já já publico para você.
Comment: Obrigado, Mateus! Aguardando :D
Comment: Sua DML não corresponde ao diagrama. De acordo com sua DML um livro está relacionado a 0 ou 1 categoria (idem autor e editora). Em seu diagrama um livro está relacionado a N categorias (idem autor e editora). Para implementar um relacionamento N:N você precisa criar uma tabela auxiliar em seu modelo físico, assim deveria existir uma tabela Livro-Autor que relacionasse cada autor com todos os seus livros e cada livro com todos os seus autores (idem categoria e editora). Seu modelo prevê que um livro possa ter diversas editoras?
Comment: opa amigo, editei as cardinalidades. seria dessa forma ?
Comment: @anonimo me perdoe a correção: DDL (Data Definition Language). DML é Manipulation (Manipulação dos dados, não das estruturas). Criação de tabelas é DDL ;-)
Comment: @Mateus: correto. Falha minha.
Comment: @emanoel: agora corresponde à sua DDL, resta saber se corresponde a realidade sendo modelada, mas você não postou nada que pudesse elucidar este pontos. Por exemplo no mundo real um livro pode ter diversos autores e um autor pode escrever diversos livros, seria um relacionamento N:N.
Comment: No brmodelo (que eles pedem pra gente fazer) não existe relacionamento N:N, o correto então seria 0:N?
Comment: Um relacionamento (A) N:N (B) é traduzido, no modelo físico, em (A) 0:N (A-B) N:0 (B), ou seja é criada uma tabela intermediária com a combinação das chaves estrangeiras. Não conheço este tal de brmodelo mas pode ser que você já tenha que criar estas tabelas intermediárias nele.
Answer: O MER (modelo entidade relacionamento) deve ser o ponto de partida para você
Elaborar seu exercício. Claro, mais tarde você desenvolverá seu próprio
Método para poder mapear certinho as entidades, seus relacionamentos e transformar
Is
Com a prática, você vai perceber que é muito mais fácil visualizar o modelo de maneira inversa (do banco para o modelo e perceber as deficiências).
Ao invés de responder sua pergunta por completo e, aliás projetar isso depende muito do nível que você quer chegar, podemos simplificar demais ou deixar completo demais (esse é o risco que toda a modelagem corre), vou me propor a responder sua pergunta de uma maneira que te ensine a refletir sobre a abstração e modelagem. É isso que você está precisando pelo que percebi na sua pergunta. E não é difícil.
Vamos lá...
Substantivos tendem a ser Entidades no Modelo:
Verbos tendem a ser papéis / relacionamentos
Substantivos: Livro, Autor, Editora
Agora vamos pensar nos verbos para enxergar as relações entre as entidades (tudo no singular)
Livro é CLASSIFICADO em Categoria <<>> Categoria CLASSIFICA livro
Autor REDIGE Livro <<>> Livro é REDIGIDO por Autor
Tradutor TRADUZ Livro <<>> Livro é TRADUZIDO por Tradutor
(Mas porque precisamos pensar nos tradutores revisores etc? Porque num sistema de biblioteca a classificação considera diversos dados, olhe a ficha catalográfica de um livro).
Editora PUBLICA Livro
Livro é PUBLICADO por Editora
Quando o livro é publicado, existe uma edição! Portanto não é o Livro que é publicado, e sim a EDIÇÃO dele, que possui, número, data etc.
Agora, vamos observar melhor as relações
A Editora publica de fato o Livro? Não, fisicamente a publicação está associada a uma edição que tem tiragem, edição, data, revisão e muitos outros atributos.
Autor redige livro? Como fica co-autor? E o tradutor?
Não seria melhor ao invés de ter uma Entidade chamada AUTOR ter uma chamada pessoa, e ela assume um papel de participação? Opa! Participação? Em quê? Participação no Livro.
Então veja um exemplo apenas para as entidades:
PESSOA <<<< PARTICIPAÇÃO >>>>> LIVRO
O resto vou deixar para você terminar seu trabalho ;-)
(Treine bastante modelagem!)

**Agora a bomba para você pensar: **
MAS NO MEU MODELO COMO FICARIA SE NA SEGUNDA EDIÇÃO O TRADUTOR fosse outra pessoa de um determinado livro? Aliás, e se trocássemos o nome do relacionamento Participação para "Edição"? (agora é hora de você se exercitar por aí :-D)
Comment: Opa, Mateus. Agradeço muito sua atençao e dicas. de acordo com meus colegas da faculdade esse modelo ai nao é aceito, tbm nao vi ele nas aulas ou no livro. Tem que ser DER criado no BrModelo, seguindo os conceitos desse que postei :(
Comment: @emaonel.exe MER é uma coisa DER é outra. Quando vi suas tabelas, logo notei que vc não pensou na modelagem CONCEITUAL que é usando o MER. O DER vem depois. Faça esse exercício da forma como estou te orientando, não para entregar, para aprender. Entregar, não é o objetivo final. Aliás o BrModelo é inútil nas empresas. Nem deveria ser ensinado mais na graduação. Porque além dele ser cheio de bugs, funcionar só no Windows e quando vc dá um control z nele some tudo (em algumas versões) não tem a notação mais clássica da modelagem que é a do Peter Chen. Mostre essa resposta ao seu professor.
Comment: @emaonel.exe essa aula deve servir para você entender melhor: https://course.ccs.neu.edu/cs3200sp18s2/download/L08-ER.pdf
Comment: Ok. Vou dar uma olhada. Obg


Android build variants on travis.ci

Question: I currently have an Android project using gradle and integrated with travis.ci which has different productFlavors and buildTypes. When the "connectedCheck" task is then executed on travis.ci, it tries to package all build variants (all combinations of flavors and types). Some of them fail as the release builds need password input which I can't automate at the moment. Is there a way to tell travis.ci to build and test only a certain build variant of an Android project?
Comment: I suppose it's possible. You just probably need to specify the tasks for variants that You'd like to be built - not for all variants. How is the build process invoked with travis?
Comment: run `gradle tasks` and you will see tasks related to each combination of flavour/type. So in your travis build only run these specific tasks
Comment: Thx, running a connectedAndroidTestt task instead of connectedCheck seems to do the trick.
Comment: Also, I had to set the assemble task in the install section of the .travis.yml:
Comment: install:
  - TERM=dumb ./gradlew -s assemble
Comment: You should post your solution as an answer.
Answer: Say you only want to run the product flavor Trial and the build type Debug.
Instead of running ./gradlew assemble connectedCheck, which is similar to what you're doing, run this instead:
./gradlew assembleTrialDebug connectedCheckTrialDebug

Answer: So here's how I made it work:
Run a connectedAndroidTest<productFlavor><buildType> task instead of connectedCheck.
Also set the assemble task in the install section of the .travis.yml:
install: - TERM=dumb ./gradlew -s assemble<productFlavor><buildType>

Android build variants on travis.ci


How do I alter the route defined by another module?

Question: In other words, what is the Drupal 8 equivalent of hook_menu_alter()?
Drupal 8 still uses hook_menu(), but for what I can see, the information returned by the hook is different from what the hook returned in Drupal 7. For example, the definition given in user_menu() for user is the following.
  $items['user'] = array(
    'title' => 'User account',
    'title callback' => 'user_menu_title',
    'weight' => -10,
    'route_name' => 'user_page',
    'menu_name' => 'account',
  );

The route_name property links to an entry in the user.routing.yml file.
user_page:
  pattern: '/user'
  defaults:
    _content: '\Drupal\user\Controller\UserController::userPage'
  requirements:
    _access: 'TRUE'

This is different from what done with Symphony, and it confuses me about how a module can alter the route defined from another user.
The only function that is still invoking hook_menu_alter() is menu_router_build(), but that function still contains code that needs to be updated, since it is still using the now deprecated drupal_alter().
  // Alter the menu as defined in modules, keys are like user/%user.
  drupal_alter('menu', $callbacks);
  foreach ($callbacks as $path => $router_item) {
    // If the menu item is a default local task and incorrectly references a
    // route, remove it.
    // @todo This may be removed later depending on the outcome of
    // http://drupal.org/node/1889790
    if (isset($router_item['type']) && $router_item['type'] == MENU_DEFAULT_LOCAL_TASK) {
      unset($callbacks[$path]['route_name']);
    }
    // If the menu item references a route, normalize the route information
    // into the old structure. Note that routes are keyed by name, not path,
    // so the path of the route takes precedence.
    if (isset($router_item['route_name'])) {
      $router_item['page callback'] = 'USES_ROUTE';
      $router_item['access callback'] = TRUE;
      $new_path = _menu_router_translate_route($router_item['route_name']);

      unset($callbacks[$path]);
      $callbacks[$new_path] = $router_item;
    }
  }

Answer: Allow views to override existing routing items just uses existing functionality.
If you want to change the information attached to a route, not the menu,
like the actual used controller, or the requirements (permission/role etc.)
you can use an event provided by Drupal:
  <?php

  use Drupal\Core\Routing\RouteBuildEvent;
  use Drupal\Core\Routing\RoutingEvents;
  use Symfony\Component\EventDispatcher\EventSubscriberInterface;

  class RouteSubscriber implements EventSubscriberInterface {

   /**
    * {@inheritdoc}
    */
   public static function getSubscribedEvents() {
      $events[RoutingEvents::ALTER] = 'alterRoutes';
     return $events;
   }

  /**
   * Alters existing routes.
   *
   * @param \Drupal\Core\Routing\RouteBuildEvent $event
   *   The route building event.
   */
  protected function alterRoutes(RouteBuildEvent $event) {
    // Fetch the collection which can be altered.
    $collection = $event->getRouteCollection();
    // The event is fired multiple times so ensure that the user_page route
    // is available.
    if ($route = $collection->get('user_page')) {
      // As example add a new requirement.
      $route->setRequirement('_role', 'anonymous');
    }
  }

  }

Additionally you have to register a service with the tag 'event_subscriber' for this class.
Comment: There are details for setting up the service registration in [Altering existing routes and adding new routes based on dynamic ones](https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones).
Comment: The tag to use for the service is the most important part. Without that, the service would not be added to the event subscribers list, and it won't be invoked.
Comment: The code example works good, but event method (alterRoutes) should be public, instead of protected.
Answer: Since I asked the question, Drupal 8 core code has been changed. Some of the issues about routes have been fixed.
hook_menu() isn't used from Drupal 8 anymore; the routes a module uses are defined in a .routing.yml file (for example user.routing.yml). Alter hooks are still used, but since hook_menu() isn't invoked from Drupal core, hook_menu_alter() won't be invoked.
The steps necessary to alter a route defined from other modules are the following:

Define a service tagged as event_subscriber (The tag is the important part, or the service would not work as expected.)
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Create a class that extends RouteSubscriberBase
namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change the route associated with the user profile page (/user, /user/{uid}).
    if ($route = $collection->get('user.page')) {
      $route->setDefault('_controller', '\Drupal\mymodule\Controller\UserController::userPage');
    }
  }

}

For real implementation examples of alterRoutes(), see AdminRouteSubscriber::alterRoutes() or RouteSubscriber::alterRoutes() .
protected function alterRoutes(RouteCollection $collection) {
  foreach ($collection->all() as $route) {
    if (strpos($route->getPath(), '/admin') === 0 && !$route->hasOption('_admin_route') && static::isHtmlRoute($route)) {
      $route->setOption('_admin_route', TRUE);
    }
  }
}

protected function alterRoutes(RouteCollection $collection) {
  $mappers = $this->mapperManager->getMappers($collection);
  foreach ($mappers as $mapper) {
    $collection->add($mapper->getOverviewRouteName(), $mapper->getOverviewRoute());
    $collection->add($mapper->getAddRouteName(), $mapper->getAddRoute());
    $collection->add($mapper->getEditRouteName(), $mapper->getEditRoute());
    $collection->add($mapper->getDeleteRouteName(), $mapper
      ->getDeleteRoute());
  }
}

Notice that compared with earlier Drupal 8 releases, some details are changed.

The route name is changed from user_page to user.page
The requirements for that route changed from _access: 'TRUE' to _user_is_logged_in: 'TRUE'
The property to set a route controller changed from _content to _controller
Answer: See Altering existing routes and adding new routes based on dynamic ones; it worked nicely for me to remove /search handled by the Search module. In my case, I used the following code.
<?php
/**
 * @file
 * Contains \Drupal\ua_sc_module\Routing\SearchAlterRouteSubscriber.
 */

namespace Drupal\ua_sc_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class SearchAlterRouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Remove the /search route.
    if ($collection->get('search.view')) {
      $collection->remove('search.view');
    }
  }

}


How many triangles are in this figure?

Question: How many triangles are there in the given figure?

I counted 12 but the solution manual says 14. If you have any tips on counting triangles in figures like this please advise. I have to prepare for aptitude test.
Comment: Iterate over all triples of vertices.  If they form a triangle, count it, else proceed to the next triple.  In practice, it may be easier to actually look at each pair of vertices who are connected by a line and look to see if there are other vertices who are also connected to both of the endpoints of your original line.
Answer: There are, indeed, 14 triangles:
Comment: Did you construct this by hand, or algorithmically @ParclyTaxel?
Comment: @DavidGStork By hand, in Inkscape (the same tool I use to draw ponies).

How many triangles are in this figure?


Como recuperar o ID do elemento selecionado no asp:Repeater via javascript?

Question: Eu tenho um asp:Repeater e preciso recuperar no javascript o ID do item referente ao registro exibido no asp:Repeater.
Veja como esta o meu asp:Repeater
<asp:Repeater ID="rpt" runat="server" OnItemDataBound="rpt_OnItemDataBound">
    <ItemTemplate>

                <asp:HiddenField runat="server" ID="hdnID" Value='<%# Eval(" ID ") %>' />
                <asp:Label runat="server" ID="lblNome" Text='<%# Eval(" Nome ") %>' />

                <asp:TextBox runat="server" ID="txtData" ReadOnly="True" CssClass="Data" />

                <asp:LinkButton runat="server" ID="btnInformacoes" Text="Informações" Visible="False" />

    </ItemTemplate>
</asp:Repeater>

Veja que eu tenho um asp:HiddenField que armazena o ID.
O que preciso é recuperar este ID para passar para a função javascript abaixo.
$.ajax
            ({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "listas.aspx/Listar",
                data: "{'id':'" + "58" + "'}", // nesta linha, no lugar do 58, quero passar o ID que esta no meu asp:Repeater.
                dataType: "json",
                success: function (data) {
                    alert('Sucesso');
                },
                error: function (result) {
                    alert('Erro');
                }
            });

Alguém tem alguma ideia de como posso fazer isto?
Comment: Você usa `MasterPage`?
Comment: @Jota eu uso sim.
Answer: Consegui resolver o problema da seguinte maneira.
segue o código javascript com a solução:
$(".elemento").click(function () {
    var index = this.id.substr(this.id.length - 1, 1);
    var id = $("[id*='hdnID']")[index].value;
    $.ajax
       ({
           type: "POST",
           contentType: "application/json; charset=utf-8",
           url: "listas.aspx/Listar",
           data: "{'id':'" + id + "'}",
           dataType: "json",
           success: function (data) {
                alert('Sucesso');
           },
           error: function (result) {
                alert('Erro');
           }
       });
});

Comment: Ribeiro de Agusto Então você pode marcar a resposta como certa.
Comment: Só posso aceitar minha própria resposta depois de 2 dias. Isso é bom, vai que alguém tem uma idéia melhor.


Using eigenvectors to find the general solution from a system of equations

Question: \begin{bmatrix}-13&40&-48\\-8&23&-24\\0&0&3\end{bmatrix}
Consider the matrix above. This corresponds to
\begin{align*}
x_{1}'&=-13x_{1}+40x_{2}-48x_{3}\\
x_{2}'&=-8x_{1}+23x_{2}-24x_{3}\\
x_{3}'&=3x_{3}
\end{align*}
What I want to do is use eigenvectors to find the general solution. First I computed $\det(A-\lambda I)=0$. From this I got my eigenvalues to be $\lambda = 7$ and $\lambda = 3$ (this one is multiplicity 2).
Next I would find $(A-\lambda I)x=0$ where $x$ is the eigenvector I am looking for. For $\lambda=7$, my eigenvector came out to be,
\begin{bmatrix} 2\\1\\0 \end{bmatrix}
So no problems here. On the other hand, I had some difficulties for when $\lambda = 3$. The matrix I would be solving for is
\begin{bmatrix} -16&40&-48&0 \\ -8&20&-24&0 \\ 0&0&0&0 \end{bmatrix}
When I do this I obtain,
\begin{bmatrix} 1&-2.5&3&0 \\ 0&0&0&0 \\ 0&0&0&0 \end{bmatrix}
so $$x_{1} -2.5x_{2}+3x_{3} = 0.$$
From here I am not sure how to get the two eigenvectors. The computer told me they are,
\begin{bmatrix} -3 \\ 0 \\ 1 \end{bmatrix} and \begin{bmatrix} 5 \\ 2 \\ 0 \end{bmatrix}
but I have no idea how to get these from what I have remaining. Also how would I write the general solution?
Comment: You have $x_{1} = 2.5x_{2}-3x_{3}$. You just want to pick values such that you have two linearly independent eigenvectors. Do you see how the two eigenvectors (choose values randomly - eigenvectors are not unique) satisfy this relation? You have two free variables, $x_2$ and $x_3$. Pick them randomly so you get two linearly independent eigenvectors - they can be anything as long as that condition is satisfied.
Comment: That is correct. However, an eigenvector can never be a zero vector. So, you could have chosen $x_2 = \dfrac{2}{5}, x_3 = 0$, so $x_1 = 1$, for example.
Comment: Since you can find three linearly independent eigenvectors (you have a repeated eigenvalue - so this may not always be true and you might have to resort to generalized eigenvectors and Jordan Forms), it is $$X(t) = c_1 e^{\lambda_1 t} v_1 + c_2 e^{\lambda_2 t} v_2 + c_3 e^{\lambda_3 t} v_3 $$
Comment: You found three LI eigenvectors - so it is **not** a defective matrix - you have a diagonalizable matrix. The form I show is how you would write it out. You can show the eigenvalue and eigenvectors in the solution.
Comment: So the eigenvectors the computer generated don't necessarily have to be the eigenvectors I write down? Those are just two out of infinitely many of them?
Comment: If you think about it, $Av_1 = 3v_1$ and $Av_2 = 3v_2$, so really if I let $\omega = \lambda v_1 + \mu v_2$, then $A\omega = A(\lambda v_1 + \mu v_2) = A\lambda v_1 + A\mu v_2 =\lambda Av_1 + \mu A v_2 = 3\lambda v_1 + 3\mu v_2 = 3(\lambda v_1 + \mu v_2) = 3 \omega$. Does this help? (So long as $\omega \neq 0$ ofc)
Comment: Thanks. That does help. My only other question here is, if I have all the eigenvectors, what would the general solution look like?
Comment: Thank you so much Moo. I appreciate it and have learned a lot here. I have just one question. With the problem I am working with, can I write it in the form above that you just stated or do I have to do more? I just wanted to double check. I have seen examples of a defective matrix and it looks like more has to be done for the general solution. Didn't know if I had a defective matrix here.
Answer: Solving the System of linear Equations
So it seems you want to solve the system of equations
$$
Ax =
\begin{pmatrix}-13&40&-48\\-8&23&-24\\0&0&3\end{pmatrix}
\begin{pmatrix} x_1 \\ x_2 \\ x_3 \end{pmatrix}
=
\begin{pmatrix} x'_1 \\ x'_2 \\ x'_3 \end{pmatrix}
= x'
$$
Where the $x'$ is given and the $x_j$ are looked for.
You would normally solve this by calculating the inverse of $A$, since then
$$
x = A^{-1} x'
$$
But let's say you really want to solve this by using the eigenvalues and eigenvectors. You have already determined both of these, providing the change of base matrix $S$ which contains the eigenvectors
$$
S =
\begin{pmatrix}
2 & 5 & -3 \\
1 & 2 & 0 \\
0 & 0 & 1
\end{pmatrix}
$$
which accomplishes
$$
S^{-1} A S = D =
\begin{pmatrix}
7 & 0 & 0 \\
0 & 3 & 0 \\
0 & 0 & 3
\end{pmatrix}
$$
We can now solve for $x$. Using the above,
\begin{align*}
x &= A^{-1} x'
\\&= (SDS^{-1})^{-1} x'
\\&= SD^{-1}S^{-1} x'
\\&=
\begin{pmatrix}
2 & 5 & -3 \\
1 & 2 & 0 \\
0 & 0 & 1
\end{pmatrix}
\begin{pmatrix}
\frac{1}{7} & 0 & 0 \\
0 & \frac{1}{3} & 0 \\
0 & 0 & \frac{1}{7}
\end{pmatrix}
S^{-1} x'
\end{align*}
As you can see, we do not yet have the solution, since we don't know what $S^{-1}$ looks like. So what's left to do is: calculate the inverse of $S$, multiply everything and be done.
(So whatever method you use, you have to calculate the inverse of some matrix)

Getting the Eigenvectors
To determine the last two eigenvectors, you got the equation
$$
x_1 - 2.5 x_2 + 3 x_3 = 0
$$
whose solutions $(x_1,x_2,x_3)$ you want to find. What the equation tells us is, that if we are given two of the variables, the third one (for example $x_1$) will be determined.
$$
x_1 = 2.5 x_2 - 3 x_3
$$
Thus the solutions can be written as
$$
( 2.5 x_2 - 3 x_3 , x_2 , x_3 )
\equiv
\begin{pmatrix}
2.5 x_2 - 3 x_3 \\
x_2 \\
x_3
\end{pmatrix}
=
x_2
\begin{pmatrix}
2.5 \\
1 \\
0
\end{pmatrix}
+
x_3
\begin{pmatrix}
- 3 \\
0 \\
1
\end{pmatrix}
~~~~~~~ \text{with} ~~ x_2 , x_3 \in \mathbb{R}
$$
Any solution of this form is an eigenvector. Since you need two eigenvectors, you take two different solutions. For example the solutions with
$$
(x_2,x_3) = (2,0) ~~~\text{or}~~~ (0,1)
$$
Which yield the eigenvectors that the computer gave you.


How do I compare multiple runs of K-means?

Question: I have results of best centroids for multiple (10) runs of k-means. How do I compare these weights to check if they are close to each other or different?
My goal is to check weather I get to the same local minima after training with random initial centroids.
Answer: First off, unless your clustering problem is a trivial clustering problem the global minima will be virtually impossible to solve for (requires enumerating through all possible cluster points). Therefore the solution of multiple different runs will most likely place you in multiple local minimas.
Here are a couple resources discussing why the k-means algorithm's do not find the global minima.
https://stackoverflow.com/questions/14577329/why-doesnt-k-means-give-the-global-minima
Why doesn't k-means give the global minimum?
One way to compare the learned weights is to compare the expressive power of their respective classifiers. One way to do so is by utilizing the squared L2 difference.
$$\sum_{c}\sum_{x \in c}{(c-x)^2}$$
Where $c$ is ever cluster, and $x$ represents ever data-point registered to that cluster. The smaller the loss the better the classifier.
I don't believe that directly comparing the clusters weights gives you much information about individual run's of k-means.
EDIT:  Authors comment clarified the question a little bit more.
Let's say we want compare the weights of two k-means. Let us say that the $i$th k-means produces $k$ centroid's $C_i: {c^i_0,c^i_1,...c^i_k}$.Now the problem with directly comparing clusters at the same index for different k-mean runs is that clusters do not necessarily have to be localized to a specific index. In one run a centroid might appear in the first index, while in a separate run that same centroid might appear in a different index. Here is a very naive approach.
$$D[i,j]=\begin{bmatrix}
  ||c^i_0-c^j_0||_2^2&||c^i_0-c^j_1||_2^2&||c^i_0-c^j_k||_2^2
\\0&||c^i_1-c^j_1||_2^2&||c^i_1-c^j_k||_2^2
\\0&0&||c^i_k-c^j_k||_2^2 \end{bmatrix}.$$
This is the distance between every centroid in two k-means runs. Keep in mind that this matrix only has to be calculated for the upper triangular due to the symmetry in the distance function used (squared $L2$).Then you can calculate the total distance between two k-mean runs as $$D(i,j)=\sum_i{min(D_i)}$$.
This is a very naive approach. It does not set a constraint that indices can only show up once in the minimum function ($1$ to $1$ mapping between every centroid in two k-mean runs). To generalise this approach to $n$ k-mean runs, you can construct another distance matrix like the one above with every entry $D_{i,j}=D[i,j]$ Let me reiterate that this is a very naive approach. But it does show the distance between two k-means, and it has a nice property that if two k-mean runs did learn the same exact centroids, regardless of order the distance $D[i,j]=0$.
Let me know if this helps.
Comment: Couldn't you just check if you get the same value for the cost function for all the solutions? in that case it means you get to the same local minimum.
Comment: @ArmenAghajanyan Brilliant solution, i have implemented a function to compute your D(i,J) in MATLAB. Now the challenge i am facing is i am getting a matrix that shows the index of closest centroids by its individual mapped feature. (Ci1 Ci2...Cid) were d is data dimension therefore each centroid has multiple different closest index, how will i solve this? I need distance of a centroid as a whole. Ci
Comment: @Young_DataAnalyst The distance between two centroids in my formulation, $||c_0 - c_1||_2^2$ is equal to $\sum_{i=0}^{d}{(c_{1,i} - c_{0,i})^2}$. Essentially you have to subtract the two centroid vectors, square the elements of the resulting vector, and then calculate the sum over that vector. For more information on norms check out: http://www.wikiwand.com/en/Norm_(mathematics)
Comment: Thanks @ArmenAghajanyan your answer is brilliant for comparing how well the weights classified the data. What i am trying to do is slightly different, i am using a different cost function from standard k-means, i am trying to check if the function has multiple local minima, please see my complete question here http://stats.stackexchange.com/questions/186130/how-do-i-compare-two-self-organizing-maps?noredirect=1#comment353577_186130
Comment: @Young_DataAnalyst I added a possible approach to my problem, in the edit of my answer.
Comment: @Simone And I agree with Simone, the same solution should yield the same exact cost.
Answer: To add up to Armen Aghajanyan answer, I guess it is difficult to check if you get the global minimum unless you know theoretical properties of your clustering problem.
As he suggested, you might be limited to compare the 10 solutions between each others. An empirical way to quantify the similarity between clusterings might be using the squared L2 distance indeed.
If you have cluster labels you can also compute the similarity between clusterings by the consensus index. This is just an average similarity between all clustering pairs.
For example you might want to use the Adjusted Mutual Information (AMI) in Matlab (here or here) as similarity measure between two clusterings $U$ and $V$. Then the consensus index (CI) between $n$ clusterings is defined as:
$$
\mbox{CI} = \frac{2}{n(n-1)}\sum_{i < j} \mbox{AMI}(U_i,V_j)
$$
Try to have a look here for reference. If you use an adjusted similarity measure for clustering comparisons the CI is equal to 0 if there the clusterings are random and independent and is equal to 1 when they are identical.
Comment: The Rand index and the adjusted rand index provide a classical approach, this statistic is simply based on pairwise counts between clusterings.  https://en.wikipedia.org/wiki/Rand_index
Comment: Thanks @JonathanLisic, yes you can use any similarity measure between clusterings you like. Actually the adjusted rand index and the adjusted mutual information are connected: http://arxiv.org/abs/1512.01286


Updating cached REST resources

Question: I'm building my first custom REST resources.  I have a custom entity and returning specific fields from it.  However, it's very important that if a specific field changes (a status field) that it is reflected in the response.
What I'm seeing is that I have to clear the cache every time I update the entity.  How do I make sure the response is up-to-date?
I have tried using both \Drupal::entityQuery and \Drupal::entityTypeManager()->getStorage()... but both require a cache clear.  Maybe I'm loading the entity incorrectly?
Answer: It's not about how you load the entity. It's how you build the response. You have to add the correct cache tags. A cacheable response has the method addCacheableDependency(), which accepts objects which provide cache metadata:
$response->addCacheableDependency($entity);

This adds the tag custom_entity:[id] to the cached response. All cached responses with this tag will be invalidated, when the entity is updated.
This is an example from core for the cache data and access checks you need in a response which contains entity data:
Drupal\rest\Plugin\rest\resource::get()
public function get(EntityInterface $entity) {
    $entity_access = $entity->access('view', NULL, TRUE);
    if (!$entity_access->isAllowed()) {
      throw new AccessDeniedHttpException();
    }

    $response = new ResourceResponse($entity, 200);
    $response->addCacheableDependency($entity);
    $response->addCacheableDependency($entity_access);

    if ($entity instanceof FieldableEntityInterface) {
      foreach ($entity as $field_name => $field) {
        /** @var \Drupal\Core\Field\FieldItemListInterface $field */
        $field_access = $field->access('view', NULL, TRUE);
        $response->addCacheableDependency($field_access);

        if (!$field_access->isAllowed()) {
          $entity->set($field_name, NULL);
        }
      }
    }

    return $response;
  }

Updating cached REST resources


Using least squares with an incomplete quadratic basis

Question: I am currently using least squares (LS) to compute gradients/derivatives. I am using LS with an incomplete quadratic basis:
$$\phi = \begin{bmatrix}
1 & x & y & z & 0.5x^2 & 0.5y^2 & 0.5z^2
\end{bmatrix}
$$
rather than the full basis:
$$\phi = \begin{bmatrix}
1 & x & y & z & xy & xz & yz & 0.5x^2 & 0.5y^2 & 0.5z^2
\end{bmatrix}
$$
What are the main disadvantages in using an incomplete quadratic basis over the full quadratic basis?
Answer: The isosurfaces associated to the incomplete basis are spheres, while the complete basis yields quadrics.
Hence the former are more appropriate for isotropic phenomena, with no coupling between the variables.
Notice that the complete basis has more degrees of freedom and will always achieve smaller residual error, possibly giving you a false feeling of a better fit (which can be overfitting).
Comment: Thanks! Another question. Is "1/2" the typical coefficient in front of the squared terms? What is the significance of these coefficients?


How to set the learning rate in scikit-learn's ridge regression?

Question: I'm using scikit-learn's ridge regression:
regr = linear_model.Ridge (alpha = 0.5)

# Train the model using the training sets
regr.fit(X_train, Y_train)

#bias:
print('bias: \n', regr.intercept_)
# The coefficients
print('Coefficients: \n', regr.coef_)

I found (here) the different options for the linear_model.Ridge function, but there is a specific option that I didn't find in the list: How could I set the learning rate (or learning step) of the update function?
By learning rate, I mean:
w_{t+1} = w_t + (learning_rate) * (partial derivative of objective function)
Answer: I refer to learning rate as step size.
Your code is not using the sag (stochastic average gradient) solver. The default parameter for solver is set to auto, which will choose a solver depending on the data type. A description of the other solvers and which to use is here.
To use the sag solver:
regr = linear_model.Ridge (alpha = 0.5, solver = 'sag')

However, for this solver you do not set the step size because the solver computes the step size based on your data and alpha. Here is the code for sag solver used for ridge regression, where they explain how the step size is computed.

The step size is set to 1 / (alpha_scaled + L + fit_intercept) where L is
          the max sum of squares for over all samples.

Line 401 shows how sag_solver being used for ridge regression.
Comment: Thanks so much! But then, it seems to be using a step size only for SAG, and not for the "regular" (i.e., batch) Gradient Descent. Is  there a reason why?


SSMTP and .forward

Question: I configured the SSMTP in a ubuntu server 13.04.
Configured the root user email address.
Everything works correctly.
But, now I want to configure the "~/.forward" to send all emails to another address.
I created the file at the root user home /root/.forward, and added to it:
firstname.lastname@example.com

But this isn't working. When I sent a email to root, only the root email receives the email.
I'm sending emails with:
echo Msg body | mail -s Subject root

What I need to do to get the .forward file working?
Comment: I could be wrong, but I didn't think SSMTP support `.forwards`.  Did you see some document somewhere saying that it did?  If you really nead that, then you probably need a different MTA.
Answer: Unfortunately,  ssmtp does not read ~/.forward. Here is a quote from the ssmtp manpage:

It does not do aliasing, which must be done either in the user agent or on the mailhub.
  Nor does it honor .forwards, which have to be done on the recieving host. It especially
  does not deliver to pipelines.

SSMTP and .forward


Moving the Views header

Question: I've enabled the Result summary in the Header for my view... However, it is being displayed at the top of the conetnt. I would like it to be display in between the search form and the search results. Is the only way to do this via a template?
The view is made up of nodes being imported using a Feeds module.
They are displayed in a table, and there is a search on top...
Comment: Please give more details as in what you are trying to achieve, what the view is about, etc.
Comment: Edited my post. Hope this is enough detail...
Comment: Your search is a filter right?
Answer: I think using a template file will be the easiest way to do this.
In your view => click Theming information

=> Select the tpl file that suits you best
=> place that tpl file in your templates folder under your theme
=> for the content of the file
=> under Theming Information in your view click Display output
=> copy that content to your tpl and change the position of your header
=> come back to Theming Information and click Rescan template files - your newly added tpl(under your theme directory) should be highlighted(bold) now, which means you tpl is up and working!

Hope this helps.
[I am sure you might know how to do all this, yet putting it in details might help somebody else looking for the same solution who hasn't yet learned how to :)]

Moving the Views header


How do I simplify this verbose ADO.NET Database Code

Question: Trivial question - I'm inexperienced with C#.
I have the following code to call a multi-parameter SQL-Server stored procedure.
It works and it is nice and explicit i.e. easy to read what is happening but it's very verbose.
Is there a standard shorter version of the following?
using(var conn = new SqlConnection(this.connString))
using(var comm = new SqlCommand(DatabaseLayer.procSendEmail,conn))
{
  comm.CommandType = CommandType.StoredProcedure;

  SqlParameter pmIsTemplate = new SqlParameter("@IsTemplate",SqlDbType.TinyInt);
  SqlParameter pmDateInsertKey = new SqlParameter("@DateInsertKey",SqlDbType.Int);
  SqlParameter pmEmailTO = new SqlParameter("@EmailTO",SqlDbType.NVarChar,1000);
  SqlParameter pmEmailBody = new SqlParameter("@EmailBody",SqlDbType.NVarChar,-1);
  SqlParameter pmEmailImportance = new SqlParameter("@EmailImportance",SqlDbType.TinyInt);
  SqlParameter pmEmailSubject = new SqlParameter("@EmailSubject",SqlDbType.NVarChar,1000);
  SqlParameter pmSuccess = new SqlParameter("@Success",SqlDbType.Bit);

  pmIsTemplate.Direction        = ParameterDirection.Input;
  pmDateInsertKey.Direction     = ParameterDirection.Input;
  pmEmailTO.Direction           = ParameterDirection.Input;
  pmEmailBody.Direction         = ParameterDirection.Input;
  pmEmailImportance.Direction   = ParameterDirection.Input;
  pmEmailSubject.Direction      = ParameterDirection.Input;
  pmSuccess.Direction           = ParameterDirection.Output;

  comm.Parameters.Add(pmIsTemplate);
  comm.Parameters.Add(pmDateInsertKey);
  comm.Parameters.Add(pmEmailTO);
  comm.Parameters.Add(pmEmailBody);
  comm.Parameters.Add(pmEmailImportance);
  comm.Parameters.Add(pmEmailSubject);
  comm.Parameters.Add(pmSuccess);

  ...
  ...

Comment: You can `comm.Parameters.Add("@IsTemplate", SqlDbType.TinyInt).Value = xxx;`
Comment: Have you considered using `Dapper`?
Comment: You don't need to set `ParameterDirection.Input`. It is the default.
Comment: You should be able to use comm.Parameters.AddWithValue(string,object).  Just be sure to do a null check, and use DBNull.Value instead of null for the object parameter.
Comment: @CodeMonkey Read [Can we stop using AddWithValue() already?](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/)
Answer: Maybe doing something like this:
using (var conn = new SqlConnection(this.connString))
{
    using (var comm = new SqlCommand(DatabaseLayer.procSendEmail, conn) { CommandType = CommandType.StoredProcedure })
    {
        comm.Parameters.Add(new SqlParameter("@IsTemplate", SqlDbType.TinyInt));
        comm.Parameters.Add(new SqlParameter("@DateInsertKey", SqlDbType.Int));
        comm.Parameters.Add(new SqlParameter("@EmailTO", SqlDbType.NVarChar, 1000));
        comm.Parameters.Add(new SqlParameter("@EmailBody", SqlDbType.NVarChar, -1));
        comm.Parameters.Add(new SqlParameter("@EmailImportance", SqlDbType.TinyInt));
        comm.Parameters.Add(new SqlParameter("@EmailSubject", SqlDbType.NVarChar, 1000));
        comm.Parameters.Add(new SqlParameter("@Success", SqlDbType.Bit) { Direction = ParameterDirection.Output });
    }
}

Comment: Or even Shorter - `comm.Parameters.Add("@IsTemplate", SqlDbType.TinyInt);` Please also note that the `Add` method returns a reference to the parameter that was  just added, so you can use it to also set it's value, like in Alex's comment to the question.


Converter Json em Array com Jquery

Question: Estou fazendo uma requisição ajax com jquery e Php assim:
// arquivo php
    $json = array(
      "status"=>"true",
      "message"=>"inserido com sucesso"
    );

    echo json_encode($json);

.
// arquivo js
    $.ajax({
        url, url,
        type: "post",
        data: dados,
        success: function(json){
          console.log(json);
        },
        error: function(){
          msg.text("Erro ao fazer requisição");
        }
      });

O meu console.log devolve {"status":"true","message":"inserido com sucesso"} e queria fosse transformado em um array Java Script, como eu poderia fazer essa conversão ?
Comment: Basta adicionar o atributo `dataType: "json"` à sua requisição AJAX.
Comment: funcionou obrigado, acha melhor eu fechar a pergunta ?
Answer: Use o $.map, assim transformara o json em array.
// arquivo js
$.ajax({
    url: url,
    type: "post",
    data: dados,
    dataType: 'json',
    success: function(json){
      let arr = $.map(json, function(el) { return el; })
      console.log(arr['status']);
      console.log(arr['message']);
    },
    error: function(){
      msg.text("Erro ao fazer requisição");
    }
});

Caso queira somente fazer o json do PHP ser um objeto/json no javascript, basta adicionar dataType: 'json'
// arquivo js
$.ajax({
    url: url,
    type: "post",
    data: dados,
    dataType: 'json',
    success: function(json){
      console.log(json.status);
      console.log(json.message);
    },
    error: function(){
      msg.text("Erro ao fazer requisição");
    }
});

Converter Json em Array com Jquery


Populate Dropdown list from a web service without code

Question: I know that in Drupal a drop down list field can be populated with taxonomy terms, but is there a way without having to go custom (custom PHP development) to populate a dropdown list from the results of consuming a web service?
Say I consume a web service that returns the weather for the current week (7 days), I would like to populate the data returned into a dropdown list so that whenever the data is changed at the web service it is automatically reflected in my list.
Is there way to do this in the Drupal UI?
Many Thanks
Answer: I think you have to do it in code call the webservice in a custom module process the results and pass it to the template for display as you need


Is it true that the thumb should be always on top of the piano keyboard when playing?

Question: Piano teachers often say that the thumb should never be outside the piano keyboard, that is : the thumb should always be above the piano keyboard.
I'm not sure if this is correct. I give a counter-argument : if one play dominant 7th arpeggio on C on two octaves for example, on the left hand four first notes, my thumb is outside the keyboard : this is only on the G that I put it : the reason is that in order to have the important extension for this space of fingers, I need to rotate my left hand a bit to the right, thus my thumb naturally is outside the keyboard
This looks almost impossible (apart if one has giant hands) to avoid having the thumb outside the piano keyboard for a non negligible time.
Is it true that the thumb should be always on top of the piano keyboard when playing ?
Comment: I have edited that essential piece of info in. Please try to do that in future.
Comment: You might say it's... a rule of thumb.
Answer: I have never been particularly aware of whether my thumb is over the actual keys or not. In my view you should do whatever works for you.
As a piano teacher I would want beginning students to keep all their 10 fingers above the keyboard, and I would correct them if they were to play so close to the ends of the keys that the thumb was too far away. When passing the thumb under the hand it should not be so low as to need to be beyond the edge of the keys.
I regard this as good general advice, but not a straitjacket.
The advice certainly does not apply universally to keyboards generally; there are organ works where the thumb is used to play a note on the keyboard (manual) below the keyboard being played by the other fingers.
Comment: Honestly, most advice teachers impart to students falls under "good general advice". Gotta learn the basic expectations and posture before you move to more advanced stuff which, in any subject, circumvents those original rules at least to some degree.
Answer: Yes and no. Your thumb can go anywhere if necessary. But generally one requirement for speed and fluency is to have the fingers right above the keys they need to play, so you only need to press down the key without having to move the finger into position first.
Now, if you hold your hands straight the thumbs will not make it onto the keyboard, so anytime you want to use your thumb you need to change the hand angle, which will drastically limit your playing. Instead the default position should have the hand slightly angled in such a way that all fingers are at the necessary position, ready to just press down when you need it. This is why a piano teacher would put emphasis on such things when teaching a beginner, so that the student develops a good posture.
Once you have a good posture this won't be a thing anymore. Most of the time you'll stick to it naturally, and when you don't there might be good reason not to do so.
Comment: When you refer to "hand angle", do you mean rotating, twisting, some other motion? That should be clarified, I think.
Answer: While there can be occasions where one's thumb is away from the keyboard, it's a good idea to consider fingering to see if there's an alternative that allows the thumb to stay in better position.
In the case of the left hand, use the fingering 3-2-1-4.

C E G Bb C E G Bb
3 2 1 4  3 2 1 4

With this approach, the thumb can stay in position over the keys during the 3-2-1, and since now a longer finger will handle the Bb, the thumb will stay naturally over the keys as well.
Another option, in general situations, is to position one's hand closer toward the fall board. Applying this is the C7 case would allow for using a 5-3-2-1-4-3-2-1 fingering by positioning the hand so that the thumb starts off in position of the Bb. This avoids the need for twisting and rotation, provided one is able and comfortable having fingers 2 and 3 playing in between black keys. (However, in this specific case, I still recommend the alternative fingering, which gives smoother execution regardless.)
The GM7 chord presents the same problem. It's address, with photos of the hand position, in Piano: Left handed Gmaj7 chord.
Answer: Just tried that. On the way up, my thumb stays happily above the keys for the change to the second octave, but on the way down, it seems happy to move away, towards me, thus not over the keys at that same change point. Don't think I've ever been told that 'rule', and certainly not mentioned it to any student.
Answer: Just a few thoughts:  Know that a teacher (and internet teachers) only know what they know and they don't know what they don't know, you know? We all think what we know and what we were taught is gospel truth.
First, the thumb isn't a finger and doesn't attach to the hand the way the fingers do.  It is attached to the side of the radius and often when playing down, many teachers teach students to use the thumb's abductor which is its weakest and most sluggish muscle. The thumb's strongest muscle is its flexor but it curls the thumb under the palm and is designed for gripping.  When the thumb is curled under the palm for many people it intersects with the index finger's long flexor tendon and can cause grinding damage.  There are several disorders which can occur by curling the thumb under the palm such as distal intersection syndrome or Linburg-Comstock Anomaly. Also, curling the thumb under the palm creates a tension called a muscular co-contraction.  Some teachers teach pianists to use the thumb through pronation or forearm rotation while others teach to play the thumb straight down using gravity or arm weight.  Some advocate a tilt while others suggest a forward shift.  I personally subscribe to using all of the above simultaneously to avoid any one muscle to be used twice in a row.
An example of teachers not knowing what they were talking about is Bach.  He was a virtuoso whose technique came natural to him.  He didn't know how or what he was doing so he taught his students what he felt and he felt his fingers caressing the keys so he taught his students the carrezando method. What he was actually doing was moving in/out/up/down and he felt like he was caressing the keys as his arm moved his hand across the keys, his arm was doing all the work and his fingers were not doing much and it felt like carrezando. Playing carrezando can facilitate flat finger playing which can lead to long flexor tendonitis and median nerve entrapment.
As far as the thumb being off the keys, all your fingers and digits are different lengths which SHOULD require the pianist to play with an in/out motion.  Curling them to equalize them creates tension*.   So when playing a five finger scale, the thumb plays and when the index plays the arm moves out because the index is longer, the middle finger moves the arm and hand further out.  This will take the thumb off the keys then there is a shift forward to play the shorter ring and further in for the pinky.   When the thumb is off the key, it should never drop below the keys and instead remain naturally and relaxed next to the index.  When you allow the thumb to drop below the keys, it throws off any rotation and gravity of the arm and hand.  Up is very important because you can't play down on the next note if your weight is hanging down. Your arm can only move in one direction at a time and if the thumb is pulling down the arm can't play up.  It is like walking up stairs, your foot raises higher than the next step then comes straight down.  If you don't lift your foot high enough you will trip up stairs.  Dangling the thumb below the keys will throw the balance of everything else off.  It also behooves the pianist to play on the outside edge of the keys because they are a fulcrum and thus, lightest on the edge and heavier the further in you play.
*With all five fingers together, wave bye bye.  It should be effortless.  Now curl and make a claw with your fingers and wave bye bye.  You will probably feel strain.  Likewise, abduct (spread out) all your fingers and wave bye. More strain.  A lot of teachers will then tell their students they need to practice more, prescribe a silly exercise or tell them they need to build strength and endurance.  I suggest they cease moving improperly and the strain will go away. Another fallacy is to tell the student to relax but, relax what?  If you relax the muscles you are using to play, you can't play.  Instead, relax the wrong muscles and employ the proper ones.


Odd anomaly with PHP and jQuery Mobile?

Question: I am having a problem with jQuery and PHP that I can't figure out. To understand, let me explain what I am doing.
I am making a small mobile web-app using jQuery Mobile for the UI and PHP for the server side. I have 95% of the app ready and on the last page I am having a problem.
The first page has three drop-down menus and a submit button. When the button is pressed, the info from the dropdown menus are transmitted via $_POST to the 2nd screen. Here, I verify that I have data and do some operations. If no data is send, I show an error. So far I hope everything makes sense.
Here is the code for the two pages:
Page 1: http://pastebin.com/N0bWdbv0
Page 2: http://pastebin.com/TpbHqGai
On the second page, in the browser I see this: Choose members:  (line 75)
BUT! if I look at the source of the page I don't see it anywhere, instead there is "Error! date" (line 65).
I honestly don't know why I get this inconsistency between what is show and what "View page source" displays.
Any help is greatly appreciated.
Answer: jQuery Mobile uses AJAX by default to navigate between pages in your site. So when you click a link to another page, you're still using the same DOM and bringing another pseudo-page into the DOM. This means that there are no actual page-loads that occur while navigating a jQuery Mobile website (by default) which in turn means that the source of the webpage does not change unless you refresh the page.
You can however see the "live DOM" by using some of the developer tools at your disposal (Chrome has a great set of DOM inspection tools).

Odd anomaly with PHP and jQuery Mobile?


JSF application scoped managed bean injection

Question: I'm developping a web app, with jsf2,spring and hibernate.
I have an "application scoped" managed bean (called "utilsJSF") with JSF util methods, such as:

Reading properties files for getting a message from its key (using getBundle).
Adding a string as a facesmessage to be shown later on a view.
etc

I inject this bean in my "Base Controller" (as a "managed property"), so that all my controllers extend this one, and can access those utilities. Here I have no problem.
But, how can I use these utilities from other classes that are not "managed beans"?
I will explain myself:
I have an exception hierarchy, where each particular exception class has to access a resource bundle (property file), where the key is the name of the exception and the value is the message I'm gonna show to the user. The exception constructor gets the value from the file, stores it in a field of the exception, and then the controller shows the message to the user as a facesmessage.
I can show the message from the controller using the "utilsJSF" managed bean, because I injected it into the BaseController.
But I cannot inject "utilsJSF" into the exception class in order to use it (because the exception classes are not managed beans).
What's the best solution to solve this problem?
Answer: You should refactor all those utility methods (the ones which are (or can be) public static), into a real utility class, not keep it in an application scoped bean.
public final class Faces {

    private Faces() {
        // Prevent construction.
    }

    public static void addGlobalInfoMessage(String summary) {
        FacesContext.getCurrentInstance().addMessage(null,
            new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null));
    }

    // ...
}

This way you can use it everywhere. Create a similar one for getting bundle messages.
Comment: Thank you very much BalusC. Using static methods were my 1st solution for that, and it works. I was just wondering if there exists another way. In fact, I tried putting the utils methods in application scoped bean just because I read it in a website. But I think application scoped beans are for storing application data (constants,static lists,etc), not to hold utility methods, don't you think so? Thank you, I appreciate you very much and read your web. (Sorry if my english isn't very good, but I'm from Spain).
Comment: If the class holds no state, then there's no need to make it a stateful class. An application scoped bean is however useful to expose application wide data into views, such as static dropdown lists.


Find $\lim_{x\to 4}f(x)$

Question: If $\lim_{x\to 4}$$\frac{f(x)-5}{x-2}=1$, find $\lim_{x\to 4}$$f(x)$.
I plugged $4$ into the equation and i found that $f(4)-5=2$ and $f(4)=7$.
How can i find what is $\lim_{x\to 4}$$f(x)$.
Comment: Hint: you can multiply limits
Comment: Can you be a little more specific?
Answer: Well, you are actually almost correct.
$$\lim \limits_{x \to 4} \frac{f(x)-5}{x-2}=1$$
$$ \frac{\lim \limits_{x \to 4}[f(x)-5]}{\lim \limits_{x \to 4}[x-2]}=1$$
$$ \frac{\lim \limits_{x \to 4}f(x)-5}{2}=1$$
$$ \lim \limits_{x \to 4}f(x)=2+5=7$$
which is almost exactly what you did.
However, notice that at no point of time did I mention $f(4)$. I cannot make such conclusion because I have no information that $f$ is continuous.
Comment: You are a life saver thank you :)

Find $\lim_{x\to 4}f(x)$


Views Exposed Filters: how to get functionality shown in this image?

Question: I'm wondering how hard it would be to get the functionality shown in the image, and at the associated webpage, with Views Exposed Filters. How would you go about it? Thanks in advance!
I notice 3 main things:

Entering text in the autocomplete search box causes the select list options to filter. (The matching letters are also underlined, which is fancy but not necessary.)
Selecting an option causes it to fill the search box.
A number after each select list option tells the user how many pieces of content are available.

The actual search box can be seen on this webpage: https://properties.aplaceinthesun.com/AP1724897/Beautifully-Maintained-Four-Bedroom-Villa-For-Sale
Answer: You would need to configure the Select2 or Chosen JQuery component to do this.
Create the list of object with count and apply the one of the above library.
For Drupal use Select2 module
Answer: Chosen

By default the module will automatically apply itself to any select
  elements that have more than 20 options, which is a reasonable default
  for which having Chosen will be useful. To change or disable this
  automatic enhancement, you can change the selectors (or remove all
  selectors) from the Apply Chosen to the following elements field on
  the Chosen administration page.


Clearing bits in a register in assembly

Question: How to write an instruction that clears bits 0 and 1 in the AL register using assembly?
Comment: The CPU is obviously x86 since is talking of AL.
Comment: In what assembler? On what CPU?
Answer: AND AL,11111100b assuming MASM format
Answer: You can clear bits by using the AND -operation.
for each bit index `i`
  result[i] = boolean_and(first[i], second[i])

.--------- commonly associated symbol for the operation
|

&   1 0 <- first argument
-------
1 | 1 0 <- result
0 | 0 0

^--------- second argument

An example with a byte:
00101100
00111010
       &
00101000

So you can use this operation to mask and flip bit regions in a register. Pass in a constant as the second argument which has bits flipped up you want to keep up.
x86 mnemonic: AND a, b
operation: a = a & b

Here's how to do it unless you didn't yet understood it:
AND eax, 0xfffffffc

AL is the lowest byte portion of EAX -register so you can do it this way.
Here's binary -> hexadecimal conversion table:
0000 | 0
0001 | 1
0010 | 2
0011 | 3
0100 | 4
0101 | 5
0110 | 6
0111 | 7
1000 | 8
1001 | 9
1010 | a
1011 | b
1100 | c
1101 | d
1110 | e
1111 | f

Oh, and you should remember this from the back of your head if you're going to be a self-respecting assembly-knowing programmer.
Also read about OR and XOR -bit operations.
Answer: AL is the low byte of the AX register, so you should be able to AND AL 0xFC to mask out the low bits.
AND AL,0xfc

Answer: there is another way to do this by using xor
example:
mov al, ff

xor al, 00000011b

al = fc because we cleared bit 0 and 1

Comment: `xor` only works if both bit 0 and bit 1 were on before the xor, but the question makes no such precondition and wants the bits cleared regardless.
Answer: and al, 0xFD

Adapt it to the assembler your are using: gas, nasm, masm ...
EDIT: Actually it is and al, 0xFC but you get the idea
Answer: equate it to zero?
like
mov al,00000000
ax=16bits
al=8bits
now if anything is ored with al the answer will be the same as what is ored
but
if anything is anded with al the answer will be "0"
so i guess clearing it with all 1s or all 0s depends on your work and how you want to identify that there is nothing in the register.
Comment: it would appear that you didn't actually understand the question and/or don't know how to answer it, which is probably why you got a couple of downvotes. Look at the other (correct) answers to get a better understanding of what's being asked and how to solve it. In general it's probably a good idea to only attempt answering questions if (a) you're reasonably sure that you understand the question and (b) you have some confidence that you can provide a useful answer. Good luck.
Comment: how about a comment why this is so un clear to the negative marker/? whats wrong? am also learning
Comment: he only wants to clear the lowest 2 bits, not the entire register(or sub-register), your method discards too many bits, hence it totally the wrong method, just see the methods above yours.

haha, 14 sec ninja Paul R is :P

Clearing bits in a register in assembly


Area of Overlapping Circles a Convex Function?

Question: All,
I'm not sure how to phrase this. I've calculated the area of overlap of two circles of radius 1, with the first circle centered at $x=0$ and the second at $x=2d$ as
$$A = 2\arccos(d) - 2d\sqrt{1-d^2}$$
I'm pretty confident that this is correct. The circles touch at $x=d$, the midpoint of the centers. This is a convex function for $d\in[0,1]$, which I'm struggling to understand. That means that if I slide a circle from $x=2d$ to $x=-2d$ there will be a cusp in the graph of area, which seems unintuitive?
Is this true? I feel like it should be a smooth curve...
Here is a graph I've generated of this case in MATLAB
GRAPH
Answer: Let's analyse the derivative of our area function at a given $d>0$. As you noted, the circles intersect at $x=d$. Let $h$ denote the height difference of the two intersection points. If we move the right disk a tiny $\epsilon>0$ to the right, then the change in area is approximately $\epsilon h$. This is because at any fixed horizontal line through the intersection, the change in width of the intersection is exactly $\epsilon$ (or approximatly, but only when the horizontal line is so close to the edge that the new intersection does not go through the line.) Since $d>0$, the area decreases, so the derivative is exactly $-h$. However if $d<0$, then the area would have increased, so the derivative would have been exactly $+h$. I believe this is enough to explain the convexity and the cusp in the graph.


SVG text disappears on larger label

Question: I am using Morris.js for making charts. Morris.js uses SVG to draw the graphs. I have set up a JSbin here: JSbin example
Morris.js uses Raphael to draw the svg graphs. The issue is with the labels on the X-Axis. They disappear when the size of labels is too large. I tinkered around with the size of the div element holding the graph and font size of the labels but since the labels are dynamically generated for various users I cannot decide on a fixed value. An ideal solution would be to have the text wrapped up. What can be done to counter the situation?
Morris.js uses the following snippet to make the text svg element.
 this.raphael.text(xPos, yPos, text).attr('font-size', '11').attr('font-family', 'calibri').attr('fill', this.options.gridTextColor);

Comment: Not sure if this is a solution, but you could always just do a nameofplace.substr(0,14) type solution applied to the dynamic variable.
Comment: Had a similar issue, turning texts in my svg to paths (using inkscape) fixed it for me.
Answer: It seems raphael supports multiline strings by putting "\n" in the text. This could be a cheap solution for you, systematically replacing " " by "\n" in your labels.
The other (more tricky) solution would be to replace the "text" element in the SVG generated by raphael by a foreign element that allows word wrapping:
<foreignObject x="20" y="10" width="150" height="200">

Wrapping text using some foreignObject in SVG!

</foreignObject>

or if you need a fallback:
<switch>
  <foreignObject x="160" y="10" width="150" height="200">
Wrapping text using some foreignObject in SVG!
</foreignObject>
  <text x="20" y="20">Your SVG viewer cannot display html.</text>
</switch>

I don't know the best way to do this replacement of "text" by a foreign object: either after the Morris rendering or by hacking Morris/Raphael.
Comment: Thank you for super trick! I have read SVG spec one year ago, but somehow missed this tag definition! Unfortunately, the Morris lib, calculate the width of label and makes decision to draw or not to draw the odd labels. Therefore, after rendering, we have no chance "to fix" it by replacing a part of html/svg tags. But anyway,  is awesome!
Answer: I think the problem definition need more clarification,
at my end the code you have sent works fine, also I have replicated the same in JSFIDDLE that is also working fine..
I think the label problem is done automatically as I have tested the default size you have kept was carrying width 385px when looking in to CSS and 518px when looking the same, in both case the rendered labels were different, in-fact the label exceeding certain width were not rendered. SO there is no meaning to set style and override.
I think the things are built in library. So its a long way to go, or change the library.
let me know which will be convenient way, I will help you accordingly :)
Edit:
However, you can change property of GridTextSize: that is 16 by default
Fiddle2 here I have updated
'gridTextSize:8' that displays all text in size 8.
Not perfect but will do :)
Comment: Changing font size would not work. The example you set has 'North America' and 'South America' missing on my screen. I think it would require a library change.
Comment: Yes Library change is required, but this works if the page width is more. This is an automatic calculation within library which works like `min width = Total width/no of Bar. If Test Size > min width ( do not render Text node)`
Answer: Download not minimized morris.js from there. In zip-archive you can find a file morris.js. Open it in edit mode and change value of default label angle parameter (line 133):
133 |     xLabelAngle: 90,//original value 0

Now, if you really need it minimized, you can compress file by any online js compress tool.

SVG text disappears on larger label