Erro desconhecido na integração com WebService REST

Question: Estou tentando fazer uma requisição do tipo POST usando os componentes: RESRRequest, RESTClient, RESTResponse pelo Delphi Xe8.
Na integração do tipo GET eu consigo fazer normalmente, recebo o retorno normalmente do servidor.
Porém, ao fazer a integração via POST está dando uma excessão na execução: "Execution of request terminated with unknown error".
Pode ser que eu esteja errando em alguma coisa. O servidor espera 2 parâmetros:
1 - HeaderParam, tipo AlfaNumérico, Identificador "Token-Integracao"
2 - BodyParam, tipo Complexo, Identificador "itensResolvidos"

Segue o código que estou usando para fazer a integração:
with fDm do
begin
  sRet := EmptyStr;

  RESTClient.BaseURL := sInfo[7];
  RESTClient.Params.ParameterByName('Token-Integracao').Value := sInfo[6];

  with RESTClient.Params.AddItem do
  begin
    name := 'itensResolvidos';
    Value := sJson; // String com o JSON a ser enviado, montado anteriormente
    Kind := TRESTRequestParameterKind.pkREQUESTBODY;
  end;

  RESTRequest.Method := rmPOST;
  RESTRequest.Execute; // Aqui dá a Excessão e não continua o programa

  sRet := '{"retorno":' + RESTResponse.JSONValue.ToString + '}';
end;

Comment: Coloquei o Token da mesma forma, não resolveu. Estou indo atrás de testar pelo Postman. Valeu!
Comment: Para o token tens que criar um parâmetro do tipo cabeçalho, faz o mesmo que você fez para criar o parâmetro para itens resolvidos só que no tipo escolha pkHTTPHEADER. Pois o retorno espera o token via cabeçalho.
Comment: O token eu criei diretamente no componente, pois estou utilizando o componente RESTCliente para fazer o GET, e deu certo. Mesmo assim vou fazer o que você disse, criar da mesma forma que o outro pra ver se é isso. Obrigado!
Comment: Qualquer coisa, tente fazer o teste pelo Postman
Answer: Constumo utilizar da seguinte forma:
RESTClient.BaseURL := MINHA_URL;
Requisicao.Method := TRESTRequestMethod.rmPOST;
Requisicao.Resource := '/REQUISICAO_QUALQUER';
Requisicao.Params.AddItem('username', aUsuario, TRESTRequestParameterKind.pkGETorPOST);
Requisicao.Params.AddItem('password', aSenha, TRESTRequestParameterKind.pkGETorPOST);
Requisicao.Execute;

TRESTRequestMethod.rmPOST; este deve resolver seu problema.
Tanto para GET quanto para POST deve ser especificado para cada parâmetro o que esta fazendo. No caso, eu utilizo o pkGETorPOST.
Quanto ao Token o envio é da seguinte forma:
Requisicao.Params.AddItem('Authorization'
                          ,SEU_TOKEN
                          ,TRESTRequestParameterKind.pkHTTPHEADER
                          ,[poDoNotEncode]
                          ,ctAPPLICATION_JSON);

Quanto ao JSON o envio é da seguinte forma:
Requisicao.AddBody(SEU_JSON, TRESTContentType.ctAPPLICATION_JSON);

Comment: Júnior, adaptei algumas coisas que estavam faltando, porém mesmo assim ainda não resolveu. O erro desconhecido ainda aparece. Pelo POSTMAN eu consegui, mas ainda não sei o que eu preciso fazer no Delphi para que funcione corretamente. Continuarei fazendo testes e retornarei aqui para dizer o resultado. Muito obrigado até aqui
Comment: Júnior, consegui! Eu estava cometendo um erro de iniciante aqui! às vezes tenho vergonha por não ter prestado atenção a algo simples que eu estava errando... Do seu jeito deu certo. Muito obrigado!


$a, b, c, d$ are positive integers, $a-c|a b+c d$, and then $a-c|a d+b c$

Question:
$a, b, c, d$ are positive integers, $a-c|a b+c d$, and then $a-c|a d+b c$

proof: really easy when use $a b+c d-(a d+b c)$

however my first thought is, $a-c| a b+c d+k(a-c)$, and set some $k$ to prove, failed.
question1 : is this method could be done? any other methods?
question2 : And is there any relations between the question and determinant/matrix
$$\begin{array}{cc} a & d  \\-c & b \end{array}$$
Comment: Suppose $a=4, b=1, c=1, d=2$. Then $a-c=3$ is a divisor of $ab+cd=6$, but not of $ad+bd=10$.
Comment: @HagenvonEitzen typo, fixed
Answer: HINT:
$$ab+cd-(ad+bc)=b(a-c)-d(a-c)=(a-c)(b-d)$$
Alternatively, $$ab+cd=b(a-c)+bc-(a-c)d+ad=(a-c)(b-d)+ad+bc$$ we  are reaching at the same point
Comment: this answers question 1: $k=(b-d)$ ;)
Comment: Yes, this is one right/efficient/simple method.
How do you think about my question1 and question2.
Comment: @N.S. oh... good to know that...
Answer: As lab gave you the $k$ which works for question 1, here is the answer to question 2:
$$\det \begin{pmatrix} a & d  \\-c& b \end{pmatrix} = \det \begin{pmatrix} a & b  \\-c & d \end{pmatrix}+\det \begin{pmatrix} a & d-b  \\-c & b-d \end{pmatrix}$$
$$ = \det \begin{pmatrix} a & b  \\-c & d \end{pmatrix}+(b-d)\det \begin{pmatrix} a & -1  \\-c & 1\end{pmatrix} = \det \begin{pmatrix} a & b  \\-c & d \end{pmatrix}+(b-d)\det \begin{pmatrix} a+c & 0  \\-c & 1\end{pmatrix}
$$
The solutions is pretty artificial though...

$a, b, c, d$ are positive integers， $a-c|a b+c d$, and then $a-c|a d+b c$


Telegram bot & feed parser-> reply rss feed in 1 msg instead of 2

Question: Im trying to get my Telegram bot to reply news via rss feed. For this I'm using the module Feedparser. Now I have managed to get it to work however the bot sends 2 separate messages per feed item. The first one has the summary of the feed and the second one has the link. I want to change the code so that it sends it in 1 message. I have tried 2 different methods and both came up with errors.
Working method with 2 msg per item:
elif text == "/news":
            for i in range(3):
                reply (feed.entries[i].summary)
                reply (feed.entries[i].link)

My failed fixes:
Fix1
elif text == "/news":
            for i in range(3):
                reply ((feed.entries[i].summary)
                       (feed.entries[i].link))

error1
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/e~thalia-bot/1.391503855076259816/main.py", line 169, in post
(feed.entries[i].link))
TypeError: 'unicode' object is not callable

Fix2
elif text == "/news":
            for i in range(3):
                reply (feed.entries[i].summary.link)

Error2
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/e~thalia-bot/1.391503917377816930/main.py", line 168, in post
reply (feed.entries[i].summary.link)
AttributeError: 'unicode' object has no attribute 'link'

I'm not sure what i have done wrong here, looked up the errors to try and get a fix but haven't found a working solution yet. Would appreciate if someone could point me in the right direction.
Answer: You can try
elif text == "/news":
  for i in range(3):
    reply("{} {}".format(feed.entries[i].summary, feed.entries[i].link))

You can replace the whitespace in "{} {}" with "\n" (newline character) if you want to have the link on the next line.


How to translate Groups in a multilingual site?

Question: I have created a new grouptype and added some fields to have a "site". And then created a new group with this grouptype. I edited the overview site with some information. Now I would like to translate the site, because I have an multilingual site. Unfortunately I can't find out how to do so.
Is it possible to translate a groupsite on a multilingual site?
Or do I have to create two groups for that?
Answer: Your question appears to be somehow related to this issue, which is closed and fixed. That issue contains an image which looks like so:

So check if the version of the Group module that you're using, includes the patch included in that issue.
If you don't have it included, it's probably why you don't have a "group content type" translation option in <code>/admin/config/regional/config-translation</code>. And if you do have it included, go checkout that translation option to see what happens.
Comment: The patch was already included in my version of the grouo modul, but I still can't translate the content of my group node.
I think I should enable the translation for groupe and group content: /admin/config/regional/content-language But when I will enable it, it appears the following error: Warning: Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini. in Unknown on line 0
Answer: I could translate the group node by enable "group" and "group content" in /admin/config/regional/content-language


Nginx not logging $remote_port when coming from cloudflare

Question: We offen receive requests from police to provide the ip and port of visitors.
When the requests come via cloudflare(https), the $remote_port variable is empty, when I access the load balancer via it's ip the port is set correctly.
<code>log_format  main  '[$time_local] - $http_x_forwarded_for - $remote_addr - p$remote_port - $status - $request_time - "$uri"';
</code>
Answer: CloudFlare does not pass that information to you, so it is not surprising that you do not have it.
The only information CloudFlare provides is here. If the port is needed then police will have to get the IP from you and take the request to CloudFlare to get the port number.
Comment: That's what I was afraid of, but could not find anything official from cloudflare or anything at all while googling.


Moving tensor products inside homs

Question: Suppose that $(\mathcal C, \otimes, I)$ is a closed symmetric monoidal category with $\hom(A,B)$ the hom-sets and $[A,B]$ the internal hom (where $[A,-]$ is right adjoint to $-\otimes A$).  Is there always a map $[A,B]\otimes C \to [A,B\otimes C]$?  Are there additional hypotheses needed to get such a map?
The map exists in $R$-mod, where $R$ is a commutative ring.  However, I am having trouble finding a purely categorical justification for its existence (unlike, say, the evaluation map $A\otimes [A,B]\to B$, which is the image of the identity map under a hom-tensor adjunction $\hom([A,B],[A,B])\to \hom([A,B]\otimes A,B)$).
Answer: A map $[A,B]\otimes C\to[A,B\otimes C]$ is the same as a map $A\otimes[A,B]\otimes C\to B\otimes C$, and you have one $A\otimes[A,B]\to B$.
Comment: (Up to permutations of factors)
Comment: Now I feel a bit silly.

Moving tensor products inside homs


Bulk insertion using Visual Studio 2010 in C#

Question: I have a dictionary database in a C# project that contain large amount of words and their meanings. My database has a table named "dic", that have 2 columns: first is "english" (the one which contains the English word) and the second is "bangla" (which contains the meaning).
I have 2 text files: english.txt containing 20000 words and bangla.txt containing their meanings.
i tried put the query on visual stdio 2010 like :
BULK INSERT dic FROM 'C:\Users\Imon-Bayazid\Desktop\wordddd\good one\list.txt'
WITH (  FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' )

But it didnt work.shows the error "The BULK INSERT SQL construct or statement is not supported";
How can I insert these words and their meaning into the "dic" table from the two txt files using bulk insertion of MS SQL? can anyone tell me details about this ??
Comment: Use the [bcp](http://msdn.microsoft.com/en-us/library/ms162802.aspx) utility
Answer: The SqlBulkCopy class is just for you
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy(v=vs.100).aspx
Comment: i tried to use it but i cant do that.Can you help me how to do that.@Wiktor
Comment: What have you tried that didn't work more precisely? Could you show your code? It's quite difficult to tell you what might be wrong with your code if you are not showing it.


Solving equivalence relations

Question: A relation R is defined on R such that aRb if and only if  |a−b|< 1. Show that R is reflexive and symmetric but not transitive. Could you explain in detail? I tried reflexivity, but i don't know how to do the rest.
Comment: You tried reflexivity. Did you succeed?
Answer: Hint on symmetry:
There is no difference between the distances Amsterdam-Rotterdam and  Rotterdam-Amsterdam.
Hint on transitivity:
If the distance from $A$ to $B$ and the distance from $B$ to $C$ are both less than a mile, then is it necessarily true that the distance from $A$ to $C$ is less than a mile?

Solving equivalence relations


HTML form submit to PHP script with associative array

Question: I'm making an HTML form. I want the results to appear in the PHP script on another page.
Here is my form :
echo '<form name="form1" action="page2.php" method="post">';
echo '<SELECT name="choice">';
foreach ($array as $key => $value)
echo '<OPTION VALUE="'.$value.'" name="'.$value.'">'.$key.'</OPTION>';

Now, on my page2.php I want to retrieve both $key AND $value using the "post" method, I tried these 3 solutions one by one and it failed :
echo $_POST["choice"]; //nothing
echo $_POST[$key];     //nothing
echo $_POST[$value];   //nothing

What is the problem ?
Answer: You dont need to give a name to the option in select field. Just give a name to the select tag like below:
echo '<form name="form1" action="page2.php" method="post">';
echo '<SELECT name="choice">';
foreach ($array as $key => $value)
       echo '<OPTION VALUE="'.$value.'">'.$key.'</OPTION>';

and then in your php code after selecting a value and submitting the form:
echo $_POST['choice']

will give you the selected value.
Answer: You can have a delimiter in the value of your options like this:
echo '<form name="form1" action="page2.php" method="post">';
echo '<SELECT name="choice">';
foreach ($array as $key => $value)
echo '<OPTION VALUE="'.$key.'|'.$value.'" >'.$value.'</OPTION>';

and then, on post, retrieve it this way:
$expldedArray = explode("|", $_POST["choice"]);
$key = $expldedArray[0];
$value = $expldedArray[1];

Answer: foreach($_POST as $key => $value) {

     echo ucfirst($key); echo " = ";
     if(is_array($value))
          echo implode(",", $value);
     else
          echo $value;

     echo '
';
}

Where ucfirst() capitalizes first letter of string.
implode() will glue array elements with given string


My yum repository able to search packages, but not able to install it in RHEL?

Question: I set up yum from  dvd. Following is the containts of my .repo file:
[dvd]
name=Red Hat Enterprise Linux Installation DVD
baseurl=file:///media/dvd
enabled=0.

I'm able to search packages. However while installation I'm getting below error:
[root@localhost dvd]# yum install libstdc++.x86_64
Loaded plugins: rhnplugin, security
This system is not registered with RHN.
RHN support will be disabled.
Setting up Install Process
Nothing to do

My Yum Search output:
[root@localhost dvd]# yum search gcc
Loaded plugins: rhnplugin, security
This system is not registered with RHN.
RHN support will be disabled.
============================================================================= Matched: gcc =============================================================================
compat-libgcc-296.i386 : Compatibility 2.96-RH libgcc library
compat-libstdc++-296.i386 : Compatibility 2.96-RH standard C++ libraries
compat-libstdc++-33.i386 : Compatibility standard C++ libraries
compat-libstdc++-33.x86_64 : Compatibility standard C++ libraries
cpp.x86_64 : The C Preprocessor.
libgcc.i386 : GCC version 4.1 shared support library
libgcc.x86_64 : GCC version 4.1 shared support library
libgcj.i386 : Java runtime library for gcc
libgcj.x86_64 : Java runtime library for gcc
libstdc++.i386 : GNU Standard C++ Library
libstdc++.x86_64 : GNU Standard C++ Library
libtermcap.i386 : A basic system library for accessing the termcap database.
libtermcap.x86_64 : A basic system library for accessing the termcap database.

Please guide me on this, I want to install gcc on my RHEL.
Answer: Try changing enabled=0 to enabled=1.

Set enable=0 in a definition file to prevent yum from using that repository. The yum utility ignores any definition file with this setting.

When you enabled the repo you got the following error message

file:///media/dvd/repodata/repomd.xml: [Errno 5] OSError: [Errno 2] No
  such file or directory: '/media/dvd/repodata/repomd.xml' Trying other
  mirror. Error: Cannot retrieve repository metadata (repomd.xml) for
  repository: dvd. Please verify its path and try again

Which suggests that your dvd isn't mounted or if it is mounted, then it is mounted somewhere other than /media/dvd
Comment: @mandy You didn't mount the DVD at `/media/dvd` so `yum` couldn't find it. Try again.
Comment: With `enabled=1`, I even not able to search the packages also. I'm getting below error: `[root@localhost dvd]# yum install libstdc++.x86_64
Loaded plugins: rhnplugin, security
This system is not registered with RHN.
RHN support will be disabled.
file:///media/dvd/repodata/repomd.xml: [Errno 5] OSError: [Errno 2] No such file or directory: '/media/dvd/repodata/repomd.xml'
Trying other mirror.
Error: Cannot retrieve repository metadata (repomd.xml) for repository: dvd. Please verify its path and try again
`
Comment: Now, It shows following informtion/error: `[root@localhost media]# yum install cpp.x86_64
Loaded plugins: rhnplugin, security
This system is not registered with RHN.
RHN support will be disabled.
Setting up Install Process
Nothing to do
`
Answer: You can solve this problem in one of two ways. Choose one:

Pay for your Red Hat subscription and register the machine on Red Hat Network.
Use a RHEL clone such as CentOS.


saving long strings containing quotes to a hidden input

Question: I have a long string which contians anything (single quote, double quote ...). Now I want to save this string in a hidden input and using it in my JavaScript code. How can I save this string in a hidden input?
Answer: I have misunderstood the question first time.
All you need to do is to encode your variable for html. You can have a look on how to do it here http://msdn.microsoft.com/en-us/library/73z22y6h(v=vs.110).aspx
A basic use would be
myString = "asd\"ewr'2";
myEncodedString = HttpUtility.HtmlEncode(myString);

And then in HTML
<input type="hidden" value="@{ @myEncodedString }">

Comment: I am using Code behind and I think I have to encode my string because it contains quotation marks.
Comment: Can you show me how you pass the string to javascript? Once you manage to put the string into a javascript variable, then you can do what I suggested ...
Comment: I just get it from value of the hidden input. $("#myhidden").val();
Comment: What I mean is where do you get that string from, how do you "bring" that string to javascript?
Comment: I am using code behind to read it from a file and put it to the hidden input
Comment: So you're doing the opposite ... You put it in the hidden input using some server-side technology and then you want to access it with javascript using `$("#myhidden").val();`, right?
Comment: THanks, Do I need to decode it when I access it from JS?
Comment: No decoding is needed if you want to print it to page, for example. But it depends on what you want to do with


Isometric Embedding of a Riemannian Manifold into Euclidean Space

Question: From the Nash Embedding theorem e.g. see
https://en.wikipedia.org/wiki/Nash_embedding_theorem
an $m$ dimensional Riemannian manifold has an isometric embedding into a dimension of $\frac{m(3m+11)}{2}$ or $\frac{m(m+1)(3m+11)}{2}$ depending on if its compact or not.
My questions are:

does there always exist an isometric embedding, in the sense of the of the Nash theorem above, of an $m$ dimensional Riemannian manifold into $\frac{m(m+1)}{2}$ space?
Is the first question known to be false for any $m$?

As far as I'm aware the answer to the first question is probably true because
there are specific known examples of $m$ manifolds into $\frac{m(m+1)}{2}$ space for certain $m$.
Comment: it seems that the Poincare disk with constant negative curvature cannot be embedded into $\mathbb{R}^3$.
Answer: The answer is no, at least for $m=2$. Indeed, even the (much weaker) Whitney embedding theorem doesn't hold for $m=2$ and $n = \frac{m(m+1)}{2} = 3$. One of examples is the projective plane $\mathbb{R} P^2$, which doesn't admit a smooth embedding into $\mathbb{R}^3$ (as any closed surface in $\mathbb{R}^3$ can be oriented).
Comment: Does $\mathbb{R}\mathbb{P}^2$ admits a topological embedding into $\mathbb{R}^3$?
Comment: Also no (although the proof I had in mind takes advantage of the differential structure). I meant to use the word _smooth_ only as an opposition to _isometric_.
Comment: I understood what you meant, I am just curious for a proof that no topological embedding exists.
Comment: If (for some reason) you already know that any representation of the clique $K_6$ in $\mathbb{R}^3$ contains a nontrivial link (i.e. two disjoint subgraphs $K_3$ have nonzero linking number), this impossibility can be shown by noting that on $\mathbb{R}P^2$ one can draw $K_6$ so that any two subgraphs $K_3$ are unlinked, i.e. one of the cirles bounds a disk disjoint with the other circle. [Here](http://www.deltami.edu.pl/temat/matematyka/geometria/2011/05/25/Czy_widzial_ktos_plaszczyzne_rzutowa/) is a popular article about it, in Polish.


Input inside Select Angular

Question: I have a small piece of code in which I have a select i option. With their help, I iterate through the elements and select the one I need. The point is that I need to do a search inside this select. That is, I can both select an item from the list and start typing, looking for the item I need and the items are shown to me.
<mat-select formControlName="targetListValue">
   <input>
   <mat-option [selected]="true" [value]="null"></mat-option>
   <mat-option *ngFor="let targetItem of targetListOptions" [value]="targetItem.id">
      {{ targetItem.name }}
   </mat-option>
</mat-select>

Comment: Is mat-autosuggest what you're looking for maybe?
Comment: @MikeOne i don't know what it is but i need to put input inside select to make search
Answer: You can use the idea of 'autocomplete' control.
angular material provides an autoComplete component that contains a select with input:

The autocomplete is a normal text input enhanced by a panel of suggested options.

HTML CODE:
<form class="example-form">
  <mat-form-field class="example-full-width" appearance="fill">
    <mat-label>Number</mat-label>
    <input type="text"
           placeholder="Pick one"
           aria-label="Number"
           matInput
           [formControl]="myControl"
           [matAutocomplete]="auto">
    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

TS CODE:
import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';

/**
 * @title Highlight the first autocomplete option
 */
@Component({
  selector: 'autocomplete-auto-active-first-option-example',
  templateUrl: 'autocomplete-auto-active-first-option-example.html',
  styleUrls: ['autocomplete-auto-active-first-option-example.css'],
})
export class AutocompleteAutoActiveFirstOptionExample implements OnInit {
  myControl = new FormControl('');
  options: string[] = ['One', 'Two', 'Three'];
  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value || '')),
    );
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.options.filter(option => option.toLowerCase().includes(filterValue));
  }
}

CSS:
.example-form {
  min-width: 150px;
  max-width: 500px;
  width: 100%;
}

.example-full-width {
  width: 100%;
}

Comment: Thank you, but why do you `mat-autocomplete`? I can't scroll in my `select` to see all my elements. Is that how it should work?
Comment: sorry to ask youm but how to do it??? can you show me it, please??? thanks
Comment: mat-autocomplete will automatically display a vertical scroll bar when there are too many options to display in the panel.
Comment: yes, i have a lot of them but i don't see scrool vertical. How to fix it? Thanks)
Comment: Please open a new question "How to display a vertical scroll bar in mat-autocomplete"

Input inside Select Angular


Removing a Table From CakePHP

Question: I am trying to remove a table from CakePHP. All the tables were created with the cake bake function and I have removed the table from all the models. But when I remove the table from the database I get an error message:
Error: Database table channels_offers for model ChannelsOffer was not found.

Notice: If you want to customize this error message, create app/views/errors/missing_table.ctp

So how do I remove a table that was originally baked in?
Answer: Well, it appears that you still have a model called ChannelsOffer.  You would need to add a property to your ChannelsOffer model.  Here's an example
class ChannelsOffer extends AppModel {

    // this tells the model not to use a table, alternatively you could supply your
    // own table name here.
    public $useTable = false;

Removing a Table From CakePHP


Ways to accurately transcribe audible music to tabs

Question: What are some common ways people take music and create tabs for their respective instruments?
For example If I were to take a musicians rendering of a song (

) what steps would have to be taken to recreate this piece in tablature form? Is there software that can be used to either find the notes being played or other ways to preform this task?
I am interested in trying to recreate many works on the harmonica and I am looking for an efficient work flow to help an amateur create tabs for the pieces.
Thanks
Comment: On guitar, generally, someone will attempt  to copy what's been played, and tab where they found the notes on their guitar. Can't help with harp tab!
Answer: The exact steps and tools used will most likely vary from one instrument or musician to another, but here are a few tips that I personally use when transcribing bass guitar:

Use sheet music software: It can really help to use software designed for writing music rather than writing the tabs in something like notepad. For guitar and bass, there's Guitar Pro. Such software will usually allow you to write using music notation and play a piece you've transcribed back to you, helping you validate your transcription.
Determine the tempo of the piece using a metronome app: There are tons of metronome applications available for your phone. Most of them will let you tap a button to the rhythm of the music and tell you the tempo of that rhythm. This is usually my first step, after which I will set the tempo of the piece in Guitar Pro.
Slow down the piece and filter out frequencies: Depending on the piece you are transcribing, it may be difficult to hear exactly what is being played. Some software (I personally use Amazing Slow Downer by Roni Music) will allow you to slow down a piece, loop a certain section, and filter out certain frequencies in order to isolate the instrument you are transcribing.
Start transcribing: Use a metronome set to the right tempo, listen to a section of the piece and try to reproduce it on your instrument. When you think you have it down, transcribe it and have it played back to you to make sure you have it right.
Determine the key of the piece: Looking at notes that are in the key will help you find the right notes faster, but beware of key modulations and secondary chords.


Multiple Linear Regression coefficents

Question: I'm doing a linear regression, in R. The values are like this -
u  <-  c(1,2,3,4,5,6,7,8,9,10)
v <- c(21,22,23,24,25,26,27,28,29,30)
w <- c(41,42,43,44,45,46,47,48,49,50)
y <- c(128.2305,132.4040,140.1732,147.3236, 154.5410, 158.7206, 165.1761, 169.7121,178.9751,181.0309)

If I call linear regression function, it's returning a model, which is disregarding v and w.
model <- lm(y~u+v+w)

Coefficients:
(Intercept)            u            v            w
    122.074        6.101           NA           NA

summary(model)

Output:
Call:
lm(formula = y ~ u + v + w)

Residuals:
       Min       1Q   Median       3Q      Max
-2.05143 -0.92734  0.04845  0.73362  1.99357

Coefficients: (2 not defined because of singularities)
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 122.0743     1.0197  119.72 2.65e-14 ***
u             6.1008     0.1643   37.12 3.04e-10 ***
v                 NA         NA      NA       NA
w                 NA         NA      NA       NA
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.493 on 8 degrees of freedom
Multiple R-squared:  0.9942,    Adjusted R-squared:  0.9935
F-statistic:  1378 on 1 and 8 DF,  p-value: 3.04e-10

I tried to fit a linear model before with different values of y,u,v (with two predictor variables, w was absent), and there also, v was being assigned NA, and only u was getting co-efficients. What's happening?
Comment: Try summary(model) command. It may be useful to post its output here. For reproducible code in R, use proper commands like u = c(1,2,...) etc.
Answer: Two of your three regressors ($v$ and $w$, say) are linear combinations of the intercept column (the "1"-vector) and the third regressor ($u$, say), thus causing "perfect multicollinearity". For instance, the vector $v$ equals $u$ plus 20.
Technically speaking, the design matrix $X$ with rows
$$
  X_{i,.} = (1, u_i, v_i, w_i)
$$
is not of full column rank, so the square matrix $(X'X)$ appearing in the least-squares solution $\hat \beta$
$$
  \hat \beta =(X'X)^{-1}X'y
$$
cannot be inverted.
Fortunately, R is so smart that it still provides the correct solution by dropping two of the three linearly dependent regressors. So it uses the design matrix $\tilde X$ with rows
$$
  \tilde X_i = (1, u_i)
$$
with the corresponding solution in your output.
Comment: okay. So you mean to say, the variables are like v = k*u+e, or w = k*u+e, so it'll be a case for multi-collinearity e is some error or intercept?
Comment: no, thats not what I meant. There is no "e" in my text. $v = u + 20\cdot 1$ e.g.
Comment: Thanks so much... :) Okay. This one.. v(1) = u(1)+20; v(2) = u(2)+20;
Comment: Exactly, that is right.
Comment: I liked the clarity with which you answered. Could you please suggest a good discussion on regression, with math concepts, preferably using R..
Comment: Online source would be a great help..

Multiple Linear Regression coefficents


Forbidden after enabling SSL

Question: I recently used LetsEncrypt's Certbot to enable SSL on my server. It's running Apache 2.4.18 with Django 1.11 on Ubuntu 16.04. As explained here, I duplicated my :80 VirtualHost definition for 443 in the same file. I am now getting 403 Forbidden whenever I try to access my site over HTTPS. Below is my current site conf file, lightly anonymized:
WSGIApplicationGroup %{GLOBAL}
WSGIDaemonProcess MyApp python-home=/home/Administrator/Documents/MyRepo/MyRepo_env python-path=/home/administrator/Documents/MyRepo/MyApp
WSGIProcessGroup MyApp

<VirtualHost *:80>
        ServerName myapp.com

        ServerAdmin email@example.com
        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        Alias /static /home/administrator/Documents/MyRepo/MyApp/static
        <Directory /home/administrator/Documents/MyRepo/MyApp/static>
                Require all granted
        </Directory>

        <Directory /home/administrator/Documents/MyRepo/MyApp/MyApp>
                <Files wsgi.py>
                        Require all granted
                </Files>
        </Directory>

        WSGIScriptAlias / /home/administrator/Documents/MyRepo/MyApp/MyApp/wsgi.py

RewriteEngine on
RewriteCond %{SERVER_NAME} =myapp.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

<VirtualHost *:443>
        ServerName myapp.com

        ServerAdmin email@example.com
        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        Alias /static /home/administrator/Documents/MyRepo/MyApp/static
        <Directory /home/administrator/Documents/MyRepo/MyApp/static>
                Require all granted
        </Directory>

        <Directory /home/administrator/Documents/MyRepo/MyApp/MyApp>
                <Files wsgi.py>
                        Require all granted
                </Files>
        </Directory>

        <Directory /var/www/html>
                Require all granted
        </Directory>
        WSGIScriptAlias / /home/administrator/Documents/MyRepo/MyApp/MyApp.wsgi.py

SSLCertificateFile /etc/letsencrypt/live/myapp.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/myapp.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

The only thing showing in the Apache log is client denied by server configuration: /home/administrator/Documents/MyRepo/MyApp/MyApp.wsgi.py
What permissions do I need to modify, or what settings do I need to change to get it working over SSL?
Comment: You do  know that you added an extra `.com` to your `ServerName` directive. Is that a typo or is the same error actually in your config file?
Comment: I found [this](https://serverfault.com/questions/774819/virtual-host-forbidden-after-enabled-ssl) which looks like a similar issue, but was due to syntax errors I don't think I've made
Comment: 403 errors in your browser usually come (like most web **server** warnings and errors) with a much more verbose description in your server (error) log file - so start there
Comment: Unfortunately the message in error.log isn't much more helpful (to me at least). Just says "client denied by server configuration: /home/administrator/Documents/MyRepo/MyApp/MyApp.wsgi.py"
Comment: Ah, oops. That is just a typo, not present in the config. I got a bit overzealous with find/replace apparently
Answer: Well, that was frustrating. The issue ended up being a simple typo in my second VirtualHost definition. Specifically, the WSGIScriptAlias should be WSGIScriptAlias / /home/administrator/Documents/MyRepo/MyApp/MyApp/wsgi.py not WSGIScriptAlias / /home/administrator/Documents/MyRepo/MyApp/MyApp.wsgi.py. The only difference is a period where there should have been a slash, between the final MyApp and wsgi.py. Hopefully someone else will read this and be spared the hours of nonsensical debugging.

Forbidden after enabling SSL


Sender name in "send HTML mail" rule

Question: I have a local site I am testing. I have PhPMailer installed which works fine to send plain text email with the Sender name populated properly.  However when I installed MimeMail and try to use the same rule, except using action send HTML mail, the Sender name no longer appears.  Any help would be great.
{ "rules_entityform_client_confirmation_email" : {
"LABEL" : "Entityform Client Confirmation Email",
"PLUGIN" : "rule",
"OWNER" : "rules",
"TAGS" : [ "entity_rules_entityform_submission" ],
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : {
  "entity" : { "label" : "Entity", "type" : "entityform" },
  "continue" : { "label" : "Continue Rules", "type" : "boolean" }
},
"IF" : [
  { "user_has_role" : { "account" : [ "entity:user" ], "roles" : { "value" : { "4" : "4" } } } }
],
"DO" : [
  { "drupal_message" : { "message" : "Email to: [entity:user:mail]\r\nHi [entity:user],\r\nThanks for creating a new project\r\n" } },
  { "mimemail" : {
      "USING" : {
        "key" : [ "entity:entityform-id" ],
        "to" : [ "entity:user:mail" ],
        "from_name" : "[site:name]",
        "subject" : "New Project Created",
        "body" : "Hi [entity:user],\r\nThanks for creating a new project",
        "plaintext" : "Hi [entity:user],\r\nThanks for creating a new project",
        "language" : [ "" ]
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
],
"PROVIDES VARIABLES" : [ "continue" ]
}
}

Answer: Try this variation of your rule (using the rules UI to import it in your site):
{ "rules_entityform_client_confirmation_email_pv" : {
"LABEL" : "Entityform Client Confirmation Email PV",
"PLUGIN" : "rule",
"OWNER" : "rules",
"TAGS" : [ "entity_rules_entityform_submission" ],
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : {
  "entity" : { "label" : "Entity", "type" : "entityform" },
  "continue" : { "label" : "Continue Rules", "type" : "boolean" }
},
"IF" : [
  { "user_has_role" : { "account" : [ "entity:user" ], "roles" : { "value" : { "4" : "4" } } } }
],
"DO" : [
  { "drupal_message" : { "message" : "Email to: [entity:user:mail]\r\nHi [entity:user],\r\nThanks for creating a new project\r\n" } },
  { "mimemail" : {
      "USING" : {
        "key" : [ "entity:entityform-id" ],
        "to" : [ "entity:user:mail" ],
        "from_name" : "[site:name]",
        "from_mail" : "firstname.lastname@example.com",
        "subject" : "New Project Created",
        "body" : "Hi [entity:user],\r\nThanks for creating a new project",
        "plaintext" : "Hi [entity:user],\r\nThanks for creating a new project",
        "language" : [ "" ]
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
],
"PROVIDES VARIABLES" : [ "continue" ]
}
}

The only difference with your exported rule is the line with from_mail that is added (and a slightly different machine name of your rule). Adapt the eMail Id I used to fit your needs.
Comment: Thanks Pierre - I thought the rule was supposed to automatically pick up both the sender email and name from the sitewide name and address, but I guess not because this works :)
Comment: @SharonDankwardt merci for the update (and accept / +1). Yes rules can sometimes be a little bit tricky. But apart from that It's an amazing module! Next ( [Rules](https://www.drupal.org/project/rules) ) question?
Comment: I'm sure I'll be back if I have more questions :) Thanks Pierre

Sender name in "send HTML mail" rule


Trying to display all posts in my archive page but it is only returning the page content

Question: I'm having a problem with displaying all posts in my archive page using the have_posts loop. When I try to return the title and the content, it returns the template page's title and content instead of the posts' content.
What I did to try and fix it is I ran a WP_Query post loop which grabs all the posts of post type = post and it displays the content just fine. The only problem is I want a dynamic archive page so when users select a tag - it will take them to an archive page with all the posts containing that tag. Since I am running a specific WP_Query, all my archive pages display all the posts with the post-type = post.
My guess is that I have to run a simple have_posts loop instead of running WP_Query in order for my archive page to dynamic.
How I set up my archive page: I have a file called archive.php which I gave the template name of Archives and created a page for it on wp-admin and titled it Blog.
<?php
/**
 * The template for displaying archive pages
 * Template Name: Archives
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package WordPress
 * @subpackage Twenty_Seventeen
 * @since 1.0
 * @version 1.0
 */

get_header(); ?>

    <?php // Show the selected frontpage content.
    if ( have_posts() ) :
        while ( have_posts() ) : the_post(); ?>

            <?php
                the_title( '
', '
' );
                the_content( '
', '
');
            ?>

    <?php

        get_template_part( 'template-parts/post/content', 'archive' );

        endwhile;

        the_posts_pagination( array(
            'prev_text' => twentyseventeen_get_svg( array( 'icon' => 'arrow-left' ) ) . '' . __( 'Previous page', 'twentyseventeen' ) . '',
            'next_text' => '' . __( 'Next page', 'twentyseventeen' ) . '' . twentyseventeen_get_svg( array( 'icon' => 'arrow-right' ) ),
            'before_page_number' => '' . __( 'Page', 'twentyseventeen' ) . ' ',
        ) );

    endif; ?>

        <?php dynamic_sidebar( 'sidebar-4' ); ?>

<?php get_footer();

Inside my template content archive file I have the following:
<?php
 // the query
 $wpb_all_query = new WP_Query(array('post_type'=>'post',
 'post_status'=>'publish', 'posts_per_page'=>-1)); ?>

<?php if ( $wpb_all_query->have_posts() ) : ?>

    <?php while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post(); ?>
    <div id="post-<?php the_ID(); ?>" class="col-12 article-container">
        <div class="article-image-div" style="background-image: url('<?php echo get_the_post_thumbnail_url( $post_id, 'large' );  ?> ');">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

by <?php echo get_the_author(); ?>

        <?php echo apply_filters( 'the_content', wp_trim_words( strip_tags( $post->post_content ), 55 ) ); ?>

    <?php endwhile; ?>

    <?php wp_reset_postdata(); ?>

<?php else : ?>

<?php _e( 'Sorry, no posts matched your criteria.' ); ?>

<?php endif; ?>

Answer: Try to use Query_posts or get_posts instead of
https://developer.wordpress.org/reference/functions/get_posts/
https://developer.wordpress.org/reference/functions/query_posts/


finite group whose only automorphism is identity map

Question: Question is to prove that  :
A finite group whose only automorphism is identity map must have order at most $2$.
What i have tried is  :
As any automorphism is trivial, so would be inner automorphism
i.e., each map for fixed $g\in G $ with $\eta : G\rightarrow G$ taking $h$ to $ghg^{-1}$ is trivial.
Thus, $ghg^{-1}=g$ i.e., $gh=hg$ for all $g\in G$ and $h\in G$ which would say that $G$ is abelian.
So, I would have that $G$ is finite abelian group.
Now, As $G$ is abelian, the map $g\rightarrow g^{-1}$ is an automorphism.
But only automorphism is identity map, so we would have  :
$g=g^{-1}$ i.e., $g^2=e$ for all $g\in G$
So, I would have that $G$ is group with each element of order $2$.
Combining with previous result I would have :

$G$ is a finite abelian group in which each element is of order $2$

I am not able to conclude anything more than this....
A kind of cheating would give something very close :
As group is finite abelian which has each element with order $2$, It should be :
$\mathbb{Z}_2\times \mathbb{Z}_2$ Or
$\mathbb{Z}_2\times \mathbb{Z}_2\times \mathbb{Z}_2$ Or
$\mathbb{Z}_2\times \mathbb{Z}_2\times \mathbb{Z}_2\times \mathbb{Z}_2$ Or something very similar to this.
For first group $\mathbb{Z}_2\times \mathbb{Z}_2$  automorphism group is general linear group of order $2$ with entries from $\mathbb{Z}_2$ which is not trivial. So, this should not be the required group.
This would hold for similar cases
So, I feel that i am on right path but i need some help to make it more clear.
Thank you :)
Comment: Does this answer your question? [$|G|>2$ implies $G$ has non trivial automorphism](https://math.stackexchange.com/questions/8379/g2-implies-g-has-non-trivial-automorphism)
Comment: You basically have it! Your observation that Aut (Z/2 \times Z/2) = GL_2 (Z/2) generalizes in a straigtforward case to the situation where there are n factors of Z/2 on the lhs. What must you change on the rhs?
Comment: I should have $GL_n (\mathbb{Z}_2) $ which is not identity so....... :) :)
Comment: See also: [Let $G$ be a finite group with $|G|>2$. Prove that Aut($G$) contains at least two elements.](https://math.stackexchange.com/q/395569) and [$|G|>2$ implies $G$ has non trivial automorphism](https://math.stackexchange.com/q/8379).
Answer: A (finite) abelian group with $g^2=e$ for all $g\in G$ is in fact a (finite dimensional) $\Bbb Z_2$-vector space, and then its automorphisms correspond to invertible matrices over $\Bbb Z_2$, so...
Comment: I got your point.. I am just waiting if some one would give a more general description.... Thank you so much for your interest :)
Answer: You are already very close.
Indeed, nonabelian groups have nontrivial inner automorphisms, while abelian ones have the automorphism $a\mapsto a^{-1}$, which is trivial only when all $a$ have order $2$.
So we only need to deal with the direct sums of $\mathbb{Z}_2$. But for such groups we have the automorphism \begin{equation}
(x,y)\mapsto (y,x),
\end{equation} which is nontrivial unless we have only one copy in our direct sum.
Comment: This is so helpful.... I had not recognized your last statement before... Thank you so much :)
Comment: Yes, these are cute little facts XD
Answer: We show that $Aut(G)$ is nontrivial if $G$ is abelian, $|G|>2$ (may be infinite), and all its non-identity elements are of order 2.
Let $G$ be an abelian group with all non-identity elements of order $2$ and $|G|>2$.  It's easy to see that $A = \{1, a_1, a_2, a_1a_2\}$ is a subgroup of $G$, where $a_1$ and $a_2$ are distinct non-identity elements of $G$. Let $B$ be a subgroup of $G$ and also a transversal of the collection of all cosets of $A$. Let $h$ be a nontrivial automorphism on $A$, and we can cronstuct an nontrivial automorphism $f$ on $G$ by defining $f$($b$$a$) = $b$$h$($a$) for all $b \in B$ and $a \in A$. $ So, Aut(G)$ is nontrivial.


Habilitar e desabilitar Ttimer

Question: Como habilitar e desabilitar o TTimer? Tenho um procedure:
procedure TForm3.Timer1Timer(Sender: TObject);

Quando clico em um botão de download, habilito o Timer:
Timer1.enabled := true;

E quando clico em cancelar ele deveria parar o Timer:
Timer1.enabled := False;

Mas não é isso que acontece. O Timer continua e fica processando os dados e exibindo em um Label...  para eu parar o Timer de vez tenho que usar:
Timer1.OnTimer :=  nil;

Qual a maneira correta de habilitar e desabilitar esse timer, pois na procedure TForm3.Timer1Timer( tem alguns comandos, e, mesmo eu dando Timer1.enabled := False; no botão cancelar ele continua processando e mostrando na tela.
Qual a maneira correta de usar o timer em uma situação dessa, habilitar e desabilitar?
Answer: Para desabilitar o timer basta digitar:
Timer1.enabled := False;

E para habilitar:
Timer1.enabled := True;

Você deve estar desabilitando o timer no lugar errado.
Comment: Realmente... eu estava desabilitando ele no local errado...  Estava dentro de um try ... Mas eu não sei se é errado, eu fui e coloquei uma variável global, onde recebia um valor booleano... daí verifico dentro do timer se é true ou False... deu super certo... daí eu não preciso desabilitar o timer...  Não sei se é vantagem...  mas dessa forma utilizo  apenas um timer com vários comandos diferentes... pois em nenhum momento ele será desabilitado...

Habilitar e desabilitar Ttimer


Retornar um " SELECT * FROM" no navegador JavaWeb

Question: Olá pessoal estou estudando JavaWeb e me deparei com um erro chato!!
Já pesquisei muito sobre o assunto porém não consegui resolver este erro.
Tenho este método que está puxando todos os dados da tabela "contatos" do banco de dados e retornando em uma lista.
public   ArrayList<User> buscarTodos() {
    //Monta a Query
    String sql = "select * from contatos";
    //Constroi PreparedStatement com SQL
    ArrayList<User> lista = new ArrayList<User>();
    try {
        PreparedStatement preparador = con.prepareStatement(sql);

        ResultSet resultado = preparador.executeQuery();
        while (resultado.next()){
            User contato = new User();
            contato.setContato_id(resultado.getInt("contato_id"));
            contato.setContato_nome(resultado.getString("contato_nome"));
            contato.setContato_tel(resultado.getString("contato_tel"));
            contato.setContato_email(resultado.getString("contato_email"));
            contato.setContato_sobrenome(resultado.getString("contato_sobrenome"));

            lista.add (contato);
        }
        preparador.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return lista;

}

Porém quando eu vou exibir essa lista ela retorna apenas o último contato repetido em várias vezes, como na imagem abaixo:

Segue o código chamando o método:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Chamando Método Get");
    String acao = request.getParameter("acao");
    UsuarioDAO contatoDAO = new UsuarioDAO();

    if (acao!= null && acao.equals("exc")  ) {
        String id = request.getParameter("id");
        User contato = new User();
        contato.setContato_id(Integer.parseInt(id));
        contatoDAO.excluir(contato);
    }

    List<User> lista = contatoDAO.buscarTodos();

    //Atribuir a Lista no request
    request.setAttribute("lista", lista );

    //Encaminhando para o JSP
    RequestDispatcher saida= request.getRequestDispatcher("exibeContatos.jsp");
    saida.forward(request, response);
}

Conseguem me ajudar?
Obrigado!
Comment: Posta seu HTML, por favor
Answer: testei aqui e rodou!, passa a sua JSP para vermos como esta esse foreach.
public List<User> buscarTodos() throws Exception {

    List<User> results = new ArrayList<>();
    String sql = "SELECT * FROM contatos;";

    try (PreparedStatement stmt = con.prepareStatement(sql);
            ResultSet resultSet = stmt.executeQuery()) {

        while (resultSet.next()) {
            results.add(populate(resultSet));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {

    }
    return results;
}

// popula com esse metodo
private User populate(ResultSet resultado) throws SQLException {

    User contato = new User();
    contato.setContato_id(resultado.getInt("contato_id"));
    contato.setContato_nome(resultado.getString("contato_nome"));
    contato.setContato_tel(resultado.getString("contato_tel"));
    contato.setContato_email(resultado.getString("contato_email"));
    contato.setContato_sobrenome(resultado.getString("contato_sobrenome"));

    return contato;
}

Comment: Coloquei o jsp aqui em baixo
Answer: Algumas dicas que podem lhe ajudar:
1) Verifique sua tabela na base de dados.
2) Verifique a Lista retornada exatamente pelo DAO, sem passar pela tela.
3) Coloque o método de listar os contatos, no construtor da classe. Pois o do GET pode está sendo chamado para cada linha da tabela.
4) Tente passar seu SQL, como parametro do executeQuery
        ResultSet rs = statement.executeQuery(sql.toString());

Comment: Coloquei o jsp aqui em baixo
Answer: Segue o JSP:
(Estava dando erro quando eu coloquei ele completo então segue a imagem com os marcadores "<% %>".)

List<User> lista = (List<User>) request.getAttribute("lista");

for (User contato : lista){

<%= contato.getContato_id() %>
<%= contato.getContato_nome() %>
<%= contato.getContato_sobrenome()%>
<%= contato.getContato_tel() %>
<%= contato.getContato_email() %>
<a href = "contatocontroller.do?acao=exc&id=<%= contato.getContato_id() %>">Excluir

    <a href = "contatocontroller.do?acao=alt&id=<%= contato.getContato_id() %>">Alterar

<%

}

%>


Re-stringing a Classical guitar

Question: I'm following how to do this on line but I can't seem to get the 6th E string to go through the roller hole twice, as instructed.  It just seems impossibly thick to achieve this.
Comment: Don't mind. You can fix the string by spinning it  over the first turn. It will keep and hold anyway.
Comment: Please reveal the source of the instruction.
Answer: Can't think why any string needs to go through the hole twice!
Difficult to describe in words, but here goes.
Put one end of a string through the hole in the bridge, pushing away from the soundhole. Pull 3-4" through. take that end over the bridge, round the long part of the string, and wrap it round itself a couple of times.
One more wind takes the end over the edge of the bridge, towards the body of the guitar. By pulling the long part of the string, it'll all tighten up leaving the simple task of putting that end into the machine head hole, and turning the knob the right way giving three or four complete turns to tighten the string roughly to tension.
Then the time consuming job of tighten, tune, stretch, tighten, tune, stretch, tighten, tune...
If, however, you mean the hole at the tuner end, forget it. There's no need to put any string through twice! And if yo mean the fat E, certainly forget it. Also forget it with the thin E. Just because something is on the internet doesn't mean it's good, authentic, sensible, feasible, workable, etc., etc.!
Answer: It's not essential that you go through the tuning roller twice - that's just a general instruction, and the gauge of your string might prevent you from doing it.
The purpose is to increase the friction so the string doesn't slip.  If you can't go through twice, go once with enough of a 'tail' to place under the next wrap or two of strings - then the string tension will keep it from slipping.

Re-stringing a Classical guitar


Undefined index: method in drupal_prepare_form()

Question: I am getting this strange notice

Undefined index: method in drupal_prepare_form()

in my Drupal 7 application but only on production server. It is really weird, on my development PC I have PHP 5.4.6 and on my server I have 5.3.3 and this is probably the only difference. I cannot get this error on my dev PC, so I really don't have any idea what is wrong and how to repair this.
I couldn't find anything good on the web, only that it could be connected with localization modules.
thanks!
Answer: I hope, this can be useful, to you
http://drupal.org/node/1024298
Probably, there is new patch introduced, please go through the blog above.
Comment: I found it:) it was the creation of new form. For php 5.3.3. you have to use $form_sate = form_state_defaults() instead of array(). Thanks anyway!


Lazy Loading with Spring Data and HIbernate JPA

Question: I am performing some tests with SpringData and Hibernate and found some interesting behavior on lazy loading and findBy... methods.
I have the following method on a child class.
List findByArtistCredit(Long artistCreditId);
and the following mapping between Recording and ArtistCredit...
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="artist_credit" , referencedColumnName="artist_credit_id")
private ArtistCredit artistCreditReference;

on the "One" side...
@OneToMany(fetch=FetchType.LAZY,mappedBy="artistCreditReference")
private Set<Recording> recordings;

And what happens is that the collection on the "Many side" is being eagerly fetched...
Does anyone know "why is happening?"
Any answer is wellcome.
Regards.
Answer: Normally it shouldn't be eagerly fetched base on what you have done.
The recordings should be a lazy-loading proxy which loading is only triggered when needed.
However it is a common mistake that lazy-loading is accidentally triggered:

You may have accidentally accessed that field in your code, for example, in toString()/hashCode()/equals().
You are inspecting your object state through a debugger, which will in turns trigger toString() or access to the lazy-loading field.

I strongly suggest you turn on SQL loading and inspect when is the lazy loading be triggered.  Tools like JdbcDsLog or even simply turn on the SQL logger of Hibernate should help
Answer: By default, Hibernate will fetch related objects when they are not in a collection. The FetchType is just a hint. The reason is because the normally Hibernate MUST load the object to determine if the field should be NULL or not. If the field were a collection, then the collection can always be non-NULL, so Hibernate can replace the collection with a proxy that will load on-demand.  But with a single object, there is no way to put a proxy is that can return NULL to the getter.
Comment: That's not true as far as I can tell. You can very well define `FetchType.LAZY` on a `...ToOne` relation, effectifly breaking the `join fetch` in the query. That makes sense as the foreign key column has a `null` value in the database.
Comment: this answer is obviously wrong (and irrelevant).  Logically, for case of a single object (xxxToOne), the ID of that "One" side will be there with in the record of "Many" side.  When data is retrieved for the "Many" side, Hibernate already have information on whether that FK is null (hence give a null object ref) or contains value (so it makes a proxy for it)
Comment: So, if this is wrong, how can the getter for this single value field return NULL if the value is lazy-loaded. The normal process of implementing the lazy load is to replace the container with a proxy that loads the contents when the container is dereferenced. If the object referenced in the field is replaced by a proxy, then the getter will never return NULL. It will always return the proxy. If the getter does return NULL, then there is no proxy to lazy load the actual object.


Verification of a certificate chain fails on the leaf certificate

Question: I produced a PEM certificate chain (CA, intermediate and leaf) using pyopenssl, and I wanted to confirm that I defined everything properly.
Here are the steps I took:

I made the three PEM certificates, self signed the CA and defined the basic constraint crypto.X509Extension(b'basicConstraints', False, b'CA:TRUE') following this question
I copied the CA and intermediate certificates to /usr/local/share/ca-certificates (as crt files) and ran sudo update-ca-cert
I've set up a simple server based on this OpenSSL example
I tried running the server with the CA certificate and executed openssl s_client -connect localhost:4433 -CApath /etc/ssl/certs - Worked great, got Verify return code: 0 (ok)
Did the same thing but this time the server used the intermediate certificate - Also great, Verify return code: 0 (ok)
Did the same thing but this time the server used the leaf certificate - This time I got Verify return code: 24 (invalid CA certificate)

In addition, I tried verifying the certificates and got the following:
$ openssl verify 1-ca.pem
1-ca.pem: OK
$ openssl verify 2-intermediate.pem
2-intermediate.pem: OK
$ openssl verify 3-leaf.pem
C = NL, ST = Amsterdam, L = Zaandam, O = FakeDigiCert, OU = FakeFake, CN = www.fakedigicert.nl
error 24 at 1 depth lookup: invalid CA certificate
error 3-leaf.pem: verification failed

Why is the CA certificate suddenly invalid once the server's certificate is more than one step away from the CA?
Comment: You don't make clear exactly what you put in which cert, but you say 'CA and intermediate' as if the intermediate were not a CA, which it is. What you have is a root CA, one intermediate CA, and an end-entity aka leaf. OpenSSL requires the/each intermediate CA has BasicConstraints.ca=true otherwise you get verify error 24; at least as of now it doesn't require this for the root CA unless the code sets a 'strict' flag, but a root _should_ have it nevertheless.
Comment: @dave_thompson_085 That was indeed the issue. I assumed that an intermediate certificate isn't necessarily a CA. Once I added the basic constraint, the verification passed. Thanks!
Answer: This seems to be a common trap most people fall into setting up https web server do all the time.  You need to provide the all intermediate certificates to the web server as well (normally by combining the leaf and intermediate pem files into one pem file). So when web browsers go to your site, the SSL setup should return both the leaf and the intermediate certificates from the web server.
You can see this on all web sites that provide intermediate certificates when you use the -showcerts option with the opensll s_client command:
openssl s_client -connect www.example.com:443 -showcerts

The same is true for the openssl verify command as well.
From the docs:

-untrusted file
A file of additional untrusted certificates (intermediate issuer CAs) used to construct a certificate chain from the subject
certificate to a trust-anchor. The file should contain one or more
certificates in PEM format. This option can be specified more than
once to include untrusted certificates from multiple files.

So in your example above you need to do:
openssl verify 3-leaf.pem -untrusted 2-intermediate.pem

Comment: @GabeL: per standard an SSL/TLS server should send the whole chain except that it _may_ omit the (nontrivial) root; in your case it should send at least leaf and imed. Most servers send what you configure (only), but some vary. If the server wrongly sends only the leaf, what the client does is not specified by standard; `openssl s_client` in particular, if you have both root and imed in its truststore (`-CAfile` and/or `-CApath` or their defaults), uses imed from the truststore to build the chain, and validation will succeed (if/once the certs are correct).
Comment: Omitting the intermediate is indeed a common mistake, but it CANNOT cause the specific error shown in this Q.
Comment: @dave_thompson_085 Would that mean that the leaf certificate is setup with 'CA:TRUE' when it shouldn't?
Comment: @ShanePowell It seems that dave_thompson_085's solution solved the issue, however I'd appreciate clarification on what you said. If I install the the root certificate on my client's host, and then provide a chained file containing all three certificates, s_client's check should be fine? Because when I uninstalled the intermediate certificate, I got "Verify return code: 21 (unable to verify the first certificate)"
Comment: Shane: no. As I commented on the Q, what causes verify 24 is an _intermediate_ that _lacks_ ca=true. OpenSSL accepts a 'leaf' with ca=true -- including but not limited to a self-signed cert where the leaf is also the root and must be directly trusted.


How do I find out how much of my 1TB free monthly allotment I've used in Google BigQuery?

Question: I feel like there must be some way to figure out how much of free 1TB is left besides summing up the "bytes processed" amounts for every single query. But I haven't been able to find it anywhere in the console or elsewhere.
Answer: Unfortunately this is not super easy right now. The best way to get the answer is, as you said, to sum up the bytes processed for the queries you've run.
You can get the data via the BQ jobs.list API, or you can use BQ's audit logs if that's more convenient. The audit logs can even be queried in BQ, but of course that incurs additional usage. :-)
You can also see your unbilled usage for GCP services via the GCP console. However, this only shows BQ usage from the free 1 TB tier once you've incurred some actual BQ charges (i.e., once you've gone over the 1 TB), which makes it less useful for your particular use case.
Comment: It turns out you can't actually see usage until you consume the first 1 TB. I've updated my answer.
Comment: I see entries for "Google Storage -- Download US EMEA",
"BigQuery -- Active Storage",  and "Google Storage -- Standard Storage US" . Nothing about the data I've processed, because I haven't gone over the 1TB free limit yet. I'm wondering how close I am to that 1TB limit.
Comment: Hmm, you should see an entry for BigQuery Analysis. Perhaps this page won't show anything until you exceed the 1TB limit. I'll see if I can figure out what's going on here...
Answer: To expand on Jeremy's answer, you might get that information also directly via the INFORMATION_SCHEMA.JOBS_BY_* views as I explained in my answer to How can I monitor incurred BigQuery billings costs (jobs completed) by table/dataset in real-time? based on How to monitor query costs in Google BigQuery
SELECT
  (SUM(total_bytes_processed) * 5) / (1024 * 1024 *1024 *1024),
FROM
  `region-us`.INFORMATION_SCHEMA.JOBS_BY_USER

Please consider the caveats mentioned in the linked answers (caching, region-specific costs per TB, ...)!


Validar se já existe registro no banco antes de preencher formulario

Question: Tenho o seguinte formulário:
        <form class="form-horizontal" action="cadastrar.php" method="GET">
                <fieldset>
                    <legend>DADOS CADASTRAIS</legend>

                    <input type="hidden" required id="cep" name="cep" value="<?php echo $cep; ?>">

                            CPF
                            <input type="text"
                            class="form-control"
                            required
                            id="cpf"
                            name="cpf"
                            placeholder="SOMENTE NUMEROS">

                            NOME
                            <input type="text"
                            style="text-transform:uppercase"
                            class="form-control"
                            required id="nome"
                            name="nome"
                            placeholder="NOME DO CLIENTE"
                            required>

                            ENDERECO
                            <input type="text"
                            style="text-transform:uppercase"
                            class="form-control"
                            required
                            id="end"
                            name="end"
                            placeholder="DIGITE ENDERECO">

                            NUMERO
                            <input type="text"
                            class="form-control"
                            required
                            id="num"
                            name="num"
                            placeholder="NUMERO">

                            COMPLEMENTO
                            <input type="text"
                            class="form-control"
                            id="comp"
                            name="comp"
                            placeholder="COMPLEMENTO">

                            BAIRRO
                            <input type="text"
                            style="text-transform:uppercase"
                            class="form-control"
                            required
                            id="bairro"
                            name="bairro"
                            placeholder="BAIRRO DO CLIENTE">

                            CIDADE
                            <input type="text"
                            style="text-transform:uppercase"
                            class="form-control"
                            required
                            id="cidade"
                            name="cidade"
                            placeholder="CIDADE DO CLIENTE">

                            TELEFONE
                            <input type="text"
                            class="form-control"
                            required
                            id="telefone"
                            name="telefone"
                            placeholder="TELEFONE">

                            RG
                            <input type="text"
                            class="form-control"
                            required
                            id="rg"
                            name="rg"
                            placeholder="SOMENTE NUMEROS">

                            E-MAIL
                            <input type="text"
                            style="text-transform:uppercase"
                            class="form-control"
                            required
                            id="email" n
                            ame="email"
                            placeholder="EMAIL DO CLIENTE">

                            <button type="submit" class="btn btn-primary">CADASTRAR</button>

                </fieldset>

            </form>

Tenho um functionCPF.php que retorna o seguinte json
http://localhost:8080/sys/functions/functionCPF.php?cpf=11122233344

Se existir o cpf:

 {"dados":{"cpf":"11122233344"}}

Se não existir:

{"dados":{"cpf":0}}

Com base nisso o que preciso:
 Se existir cpf : Alerta "CPF JÁ CADASTRADO";
 Se não: Não acontece nada e a pessoa pode continuar cadastrando
 Pensei em algo com ajax ou javascript mais não encontrei nada assim, alguém poderia me ajudar?
Consegui chegar até:
$(document).keydown(function(){
    var cpf = $("#cpf");
        cpf.blur(function() {
            $.ajax({
                url: '../functions/functionCPF.php',
                type: 'GET',
                data:{"cpf" : cpf.val()},
                success: function(data) {
                console.log(data);
                data = $.parseJSON(data);
                $("#resposta").text(data.cpf);
            }
        });
    });

    });

PHP:
<?php
//database configuration
    $dbHost     = '127.0.0.1';
    $dbUsername = 'root';
    $dbPassword = '';
    $dbName     = 'master';
#Verifica se tem um cpf para pesquisa
if(isset($_GET['cpf'])){
    #Recebe o cpf Postado
    $VarCPF = $_GET['cpf'];
    #Conecta banco de dados
    $Mysqli = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
    $sql = mysqli_query($Mysqli, "SELECT
    cli_cpf
        FROM
         big_clientes
         WHERE
             cli_cpf = '".$VarCPF."'") or print mysql_error();
    #Se o retorno for maior do que zero, diz que já existe um.
    if(mysqli_num_rows($sql)>0)
        echo json_encode(array('cpf' => 'CPF JÁ CADASTRADO!'));
    else
        echo json_encode(array('cpf' => 'CPF OK!' ));
}

O que preciso agora, se der CPF JÁ CADASTRADO --> Não deixar preencher o form.
Comment: dé uma olhada no ajax do jquery! http://api.jquery.com/jquery.ajax/, e utilize o evento onblur (https://www.w3schools.com/jsref/event_onblur.asp) no #cpf
Comment: @RobertoCorreia Implementei com sua dica, mais parei no ultimo detalhe, pode ver se consegue me ajudar? adicionei a pergunta.
Answer: Solução:

SCRIPT:

$(document).keydown(function(){
    var cpf = $("#cpf");
        cpf.blur(function() {
            $.ajax({
                url: '../functions/functionCPF.php',
                type: 'GET',
                data:{"cpf" : cpf.val()},
                success: function(data) {
                console.log(data);
                data = $.parseJSON(data);
                if(data.cpf) {

                    document.getElementById("myForm").reset();
                    $("#resposta").text(data.msg);

                 }
            }
        });
    });

FORM

            <form id="myForm" class="form-horizontal" action="cadastrar.php" method="GET">
                <fieldset>
                    <legend>DADOS CADASTRAIS</legend>

                            CPF
                            <input type="text"
                            class="form-control"
                            required
                            id="cpf"
                            name="cpf"
                            placeholder="SOMENTE NUMEROS">

                            NOME
                            <input type="text"
                            style="text-transform:uppercase"
                            class="form-control"
                            required id="nome"
                            name="nome"
                            placeholder="NOME DO CLIENTE"
                            required>

                            ENDERECO
                            <input type="text"
                            style="text-transform:uppercase"
                            class="form-control"
                            required
                            id="end"
                            name="end"
                            placeholder="DIGITE ENDERECO">

                            NUMERO
                            <input type="text"
                            class="form-control"
                            required
                            id="num"
                            name="num"
                            placeholder="NUMERO">

                            COMPLEMENTO
                            <input type="text"
                            class="form-control"
                            id="comp"
                            name="comp"
                            placeholder="COMPLEMENTO">

                            BAIRRO
                            <input type="text"
                            style="text-transform:uppercase"
                            class="form-control"
                            required
                            id="bairro"
                            name="bairro"
                            placeholder="BAIRRO DO CLIENTE">

                            CIDADE
                            <input type="text"
                            style="text-transform:uppercase"
                            class="form-control"
                            required
                            id="cidade"
                            name="cidade"
                            placeholder="CIDADE DO CLIENTE">

                            CEP
                            <input type="text"
                            style="text-transform:uppercase"
                            class="form-control"
                            required
                            id="cep"
                            name="cep"
                            placeholder="CEP DO CLIENTE">

                            TELEFONE
                            <input type="text"
                            class="form-control"
                            required
                            id="telefone"
                            name="telefone"
                            placeholder="TELEFONE">

                            RG
                            <input type="text"
                            class="form-control"
                            required
                            id="rg"
                            name="rg"
                            placeholder="SOMENTE NUMEROS">

                            E-MAIL
                            <input type="text"
                            style="text-transform:uppercase"
                            class="form-control"
                            required
                            id="email" n
                            ame="email"
                            placeholder="EMAIL DO CLIENTE">

                            <button type="submit" class="btn btn-primary">CADASTRAR</button>
                            <button type="reset" class="btn btn-default">CANCELAR</button>

                </fieldset>

            </form>

PHP

<?php
//database configuration
    $dbHost     = '127.0.0.1';
    $dbUsername = 'root';
    $dbPassword = '';
    $dbName     = 'master';

#Verifica se tem um cpf para pesquisa
if(isset($_GET['cpf'])){

    #Recebe o cpf Postado
    $VarCPF = $_GET['cpf'];

    #Conecta banco de dados
    $Mysqli = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
    $sql = mysqli_query($Mysqli, "SELECT
    cli_cpf
        FROM
         big_clientes
         WHERE
             cli_cpf = '".$VarCPF."'") or print mysql_error();

    #Se o retorno for maior do que zero, diz que já existe um.
    if(mysqli_num_rows($sql)>0)

        echo json_encode(array('cpf' => TRUE,'msg' => 'CPF JÁ CADASTRADO!'));

    else
        echo json_encode(array('cpf' => FALSE ));

}


how to put observablecollection in List

Question: i want to put current observablecollection data in list on button click event. bellow is c# code but it gives error : Object reference not set to an instance of an object.
<code>    ObservableCollection<CheckInData> _CheckInCollection = new ObservableCollection<CheckInData>();

    public ObservableCollection<CheckInData> CheckInCollection
    {
        get { return _CheckInCollection; }
    }

    public class CheckInData
    {
        public string RoomNumber { get; set; }
        public decimal Price { get; set; }
        public string Currecny { get; set; }
        public decimal Discount { get; set; }
        public string CheckOut { get; set; }
        public int TotalDay { get; set; }
        public decimal TotalPrice { get; set; }
        public int CheckOutYear { get; set; }
        public int CheckOutMonth { get; set; }
        public int CheckOutDay { get; set; }
        public Boolean IncToday { get; set; }
    }

    private void btnPrintInvoice_Click(object sender, RoutedEventArgs e)
    {
        DataToExcel.Invoice inv = new DataToExcel.Invoice();
        inv._BilledTo = Guest[0];

        foreach (CheckInData coll in _CheckInCollection)
        {

            for (int i = 0; i < _CheckInCollection.Count; i++)
            {
                inv._RoomPrice.Add(coll.RoomNumber[i].ToString());
            }
        }
    }
</code>
Comment: What line does it give you that exception on?
Comment: inv._RoomPrice.Add(coll.RoomNumber[i].ToString());
Answer: Looks like inv._RoomPrice or coll.RoomNumber is null.
Answer: Set a breakpoint on the line that's throwing the exception and inspect each variable that can be null:  inv, inv._RoomPrice, coll, coll.RoomNumber
Once you find it, determine where you think it's supposed to be initialized and fix the bug that's causing it not be initialized.

how to put observablecollection in List


Assert that two lists of objects are equal in django testing

Question: Is there a way to check that two lists of objects are equal in django tests.
lets say I have some model:
class Tag(models.Model):
    slug = models.SlugField(max_length=50, unique=True)
    def __unicode__(self):
        return self.slug

and I run this simple test:
def test_equal_list_fail(self):
    tag_list = []
    for tag in ['a', 'b', 'c']:
        tag_list.append(Tag.objects.create(slug=tag))

    tags = Tag.objects.all()

    self.assertEqual(tag_list, tags)

this fails with:
======================================================================
FAIL: test_equal_list_fail (userAccount.tests.ProfileTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "path/to/tests.py", line 155, in test_equal_list_fail
    self.assertEqual(tag_list, tags)
AssertionError: [<Tag: a>, <Tag: b>, <Tag: c>] != [<Tag: a>, <Tag: b>, <Tag: c>]

----------------------------------------------------------------------

this will work:
def test_equal_list_passes(self):
    tag_list = []
    for tag in ['a', 'b', 'c']:
        tag_list.append(Tag.objects.create(slug=tag))

    tags = Tag.objects.all()

    for tag_set in zip(tags, tag_list):
        self.assertEqual(*tag_set)

However, This fails:
def test_equal_list_fail(self):
    tag_list = []
    for tag in ['a', 'b', 'c']:
        tag_list.append(Tag.objects.create(slug=tag))

    tags = Tag.objects.all()

    for tag_set in zip(tags, tag_list):
        print "\n"
        print tag_set[0].slug + "'s pk is %s" % tag_set[0].pk
        print tag_set[1].slug + "'s pk is %s" % tag_set[1].pk
        print "\n"
        self.assertIs(*tag_set)

with:
Creating test database for alias 'default'...
.......

a's pk is 1
a's pk is 1

F.
======================================================================
FAIL: test_equal_list_fail (userAccount.tests.ProfileTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "path/to/tests.py", line 160, in test_equal_list_fail
    self.assertIs(*tag_set)
AssertionError: <Tag: a> is not <Tag: a>

Is this expected behavior?
Edit in response to comment
This type of comparison works:
class Obj:
    def __init__(self, x):
        self.x = x

>>> one = Obj(1)
>>> two = Obj(2)
>>> a = [one, two]
>>> b = [one, two]
>>> a == b
True

Why is the test failing for the other arrays?
Comment: The reason the zip() works is because the text representation of your tag is the slug, and that's what you are comparing with.
Comment: Why wouldn't comparing the arrays do the same? I'll edit my question to show an example
Answer: To test two lists
use: assertSequenceEqual
Because, in this case, tags = Tag.objects.all() generates a django.db.models.query.QuerySet where as tag_list.append(...) creates a list.
Other options in different situations are:

assertListEqual(a, b)
assertTupleEqual(a, b)
assertSetEqual(a, b)
assertDictEqual(a, b)

Why <Tag: a> is not <Tag: a>
The tags are the same model, but they've been loaded into different places in memory
for tag_set in zip(tags, tag_list):
    print "\n"
    print tag_set[0].slug + "'s pk is %s" % tag_set[0].pk + ' id is: ' + id(tag_set[0])
    print tag_set[1].slug + "'s pk is %s" % tag_set[1].pk + ' id is: ' + id(tag_set[1])
    print "\n"
    self.assertIs(*tag_set)

returns
.......

a's pk is 1 id is: 4522000208
a's pk is 1 id is: 4522228112

F.

Therefore, is will retrun False
Answer: I think what you want to test is if the tags created have the same slugs as those in your test list.
For that, fetch only the slug as a list with values_list, and then compare that:
assertEqual(Tag.objects.values_list('slug', flat=True), ['a','b','c'])

I have to say, this isn't quite a useful test because you are checking django orm functionality, which has already been tested quite well.
Your tests should check for specifics of your own application.
Comment: hmm `values_list` is a good trick to know, +1 for that. I agree, in this case this is a useless test. I just wanted a simple example to show the test failing. My actual test isn't this trivial. I'd prefer not to use slugs because I want to check that the actual models are equal, but I suppose that it could be done with their `pk`s
Comment: Don't use `pk` because those are incremental (most likely) and two primary keys would not be equal (they shouldn't, if they are you have bigger problems). If the desired functionality is to _prevent_ duplicates, then use [`unique_together`](https://docs.djangoproject.com/en/1.6/ref/models/options/#unique-together) to help enforce this at the database level.
Comment: Can you expand on how to use `unique_together` in this case? It's not clear to me.


Rank of the 2-cover space of a knot space

Question: It is well known that the order of the first homology group of the double branched cover of a knot $K$ in $S^3$ is the determinant of $K$,   i.e.  $\lvert H_1(B_2(K),\mathbb{Z}) \rvert = \det (K)$.  However, I did not find a formula for its rank. Does anyone know the answer to this question?
Comment: Why was this question closed? It is a perfectly valid question. It seems that the relevant knot theory terms are not widely known to the community, but it's not the OP's job to teach them knot theory.
Comment: What is " determinant of K"? What is "B_2(k)"?
Comment: @AnubhavMukherjee In "An introduction to knot theory" by Lickorish, p. 99, the determinant of a link $L$ is $\lvert \Delta_L(-1)\rvert$, where $\Delta_L$ is the Alexander polynomial, or equivalently $\lvert\det G\rvert$, where $G$ is a Goeritz matrix associated to a double branched cover of $L$. Presumably $B_2(K)$ is a double branched cover based on the context, but that ought to be clarified.
Comment: No answer for @AnubhavMukherjee ? Here is some possibly relevant material but your question is quite obscure to me: https://web.northeastern.edu/beasley/MATH7375/Lecture23.pdf
Comment: @kyle although I'm familiar with knot theory, but still I didn't get the question after reading those notations. The op should elaborate those. Anyway thank you for the explanation :)
Answer: Edit: Thanks to Sucharit Sarkar for pointing out I was spreading misinformation.  This replaces my previous answer completely.
The first homology of the double branched cover of a knot in $S^3$ is a finite abelian group.  Since it has no free part, its rank is $0$.
Presumably you meant the minimal number of generators, which is much more interesting.  I'm aware of some things you can say in terms of Fitting/elementary ideals, where the Alexander polynomial is the GCD of the zeroth one.
By considering the relationships between double branched covers $B_2(K)$, two-fold covers of the knot complement $X_2(K)$ and the infinite cyclic cover of the knot complement $X_\infty(K)$, it is possible to work out with some long exact sequences that
$$H_1(B_2(K)) \cong \frac{H_1(X_\infty(K))}{(t^2-1)H_1(X_\infty(K))}$$
where $\mathbb{Z}[t^{\pm 1}]$ acts on $H_1(X_\infty(K))$ through deck transformations, with $t$ being the meridian generator of $H_1(S^3-K)$.
Now, a fact about $H_1(X_\infty(K))$ is that $1-t$ acts on it invertibly (explained by Milnor in "Infinite cyclic coverings").  Thus,
$$H_1(B_2(K)) \cong \frac{H_1(X_\infty(K))}{(t+1)H_1(X_\infty(K))}.$$
So, if you take a presentation matrix for $H_1(X_\infty(K))$ as a $\mathbb{Z}[t^{\pm 1}]$-module, you can substitute in $t=-1$ to get a presentation matrix for $H_1(B_2(K))$ as a $\mathbb{Z}$-module.  (A Goeritz matrix is an example of such a presentation matrix.)
This is why $\lvert H_1(B_2(K))\rvert = \lvert\Delta_K(-1)\rvert$. There is a square presentation matrix for $H_1(X_\infty(K))$ from the Seifert form, and the Alexander polynomial is the determinant of this.  Plugging in $-1$ gives the determinant of the corresponding square presentation matrix for $H_1(B_2(K))$.  Since $\mathbb{Z}$ is a PID, the determinant of the presentation matrix is the order of the module; this is due to Smith normal form having the same determinant, up to multiplication by $-1$.
The Alexander polynomial actually comes from a sequence of polynomials $\Delta^0_K(t),\Delta^1_K(t),\dots$, each dividing the previous, where $\Delta_K(t)=\Delta^0_K(t)$ is the zeroth (sometimes first, depending on the convention) Alexander polynomial, all defined up to multiplication by $\pm t^{k}$.  The polynomial $\Delta^i_K(t)$ is the GCD of the $i$th Fitting ideal of $H_1(X_\infty(K))$ (in knot theory literature, it is the $(i-1)$th elementary ideal), which is an ideal of $\mathbb{Z}[t^{\pm 1}]$.  See chapter 20 of Eisenbud's "Commutative algebra" for more details about Fitting ideals.  The $i$th Fitting ideal for $H_1(X_\infty(K))$ is generated by the $(m-i)\times(m-i)$ minors of the $m\times m$ presentation matrix for $H_1(X_\infty(K))$.  Hence, the $i$th Fitting ideal for $H_1(B_2(K))$ (an ideal of $\mathbb{Z}$) is given by the same-sized minors of the same presentation matrix with $t=-1$.
Let's call $\beta^i_K\in\mathbb{Z}$ the GCD (i.e., since $\mathbb{Z}$ is a PID, the generator) of the $i$th Fitting ideal of $H_1(B_2(K))$.  One fact about Fitting ideals is that if $H_1(B_2(K)) = \bigoplus_{i=1}^n \mathbb{Z}/m_i\mathbb{Z}$ with $m_{i-1}\mid m_i$ for all $1<i\leq n$, then $\beta^i_K=m_1m_2\dots m_{n-i}$.  Hence, $\beta^0_K=\lvert H_1(B_2(K))\rvert$, and the smallest $i$ such that $\beta^i_K=1$ gives exactly the minimum number of generators for $H_1(B_2(K))$.
To be clear, GCD for $\mathbb{Z}[t^{\pm 1}]$ means to take the smallest principal ideal containing the ideal generated by the given set of polynomials.  From this, one may deduce that $\Delta^i_K(-1)$ divides $\beta^i_K$ (and it may be that they are equal, but that seems unlikely).  Thus, the smallest $i$ such that $\Delta^i_K(-1)=1$ gives a lower bound for the number of generators for $H_1(B_2(K))$.
Ideals of $\mathbb{Z}[t^{\pm 1}]$ are of the form $(p(t),n)$ for $p(t)\in\mathbb{Z}[t]$ and $n\in\mathbb{Z}$, possibly with $p(t)=0$ or $n=0$.  If this is the $i$th Fitting ideal of $H_1(X_\infty(K))$, then the corresponding Fitting ideal for $H_1(B_2(K))$ would be $(p(-1),n)$.  Then $\beta^i_K$ is the GCD of $p(-1)$ and $n$.  While the gcd of $p(t)$ and $n$ might be $1$, it might be that the gcd of $p(-1)$ and $n$ is bigger than $1$.
The zeroth Fitting ideal of $H_1(X_\infty(K))$ is principal since the presentation matrix is square, so $\beta^0_K=\Delta^0_K(-1)$.  This is restating that $\lvert H_1(B_2(K)) \rvert=\lvert\beta^0_K\rvert = \lvert \Delta_K(-1)\rvert$.
The Alexander polynomials of the knot $8_{20}$ are
\begin{align}
\Delta^0_{8_{20}}(t) &= (1-3t+t^2)(1-t+t^2)^2 \\
\Delta^1_{8_{20}}(t) &= 1-t+t^2 \\
\Delta^2_{8_{20}}(t) &= 1
\end{align}
Since $\Delta^1_{8_{20}}(-1)=3$, we know that $H_1(B_2(8_{20}))$ needs at least two generators.
I happen to know that
$$ H_1(X_\infty(8_{20})) = \mathbb{Z}[t^{\pm 1}]/((1-3t+t^2)(1-t+t^2)) \oplus \mathbb{Z}[t^{\pm 1}]/(1-t+t^2) $$
Hence, $H_1(B_2(8_{20})) = \mathbb{Z}/15\mathbb{Z} \oplus \mathbb{Z}/3\mathbb{Z}$.  That's two generators.
While the Alexander polynomials detected the number of generators in this case, consider $9_{46}$.  It has
$$ H_1(X_\infty(9_{46})) = \mathbb{Z}[t^{\pm 1}]/(2-t)\oplus \mathbb{Z}[t^{\pm 1}]/(1-2t) $$
Hence,
\begin{align}
\Delta^0_{9_{46}}(t) &= (2-t)(1-2t) \\
\Delta^1_{9_{46}}(t) &= 1 \\
\end{align}
Since $\Delta^0_{9_{46}}(-1)=9$ and $\Delta^1_{9_{46}}(-1)=1$, we know $H_1(B_2(9_{46}))$ has at least one generator.  However, $\beta^0_{9_{46}}=9$, $\beta^1_{9_{46}}=3$, and $\beta^2_{9_{46}}=1$, so it needs exactly two generators.
One more knot: $6_1$.  It has the exact same Alexander polynomials as $9_{46}$.  However, $\beta^1_{6_1}=1$.  Therefore, $6_1$ and $9_{46}$ can be distinguished by this piece of homological information about their double branched covers.
Comment: I am confused. I think the branched double cover of a connected sum of two knots is the connected sum of the two individual branched double covers, and so the first homology is the direct sum. For instance, the first homology for the branched double cover of trefoil is $Z/3$, so the first homology of the branched double cover of connected sum of two trefoils should be $Z/3 \oplus Z/3$.
Comment: Thank you Mr. Kyle Miller! I was not aware of the fact that H_1(B_2(K),\mathbb{Z})\cong \mathbb{Z}/(\Delta_K(-1)). However, I am confused here - if the rank is 1 - then the B_2(K)  can not be a homology sphere unless det(K)=1. It is known (Milnor proved it) thet B_2(T(p,q)) is the Brieskorn homology sphere $\Sigma (p,q,2)$.  This contradicts this formula.  Reference  https://www.maths.ed.ac.uk/~v1ranick/papers/milnbries.pdf
Comment: This puzzle you present took a while to pin down, but if I'm not mistaken, the paper says it is a homology sphere in the case that both $p$ and $q$ are odd. The determinant of $T(2r+1,2s+1)$ is $1$ by my calculations via the Alexander polynomial.  (Chapter 9 of Lickorish's book "An Introduction to Knot Theory" discusses the homology of cyclic branched covers, if you want a reference.)
Comment: @SucharitSarkar You're entirely right, and my answer is complete nonsense.  The double branched cover's $H_1$ is presented by a presentation matrix for the Alexander module ($H_1$ of the infinite cyclic cover as a module over $\mathbb{Z}[t^{\pm 1}]$) evaluated at $t=-1$.  The connect sum of knots has a block diagonal presentation matrix for its Alexander module, hence the $H_1$ is a direct sum.  (Also, the *rank* of a finite abelian group is $0$.  More interesting would be the minimal number of generators, but I'm not sure what's known about that.)
Comment: @SucharitSarkar I completely reworked the answer and added an example of a prime knot that contradicts my original claim.  Thanks
Comment: Alexander and Briggs pointed out long ago that 6_1 and 9_46 are distinguished by the homology of their double branched covers -- Z9 vs. Z3xZ3.  These groups are easily calculated from the standard Wirtinger cellular decomposition of such covers. --Ken Perko, email@example.com.
Comment: @user43408 Hi Ken, I'm not sure what point you're making exactly -- it's certainly easy to calculate the homologies of the double branched covers (and indeed, that's more or less how I calculated the Alexander polynomials), but the point of the $6_1$ example was to show a case where a higher Alexander polynomial can show the ranks of the homologies are different.
Comment: OK, Kyle. It just seems to me that resorting to higher polynomials to distinguish these easy homologies is doing it the hard way. My high school math teacher taught us that "the good mathematician is the lazy mathematician."  --Ken Perko


Zipping files with perl, last line is cut off

Question: I tried to zip some CSV files which are about 5 MB with Perl. Below is my zip code.
The files are zipped but when I open them with the Windows unzip utility I found that the last lines of the CSV files are missing. What could be the problem here? I tried to change the chuncksize and the desiredCompressionLevel but this didn't help.
sub zip_util{
   my $directory = shift;
   $zip = Archive::Zip->new();
   $zip->setChunkSize(65536);
   # Add a file from disk

   my $file1=File::Spec->catfile($directory, 'file.csv');
   my $file2=File::Spec->catfile($directory, 'file2.csv');
   my $file3=File::Spec->catfile($directory, 'fil3.csv');
   $zip->addFile($file1,'file1.csv')->desiredCompressionLevel( 6 );
   $zip->addFile($file2,'file2.csv')->desiredCompressionLevel( 6 );
   $zip->addFile($fil3,'file3.csv')->desiredCompressionLevel( 6 );

   # Save the Zip file
   my $zipped_file=File::Spec->catfile($directory,'files.zip');
   unless ( $zip->writeToFileNamed($zipped_file) == AZ_OK ) {
      print  LOG ": Zip Creation error\n";
   }

Comment: It might be a problem with [`Archive::Zip`](https://metacpan.org/module/Archive::Zip). However, to make sure, can you please upload the original CSV files as well as the archive that was generated?
Answer: I've checked it with warnings and strictures and I've found certain problems.

$zip doesn't use my (I don't know if it's intentional, but use strict really helps with globals like this).
You're running $zip->addFile($fil3,'file3.csv'). $fil3 variable definitely doesn't exist. If anything, this variable is $file3.
I guess it's issue during Copy and Paste, but subroutine doesn't have matching brace.

I've done quick script which I've used during testing.
use strict;
use warnings;
use Archive::Zip qw( :ERROR_CODES );
use File::Spec;

sub zip_util {
    my ($directory) = @_;
    my $zip = Archive::Zip->new();
    $zip->setChunkSize(65536);

    # Add a file from disk
    my $file1 = File::Spec->catfile( $directory, 'file.csv' );
    my $file2 = File::Spec->catfile( $directory, 'file2.csv' );
    my $file3 = File::Spec->catfile( $directory, 'file3.csv' );
    $zip->addFile( $file1, 'file1.csv' )->desiredCompressionLevel(6);
    $zip->addFile( $file2, 'file2.csv' )->desiredCompressionLevel(6);
    $zip->addFile( $file3, 'file3.csv' )->desiredCompressionLevel(6);

    # Save the Zip file
    my $zipped_file = File::Spec->catfile( $directory, 'files.zip' );
    if ( $zip->writeToFileNamed($zipped_file) != AZ_OK ) {
        print STDERR "Zip Creation error\n";
    }
}

zip_util '.';

The problem is that it was working. So, I've done this script to make some sort of 5MB files:
use strict;
use warnings;
use 5.010;

for ( 1 .. 524_288 ) {
    my $number = $_ % 10;
    say "$number-------";
}

Both files in ZIP and original "CSV" had this same size and content. So, it's probably the second issue which I've mentioned - use of $fil3 variable or something with your files (which you sadly didn't uploaded, so I cannot look into those).


How to capture HTTP throughput in BlackBerry?

Question: Please help me to findout the HTTP throughput and HTTP latency in the BB programming.
Answer: You can use System.currentTimeMillis() to get timestamps at various points in your code, then use those values to calculate timings.  For example:
long start = System.currentTimeMillis();
HttpConnection connection = (HttpConnection) Connector.open(url);
long opened = System.currentTimeMillis();
String body = new String(IOUtilities.streamToBytes(connection.openInputStream()));
long done = System.currentTimeMillis();

long bytes = body.length();
float durationSeconds = (float)(done - opened) / 1000.0f;
float bytesPerSecond = bytes / durationSeconds;

System.out.println("Latency: " + (opened - start) + " ms");
System.out.println("Bandwidth: " + bytesPerSecond + " bytes per second");